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