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