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