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