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