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