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