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