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