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