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