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