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