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