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