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