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