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