]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
* ca/Intro.lyx from Daniel
[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
768 void Paragraph::rejectChanges(pos_type start, pos_type end)
769 {
770         LASSERT(start >= 0 && start <= size(), return);
771         LASSERT(end > start && end <= size() + 1, return);
772
773         // Make sure that Buffer::hasChangesPresent is updated
774         ChangesMonitor cm(*this);
775
776         for (pos_type pos = start; pos < end; ++pos) {
777                 switch (lookupChange(pos).type) {
778                         case Change::UNCHANGED:
779                                 // reject changes in nested inset
780                                 if (Inset * inset = getInset(pos))
781                                                 inset->rejectChanges();
782                                 break;
783
784                         case Change::INSERTED:
785                                 // Suppress access to non-existent
786                                 // "end-of-paragraph char"
787                                 if (pos < size()) {
788                                         eraseChar(pos, false);
789                                         --end;
790                                         --pos;
791                                 }
792                                 break;
793
794                         case Change::DELETED:
795                                 d->changes_.set(Change(Change::UNCHANGED), pos);
796
797                                 // Do NOT reject changes within a deleted inset!
798                                 // There may be insertions of a co-author inside of it!
799
800                                 break;
801                 }
802         }
803 }
804
805
806 void Paragraph::Private::insertChar(pos_type pos, char_type c,
807                 Change const & change)
808 {
809         LASSERT(pos >= 0 && pos <= int(text_.size()), return);
810
811         // Make sure that Buffer::hasChangesPresent is updated
812         ChangesMonitor cm(*owner_);
813
814         // track change
815         changes_.insert(change, pos);
816
817         // This is actually very common when parsing buffers (and
818         // maybe inserting ascii text)
819         if (pos == pos_type(text_.size())) {
820                 // when appending characters, no need to update tables
821                 text_.push_back(c);
822                 // but we want spell checking
823                 requestSpellCheck(pos);
824                 return;
825         }
826
827         text_.insert(text_.begin() + pos, c);
828
829         // Update the font table.
830         fontlist_.increasePosAfterPos(pos);
831
832         // Update the insets
833         insetlist_.increasePosAfterPos(pos);
834
835         // Update list of misspelled positions
836         speller_state_.increasePosAfterPos(pos);
837
838         // Update bookmarks
839         if (inset_owner_ && inset_owner_->isBufferValid())
840                 theSession().bookmarks().adjustPosAfterPos(inset_owner_->buffer().fileName(),
841                                                        id_, pos, 1);
842 }
843
844
845 bool Paragraph::insertInset(pos_type pos, Inset * inset,
846                                    Font const & font, Change const & change)
847 {
848         LASSERT(inset, return false);
849         LASSERT(pos >= 0 && pos <= size(), return false);
850
851         // Make sure that Buffer::hasChangesPresent is updated
852         ChangesMonitor cm(*this);
853
854         // Paragraph::insertInset() can be used in cut/copy/paste operation where
855         // d->inset_owner_ is not set yet.
856         if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
857                 return false;
858
859         d->insertChar(pos, META_INSET, change);
860         LASSERT(d->text_[pos] == META_INSET, return false);
861
862         // Add a new entry in the insetlist_.
863         d->insetlist_.insert(inset, pos);
864
865         // Some insets require run of spell checker
866         requestSpellCheck(pos);
867         setFont(pos, font);
868         return true;
869 }
870
871
872 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
873 {
874         LASSERT(pos >= 0 && pos <= size(), return false);
875
876         // Make sure that Buffer::hasChangesPresent is updated
877         ChangesMonitor cm(*this);
878
879         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
880
881         if (trackChanges) {
882                 Change change = d->changes_.lookup(pos);
883
884                 // set the character to DELETED if
885                 //  a) it was previously unchanged or
886                 //  b) it was inserted by a co-author
887
888                 if (!change.changed() ||
889                       (change.inserted() && !change.currentAuthor())) {
890                         setChange(pos, Change(Change::DELETED));
891                         // request run of spell checker
892                         requestSpellCheck(pos);
893                         return false;
894                 }
895
896                 if (change.deleted())
897                         return false;
898         }
899
900         // Don't physically access the imaginary end-of-paragraph character.
901         // eraseChar() can only mark it as DELETED. A physical deletion of
902         // end-of-par must be handled externally.
903         if (pos == size()) {
904                 return false;
905         }
906
907         // track change
908         d->changes_.erase(pos);
909
910         // if it is an inset, delete the inset entry
911         if (d->text_[pos] == META_INSET)
912                 d->insetlist_.erase(pos);
913
914         d->text_.erase(d->text_.begin() + pos);
915
916         // Update the fontlist_
917         d->fontlist_.erase(pos);
918
919         // Update the insetlist_
920         d->insetlist_.decreasePosAfterPos(pos);
921
922         // Update list of misspelled positions
923         d->speller_state_.decreasePosAfterPos(pos);
924         d->speller_state_.refreshLast(size());
925
926         // Update bookmarks
927         if (d->inset_owner_ && d->inset_owner_->isBufferValid())
928                 theSession().bookmarks().adjustPosAfterPos(d->inset_owner_->buffer().fileName(),
929                                                        d->id_, pos, -1);
930
931         return true;
932 }
933
934
935 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
936 {
937         LASSERT(start >= 0 && start <= size(), return 0);
938         LASSERT(end >= start && end <= size() + 1, return 0);
939
940         pos_type i = start;
941         for (pos_type count = end - start; count; --count) {
942                 if (!eraseChar(i, trackChanges))
943                         ++i;
944         }
945         return end - i;
946 }
947
948
949 // Handle combining characters
950 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
951                 otexstream & os, char_type c, char_type next,
952                 OutputParams const & runparams) const
953 {
954         // Writing next here may circumvent a possible font change between
955         // c and next. Since next is only output if it forms a surrogate pair
956         // with c we can ignore this:
957         // A font change inside a surrogate pair does not make sense and is
958         // hopefully impossible to input.
959         // FIXME: change tracking
960         // Is this correct WRT change tracking?
961         Encoding const & encoding = *(runparams.encoding);
962         docstring latex1 = encoding.latexChar(next).first;
963         if (runparams.inIPA) {
964                 string const tipashortcut = Encodings::TIPAShortcut(next);
965                 if (!tipashortcut.empty()) {
966                         latex1 = from_ascii(tipashortcut);
967                 }
968         }
969         docstring latex2 = encoding.latexChar(c).first;
970
971         if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
972                 // Encoding supports the combination:
973                 // output as is (combining char after base char).
974                 os << latex2 << latex1;
975                 return latex1.length() + latex2.length();
976         }
977
978         os << latex1 << "{" << latex2 << "}";
979         return latex1.length() + latex2.length() + 2;
980 }
981
982
983 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
984                                        OutputParams const & runparams,
985                                        otexstream & os,
986                                        pos_type i,
987                                        unsigned int & column,
988                                        Font const & font,
989                                        Layout const & style) const
990 {
991         if (style.pass_thru || runparams.pass_thru)
992                 return false;
993
994         if (i + 1 < int(text_.size())) {
995                 char_type next = text_[i + 1];
996                 if (Encodings::isCombiningChar(next)) {
997                         // This space has an accent, so we must always output it.
998                         column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
999                         return true;
1000                 }
1001         }
1002
1003         if (runparams.linelen > 0
1004             && column > runparams.linelen
1005             && i
1006             && text_[i - 1] != ' '
1007             && (i + 1 < int(text_.size()))
1008             // same in FreeSpacing mode
1009             && !owner_->isFreeSpacing()
1010             // In typewriter mode, we want to avoid
1011             // ! . ? : at the end of a line
1012             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1013                  && (text_[i - 1] == '.'
1014                      || text_[i - 1] == '?'
1015                      || text_[i - 1] == ':'
1016                      || text_[i - 1] == '!'))) {
1017                 os << '\n';
1018                 os.texrow().start(owner_->id(), i + 1);
1019                 column = 0;
1020         } else if (style.free_spacing) {
1021                 os << '~';
1022         } else {
1023                 os << ' ';
1024         }
1025         return false;
1026 }
1027
1028
1029 void Paragraph::Private::latexInset(BufferParams const & bparams,
1030                                     otexstream & os,
1031                                     OutputParams & runparams,
1032                                     Font & running_font,
1033                                     Font & basefont,
1034                                     Font const & outerfont,
1035                                     bool & open_font,
1036                                     Change & running_change,
1037                                     Layout const & style,
1038                                     pos_type & i,
1039                                     unsigned int & column,
1040                                     bool const fontswitch_inset,
1041                                     bool const closeLanguage,
1042                                     bool const lang_switched_at_inset) const
1043 {
1044         Inset * inset = owner_->getInset(i);
1045         LBUFERR(inset);
1046
1047         if (style.pass_thru) {
1048                 odocstringstream ods;
1049                 inset->plaintext(ods, runparams);
1050                 os << ods.str();
1051                 return;
1052         }
1053
1054         // FIXME: move this to InsetNewline::latex
1055         if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1056                 // newlines are handled differently here than
1057                 // the default in simpleTeXSpecialChars().
1058                 if (!style.newline_allowed) {
1059                         os << '\n';
1060                 } else {
1061                         if (open_font) {
1062                                 bool needPar = false;
1063                                 column += running_font.latexWriteEndChanges(
1064                                         os, bparams, runparams,
1065                                         basefont, basefont, needPar);
1066                                 open_font = false;
1067                         }
1068
1069                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1070                                 os << '~';
1071
1072                         basefont = owner_->getLayoutFont(bparams, outerfont);
1073                         running_font = basefont;
1074
1075                         if (runparams.moving_arg)
1076                                 os << "\\protect ";
1077
1078                 }
1079                 os.texrow().start(owner_->id(), i + 1);
1080                 column = 0;
1081         }
1082
1083         if (owner_->isDeleted(i)) {
1084                 if( ++runparams.inDeletedInset == 1)
1085                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
1086         }
1087
1088         if (inset->canTrackChanges()) {
1089                 column += Changes::latexMarkChange(os, bparams, running_change,
1090                         Change(Change::UNCHANGED), runparams);
1091                 running_change = Change(Change::UNCHANGED);
1092         }
1093
1094         unsigned int close_brace = 0;
1095         bool const disp_env = (inset->isEnvironment() && inset->getLayout().isDisplay())
1096                         || runparams.inDisplayMath;
1097         string close_env;
1098         odocstream::pos_type const len = os.os().tellp();
1099
1100         if (inset->forceLTR(runparams)
1101             // babel with LuaTeX does not need a switch
1102             // babel with XeTeX needs a switch only if bidi is used
1103             // and \L is not defined there.
1104             && (!runparams.isFullUnicode() || bparams.useBidiPackage(runparams) || runparams.use_polyglossia)
1105             && running_font.isRightToLeft()) {
1106                 if (bparams.useBidiPackage(runparams) || runparams.use_polyglossia) {
1107                         // (lua)bidi
1108                         // Displayed environments go in an LTR environment
1109                         if (disp_env) {
1110                                 os << "\\begin{LTR}";
1111                                 close_env = "LTR";
1112                         } else {
1113                                 if (runparams.flavor == Flavor::LuaTeX) {
1114                                         // luabidi's \LRE needs extra grouping
1115                                         // (possibly a LuaTeX bug)
1116                                         os << '{';
1117                                         close_brace = 1;
1118                                 }
1119                                 os << "\\LRE{";
1120                                 close_brace += 1;
1121                         }
1122                 } else if (running_font.language()->lang() == "farsi"
1123                          || running_font.language()->lang() == "arabic_arabi") {
1124                         os << "\\textLR{" << termcmd;
1125                         close_brace = 1;
1126                 } else {
1127                         // babel classic
1128                         os << "\\L{";
1129                         if (disp_env)
1130                                 os << safebreakln;
1131                         close_brace = 1;
1132                 }
1133         }
1134
1135         if (open_font && fontswitch_inset) {
1136                 bool lang_closed = false;
1137                 // Close language if needed
1138                 if (closeLanguage && !lang_switched_at_inset) {
1139                         // We need prev_font here as language changes directly at inset
1140                         // will only be started inside the inset.
1141                         Font const prev_font = (i > 0) ?
1142                                                 owner_->getFont(bparams, i - 1, outerfont)
1143                                               : running_font;
1144                         Font tmpfont(basefont);
1145                         tmpfont.setLanguage(prev_font.language());
1146                         bool needPar = false;
1147                         unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1148                                                                           basefont, basefont,
1149                                                                           needPar, closeLanguage);
1150                         column += count;
1151                         lang_closed = count > 0;
1152                 }
1153                 // Update the running_font, making sure, however,
1154                 // to leave the language as it was.
1155                 // FIXME: probably a better way to keep track of the old
1156                 // language, than copying the entire font?
1157                 Font const copy_font(running_font);
1158                 basefont = owner_->getLayoutFont(bparams, outerfont);
1159                 running_font = basefont;
1160                 if (!closeLanguage)
1161                         running_font.setLanguage(copy_font.language());
1162                 OutputParams rp = runparams;
1163                 rp.encoding = basefont.language()->encoding();
1164                 // For these, we use switches, so they should be taken as
1165                 // base inside the inset.
1166                 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1167                 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1168                 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1169                 // Now re-do font changes in a way needed here
1170                 // (using switches with multi-par insets)
1171                 InsetText const * textinset = inset->asInsetText();
1172                 bool const cprotect = textinset
1173                         ? textinset->hasCProtectContent(runparams.moving_arg)
1174                           && !textinset->text().isMainText()
1175                           && inset->lyxCode() != BRANCH_CODE
1176                         : 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 & table : par.insetList())
2380                                 if (table.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 & table : pars[pit].insetList())
2417                                 if (table.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                                         : false;
3019                                 column += current_font.latexWriteStartChanges(ots, bparams,
3020                                                                               runparams, basefont, last_font, false,
3021                                                                               cprotect);
3022                                 // Check again for display math in ulem commands as a
3023                                 // font change may also occur just before a math inset.
3024                                 if (runparams.inDisplayMath && !deleted_display_math
3025                                     && runparams.inulemcmd) {
3026                                         if (os.afterParbreak())
3027                                                 os << "\\noindent";
3028                                         else
3029                                                 os << "\\\\\n";
3030                                 }
3031                                 running_font = current_font;
3032                                 open_font = true;
3033                                 docstring fontchange = ots.str();
3034                                 os << fontchange;
3035                                 // check whether the fontchange ends with a \\textcolor
3036                                 // modifier and the text starts with a space. If so we
3037                                 // need to add } in order to prevent \\textcolor from gobbling
3038                                 // the space (bug 4473).
3039                                 docstring const last_modifier = rsplit(fontchange, '\\');
3040                                 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
3041                                         os << from_ascii("{}");
3042                                 else if (ots.terminateCommand())
3043                                         os << termcmd;
3044                                 if (in_ct_deletion) {
3045                                         // We have to close and then reopen \lyxdeleted,
3046                                         // as strikeout needs to be on lowest level.
3047                                         OutputParams rp = runparams;
3048                                         column += Changes::latexMarkChange(os, bparams,
3049                                                 Change(Change::UNCHANGED), change, rp);
3050                                 }
3051                         } else {// if fontswitch_inset
3052                                 if (current_font != running_font || !langClosed)
3053                                         // font is still open in fontswitch_insets if we have
3054                                         // a non-lang font difference or if the language
3055                                         // is the only difference but has not been forcedly
3056                                         // closed meanwhile
3057                                         open_font = true;
3058                                 running_font = current_font;
3059                         }
3060                 }
3061
3062                 // FIXME: think about end_pos implementation...
3063                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
3064                         // FIXME: integrate this case in latexSpecialChar
3065                         // Do not print the separation of the optional argument
3066                         // if style.pass_thru is false. This works because
3067                         // latexSpecialChar ignores spaces if
3068                         // style.pass_thru is false.
3069                         if (i != body_pos - 1) {
3070                                 if (d->simpleTeXBlanks(bparams, runparams, os,
3071                                                 i, column, current_font, style)) {
3072                                         // A surrogate pair was output. We
3073                                         // must not call latexSpecialChar
3074                                         // in this iteration, since it would output
3075                                         // the combining character again.
3076                                         ++i;
3077                                         continue;
3078                                 }
3079                         }
3080                 }
3081
3082                 OutputParams rp = runparams;
3083                 rp.free_spacing = style.free_spacing;
3084                 rp.local_font = &current_font;
3085                 rp.intitle = style.intitle;
3086
3087                 // Two major modes:  LaTeX or plain
3088                 // Handle here those cases common to both modes
3089                 // and then split to handle the two modes separately.
3090                 if (c == META_INSET) {
3091                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3092                                 // Greyedout notes and, in general, all insets
3093                                 // with InsetLayout::isDisplay() == false,
3094                                 // are typeset inline with the text. So, we
3095                                 // can add a \par to the last paragraph of
3096                                 // such insets only if nothing else follows.
3097                                 bool incremented = false;
3098                                 Inset const * inset = getInset(i);
3099                                 InsetText const * textinset = inset
3100                                                         ? inset->asInsetText()
3101                                                         : nullptr;
3102                                 if (i + 1 == size() && textinset
3103                                     && !inset->getLayout().isDisplay()) {
3104                                         ParagraphList const & pars =
3105                                                 textinset->text().paragraphs();
3106                                         pit_type const pit = pars.size() - 1;
3107                                         Font const lastfont =
3108                                                 pit < 0 || pars[pit].empty()
3109                                                 ? pars[pit].getLayoutFont(
3110                                                                 bparams,
3111                                                                 real_outerfont)
3112                                                 : pars[pit].getFont(bparams,
3113                                                         pars[pit].size() - 1,
3114                                                         real_outerfont);
3115                                         if (lastfont.fontInfo().size() !=
3116                                             basefont.fontInfo().size()) {
3117                                                 ++parInline;
3118                                                 incremented = true;
3119                                         }
3120                                 }
3121                                 // We need to restore parts of this after insets with
3122                                 // allowMultiPar() true
3123                                 Font const save_basefont = basefont;
3124                                 d->latexInset(bparams, os, rp, running_font,
3125                                                 basefont, real_outerfont, open_font,
3126                                                 runningChange, style, i, column, fontswitch_inset,
3127                                                 closeLanguage, (lang_switched_at_inset || langClosed));
3128                                 if (fontswitch_inset) {
3129                                         if (open_font) {
3130                                                 bool needPar = false;
3131                                                 column += running_font.latexWriteEndChanges(
3132                                                         os, bparams, runparams,
3133                                                         basefont, basefont, needPar);
3134                                                 open_font = false;
3135                                         }
3136                                         basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3137                                         basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3138                                         basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3139                                 }
3140                                 if (incremented)
3141                                         --parInline;
3142
3143                                 if (runparams.ctObject == CtObject::DisplayObject
3144                                     || runparams.ctObject == CtObject::UDisplayObject) {
3145                                         // Close \lyx*deleted and force its
3146                                         // reopening (if needed)
3147                                         os << '}';
3148                                         column++;
3149                                         runningChange = Change(Change::UNCHANGED);
3150                                         runparams.ctObject = CtObject::Normal;
3151                                 }
3152                         }
3153                 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3154                         if (!bparams.useNonTeXFonts)
3155                           script = Encodings::isKnownScriptChar(c);
3156                         if (script != alien_script) {
3157                                 if (!alien_script.empty()) {
3158                                         os << "}";
3159                                         alien_script.clear();
3160                                 }
3161                                 string fontenc = running_font.language()->fontenc(bparams);
3162                                 if (!script.empty()
3163                                         && !Encodings::fontencSupportsScript(fontenc, script)) {
3164                                         column += script.length() + 2;
3165                                         os << "\\" << script << "{";
3166                                         alien_script = script;
3167                                 }
3168                         }
3169                         try {
3170                                 d->latexSpecialChar(os, bparams, rp, running_font,
3171                                                                         alien_script, style, i, end_pos, column);
3172                         } catch (EncodingException & e) {
3173                                 if (runparams.dryrun) {
3174                                         os << "<" << _("LyX Warning: ")
3175                                            << _("uncodable character") << " '";
3176                                         os.put(c);
3177                                         os << "'>";
3178                                 } else {
3179                                         // add location information and throw again.
3180                                         e.par_id = id();
3181                                         e.pos = i;
3182                                         throw;
3183                                 }
3184                         }
3185                 }
3186
3187                 // Set the encoding to that returned from latexSpecialChar (see
3188                 // comment for encoding member in OutputParams.h)
3189                 runparams.encoding = rp.encoding;
3190
3191                 // Also carry on the info on a closed ulem command for insets
3192                 // such as Note that do not produce any output, so that no
3193                 // command is ever executed but its opening was recorded.
3194                 runparams.inulemcmd = rp.inulemcmd;
3195
3196                 // These need to be passed upstream as well
3197                 runparams.need_maketitle = rp.need_maketitle;
3198                 runparams.have_maketitle = rp.have_maketitle;
3199
3200                 // And finally, pass the post_macros upstream
3201                 runparams.post_macro = rp.post_macro;
3202         }
3203
3204         // Close wrapper for alien script
3205         if (!alien_script.empty()) {
3206                 os << "}";
3207                 alien_script.clear();
3208         }
3209
3210         Font const font = empty()
3211                 ? getLayoutFont(bparams, real_outerfont)
3212                 : getFont(bparams, size() - 1, real_outerfont);
3213
3214         InsetText const * textinset = inInset().asInsetText();
3215
3216         bool const maintext = textinset
3217                 ? textinset->text().isMainText()
3218                 : false;
3219
3220         size_t const numpars = textinset
3221                 ? textinset->text().paragraphs().size()
3222                 : 0;
3223
3224         bool needPar = false;
3225
3226         if (style.resfont.size() != font.fontInfo().size()
3227             && (!runparams.isLastPar || maintext
3228                 || (numpars > 1 && d->ownerCode() != CELL_CODE
3229                     && (inInset().getLayout().isDisplay()
3230                         || parInline)))
3231             && !style.isCommand()) {
3232                 needPar = true;
3233         }
3234
3235         // If we have an open font definition, we have to close it
3236         if (open_font) {
3237                 // Make sure that \\par is done with the font of the last
3238                 // character if this has another size as the default.
3239                 // This is necessary because LaTeX (and LyX on the screen)
3240                 // calculates the space between the baselines according
3241                 // to this font. (Matthias)
3242                 //
3243                 // We must not change the font for the last paragraph
3244                 // of non-multipar insets, tabular cells or commands,
3245                 // since this produces unwanted whitespace.
3246 #ifdef FIXED_LANGUAGE_END_DETECTION
3247                 if (next_) {
3248                         running_font.latexWriteEndChanges(os, bparams,
3249                                         runparams, basefont,
3250                                         next_->getFont(bparams, 0, outerfont),
3251                                                        needPar);
3252                 } else {
3253                         running_font.latexWriteEndChanges(os, bparams,
3254                                         runparams, basefont, basefont, needPar);
3255                 }
3256 #else
3257 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3258 //FIXME: there as we start another \selectlanguage with the next paragraph if
3259 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3260                 running_font.latexWriteEndChanges(os, bparams, runparams,
3261                                 basefont, basefont, needPar);
3262 #endif
3263         }
3264         if (needPar) {
3265                 // The \par could not be inserted at the same nesting
3266                 // level of the font size change, so do it now.
3267                 os << "{\\" << font.latexSize() << "\\par}";
3268         }
3269
3270         if (!runparams.inDeletedInset || inInset().canTrackChanges())
3271                 column += Changes::latexMarkChange(os, bparams, runningChange,
3272                                         Change(Change::UNCHANGED), runparams);
3273
3274         // Needed if there is an optional argument but no contents.
3275         if (body_pos > 0 && body_pos == size()) {
3276                 os << "}]~";
3277         }
3278
3279         if (!style.rightdelim().empty()) {
3280                 os << style.rightdelim();
3281                 column += style.rightdelim().size();
3282         }
3283
3284         if (allowcust && d->endTeXParParams(bparams, os, runparams)
3285             && runparams.encoding != prev_encoding) {
3286                 runparams.encoding = prev_encoding;
3287                 os << setEncoding(prev_encoding->iconvName());
3288         }
3289
3290         LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3291 }
3292
3293
3294 bool Paragraph::emptyTag() const
3295 {
3296         for (pos_type i = 0; i < size(); ++i) {
3297                 if (Inset const * inset = getInset(i)) {
3298                         InsetCode lyx_code = inset->lyxCode();
3299                         // FIXME testing like that is wrong. What is
3300                         // the intent?
3301                         if (lyx_code != TOC_CODE &&
3302                             lyx_code != INCLUDE_CODE &&
3303                             lyx_code != GRAPHICS_CODE &&
3304                             lyx_code != ERT_CODE &&
3305                             lyx_code != LISTINGS_CODE &&
3306                             lyx_code != FLOAT_CODE &&
3307                             lyx_code != TABULAR_CODE) {
3308                                 return false;
3309                         }
3310                 } else {
3311                         char_type c = d->text_[i];
3312                         if (c != ' ' && c != '\t')
3313                                 return false;
3314                 }
3315         }
3316         return true;
3317 }
3318
3319
3320 string Paragraph::getID(Buffer const &, OutputParams const &)
3321         const
3322 {
3323         for (pos_type i = 0; i < size(); ++i) {
3324                 if (Inset const * inset = getInset(i)) {
3325                         InsetCode lyx_code = inset->lyxCode();
3326                         if (lyx_code == LABEL_CODE) {
3327                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3328                                 docstring const & id = il->getParam("name");
3329                                 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3330                         }
3331                 }
3332         }
3333         return string();
3334 }
3335
3336
3337 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3338 {
3339         pos_type i;
3340         for (i = 0; i < size(); ++i) {
3341                 if (Inset const * inset = getInset(i)) {
3342                         inset->docbook(xs, runparams);
3343                 } else {
3344                         char_type c = d->text_[i];
3345                         if (c == ' ')
3346                                 break;
3347                         xs << c;
3348                 }
3349         }
3350         return i;
3351 }
3352
3353
3354 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3355         const
3356 {
3357         pos_type i;
3358         for (i = 0; i < size(); ++i) {
3359                 if (Inset const * inset = getInset(i)) {
3360                         inset->xhtml(xs, runparams);
3361                 } else {
3362                         char_type c = d->text_[i];
3363                         if (c == ' ')
3364                                 break;
3365                         xs << c;
3366                 }
3367         }
3368         return i;
3369 }
3370
3371
3372 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3373 {
3374         Font font_old;
3375         pos_type size = text_.size();
3376         for (pos_type i = initial; i < size; ++i) {
3377                 Font font = owner_->getFont(buf.params(), i, outerfont);
3378                 if (text_[i] == META_INSET)
3379                         return false;
3380                 if (i != initial && font != font_old)
3381                         return false;
3382                 font_old = font;
3383         }
3384
3385         return true;
3386 }
3387
3388
3389 namespace {
3390
3391 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3392                   vector<xml::EndFontTag> & tagsToClose,
3393                   bool & flag, FontState curstate, xml::FontTypes type)
3394 {
3395         if (curstate == FONT_ON) {
3396                 tagsToOpen.push_back(docbookStartFontTag(type));
3397                 flag = true;
3398         } else if (flag) {
3399                 tagsToClose.push_back(docbookEndFontTag(type));
3400                 flag = false;
3401         }
3402 }
3403
3404 class OptionalFontType {
3405 public:
3406         xml::FontTypes ft;
3407         bool has_value;
3408
3409         OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3410         OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3411 };
3412
3413 OptionalFontType fontShapeToXml(FontShape fs)
3414 {
3415         switch (fs) {
3416         case ITALIC_SHAPE:
3417                 return {xml::FT_ITALIC};
3418         case SLANTED_SHAPE:
3419                 return {xml::FT_SLANTED};
3420         case SMALLCAPS_SHAPE:
3421                 return {xml::FT_SMALLCAPS};
3422         case UP_SHAPE:
3423         case INHERIT_SHAPE:
3424                 return {};
3425         default:
3426                 // the other tags are for internal use
3427                 LATTEST(false);
3428                 return {};
3429         }
3430 }
3431
3432 OptionalFontType fontFamilyToXml(FontFamily fm)
3433 {
3434         switch (fm) {
3435         case ROMAN_FAMILY:
3436                 return {xml::FT_ROMAN};
3437         case SANS_FAMILY:
3438                 return {xml::FT_SANS};
3439         case TYPEWRITER_FAMILY:
3440                 return {xml::FT_TYPE};
3441         case INHERIT_FAMILY:
3442                 return {};
3443         default:
3444                 // the other tags are for internal use
3445                 LATTEST(false);
3446                 return {};
3447         }
3448 }
3449
3450 OptionalFontType fontSizeToXml(FontSize fs)
3451 {
3452         switch (fs) {
3453         case TINY_SIZE:
3454                 return {xml::FT_SIZE_TINY};
3455         case SCRIPT_SIZE:
3456                 return {xml::FT_SIZE_SCRIPT};
3457         case FOOTNOTE_SIZE:
3458                 return {xml::FT_SIZE_FOOTNOTE};
3459         case SMALL_SIZE:
3460                 return {xml::FT_SIZE_SMALL};
3461         case LARGE_SIZE:
3462                 return {xml::FT_SIZE_LARGE};
3463         case LARGER_SIZE:
3464                 return {xml::FT_SIZE_LARGER};
3465         case LARGEST_SIZE:
3466                 return {xml::FT_SIZE_LARGEST};
3467         case HUGE_SIZE:
3468                 return {xml::FT_SIZE_HUGE};
3469         case HUGER_SIZE:
3470                 return {xml::FT_SIZE_HUGER};
3471         case INCREASE_SIZE:
3472                 return {xml::FT_SIZE_INCREASE};
3473         case DECREASE_SIZE:
3474                 return {xml::FT_SIZE_DECREASE};
3475         case INHERIT_SIZE:
3476         case NORMAL_SIZE:
3477                 return {};
3478         default:
3479                 // the other tags are for internal use
3480                 LATTEST(false);
3481                 return {};
3482         }
3483 }
3484
3485 struct DocBookFontState
3486 {
3487         FontShape  curr_fs   = INHERIT_SHAPE;
3488         FontFamily curr_fam  = INHERIT_FAMILY;
3489         FontSize   curr_size = INHERIT_SIZE;
3490
3491         // track whether we have opened these tags
3492         bool emph_flag = false;
3493         bool bold_flag = false;
3494         bool noun_flag = false;
3495         bool ubar_flag = false;
3496         bool dbar_flag = false;
3497         bool sout_flag = false;
3498         bool xout_flag = false;
3499         bool wave_flag = false;
3500         // shape tags
3501         bool shap_flag = false;
3502         // family tags
3503         bool faml_flag = false;
3504         // size tags
3505         bool size_flag = false;
3506 };
3507
3508 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3509                                                                                            Font const & font,
3510                                                                                            std::string const & default_family,
3511                                                                                            DocBookFontState & fs)
3512 {
3513         vector<xml::FontTag> tagsToOpen;
3514         vector<xml::EndFontTag> tagsToClose;
3515
3516         // emphasis
3517         FontState curstate = font.fontInfo().emph();
3518         if (font_old.emph() != curstate)
3519                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3520
3521         // noun
3522         curstate = font.fontInfo().noun();
3523         if (font_old.noun() != curstate)
3524                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3525
3526         // underbar
3527         curstate = font.fontInfo().underbar();
3528         if (font_old.underbar() != curstate)
3529                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3530
3531         // strikeout
3532         curstate = font.fontInfo().strikeout();
3533         if (font_old.strikeout() != curstate)
3534                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3535
3536         // xout
3537         curstate = font.fontInfo().xout();
3538         if (font_old.xout() != curstate)
3539                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3540
3541         // double underbar
3542         curstate = font.fontInfo().uuline();
3543         if (font_old.uuline() != curstate)
3544                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3545
3546         // wavy line
3547         curstate = font.fontInfo().uwave();
3548         if (font_old.uwave() != curstate)
3549                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3550
3551         // bold
3552         // a little hackish, but allows us to reuse what we have.
3553         curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3554         if (font_old.series() != font.fontInfo().series())
3555                 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3556
3557         // Font shape
3558         fs.curr_fs = font.fontInfo().shape();
3559         FontShape old_fs = font_old.shape();
3560         if (old_fs != fs.curr_fs) {
3561                 if (fs.shap_flag) {
3562                         OptionalFontType tag = fontShapeToXml(old_fs);
3563                         if (tag.has_value)
3564                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3565                         fs.shap_flag = false;
3566                 }
3567
3568                 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3569                 if (tag.has_value)
3570                         tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3571         }
3572
3573         // Font family
3574         fs.curr_fam = font.fontInfo().family();
3575         FontFamily old_fam = font_old.family();
3576         if (old_fam != fs.curr_fam) {
3577                 if (fs.faml_flag) {
3578                         OptionalFontType tag = fontFamilyToXml(old_fam);
3579                         if (tag.has_value)
3580                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3581                         fs.faml_flag = false;
3582                 }
3583                 switch (fs.curr_fam) {
3584                         case ROMAN_FAMILY:
3585                                 // we will treat a "default" font family as roman, since we have
3586                                 // no other idea what to do.
3587                                 if (default_family != "rmdefault" && default_family != "default") {
3588                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3589                                         fs.faml_flag = true;
3590                                 }
3591                                 break;
3592                         case SANS_FAMILY:
3593                                 if (default_family != "sfdefault") {
3594                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3595                                         fs.faml_flag = true;
3596                                 }
3597                                 break;
3598                         case TYPEWRITER_FAMILY:
3599                                 if (default_family != "ttdefault") {
3600                                         tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3601                                         fs.faml_flag = true;
3602                                 }
3603                                 break;
3604                         case INHERIT_FAMILY:
3605                                 break;
3606                         default:
3607                                 // the other tags are for internal use
3608                                 LATTEST(false);
3609                                 break;
3610                 }
3611         }
3612
3613         // Font size
3614         fs.curr_size = font.fontInfo().size();
3615         FontSize old_size = font_old.size();
3616         if (old_size != fs.curr_size) {
3617                 if (fs.size_flag) {
3618                         OptionalFontType tag = fontSizeToXml(old_size);
3619                         if (tag.has_value)
3620                                 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3621                         fs.size_flag = false;
3622                 }
3623
3624                 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3625                 if (tag.has_value) {
3626                         tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3627                         fs.size_flag = true;
3628                 }
3629         }
3630
3631         return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3632 }
3633
3634 } // anonymous namespace
3635
3636
3637 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3638     Paragraph::simpleDocBookOnePar(Buffer const & buf,
3639                                                       OutputParams const & runparams,
3640                                                       Font const & outerfont,
3641                                                       pos_type initial,
3642                                                       bool is_last_par,
3643                                                       bool ignore_fonts) const
3644 {
3645         // Return values: segregation of the content of this paragraph.
3646         std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3647         std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3648         std::vector<docstring> appendedParagraphs;  // Anything that must be output after the main tag of this paragraph.
3649
3650         // Internal string stream to store the output before being added to one of the previous lists.
3651         odocstringstream os;
3652
3653         // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3654         // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3655         // wrong place.
3656         OutputParams rp = runparams;
3657     for (pos_type i = initial; i < size(); ++i) {
3658         if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3659             const InsetArgument * arg = getInset(i)->asInsetArgument();
3660             if (arg->docbookargumentbeforemaintag()) {
3661                 auto xs_local = XMLStream(os);
3662                 arg->docbook(xs_local, rp);
3663
3664                 prependedParagraphs.push_back(os.str());
3665                 os.str(from_ascii(""));
3666
3667                 rp.docbook_prepended_arguments.insert(arg);
3668             } else if (arg->docbookargumentaftermaintag()) {
3669                 rp.docbook_appended_arguments.insert(arg);
3670             }
3671         }
3672     }
3673
3674     // State variables for the main loop.
3675     auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3676     // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3677     std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3678     // This requires to store delayed characters at some point.
3679
3680         // Track whether we have opened font tags
3681     DocBookFontState fs;
3682     DocBookFontState old_fs = fs;
3683
3684     Layout const & style = *d->layout_;
3685
3686         // Conversion of the font opening/closing into DocBook tags.
3687     vector<xml::FontTag> tagsToOpen;
3688     vector<xml::EndFontTag> tagsToClose;
3689
3690         // Parsing main loop.
3691         for (pos_type i = initial; i < size(); ++i) {
3692             bool ignore_fonts_i = ignore_fonts
3693                               || style.docbooknofontinside()
3694                               || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3695
3696                 // Don't show deleted material in the output.
3697                 if (isDeleted(i))
3698                         continue;
3699
3700                 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3701                 // this paragraph.
3702                 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3703                         if (!ignore_fonts_i)
3704                                 xs->closeFontTags();
3705
3706                         // Output one paragraph (i.e. one string entry in generatedParagraphs).
3707                         generatedParagraphs.push_back(os.str());
3708
3709                         // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3710                         // that the string stream must be reset.
3711                         os.str(from_ascii(""));
3712                         delete xs;
3713                         xs = new XMLStream(os);
3714
3715                         // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3716                         if (!ignore_fonts_i) {
3717                                 fs = old_fs;
3718                         }
3719                 }
3720
3721                 // Determine which tags should be opened or closed regarding fonts.
3722                 FontInfo const font_old = (i == 0 ?
3723                                 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3724                                 getFont(buf.masterBuffer()->params(), i - 1, outerfont).fontInfo());
3725                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3726         tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3727                                 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3728
3729                 if (!ignore_fonts_i) {
3730             vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3731             vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3732             for (; cit != cen; ++cit)
3733                 *xs << *cit;
3734         }
3735
3736         // Deal with the delayed characters *after* closing font tags.
3737         if (!delayedChars.empty()) {
3738             for (const docstring& c: delayedChars)
3739                 *xs << XMLStream::ESCAPE_NONE << c;
3740             delayedChars.clear();
3741         }
3742
3743         if (!ignore_fonts_i) {
3744                         vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3745                         vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3746                         for (; sit != sen; ++sit)
3747                                 *xs << *sit;
3748
3749                         tagsToClose.clear();
3750                         tagsToOpen.clear();
3751                 }
3752
3753         // Finally, write the next character or inset.
3754                 if (Inset const * inset = getInset(i)) {
3755                     bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3756                             rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3757                             rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3758
3759                         if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3760                             // Arguments may need to be output
3761                                 OutputParams np = rp;
3762                                 np.local_font = &font;
3763
3764                                 // TODO: special case will bite here.
3765                                 np.docbook_in_par = true;
3766                                 inset->docbook(*xs, np);
3767                         }
3768                 } else {
3769                         char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3770                         if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3771                                 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3772                                         delayedChars.push_back(from_ascii("&#160;"));
3773                                 } else {
3774                                         delayedChars.emplace_back(1, c);
3775                                 }
3776                         } else { // No need to delay the character.
3777                                 if (c == '\'' && !ignore_fonts)
3778                                         *xs << XMLStream::ESCAPE_NONE << "&#8217;";
3779                                 else
3780                                         *xs << c;
3781                         }
3782                 }
3783         }
3784
3785         // FIXME, this code is just imported from XHTML
3786         // I'm worried about what happens if a branch, say, is itself
3787         // wrapped in some font stuff. I think that will not work.
3788         if (!ignore_fonts)
3789                 xs->closeFontTags();
3790
3791         // Deal with the delayed characters *after* closing font tags.
3792         if (!delayedChars.empty()) {
3793                 for (const docstring &c: delayedChars)
3794                         *xs << XMLStream::ESCAPE_NONE << c;
3795                 delayedChars.clear();
3796         }
3797
3798         // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3799         // last line to get a clean output.
3800         if (rp.docbook_in_listing && !is_last_par)
3801                 *xs << xml::CR();
3802
3803         // Finalise the last (and most likely only) paragraph.
3804         generatedParagraphs.push_back(os.str());
3805     os.str(from_ascii(""));
3806     delete xs;
3807
3808     // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3809     for (pos_type i = initial; i < size(); ++i) {
3810         if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3811             const InsetArgument * arg = getInset(i)->asInsetArgument();
3812             if (arg->docbookargumentaftermaintag()) {
3813                 // Don't use rp, as this argument would not generate anything.
3814                 auto xs_local = XMLStream(os);
3815                 arg->docbook(xs_local, runparams);
3816
3817                 appendedParagraphs.push_back(os.str());
3818                 os.str(from_ascii(""));
3819             }
3820         }
3821     }
3822
3823         return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3824 }
3825
3826
3827 namespace {
3828
3829 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3830                   vector<xml::EndFontTag> & tagsToClose,
3831                   bool & flag, FontState curstate, xml::FontTypes type)
3832 {
3833         if (curstate == FONT_ON) {
3834                 tagsToOpen.push_back(xhtmlStartFontTag(type));
3835                 flag = true;
3836         } else if (flag) {
3837                 tagsToClose.push_back(xhtmlEndFontTag(type));
3838                 flag = false;
3839         }
3840 }
3841
3842 } // anonymous namespace
3843
3844
3845 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3846                                     XMLStream & xs,
3847                                     OutputParams const & runparams,
3848                                     Font const & outerfont,
3849                                     bool start_paragraph, bool close_paragraph,
3850                                     pos_type initial) const
3851 {
3852         docstring retval;
3853
3854         // track whether we have opened these tags
3855         bool emph_flag = false;
3856         bool bold_flag = false;
3857         bool noun_flag = false;
3858         bool ubar_flag = false;
3859         bool dbar_flag = false;
3860         bool sout_flag = false;
3861         bool xout_flag = false;
3862         bool wave_flag = false;
3863         // shape tags
3864         bool shap_flag = false;
3865         // family tags
3866         bool faml_flag = false;
3867         // size tags
3868         bool size_flag = false;
3869
3870         Layout const & style = *d->layout_;
3871
3872         if (start_paragraph)
3873                 xs.startDivision(allowEmpty());
3874
3875         FontInfo font_old =
3876                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3877
3878         FontShape  curr_fs   = INHERIT_SHAPE;
3879         FontFamily curr_fam  = INHERIT_FAMILY;
3880         FontSize   curr_size = INHERIT_SIZE;
3881
3882         string const default_family =
3883                 buf.masterBuffer()->params().fonts_default_family;
3884
3885         vector<xml::FontTag> tagsToOpen;
3886         vector<xml::EndFontTag> tagsToClose;
3887
3888         // parsing main loop
3889         for (pos_type i = initial; i < size(); ++i) {
3890                 // let's not show deleted material in the output
3891                 if (isDeleted(i))
3892                         continue;
3893
3894                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3895
3896                 // emphasis
3897                 FontState curstate = font.fontInfo().emph();
3898                 if (font_old.emph() != curstate)
3899                         doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3900
3901                 // noun
3902                 curstate = font.fontInfo().noun();
3903                 if (font_old.noun() != curstate)
3904                         doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3905
3906                 // underbar
3907                 curstate = font.fontInfo().underbar();
3908                 if (font_old.underbar() != curstate)
3909                         doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3910
3911                 // strikeout
3912                 curstate = font.fontInfo().strikeout();
3913                 if (font_old.strikeout() != curstate)
3914                         doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3915
3916                 // xout
3917                 curstate = font.fontInfo().xout();
3918                 if (font_old.xout() != curstate)
3919                         doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3920
3921                 // double underbar
3922                 curstate = font.fontInfo().uuline();
3923                 if (font_old.uuline() != curstate)
3924                         doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3925
3926                 // wavy line
3927                 curstate = font.fontInfo().uwave();
3928                 if (font_old.uwave() != curstate)
3929                         doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3930
3931                 // bold
3932                 // a little hackish, but allows us to reuse what we have.
3933                 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3934                 if (font_old.series() != font.fontInfo().series())
3935                         doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3936
3937                 // Font shape
3938                 curr_fs = font.fontInfo().shape();
3939                 FontShape old_fs = font_old.shape();
3940                 if (old_fs != curr_fs) {
3941                         if (shap_flag) {
3942                                 switch (old_fs) {
3943                                 case ITALIC_SHAPE:
3944                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3945                                         break;
3946                                 case SLANTED_SHAPE:
3947                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3948                                         break;
3949                                 case SMALLCAPS_SHAPE:
3950                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3951                                         break;
3952                                 case UP_SHAPE:
3953                                 case INHERIT_SHAPE:
3954                                         break;
3955                                 default:
3956                                         // the other tags are for internal use
3957                                         LATTEST(false);
3958                                         break;
3959                                 }
3960                                 shap_flag = false;
3961                         }
3962                         switch (curr_fs) {
3963                         case ITALIC_SHAPE:
3964                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3965                                 shap_flag = true;
3966                                 break;
3967                         case SLANTED_SHAPE:
3968                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3969                                 shap_flag = true;
3970                                 break;
3971                         case SMALLCAPS_SHAPE:
3972                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3973                                 shap_flag = true;
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                 }
3984
3985                 // Font family
3986                 curr_fam = font.fontInfo().family();
3987                 FontFamily old_fam = font_old.family();
3988                 if (old_fam != curr_fam) {
3989                         if (faml_flag) {
3990                                 switch (old_fam) {
3991                                 case ROMAN_FAMILY:
3992                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3993                                         break;
3994                                 case SANS_FAMILY:
3995                                     tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3996                                     break;
3997                                 case TYPEWRITER_FAMILY:
3998                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3999                                         break;
4000                                 case INHERIT_FAMILY:
4001                                         break;
4002                                 default:
4003                                         // the other tags are for internal use
4004                                         LATTEST(false);
4005                                         break;
4006                                 }
4007                                 faml_flag = false;
4008                         }
4009                         switch (curr_fam) {
4010                         case ROMAN_FAMILY:
4011                                 // we will treat a "default" font family as roman, since we have
4012                                 // no other idea what to do.
4013                                 if (default_family != "rmdefault" && default_family != "default") {
4014                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
4015                                         faml_flag = true;
4016                                 }
4017                                 break;
4018                         case SANS_FAMILY:
4019                                 if (default_family != "sfdefault") {
4020                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
4021                                         faml_flag = true;
4022                                 }
4023                                 break;
4024                         case TYPEWRITER_FAMILY:
4025                                 if (default_family != "ttdefault") {
4026                                         tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
4027                                         faml_flag = true;
4028                                 }
4029                                 break;
4030                         case INHERIT_FAMILY:
4031                                 break;
4032                         default:
4033                                 // the other tags are for internal use
4034                                 LATTEST(false);
4035                                 break;
4036                         }
4037                 }
4038
4039                 // Font size
4040                 curr_size = font.fontInfo().size();
4041                 FontSize old_size = font_old.size();
4042                 if (old_size != curr_size) {
4043                         if (size_flag) {
4044                                 switch (old_size) {
4045                                 case TINY_SIZE:
4046                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
4047                                         break;
4048                                 case SCRIPT_SIZE:
4049                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
4050                                         break;
4051                                 case FOOTNOTE_SIZE:
4052                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
4053                                         break;
4054                                 case SMALL_SIZE:
4055                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
4056                                         break;
4057                                 case LARGE_SIZE:
4058                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
4059                                         break;
4060                                 case LARGER_SIZE:
4061                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
4062                                         break;
4063                                 case LARGEST_SIZE:
4064                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
4065                                         break;
4066                                 case HUGE_SIZE:
4067                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
4068                                         break;
4069                                 case HUGER_SIZE:
4070                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
4071                                         break;
4072                                 case INCREASE_SIZE:
4073                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
4074                                         break;
4075                                 case DECREASE_SIZE:
4076                                         tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
4077                                         break;
4078                                 case INHERIT_SIZE:
4079                                 case NORMAL_SIZE:
4080                                         break;
4081                                 default:
4082                                         // the other tags are for internal use
4083                                         LATTEST(false);
4084                                         break;
4085                                 }
4086                                 size_flag = false;
4087                         }
4088                         switch (curr_size) {
4089                         case TINY_SIZE:
4090                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4091                                 size_flag = true;
4092                                 break;
4093                         case SCRIPT_SIZE:
4094                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4095                                 size_flag = true;
4096                                 break;
4097                         case FOOTNOTE_SIZE:
4098                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4099                                 size_flag = true;
4100                                 break;
4101                         case SMALL_SIZE:
4102                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4103                                 size_flag = true;
4104                                 break;
4105                         case LARGE_SIZE:
4106                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4107                                 size_flag = true;
4108                                 break;
4109                         case LARGER_SIZE:
4110                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4111                                 size_flag = true;
4112                                 break;
4113                         case LARGEST_SIZE:
4114                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4115                                 size_flag = true;
4116                                 break;
4117                         case HUGE_SIZE:
4118                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4119                                 size_flag = true;
4120                                 break;
4121                         case HUGER_SIZE:
4122                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4123                                 size_flag = true;
4124                                 break;
4125                         case INCREASE_SIZE:
4126                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4127                                 size_flag = true;
4128                                 break;
4129                         case DECREASE_SIZE:
4130                                 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4131                                 size_flag = true;
4132                                 break;
4133                         case INHERIT_SIZE:
4134                         case NORMAL_SIZE:
4135                                 break;
4136                         default:
4137                                 // the other tags are for internal use
4138                                 LATTEST(false);
4139                                 break;
4140                         }
4141                 }
4142
4143                 // FIXME XHTML
4144                 // Other such tags? What about the other text ranges?
4145
4146                 for (auto const & t : tagsToClose)
4147                         xs << t;
4148                 for (auto const & t : tagsToOpen)
4149                         xs << t;
4150                 tagsToClose.clear();
4151                 tagsToOpen.clear();
4152
4153                 Inset const * inset = getInset(i);
4154                 if (inset) {
4155                         if (!runparams.for_toc || inset->isInToc()) {
4156                                 OutputParams np = runparams;
4157                                 np.local_font = &font;
4158                                 // If the paragraph has size 1, then we are in the "special
4159                                 // case" where we do not output the containing paragraph info
4160                                 if (!inset->getLayout().htmlisblock() && size() != 1)
4161                                         np.html_in_par = true;
4162                                 retval += inset->xhtml(xs, np);
4163                         }
4164                 } else {
4165                         char_type c = getUChar(buf.masterBuffer()->params(),
4166                                                runparams, i);
4167                         if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4168                                 xs << XMLStream::ESCAPE_NONE << "&#160;";
4169                         else if (c == '\'')
4170                                 xs << XMLStream::ESCAPE_NONE << "&#8217;";
4171                         else
4172                                 xs << c;
4173                 }
4174                 font_old = font.fontInfo();
4175         }
4176
4177         // FIXME XHTML
4178         // I'm worried about what happens if a branch, say, is itself
4179         // wrapped in some font stuff. I think that will not work.
4180         xs.closeFontTags();
4181         if (close_paragraph)
4182                 xs.endDivision();
4183
4184         return retval;
4185 }
4186
4187
4188 bool Paragraph::isHfill(pos_type pos) const
4189 {
4190         Inset const * inset = getInset(pos);
4191         return inset && inset->isHfill();
4192 }
4193
4194
4195 bool Paragraph::isNewline(pos_type pos) const
4196 {
4197         // U+2028 LINE SEPARATOR
4198         // U+2029 PARAGRAPH SEPARATOR
4199         char_type const c = d->text_[pos];
4200         if (c == 0x2028 || c == 0x2029)
4201                 return true;
4202         Inset const * inset = getInset(pos);
4203         return inset && inset->lyxCode() == NEWLINE_CODE;
4204 }
4205
4206
4207 bool Paragraph::isEnvSeparator(pos_type pos) const
4208 {
4209         Inset const * inset = getInset(pos);
4210         return inset && inset->lyxCode() == SEPARATOR_CODE;
4211 }
4212
4213
4214 bool Paragraph::isLineSeparator(pos_type pos) const
4215 {
4216         char_type const c = d->text_[pos];
4217         if (isLineSeparatorChar(c))
4218                 return true;
4219         Inset const * inset = getInset(pos);
4220         return inset && inset->isLineSeparator();
4221 }
4222
4223
4224 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4225 {
4226         if (pos == size())
4227                 return true;
4228         if (ignore_deleted && isDeleted(pos))
4229                 return false;
4230         if (Inset const * inset = getInset(pos))
4231                 return !inset->isLetter();
4232         // if we have a hard hyphen (no en- or emdash) or apostrophe
4233         // we pass this to the spell checker
4234         // FIXME: this method is subject to change, visit
4235         // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4236         // to get an impression how complex this is.
4237         if (isHardHyphenOrApostrophe(pos))
4238                 return false;
4239         char_type const c = d->text_[pos];
4240         // We want to pass the escape chars to the spellchecker
4241         docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4242         return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4243 }
4244
4245
4246 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4247 {
4248         pos_type const psize = size();
4249         if (pos >= psize)
4250                 return false;
4251         char_type const c = d->text_[pos];
4252         if (c != '-' && c != '\'')
4253                 return false;
4254         pos_type nextpos = pos + 1;
4255         pos_type prevpos = pos > 0 ? pos - 1 : 0;
4256         if ((nextpos == psize || isSpace(nextpos))
4257                 && (pos == 0 || isSpace(prevpos)))
4258                 return false;
4259         return true;
4260 }
4261
4262
4263 bool Paragraph::needsCProtection(bool const fragile) const
4264 {
4265         // first check the layout of the paragraph, but only in insets
4266         InsetText const * textinset = inInset().asInsetText();
4267         bool const maintext = textinset
4268                 ? textinset->text().isMainText()
4269                 : false;
4270
4271         if (!maintext && layout().needcprotect) {
4272                 // Environments need cprotection regardless the content
4273                 if (layout().latextype == LATEX_ENVIRONMENT)
4274                         return true;
4275
4276                 // Commands need cprotection if they contain specific chars
4277                 int const nchars_escape = 9;
4278                 static char_type const chars_escape[nchars_escape] = {
4279                         '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4280
4281                 docstring const pars = asString();
4282                 for (int k = 0; k < nchars_escape; k++) {
4283                         if (contains(pars, chars_escape[k]))
4284                                 return true;
4285                 }
4286         }
4287
4288         // now check whether we have insets that need cprotection
4289         for (auto const & icit : d->insetlist_) {
4290                 Inset const * ins = icit.inset;
4291                 if (!ins)
4292                         continue;
4293                 if (ins->needsCProtection(maintext, fragile))
4294                         return true;
4295         }
4296
4297         return false;
4298 }
4299
4300
4301 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4302 {
4303         return d->speller_state_.getRange(pos);
4304 }
4305
4306
4307 bool Paragraph::isChar(pos_type pos) const
4308 {
4309         if (Inset const * inset = getInset(pos))
4310                 return inset->isChar();
4311         char_type const c = d->text_[pos];
4312         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4313 }
4314
4315
4316 bool Paragraph::isSpace(pos_type pos) const
4317 {
4318         if (Inset const * inset = getInset(pos))
4319                 return inset->isSpace();
4320         char_type const c = d->text_[pos];
4321         return lyx::isSpace(c);
4322 }
4323
4324
4325 Language const *
4326 Paragraph::getParLanguage(BufferParams const & bparams) const
4327 {
4328         if (!empty())
4329                 return getFirstFontSettings(bparams).language();
4330         // FIXME: we should check the prev par as well (Lgb)
4331         return bparams.language;
4332 }
4333
4334
4335 bool Paragraph::isRTL(BufferParams const & bparams) const
4336 {
4337         return getParLanguage(bparams)->rightToLeft()
4338                 && !inInset().getLayout().forceLTR();
4339 }
4340
4341
4342 void Paragraph::changeLanguage(BufferParams const & bparams,
4343                                Language const * from, Language const * to)
4344 {
4345         // change language including dummy font change at the end
4346         for (pos_type i = 0; i <= size(); ++i) {
4347                 Font font = getFontSettings(bparams, i);
4348                 if (font.language() == from) {
4349                         font.setLanguage(to);
4350                         setFont(i, font);
4351                         d->requestSpellCheck(i);
4352                 }
4353         }
4354 }
4355
4356
4357 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4358 {
4359         Language const * doc_language = bparams.language;
4360         for (auto const & f : d->fontlist_)
4361                 if (f.font().language() != ignore_language &&
4362                     f.font().language() != latex_language &&
4363                     f.font().language() != doc_language)
4364                         return true;
4365         return false;
4366 }
4367
4368
4369 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4370 {
4371         for (auto const & f : d->fontlist_) {
4372                 Language const * lang = f.font().language();
4373                 if (lang != ignore_language &&
4374                     lang != latex_language)
4375                         langs.insert(lang);
4376         }
4377 }
4378
4379
4380 docstring Paragraph::asString(int options) const
4381 {
4382         return asString(0, size(), options);
4383 }
4384
4385
4386 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4387 {
4388         odocstringstream os;
4389
4390         if (beg == 0
4391             && options & AS_STR_LABEL
4392             && d->layout_->labeltype != LABEL_MANUAL
4393             && !d->params_.labelString().empty())
4394                 os << d->params_.labelString() << ' ';
4395
4396         for (pos_type i = beg; i < end; ++i) {
4397                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4398                         continue;
4399                 char_type const c = d->text_[i];
4400                 if (isPrintable(c) || c == '\t'
4401                     || (c == '\n' && (options & AS_STR_NEWLINES)))
4402                         os.put(c);
4403                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4404                         if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4405                                 LASSERT(runparams != nullptr, return docstring());
4406                                 if (runparams->find_effective() && getInset(i)->hasToString())
4407                                         getInset(i)->toString(os);
4408                                 else
4409                                         getInset(i)->plaintext(os, *runparams);
4410                         } else if (c == META_INSET && (options & AS_STR_MATHED)
4411                                    && getInset(i)->lyxCode() == REF_CODE) {
4412                                 Buffer const & buf = getInset(i)->buffer();
4413                                 OutputParams rp(&buf.params().encoding());
4414                                 Font const font(inherit_font, buf.params().language);
4415                                 rp.local_font = &font;
4416                                 otexstream ots(os);
4417                                 getInset(i)->latex(ots, rp);
4418                         } else {
4419                                 getInset(i)->toString(os);
4420                         }
4421                 }
4422         }
4423
4424         return os.str();
4425 }
4426
4427
4428 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4429                             bool const shorten, bool const label) const
4430 {
4431         size_t tmplen = shorten ? maxlen + 1 : maxlen;
4432         if (label && !labelString().empty())
4433                 os += labelString() + ' ';
4434         if (!layout().isTocCaption())
4435                 return;
4436         for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4437                 if (isDeleted(i))
4438                         continue;
4439                 char_type const c = d->text_[i];
4440                 if (isPrintable(c))
4441                         os += c;
4442                 else if (c == META_INSET)
4443                         getInset(i)->forOutliner(os, tmplen, false);
4444         }
4445         if (shorten)
4446                 Text::shortenForOutliner(os, maxlen);
4447 }
4448
4449
4450 void Paragraph::setInsetOwner(Inset const * inset)
4451 {
4452         d->inset_owner_ = inset;
4453 }
4454
4455
4456 int Paragraph::id() const
4457 {
4458         return d->id_;
4459 }
4460
4461
4462 void Paragraph::setId(int id)
4463 {
4464         d->id_ = id;
4465 }
4466
4467
4468 Layout const & Paragraph::layout() const
4469 {
4470         return *d->layout_;
4471 }
4472
4473
4474 void Paragraph::setLayout(Layout const & layout)
4475 {
4476         d->layout_ = &layout;
4477 }
4478
4479
4480 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4481 {
4482         setLayout(tc.defaultLayout());
4483 }
4484
4485
4486 void Paragraph::setPlainLayout(DocumentClass const & tc)
4487 {
4488         setLayout(tc.plainLayout());
4489 }
4490
4491
4492 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4493 {
4494         if (usePlainLayout())
4495                 setPlainLayout(tc);
4496         else
4497                 setDefaultLayout(tc);
4498 }
4499
4500
4501 Inset const & Paragraph::inInset() const
4502 {
4503         LBUFERR(d->inset_owner_);
4504         return *d->inset_owner_;
4505 }
4506
4507
4508 ParagraphParameters & Paragraph::params()
4509 {
4510         return d->params_;
4511 }
4512
4513
4514 ParagraphParameters const & Paragraph::params() const
4515 {
4516         return d->params_;
4517 }
4518
4519
4520 bool Paragraph::isFreeSpacing() const
4521 {
4522         if (d->layout_->free_spacing)
4523                 return true;
4524         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4525 }
4526
4527
4528 bool Paragraph::allowEmpty() const
4529 {
4530         if (d->layout_->keepempty)
4531                 return true;
4532         return d->inset_owner_ && d->inset_owner_->allowEmpty();
4533 }
4534
4535
4536 bool Paragraph::brokenBiblio() const
4537 {
4538         // There is a problem if there is no bibitem at position 0 in
4539         // paragraphs that need one, if there is another bibitem in the
4540         // paragraph or if this paragraph is not supposed to have
4541         // a bibitem inset at all.
4542         return ((d->layout_->labeltype == LABEL_BIBLIO
4543                 && (d->insetlist_.find(BIBITEM_CODE) != 0
4544                     || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4545                 || (d->layout_->labeltype != LABEL_BIBLIO
4546                     && d->insetlist_.find(BIBITEM_CODE) != -1));
4547 }
4548
4549
4550 int Paragraph::fixBiblio(Buffer const & buffer)
4551 {
4552         // FIXME: when there was already an inset at 0, the return value is 1,
4553         // which does not tell whether another inset has been removed; the
4554         // cursor cannot be correctly updated.
4555
4556         bool const track_changes = buffer.params().track_changes;
4557         int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4558
4559         // The case where paragraph is not BIBLIO
4560         if (d->layout_->labeltype != LABEL_BIBLIO) {
4561                 if (bibitem_pos == -1)
4562                         // No InsetBibitem => OK
4563                         return 0;
4564                 // There is an InsetBibitem: remove it!
4565                 d->insetlist_.release(bibitem_pos);
4566                 eraseChar(bibitem_pos, track_changes);
4567                 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4568         }
4569
4570         bool const hasbibitem0 = bibitem_pos == 0;
4571         if (hasbibitem0) {
4572                 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4573                 // There was an InsetBibitem at pos 0,
4574                 // and no other one => OK
4575                 if (bibitem_pos == -1)
4576                         return 0;
4577                 // there is a bibitem at the 0 position, but since
4578                 // there is a second one, we copy the second on the
4579                 // first. We're assuming there are at most two of
4580                 // these, which there should be.
4581                 // FIXME: why does it make sense to do that rather
4582                 // than keep the first? (JMarc)
4583                 Inset * inset = releaseInset(bibitem_pos);
4584                 d->insetlist_.begin()->inset = inset;
4585                 // This needs to be done to update the counter (#8499)
4586                 buffer.updateBuffer();
4587                 return -bibitem_pos;
4588         }
4589
4590         // We need to create an inset at the beginning
4591         Inset * inset = nullptr;
4592         if (bibitem_pos > 0) {
4593                 // there was one somewhere in the paragraph, let's move it
4594                 inset = d->insetlist_.release(bibitem_pos);
4595                 eraseChar(bibitem_pos, track_changes);
4596         } else
4597                 // make a fresh one
4598                 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4599                                          InsetCommandParams(BIBITEM_CODE));
4600
4601         Font font(inherit_font, buffer.params().language);
4602         insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4603                                                    : Change::UNCHANGED));
4604
4605         // This is needed to get the counters right
4606         buffer.updateBuffer();
4607         return 1;
4608 }
4609
4610
4611 void Paragraph::checkAuthors(AuthorList const & authorList)
4612 {
4613         d->changes_.checkAuthors(authorList);
4614 }
4615
4616
4617 bool Paragraph::isChanged(pos_type pos) const
4618 {
4619         return lookupChange(pos).changed();
4620 }
4621
4622
4623 bool Paragraph::isInserted(pos_type pos) const
4624 {
4625         return lookupChange(pos).inserted();
4626 }
4627
4628
4629 bool Paragraph::isDeleted(pos_type pos) const
4630 {
4631         return lookupChange(pos).deleted();
4632 }
4633
4634
4635 InsetList const & Paragraph::insetList() const
4636 {
4637         return d->insetlist_;
4638 }
4639
4640
4641 void Paragraph::setInsetBuffers(Buffer & b)
4642 {
4643         d->insetlist_.setBuffer(b);
4644 }
4645
4646
4647 void Paragraph::resetBuffer()
4648 {
4649         d->insetlist_.resetBuffer();
4650 }
4651
4652
4653 Inset * Paragraph::releaseInset(pos_type pos)
4654 {
4655         Inset * inset = d->insetlist_.release(pos);
4656         /// does not honour change tracking!
4657         eraseChar(pos, false);
4658         return inset;
4659 }
4660
4661
4662 Inset * Paragraph::getInset(pos_type pos)
4663 {
4664         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4665                  ? d->insetlist_.get(pos) : nullptr;
4666 }
4667
4668
4669 Inset const * Paragraph::getInset(pos_type pos) const
4670 {
4671         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4672                  ? d->insetlist_.get(pos) : nullptr;
4673 }
4674
4675
4676 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4677                 pos_type & right, TextCase action)
4678 {
4679         // process sequences of modified characters; in change
4680         // tracking mode, this approach results in much better
4681         // usability than changing case on a char-by-char basis
4682         // We also need to track the current font, since font
4683         // changes within sequences can occur.
4684         vector<pair<char_type, Font> > changes;
4685
4686         bool const trackChanges = bparams.track_changes;
4687
4688         bool capitalize = true;
4689
4690         for (; pos < right; ++pos) {
4691                 char_type oldChar = d->text_[pos];
4692                 char_type newChar = oldChar;
4693
4694                 // ignore insets and don't play with deleted text!
4695                 if (oldChar != META_INSET && !isDeleted(pos)) {
4696                         switch (action) {
4697                                 case text_lowercase:
4698                                         newChar = lowercase(oldChar);
4699                                         break;
4700                                 case text_capitalization:
4701                                         if (capitalize) {
4702                                                 newChar = uppercase(oldChar);
4703                                                 capitalize = false;
4704                                         }
4705                                         break;
4706                                 case text_uppercase:
4707                                         newChar = uppercase(oldChar);
4708                                         break;
4709                         }
4710                 }
4711
4712                 if (isWordSeparator(pos) || isDeleted(pos)) {
4713                         // permit capitalization again
4714                         capitalize = true;
4715                 }
4716
4717                 if (oldChar != newChar) {
4718                         changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4719                         if (pos != right - 1)
4720                                 continue;
4721                         // step behind the changing area
4722                         pos++;
4723                 }
4724
4725                 int erasePos = pos - changes.size();
4726                 for (auto const & change : changes) {
4727                         insertChar(pos, change.first, change.second, trackChanges);
4728                         if (!eraseChar(erasePos, trackChanges)) {
4729                                 ++erasePos;
4730                                 ++pos; // advance
4731                                 ++right; // expand selection
4732                         }
4733                 }
4734                 changes.clear();
4735         }
4736 }
4737
4738 int Paragraph::find(docstring const & str, bool cs, bool mw,
4739                 pos_type start_pos, bool del) const
4740 {
4741         pos_type pos = start_pos;
4742         int const strsize = str.length();
4743         int i = 0;
4744         pos_type const parsize = d->text_.size();
4745         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4746                 // ignore deleted matter
4747                 if (!del && isDeleted(pos)) {
4748                         if (pos == parsize - 1)
4749                                 break;
4750                         pos++;
4751                         --i;
4752                         continue;
4753                 }
4754                 // Ignore "invisible" letters such as ligature breaks
4755                 // and hyphenation chars while searching
4756                 bool nonmatch = false;
4757                 while (pos < parsize && isInset(pos)) {
4758                         Inset const * inset = getInset(pos);
4759                         if (!inset->isLetter() && !inset->isChar())
4760                                 break;
4761                         odocstringstream os;
4762                         if (inset->lyxCode() == lyx::QUOTE_CODE || inset->lyxCode() == lyx::SPACE_CODE) {
4763                                 OutputParams op(0);
4764                                 op.find_set_feature(OutputParams::SearchQuick);
4765                                 inset->plaintext(os, op);
4766                         }
4767                         else {
4768                                 inset->toString(os);
4769                         }
4770                         docstring const insetstring = os.str();
4771                         if (!insetstring.empty()) {
4772                                 int const insetstringsize = insetstring.length();
4773                                 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4774                                         if ((cs && str[i] != insetstring[j])
4775                                             || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4776                                                 nonmatch = true;
4777                                                 break;
4778                                         }
4779                                 }
4780                         }
4781                         pos++;
4782                 }
4783                 if (nonmatch || i == strsize)
4784                         break;
4785                 char_type dp = d->text_[pos];
4786                 if (cs && str[i] != dp)
4787                         break;
4788                 if (!cs && uppercase(str[i]) != uppercase(dp))
4789                         break;
4790         }
4791
4792         if (i != strsize)
4793                 return 0;
4794
4795         // if necessary, check whether string matches word
4796         if (mw) {
4797                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4798                         return 0;
4799                 if (pos < parsize
4800                         && !isWordSeparator(pos))
4801                         return 0;
4802         }
4803
4804         return pos - start_pos;
4805 }
4806
4807
4808 char_type Paragraph::getChar(pos_type pos) const
4809 {
4810         return d->text_[pos];
4811 }
4812
4813
4814 pos_type Paragraph::size() const
4815 {
4816         return d->text_.size();
4817 }
4818
4819
4820 bool Paragraph::empty() const
4821 {
4822         return d->text_.empty();
4823 }
4824
4825
4826 bool Paragraph::isInset(pos_type pos) const
4827 {
4828         return d->text_[pos] == META_INSET;
4829 }
4830
4831
4832 bool Paragraph::isSeparator(pos_type pos) const
4833 {
4834         //FIXME: Are we sure this can be the only separator?
4835         return d->text_[pos] == ' ';
4836 }
4837
4838
4839 void Paragraph::deregisterWords()
4840 {
4841         Private::LangWordsMap::const_iterator itl = d->words_.begin();
4842         Private::LangWordsMap::const_iterator ite = d->words_.end();
4843         for (; itl != ite; ++itl) {
4844                 WordList & wl = theWordList(itl->first);
4845                 Private::Words::const_iterator it = (itl->second).begin();
4846                 Private::Words::const_iterator et = (itl->second).end();
4847                 for (; it != et; ++it)
4848                         wl.remove(*it);
4849         }
4850         d->words_.clear();
4851 }
4852
4853
4854 void Paragraph::locateWord(pos_type & from, pos_type & to,
4855         word_location const loc, bool const ignore_deleted) const
4856 {
4857         switch (loc) {
4858         case WHOLE_WORD_STRICT:
4859                 if (from == 0 || from == size()
4860                     || isWordSeparator(from, ignore_deleted)
4861                     || isWordSeparator(from - 1, ignore_deleted)) {
4862                         to = from;
4863                         return;
4864                 }
4865                 // fall through
4866
4867         case WHOLE_WORD:
4868                 // If we are already at the beginning of a word, do nothing
4869                 if (!from || isWordSeparator(from - 1, ignore_deleted))
4870                         break;
4871                 // fall through
4872
4873         case PREVIOUS_WORD:
4874                 // always move the cursor to the beginning of previous word
4875                 while (from && !isWordSeparator(from - 1, ignore_deleted))
4876                         --from;
4877                 break;
4878         case NEXT_WORD:
4879                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4880                 break;
4881         case PARTIAL_WORD:
4882                 // no need to move the 'from' cursor
4883                 break;
4884         }
4885         to = from;
4886         while (to < size() && !isWordSeparator(to, ignore_deleted))
4887                 ++to;
4888 }
4889
4890
4891 void Paragraph::collectWords()
4892 {
4893         for (pos_type pos = 0; pos < size(); ++pos) {
4894                 if (isWordSeparator(pos))
4895                         continue;
4896                 pos_type from = pos;
4897                 locateWord(from, pos, WHOLE_WORD);
4898                 // Work around MSVC warning: The statement
4899                 // if (pos < from + lyxrc.completion_minlength)
4900                 // triggers a signed vs. unsigned warning.
4901                 // I don't know why this happens, it could be a MSVC bug, or
4902                 // related to LLP64 (windows) vs. LP64 (unix) programming
4903                 // model, or the C++ standard might be ambigous in the section
4904                 // defining the "usual arithmetic conversions". However, using
4905                 // a temporary variable is safe and works on all compilers.
4906                 pos_type const endpos = from + lyxrc.completion_minlength;
4907                 if (pos < endpos)
4908                         continue;
4909                 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4910                 if (cit == d->fontlist_.end())
4911                         return;
4912                 Language const * lang = cit->font().language();
4913                 docstring const word = asString(from, pos, AS_STR_NONE);
4914                 d->words_[lang->lang()].insert(word);
4915         }
4916 }
4917
4918
4919 void Paragraph::registerWords()
4920 {
4921         Private::LangWordsMap::const_iterator itl = d->words_.begin();
4922         Private::LangWordsMap::const_iterator ite = d->words_.end();
4923         for (; itl != ite; ++itl) {
4924                 WordList & wl = theWordList(itl->first);
4925                 Private::Words::const_iterator it = (itl->second).begin();
4926                 Private::Words::const_iterator et = (itl->second).end();
4927                 for (; it != et; ++it)
4928                         wl.insert(*it);
4929         }
4930 }
4931
4932
4933 void Paragraph::updateWords()
4934 {
4935         deregisterWords();
4936         collectWords();
4937         registerWords();
4938 }
4939
4940
4941 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4942 {
4943         SkipPositionsIterator begin = skips.begin();
4944         SkipPositions::iterator end = skips.end();
4945         if (pos > 0 && begin < end) {
4946                 --end;
4947                 if (end->last == pos - 1) {
4948                         end->last = pos;
4949                         return;
4950                 }
4951         }
4952         skips.insert(end, FontSpan(pos, pos));
4953 }
4954
4955
4956 Language * Paragraph::Private::locateSpellRange(
4957         pos_type & from, pos_type & to,
4958         SkipPositions & skips) const
4959 {
4960         // skip leading white space
4961         while (from < to && owner_->isWordSeparator(from))
4962                 ++from;
4963         // don't check empty range
4964         if (from >= to)
4965                 return nullptr;
4966         // get current language
4967         Language * lang = getSpellLanguage(from);
4968         pos_type last = from;
4969         bool samelang = true;
4970         bool sameinset = true;
4971         while (last < to && samelang && sameinset) {
4972                 // hop to end of word
4973                 while (last < to && !owner_->isWordSeparator(last)) {
4974                         Inset const * inset = owner_->getInset(last);
4975                         if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4976                                 // check for "invisible" letters such as ligature breaks
4977                                 odocstringstream os;
4978                                 inset->toString(os);
4979                                 if (os.str().length() != 0) {
4980                                         // avoid spell check of visible special char insets
4981                                         // stop the loop in front of the special char inset
4982                                         sameinset = false;
4983                                         break;
4984                                 }
4985                         } else if (inset) {
4986                                 appendSkipPosition(skips, last);
4987                         } else if (owner_->isDeleted(last)) {
4988                                 appendSkipPosition(skips, last);
4989                         }
4990                         ++last;
4991                 }
4992                 // hop to next word while checking for insets
4993                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4994                         if (Inset const * inset = owner_->getInset(last))
4995                                 sameinset = inset->isChar() && inset->isLetter();
4996                         if (sameinset && owner_->isDeleted(last)) {
4997                                 appendSkipPosition(skips, last);
4998                         }
4999                         if (sameinset)
5000                                 last++;
5001                 }
5002                 if (sameinset && last < to) {
5003                         // now check for language change
5004                         samelang = lang == getSpellLanguage(last);
5005                 }
5006         }
5007         // if language change detected backstep is needed
5008         if (!samelang)
5009                 --last;
5010         to = last;
5011         return lang;
5012 }
5013
5014
5015 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
5016 {
5017         Language * lang =
5018                 const_cast<Language *>(owner_->getFontSettings(
5019                         inset_owner_->buffer().params(), from).language());
5020         if (lang == inset_owner_->buffer().params().language
5021                 && !lyxrc.spellchecker_alt_lang.empty()) {
5022                 string lang_code;
5023                 string const lang_variety =
5024                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
5025                 lang->setCode(lang_code);
5026                 lang->setVariety(lang_variety);
5027         }
5028         return lang;
5029 }
5030
5031
5032 void Paragraph::requestSpellCheck(pos_type pos)
5033 {
5034         d->requestSpellCheck(pos);
5035         if (pos == -1) {
5036                 // Also request spellcheck within (text) insets
5037                 for (auto const & insets : insetList()) {
5038                         if (!insets.inset->asInsetText())
5039                                 continue;
5040                         ParagraphList & inset_pars =
5041                                 insets.inset->asInsetText()->paragraphs();
5042                         ParagraphList::iterator pit = inset_pars.begin();
5043                         ParagraphList::iterator pend = inset_pars.end();
5044                         for (; pit != pend; ++pit)
5045                                 pit->requestSpellCheck();
5046                 }
5047         }
5048 }
5049
5050
5051 bool Paragraph::needsSpellCheck() const
5052 {
5053         SpellChecker::ChangeNumber speller_change_number = 0;
5054         if (theSpellChecker())
5055                 speller_change_number = theSpellChecker()->changeNumber();
5056         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
5057                 d->speller_state_.needsCompleteRefresh(speller_change_number);
5058         }
5059         return d->needsSpellCheck();
5060 }
5061
5062
5063 bool Paragraph::Private::ignoreWord(docstring const & word) const
5064 {
5065         // Ignore words with digits
5066         // FIXME: make this customizable
5067         // (note that some checkers ignore words with digits by default)
5068         docstring::const_iterator cit = word.begin();
5069         docstring::const_iterator const end = word.end();
5070         for (; cit != end; ++cit) {
5071                 if (isNumber((*cit)))
5072                         return true;
5073         }
5074         return false;
5075 }
5076
5077
5078 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
5079         WordLangTuple & wl, docstring_list & suggestions,
5080         bool do_suggestion, bool check_learned) const
5081 {
5082         SpellChecker::Result result = SpellChecker::WORD_OK;
5083         SpellChecker * speller = theSpellChecker();
5084         if (!speller)
5085                 return result;
5086
5087         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
5088                 return result;
5089
5090         locateWord(from, to, WHOLE_WORD, true);
5091         if (from == to || from >= size())
5092                 return result;
5093
5094         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5095         Language * lang = d->getSpellLanguage(from);
5096
5097         BufferParams const & bparams = d->inset_owner_->buffer().params();
5098
5099         if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5100                 return result;
5101
5102         wl = WordLangTuple(word, lang);
5103
5104         if (word.empty())
5105                 return result;
5106
5107         if (needsSpellCheck() || check_learned) {
5108                 pos_type end = to;
5109                 if (!d->ignoreWord(word)) {
5110                         bool const trailing_dot = to < size() && d->text_[to] == '.';
5111                         result = speller->check(wl, bparams.spellignore());
5112                         if (SpellChecker::misspelled(result) && trailing_dot) {
5113                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5114                                 result = speller->check(wl, bparams.spellignore());
5115                                 if (!SpellChecker::misspelled(result)) {
5116                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5117                                            word << "\" [" <<
5118                                            from << ".." << to << "]");
5119                                 } else {
5120                                         // spell check with dot appended failed too
5121                                         // restore original word/lang value
5122                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5123                                         wl = WordLangTuple(word, lang);
5124                                 }
5125                         }
5126                 }
5127                 if (!SpellChecker::misspelled(result)) {
5128                         // area up to the begin of the next word is not misspelled
5129                         while (end < size() && isWordSeparator(end))
5130                                 ++end;
5131                 }
5132                 d->setMisspelled(from, end, result);
5133         } else {
5134                 result = d->speller_state_.getState(from);
5135         }
5136
5137         if (do_suggestion)
5138                 suggestions.clear();
5139
5140         if (SpellChecker::misspelled(result)) {
5141                 LYXERR(Debug::GUI, "misspelled word: \"" <<
5142                            word << "\" [" <<
5143                            from << ".." << to << "]");
5144                 if (do_suggestion)
5145                         speller->suggest(wl, suggestions);
5146         }
5147         return result;
5148 }
5149
5150
5151 void Paragraph::anonymize()
5152 {
5153         // This is a very crude anonymization for now
5154         for (char_type & c : d->text_)
5155                 if (isLetterChar(c) || isNumber(c))
5156                         c = 'a';
5157 }
5158
5159
5160 void Paragraph::Private::markMisspelledWords(
5161         Language const * lang,
5162         pos_type const & first, pos_type const & last,
5163         SpellChecker::Result result,
5164         docstring const & word,
5165         SkipPositions const & skips)
5166 {
5167         if (!SpellChecker::misspelled(result)) {
5168                 setMisspelled(first, last, SpellChecker::WORD_OK);
5169                 return;
5170         }
5171         int snext = first;
5172         SpellChecker * speller = theSpellChecker();
5173         // locate and enumerate the error positions
5174         int nerrors = speller->numMisspelledWords();
5175         int numskipped = 0;
5176         SkipPositionsIterator it = skips.begin();
5177         SkipPositionsIterator et = skips.end();
5178         for (int index = 0; index < nerrors; ++index) {
5179                 int wstart;
5180                 int wlen = 0;
5181                 speller->misspelledWord(index, wstart, wlen);
5182                 /// should not happen if speller supports range checks
5183                 if (!wlen)
5184                         continue;
5185                 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5186                 wstart += first + numskipped;
5187                 if (snext < wstart) {
5188                         /// mark the range of correct spelling
5189                         numskipped += countSkips(it, et, wstart);
5190                         setMisspelled(snext,
5191                                 wstart - 1, SpellChecker::WORD_OK);
5192                 }
5193                 snext = wstart + wlen;
5194                 // Check whether the candidate is in the document's local dict
5195                 SpellChecker::Result actresult = result;
5196                 if (inset_owner_->buffer().params().spellignored(candidate))
5197                         actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5198                 numskipped += countSkips(it, et, snext);
5199                 /// mark the range of misspelling
5200                 setMisspelled(wstart, snext, actresult);
5201                 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5202                         LYXERR(Debug::GUI, "local dictionary word: \"" <<
5203                                    candidate.word() << "\" [" <<
5204                                    wstart << ".." << (snext-1) << "]");
5205                 else
5206                         LYXERR(Debug::GUI, "misspelled word: \"" <<
5207                                    candidate.word() << "\" [" <<
5208                                    wstart << ".." << (snext-1) << "]");
5209                 ++snext;
5210         }
5211         if (snext <= last) {
5212                 /// mark the range of correct spelling at end
5213                 setMisspelled(snext, last, SpellChecker::WORD_OK);
5214         }
5215 }
5216
5217
5218 void Paragraph::spellCheck() const
5219 {
5220         SpellChecker * speller = theSpellChecker();
5221         if (!speller || empty() ||!needsSpellCheck())
5222                 return;
5223         pos_type start;
5224         pos_type endpos;
5225         d->rangeOfSpellCheck(start, endpos);
5226         if (speller->canCheckParagraph()) {
5227                 // loop until we leave the range
5228                 for (pos_type first = start; first < endpos; ) {
5229                         pos_type last = endpos;
5230                         Private::SkipPositions skips;
5231                         Language * lang = d->locateSpellRange(first, last, skips);
5232                         if (first >= endpos)
5233                                 break;
5234                         // start the spell checker on the unit of meaning
5235                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5236                         WordLangTuple wl = WordLangTuple(word, lang);
5237                         BufferParams const & bparams = d->inset_owner_->buffer().params();
5238                         SpellChecker::Result result = !word.empty() ?
5239                                 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5240                         d->markMisspelledWords(lang, first, last, result, word, skips);
5241                         first = ++last;
5242                 }
5243         } else {
5244                 static docstring_list suggestions;
5245                 pos_type to = endpos;
5246                 while (start < endpos) {
5247                         WordLangTuple wl;
5248                         spellCheck(start, to, wl, suggestions, false);
5249                         start = to + 1;
5250                 }
5251         }
5252         d->readySpellCheck();
5253 }
5254
5255
5256 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5257 {
5258         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5259         if (result || pos <= 0 || pos > size())
5260                 return result;
5261         if (check_boundary && (pos == size() || isWordSeparator(pos)))
5262                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5263         return result;
5264 }
5265
5266
5267 string Paragraph::magicLabel() const
5268 {
5269         stringstream ss;
5270         ss << "magicparlabel-" << id();
5271         return ss.str();
5272 }
5273
5274
5275 } // namespace lyx