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