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