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