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