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