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