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