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