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