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