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