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