]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Fix too general application of \cprotect
[lyx.git] / src / Paragraph.cpp
1 /**
2  * \file Paragraph.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Richard Heck (XHTML output)
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Paragraph.h"
22
23 #include "LayoutFile.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "Changes.h"
27 #include "Counters.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Font.h"
34 #include "FontList.h"
35 #include "LyXRC.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "output_docbook.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "xml.h"
43 #include "texstream.h"
44 #include "TextClass.h"
45 #include "TexRow.h"
46 #include "Text.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
56
57 #include "mathed/InsetMathHull.h"
58
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/Length.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "output_docbook.h"
68
69 #include <atomic>
70 #include <sstream>
71 #include <vector>
72
73 using namespace std;
74 using namespace lyx::support;
75
76 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
77 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
78 #define THREAD_LOCAL_STATIC static __thread
79 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
80 #define THREAD_LOCAL_STATIC static __declspec(thread)
81 #else
82 #define THREAD_LOCAL_STATIC thread_local static
83 #endif
84
85 namespace lyx {
86
87 /////////////////////////////////////////////////////////////////////
88 //
89 // SpellResultRange
90 //
91 /////////////////////////////////////////////////////////////////////
92
93 class SpellResultRange {
94 public:
95         SpellResultRange(FontSpan range, SpellChecker::Result result)
96         : range_(range), result_(result)
97         {}
98         ///
99         FontSpan const & range() const { return range_; }
100         ///
101         void range(FontSpan const & r) { range_ = r; }
102         ///
103         SpellChecker::Result result() const { return result_; }
104         ///
105         void result(SpellChecker::Result r) { result_ = r; }
106         ///
107         bool contains(pos_type pos) const { return range_.contains(pos); }
108         ///
109         bool covered(FontSpan const & r) const
110         {
111                 // 1. first of new range inside current range or
112                 // 2. last of new range inside current range or
113                 // 3. first of current range inside new range or
114                 // 4. last of current range inside new range
115                 //FIXME: is this the same as !range_.intersect(r).empty() ?
116                 return range_.contains(r.first) || range_.contains(r.last) ||
117                         r.contains(range_.first) || r.contains(range_.last);
118         }
119         ///
120         void shift(pos_type pos, int offset)
121         {
122                 if (range_.first > pos) {
123                         range_.first += offset;
124                         range_.last += offset;
125                 } else if (range_.last >= pos) {
126                         range_.last += offset;
127                 }
128         }
129 private:
130         FontSpan range_ ;
131         SpellChecker::Result result_ ;
132 };
133
134
135 /////////////////////////////////////////////////////////////////////
136 //
137 // SpellCheckerState
138 //
139 /////////////////////////////////////////////////////////////////////
140
141 class SpellCheckerState {
142 public:
143         SpellCheckerState()
144         {
145                 needs_refresh_ = true;
146                 current_change_number_ = 0;
147         }
148
149         void setRange(FontSpan const & fp, SpellChecker::Result state)
150         {
151                 Ranges result;
152                 RangesIterator et = ranges_.end();
153                 RangesIterator it = ranges_.begin();
154                 for (; it != et; ++it) {
155                         if (!it->covered(fp))
156                                 result.push_back(SpellResultRange(it->range(), it->result()));
157                         else if (state == SpellChecker::WORD_OK) {
158                                 // trim or split the current misspelled range
159                                 // store misspelled ranges only
160                                 FontSpan range = it->range();
161                                 if (fp.first > range.first) {
162                                         // misspelled area in front of WORD_OK
163                                         range.last = fp.first - 1;
164                                         result.push_back(SpellResultRange(range, it->result()));
165                                         range = it->range();
166                                 }
167                                 if (fp.last < range.last) {
168                                         // misspelled area after WORD_OK range
169                                         range.first = fp.last + 1;
170                                         result.push_back(SpellResultRange(range, it->result()));
171                                 }
172                         }
173                 }
174                 ranges_ = result;
175                 if (state != SpellChecker::WORD_OK)
176                         ranges_.push_back(SpellResultRange(fp, state));
177         }
178
179         void increasePosAfterPos(pos_type pos)
180         {
181                 correctRangesAfterPos(pos, 1);
182                 needsRefresh(pos);
183         }
184
185         void decreasePosAfterPos(pos_type pos)
186         {
187                 correctRangesAfterPos(pos, -1);
188                 needsRefresh(pos);
189         }
190
191         void refreshLast(pos_type pos)
192         {
193                 if (pos < refresh_.last)
194                         refresh_.last = pos;
195         }
196
197         SpellChecker::Result getState(pos_type pos) const
198         {
199                 SpellChecker::Result result = SpellChecker::WORD_OK;
200                 RangesIterator et = ranges_.end();
201                 RangesIterator it = ranges_.begin();
202                 for (; it != et; ++it) {
203                         if(it->contains(pos)) {
204                                 return it->result();
205                         }
206                 }
207                 return result;
208         }
209
210         FontSpan const & getRange(pos_type pos) const
211         {
212                 /// empty span to indicate mismatch
213                 static FontSpan empty_;
214                 RangesIterator et = ranges_.end();
215                 RangesIterator it = ranges_.begin();
216                 for (; it != et; ++it) {
217                         if(it->contains(pos)) {
218                                 return it->range();
219                         }
220                 }
221                 return empty_;
222         }
223
224         bool needsRefresh() const
225         {
226                 return needs_refresh_;
227         }
228
229         SpellChecker::ChangeNumber currentChangeNumber() const
230         {
231                 return current_change_number_;
232         }
233
234         void refreshRange(pos_type & first, pos_type & last) const
235         {
236                 first = refresh_.first;
237                 last = refresh_.last;
238         }
239
240         void needsRefresh(pos_type pos)
241         {
242                 if (needs_refresh_ && pos != -1) {
243                         if (pos < refresh_.first)
244                                 refresh_.first = pos;
245                         if (pos > refresh_.last)
246                                 refresh_.last = pos;
247                 } else if (pos != -1) {
248                         // init request check for neighbour positions too
249                         refresh_.first = pos > 0 ? pos - 1 : 0;
250                         // no need for special end of paragraph check
251                         refresh_.last = pos + 1;
252                 }
253                 needs_refresh_ = pos != -1;
254         }
255
256         void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
257         {
258                 needs_refresh_ = true;
259                 refresh_.first = 0;
260                 refresh_.last = -1;
261                 current_change_number_ = change_number;
262         }
263 private:
264         typedef vector<SpellResultRange> Ranges;
265         typedef Ranges::const_iterator RangesIterator;
266         Ranges ranges_;
267         /// the area of the paragraph with pending spell check
268         FontSpan refresh_;
269         /// spell state cache version number
270         SpellChecker::ChangeNumber current_change_number_;
271         bool needs_refresh_;
272
273
274         void correctRangesAfterPos(pos_type pos, int offset)
275         {
276                 RangesIterator et = ranges_.end();
277                 Ranges::iterator it = ranges_.begin();
278                 for (; it != et; ++it) {
279                         it->shift(pos, offset);
280                 }
281         }
282
283 };
284
285 /////////////////////////////////////////////////////////////////////
286 //
287 // Paragraph::Private
288 //
289 /////////////////////////////////////////////////////////////////////
290
291 class Paragraph::Private
292 {
293         // Enforce our own "copy" constructor
294         Private(Private const &) = delete;
295         Private & operator=(Private const &) = delete;
296         // Unique ID generator
297         static int make_id();
298 public:
299         ///
300         Private(Paragraph * owner, Layout const & layout);
301         /// "Copy constructor"
302         Private(Private const &, Paragraph * owner);
303         /// Copy constructor from \p beg  to \p end
304         Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
305
306         ///
307         void insertChar(pos_type pos, char_type c, Change const & change);
308
309         /// Output the surrogate pair formed by \p c and \p next to \p os.
310         /// \return the number of characters written.
311         int latexSurrogatePair(BufferParams const &, otexstream & os,
312                                char_type c, char_type next,
313                                OutputParams const &);
314
315         /// Output a space in appropriate formatting (or a surrogate pair
316         /// if the next character is a combining character).
317         /// \return whether a surrogate pair was output.
318         bool simpleTeXBlanks(BufferParams const &,
319                              OutputParams const &,
320                              otexstream &,
321                              pos_type i,
322                              unsigned int & column,
323                              Font const & font,
324                              Layout const & style);
325
326         /// This could go to ParagraphParameters if we want to.
327         int startTeXParParams(BufferParams const &, otexstream &,
328                               OutputParams const &) const;
329
330         /// This could go to ParagraphParameters if we want to.
331         bool endTeXParParams(BufferParams const &, otexstream &,
332                              OutputParams const &) const;
333
334         ///
335         void latexInset(BufferParams const &,
336                                    otexstream &,
337                                    OutputParams &,
338                                    Font & running_font,
339                                    Font & basefont,
340                                    Font const & outerfont,
341                                    bool & open_font,
342                                    Change & running_change,
343                                    Layout const & style,
344                                    pos_type & i,
345                                    unsigned int & column);
346
347         ///
348         void latexSpecialChar(
349                                    otexstream & os,
350                                    BufferParams const & bparams,
351                                    OutputParams const & runparams,
352                                    Font const & running_font,
353                                    string & alien_script,
354                                    Layout const & style,
355                                    pos_type & i,
356                                    pos_type end_pos,
357                                    unsigned int & column);
358
359         ///
360         bool latexSpecialT1(
361                 char_type const c,
362                 otexstream & os,
363                 pos_type i,
364                 unsigned int & column);
365         ///
366         bool latexSpecialTU(
367                 char_type const c,
368                 otexstream & os,
369                 pos_type i,
370                 unsigned int & column);
371         ///
372         bool latexSpecialT3(
373                 char_type const c,
374                 otexstream & os,
375                 pos_type i,
376                 unsigned int & column);
377
378         ///
379         void validate(LaTeXFeatures & features) const;
380
381         /// Checks if the paragraph contains only text and no inset or font change.
382         bool onlyText(Buffer const & buf, Font const & outerfont,
383                       pos_type initial) const;
384
385         /// a vector of speller skip positions
386         typedef vector<FontSpan> SkipPositions;
387         typedef SkipPositions::const_iterator SkipPositionsIterator;
388
389         void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
390
391         Language * getSpellLanguage(pos_type const from) const;
392
393         Language * locateSpellRange(pos_type & from, pos_type & to,
394                                     SkipPositions & skips) const;
395
396         bool hasSpellerChange() const
397         {
398                 SpellChecker::ChangeNumber speller_change_number = 0;
399                 if (theSpellChecker())
400                         speller_change_number = theSpellChecker()->changeNumber();
401                 return speller_change_number > speller_state_.currentChangeNumber();
402         }
403
404         bool ignoreWord(docstring const & word) const ;
405
406         void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
407         {
408                 pos_type textsize = owner_->size();
409                 // check for sane arguments
410                 if (to <= from || from >= textsize)
411                         return;
412                 FontSpan fp = FontSpan(from, to - 1);
413                 speller_state_.setRange(fp, state);
414         }
415
416         void requestSpellCheck(pos_type pos)
417         {
418                 if (pos == -1)
419                         speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
420                 else
421                         speller_state_.needsRefresh(pos);
422         }
423
424         void readySpellCheck()
425         {
426                 speller_state_.needsRefresh(-1);
427         }
428
429         bool needsSpellCheck() const
430         {
431                 return speller_state_.needsRefresh();
432         }
433
434         void rangeOfSpellCheck(pos_type & first, pos_type & last) const
435         {
436                 speller_state_.refreshRange(first, last);
437                 if (last == -1) {
438                         last = owner_->size();
439                         return;
440                 }
441                 pos_type endpos = last;
442                 owner_->locateWord(first, endpos, WHOLE_WORD, true);
443                 if (endpos < last) {
444                         endpos = last;
445                         owner_->locateWord(last, endpos, WHOLE_WORD, true);
446                 }
447                 last = endpos;
448         }
449
450         int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
451                             int & start) const
452         {
453                 int numskips = 0;
454                 while (it != et && it->first < start) {
455                         long skip = it->last - it->first + 1;
456                         start += skip;
457                         numskips += skip;
458                         ++it;
459                 }
460                 return numskips;
461         }
462
463         void markMisspelledWords(pos_type const & first, pos_type const & last,
464                                                          SpellChecker::Result result,
465                                                          docstring const & word,
466                                                          SkipPositions const & skips);
467
468         InsetCode ownerCode() const
469         {
470                 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
471         }
472
473         /// Which Paragraph owns us?
474         Paragraph * owner_;
475
476         /// In which Inset?
477         Inset const * inset_owner_;
478
479         ///
480         FontList fontlist_;
481
482         ///
483         ParagraphParameters params_;
484
485         /// for recording and looking up changes
486         Changes changes_;
487
488         ///
489         InsetList insetlist_;
490
491         /// end of label
492         pos_type begin_of_body_;
493
494         typedef docstring TextContainer;
495         ///
496         TextContainer text_;
497
498         typedef set<docstring> Words;
499         typedef map<string, Words> LangWordsMap;
500         ///
501         LangWordsMap words_;
502         ///
503         Layout const * layout_;
504         ///
505         SpellCheckerState speller_state_;
506         ///
507         int id_;
508 };
509
510
511 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
512         : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
513 {
514         text_.reserve(100);
515 }
516
517
518 //static
519 int Paragraph::Private::make_id()
520 {
521         // The id is unique per session across buffers because it is used in
522         // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
523         // outliner.
524         // (thread-safe)
525         static int next_id(0);
526         return next_id++;
527 }
528
529
530 Paragraph::Private::Private(Private const & p, Paragraph * owner)
531         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
532           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
533           begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
534           layout_(p.layout_), id_(make_id())
535 {
536         requestSpellCheck(p.text_.size());
537 }
538
539
540 Paragraph::Private::Private(Private const & p, Paragraph * owner,
541         pos_type beg, pos_type end)
542         : owner_(owner), inset_owner_(p.inset_owner_),
543           params_(p.params_), changes_(p.changes_),
544           insetlist_(p.insetlist_, beg, end),
545           begin_of_body_(p.begin_of_body_), words_(p.words_),
546           layout_(p.layout_), id_(make_id())
547 {
548         if (beg >= pos_type(p.text_.size()))
549                 return;
550         text_ = p.text_.substr(beg, end - beg);
551
552         FontList::const_iterator fcit = fontlist_.begin();
553         FontList::const_iterator fend = fontlist_.end();
554         for (; fcit != fend; ++fcit) {
555                 if (fcit->pos() < beg)
556                         continue;
557                 if (fcit->pos() >= end) {
558                         // Add last entry in the fontlist_.
559                         fontlist_.set(text_.size() - 1, fcit->font());
560                         break;
561                 }
562                 // Add a new entry in the fontlist_.
563                 fontlist_.set(fcit->pos() - beg, fcit->font());
564         }
565         requestSpellCheck(p.text_.size());
566 }
567
568
569 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
570                                 bool output_active, TocBackend & backend) const
571 {
572         d->changes_.addToToc(cdit, buf, output_active, backend);
573 }
574
575
576 bool Paragraph::isDeleted(pos_type start, pos_type end) const
577 {
578         LASSERT(start >= 0 && start <= size(), return false);
579         LASSERT(end > start && end <= size() + 1, return false);
580
581         return d->changes_.isDeleted(start, end);
582 }
583
584
585 bool Paragraph::isChanged(pos_type start, pos_type end) const
586 {
587         LASSERT(start >= 0 && start <= size(), return false);
588         LASSERT(end > start && end <= size() + 1, return false);
589
590         return d->changes_.isChanged(start, end);
591 }
592
593 // FIXME: Ideally the diverse isChanged() methods should account for that!
594 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
595 {
596         LASSERT(start >= 0 && start <= size(), return false);
597         LASSERT(end > start && end <= size() + 1, return false);
598
599         for (auto const & icit : d->insetlist_) {
600                 if (icit.pos < start)
601                         continue;
602                 if (icit.pos >= end)
603                         break;
604                 if (icit.inset && icit.inset->isChanged())
605                         return true;
606         }
607         return false;
608 }
609
610 bool Paragraph::isChanged() const
611 {
612         return d->changes_.isChanged();
613 }
614
615
616 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
617 {
618         // keep the logic here in sync with the logic of eraseChars()
619         if (!trackChanges)
620                 return true;
621
622         Change const & change = d->changes_.lookup(size());
623         return change.inserted() && change.currentAuthor();
624 }
625
626 Change Paragraph::parEndChange() const
627 {
628         return d->changes_.lookup(size());
629 }
630
631
632 void Paragraph::setChange(Change const & change)
633 {
634         // beware of the imaginary end-of-par character!
635         d->changes_.set(change, 0, size() + 1);
636
637         /*
638          * Propagate the change recursively - but not in case of DELETED!
639          *
640          * Imagine that your co-author makes changes in an existing inset. He
641          * sends your document to you and you come to the conclusion that the
642          * inset should go completely. If you erase it, LyX must not delete all
643          * text within the inset. Otherwise, the change tracked insertions of
644          * your co-author get lost and there is no way to restore them later.
645          *
646          * Conclusion: An inset's content should remain untouched if you delete it
647          */
648
649         if (!change.deleted()) {
650                 for (pos_type pos = 0; pos < size(); ++pos) {
651                         if (Inset * inset = getInset(pos))
652                                 inset->setChange(change);
653                 }
654         }
655 }
656
657
658 void Paragraph::setChange(pos_type pos, Change const & change)
659 {
660         LASSERT(pos >= 0 && pos <= size(), return);
661         d->changes_.set(change, pos);
662
663         // see comment in setChange(Change const &) above
664         if (!change.deleted() && pos < size())
665                 if (Inset * inset = getInset(pos))
666                         inset->setChange(change);
667 }
668
669
670 Change const & Paragraph::lookupChange(pos_type pos) const
671 {
672         LBUFERR(pos >= 0 && pos <= size());
673         return d->changes_.lookup(pos);
674 }
675
676
677 void Paragraph::acceptChanges(pos_type start, pos_type end)
678 {
679         LASSERT(start >= 0 && start <= size(), return);
680         LASSERT(end > start && end <= size() + 1, return);
681
682         for (pos_type pos = start; pos < end; ++pos) {
683                 switch (lookupChange(pos).type) {
684                         case Change::UNCHANGED:
685                                 // accept changes in nested inset
686                                 if (Inset * inset = getInset(pos))
687                                         inset->acceptChanges();
688                                 break;
689
690                         case Change::INSERTED:
691                                 d->changes_.set(Change(Change::UNCHANGED), pos);
692                                 // also accept changes in nested inset
693                                 if (Inset * inset = getInset(pos))
694                                         inset->acceptChanges();
695                                 break;
696
697                         case Change::DELETED:
698                                 // Suppress access to non-existent
699                                 // "end-of-paragraph char"
700                                 if (pos < size()) {
701                                         eraseChar(pos, false);
702                                         --end;
703                                         --pos;
704                                 }
705                                 break;
706                 }
707
708         }
709 }
710
711
712 void Paragraph::rejectChanges(pos_type start, pos_type end)
713 {
714         LASSERT(start >= 0 && start <= size(), return);
715         LASSERT(end > start && end <= size() + 1, return);
716
717         for (pos_type pos = start; pos < end; ++pos) {
718                 switch (lookupChange(pos).type) {
719                         case Change::UNCHANGED:
720                                 // reject changes in nested inset
721                                 if (Inset * inset = getInset(pos))
722                                                 inset->rejectChanges();
723                                 break;
724
725                         case Change::INSERTED:
726                                 // Suppress access to non-existent
727                                 // "end-of-paragraph char"
728                                 if (pos < size()) {
729                                         eraseChar(pos, false);
730                                         --end;
731                                         --pos;
732                                 }
733                                 break;
734
735                         case Change::DELETED:
736                                 d->changes_.set(Change(Change::UNCHANGED), pos);
737
738                                 // Do NOT reject changes within a deleted inset!
739                                 // There may be insertions of a co-author inside of it!
740
741                                 break;
742                 }
743         }
744 }
745
746
747 void Paragraph::Private::insertChar(pos_type pos, char_type c,
748                 Change const & change)
749 {
750         LASSERT(pos >= 0 && pos <= int(text_.size()), return);
751
752         // track change
753         changes_.insert(change, pos);
754
755         // This is actually very common when parsing buffers (and
756         // maybe inserting ascii text)
757         if (pos == pos_type(text_.size())) {
758                 // when appending characters, no need to update tables
759                 text_.push_back(c);
760                 // but we want spell checking
761                 requestSpellCheck(pos);
762                 return;
763         }
764
765         text_.insert(text_.begin() + pos, c);
766
767         // Update the font table.
768         fontlist_.increasePosAfterPos(pos);
769
770         // Update the insets
771         insetlist_.increasePosAfterPos(pos);
772
773         // Update list of misspelled positions
774         speller_state_.increasePosAfterPos(pos);
775 }
776
777
778 bool Paragraph::insertInset(pos_type pos, Inset * inset,
779                                    Font const & font, Change const & change)
780 {
781         LASSERT(inset, return false);
782         LASSERT(pos >= 0 && pos <= size(), return false);
783
784         // Paragraph::insertInset() can be used in cut/copy/paste operation where
785         // d->inset_owner_ is not set yet.
786         if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
787                 return false;
788
789         d->insertChar(pos, META_INSET, change);
790         LASSERT(d->text_[pos] == META_INSET, return false);
791
792         // Add a new entry in the insetlist_.
793         d->insetlist_.insert(inset, pos);
794
795         // Some insets require run of spell checker
796         requestSpellCheck(pos);
797         setFont(pos, font);
798         return true;
799 }
800
801
802 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
803 {
804         LASSERT(pos >= 0 && pos <= size(), return false);
805
806         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
807
808         if (trackChanges) {
809                 Change change = d->changes_.lookup(pos);
810
811                 // set the character to DELETED if
812                 //  a) it was previously unchanged or
813                 //  b) it was inserted by a co-author
814
815                 if (!change.changed() ||
816                       (change.inserted() && !change.currentAuthor())) {
817                         setChange(pos, Change(Change::DELETED));
818                         // request run of spell checker
819                         requestSpellCheck(pos);
820                         return false;
821                 }
822
823                 if (change.deleted())
824                         return false;
825         }
826
827         // Don't physically access the imaginary end-of-paragraph character.
828         // eraseChar() can only mark it as DELETED. A physical deletion of
829         // end-of-par must be handled externally.
830         if (pos == size()) {
831                 return false;
832         }
833
834         // track change
835         d->changes_.erase(pos);
836
837         // if it is an inset, delete the inset entry
838         if (d->text_[pos] == META_INSET)
839                 d->insetlist_.erase(pos);
840
841         d->text_.erase(d->text_.begin() + pos);
842
843         // Update the fontlist_
844         d->fontlist_.erase(pos);
845
846         // Update the insetlist_
847         d->insetlist_.decreasePosAfterPos(pos);
848
849         // Update list of misspelled positions
850         d->speller_state_.decreasePosAfterPos(pos);
851         d->speller_state_.refreshLast(size());
852
853         return true;
854 }
855
856
857 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
858 {
859         LASSERT(start >= 0 && start <= size(), return 0);
860         LASSERT(end >= start && end <= size() + 1, return 0);
861
862         pos_type i = start;
863         for (pos_type count = end - start; count; --count) {
864                 if (!eraseChar(i, trackChanges))
865                         ++i;
866         }
867         return end - i;
868 }
869
870 // Handle combining characters
871 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
872                 otexstream & os, char_type c, char_type next,
873                 OutputParams const & runparams)
874 {
875         // Writing next here may circumvent a possible font change between
876         // c and next. Since next is only output if it forms a surrogate pair
877         // with c we can ignore this:
878         // A font change inside a surrogate pair does not make sense and is
879         // hopefully impossible to input.
880         // FIXME: change tracking
881         // Is this correct WRT change tracking?
882         Encoding const & encoding = *(runparams.encoding);
883         docstring latex1 = encoding.latexChar(next).first;
884         if (runparams.inIPA) {
885                 string const tipashortcut = Encodings::TIPAShortcut(next);
886                 if (!tipashortcut.empty()) {
887                         latex1 = from_ascii(tipashortcut);
888                 }
889         }
890         docstring latex2 = encoding.latexChar(c).first;
891
892         if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
893                 // Encoding supports the combination:
894                 // output as is (combining char after base char).
895                 os << latex2 << latex1;
896                 return latex1.length() + latex2.length();
897         }
898
899         os << latex1 << "{" << latex2 << "}";
900         return latex1.length() + latex2.length() + 2;
901 }
902
903
904 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
905                                        OutputParams const & runparams,
906                                        otexstream & os,
907                                        pos_type i,
908                                        unsigned int & column,
909                                        Font const & font,
910                                        Layout const & style)
911 {
912         if (style.pass_thru || runparams.pass_thru)
913                 return false;
914
915         if (i + 1 < int(text_.size())) {
916                 char_type next = text_[i + 1];
917                 if (Encodings::isCombiningChar(next)) {
918                         // This space has an accent, so we must always output it.
919                         column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
920                         return true;
921                 }
922         }
923
924         if (runparams.linelen > 0
925             && column > runparams.linelen
926             && i
927             && text_[i - 1] != ' '
928             && (i + 1 < int(text_.size()))
929             // same in FreeSpacing mode
930             && !owner_->isFreeSpacing()
931             // In typewriter mode, we want to avoid
932             // ! . ? : at the end of a line
933             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
934                  && (text_[i - 1] == '.'
935                      || text_[i - 1] == '?'
936                      || text_[i - 1] == ':'
937                      || text_[i - 1] == '!'))) {
938                 os << '\n';
939                 os.texrow().start(owner_->id(), i + 1);
940                 column = 0;
941         } else if (style.free_spacing) {
942                 os << '~';
943         } else {
944                 os << ' ';
945         }
946         return false;
947 }
948
949
950 void Paragraph::Private::latexInset(BufferParams const & bparams,
951                                     otexstream & os,
952                                     OutputParams & runparams,
953                                     Font & running_font,
954                                     Font & basefont,
955                                     Font const & outerfont,
956                                     bool & open_font,
957                                     Change & running_change,
958                                     Layout const & style,
959                                     pos_type & i,
960                                     unsigned int & column)
961 {
962         Inset * inset = owner_->getInset(i);
963         LBUFERR(inset);
964
965         if (style.pass_thru) {
966                 odocstringstream ods;
967                 inset->plaintext(ods, runparams);
968                 os << ods.str();
969                 return;
970         }
971
972         // FIXME: move this to InsetNewline::latex
973         if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
974                 // newlines are handled differently here than
975                 // the default in simpleTeXSpecialChars().
976                 if (!style.newline_allowed) {
977                         os << '\n';
978                 } else {
979                         if (open_font) {
980                                 bool needPar = false;
981                                 column += running_font.latexWriteEndChanges(
982                                         os, bparams, runparams,
983                                         basefont, basefont, needPar);
984                                 open_font = false;
985                         }
986
987                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
988                                 os << '~';
989
990                         basefont = owner_->getLayoutFont(bparams, outerfont);
991                         running_font = basefont;
992
993                         if (runparams.moving_arg)
994                                 os << "\\protect ";
995
996                 }
997                 os.texrow().start(owner_->id(), i + 1);
998                 column = 0;
999         }
1000
1001         if (owner_->isDeleted(i)) {
1002                 if( ++runparams.inDeletedInset == 1)
1003                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
1004         }
1005
1006         if (inset->canTrackChanges()) {
1007                 column += Changes::latexMarkChange(os, bparams, running_change,
1008                         Change(Change::UNCHANGED), runparams);
1009                 running_change = Change(Change::UNCHANGED);
1010         }
1011
1012         bool close = false;
1013         odocstream::pos_type const len = os.os().tellp();
1014
1015         if (inset->forceLTR(runparams)
1016             && running_font.isRightToLeft()
1017             // ERT is an exception, it should be output with no
1018             // decorations at all
1019             && inset->lyxCode() != ERT_CODE) {
1020                 if (runparams.use_polyglossia) {
1021                         os << "\\LRE{";
1022                 } else if (running_font.language()->lang() == "farsi"
1023                            || running_font.language()->lang() == "arabic_arabi")
1024                         os << "\\textLR{" << termcmd;
1025                 else
1026                         os << "\\L{";
1027                 close = true;
1028         }
1029
1030         // FIXME: Bug: we can have an empty font change here!
1031         // if there has just been a font change, we are going to close it
1032         // right now, which means stupid latex code like \textsf{}. AFAIK,
1033         // this does not harm dvi output. A minor bug, thus (JMarc)
1034
1035         // Some insets cannot be inside a font change command.
1036         // However, even such insets *can* be placed in \L or \R
1037         // or their equivalents (for RTL language switches), so we don't
1038         // close the language in those cases.
1039         // ArabTeX, though, cannot handle this special behavior, it seems.
1040         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1041                 || running_font.language()->lang() == "arabic_arabtex";
1042         if (open_font && (!inset->inheritFont() || inset->allowMultiPar())) {
1043                 bool closeLanguage = arabtex
1044                         || basefont.isRightToLeft() == running_font.isRightToLeft();
1045                 InsetText const * textinset = inset->asInsetText();
1046                 bool const cprotect = textinset
1047                         ? textinset->hasCProtectContent(runparams.moving_arg)
1048                           && !textinset->text().isMainText()
1049                         : false;
1050                 unsigned int count = running_font.latexWriteStartChanges(os, bparams,
1051                                                       runparams, basefont,
1052                                                       running_font, true,
1053                                                       cprotect);
1054                 column += count;
1055                 // if any font properties were closed, update the running_font,
1056                 // making sure, however, to leave the language as it was
1057                 if (count > 0) {
1058                         // FIXME: probably a better way to keep track of the old
1059                         // language, than copying the entire font?
1060                         Font const copy_font(running_font);
1061                         basefont = owner_->getLayoutFont(bparams, outerfont);
1062                         running_font = basefont;
1063                         if (!closeLanguage)
1064                                 running_font.setLanguage(copy_font.language());
1065                         // For these, we use switches, so no need to close
1066                         basefont.fontInfo().setSize(copy_font.fontInfo().size());
1067                         basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1068                         basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1069                         if (closeLanguage)
1070                                 runparams.local_font = &basefont;
1071                 }
1072         }
1073
1074         size_t const previous_row_count = os.texrow().rows();
1075
1076         try {
1077                 runparams.lastid = id_;
1078                 runparams.lastpos = i;
1079                 inset->latex(os, runparams);
1080         } catch (EncodingException & e) {
1081                 // add location information and throw again.
1082                 e.par_id = id_;
1083                 e.pos = i;
1084                 throw(e);
1085         }
1086
1087         if (close)
1088                 os << '}';
1089
1090         if (os.texrow().rows() > previous_row_count) {
1091                 os.texrow().start(owner_->id(), i + 1);
1092                 column = 0;
1093         } else {
1094                 column += (unsigned int)(os.os().tellp() - len);
1095         }
1096
1097         if (owner_->isDeleted(i))
1098                 --runparams.inDeletedInset;
1099 }
1100
1101
1102 void Paragraph::Private::latexSpecialChar(otexstream & os,
1103                                           BufferParams const & bparams,
1104                                           OutputParams const & runparams,
1105                                           Font const & running_font,
1106                                           string & alien_script,
1107                                           Layout const & style,
1108                                           pos_type & i,
1109                                           pos_type end_pos,
1110                                           unsigned int & column)
1111 {
1112         char_type const c = owner_->getUChar(bparams, runparams, i);
1113
1114         if (style.pass_thru || runparams.pass_thru
1115             || contains(style.pass_thru_chars, c)
1116             || contains(runparams.pass_thru_chars, c)) {
1117                 if (c != '\0') {
1118                         Encoding const * const enc = runparams.encoding;
1119                         if (enc && !enc->encodable(c))
1120                                 throw EncodingException(c);
1121                         os.put(c);
1122                 }
1123                 return;
1124         }
1125
1126         // TIPA uses its own T3 encoding
1127         if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1128                 return;
1129         // If T1 font encoding is used, use the special
1130         // characters it provides.
1131         // NOTE: Some languages reset the font encoding internally to a
1132         //       non-standard font encoding. If we are using such a language,
1133         //       we do not output special T1 chars.
1134         if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1135             && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1136             && latexSpecialT1(c, os, i, column))
1137                 return;
1138         // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1139         else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1140                  && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1141                      return;
1142
1143         // Otherwise, we use what LaTeX provides us.
1144         switch (c) {
1145         case '\\':
1146                 os << "\\textbackslash" << termcmd;
1147                 column += 15;
1148                 break;
1149         case '<':
1150                 os << "\\textless" << termcmd;
1151                 column += 10;
1152                 break;
1153         case '>':
1154                 os << "\\textgreater" << termcmd;
1155                 column += 13;
1156                 break;
1157         case '|':
1158                 os << "\\textbar" << termcmd;
1159                 column += 9;
1160                 break;
1161         case '-':
1162                 os << '-';
1163                 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1164                     (end_pos == -1 || i + 1 < end_pos) &&
1165                     text_[i+1] == '-') {
1166                         // Prevent "--" becoming an en dash and "---" an em dash.
1167                         // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1168                         os << "{}";
1169                         column += 2;
1170                 }
1171                 break;
1172         case '\"':
1173                 os << "\\textquotedbl" << termcmd;
1174                 column += 14;
1175                 break;
1176
1177         case '$': case '&':
1178         case '%': case '#': case '{':
1179         case '}': case '_':
1180                 os << '\\';
1181                 os.put(c);
1182                 column += 1;
1183                 break;
1184
1185         case '~':
1186                 os << "\\textasciitilde" << termcmd;
1187                 column += 16;
1188                 break;
1189
1190         case '^':
1191                 os << "\\textasciicircum" << termcmd;
1192                 column += 17;
1193                 break;
1194
1195         case '*':
1196         case '[':
1197         case ']':
1198                 // avoid being mistaken for optional arguments
1199                 os << '{';
1200                 os.put(c);
1201                 os << '}';
1202                 column += 2;
1203                 break;
1204
1205         case ' ':
1206                 // Blanks are printed before font switching.
1207                 // Sure? I am not! (try nice-latex)
1208                 // I am sure it's correct. LyX might be smarter
1209                 // in the future, but for now, nothing wrong is
1210                 // written. (Asger)
1211                 break;
1212
1213         case 0x2013:
1214         case 0x2014:
1215                 // XeTeX's dash behaviour is determined via a global setting
1216                 if (bparams.use_dash_ligatures
1217                     && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1218                     && !runparams.inIPA
1219                         // TODO #10961: && not in inset Flex Code
1220                         // TODO #10961: && not in layout LyXCode
1221                     && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1222                         if (c == 0x2013) {
1223                                 // en-dash
1224                                 os << "--";
1225                                 column +=2;
1226                         } else {
1227                                 // em-dash
1228                                 os << "---";
1229                                 column +=3;
1230                         }
1231                         break;
1232                 }
1233                 // fall through
1234         default:
1235                 if (c == '\0')
1236                         return;
1237
1238                 Encoding const & encoding = *(runparams.encoding);
1239                 char_type next = '\0';
1240                 if (i + 1 < int(text_.size())) {
1241                         next = text_[i + 1];
1242                         if (Encodings::isCombiningChar(next)) {
1243                                 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1244                                 ++i;
1245                                 break;
1246                         }
1247                 }
1248                 pair<docstring, bool> latex = encoding.latexChar(c);
1249                 docstring nextlatex;
1250                 bool nexttipas = false;
1251                 string nexttipashortcut;
1252                 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1253                         nextlatex = encoding.latexChar(next).first;
1254                         if (runparams.inIPA) {
1255                                 nexttipashortcut = Encodings::TIPAShortcut(next);
1256                                 nexttipas = !nexttipashortcut.empty();
1257                         }
1258                 }
1259                 bool tipas = false;
1260                 if (runparams.inIPA) {
1261                         string const tipashortcut = Encodings::TIPAShortcut(c);
1262                         if (!tipashortcut.empty()) {
1263                                 latex.first = from_ascii(tipashortcut);
1264                                 latex.second = false;
1265                                 tipas = true;
1266                         }
1267                 }
1268                 // eventually close "script wrapper" command (see `Paragraph::latex`)
1269                 if (!alien_script.empty()
1270                         && alien_script != Encodings::isKnownScriptChar(next)) {
1271                         column += latex.first.length();
1272                         alien_script.clear();
1273                         os << latex.first << "}";
1274                         break;
1275                 }
1276                 if (latex.second
1277                          && ((!prefixIs(nextlatex, '\\')
1278                                && !prefixIs(nextlatex, '{')
1279                                && !prefixIs(nextlatex, '}'))
1280                              || (nexttipas
1281                                  && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1282                          && !tipas) {
1283                         // Prevent eating of a following space or command corruption by
1284                         // following characters
1285                         if (next == ' ' || next == '\0') {
1286                                 column += latex.first.length() + 1;
1287                                 os << latex.first << "{}";
1288                         } else {
1289                                 column += latex.first.length();
1290                                 os << latex.first << " ";
1291                         }
1292                 } else {
1293                         column += latex.first.length() - 1;
1294                         os << latex.first;
1295                 }
1296                 break;
1297         }
1298 }
1299
1300
1301 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1302         pos_type i, unsigned int & column)
1303 {
1304         switch (c) {
1305         case '>':
1306         case '<':
1307                 os.put(c);
1308                 // In T1 encoding, these characters exist
1309                 // but we should avoid ligatures
1310                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1311                         return true;
1312                 os << "\\textcompwordmark" << termcmd;
1313                 column += 19;
1314                 return true;
1315         case '|':
1316                 os.put(c);
1317                 return true;
1318         case '\"':
1319                 // soul.sty breaks with \char`\"
1320                 os << "\\textquotedbl" << termcmd;
1321                 column += 14;
1322                 return true;
1323         default:
1324                 return false;
1325         }
1326 }
1327
1328
1329 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1330         pos_type i, unsigned int & column)
1331 {
1332         // TU encoding is currently on par with T1.
1333         return latexSpecialT1(c, os, i, column);
1334 }
1335
1336
1337 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1338         pos_type /*i*/, unsigned int & column)
1339 {
1340         switch (c) {
1341         case '*':
1342         case '[':
1343         case ']':
1344         case '\"':
1345                 os.put(c);
1346                 return true;
1347         case '|':
1348                 os << "\\textvertline" << termcmd;
1349                 column += 14;
1350                 return true;
1351         default:
1352                 return false;
1353         }
1354 }
1355
1356
1357 void Paragraph::Private::validate(LaTeXFeatures & features) const
1358 {
1359         if (layout_->inpreamble && inset_owner_) {
1360                 // FIXME: Using a string stream here circumvents the encoding
1361                 // switching machinery of odocstream. Therefore the
1362                 // output is wrong if this paragraph contains content
1363                 // that needs to switch encoding.
1364                 Buffer const & buf = inset_owner_->buffer();
1365                 otexstringstream os;
1366                 os << layout_->preamble();
1367                 size_t const length = os.length();
1368                 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1369                           buf.getParFromID(owner_->id()).pit(), os,
1370                           features.runparams(), string(), 0, -1, true);
1371                 if (os.length() > length)
1372                         features.addPreambleSnippet(os.release(), true);
1373         }
1374
1375         if (features.runparams().flavor == OutputParams::HTML
1376             && layout_->htmltitle()) {
1377                 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1378         }
1379
1380         // check the params.
1381         if (!params_.spacing().isDefault())
1382                 features.require("setspace");
1383
1384         // then the layouts
1385         features.useLayout(layout_->name());
1386
1387         // then the fonts
1388         fontlist_.validate(features);
1389
1390         // then the indentation
1391         if (!params_.leftIndent().zero())
1392                 features.require("ParagraphLeftIndent");
1393
1394         // then the insets
1395         InsetList::const_iterator icit = insetlist_.begin();
1396         InsetList::const_iterator iend = insetlist_.end();
1397         for (; icit != iend; ++icit) {
1398                 if (icit->inset) {
1399                         features.inDeletedInset(owner_->isDeleted(icit->pos));
1400                         if (icit->inset->lyxCode() == FOOT_CODE) {
1401                                 // FIXME: an item inset would make things much easier.
1402                                 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1403                                      || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1404                                          && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1405                                     && (icit->pos < begin_of_body_
1406                                         || (icit->pos == begin_of_body_
1407                                             && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1408                                         features.saveNoteEnv("description");
1409                         }
1410                         icit->inset->validate(features);
1411                         features.inDeletedInset(false);
1412                         if (layout_->needprotect &&
1413                             icit->inset->lyxCode() == FOOT_CODE)
1414                                 features.require("NeedLyXFootnoteCode");
1415                 }
1416         }
1417
1418         // then the contents
1419         BufferParams const bp = features.runparams().is_child
1420                 ? features.buffer().masterParams() : features.buffer().params();
1421         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1422                 char_type c = text_[i];
1423                 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1424                 if (c == 0x0022) {
1425                         if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1426                                 features.require("textquotedblp");
1427                         else if (bp.main_font_encoding() != "T1"
1428                                  || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1429                                 features.require("textquotedbl");
1430                 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1431                         // features that depend on the font or input encoding
1432                         string feats = ci.textpreamble();
1433                         string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1434                         if (fontenc.empty())
1435                                 fontenc = features.runparams().main_fontenc;
1436                         while (!feats.empty()) {
1437                                 string feat;
1438                                 feats = split(feats, feat, ',');
1439                                 if (contains(feat, "!=")) {
1440                                         // a feature that is required except for the spcified
1441                                         // font or input encodings
1442                                         string realfeature;
1443                                         string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1444                                         // multiple encodings are separated by semicolon
1445                                         vector<string> context = getVectorFromString(contexts, ";");
1446                                         // require feature if the context matches neither current font
1447                                         // nor input encoding
1448                                         if (std::find(context.begin(), context.end(), fontenc) == context.end()
1449                                             && std::find(context.begin(), context.end(),
1450                                                          features.runparams().encoding->name()) == context.end())
1451                                                 features.require(realfeature);
1452                                 } else if (contains(feat, '=')) {
1453                                         // a feature that is required only for the spcified
1454                                         // font or input encodings
1455                                         string realfeature;
1456                                         string const contexts = split(feat, realfeature, '=');
1457                                         // multiple encodings are separated by semicolon
1458                                         vector<string> context = getVectorFromString(contexts, ";");
1459                                         // require feature if the context matches either current font
1460                                         // or input encoding
1461                                         if (std::find(context.begin(), context.end(), fontenc) != context.end()
1462                                             || std::find(context.begin(), context.end(),
1463                                                          features.runparams().encoding->name()) != context.end())
1464                                                 features.require(realfeature);
1465                                 }
1466                         }
1467                 } else if (!bp.use_dash_ligatures
1468                            && (c == 0x2013 || c == 0x2014)
1469                            && bp.useNonTeXFonts
1470                            && features.runparams().flavor == OutputParams::XETEX)
1471                         // XeTeX's dash behaviour is determined via a global setting
1472                         features.require("xetexdashbreakstate");
1473                 BufferEncodings::validate(c, features);
1474         }
1475 }
1476
1477 /////////////////////////////////////////////////////////////////////
1478 //
1479 // Paragraph
1480 //
1481 /////////////////////////////////////////////////////////////////////
1482
1483 namespace {
1484         Layout const emptyParagraphLayout;
1485 }
1486
1487 Paragraph::Paragraph()
1488         : d(new Paragraph::Private(this, emptyParagraphLayout))
1489 {
1490         itemdepth = 0;
1491         d->params_.clear();
1492 }
1493
1494
1495 Paragraph::Paragraph(Paragraph const & par)
1496         : itemdepth(par.itemdepth),
1497         d(new Paragraph::Private(*par.d, this))
1498 {
1499         registerWords();
1500 }
1501
1502
1503 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1504         : itemdepth(par.itemdepth),
1505         d(new Paragraph::Private(*par.d, this, beg, end))
1506 {
1507         registerWords();
1508 }
1509
1510
1511 Paragraph & Paragraph::operator=(Paragraph const & par)
1512 {
1513         // needed as we will destroy the private part before copying it
1514         if (&par != this) {
1515                 itemdepth = par.itemdepth;
1516
1517                 deregisterWords();
1518                 delete d;
1519                 d = new Private(*par.d, this);
1520                 registerWords();
1521         }
1522         return *this;
1523 }
1524
1525
1526 Paragraph::~Paragraph()
1527 {
1528         deregisterWords();
1529         delete d;
1530 }
1531
1532
1533 namespace {
1534
1535 // this shall be called just before every "os << ..." action.
1536 void flushString(ostream & os, docstring & s)
1537 {
1538         os << to_utf8(s);
1539         s.erase();
1540 }
1541
1542 } // namespace
1543
1544
1545 void Paragraph::write(ostream & os, BufferParams const & bparams,
1546         depth_type & dth) const
1547 {
1548         // The beginning or end of a deeper (i.e. nested) area?
1549         if (dth != d->params_.depth()) {
1550                 if (d->params_.depth() > dth) {
1551                         while (d->params_.depth() > dth) {
1552                                 os << "\n\\begin_deeper";
1553                                 ++dth;
1554                         }
1555                 } else {
1556                         while (d->params_.depth() < dth) {
1557                                 os << "\n\\end_deeper";
1558                                 --dth;
1559                         }
1560                 }
1561         }
1562
1563         // First write the layout
1564         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1565
1566         d->params_.write(os);
1567
1568         Font font1(inherit_font, bparams.language);
1569
1570         Change running_change = Change(Change::UNCHANGED);
1571
1572         // this string is used as a buffer to avoid repetitive calls
1573         // to to_utf8(), which turn out to be expensive (JMarc)
1574         docstring write_buffer;
1575
1576         int column = 0;
1577         for (pos_type i = 0; i <= size(); ++i) {
1578
1579                 Change const & change = lookupChange(i);
1580                 if (change != running_change)
1581                         flushString(os, write_buffer);
1582                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1583                 running_change = change;
1584
1585                 if (i == size())
1586                         break;
1587
1588                 // Write font changes
1589                 Font font2 = getFontSettings(bparams, i);
1590                 if (font2 != font1) {
1591                         flushString(os, write_buffer);
1592                         font2.lyxWriteChanges(font1, os);
1593                         column = 0;
1594                         font1 = font2;
1595                 }
1596
1597                 char_type const c = d->text_[i];
1598                 switch (c) {
1599                 case META_INSET:
1600                         if (Inset const * inset = getInset(i)) {
1601                                 flushString(os, write_buffer);
1602                                 if (inset->directWrite()) {
1603                                         // international char, let it write
1604                                         // code directly so it's shorter in
1605                                         // the file
1606                                         inset->write(os);
1607                                 } else {
1608                                         if (i)
1609                                                 os << '\n';
1610                                         os << "\\begin_inset ";
1611                                         inset->write(os);
1612                                         os << "\n\\end_inset\n\n";
1613                                         column = 0;
1614                                 }
1615                                 // FIXME This can be removed again once the mystery
1616                                 // crash has been resolved.
1617                                 os << flush;
1618                         }
1619                         break;
1620                 case '\\':
1621                         flushString(os, write_buffer);
1622                         os << "\n\\backslash\n";
1623                         column = 0;
1624                         break;
1625                 case '.':
1626                         flushString(os, write_buffer);
1627                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1628                                 os << ".\n";
1629                                 column = 0;
1630                         } else
1631                                 os << '.';
1632                         break;
1633                 default:
1634                         if ((column > 70 && c == ' ')
1635                             || column > 79) {
1636                                 flushString(os, write_buffer);
1637                                 os << '\n';
1638                                 column = 0;
1639                         }
1640                         // this check is to amend a bug. LyX sometimes
1641                         // inserts '\0' this could cause problems.
1642                         if (c != '\0')
1643                                 write_buffer.push_back(c);
1644                         else
1645                                 LYXERR0("NUL char in structure.");
1646                         ++column;
1647                         break;
1648                 }
1649         }
1650
1651         flushString(os, write_buffer);
1652         os << "\n\\end_layout\n";
1653         // FIXME This can be removed again once the mystery
1654         // crash has been resolved.
1655         os << flush;
1656 }
1657
1658
1659 void Paragraph::validate(LaTeXFeatures & features) const
1660 {
1661         d->validate(features);
1662         bool fragile = features.runparams().moving_arg;
1663         fragile |= layout().needprotect;
1664         if (inInset().getLayout().isNeedProtect())
1665                 fragile = true;
1666         if (needsCProtection(fragile))
1667                 features.require("cprotect");
1668 }
1669
1670
1671 void Paragraph::insert(pos_type start, docstring const & str,
1672                        Font const & font, Change const & change)
1673 {
1674         for (size_t i = 0, n = str.size(); i != n ; ++i)
1675                 insertChar(start + i, str[i], font, change);
1676 }
1677
1678
1679 void Paragraph::appendChar(char_type c, Font const & font,
1680                 Change const & change)
1681 {
1682         // track change
1683         d->changes_.insert(change, d->text_.size());
1684         // when appending characters, no need to update tables
1685         d->text_.push_back(c);
1686         setFont(d->text_.size() - 1, font);
1687         d->requestSpellCheck(d->text_.size() - 1);
1688 }
1689
1690
1691 void Paragraph::appendString(docstring const & s, Font const & font,
1692                 Change const & change)
1693 {
1694         pos_type end = s.size();
1695         size_t oldsize = d->text_.size();
1696         size_t newsize = oldsize + end;
1697         size_t capacity = d->text_.capacity();
1698         if (newsize >= capacity)
1699                 d->text_.reserve(max(capacity + 100, newsize));
1700
1701         // when appending characters, no need to update tables
1702         d->text_.append(s);
1703
1704         // FIXME: Optimize this!
1705         for (size_t i = oldsize; i != newsize; ++i) {
1706                 // track change
1707                 d->changes_.insert(change, i);
1708                 d->requestSpellCheck(i);
1709         }
1710         d->fontlist_.set(oldsize, font);
1711         d->fontlist_.set(newsize - 1, font);
1712 }
1713
1714
1715 void Paragraph::insertChar(pos_type pos, char_type c,
1716                            bool trackChanges)
1717 {
1718         d->insertChar(pos, c, Change(trackChanges ?
1719                            Change::INSERTED : Change::UNCHANGED));
1720 }
1721
1722
1723 void Paragraph::insertChar(pos_type pos, char_type c,
1724                            Font const & font, bool trackChanges)
1725 {
1726         d->insertChar(pos, c, Change(trackChanges ?
1727                            Change::INSERTED : Change::UNCHANGED));
1728         setFont(pos, font);
1729 }
1730
1731
1732 void Paragraph::insertChar(pos_type pos, char_type c,
1733                            Font const & font, Change const & change)
1734 {
1735         d->insertChar(pos, c, change);
1736         setFont(pos, font);
1737 }
1738
1739
1740 void Paragraph::resetFonts(Font const & font)
1741 {
1742         d->fontlist_.clear();
1743         d->fontlist_.set(0, font);
1744         d->fontlist_.set(d->text_.size() - 1, font);
1745 }
1746
1747 // Gets uninstantiated font setting at position.
1748 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1749                                          pos_type pos) const
1750 {
1751         if (pos > size()) {
1752                 LYXERR0("pos: " << pos << " size: " << size());
1753                 LBUFERR(false);
1754         }
1755
1756         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1757         if (cit != d->fontlist_.end())
1758                 return cit->font();
1759
1760         if (pos == size() && !empty())
1761                 return getFontSettings(bparams, pos - 1);
1762
1763         // Optimisation: avoid a full font instantiation if there is no
1764         // language change from previous call.
1765         static Font previous_font;
1766         static Language const * previous_lang = nullptr;
1767         Language const * lang = getParLanguage(bparams);
1768         if (lang != previous_lang) {
1769                 previous_lang = lang;
1770                 previous_font = Font(inherit_font, lang);
1771         }
1772         return previous_font;
1773 }
1774
1775
1776 FontSpan Paragraph::fontSpan(pos_type pos) const
1777 {
1778         LBUFERR(pos <= size());
1779
1780         if (pos == size())
1781                 return FontSpan(pos, pos);
1782
1783         pos_type start = 0;
1784         FontList::const_iterator cit = d->fontlist_.begin();
1785         FontList::const_iterator end = d->fontlist_.end();
1786         for (; cit != end; ++cit) {
1787                 if (cit->pos() >= pos) {
1788                         if (pos >= beginOfBody())
1789                                 return FontSpan(max(start, beginOfBody()),
1790                                                 cit->pos());
1791                         else
1792                                 return FontSpan(start,
1793                                                 min(beginOfBody() - 1,
1794                                                          cit->pos()));
1795                 }
1796                 start = cit->pos() + 1;
1797         }
1798
1799         // This should not happen, but if so, we take no chances.
1800         LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1801         LASSERT(false, return FontSpan(pos, pos));
1802 }
1803
1804
1805 // Gets uninstantiated font setting at position 0
1806 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1807 {
1808         if (!empty() && !d->fontlist_.empty())
1809                 return d->fontlist_.begin()->font();
1810
1811         // Optimisation: avoid a full font instantiation if there is no
1812         // language change from previous call.
1813         static Font previous_font;
1814         static Language const * previous_lang = nullptr;
1815         if (bparams.language != previous_lang) {
1816                 previous_lang = bparams.language;
1817                 previous_font = Font(inherit_font, bparams.language);
1818         }
1819
1820         return previous_font;
1821 }
1822
1823
1824 // Gets the fully instantiated font at a given position in a paragraph
1825 // This is basically the same function as Text::GetFont() in text2.cpp.
1826 // The difference is that this one is used for generating the LaTeX file,
1827 // and thus cosmetic "improvements" are disallowed: This has to deliver
1828 // the true picture of the buffer. (Asger)
1829 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1830                                  Font const & outerfont) const
1831 {
1832         LBUFERR(pos >= 0);
1833
1834         Font font = getFontSettings(bparams, pos);
1835
1836         pos_type const body_pos = beginOfBody();
1837         FontInfo & fi = font.fontInfo();
1838         if (pos < body_pos)
1839                 fi.realize(d->layout_->labelfont);
1840         else
1841                 fi.realize(d->layout_->font);
1842
1843         fi.realize(outerfont.fontInfo());
1844         fi.realize(bparams.getFont().fontInfo());
1845
1846         return font;
1847 }
1848
1849
1850 Font const Paragraph::getLabelFont
1851         (BufferParams const & bparams, Font const & outerfont) const
1852 {
1853         FontInfo tmpfont = d->layout_->labelfont;
1854         tmpfont.realize(outerfont.fontInfo());
1855         tmpfont.realize(bparams.getFont().fontInfo());
1856         return Font(tmpfont, getParLanguage(bparams));
1857 }
1858
1859
1860 Font const Paragraph::getLayoutFont
1861         (BufferParams const & bparams, Font const & outerfont) const
1862 {
1863         FontInfo tmpfont = d->layout_->font;
1864         tmpfont.realize(outerfont.fontInfo());
1865         tmpfont.realize(bparams.getFont().fontInfo());
1866         return Font(tmpfont, getParLanguage(bparams));
1867 }
1868
1869
1870 char_type Paragraph::getUChar(BufferParams const & bparams,
1871                               OutputParams const & rp,
1872                               pos_type pos) const
1873 {
1874         char_type c = d->text_[pos];
1875
1876         // Return unchanged character in LTR languages
1877         // or if we use poylglossia/bidi (XeTeX).
1878         if (rp.useBidiPackage()
1879             || !getFontSettings(bparams, pos).isRightToLeft())
1880                 return c;
1881
1882         // Without polyglossia/bidi, we need to account for some special cases.
1883         // FIXME This needs to be audited!
1884         // Check if:
1885         // * The input is as expected for all delimiters
1886         //   => checked for Hebrew!
1887         // * The output matches the display in the LyX workarea
1888         //   => checked for Hebrew!
1889         // * The special cases below are really necessary
1890         //   => checked for Hebrew!
1891         // * In arabic_arabi, brackets are transformed to Arabic
1892         //   Ornate Parentheses. Is this is really wanted?
1893
1894         string const & lang = getFontSettings(bparams, pos).language()->lang();
1895         char_type uc = c;
1896
1897         // 1. In the following languages, parentheses need to be reversed.
1898         //    Also with polyglodia/luabidi
1899         bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1900
1901         // 2. In the following languages, brackets don't need to be reversed.
1902         bool const reversebrackets = lang != "arabic_arabtex"
1903                         && lang != "arabic_arabi"
1904                         && lang != "farsi";
1905
1906         // Now swap delimiters if needed.
1907         switch (c) {
1908         case '(':
1909                 if (reverseparens)
1910                         uc = ')';
1911                 break;
1912         case ')':
1913                 if (reverseparens)
1914                         uc = '(';
1915                 break;
1916         case '[':
1917                 if (reversebrackets)
1918                         uc = ']';
1919                 break;
1920         case ']':
1921                 if (reversebrackets)
1922                         uc = '[';
1923                 break;
1924         case '{':
1925                 uc = '}';
1926                 break;
1927         case '}':
1928                 uc = '{';
1929                 break;
1930         case '<':
1931                 uc = '>';
1932                 break;
1933         case '>':
1934                 uc = '<';
1935                 break;
1936         }
1937
1938         return uc;
1939 }
1940
1941
1942 void Paragraph::setFont(pos_type pos, Font const & font)
1943 {
1944         LASSERT(pos <= size(), return);
1945
1946         // First, reduce font against layout/label font
1947         // Update: The setCharFont() routine in text2.cpp already
1948         // reduces font, so we don't need to do that here. (Asger)
1949
1950         d->fontlist_.set(pos, font);
1951 }
1952
1953
1954 void Paragraph::makeSameLayout(Paragraph const & par)
1955 {
1956         d->layout_ = par.d->layout_;
1957         d->params_ = par.d->params_;
1958 }
1959
1960
1961 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1962 {
1963         if (isFreeSpacing())
1964                 return false;
1965
1966         int pos = 0;
1967         int count = 0;
1968
1969         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1970                 if (eraseChar(pos, trackChanges))
1971                         ++count;
1972                 else
1973                         ++pos;
1974         }
1975
1976         return count > 0 || pos > 0;
1977 }
1978
1979
1980 bool Paragraph::hasSameLayout(Paragraph const & par) const
1981 {
1982         return par.d->layout_ == d->layout_
1983                 && d->params_.sameLayout(par.d->params_);
1984 }
1985
1986
1987 depth_type Paragraph::getDepth() const
1988 {
1989         return d->params_.depth();
1990 }
1991
1992
1993 depth_type Paragraph::getMaxDepthAfter() const
1994 {
1995         if (d->layout_->isEnvironment())
1996                 return d->params_.depth() + 1;
1997         else
1998                 return d->params_.depth();
1999 }
2000
2001
2002 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2003 {
2004         if (d->params_.align() == LYX_ALIGN_LAYOUT)
2005                 return getDefaultAlign(bparams);
2006         else
2007                 return d->params_.align();
2008 }
2009
2010
2011 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2012 {
2013         LyXAlignment res = layout().align;
2014         if (isRTL(bparams)) {
2015                 // Swap sides
2016                 if (res == LYX_ALIGN_LEFT)
2017                         res = LYX_ALIGN_RIGHT;
2018                 else if  (res == LYX_ALIGN_RIGHT)
2019                         res = LYX_ALIGN_LEFT;
2020         }
2021         return res;
2022 }
2023
2024
2025 docstring const & Paragraph::labelString() const
2026 {
2027         return d->params_.labelString();
2028 }
2029
2030
2031 // the next two functions are for the manual labels
2032 docstring const Paragraph::getLabelWidthString() const
2033 {
2034         if (d->layout_->margintype == MARGIN_MANUAL
2035             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2036                 return d->params_.labelWidthString();
2037         else
2038                 return _("Senseless with this layout!");
2039 }
2040
2041
2042 void Paragraph::setLabelWidthString(docstring const & s)
2043 {
2044         d->params_.labelWidthString(s);
2045 }
2046
2047
2048 docstring Paragraph::expandLabel(Layout const & layout,
2049                 BufferParams const & bparams) const
2050 {
2051         return expandParagraphLabel(layout, bparams, true);
2052 }
2053
2054
2055 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2056                 BufferParams const & bparams, bool process_appendix) const
2057 {
2058         DocumentClass const & tclass = bparams.documentClass();
2059         string const & lang = getParLanguage(bparams)->code();
2060         bool const in_appendix = process_appendix && d->params_.appendix();
2061         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2062
2063         if (fmt.empty() && !layout.counter.empty())
2064                 return tclass.counters().theCounter(layout.counter, lang);
2065
2066         // handle 'inherited level parts' in 'fmt',
2067         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
2068         size_t const i = fmt.find('@', 0);
2069         if (i != docstring::npos) {
2070                 size_t const j = fmt.find('@', i + 1);
2071                 if (j != docstring::npos) {
2072                         docstring parent(fmt, i + 1, j - i - 1);
2073                         docstring label = from_ascii("??");
2074                         if (tclass.hasLayout(parent))
2075                                 label = expandParagraphLabel(tclass[parent], bparams,
2076                                                       process_appendix);
2077                         fmt = docstring(fmt, 0, i) + label
2078                                 + docstring(fmt, j + 1, docstring::npos);
2079                 }
2080         }
2081
2082         return tclass.counters().counterLabel(fmt, lang);
2083 }
2084
2085
2086 void Paragraph::applyLayout(Layout const & new_layout)
2087 {
2088         d->layout_ = &new_layout;
2089         LyXAlignment const oldAlign = d->params_.align();
2090
2091         if (!(oldAlign & d->layout_->alignpossible)) {
2092                 frontend::Alert::warning(_("Alignment not permitted"),
2093                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
2094                 d->params_.align(LYX_ALIGN_LAYOUT);
2095         }
2096 }
2097
2098
2099 pos_type Paragraph::beginOfBody() const
2100 {
2101         return d->begin_of_body_;
2102 }
2103
2104
2105 void Paragraph::setBeginOfBody()
2106 {
2107         if (d->layout_->labeltype != LABEL_MANUAL) {
2108                 d->begin_of_body_ = 0;
2109                 return;
2110         }
2111
2112         // Unroll the first two cycles of the loop
2113         // and remember the previous character to
2114         // remove unnecessary getChar() calls
2115         pos_type i = 0;
2116         pos_type end = size();
2117         bool prev_char_deleted = false;
2118         if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2119                 ++i;
2120                 if (i < end) {
2121                         char_type previous_char = d->text_[i];
2122                         if (!(isNewline(i) || isEnvSeparator(i))) {
2123                                 ++i;
2124                                 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2125                                         char_type temp = d->text_[i];
2126                                         prev_char_deleted = isDeleted(i);
2127                                         if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2128                                                 break;
2129                                         ++i;
2130                                         previous_char = temp;
2131                                 }
2132                         }
2133                 }
2134         }
2135
2136         d->begin_of_body_ = i;
2137 }
2138
2139
2140 bool Paragraph::allowParagraphCustomization() const
2141 {
2142         return inInset().allowParagraphCustomization();
2143 }
2144
2145
2146 bool Paragraph::usePlainLayout() const
2147 {
2148         return inInset().usePlainLayout();
2149 }
2150
2151
2152 bool Paragraph::isPassThru() const
2153 {
2154         return inInset().isPassThru() || d->layout_->pass_thru;
2155 }
2156
2157 namespace {
2158
2159 // paragraphs inside floats need different alignment tags to avoid
2160 // unwanted space
2161
2162 bool noTrivlistCentering(InsetCode code)
2163 {
2164         return code == FLOAT_CODE
2165                || code == WRAP_CODE
2166                || code == CELL_CODE;
2167 }
2168
2169
2170 string correction(string const & orig)
2171 {
2172         if (orig == "flushleft")
2173                 return "raggedright";
2174         if (orig == "flushright")
2175                 return "raggedleft";
2176         if (orig == "center")
2177                 return "centering";
2178         return orig;
2179 }
2180
2181
2182 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2183         InsetCode code, bool const lastpar, int & col)
2184 {
2185         string macro = suffix + "{";
2186         if (noTrivlistCentering(code)) {
2187                 if (lastpar) {
2188                         // the last paragraph in non-trivlist-aligned
2189                         // context is special (to avoid unwanted whitespace)
2190                         if (suffix == "\\begin") {
2191                                 macro = "\\" + correction(env) + "{}";
2192                                 os << from_ascii(macro);
2193                                 col += macro.size();
2194                                 return true;
2195                         }
2196                         return false;
2197                 }
2198                 macro += correction(env);
2199         } else
2200                 macro += env;
2201         macro += "}";
2202         if (suffix == "\\par\\end") {
2203                 os << breakln;
2204                 col = 0;
2205         }
2206         os << from_ascii(macro);
2207         col += macro.size();
2208         if (suffix == "\\begin") {
2209                 os << breakln;
2210                 col = 0;
2211         }
2212         return true;
2213 }
2214
2215 } // namespace
2216
2217
2218 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2219                         otexstream & os, OutputParams const & runparams) const
2220 {
2221         int column = 0;
2222
2223         bool canindent =
2224                 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2225                         (layout_->toggle_indent != ITOGGLE_NEVER) :
2226                         (layout_->toggle_indent == ITOGGLE_ALWAYS);
2227
2228         if (canindent && params_.noindent() && !layout_->pass_thru) {
2229                 os << "\\noindent ";
2230                 column += 10;
2231         }
2232
2233         LyXAlignment const curAlign = params_.align();
2234
2235         if (curAlign == layout_->align)
2236                 return column;
2237
2238         switch (curAlign) {
2239         case LYX_ALIGN_NONE:
2240         case LYX_ALIGN_BLOCK:
2241         case LYX_ALIGN_LAYOUT:
2242         case LYX_ALIGN_SPECIAL:
2243         case LYX_ALIGN_DECIMAL:
2244                 break;
2245         case LYX_ALIGN_LEFT:
2246         case LYX_ALIGN_RIGHT:
2247         case LYX_ALIGN_CENTER:
2248                 if (runparams.moving_arg) {
2249                         os << "\\protect";
2250                         column += 8;
2251                 }
2252                 break;
2253         }
2254
2255         string const begin_tag = "\\begin";
2256         InsetCode code = ownerCode();
2257         bool const lastpar = runparams.isLastPar;
2258         // RTL in classic (PDF)LaTeX (without the Bidi package)
2259         // Luabibdi (used by LuaTeX) behaves like classic
2260         bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2261                 && !runparams.useBidiPackage();
2262
2263         switch (curAlign) {
2264         case LYX_ALIGN_NONE:
2265         case LYX_ALIGN_BLOCK:
2266         case LYX_ALIGN_LAYOUT:
2267         case LYX_ALIGN_SPECIAL:
2268         case LYX_ALIGN_DECIMAL:
2269                 break;
2270         case LYX_ALIGN_LEFT: {
2271                 if (rtl_classic)
2272                         // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2273                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2274                 else
2275                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2276                 break;
2277         } case LYX_ALIGN_RIGHT: {
2278                 if (rtl_classic)
2279                         // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2280                         corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2281                 else
2282                         corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2283                 break;
2284         } case LYX_ALIGN_CENTER: {
2285                 corrected_env(os, begin_tag, "center", code, lastpar, column);
2286                 break;
2287         }
2288         }
2289
2290         return column;
2291 }
2292
2293
2294 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2295                         otexstream & os, OutputParams const & runparams) const
2296 {
2297         LyXAlignment const curAlign = params_.align();
2298
2299         if (curAlign == layout_->align)
2300                 return false;
2301
2302         switch (curAlign) {
2303         case LYX_ALIGN_NONE:
2304         case LYX_ALIGN_BLOCK:
2305         case LYX_ALIGN_LAYOUT:
2306         case LYX_ALIGN_SPECIAL:
2307         case LYX_ALIGN_DECIMAL:
2308                 break;
2309         case LYX_ALIGN_LEFT:
2310         case LYX_ALIGN_RIGHT:
2311         case LYX_ALIGN_CENTER:
2312                 if (runparams.moving_arg)
2313                         os << "\\protect";
2314                 break;
2315         }
2316
2317         bool output = false;
2318         int col = 0;
2319         string const end_tag = "\\par\\end";
2320         InsetCode code = ownerCode();
2321         bool const lastpar = runparams.isLastPar;
2322         // RTL in classic (PDF)LaTeX (without the Bidi package)
2323         // Luabibdi (used by LuaTeX) behaves like classic
2324         bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2325                 && !runparams.useBidiPackage();
2326
2327         switch (curAlign) {
2328         case LYX_ALIGN_NONE:
2329         case LYX_ALIGN_BLOCK:
2330         case LYX_ALIGN_LAYOUT:
2331         case LYX_ALIGN_SPECIAL:
2332         case LYX_ALIGN_DECIMAL:
2333                 break;
2334         case LYX_ALIGN_LEFT: {
2335                 if (rtl_classic)
2336                         // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2337                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2338                 else
2339                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2340                 break;
2341         } case LYX_ALIGN_RIGHT: {
2342                 if (rtl_classic)
2343                         // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2344                         output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2345                 else
2346                         output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2347                 break;
2348         } case LYX_ALIGN_CENTER: {
2349                 corrected_env(os, end_tag, "center", code, lastpar, col);
2350                 break;
2351         }
2352         }
2353
2354         return output || lastpar;
2355 }
2356
2357
2358 // This one spits out the text of the paragraph
2359 void Paragraph::latex(BufferParams const & bparams,
2360         Font const & outerfont,
2361         otexstream & os,
2362         OutputParams const & runparams,
2363         int start_pos, int end_pos, bool force) const
2364 {
2365         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2366
2367         // FIXME This check should not be needed. Perhaps issue an
2368         // error if it triggers.
2369         Layout const & style = inInset().forcePlainLayout() ?
2370                 bparams.documentClass().plainLayout() : *d->layout_;
2371
2372         if (!force && style.inpreamble)
2373                 return;
2374
2375         bool const allowcust = allowParagraphCustomization();
2376
2377         // Current base font for all inherited font changes, without any
2378         // change caused by an individual character, except for the language:
2379         // It is set to the language of the first character.
2380         // As long as we are in the label, this font is the base font of the
2381         // label. Before the first body character it is set to the base font
2382         // of the body.
2383         Font basefont;
2384
2385         // If there is an open font-encoding changing command (script wrapper),
2386         // alien_script is set to its name
2387         string alien_script;
2388         string script;
2389
2390         // Maybe we have to create a optional argument.
2391         pos_type body_pos = beginOfBody();
2392         unsigned int column = 0;
2393
2394         // If we are inside an non inheritFont() inset, the real outerfont is local_font
2395         Font const real_outerfont = (!inInset().inheritFont()
2396                                      && runparams.local_font != nullptr)
2397                         ? Font(runparams.local_font->fontInfo()) : outerfont;
2398
2399         if (body_pos > 0) {
2400                 // the optional argument is kept in curly brackets in
2401                 // case it contains a ']'
2402                 // This is not strictly needed, but if this is changed it
2403                 // would be a file format change, and tex2lyx would need
2404                 // to be adjusted, since it unconditionally removes the
2405                 // braces when it parses \item.
2406                 os << "[{";
2407                 column += 2;
2408                 basefont = getLabelFont(bparams, real_outerfont);
2409         } else {
2410                 basefont = getLayoutFont(bparams, real_outerfont);
2411         }
2412
2413         // Which font is currently active?
2414         Font running_font(basefont);
2415         // Do we have an open font change?
2416         bool open_font = false;
2417
2418         Change runningChange = Change(Change::UNCHANGED);
2419
2420         Encoding const * const prev_encoding = runparams.encoding;
2421
2422         os.texrow().start(id(), 0);
2423
2424         // if the paragraph is empty, the loop will not be entered at all
2425         if (empty()) {
2426                 // For InTitle commands, we have already opened a group
2427                 // in output_latex::TeXOnePar.
2428                 if (style.isCommand() && !style.intitle) {
2429                         os << '{';
2430                         ++column;
2431                 }
2432                 if (!style.leftdelim().empty()) {
2433                         os << style.leftdelim();
2434                         column += style.leftdelim().size();
2435                 }
2436                 if (allowcust)
2437                         column += d->startTeXParParams(bparams, os, runparams);
2438         }
2439
2440         // Whether a \par can be issued for insets typeset inline with text.
2441         // Yes if greater than 0. This has to be static.
2442         THREAD_LOCAL_STATIC int parInline = 0;
2443
2444         for (pos_type i = 0; i < size(); ++i) {
2445                 // First char in paragraph or after label?
2446                 if (i == body_pos) {
2447                         if (body_pos > 0) {
2448                                 if (open_font) {
2449                                         bool needPar = false;
2450                                         column += running_font.latexWriteEndChanges(
2451                                                 os, bparams, runparams,
2452                                                 basefont, basefont, needPar);
2453                                         open_font = false;
2454                                 }
2455                                 basefont = getLayoutFont(bparams, real_outerfont);
2456                                 running_font = basefont;
2457
2458                                 column += Changes::latexMarkChange(os, bparams,
2459                                                 runningChange, Change(Change::UNCHANGED),
2460                                                 runparams);
2461                                 runningChange = Change(Change::UNCHANGED);
2462
2463                                 os << "}] ";
2464                                 column +=3;
2465                         }
2466                         // For InTitle commands, we have already opened a group
2467                         // in output_latex::TeXOnePar.
2468                         if (style.isCommand() && !style.intitle) {
2469                                 os << '{';
2470                                 ++column;
2471                         }
2472
2473                         if (!style.leftdelim().empty()) {
2474                                 os << style.leftdelim();
2475                                 column += style.leftdelim().size();
2476                         }
2477
2478                         if (allowcust)
2479                                 column += d->startTeXParParams(bparams, os,
2480                                                             runparams);
2481                 }
2482
2483                 runparams.wasDisplayMath = runparams.inDisplayMath;
2484                 runparams.inDisplayMath = false;
2485                 bool deleted_display_math = false;
2486                 Change const & change = runparams.inDeletedInset
2487                         ? runparams.changeOfDeletedInset : lookupChange(i);
2488
2489                 char_type const c = d->text_[i];
2490
2491                 // Check whether a display math inset follows
2492                 if (c == META_INSET
2493                     && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2494                         if (isDeleted(i))
2495                                 runparams.ctObject = getInset(i)->CtObject(runparams);
2496         
2497                         InsetMath const * im = getInset(i)->asInsetMath();
2498                         if (im && im->asHullInset()
2499                             && im->asHullInset()->outerDisplay()) {
2500                                 runparams.inDisplayMath = true;
2501                                 // runparams.inDeletedInset will be set by
2502                                 // latexInset later, but we need this info
2503                                 // before it is called. On the other hand, we
2504                                 // cannot set it here because it is a counter.
2505                                 deleted_display_math = isDeleted(i);
2506                         }
2507                         if (bparams.output_changes && deleted_display_math
2508                             && runningChange == change
2509                             && change.type == Change::DELETED
2510                             && !os.afterParbreak()) {
2511                                 // A display math in the same paragraph follows.
2512                                 // We have to close and then reopen \lyxdeleted,
2513                                 // otherwise the math will be shifted up.
2514                                 OutputParams rp = runparams;
2515                                 if (open_font) {
2516                                         bool needPar = false;
2517                                         column += running_font.latexWriteEndChanges(
2518                                                 os, bparams, rp, basefont,
2519                                                 basefont, needPar);
2520                                         open_font = false;
2521                                 }
2522                                 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2523                                                           : getLayoutFont(bparams, real_outerfont);
2524                                 running_font = basefont;
2525                                 column += Changes::latexMarkChange(os, bparams,
2526                                         Change(Change::INSERTED), change, rp);
2527                         }
2528                 }
2529
2530                 if (bparams.output_changes && runningChange != change) {
2531                         if (!alien_script.empty()) {
2532                                 column += 1;
2533                                 os << "}";
2534                                 alien_script.clear();
2535                         }
2536                         if (open_font) {
2537                                 bool needPar = false;
2538                                 column += running_font.latexWriteEndChanges(
2539                                                 os, bparams, runparams,
2540                                                 basefont, basefont, needPar);
2541                                 open_font = false;
2542                         }
2543                         basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2544                                                   : getLayoutFont(bparams, real_outerfont);
2545                         running_font = basefont;
2546                         column += Changes::latexMarkChange(os, bparams, runningChange,
2547                                                            change, runparams);
2548                         runningChange = change;
2549                 }
2550
2551                 // do not output text which is marked deleted
2552                 // if change tracking output is disabled
2553                 if (!bparams.output_changes && change.deleted()) {
2554                         continue;
2555                 }
2556
2557                 ++column;
2558
2559                 // Fully instantiated font
2560                 Font const current_font = getFont(bparams, i, outerfont);
2561                 // Previous font
2562                 Font const prev_font = (i > 0) ?
2563                                         getFont(bparams, i - 1, outerfont)
2564                                       : current_font;
2565
2566                 Font const last_font = running_font;
2567                 bool const in_ct_deletion = (bparams.output_changes
2568                                              && runningChange == change
2569                                              && change.type == Change::DELETED
2570                                              && !os.afterParbreak());
2571                 bool const multipar_inset =
2572                         (c == META_INSET && getInset(i) && getInset(i)->allowMultiPar());
2573
2574                 // Do we need to close the previous font?
2575                 if (open_font &&
2576                     ((current_font != running_font
2577                       || current_font.language() != running_font.language())
2578                      || (multipar_inset
2579                          && (current_font == prev_font
2580                              || current_font.language() == prev_font.language()))))
2581                 {
2582                         // ensure there is no open script-wrapper
2583                         if (!alien_script.empty()) {
2584                                 column += 1;
2585                                 os << "}";
2586                                 alien_script.clear();
2587                         }
2588                         bool needPar = false;
2589                         if (in_ct_deletion) {
2590                                 // We have to close and then reopen \lyxdeleted,
2591                                 // as strikeout needs to be on lowest level.
2592                                 os << '}';
2593                                 column += 1;
2594                         }
2595                         column += running_font.latexWriteEndChanges(
2596                                     os, bparams, runparams, basefont,
2597                                     (i == body_pos-1) ? basefont : current_font,
2598                                     needPar);
2599                         if (in_ct_deletion) {
2600                                 // We have to close and then reopen \lyxdeleted,
2601                                 // as strikeout needs to be on lowest level.
2602                                 OutputParams rp = runparams;
2603                                 column += Changes::latexMarkChange(os, bparams,
2604                                         Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2605                         }
2606                         running_font = basefont;
2607                         open_font = false;
2608                 }
2609
2610                 // if necessary, close language environment before opening CJK
2611                 string const running_lang = running_font.language()->babel();
2612                 string const lang_end_command = lyxrc.language_command_end;
2613                 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2614                         && !running_lang.empty()
2615                         && running_lang == openLanguageName()
2616                         && current_font.language()->encoding()->package() == Encoding::CJK) {
2617                         string end_tag = subst(lang_end_command, "$$lang", running_lang);
2618                         os << from_ascii(end_tag);
2619                         column += end_tag.length();
2620                         popLanguageName();
2621                 }
2622
2623                 // Switch file encoding if necessary (and allowed)
2624                 if (!runparams.pass_thru && !style.pass_thru &&
2625                     runparams.encoding->package() != Encoding::none &&
2626                     current_font.language()->encoding()->package() != Encoding::none) {
2627                         pair<bool, int> const enc_switch =
2628                                 switchEncoding(os.os(), bparams, runparams,
2629                                         *(current_font.language()->encoding()));
2630                         if (enc_switch.first) {
2631                                 column += enc_switch.second;
2632                                 runparams.encoding = current_font.language()->encoding();
2633                         }
2634                 }
2635
2636                 // A display math inset inside an ulem command will be output
2637                 // as a box of width \linewidth, so we have to either disable
2638                 // indentation if the inset starts a paragraph, or start a new
2639                 // line to accommodate such box. This has to be done before
2640                 // writing any font changing commands.
2641                 if (runparams.inDisplayMath && !deleted_display_math
2642                     && runparams.inulemcmd) {
2643                         if (os.afterParbreak())
2644                                 os << "\\noindent";
2645                         else
2646                                 os << "\\\\\n";
2647                 }
2648
2649                 // Do we need to change font?
2650                 if ((current_font != running_font ||
2651                      current_font.language() != running_font.language())
2652                     && i != body_pos - 1)
2653                 {
2654                         if (in_ct_deletion) {
2655                                 // We have to close and then reopen \lyxdeleted,
2656                                 // as strikeout needs to be on lowest level.
2657                                 bool needPar = false;
2658                                 OutputParams rp = runparams;
2659                                 column += running_font.latexWriteEndChanges(
2660                                         os, bparams, rp, basefont,
2661                                         basefont, needPar);
2662                                 os << '}';
2663                                 column += 1;
2664                         }
2665                         otexstringstream ots;
2666                         if (!multipar_inset) {
2667                                 InsetText const * textinset = inInset().asInsetText();
2668                                 bool const cprotect = textinset
2669                                         ? textinset->hasCProtectContent(runparams.moving_arg)
2670                                           && !textinset->text().isMainText()
2671                                         : false;
2672                                 column += current_font.latexWriteStartChanges(ots, bparams,
2673                                                                               runparams, basefont, last_font, false,
2674                                                                               cprotect);
2675                         }
2676                         // Check again for display math in ulem commands as a
2677                         // font change may also occur just before a math inset.
2678                         if (runparams.inDisplayMath && !deleted_display_math
2679                             && runparams.inulemcmd) {
2680                                 if (os.afterParbreak())
2681                                         os << "\\noindent";
2682                                 else
2683                                         os << "\\\\\n";
2684                         }
2685                         running_font = current_font;
2686                         open_font = true;
2687                         docstring fontchange = ots.str();
2688                         os << fontchange;
2689                         // check whether the fontchange ends with a \\textcolor
2690                         // modifier and the text starts with a space. If so we
2691                         // need to add } in order to prevent \\textcolor from gobbling
2692                         // the space (bug 4473).
2693                         docstring const last_modifier = rsplit(fontchange, '\\');
2694                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2695                                 os << from_ascii("{}");
2696                         else if (ots.terminateCommand())
2697                                 os << termcmd;
2698                         if (in_ct_deletion) {
2699                                 // We have to close and then reopen \lyxdeleted,
2700                                 // as strikeout needs to be on lowest level.
2701                                 OutputParams rp = runparams;
2702                                 column += Changes::latexMarkChange(os, bparams,
2703                                         Change(Change::UNCHANGED), change, rp);
2704                         }
2705                 }
2706
2707                 // FIXME: think about end_pos implementation...
2708                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2709                         // FIXME: integrate this case in latexSpecialChar
2710                         // Do not print the separation of the optional argument
2711                         // if style.pass_thru is false. This works because
2712                         // latexSpecialChar ignores spaces if
2713                         // style.pass_thru is false.
2714                         if (i != body_pos - 1) {
2715                                 if (d->simpleTeXBlanks(bparams, runparams, os,
2716                                                 i, column, current_font, style)) {
2717                                         // A surrogate pair was output. We
2718                                         // must not call latexSpecialChar
2719                                         // in this iteration, since it would output
2720                                         // the combining character again.
2721                                         ++i;
2722                                         continue;
2723                                 }
2724                         }
2725                 }
2726
2727                 OutputParams rp = runparams;
2728                 rp.free_spacing = style.free_spacing;
2729                 rp.local_font = &current_font;
2730                 rp.intitle = style.intitle;
2731
2732                 // Two major modes:  LaTeX or plain
2733                 // Handle here those cases common to both modes
2734                 // and then split to handle the two modes separately.
2735                 if (c == META_INSET) {
2736                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2737                                 // Greyedout notes and, in general, all insets
2738                                 // with InsetLayout::isDisplay() == false,
2739                                 // are typeset inline with the text. So, we
2740                                 // can add a \par to the last paragraph of
2741                                 // such insets only if nothing else follows.
2742                                 bool incremented = false;
2743                                 Inset const * inset = getInset(i);
2744                                 InsetText const * textinset = inset
2745                                                         ? inset->asInsetText()
2746                                                         : nullptr;
2747                                 if (i + 1 == size() && textinset
2748                                     && !inset->getLayout().isDisplay()) {
2749                                         ParagraphList const & pars =
2750                                                 textinset->text().paragraphs();
2751                                         pit_type const pit = pars.size() - 1;
2752                                         Font const lastfont =
2753                                                 pit < 0 || pars[pit].empty()
2754                                                 ? pars[pit].getLayoutFont(
2755                                                                 bparams,
2756                                                                 real_outerfont)
2757                                                 : pars[pit].getFont(bparams,
2758                                                         pars[pit].size() - 1,
2759                                                         real_outerfont);
2760                                         if (lastfont.fontInfo().size() !=
2761                                             basefont.fontInfo().size()) {
2762                                                 ++parInline;
2763                                                 incremented = true;
2764                                         }
2765                                 }
2766                                 // We need to restore these after insets with
2767                                 // allowMultiPar() true
2768                                 Font const save_running_font = running_font;
2769                                 Font const save_basefont = basefont;
2770                                 d->latexInset(bparams, os, rp, running_font,
2771                                                 basefont, real_outerfont, open_font,
2772                                                 runningChange, style, i, column);
2773                                 if (multipar_inset) {
2774                                         running_font = save_running_font;
2775                                         basefont = save_basefont;
2776                                 }
2777                                 if (incremented)
2778                                         --parInline;
2779
2780                                 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2781                                     || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2782                                         // Close \lyx*deleted and force its
2783                                         // reopening (if needed)
2784                                         os << '}';
2785                                         column++;
2786                                         runningChange = Change(Change::UNCHANGED);
2787                                         runparams.ctObject = OutputParams::CT_NORMAL;
2788                                 }
2789                         }
2790                 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2791                         if (!bparams.useNonTeXFonts)
2792                           script = Encodings::isKnownScriptChar(c);
2793                         if (script != alien_script) {
2794                                 if (!alien_script.empty()) {
2795                                         os << "}";
2796                                         alien_script.clear();
2797                                 }
2798                                 string fontenc = running_font.language()->fontenc(bparams);
2799                                 if (!script.empty()
2800                                         && !Encodings::fontencSupportsScript(fontenc, script)) {
2801                                         column += script.length() + 2;
2802                                         os << "\\" << script << "{";
2803                                         alien_script = script;
2804                                 }
2805                         }
2806                         try {
2807                                 d->latexSpecialChar(os, bparams, rp, running_font,
2808                                                                         alien_script, style, i, end_pos, column);
2809                         } catch (EncodingException & e) {
2810                                 if (runparams.dryrun) {
2811                                         os << "<" << _("LyX Warning: ")
2812                                            << _("uncodable character") << " '";
2813                                         os.put(c);
2814                                         os << "'>";
2815                                 } else {
2816                                         // add location information and throw again.
2817                                         e.par_id = id();
2818                                         e.pos = i;
2819                                         throw(e);
2820                                 }
2821                         }
2822                 }
2823
2824                 // Set the encoding to that returned from latexSpecialChar (see
2825                 // comment for encoding member in OutputParams.h)
2826                 runparams.encoding = rp.encoding;
2827
2828                 // Also carry on the info on a closed ulem command for insets
2829                 // such as Note that do not produce any output, so that no
2830                 // command is ever executed but its opening was recorded.
2831                 runparams.inulemcmd = rp.inulemcmd;
2832
2833                 // These need to be passed upstream as well
2834                 runparams.need_maketitle = rp.need_maketitle;
2835                 runparams.have_maketitle = rp.have_maketitle;
2836
2837                 // And finally, pass the post_macros upstream
2838                 runparams.post_macro = rp.post_macro;
2839         }
2840
2841         // Close wrapper for alien script
2842         if (!alien_script.empty()) {
2843                 os << "}";
2844                 alien_script.clear();
2845         }
2846
2847         // If we have an open font definition, we have to close it
2848         if (open_font) {
2849                 // Make sure that \\par is done with the font of the last
2850                 // character if this has another size as the default.
2851                 // This is necessary because LaTeX (and LyX on the screen)
2852                 // calculates the space between the baselines according
2853                 // to this font. (Matthias)
2854                 //
2855                 // We must not change the font for the last paragraph
2856                 // of non-multipar insets, tabular cells or commands,
2857                 // since this produces unwanted whitespace.
2858
2859                 Font const font = empty()
2860                         ? getLayoutFont(bparams, real_outerfont)
2861                         : getFont(bparams, size() - 1, real_outerfont);
2862
2863                 InsetText const * textinset = inInset().asInsetText();
2864
2865                 bool const maintext = textinset
2866                         ? textinset->text().isMainText()
2867                         : false;
2868
2869                 size_t const numpars = textinset
2870                         ? textinset->text().paragraphs().size()
2871                         : 0;
2872
2873                 bool needPar = false;
2874
2875                 if (style.resfont.size() != font.fontInfo().size()
2876                     && (!runparams.isLastPar || maintext
2877                         || (numpars > 1 && d->ownerCode() != CELL_CODE
2878                             && (inInset().getLayout().isDisplay()
2879                                 || parInline)))
2880                     && !style.isCommand()) {
2881                         needPar = true;
2882                 }
2883 #ifdef FIXED_LANGUAGE_END_DETECTION
2884                 if (next_) {
2885                         running_font.latexWriteEndChanges(os, bparams,
2886                                         runparams, basefont,
2887                                         next_->getFont(bparams, 0, outerfont),
2888                                                        needPar);
2889                 } else {
2890                         running_font.latexWriteEndChanges(os, bparams,
2891                                         runparams, basefont, basefont, needPar);
2892                 }
2893 #else
2894 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2895 //FIXME: there as we start another \selectlanguage with the next paragraph if
2896 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2897                 running_font.latexWriteEndChanges(os, bparams, runparams,
2898                                 basefont, basefont, needPar);
2899 #endif
2900                 if (needPar) {
2901                         // The \par could not be inserted at the same nesting
2902                         // level of the font size change, so do it now.
2903                         os << "{\\" << font.latexSize() << "\\par}";
2904                 }
2905         }
2906
2907         column += Changes::latexMarkChange(os, bparams, runningChange,
2908                                            Change(Change::UNCHANGED), runparams);
2909
2910         // Needed if there is an optional argument but no contents.
2911         if (body_pos > 0 && body_pos == size()) {
2912                 os << "}]~";
2913         }
2914
2915         if (!style.rightdelim().empty()) {
2916                 os << style.rightdelim();
2917                 column += style.rightdelim().size();
2918         }
2919
2920         if (allowcust && d->endTeXParParams(bparams, os, runparams)
2921             && runparams.encoding != prev_encoding) {
2922                 runparams.encoding = prev_encoding;
2923                 os << setEncoding(prev_encoding->iconvName());
2924         }
2925
2926         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2927 }
2928
2929
2930 bool Paragraph::emptyTag() const
2931 {
2932         for (pos_type i = 0; i < size(); ++i) {
2933                 if (Inset const * inset = getInset(i)) {
2934                         InsetCode lyx_code = inset->lyxCode();
2935                         // FIXME testing like that is wrong. What is
2936                         // the intent?
2937                         if (lyx_code != TOC_CODE &&
2938                             lyx_code != INCLUDE_CODE &&
2939                             lyx_code != GRAPHICS_CODE &&
2940                             lyx_code != ERT_CODE &&
2941                             lyx_code != LISTINGS_CODE &&
2942                             lyx_code != FLOAT_CODE &&
2943                             lyx_code != TABULAR_CODE) {
2944                                 return false;
2945                         }
2946                 } else {
2947                         char_type c = d->text_[i];
2948                         if (c != ' ' && c != '\t')
2949                                 return false;
2950                 }
2951         }
2952         return true;
2953 }
2954
2955
2956 string Paragraph::getID(Buffer const &, OutputParams const &)
2957         const
2958 {
2959         for (pos_type i = 0; i < size(); ++i) {
2960                 if (Inset const * inset = getInset(i)) {
2961                         InsetCode lyx_code = inset->lyxCode();
2962                         if (lyx_code == LABEL_CODE) {
2963                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2964                                 docstring const & id = il->getParam("name");
2965                                 return "id='" + to_utf8(xml::cleanID(id)) + "'";
2966                         }
2967                 }
2968         }
2969         return string();
2970 }
2971
2972
2973 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
2974 {
2975         pos_type i;
2976         for (i = 0; i < size(); ++i) {
2977                 if (Inset const * inset = getInset(i)) {
2978                         inset->docbook(xs, runparams);
2979                 } else {
2980                         char_type c = d->text_[i];
2981                         if (c == ' ')
2982                                 break;
2983                         xs << c;
2984                 }
2985         }
2986         return i;
2987 }
2988
2989
2990 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
2991         const
2992 {
2993         pos_type i;
2994         for (i = 0; i < size(); ++i) {
2995                 if (Inset const * inset = getInset(i)) {
2996                         inset->xhtml(xs, runparams);
2997                 } else {
2998                         char_type c = d->text_[i];
2999                         if (c == ' ')
3000                                 break;
3001                         xs << c;
3002                 }
3003         }
3004         return i;
3005 }
3006
3007
3008 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3009 {
3010         Font font_old;
3011         pos_type size = text_.size();
3012         for (pos_type i = initial; i < size; ++i) {
3013                 Font font = owner_->getFont(buf.params(), i, outerfont);
3014                 if (text_[i] == META_INSET)
3015                         return false;
3016                 if (i != initial && font != font_old)
3017                         return false;
3018                 font_old = font;
3019         }
3020
3021         return true;
3022 }
3023
3024
3025 namespace {
3026
3027 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3028                   vector<xml::EndFontTag> & tagsToClose,
3029                   bool & flag, FontState curstate, xml::FontTypes type)
3030 {
3031         if (curstate == FONT_ON) {
3032                 tagsToOpen.push_back(docbookStartFontTag(type));
3033                 flag = true;
3034         } else if (flag) {
3035                 tagsToClose.push_back(docbookEndFontTag(type));
3036                 flag = false;
3037         }
3038 }
3039
3040 class OptionalFontType {
3041 public:
3042         xml::FontTypes ft;
3043         bool has_value;
3044
3045         OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3046         OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3047 };
3048
3049 OptionalFontType fontShapeToXml(FontShape fs)
3050 {
3051         switch (fs) {
3052         case ITALIC_SHAPE:
3053                 return {xml::FT_ITALIC};
3054         case SLANTED_SHAPE:
3055                 return {xml::FT_SLANTED};
3056         case SMALLCAPS_SHAPE:
3057                 return {xml::FT_SMALLCAPS};
3058         case UP_SHAPE:
3059         case INHERIT_SHAPE:
3060                 return {};
3061         default:
3062                 // the other tags are for internal use
3063                 LATTEST(false);
3064                 return {};
3065         }
3066 }
3067
3068 OptionalFontType fontFamilyToXml(FontFamily fm)
3069 {
3070         switch (fm) {
3071         case ROMAN_FAMILY:
3072                 return {xml::FT_ROMAN};
3073         case SANS_FAMILY:
3074                 return {xml::FT_SANS};
3075         case TYPEWRITER_FAMILY:
3076                 return {xml::FT_TYPE};
3077         case INHERIT_FAMILY:
3078                 return {};
3079         default:
3080                 // the other tags are for internal use
3081                 LATTEST(false);
3082                 return {};
3083         }
3084 }
3085
3086 OptionalFontType fontSizeToXml(FontSize fs)
3087 {
3088         switch (fs) {
3089         case TINY_SIZE:
3090                 return {xml::FT_SIZE_TINY};
3091         case SCRIPT_SIZE:
3092                 return {xml::FT_SIZE_SCRIPT};
3093         case FOOTNOTE_SIZE:
3094                 return {xml::FT_SIZE_FOOTNOTE};
3095         case SMALL_SIZE:
3096                 return {xml::FT_SIZE_SMALL};
3097         case LARGE_SIZE:
3098                 return {xml::FT_SIZE_LARGE};
3099         case LARGER_SIZE:
3100                 return {xml::FT_SIZE_LARGER};
3101         case LARGEST_SIZE:
3102                 return {xml::FT_SIZE_LARGEST};
3103         case HUGE_SIZE:
3104                 return {xml::FT_SIZE_HUGE};
3105         case HUGER_SIZE:
3106                 return {xml::FT_SIZE_HUGER};
3107         case INCREASE_SIZE:
3108                 return {xml::FT_SIZE_INCREASE};
3109         case DECREASE_SIZE:
3110                 return {xml::FT_SIZE_DECREASE};
3111         case INHERIT_SIZE:
3112         case NORMAL_SIZE:
3113                 return {};
3114         default:
3115                 // the other tags are for internal use
3116                 LATTEST(false);
3117                 return {};
3118         }
3119 }
3120
3121 struct DocBookFontState
3122 {
3123         FontShape  curr_fs   = INHERIT_SHAPE;
3124         FontFamily curr_fam  = INHERIT_FAMILY;
3125         FontSize   curr_size = INHERIT_SIZE;
3126
3127         // track whether we have opened these tags
3128         bool emph_flag = false;
3129         bool bold_flag = false;
3130         bool noun_flag = false;
3131         bool ubar_flag = false;
3132         bool dbar_flag = false;
3133         bool sout_flag = false;
3134         bool xout_flag = false;
3135         bool wave_flag = false;
3136         // shape tags
3137         bool shap_flag = false;
3138         // family tags
3139         bool faml_flag = false;
3140         // size tags
3141         bool size_flag = false;
3142 };
3143
3144 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3145                                                                                            Font const & font,
3146                                                                                            std::string const & default_family,
3147                                                                                            DocBookFontState & fs)
3148 {
3149         vector<xml::FontTag> tagsToOpen;
3150         vector<xml::EndFontTag> tagsToClose;
3151
3152         // emphasis
3153         FontState curstate = font.fontInfo().emph();
3154         if (font_old.emph() != curstate)
3155                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3156
3157         // noun
3158         curstate = font.fontInfo().noun();
3159         if (font_old.noun() != curstate)
3160                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3161
3162         // underbar
3163         curstate = font.fontInfo().underbar();
3164         if (font_old.underbar() != curstate)
3165                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3166
3167         // strikeout
3168         curstate = font.fontInfo().strikeout();
3169         if (font_old.strikeout() != curstate)
3170                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3171
3172         // xout
3173         curstate = font.fontInfo().xout();
3174         if (font_old.xout() != curstate)
3175                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3176
3177         // double underbar
3178         curstate = font.fontInfo().uuline();
3179         if (font_old.uuline() != curstate)
3180                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3181
3182         // wavy line
3183         curstate = font.fontInfo().uwave();
3184         if (font_old.uwave() != curstate)
3185                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3186
3187         // bold
3188         // a little hackish, but allows us to reuse what we have.
3189         curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3190         if (font_old.series() != font.fontInfo().series())
3191                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3192
3193         // Font shape
3194         fs.curr_fs = font.fontInfo().shape();
3195         FontShape old_fs = font_old.shape();
3196         if (old_fs != fs.curr_fs) {
3197                 if (fs.shap_flag) {
3198                         OptionalFontType tag = fontShapeToXml(old_fs);
3199                         if (tag.has_value)
3200                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3201                         fs.shap_flag = false;
3202                 }
3203
3204                 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3205                 if (tag.has_value)
3206                         tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3207         }
3208
3209         // Font family
3210         fs.curr_fam = font.fontInfo().family();
3211         FontFamily old_fam = font_old.family();
3212         if (old_fam != fs.curr_fam) {
3213                 if (fs.faml_flag) {
3214                         OptionalFontType tag = fontFamilyToXml(old_fam);
3215                         if (tag.has_value)
3216                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3217                         fs.faml_flag = false;
3218                 }
3219                 switch (fs.curr_fam) {
3220                         case ROMAN_FAMILY:
3221                                 // we will treat a "default" font family as roman, since we have
3222                                 // no other idea what to do.
3223                                 if (default_family != "rmdefault" && default_family != "default") {
3224                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3225                                         fs.faml_flag = true;
3226                                 }
3227                                 break;
3228                         case SANS_FAMILY:
3229                                 if (default_family != "sfdefault") {
3230                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3231                                         fs.faml_flag = true;
3232                                 }
3233                                 break;
3234                         case TYPEWRITER_FAMILY:
3235                                 if (default_family != "ttdefault") {
3236                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3237                                         fs.faml_flag = true;
3238                                 }
3239                                 break;
3240                         case INHERIT_FAMILY:
3241                                 break;
3242                         default:
3243                                 // the other tags are for internal use
3244                                 LATTEST(false);
3245                                 break;
3246                 }
3247         }
3248
3249         // Font size
3250         fs.curr_size = font.fontInfo().size();
3251         FontSize old_size = font_old.size();
3252         if (old_size != fs.curr_size) {
3253                 if (fs.size_flag) {
3254                         OptionalFontType tag = fontSizeToXml(old_size);
3255                         if (tag.has_value)
3256                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3257                         fs.size_flag = false;
3258                 }
3259
3260                 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3261                 if (tag.has_value) {
3262                         tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3263                         fs.size_flag = true;
3264                 }
3265         }
3266
3267         return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3268 }
3269
3270 } // anonymous namespace
3271
3272
3273 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3274                                     XMLStream & xs,
3275                                     OutputParams const & runparams,
3276                                     Font const & outerfont,
3277                                     bool start_paragraph, bool close_paragraph,
3278                                     pos_type initial) const
3279 {
3280         // track whether we have opened these tags
3281         DocBookFontState fs;
3282
3283         if (start_paragraph)
3284                 xs.startDivision(allowEmpty());
3285
3286         Layout const & style = *d->layout_;
3287         FontInfo font_old =
3288                         style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3289
3290         string const default_family =
3291                         buf.masterBuffer()->params().fonts_default_family;
3292
3293         vector<xml::FontTag> tagsToOpen;
3294         vector<xml::EndFontTag> tagsToClose;
3295
3296         // parsing main loop
3297         for (pos_type i = initial; i < size(); ++i) {
3298                 // let's not show deleted material in the output
3299                 if (isDeleted(i))
3300                         continue;
3301
3302                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3303
3304                 // Determine which tags should be opened or closed.
3305                 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3306
3307                 // FIXME XHTML
3308                 // Other such tags? What about the other text ranges?
3309
3310                 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3311                 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3312                 for (; cit != cen; ++cit)
3313                         xs << *cit;
3314
3315                 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3316                 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3317                 for (; sit != sen; ++sit)
3318                         xs << *sit;
3319
3320                 tagsToClose.clear();
3321                 tagsToOpen.clear();
3322
3323                 if (Inset const * inset = getInset(i)) {
3324                         if (!runparams.for_toc || inset->isInToc()) {
3325                                 OutputParams np = runparams;
3326                                 np.local_font = &font;
3327                                 // If the paragraph has size 1, then we are in the "special
3328                                 // case" where we do not output the containing paragraph info.
3329                                 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3330                                 // of that brittle logic is passed to this function through open_par.
3331                                 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3332                                         np.docbook_in_par = true;
3333                                 inset->docbook(xs, np);
3334                         }
3335                 } else {
3336                         char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3337                         xs << c;
3338                 }
3339                 font_old = font.fontInfo();
3340         }
3341
3342         // FIXME, this code is just imported from XHTML
3343         // I'm worried about what happens if a branch, say, is itself
3344         // wrapped in some font stuff. I think that will not work.
3345         xs.closeFontTags();
3346         if (runparams.docbook_in_listing)
3347                 xs << xml::CR();
3348         if (close_paragraph)
3349                 xs.endDivision();
3350 }
3351
3352
3353 namespace {
3354
3355 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3356                   vector<xml::EndFontTag> & tagsToClose,
3357                   bool & flag, FontState curstate, xml::FontTypes type)
3358 {
3359         if (curstate == FONT_ON) {
3360                 tagsToOpen.push_back(xhtmlStartFontTag(type));
3361                 flag = true;
3362         } else if (flag) {
3363                 tagsToClose.push_back(xhtmlEndFontTag(type));
3364                 flag = false;
3365         }
3366 }
3367
3368 } // anonymous namespace
3369
3370
3371 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3372                                     XMLStream & xs,
3373                                     OutputParams const & runparams,
3374                                     Font const & outerfont,
3375                                     bool start_paragraph, bool close_paragraph,
3376                                     pos_type initial) const
3377 {
3378         docstring retval;
3379
3380         // track whether we have opened these tags
3381         bool emph_flag = false;
3382         bool bold_flag = false;
3383         bool noun_flag = false;
3384         bool ubar_flag = false;
3385         bool dbar_flag = false;
3386         bool sout_flag = false;
3387         bool xout_flag = false;
3388         bool wave_flag = false;
3389         // shape tags
3390         bool shap_flag = false;
3391         // family tags
3392         bool faml_flag = false;
3393         // size tags
3394         bool size_flag = false;
3395
3396         Layout const & style = *d->layout_;
3397
3398         if (start_paragraph)
3399                 xs.startDivision(allowEmpty());
3400
3401         FontInfo font_old =
3402                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3403
3404         FontShape  curr_fs   = INHERIT_SHAPE;
3405         FontFamily curr_fam  = INHERIT_FAMILY;
3406         FontSize   curr_size = INHERIT_SIZE;
3407
3408         string const default_family =
3409                 buf.masterBuffer()->params().fonts_default_family;
3410
3411         vector<xml::FontTag> tagsToOpen;
3412         vector<xml::EndFontTag> tagsToClose;
3413
3414         // parsing main loop
3415         for (pos_type i = initial; i < size(); ++i) {
3416                 // let's not show deleted material in the output
3417                 if (isDeleted(i))
3418                         continue;
3419
3420                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3421
3422                 // emphasis
3423                 FontState curstate = font.fontInfo().emph();
3424                 if (font_old.emph() != curstate)
3425                         doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3426
3427                 // noun
3428                 curstate = font.fontInfo().noun();
3429                 if (font_old.noun() != curstate)
3430                         doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3431
3432                 // underbar
3433                 curstate = font.fontInfo().underbar();
3434                 if (font_old.underbar() != curstate)
3435                         doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3436
3437                 // strikeout
3438                 curstate = font.fontInfo().strikeout();
3439                 if (font_old.strikeout() != curstate)
3440                         doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3441
3442                 // xout
3443                 curstate = font.fontInfo().xout();
3444                 if (font_old.xout() != curstate)
3445                         doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3446
3447                 // double underbar
3448                 curstate = font.fontInfo().uuline();
3449                 if (font_old.uuline() != curstate)
3450                         doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3451
3452                 // wavy line
3453                 curstate = font.fontInfo().uwave();
3454                 if (font_old.uwave() != curstate)
3455                         doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3456
3457                 // bold
3458                 // a little hackish, but allows us to reuse what we have.
3459                 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3460                 if (font_old.series() != font.fontInfo().series())
3461                         doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3462
3463                 // Font shape
3464                 curr_fs = font.fontInfo().shape();
3465                 FontShape old_fs = font_old.shape();
3466                 if (old_fs != curr_fs) {
3467                         if (shap_flag) {
3468                                 switch (old_fs) {
3469                                 case ITALIC_SHAPE:
3470                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3471                                         break;
3472                                 case SLANTED_SHAPE:
3473                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3474                                         break;
3475                                 case SMALLCAPS_SHAPE:
3476                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3477                                         break;
3478                                 case UP_SHAPE:
3479                                 case INHERIT_SHAPE:
3480                                         break;
3481                                 default:
3482                                         // the other tags are for internal use
3483                                         LATTEST(false);
3484                                         break;
3485                                 }
3486                                 shap_flag = false;
3487                         }
3488                         switch (curr_fs) {
3489                         case ITALIC_SHAPE:
3490                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3491                                 shap_flag = true;
3492                                 break;
3493                         case SLANTED_SHAPE:
3494                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3495                                 shap_flag = true;
3496                                 break;
3497                         case SMALLCAPS_SHAPE:
3498                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3499                                 shap_flag = true;
3500                                 break;
3501                         case UP_SHAPE:
3502                         case INHERIT_SHAPE:
3503                                 break;
3504                         default:
3505                                 // the other tags are for internal use
3506                                 LATTEST(false);
3507                                 break;
3508                         }
3509                 }
3510
3511                 // Font family
3512                 curr_fam = font.fontInfo().family();
3513                 FontFamily old_fam = font_old.family();
3514                 if (old_fam != curr_fam) {
3515                         if (faml_flag) {
3516                                 switch (old_fam) {
3517                                 case ROMAN_FAMILY:
3518                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3519                                         break;
3520                                 case SANS_FAMILY:
3521                                     tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3522                                     break;
3523                                 case TYPEWRITER_FAMILY:
3524                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3525                                         break;
3526                                 case INHERIT_FAMILY:
3527                                         break;
3528                                 default:
3529                                         // the other tags are for internal use
3530                                         LATTEST(false);
3531                                         break;
3532                                 }
3533                                 faml_flag = false;
3534                         }
3535                         switch (curr_fam) {
3536                         case ROMAN_FAMILY:
3537                                 // we will treat a "default" font family as roman, since we have
3538                                 // no other idea what to do.
3539                                 if (default_family != "rmdefault" && default_family != "default") {
3540                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3541                                         faml_flag = true;
3542                                 }
3543                                 break;
3544                         case SANS_FAMILY:
3545                                 if (default_family != "sfdefault") {
3546                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3547                                         faml_flag = true;
3548                                 }
3549                                 break;
3550                         case TYPEWRITER_FAMILY:
3551                                 if (default_family != "ttdefault") {
3552                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3553                                         faml_flag = true;
3554                                 }
3555                                 break;
3556                         case INHERIT_FAMILY:
3557                                 break;
3558                         default:
3559                                 // the other tags are for internal use
3560                                 LATTEST(false);
3561                                 break;
3562                         }
3563                 }
3564
3565                 // Font size
3566                 curr_size = font.fontInfo().size();
3567                 FontSize old_size = font_old.size();
3568                 if (old_size != curr_size) {
3569                         if (size_flag) {
3570                                 switch (old_size) {
3571                                 case TINY_SIZE:
3572                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3573                                         break;
3574                                 case SCRIPT_SIZE:
3575                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3576                                         break;
3577                                 case FOOTNOTE_SIZE:
3578                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3579                                         break;
3580                                 case SMALL_SIZE:
3581                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3582                                         break;
3583                                 case LARGE_SIZE:
3584                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3585                                         break;
3586                                 case LARGER_SIZE:
3587                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3588                                         break;
3589                                 case LARGEST_SIZE:
3590                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3591                                         break;
3592                                 case HUGE_SIZE:
3593                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3594                                         break;
3595                                 case HUGER_SIZE:
3596                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3597                                         break;
3598                                 case INCREASE_SIZE:
3599                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3600                                         break;
3601                                 case DECREASE_SIZE:
3602                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3603                                         break;
3604                                 case INHERIT_SIZE:
3605                                 case NORMAL_SIZE:
3606                                         break;
3607                                 default:
3608                                         // the other tags are for internal use
3609                                         LATTEST(false);
3610                                         break;
3611                                 }
3612                                 size_flag = false;
3613                         }
3614                         switch (curr_size) {
3615                         case TINY_SIZE:
3616                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3617                                 size_flag = true;
3618                                 break;
3619                         case SCRIPT_SIZE:
3620                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3621                                 size_flag = true;
3622                                 break;
3623                         case FOOTNOTE_SIZE:
3624                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3625                                 size_flag = true;
3626                                 break;
3627                         case SMALL_SIZE:
3628                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3629                                 size_flag = true;
3630                                 break;
3631                         case LARGE_SIZE:
3632                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3633                                 size_flag = true;
3634                                 break;
3635                         case LARGER_SIZE:
3636                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3637                                 size_flag = true;
3638                                 break;
3639                         case LARGEST_SIZE:
3640                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3641                                 size_flag = true;
3642                                 break;
3643                         case HUGE_SIZE:
3644                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3645                                 size_flag = true;
3646                                 break;
3647                         case HUGER_SIZE:
3648                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3649                                 size_flag = true;
3650                                 break;
3651                         case INCREASE_SIZE:
3652                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3653                                 size_flag = true;
3654                                 break;
3655                         case DECREASE_SIZE:
3656                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3657                                 size_flag = true;
3658                                 break;
3659                         case INHERIT_SIZE:
3660                         case NORMAL_SIZE:
3661                                 break;
3662                         default:
3663                                 // the other tags are for internal use
3664                                 LATTEST(false);
3665                                 break;
3666                         }
3667                 }
3668
3669                 // FIXME XHTML
3670                 // Other such tags? What about the other text ranges?
3671
3672                 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3673                 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3674                 for (; cit != cen; ++cit)
3675                         xs << *cit;
3676
3677                 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3678                 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3679                 for (; sit != sen; ++sit)
3680                         xs << *sit;
3681
3682                 tagsToClose.clear();
3683                 tagsToOpen.clear();
3684
3685                 Inset const * inset = getInset(i);
3686                 if (inset) {
3687                         if (!runparams.for_toc || inset->isInToc()) {
3688                                 OutputParams np = runparams;
3689                                 np.local_font = &font;
3690                                 // If the paragraph has size 1, then we are in the "special
3691                                 // case" where we do not output the containing paragraph info
3692                                 if (!inset->getLayout().htmlisblock() && size() != 1)
3693                                         np.html_in_par = true;
3694                                 retval += inset->xhtml(xs, np);
3695                         }
3696                 } else {
3697                         char_type c = getUChar(buf.masterBuffer()->params(),
3698                                                runparams, i);
3699                         if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3700                                 xs << XMLStream::ESCAPE_NONE << "&nbsp;";
3701                         else
3702                                 xs << c;
3703                 }
3704                 font_old = font.fontInfo();
3705         }
3706
3707         // FIXME XHTML
3708         // I'm worried about what happens if a branch, say, is itself
3709         // wrapped in some font stuff. I think that will not work.
3710         xs.closeFontTags();
3711         if (close_paragraph)
3712                 xs.endDivision();
3713
3714         return retval;
3715 }
3716
3717
3718 bool Paragraph::isHfill(pos_type pos) const
3719 {
3720         Inset const * inset = getInset(pos);
3721         return inset && inset->isHfill();
3722 }
3723
3724
3725 bool Paragraph::isNewline(pos_type pos) const
3726 {
3727         // U+2028 LINE SEPARATOR
3728         // U+2029 PARAGRAPH SEPARATOR
3729         char_type const c = d->text_[pos];
3730         if (c == 0x2028 || c == 0x2029)
3731                 return true;
3732         Inset const * inset = getInset(pos);
3733         return inset && inset->lyxCode() == NEWLINE_CODE;
3734 }
3735
3736
3737 bool Paragraph::isEnvSeparator(pos_type pos) const
3738 {
3739         Inset const * inset = getInset(pos);
3740         return inset && inset->lyxCode() == SEPARATOR_CODE;
3741 }
3742
3743
3744 bool Paragraph::isLineSeparator(pos_type pos) const
3745 {
3746         char_type const c = d->text_[pos];
3747         if (isLineSeparatorChar(c))
3748                 return true;
3749         Inset const * inset = getInset(pos);
3750         return inset && inset->isLineSeparator();
3751 }
3752
3753
3754 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3755 {
3756         if (pos == size())
3757                 return true;
3758         if (ignore_deleted && isDeleted(pos))
3759                 return false;
3760         if (Inset const * inset = getInset(pos))
3761                 return !inset->isLetter();
3762         // if we have a hard hyphen (no en- or emdash) or apostrophe
3763         // we pass this to the spell checker
3764         // FIXME: this method is subject to change, visit
3765         // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3766         // to get an impression how complex this is.
3767         if (isHardHyphenOrApostrophe(pos))
3768                 return false;
3769         char_type const c = d->text_[pos];
3770         // We want to pass the escape chars to the spellchecker
3771         docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3772         return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3773 }
3774
3775
3776 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3777 {
3778         pos_type const psize = size();
3779         if (pos >= psize)
3780                 return false;
3781         char_type const c = d->text_[pos];
3782         if (c != '-' && c != '\'')
3783                 return false;
3784         int nextpos = pos + 1;
3785         int prevpos = pos > 0 ? pos - 1 : 0;
3786         if ((nextpos == psize || isSpace(nextpos))
3787                 && (pos == 0 || isSpace(prevpos)))
3788                 return false;
3789         return true;
3790 }
3791
3792
3793 bool Paragraph::needsCProtection(bool const fragile) const
3794 {
3795         // first check the layout of the paragraph, but only in insets
3796         InsetText const * textinset = inInset().asInsetText();
3797         bool const maintext = textinset
3798                 ? textinset->text().isMainText()
3799                 : false;
3800
3801         if (!maintext && layout().needcprotect) {
3802                 // Environments need cprotection regardless the content
3803                 if (layout().latextype == LATEX_ENVIRONMENT)
3804                         return true;
3805
3806                 // Commands need cprotection if they contain specific chars
3807                 int const nchars_escape = 9;
3808                 static char_type const chars_escape[nchars_escape] = {
3809                         '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3810
3811                 docstring const pars = asString();
3812                 for (int k = 0; k < nchars_escape; k++) {
3813                         if (contains(pars, chars_escape[k]))
3814                                 return true;
3815                 }
3816         }
3817
3818         // now check whether we have insets that need cprotection
3819         pos_type size = pos_type(d->text_.size());
3820         for (pos_type i = 0; i < size; ++i) {
3821                 if (!isInset(i))
3822                         continue;
3823                 Inset const * ins = getInset(i);
3824                 if (ins->needsCProtection(maintext, fragile))
3825                         return true;
3826                 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3827                         // Environments need cprotection regardless the content
3828                         return true;
3829                 // Now check math environments
3830                 InsetMath const * im = getInset(i)->asInsetMath();
3831                 if (!im || im->cell(0).empty())
3832                         continue;
3833                 switch(im->cell(0)[0]->lyxCode()) {
3834                 case MATH_AMSARRAY_CODE:
3835                 case MATH_SUBSTACK_CODE:
3836                 case MATH_ENV_CODE:
3837                 case MATH_XYMATRIX_CODE:
3838                         // these need cprotection
3839                         return true;
3840                 default:
3841                         break;
3842                 }
3843         }
3844
3845         return false;
3846 }
3847
3848
3849 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3850 {
3851         return d->speller_state_.getRange(pos);
3852 }
3853
3854
3855 bool Paragraph::isChar(pos_type pos) const
3856 {
3857         if (Inset const * inset = getInset(pos))
3858                 return inset->isChar();
3859         char_type const c = d->text_[pos];
3860         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3861 }
3862
3863
3864 bool Paragraph::isSpace(pos_type pos) const
3865 {
3866         if (Inset const * inset = getInset(pos))
3867                 return inset->isSpace();
3868         char_type const c = d->text_[pos];
3869         return lyx::isSpace(c);
3870 }
3871
3872
3873 Language const *
3874 Paragraph::getParLanguage(BufferParams const & bparams) const
3875 {
3876         if (!empty())
3877                 return getFirstFontSettings(bparams).language();
3878         // FIXME: we should check the prev par as well (Lgb)
3879         return bparams.language;
3880 }
3881
3882
3883 bool Paragraph::isRTL(BufferParams const & bparams) const
3884 {
3885         return getParLanguage(bparams)->rightToLeft()
3886                 && !inInset().getLayout().forceLTR();
3887 }
3888
3889
3890 void Paragraph::changeLanguage(BufferParams const & bparams,
3891                                Language const * from, Language const * to)
3892 {
3893         // change language including dummy font change at the end
3894         for (pos_type i = 0; i <= size(); ++i) {
3895                 Font font = getFontSettings(bparams, i);
3896                 if (font.language() == from) {
3897                         font.setLanguage(to);
3898                         setFont(i, font);
3899                         d->requestSpellCheck(i);
3900                 }
3901         }
3902 }
3903
3904
3905 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3906 {
3907         Language const * doc_language = bparams.language;
3908         for (auto const & f : d->fontlist_)
3909                 if (f.font().language() != ignore_language &&
3910                     f.font().language() != latex_language &&
3911                     f.font().language() != doc_language)
3912                         return true;
3913         return false;
3914 }
3915
3916
3917 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3918 {
3919         for (auto const & f : d->fontlist_) {
3920                 Language const * lang = f.font().language();
3921                 if (lang != ignore_language &&
3922                     lang != latex_language)
3923                         langs.insert(lang);
3924         }
3925 }
3926
3927
3928 docstring Paragraph::asString(int options) const
3929 {
3930         return asString(0, size(), options);
3931 }
3932
3933
3934 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3935 {
3936         odocstringstream os;
3937
3938         if (beg == 0
3939             && options & AS_STR_LABEL
3940             && !d->params_.labelString().empty())
3941                 os << d->params_.labelString() << ' ';
3942
3943         for (pos_type i = beg; i < end; ++i) {
3944                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3945                         continue;
3946                 char_type const c = d->text_[i];
3947                 if (isPrintable(c) || c == '\t'
3948                     || (c == '\n' && (options & AS_STR_NEWLINES)))
3949                         os.put(c);
3950                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3951                         if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3952                                 LASSERT(runparams != nullptr, return docstring());
3953                                 getInset(i)->plaintext(os, *runparams);
3954                         } else {
3955                                 getInset(i)->toString(os);
3956                         }
3957                 }
3958         }
3959
3960         return os.str();
3961 }
3962
3963
3964 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3965                             bool const shorten, bool const label) const
3966 {
3967         size_t tmplen = shorten ? maxlen + 1 : maxlen;
3968         if (label && !labelString().empty())
3969                 os += labelString() + ' ';
3970         if (!layout().isTocCaption())
3971                 return;
3972         for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3973                 if (isDeleted(i))
3974                         continue;
3975                 char_type const c = d->text_[i];
3976                 if (isPrintable(c))
3977                         os += c;
3978                 else if (c == META_INSET)
3979                         getInset(i)->forOutliner(os, tmplen, false);
3980         }
3981         if (shorten)
3982                 Text::shortenForOutliner(os, maxlen);
3983 }
3984
3985
3986 void Paragraph::setInsetOwner(Inset const * inset)
3987 {
3988         d->inset_owner_ = inset;
3989 }
3990
3991
3992 int Paragraph::id() const
3993 {
3994         return d->id_;
3995 }
3996
3997
3998 void Paragraph::setId(int id)
3999 {
4000         d->id_ = id;
4001 }
4002
4003
4004 Layout const & Paragraph::layout() const
4005 {
4006         return *d->layout_;
4007 }
4008
4009
4010 void Paragraph::setLayout(Layout const & layout)
4011 {
4012         d->layout_ = &layout;
4013 }
4014
4015
4016 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4017 {
4018         setLayout(tc.defaultLayout());
4019 }
4020
4021
4022 void Paragraph::setPlainLayout(DocumentClass const & tc)
4023 {
4024         setLayout(tc.plainLayout());
4025 }
4026
4027
4028 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4029 {
4030         if (usePlainLayout())
4031                 setPlainLayout(tclass);
4032         else
4033                 setDefaultLayout(tclass);
4034 }
4035
4036
4037 Inset const & Paragraph::inInset() const
4038 {
4039         LBUFERR(d->inset_owner_);
4040         return *d->inset_owner_;
4041 }
4042
4043
4044 ParagraphParameters & Paragraph::params()
4045 {
4046         return d->params_;
4047 }
4048
4049
4050 ParagraphParameters const & Paragraph::params() const
4051 {
4052         return d->params_;
4053 }
4054
4055
4056 bool Paragraph::isFreeSpacing() const
4057 {
4058         if (d->layout_->free_spacing)
4059                 return true;
4060         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4061 }
4062
4063
4064 bool Paragraph::allowEmpty() const
4065 {
4066         if (d->layout_->keepempty)
4067                 return true;
4068         return d->inset_owner_ && d->inset_owner_->allowEmpty();
4069 }
4070
4071
4072 bool Paragraph::brokenBiblio() const
4073 {
4074         // There is a problem if there is no bibitem at position 0 in
4075         // paragraphs that need one, if there is another bibitem in the
4076         // paragraph or if this paragraph is not supposed to have
4077         // a bibitem inset at all.
4078         return ((d->layout_->labeltype == LABEL_BIBLIO
4079                 && (d->insetlist_.find(BIBITEM_CODE) != 0
4080                     || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4081                 || (d->layout_->labeltype != LABEL_BIBLIO
4082                     && d->insetlist_.find(BIBITEM_CODE) != -1));
4083 }
4084
4085
4086 int Paragraph::fixBiblio(Buffer const & buffer)
4087 {
4088         // FIXME: when there was already an inset at 0, the return value is 1,
4089         // which does not tell whether another inset has been removed; the
4090         // cursor cannot be correctly updated.
4091
4092         bool const track_changes = buffer.params().track_changes;
4093         int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4094
4095         // The case where paragraph is not BIBLIO
4096         if (d->layout_->labeltype != LABEL_BIBLIO) {
4097                 if (bibitem_pos == -1)
4098                         // No InsetBibitem => OK
4099                         return 0;
4100                 // There is an InsetBibitem: remove it!
4101                 d->insetlist_.release(bibitem_pos);
4102                 eraseChar(bibitem_pos, track_changes);
4103                 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4104         }
4105
4106         bool const hasbibitem0 = bibitem_pos == 0;
4107         if (hasbibitem0) {
4108                 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4109                 // There was an InsetBibitem at pos 0,
4110                 // and no other one => OK
4111                 if (bibitem_pos == -1)
4112                         return 0;
4113                 // there is a bibitem at the 0 position, but since
4114                 // there is a second one, we copy the second on the
4115                 // first. We're assuming there are at most two of
4116                 // these, which there should be.
4117                 // FIXME: why does it make sense to do that rather
4118                 // than keep the first? (JMarc)
4119                 Inset * inset = releaseInset(bibitem_pos);
4120                 d->insetlist_.begin()->inset = inset;
4121                 // This needs to be done to update the counter (#8499)
4122                 buffer.updateBuffer();
4123                 return -bibitem_pos;
4124         }
4125
4126         // We need to create an inset at the beginning
4127         Inset * inset = nullptr;
4128         if (bibitem_pos > 0) {
4129                 // there was one somewhere in the paragraph, let's move it
4130                 inset = d->insetlist_.release(bibitem_pos);
4131                 eraseChar(bibitem_pos, track_changes);
4132         } else
4133                 // make a fresh one
4134                 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4135                                          InsetCommandParams(BIBITEM_CODE));
4136
4137         Font font(inherit_font, buffer.params().language);
4138         insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4139                                                    : Change::UNCHANGED));
4140
4141         // This is needed to get the counters right
4142         buffer.updateBuffer();
4143         return 1;
4144 }
4145
4146
4147 void Paragraph::checkAuthors(AuthorList const & authorList)
4148 {
4149         d->changes_.checkAuthors(authorList);
4150 }
4151
4152
4153 bool Paragraph::isChanged(pos_type pos) const
4154 {
4155         return lookupChange(pos).changed();
4156 }
4157
4158
4159 bool Paragraph::isInserted(pos_type pos) const
4160 {
4161         return lookupChange(pos).inserted();
4162 }
4163
4164
4165 bool Paragraph::isDeleted(pos_type pos) const
4166 {
4167         return lookupChange(pos).deleted();
4168 }
4169
4170
4171 InsetList const & Paragraph::insetList() const
4172 {
4173         return d->insetlist_;
4174 }
4175
4176
4177 void Paragraph::setInsetBuffers(Buffer & b)
4178 {
4179         d->insetlist_.setBuffer(b);
4180 }
4181
4182
4183 void Paragraph::resetBuffer()
4184 {
4185         d->insetlist_.resetBuffer();
4186 }
4187
4188
4189 Inset * Paragraph::releaseInset(pos_type pos)
4190 {
4191         Inset * inset = d->insetlist_.release(pos);
4192         /// does not honour change tracking!
4193         eraseChar(pos, false);
4194         return inset;
4195 }
4196
4197
4198 Inset * Paragraph::getInset(pos_type pos)
4199 {
4200         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4201                  ? d->insetlist_.get(pos) : nullptr;
4202 }
4203
4204
4205 Inset const * Paragraph::getInset(pos_type pos) const
4206 {
4207         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4208                  ? d->insetlist_.get(pos) : nullptr;
4209 }
4210
4211
4212 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4213                 pos_type & right, TextCase action)
4214 {
4215         // process sequences of modified characters; in change
4216         // tracking mode, this approach results in much better
4217         // usability than changing case on a char-by-char basis
4218         // We also need to track the current font, since font
4219         // changes within sequences can occur.
4220         vector<pair<char_type, Font> > changes;
4221
4222         bool const trackChanges = bparams.track_changes;
4223
4224         bool capitalize = true;
4225
4226         for (; pos < right; ++pos) {
4227                 char_type oldChar = d->text_[pos];
4228                 char_type newChar = oldChar;
4229
4230                 // ignore insets and don't play with deleted text!
4231                 if (oldChar != META_INSET && !isDeleted(pos)) {
4232                         switch (action) {
4233                                 case text_lowercase:
4234                                         newChar = lowercase(oldChar);
4235                                         break;
4236                                 case text_capitalization:
4237                                         if (capitalize) {
4238                                                 newChar = uppercase(oldChar);
4239                                                 capitalize = false;
4240                                         }
4241                                         break;
4242                                 case text_uppercase:
4243                                         newChar = uppercase(oldChar);
4244                                         break;
4245                         }
4246                 }
4247
4248                 if (isWordSeparator(pos) || isDeleted(pos)) {
4249                         // permit capitalization again
4250                         capitalize = true;
4251                 }
4252
4253                 if (oldChar != newChar) {
4254                         changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4255                         if (pos != right - 1)
4256                                 continue;
4257                         // step behind the changing area
4258                         pos++;
4259                 }
4260
4261                 int erasePos = pos - changes.size();
4262                 for (size_t i = 0; i < changes.size(); i++) {
4263                         insertChar(pos, changes[i].first,
4264                                    changes[i].second,
4265                                    trackChanges);
4266                         if (!eraseChar(erasePos, trackChanges)) {
4267                                 ++erasePos;
4268                                 ++pos; // advance
4269                                 ++right; // expand selection
4270                         }
4271                 }
4272                 changes.clear();
4273         }
4274 }
4275
4276
4277 int Paragraph::find(docstring const & str, bool cs, bool mw,
4278                 pos_type start_pos, bool del) const
4279 {
4280         pos_type pos = start_pos;
4281         int const strsize = str.length();
4282         int i = 0;
4283         pos_type const parsize = d->text_.size();
4284         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4285                 // Ignore "invisible" letters such as ligature breaks
4286                 // and hyphenation chars while searching
4287                 while (pos < parsize - 1 && isInset(pos)) {
4288                         odocstringstream os;
4289                         getInset(pos)->toString(os);
4290                         if (!getInset(pos)->isLetter() || !os.str().empty())
4291                                 break;
4292                         pos++;
4293                 }
4294                 if (cs && str[i] != d->text_[pos])
4295                         break;
4296                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4297                         break;
4298                 if (!del && isDeleted(pos))
4299                         break;
4300         }
4301
4302         if (i != strsize)
4303                 return 0;
4304
4305         // if necessary, check whether string matches word
4306         if (mw) {
4307                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4308                         return 0;
4309                 if (pos < parsize
4310                         && !isWordSeparator(pos))
4311                         return 0;
4312         }
4313
4314         return pos - start_pos;
4315 }
4316
4317
4318 char_type Paragraph::getChar(pos_type pos) const
4319 {
4320         return d->text_[pos];
4321 }
4322
4323
4324 pos_type Paragraph::size() const
4325 {
4326         return d->text_.size();
4327 }
4328
4329
4330 bool Paragraph::empty() const
4331 {
4332         return d->text_.empty();
4333 }
4334
4335
4336 bool Paragraph::isInset(pos_type pos) const
4337 {
4338         return d->text_[pos] == META_INSET;
4339 }
4340
4341
4342 bool Paragraph::isSeparator(pos_type pos) const
4343 {
4344         //FIXME: Are we sure this can be the only separator?
4345         return d->text_[pos] == ' ';
4346 }
4347
4348
4349 void Paragraph::deregisterWords()
4350 {
4351         Private::LangWordsMap::const_iterator itl = d->words_.begin();
4352         Private::LangWordsMap::const_iterator ite = d->words_.end();
4353         for (; itl != ite; ++itl) {
4354                 WordList & wl = theWordList(itl->first);
4355                 Private::Words::const_iterator it = (itl->second).begin();
4356                 Private::Words::const_iterator et = (itl->second).end();
4357                 for (; it != et; ++it)
4358                         wl.remove(*it);
4359         }
4360         d->words_.clear();
4361 }
4362
4363
4364 void Paragraph::locateWord(pos_type & from, pos_type & to,
4365         word_location const loc, bool const ignore_deleted) const
4366 {
4367         switch (loc) {
4368         case WHOLE_WORD_STRICT:
4369                 if (from == 0 || from == size()
4370                     || isWordSeparator(from, ignore_deleted)
4371                     || isWordSeparator(from - 1, ignore_deleted)) {
4372                         to = from;
4373                         return;
4374                 }
4375                 // fall through
4376
4377         case WHOLE_WORD:
4378                 // If we are already at the beginning of a word, do nothing
4379                 if (!from || isWordSeparator(from - 1, ignore_deleted))
4380                         break;
4381                 // fall through
4382
4383         case PREVIOUS_WORD:
4384                 // always move the cursor to the beginning of previous word
4385                 while (from && !isWordSeparator(from - 1, ignore_deleted))
4386                         --from;
4387                 break;
4388         case NEXT_WORD:
4389                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4390                 break;
4391         case PARTIAL_WORD:
4392                 // no need to move the 'from' cursor
4393                 break;
4394         }
4395         to = from;
4396         while (to < size() && !isWordSeparator(to, ignore_deleted))
4397                 ++to;
4398 }
4399
4400
4401 void Paragraph::collectWords()
4402 {
4403         for (pos_type pos = 0; pos < size(); ++pos) {
4404                 if (isWordSeparator(pos))
4405                         continue;
4406                 pos_type from = pos;
4407                 locateWord(from, pos, WHOLE_WORD);
4408                 // Work around MSVC warning: The statement
4409                 // if (pos < from + lyxrc.completion_minlength)
4410                 // triggers a signed vs. unsigned warning.
4411                 // I don't know why this happens, it could be a MSVC bug, or
4412                 // related to LLP64 (windows) vs. LP64 (unix) programming
4413                 // model, or the C++ standard might be ambigous in the section
4414                 // defining the "usual arithmetic conversions". However, using
4415                 // a temporary variable is safe and works on all compilers.
4416                 pos_type const endpos = from + lyxrc.completion_minlength;
4417                 if (pos < endpos)
4418                         continue;
4419                 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4420                 if (cit == d->fontlist_.end())
4421                         return;
4422                 Language const * lang = cit->font().language();
4423                 docstring const word = asString(from, pos, AS_STR_NONE);
4424                 d->words_[lang->lang()].insert(word);
4425         }
4426 }
4427
4428
4429 void Paragraph::registerWords()
4430 {
4431         Private::LangWordsMap::const_iterator itl = d->words_.begin();
4432         Private::LangWordsMap::const_iterator ite = d->words_.end();
4433         for (; itl != ite; ++itl) {
4434                 WordList & wl = theWordList(itl->first);
4435                 Private::Words::const_iterator it = (itl->second).begin();
4436                 Private::Words::const_iterator et = (itl->second).end();
4437                 for (; it != et; ++it)
4438                         wl.insert(*it);
4439         }
4440 }
4441
4442
4443 void Paragraph::updateWords()
4444 {
4445         deregisterWords();
4446         collectWords();
4447         registerWords();
4448 }
4449
4450
4451 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4452 {
4453         SkipPositionsIterator begin = skips.begin();
4454         SkipPositions::iterator end = skips.end();
4455         if (pos > 0 && begin < end) {
4456                 --end;
4457                 if (end->last == pos - 1) {
4458                         end->last = pos;
4459                         return;
4460                 }
4461         }
4462         skips.insert(end, FontSpan(pos, pos));
4463 }
4464
4465
4466 Language * Paragraph::Private::locateSpellRange(
4467         pos_type & from, pos_type & to,
4468         SkipPositions & skips) const
4469 {
4470         // skip leading white space
4471         while (from < to && owner_->isWordSeparator(from))
4472                 ++from;
4473         // don't check empty range
4474         if (from >= to)
4475                 return nullptr;
4476         // get current language
4477         Language * lang = getSpellLanguage(from);
4478         pos_type last = from;
4479         bool samelang = true;
4480         bool sameinset = true;
4481         while (last < to && samelang && sameinset) {
4482                 // hop to end of word
4483                 while (last < to && !owner_->isWordSeparator(last)) {
4484                         if (owner_->getInset(last)) {
4485                                 appendSkipPosition(skips, last);
4486                         } else if (owner_->isDeleted(last)) {
4487                                 appendSkipPosition(skips, last);
4488                         }
4489                         ++last;
4490                 }
4491                 // hop to next word while checking for insets
4492                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4493                         if (Inset const * inset = owner_->getInset(last))
4494                                 sameinset = inset->isChar() && inset->isLetter();
4495                         if (sameinset && owner_->isDeleted(last)) {
4496                                 appendSkipPosition(skips, last);
4497                         }
4498                         if (sameinset)
4499                                 last++;
4500                 }
4501                 if (sameinset && last < to) {
4502                         // now check for language change
4503                         samelang = lang == getSpellLanguage(last);
4504                 }
4505         }
4506         // if language change detected backstep is needed
4507         if (!samelang)
4508                 --last;
4509         to = last;
4510         return lang;
4511 }
4512
4513
4514 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4515 {
4516         Language * lang =
4517                 const_cast<Language *>(owner_->getFontSettings(
4518                         inset_owner_->buffer().params(), from).language());
4519         if (lang == inset_owner_->buffer().params().language
4520                 && !lyxrc.spellchecker_alt_lang.empty()) {
4521                 string lang_code;
4522                 string const lang_variety =
4523                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4524                 lang->setCode(lang_code);
4525                 lang->setVariety(lang_variety);
4526         }
4527         return lang;
4528 }
4529
4530
4531 void Paragraph::requestSpellCheck(pos_type pos)
4532 {
4533         d->requestSpellCheck(pos);
4534 }
4535
4536
4537 bool Paragraph::needsSpellCheck() const
4538 {
4539         SpellChecker::ChangeNumber speller_change_number = 0;
4540         if (theSpellChecker())
4541                 speller_change_number = theSpellChecker()->changeNumber();
4542         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4543                 d->speller_state_.needsCompleteRefresh(speller_change_number);
4544         }
4545         return d->needsSpellCheck();
4546 }
4547
4548
4549 bool Paragraph::Private::ignoreWord(docstring const & word) const
4550 {
4551         // Ignore words with digits
4552         // FIXME: make this customizable
4553         // (note that some checkers ignore words with digits by default)
4554         docstring::const_iterator cit = word.begin();
4555         docstring::const_iterator const end = word.end();
4556         for (; cit != end; ++cit) {
4557                 if (isNumber((*cit)))
4558                         return true;
4559         }
4560         return false;
4561 }
4562
4563
4564 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4565         WordLangTuple & wl, docstring_list & suggestions,
4566         bool do_suggestion, bool check_learned) const
4567 {
4568         SpellChecker::Result result = SpellChecker::WORD_OK;
4569         SpellChecker * speller = theSpellChecker();
4570         if (!speller)
4571                 return result;
4572
4573         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4574                 return result;
4575
4576         locateWord(from, to, WHOLE_WORD, true);
4577         if (from == to || from >= size())
4578                 return result;
4579
4580         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4581         Language * lang = d->getSpellLanguage(from);
4582
4583         if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4584                 return result;
4585
4586         wl = WordLangTuple(word, lang);
4587
4588         if (word.empty())
4589                 return result;
4590
4591         if (needsSpellCheck() || check_learned) {
4592                 pos_type end = to;
4593                 if (!d->ignoreWord(word)) {
4594                         bool const trailing_dot = to < size() && d->text_[to] == '.';
4595                         result = speller->check(wl);
4596                         if (SpellChecker::misspelled(result) && trailing_dot) {
4597                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4598                                 result = speller->check(wl);
4599                                 if (!SpellChecker::misspelled(result)) {
4600                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4601                                            word << "\" [" <<
4602                                            from << ".." << to << "]");
4603                                 } else {
4604                                         // spell check with dot appended failed too
4605                                         // restore original word/lang value
4606                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4607                                         wl = WordLangTuple(word, lang);
4608                                 }
4609                         }
4610                 }
4611                 if (!SpellChecker::misspelled(result)) {
4612                         // area up to the begin of the next word is not misspelled
4613                         while (end < size() && isWordSeparator(end))
4614                                 ++end;
4615                 }
4616                 d->setMisspelled(from, end, result);
4617         } else {
4618                 result = d->speller_state_.getState(from);
4619         }
4620
4621         if (do_suggestion)
4622                 suggestions.clear();
4623
4624         if (SpellChecker::misspelled(result)) {
4625                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4626                            word << "\" [" <<
4627                            from << ".." << to << "]");
4628                 if (do_suggestion)
4629                         speller->suggest(wl, suggestions);
4630         }
4631         return result;
4632 }
4633
4634
4635 void Paragraph::anonymize()
4636 {
4637         // This is a very crude anonymization for now
4638         for (char_type & c : d->text_)
4639                 if (isLetterChar(c) || isNumber(c))
4640                         c = 'a';
4641 }
4642
4643
4644 void Paragraph::Private::markMisspelledWords(
4645         pos_type const & first, pos_type const & last,
4646         SpellChecker::Result result,
4647         docstring const & word,
4648         SkipPositions const & skips)
4649 {
4650         if (!SpellChecker::misspelled(result)) {
4651                 setMisspelled(first, last, SpellChecker::WORD_OK);
4652                 return;
4653         }
4654         int snext = first;
4655         SpellChecker * speller = theSpellChecker();
4656         // locate and enumerate the error positions
4657         int nerrors = speller->numMisspelledWords();
4658         int numskipped = 0;
4659         SkipPositionsIterator it = skips.begin();
4660         SkipPositionsIterator et = skips.end();
4661         for (int index = 0; index < nerrors; ++index) {
4662                 int wstart;
4663                 int wlen = 0;
4664                 speller->misspelledWord(index, wstart, wlen);
4665                 /// should not happen if speller supports range checks
4666                 if (!wlen) continue;
4667                 docstring const misspelled = word.substr(wstart, wlen);
4668                 wstart += first + numskipped;
4669                 if (snext < wstart) {
4670                         /// mark the range of correct spelling
4671                         numskipped += countSkips(it, et, wstart);
4672                         setMisspelled(snext,
4673                                 wstart - 1, SpellChecker::WORD_OK);
4674                 }
4675                 snext = wstart + wlen;
4676                 numskipped += countSkips(it, et, snext);
4677                 /// mark the range of misspelling
4678                 setMisspelled(wstart, snext, result);
4679                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4680                            misspelled << "\" [" <<
4681                            wstart << ".." << (snext-1) << "]");
4682                 ++snext;
4683         }
4684         if (snext <= last) {
4685                 /// mark the range of correct spelling at end
4686                 setMisspelled(snext, last, SpellChecker::WORD_OK);
4687         }
4688 }
4689
4690
4691 void Paragraph::spellCheck() const
4692 {
4693         SpellChecker * speller = theSpellChecker();
4694         if (!speller || empty() ||!needsSpellCheck())
4695                 return;
4696         pos_type start;
4697         pos_type endpos;
4698         d->rangeOfSpellCheck(start, endpos);
4699         if (speller->canCheckParagraph()) {
4700                 // loop until we leave the range
4701                 for (pos_type first = start; first < endpos; ) {
4702                         pos_type last = endpos;
4703                         Private::SkipPositions skips;
4704                         Language * lang = d->locateSpellRange(first, last, skips);
4705                         if (first >= endpos)
4706                                 break;
4707                         // start the spell checker on the unit of meaning
4708                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4709                         WordLangTuple wl = WordLangTuple(word, lang);
4710                         SpellChecker::Result result = word.size() ?
4711                                 speller->check(wl) : SpellChecker::WORD_OK;
4712                         d->markMisspelledWords(first, last, result, word, skips);
4713                         first = ++last;
4714                 }
4715         } else {
4716                 static docstring_list suggestions;
4717                 pos_type to = endpos;
4718                 while (start < endpos) {
4719                         WordLangTuple wl;
4720                         spellCheck(start, to, wl, suggestions, false);
4721                         start = to + 1;
4722                 }
4723         }
4724         d->readySpellCheck();
4725 }
4726
4727
4728 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4729 {
4730         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4731         if (result || pos <= 0 || pos > size())
4732                 return result;
4733         if (check_boundary && (pos == size() || isWordSeparator(pos)))
4734                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4735         return result;
4736 }
4737
4738
4739 string Paragraph::magicLabel() const
4740 {
4741         stringstream ss;
4742         ss << "magicparlabel-" << id();
4743         return ss.str();
4744 }
4745
4746
4747 } // namespace lyx