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