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