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