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