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