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