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