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