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