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