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