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