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