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