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