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