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