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