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