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