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