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