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