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