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