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