]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Clean up a bit. These comments are no help here.
[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         d->requestSpellCheck(d->text_.size() - 1);
1642 }
1643
1644
1645 void Paragraph::appendString(docstring const & s, Font const & font,
1646                 Change const & change)
1647 {
1648         pos_type end = s.size();
1649         size_t oldsize = d->text_.size();
1650         size_t newsize = oldsize + end;
1651         size_t capacity = d->text_.capacity();
1652         if (newsize >= capacity)
1653                 d->text_.reserve(max(capacity + 100, newsize));
1654
1655         // when appending characters, no need to update tables
1656         d->text_.append(s);
1657
1658         // FIXME: Optimize this!
1659         for (size_t i = oldsize; i != newsize; ++i) {
1660                 // track change
1661                 d->changes_.insert(change, i);
1662                 d->requestSpellCheck(i);
1663         }
1664         d->fontlist_.set(oldsize, font);
1665         d->fontlist_.set(newsize - 1, font);
1666 }
1667
1668
1669 void Paragraph::insertChar(pos_type pos, char_type c,
1670                            bool trackChanges)
1671 {
1672         d->insertChar(pos, c, Change(trackChanges ?
1673                            Change::INSERTED : Change::UNCHANGED));
1674 }
1675
1676
1677 void Paragraph::insertChar(pos_type pos, char_type c,
1678                            Font const & font, bool trackChanges)
1679 {
1680         d->insertChar(pos, c, Change(trackChanges ?
1681                            Change::INSERTED : Change::UNCHANGED));
1682         setFont(pos, font);
1683 }
1684
1685
1686 void Paragraph::insertChar(pos_type pos, char_type c,
1687                            Font const & font, Change const & change)
1688 {
1689         d->insertChar(pos, c, change);
1690         setFont(pos, font);
1691 }
1692
1693
1694 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1695                             Font const & font, Change const & change)
1696 {
1697         bool const success = insertInset(pos, inset, change);
1698         // Set the font/language of the inset...
1699         setFont(pos, font);
1700         return success;
1701 }
1702
1703
1704 void Paragraph::resetFonts(Font const & font)
1705 {
1706         d->fontlist_.clear();
1707         d->fontlist_.set(0, font);
1708         d->fontlist_.set(d->text_.size() - 1, font);
1709 }
1710
1711 // Gets uninstantiated font setting at position.
1712 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1713                                          pos_type pos) const
1714 {
1715         if (pos > size()) {
1716                 LYXERR0("pos: " << pos << " size: " << size());
1717                 LASSERT(pos <= size(), /**/);
1718         }
1719
1720         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1721         if (cit != d->fontlist_.end())
1722                 return cit->font();
1723
1724         if (pos == size() && !empty())
1725                 return getFontSettings(bparams, pos - 1);
1726
1727         // Optimisation: avoid a full font instantiation if there is no
1728         // language change from previous call.
1729         static Font previous_font;
1730         static Language const * previous_lang = 0;
1731         Language const * lang = getParLanguage(bparams);
1732         if (lang != previous_lang) {
1733                 previous_lang = lang;
1734                 previous_font = Font(inherit_font, lang);
1735         }
1736         return previous_font;
1737 }
1738
1739
1740 FontSpan Paragraph::fontSpan(pos_type pos) const
1741 {
1742         LASSERT(pos <= size(), /**/);
1743         pos_type start = 0;
1744
1745         FontList::const_iterator cit = d->fontlist_.begin();
1746         FontList::const_iterator end = d->fontlist_.end();
1747         for (; cit != end; ++cit) {
1748                 if (cit->pos() >= pos) {
1749                         if (pos >= beginOfBody())
1750                                 return FontSpan(max(start, beginOfBody()),
1751                                                 cit->pos());
1752                         else
1753                                 return FontSpan(start,
1754                                                 min(beginOfBody() - 1,
1755                                                          cit->pos()));
1756                 }
1757                 start = cit->pos() + 1;
1758         }
1759
1760         // This should not happen, but if so, we take no chances.
1761         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1762         return FontSpan(pos, pos);
1763 }
1764
1765
1766 // Gets uninstantiated font setting at position 0
1767 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1768 {
1769         if (!empty() && !d->fontlist_.empty())
1770                 return d->fontlist_.begin()->font();
1771
1772         // Optimisation: avoid a full font instantiation if there is no
1773         // language change from previous call.
1774         static Font previous_font;
1775         static Language const * previous_lang = 0;
1776         if (bparams.language != previous_lang) {
1777                 previous_lang = bparams.language;
1778                 previous_font = Font(inherit_font, bparams.language);
1779         }
1780
1781         return previous_font;
1782 }
1783
1784
1785 // Gets the fully instantiated font at a given position in a paragraph
1786 // This is basically the same function as Text::GetFont() in text2.cpp.
1787 // The difference is that this one is used for generating the LaTeX file,
1788 // and thus cosmetic "improvements" are disallowed: This has to deliver
1789 // the true picture of the buffer. (Asger)
1790 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1791                                  Font const & outerfont) const
1792 {
1793         LASSERT(pos >= 0, /**/);
1794
1795         Font font = getFontSettings(bparams, pos);
1796
1797         pos_type const body_pos = beginOfBody();
1798         FontInfo & fi = font.fontInfo();
1799         if (pos < body_pos)
1800                 fi.realize(d->layout_->labelfont);
1801         else
1802                 fi.realize(d->layout_->font);
1803
1804         fi.realize(outerfont.fontInfo());
1805         fi.realize(bparams.getFont().fontInfo());
1806
1807         return font;
1808 }
1809
1810
1811 Font const Paragraph::getLabelFont
1812         (BufferParams const & bparams, Font const & outerfont) const
1813 {
1814         FontInfo tmpfont = d->layout_->labelfont;
1815         tmpfont.realize(outerfont.fontInfo());
1816         tmpfont.realize(bparams.getFont().fontInfo());
1817         return Font(tmpfont, getParLanguage(bparams));
1818 }
1819
1820
1821 Font const Paragraph::getLayoutFont
1822         (BufferParams const & bparams, Font const & outerfont) const
1823 {
1824         FontInfo tmpfont = d->layout_->font;
1825         tmpfont.realize(outerfont.fontInfo());
1826         tmpfont.realize(bparams.getFont().fontInfo());
1827         return Font(tmpfont, getParLanguage(bparams));
1828 }
1829
1830
1831 /// Returns the height of the highest font in range
1832 FontSize Paragraph::highestFontInRange
1833         (pos_type startpos, pos_type endpos, FontSize def_size) const
1834 {
1835         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1836 }
1837
1838
1839 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1840 {
1841         char_type c = d->text_[pos];
1842         if (!lyxrc.rtl_support)
1843                 return c;
1844
1845         char_type uc = c;
1846         switch (c) {
1847         case '(':
1848                 uc = ')';
1849                 break;
1850         case ')':
1851                 uc = '(';
1852                 break;
1853         case '[':
1854                 uc = ']';
1855                 break;
1856         case ']':
1857                 uc = '[';
1858                 break;
1859         case '{':
1860                 uc = '}';
1861                 break;
1862         case '}':
1863                 uc = '{';
1864                 break;
1865         case '<':
1866                 uc = '>';
1867                 break;
1868         case '>':
1869                 uc = '<';
1870                 break;
1871         }
1872         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1873                 return uc;
1874         return c;
1875 }
1876
1877
1878 void Paragraph::setFont(pos_type pos, Font const & font)
1879 {
1880         LASSERT(pos <= size(), /**/);
1881
1882         // First, reduce font against layout/label font
1883         // Update: The setCharFont() routine in text2.cpp already
1884         // reduces font, so we don't need to do that here. (Asger)
1885
1886         d->fontlist_.set(pos, font);
1887 }
1888
1889
1890 void Paragraph::makeSameLayout(Paragraph const & par)
1891 {
1892         d->layout_ = par.d->layout_;
1893         d->params_ = par.d->params_;
1894 }
1895
1896
1897 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1898 {
1899         if (isFreeSpacing())
1900                 return false;
1901
1902         int pos = 0;
1903         int count = 0;
1904
1905         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1906                 if (eraseChar(pos, trackChanges))
1907                         ++count;
1908                 else
1909                         ++pos;
1910         }
1911
1912         return count > 0 || pos > 0;
1913 }
1914
1915
1916 bool Paragraph::hasSameLayout(Paragraph const & par) const
1917 {
1918         return par.d->layout_ == d->layout_
1919                 && d->params_.sameLayout(par.d->params_);
1920 }
1921
1922
1923 depth_type Paragraph::getDepth() const
1924 {
1925         return d->params_.depth();
1926 }
1927
1928
1929 depth_type Paragraph::getMaxDepthAfter() const
1930 {
1931         if (d->layout_->isEnvironment())
1932                 return d->params_.depth() + 1;
1933         else
1934                 return d->params_.depth();
1935 }
1936
1937
1938 char Paragraph::getAlign() const
1939 {
1940         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1941                 return d->layout_->align;
1942         else
1943                 return d->params_.align();
1944 }
1945
1946
1947 docstring const & Paragraph::labelString() const
1948 {
1949         return d->params_.labelString();
1950 }
1951
1952
1953 // the next two functions are for the manual labels
1954 docstring const Paragraph::getLabelWidthString() const
1955 {
1956         if (d->layout_->margintype == MARGIN_MANUAL
1957             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1958                 return d->params_.labelWidthString();
1959         else
1960                 return _("Senseless with this layout!");
1961 }
1962
1963
1964 void Paragraph::setLabelWidthString(docstring const & s)
1965 {
1966         d->params_.labelWidthString(s);
1967 }
1968
1969
1970 docstring Paragraph::expandLabel(Layout const & layout,
1971                 BufferParams const & bparams) const
1972 {
1973         return expandParagraphLabel(layout, bparams, true);
1974 }
1975
1976
1977 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1978                 BufferParams const & bparams) const
1979 {
1980         return expandParagraphLabel(layout, bparams, false);
1981 }
1982
1983
1984 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1985                 BufferParams const & bparams, bool process_appendix) const
1986 {
1987         DocumentClass const & tclass = bparams.documentClass();
1988         string const & lang = getParLanguage(bparams)->code();
1989         bool const in_appendix = process_appendix && d->params_.appendix();
1990         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1991
1992         if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1993             && !layout.counter.empty())
1994                 return tclass.counters().theCounter(layout.counter, lang);
1995
1996         // handle 'inherited level parts' in 'fmt',
1997         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1998         size_t const i = fmt.find('@', 0);
1999         if (i != docstring::npos) {
2000                 size_t const j = fmt.find('@', i + 1);
2001                 if (j != docstring::npos) {
2002                         docstring parent(fmt, i + 1, j - i - 1);
2003                         docstring label = from_ascii("??");
2004                         if (tclass.hasLayout(parent))
2005                                 docstring label = expandParagraphLabel(tclass[parent], bparams,
2006                                                       process_appendix);
2007                         fmt = docstring(fmt, 0, i) + label
2008                                 + docstring(fmt, j + 1, docstring::npos);
2009                 }
2010         }
2011
2012         return tclass.counters().counterLabel(fmt, lang);
2013 }
2014
2015
2016 void Paragraph::applyLayout(Layout const & new_layout)
2017 {
2018         d->layout_ = &new_layout;
2019         LyXAlignment const oldAlign = d->params_.align();
2020
2021         if (!(oldAlign & d->layout_->alignpossible)) {
2022                 frontend::Alert::warning(_("Alignment not permitted"),
2023                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
2024                 d->params_.align(LYX_ALIGN_LAYOUT);
2025         }
2026 }
2027
2028
2029 pos_type Paragraph::beginOfBody() const
2030 {
2031         return d->begin_of_body_;
2032 }
2033
2034
2035 void Paragraph::setBeginOfBody()
2036 {
2037         if (d->layout_->labeltype != LABEL_MANUAL) {
2038                 d->begin_of_body_ = 0;
2039                 return;
2040         }
2041
2042         // Unroll the first two cycles of the loop
2043         // and remember the previous character to
2044         // remove unnecessary getChar() calls
2045         pos_type i = 0;
2046         pos_type end = size();
2047         if (i < end && !isNewline(i)) {
2048                 ++i;
2049                 char_type previous_char = 0;
2050                 char_type temp = 0;
2051                 if (i < end) {
2052                         previous_char = d->text_[i];
2053                         if (!isNewline(i)) {
2054                                 ++i;
2055                                 while (i < end && previous_char != ' ') {
2056                                         temp = d->text_[i];
2057                                         if (isNewline(i))
2058                                                 break;
2059                                         ++i;
2060                                         previous_char = temp;
2061                                 }
2062                         }
2063                 }
2064         }
2065
2066         d->begin_of_body_ = i;
2067 }
2068
2069
2070 bool Paragraph::allowParagraphCustomization() const
2071 {
2072         return inInset().allowParagraphCustomization();
2073 }
2074
2075
2076 bool Paragraph::usePlainLayout() const
2077 {
2078         return inInset().usePlainLayout();
2079 }
2080
2081
2082 bool Paragraph::isPassThru() const
2083 {
2084         return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2085 }
2086
2087 namespace {
2088
2089 // paragraphs inside floats need different alignment tags to avoid
2090 // unwanted space
2091
2092 bool noTrivlistCentering(InsetCode code)
2093 {
2094         return code == FLOAT_CODE
2095                || code == WRAP_CODE
2096                || code == CELL_CODE;
2097 }
2098
2099
2100 string correction(string const & orig)
2101 {
2102         if (orig == "flushleft")
2103                 return "raggedright";
2104         if (orig == "flushright")
2105                 return "raggedleft";
2106         if (orig == "center")
2107                 return "centering";
2108         return orig;
2109 }
2110
2111
2112 string const corrected_env(string const & suffix, string const & env,
2113         InsetCode code, bool const lastpar)
2114 {
2115         string output = suffix + "{";
2116         if (noTrivlistCentering(code)) {
2117                 if (lastpar) {
2118                         // the last paragraph in non-trivlist-aligned
2119                         // context is special (to avoid unwanted whitespace)
2120                         if (suffix == "\\begin")
2121                                 return "\\" + correction(env) + "{}";
2122                         return string();
2123                 }
2124                 output += correction(env);
2125         } else
2126                 output += env;
2127         output += "}";
2128         if (suffix == "\\begin")
2129                 output += "\n";
2130         return output;
2131 }
2132
2133
2134 void adjust_column(string const & str, int & column)
2135 {
2136         if (!contains(str, "\n"))
2137                 column += str.size();
2138         else {
2139                 string tmp;
2140                 column = rsplit(str, tmp, '\n').size();
2141         }
2142 }
2143
2144 } // namespace anon
2145
2146
2147 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2148                         otexstream & os, OutputParams const & runparams) const
2149 {
2150         int column = 0;
2151
2152         if (params_.noindent() && !layout_->pass_thru) {
2153                 os << "\\noindent ";
2154                 column += 10;
2155         }
2156
2157         LyXAlignment const curAlign = params_.align();
2158
2159         if (curAlign == layout_->align)
2160                 return column;
2161
2162         switch (curAlign) {
2163         case LYX_ALIGN_NONE:
2164         case LYX_ALIGN_BLOCK:
2165         case LYX_ALIGN_LAYOUT:
2166         case LYX_ALIGN_SPECIAL:
2167         case LYX_ALIGN_DECIMAL:
2168                 break;
2169         case LYX_ALIGN_LEFT:
2170         case LYX_ALIGN_RIGHT:
2171         case LYX_ALIGN_CENTER:
2172                 if (runparams.moving_arg) {
2173                         os << "\\protect";
2174                         column += 8;
2175                 }
2176                 break;
2177         }
2178
2179         string const begin_tag = "\\begin";
2180         InsetCode code = ownerCode();
2181         bool const lastpar = runparams.isLastPar;
2182
2183         switch (curAlign) {
2184         case LYX_ALIGN_NONE:
2185         case LYX_ALIGN_BLOCK:
2186         case LYX_ALIGN_LAYOUT:
2187         case LYX_ALIGN_SPECIAL:
2188         case LYX_ALIGN_DECIMAL:
2189                 break;
2190         case LYX_ALIGN_LEFT: {
2191                 string output;
2192                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2193                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2194                 else
2195                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2196                 os << from_ascii(output);
2197                 adjust_column(output, column);
2198                 break;
2199         } case LYX_ALIGN_RIGHT: {
2200                 string output;
2201                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2202                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2203                 else
2204                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2205                 os << from_ascii(output);
2206                 adjust_column(output, column);
2207                 break;
2208         } case LYX_ALIGN_CENTER: {
2209                 string output;
2210                 output = corrected_env(begin_tag, "center", code, lastpar);
2211                 os << from_ascii(output);
2212                 adjust_column(output, column);
2213                 break;
2214         }
2215         }
2216
2217         return column;
2218 }
2219
2220
2221 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2222                         otexstream & os, OutputParams const & runparams) const
2223 {
2224         LyXAlignment const curAlign = params_.align();
2225
2226         if (curAlign == layout_->align)
2227                 return false;
2228
2229         switch (curAlign) {
2230         case LYX_ALIGN_NONE:
2231         case LYX_ALIGN_BLOCK:
2232         case LYX_ALIGN_LAYOUT:
2233         case LYX_ALIGN_SPECIAL:
2234         case LYX_ALIGN_DECIMAL:
2235                 break;
2236         case LYX_ALIGN_LEFT:
2237         case LYX_ALIGN_RIGHT:
2238         case LYX_ALIGN_CENTER:
2239                 if (runparams.moving_arg)
2240                         os << "\\protect";
2241                 break;
2242         }
2243
2244         string output;
2245         string const end_tag = "\n\\par\\end";
2246         InsetCode code = ownerCode();
2247         bool const lastpar = runparams.isLastPar;
2248
2249         switch (curAlign) {
2250         case LYX_ALIGN_NONE:
2251         case LYX_ALIGN_BLOCK:
2252         case LYX_ALIGN_LAYOUT:
2253         case LYX_ALIGN_SPECIAL:
2254         case LYX_ALIGN_DECIMAL:
2255                 break;
2256         case LYX_ALIGN_LEFT: {
2257                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2258                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2259                 else
2260                         output = corrected_env(end_tag, "flushright", code, lastpar);
2261                 os << from_ascii(output);
2262                 break;
2263         } case LYX_ALIGN_RIGHT: {
2264                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2265                         output = corrected_env(end_tag, "flushright", code, lastpar);
2266                 else
2267                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2268                 os << from_ascii(output);
2269                 break;
2270         } case LYX_ALIGN_CENTER: {
2271                 output = corrected_env(end_tag, "center", code, lastpar);
2272                 os << from_ascii(output);
2273                 break;
2274         }
2275         }
2276
2277         return !output.empty() || lastpar;
2278 }
2279
2280
2281 // This one spits out the text of the paragraph
2282 void Paragraph::latex(BufferParams const & bparams,
2283         Font const & outerfont,
2284         otexstream & os,
2285         OutputParams const & runparams,
2286         int start_pos, int end_pos, bool force) const
2287 {
2288         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2289
2290         // FIXME This check should not be needed. Perhaps issue an
2291         // error if it triggers.
2292         Layout const & style = inInset().forcePlainLayout() ?
2293                 bparams.documentClass().plainLayout() : *d->layout_;
2294
2295         if (!force && style.inpreamble)
2296                 return;
2297
2298         bool const allowcust = allowParagraphCustomization();
2299
2300         // Current base font for all inherited font changes, without any
2301         // change caused by an individual character, except for the language:
2302         // It is set to the language of the first character.
2303         // As long as we are in the label, this font is the base font of the
2304         // label. Before the first body character it is set to the base font
2305         // of the body.
2306         Font basefont;
2307
2308         // Maybe we have to create a optional argument.
2309         pos_type body_pos = beginOfBody();
2310         unsigned int column = 0;
2311
2312         if (body_pos > 0) {
2313                 // the optional argument is kept in curly brackets in
2314                 // case it contains a ']'
2315                 os << "[{";
2316                 column += 2;
2317                 basefont = getLabelFont(bparams, outerfont);
2318         } else {
2319                 basefont = getLayoutFont(bparams, outerfont);
2320         }
2321
2322         // Which font is currently active?
2323         Font running_font(basefont);
2324         // Do we have an open font change?
2325         bool open_font = false;
2326
2327         Change runningChange = Change(Change::UNCHANGED);
2328
2329         Encoding const * const prev_encoding = runparams.encoding;
2330
2331         os.texrow().start(id(), 0);
2332
2333         // if the paragraph is empty, the loop will not be entered at all
2334         if (empty()) {
2335                 if (style.isCommand()) {
2336                         os << '{';
2337                         ++column;
2338                 }
2339                 if (allowcust)
2340                         column += d->startTeXParParams(bparams, os, runparams);
2341         }
2342
2343         for (pos_type i = 0; i < size(); ++i) {
2344                 // First char in paragraph or after label?
2345                 if (i == body_pos) {
2346                         if (body_pos > 0) {
2347                                 if (open_font) {
2348                                         column += running_font.latexWriteEndChanges(
2349                                                 os, bparams, runparams,
2350                                                 basefont, basefont);
2351                                         open_font = false;
2352                                 }
2353                                 basefont = getLayoutFont(bparams, outerfont);
2354                                 running_font = basefont;
2355
2356                                 column += Changes::latexMarkChange(os, bparams,
2357                                                 runningChange, Change(Change::UNCHANGED),
2358                                                 runparams);
2359                                 runningChange = Change(Change::UNCHANGED);
2360
2361                                 os << "}] ";
2362                                 column +=3;
2363                         }
2364                         if (style.isCommand()) {
2365                                 os << '{';
2366                                 ++column;
2367                         }
2368
2369                         if (allowcust)
2370                                 column += d->startTeXParParams(bparams, os,
2371                                                             runparams);
2372                 }
2373
2374                 Change const & change = runparams.inDeletedInset
2375                         ? runparams.changeOfDeletedInset : lookupChange(i);
2376
2377                 if (bparams.outputChanges && runningChange != change) {
2378                         if (open_font) {
2379                                 column += running_font.latexWriteEndChanges(
2380                                                 os, bparams, runparams, basefont, basefont);
2381                                 open_font = false;
2382                         }
2383                         basefont = getLayoutFont(bparams, outerfont);
2384                         running_font = basefont;
2385
2386                         column += Changes::latexMarkChange(os, bparams, runningChange,
2387                                                            change, runparams);
2388                         runningChange = change;
2389                 }
2390
2391                 // do not output text which is marked deleted
2392                 // if change tracking output is disabled
2393                 if (!bparams.outputChanges && change.deleted()) {
2394                         continue;
2395                 }
2396
2397                 ++column;
2398
2399                 // Fully instantiated font
2400                 Font const font = getFont(bparams, i, outerfont);
2401
2402                 Font const last_font = running_font;
2403
2404                 // Do we need to close the previous font?
2405                 if (open_font &&
2406                     (font != running_font ||
2407                      font.language() != running_font.language()))
2408                 {
2409                         column += running_font.latexWriteEndChanges(
2410                                         os, bparams, runparams, basefont,
2411                                         (i == body_pos-1) ? basefont : font);
2412                         running_font = basefont;
2413                         open_font = false;
2414                 }
2415
2416                 string const running_lang = runparams.use_polyglossia ?
2417                         running_font.language()->polyglossia() : running_font.language()->babel();
2418                 // close babel's font environment before opening CJK.
2419                 string const lang_end_command = runparams.use_polyglossia ?
2420                         "\\end{$$lang}" : lyxrc.language_command_end;
2421                 if (!running_lang.empty() &&
2422                     font.language()->encoding()->package() == Encoding::CJK) {
2423                                 string end_tag = subst(lang_end_command,
2424                                                         "$$lang",
2425                                                         running_lang);
2426                                 os << from_ascii(end_tag);
2427                                 column += end_tag.length();
2428                 }
2429
2430                 // Switch file encoding if necessary (and allowed)
2431                 if (!runparams.pass_thru && !style.pass_thru &&
2432                     runparams.encoding->package() != Encoding::none &&
2433                     font.language()->encoding()->package() != Encoding::none) {
2434                         pair<bool, int> const enc_switch =
2435                                 switchEncoding(os.os(), bparams, runparams,
2436                                         *(font.language()->encoding()));
2437                         if (enc_switch.first) {
2438                                 column += enc_switch.second;
2439                                 runparams.encoding = font.language()->encoding();
2440                         }
2441                 }
2442
2443                 char_type const c = d->text_[i];
2444
2445                 // Do we need to change font?
2446                 if ((font != running_font ||
2447                      font.language() != running_font.language()) &&
2448                         i != body_pos - 1)
2449                 {
2450                         odocstringstream ods;
2451                         column += font.latexWriteStartChanges(ods, bparams,
2452                                                               runparams, basefont,
2453                                                               last_font);
2454                         running_font = font;
2455                         open_font = true;
2456                         docstring fontchange = ods.str();
2457                         // check whether the fontchange ends with a \\textcolor
2458                         // modifier and the text starts with a space (bug 4473)
2459                         docstring const last_modifier = rsplit(fontchange, '\\');
2460                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2461                                 os << fontchange << from_ascii("{}");
2462                         // check if the fontchange ends with a trailing blank
2463                         // (like "\small " (see bug 3382)
2464                         else if (suffixIs(fontchange, ' ') && c == ' ')
2465                                 os << fontchange.substr(0, fontchange.size() - 1)
2466                                    << from_ascii("{}");
2467                         else
2468                                 os << fontchange;
2469                 }
2470
2471                 // FIXME: think about end_pos implementation...
2472                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2473                         // FIXME: integrate this case in latexSpecialChar
2474                         // Do not print the separation of the optional argument
2475                         // if style.pass_thru is false. This works because
2476                         // latexSpecialChar ignores spaces if
2477                         // style.pass_thru is false.
2478                         if (i != body_pos - 1) {
2479                                 if (d->simpleTeXBlanks(runparams, os,
2480                                                 i, column, font, style)) {
2481                                         // A surrogate pair was output. We
2482                                         // must not call latexSpecialChar
2483                                         // in this iteration, since it would output
2484                                         // the combining character again.
2485                                         ++i;
2486                                         continue;
2487                                 }
2488                         }
2489                 }
2490
2491                 OutputParams rp = runparams;
2492                 rp.free_spacing = style.free_spacing;
2493                 rp.local_font = &font;
2494                 rp.intitle = style.intitle;
2495
2496                 // Two major modes:  LaTeX or plain
2497                 // Handle here those cases common to both modes
2498                 // and then split to handle the two modes separately.
2499                 if (c == META_INSET) {
2500                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2501                                 d->latexInset(bparams, os, rp, running_font,
2502                                                 basefont, outerfont, open_font,
2503                                                 runningChange, style, i, column);
2504                         }
2505                 } else {
2506                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2507                                 try {
2508                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2509                                                             style, i, end_pos, column);
2510                                 } catch (EncodingException & e) {
2511                                 if (runparams.dryrun) {
2512                                         os << "<" << _("LyX Warning: ")
2513                                            << _("uncodable character") << " '";
2514                                         os.put(c);
2515                                         os << "'>";
2516                                 } else {
2517                                         // add location information and throw again.
2518                                         e.par_id = id();
2519                                         e.pos = i;
2520                                         throw(e);
2521                                 }
2522                         }
2523                 }
2524                 }
2525
2526                 // Set the encoding to that returned from latexSpecialChar (see
2527                 // comment for encoding member in OutputParams.h)
2528                 runparams.encoding = rp.encoding;
2529         }
2530
2531         // If we have an open font definition, we have to close it
2532         if (open_font) {
2533 #ifdef FIXED_LANGUAGE_END_DETECTION
2534                 if (next_) {
2535                         running_font.latexWriteEndChanges(os, bparams,
2536                                         runparams, basefont,
2537                                         next_->getFont(bparams, 0, outerfont));
2538                 } else {
2539                         running_font.latexWriteEndChanges(os, bparams,
2540                                         runparams, basefont, basefont);
2541                 }
2542 #else
2543 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2544 //FIXME: there as we start another \selectlanguage with the next paragraph if
2545 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2546                 running_font.latexWriteEndChanges(os, bparams, runparams,
2547                                 basefont, basefont);
2548 #endif
2549         }
2550
2551         column += Changes::latexMarkChange(os, bparams, runningChange,
2552                                            Change(Change::UNCHANGED), runparams);
2553
2554         // Needed if there is an optional argument but no contents.
2555         if (body_pos > 0 && body_pos == size()) {
2556                 os << "}]~";
2557         }
2558
2559         if (allowcust && d->endTeXParParams(bparams, os, runparams)
2560             && runparams.encoding != prev_encoding) {
2561                 runparams.encoding = prev_encoding;
2562                 if (!runparams.isFullUnicode())
2563                         os << setEncoding(prev_encoding->iconvName());
2564         }
2565
2566         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2567 }
2568
2569
2570 bool Paragraph::emptyTag() const
2571 {
2572         for (pos_type i = 0; i < size(); ++i) {
2573                 if (Inset const * inset = getInset(i)) {
2574                         InsetCode lyx_code = inset->lyxCode();
2575                         // FIXME testing like that is wrong. What is
2576                         // the intent?
2577                         if (lyx_code != TOC_CODE &&
2578                             lyx_code != INCLUDE_CODE &&
2579                             lyx_code != GRAPHICS_CODE &&
2580                             lyx_code != ERT_CODE &&
2581                             lyx_code != LISTINGS_CODE &&
2582                             lyx_code != FLOAT_CODE &&
2583                             lyx_code != TABULAR_CODE) {
2584                                 return false;
2585                         }
2586                 } else {
2587                         char_type c = d->text_[i];
2588                         if (c != ' ' && c != '\t')
2589                                 return false;
2590                 }
2591         }
2592         return true;
2593 }
2594
2595
2596 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2597         const
2598 {
2599         for (pos_type i = 0; i < size(); ++i) {
2600                 if (Inset const * inset = getInset(i)) {
2601                         InsetCode lyx_code = inset->lyxCode();
2602                         if (lyx_code == LABEL_CODE) {
2603                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2604                                 docstring const & id = il->getParam("name");
2605                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2606                         }
2607                 }
2608         }
2609         return string();
2610 }
2611
2612
2613 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2614         const
2615 {
2616         pos_type i;
2617         for (i = 0; i < size(); ++i) {
2618                 if (Inset const * inset = getInset(i)) {
2619                         inset->docbook(os, runparams);
2620                 } else {
2621                         char_type c = d->text_[i];
2622                         if (c == ' ')
2623                                 break;
2624                         os << sgml::escapeChar(c);
2625                 }
2626         }
2627         return i;
2628 }
2629
2630
2631 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2632         const
2633 {
2634         pos_type i;
2635         for (i = 0; i < size(); ++i) {
2636                 if (Inset const * inset = getInset(i)) {
2637                         inset->xhtml(xs, runparams);
2638                 } else {
2639                         char_type c = d->text_[i];
2640                         if (c == ' ')
2641                                 break;
2642                         xs << c;
2643                 }
2644         }
2645         return i;
2646 }
2647
2648
2649 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2650 {
2651         Font font_old;
2652         pos_type size = text_.size();
2653         for (pos_type i = initial; i < size; ++i) {
2654                 Font font = owner_->getFont(buf.params(), i, outerfont);
2655                 if (text_[i] == META_INSET)
2656                         return false;
2657                 if (i != initial && font != font_old)
2658                         return false;
2659                 font_old = font;
2660         }
2661
2662         return true;
2663 }
2664
2665
2666 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2667                                     odocstream & os,
2668                                     OutputParams const & runparams,
2669                                     Font const & outerfont,
2670                                     pos_type initial) const
2671 {
2672         bool emph_flag = false;
2673
2674         Layout const & style = *d->layout_;
2675         FontInfo font_old =
2676                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2677
2678         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2679                 os << "]]>";
2680
2681         // parsing main loop
2682         for (pos_type i = initial; i < size(); ++i) {
2683                 Font font = getFont(buf.params(), i, outerfont);
2684
2685                 // handle <emphasis> tag
2686                 if (font_old.emph() != font.fontInfo().emph()) {
2687                         if (font.fontInfo().emph() == FONT_ON) {
2688                                 os << "<emphasis>";
2689                                 emph_flag = true;
2690                         } else if (i != initial) {
2691                                 os << "</emphasis>";
2692                                 emph_flag = false;
2693                         }
2694                 }
2695
2696                 if (Inset const * inset = getInset(i)) {
2697                         inset->docbook(os, runparams);
2698                 } else {
2699                         char_type c = d->text_[i];
2700
2701                         if (style.pass_thru)
2702                                 os.put(c);
2703                         else
2704                                 os << sgml::escapeChar(c);
2705                 }
2706                 font_old = font.fontInfo();
2707         }
2708
2709         if (emph_flag) {
2710                 os << "</emphasis>";
2711         }
2712
2713         if (style.free_spacing)
2714                 os << '\n';
2715         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2716                 os << "<![CDATA[";
2717 }
2718
2719
2720 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2721                                     XHTMLStream & xs,
2722                                     OutputParams const & runparams,
2723                                     Font const & outerfont,
2724                                     pos_type initial) const
2725 {
2726         docstring retval;
2727
2728         bool emph_flag = false;
2729         bool bold_flag = false;
2730
2731         Layout const & style = *d->layout_;
2732
2733         xs.startParagraph(allowEmpty());
2734
2735         if (!runparams.for_toc && runparams.html_make_pars) {
2736                 // generate a magic label for this paragraph
2737                 string const attr = "id='" + magicLabel() + "'";
2738                 xs << html::CompTag("a", attr);
2739         }
2740
2741         FontInfo font_old =
2742                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2743
2744         // parsing main loop
2745         for (pos_type i = initial; i < size(); ++i) {
2746                 // let's not show deleted material in the output
2747                 if (isDeleted(i))
2748                         continue;
2749
2750                 Font font = getFont(buf.params(), i, outerfont);
2751
2752                 // emphasis
2753                 if (font_old.emph() != font.fontInfo().emph()) {
2754                         if (font.fontInfo().emph() == FONT_ON) {
2755                                 xs << html::StartTag("em");
2756                                 emph_flag = true;
2757                         } else if (emph_flag && i != initial) {
2758                                 xs << html::EndTag("em");
2759                                 emph_flag = false;
2760                         }
2761                 }
2762                 // bold
2763                 if (font_old.series() != font.fontInfo().series()) {
2764                         if (font.fontInfo().series() == BOLD_SERIES) {
2765                                 xs << html::StartTag("strong");
2766                                 bold_flag = true;
2767                         } else if (bold_flag && i != initial) {
2768                                 xs << html::EndTag("strong");
2769                                 bold_flag = false;
2770                         }
2771                 }
2772                 // FIXME XHTML
2773                 // Other such tags? What about the other text ranges?
2774
2775                 Inset const * inset = getInset(i);
2776                 if (inset) {
2777                         if (!runparams.for_toc || inset->isInToc()) {
2778                                 OutputParams np = runparams;
2779                                 if (!inset->getLayout().htmlisblock())
2780                                         np.html_in_par = true;
2781                                 retval += inset->xhtml(xs, np);
2782                         }
2783                 } else {
2784                         char_type c = d->text_[i];
2785
2786                         if (style.pass_thru)
2787                                 xs << c;
2788                         else if (c == '-') {
2789                                 docstring str;
2790                                 int j = i + 1;
2791                                 if (j < size() && d->text_[j] == '-') {
2792                                         j += 1;
2793                                         if (j < size() && d->text_[j] == '-') {
2794                                                 str += from_ascii("&mdash;");
2795                                                 i += 2;
2796                                         } else {
2797                                                 str += from_ascii("&ndash;");
2798                                                 i += 1;
2799                                         }
2800                                 }
2801                                 else
2802                                         str += c;
2803                                 // We don't want to escape the entities. Note that
2804                                 // it is safe to do this, since str can otherwise
2805                                 // only be "-". E.g., it can't be "<".
2806                                 xs << XHTMLStream::ESCAPE_NONE << str;
2807                         } else
2808                                 xs << c;
2809                 }
2810                 font_old = font.fontInfo();
2811         }
2812
2813         xs.closeFontTags();
2814         xs.endParagraph();
2815         return retval;
2816 }
2817
2818
2819 bool Paragraph::isHfill(pos_type pos) const
2820 {
2821         Inset const * inset = getInset(pos);
2822         return inset && (inset->lyxCode() == SPACE_CODE &&
2823                          inset->isStretchableSpace());
2824 }
2825
2826
2827 bool Paragraph::isNewline(pos_type pos) const
2828 {
2829         Inset const * inset = getInset(pos);
2830         return inset && inset->lyxCode() == NEWLINE_CODE;
2831 }
2832
2833
2834 bool Paragraph::isLineSeparator(pos_type pos) const
2835 {
2836         char_type const c = d->text_[pos];
2837         if (isLineSeparatorChar(c))
2838                 return true;
2839         Inset const * inset = getInset(pos);
2840         return inset && inset->isLineSeparator();
2841 }
2842
2843
2844 bool Paragraph::isWordSeparator(pos_type pos) const
2845 {
2846         if (pos == size())
2847                 return true;
2848         if (Inset const * inset = getInset(pos))
2849                 return !inset->isLetter();
2850         // if we have a hard hyphen (no en- or emdash) or apostrophe
2851         // we pass this to the spell checker
2852         // FIXME: this method is subject to change, visit
2853         // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2854         // to get an impression how complex this is.
2855         if (isHardHyphenOrApostrophe(pos))
2856                 return false;
2857         char_type const c = d->text_[pos];
2858         // We want to pass the escape chars to the spellchecker
2859         docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2860         return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2861 }
2862
2863
2864 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2865 {
2866         pos_type const psize = size();
2867         if (pos >= psize)
2868                 return false;
2869         char_type const c = d->text_[pos];
2870         if (c != '-' && c != '\'')
2871                 return false;
2872         int nextpos = pos + 1;
2873         int prevpos = pos > 0 ? pos - 1 : 0;
2874         if ((nextpos == psize || isSpace(nextpos))
2875                 && (pos == 0 || isSpace(prevpos)))
2876                 return false;
2877         return c == '\''
2878                 || ((nextpos == psize || d->text_[nextpos] != '-')
2879                 && (pos == 0 || d->text_[prevpos] != '-'));
2880 }
2881
2882
2883 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2884 {
2885         return pos1 == pos2
2886                 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2887 }
2888
2889
2890 bool Paragraph::isChar(pos_type pos) const
2891 {
2892         if (Inset const * inset = getInset(pos))
2893                 return inset->isChar();
2894         char_type const c = d->text_[pos];
2895         return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2896 }
2897
2898
2899 bool Paragraph::isSpace(pos_type pos) const
2900 {
2901         if (Inset const * inset = getInset(pos))
2902                 return inset->isSpace();
2903         char_type const c = d->text_[pos];
2904         return lyx::isSpace(c);
2905 }
2906
2907
2908 Language const *
2909 Paragraph::getParLanguage(BufferParams const & bparams) const
2910 {
2911         if (!empty())
2912                 return getFirstFontSettings(bparams).language();
2913         // FIXME: we should check the prev par as well (Lgb)
2914         return bparams.language;
2915 }
2916
2917
2918 bool Paragraph::isRTL(BufferParams const & bparams) const
2919 {
2920         return lyxrc.rtl_support
2921                 && getParLanguage(bparams)->rightToLeft()
2922                 && !inInset().getLayout().forceLTR();
2923 }
2924
2925
2926 void Paragraph::changeLanguage(BufferParams const & bparams,
2927                                Language const * from, Language const * to)
2928 {
2929         // change language including dummy font change at the end
2930         for (pos_type i = 0; i <= size(); ++i) {
2931                 Font font = getFontSettings(bparams, i);
2932                 if (font.language() == from) {
2933                         font.setLanguage(to);
2934                         setFont(i, font);
2935                         d->requestSpellCheck(i);
2936                 }
2937         }
2938 }
2939
2940
2941 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2942 {
2943         Language const * doc_language = bparams.language;
2944         FontList::const_iterator cit = d->fontlist_.begin();
2945         FontList::const_iterator end = d->fontlist_.end();
2946
2947         for (; cit != end; ++cit)
2948                 if (cit->font().language() != ignore_language &&
2949                     cit->font().language() != latex_language &&
2950                     cit->font().language() != doc_language)
2951                         return true;
2952         return false;
2953 }
2954
2955
2956 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2957 {
2958         FontList::const_iterator cit = d->fontlist_.begin();
2959         FontList::const_iterator end = d->fontlist_.end();
2960
2961         for (; cit != end; ++cit) {
2962                 Language const * lang = cit->font().language();
2963                 if (lang != ignore_language &&
2964                     lang != latex_language)
2965                         languages.insert(lang);
2966         }
2967 }
2968
2969
2970 docstring Paragraph::asString(int options) const
2971 {
2972         return asString(0, size(), options);
2973 }
2974
2975
2976 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2977 {
2978         odocstringstream os;
2979
2980         if (beg == 0
2981             && options & AS_STR_LABEL
2982             && !d->params_.labelString().empty())
2983                 os << d->params_.labelString() << ' ';
2984
2985         for (pos_type i = beg; i < end; ++i) {
2986                 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2987                         continue;
2988                 char_type const c = d->text_[i];
2989                 if (isPrintable(c) || c == '\t'
2990                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2991                         os.put(c);
2992                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2993                         getInset(i)->toString(os);
2994                         if (getInset(i)->asInsetMath())
2995                                 os << " ";
2996                 }
2997         }
2998
2999         return os.str();
3000 }
3001
3002
3003 void Paragraph::forToc(docstring & os, size_t maxlen) const
3004 {
3005         if (!d->params_.labelString().empty())
3006                 os += d->params_.labelString() + ' ';
3007         for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3008                 if (isDeleted(i))
3009                         continue;
3010                 char_type const c = d->text_[i];
3011                 if (isPrintable(c))
3012                         os += c;
3013                 else if (c == '\t' || c == '\n')
3014                         os += ' ';
3015                 else if (c == META_INSET)
3016                         getInset(i)->forToc(os, maxlen);
3017         }
3018 }
3019
3020
3021 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3022 {
3023         odocstringstream os;
3024
3025         if (beg == 0
3026                 && options & AS_STR_LABEL
3027                 && !d->params_.labelString().empty())
3028                 os << d->params_.labelString() << ' ';
3029
3030         for (pos_type i = beg; i < end; ++i) {
3031                 char_type const c = d->text_[i];
3032                 if (isPrintable(c) || c == '\t'
3033                     || (c == '\n' && (options & AS_STR_NEWLINES)))
3034                         os.put(c);
3035                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3036                         getInset(i)->plaintext(os, runparams);
3037                 }
3038         }
3039
3040         return os.str();
3041 }
3042
3043
3044 void Paragraph::setInsetOwner(Inset const * inset)
3045 {
3046         d->inset_owner_ = inset;
3047 }
3048
3049
3050 int Paragraph::id() const
3051 {
3052         return d->id_;
3053 }
3054
3055
3056 void Paragraph::setId(int id)
3057 {
3058         d->id_ = id;
3059 }
3060
3061
3062 Layout const & Paragraph::layout() const
3063 {
3064         return *d->layout_;
3065 }
3066
3067
3068 void Paragraph::setLayout(Layout const & layout)
3069 {
3070         d->layout_ = &layout;
3071 }
3072
3073
3074 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3075 {
3076         setLayout(tc.defaultLayout());
3077 }
3078
3079
3080 void Paragraph::setPlainLayout(DocumentClass const & tc)
3081 {
3082         setLayout(tc.plainLayout());
3083 }
3084
3085
3086 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3087 {
3088         if (usePlainLayout())
3089                 setPlainLayout(tclass);
3090         else
3091                 setDefaultLayout(tclass);
3092 }
3093
3094
3095 Inset const & Paragraph::inInset() const
3096 {
3097         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3098                 _("Memory problem"), _("Paragraph not properly initialized")));
3099         return *d->inset_owner_;
3100 }
3101
3102
3103 ParagraphParameters & Paragraph::params()
3104 {
3105         return d->params_;
3106 }
3107
3108
3109 ParagraphParameters const & Paragraph::params() const
3110 {
3111         return d->params_;
3112 }
3113
3114
3115 bool Paragraph::isFreeSpacing() const
3116 {
3117         if (d->layout_->free_spacing)
3118                 return true;
3119         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3120 }
3121
3122
3123 bool Paragraph::allowEmpty() const
3124 {
3125         if (d->layout_->keepempty)
3126                 return true;
3127         return d->inset_owner_ && d->inset_owner_->allowEmpty();
3128 }
3129
3130
3131 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3132 {
3133         if (!Encodings::isArabicChar(c))
3134                 return c;
3135
3136         char_type prev_char = ' ';
3137         char_type next_char = ' ';
3138
3139         for (pos_type i = pos - 1; i >= 0; --i) {
3140                 char_type const par_char = d->text_[i];
3141                 if (!Encodings::isArabicComposeChar(par_char)) {
3142                         prev_char = par_char;
3143                         break;
3144                 }
3145         }
3146
3147         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3148                 char_type const par_char = d->text_[i];
3149                 if (!Encodings::isArabicComposeChar(par_char)) {
3150                         next_char = par_char;
3151                         break;
3152                 }
3153         }
3154
3155         if (Encodings::isArabicChar(next_char)) {
3156                 if (Encodings::isArabicChar(prev_char) &&
3157                         !Encodings::isArabicSpecialChar(prev_char))
3158                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3159                 else
3160                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3161         } else {
3162                 if (Encodings::isArabicChar(prev_char) &&
3163                         !Encodings::isArabicSpecialChar(prev_char))
3164                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
3165                 else
3166                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3167         }
3168 }
3169
3170
3171 int Paragraph::checkBiblio(Buffer const & buffer)
3172 {
3173         // FIXME From JS:
3174         // This is getting more and more a mess. ...We really should clean
3175         // up this bibitem issue for 1.6.
3176
3177         // Add bibitem insets if necessary
3178         if (d->layout_->labeltype != LABEL_BIBLIO)
3179                 return 0;
3180
3181         bool hasbibitem = !d->insetlist_.empty()
3182                 // Insist on it being in pos 0
3183                 && d->text_[0] == META_INSET
3184                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3185
3186         bool track_changes = buffer.params().trackChanges;
3187
3188         docstring oldkey;
3189         docstring oldlabel;
3190
3191         // remove a bibitem in pos != 0
3192         // restore it later in pos 0 if necessary
3193         // (e.g. if a user inserts contents _before_ the item)
3194         // we're assuming there's only one of these, which there
3195         // should be.
3196         int erasedInsetPosition = -1;
3197         InsetList::iterator it = d->insetlist_.begin();
3198         InsetList::iterator end = d->insetlist_.end();
3199         for (; it != end; ++it)
3200                 if (it->inset->lyxCode() == BIBITEM_CODE
3201                       && it->pos > 0) {
3202                         InsetCommand * olditem = it->inset->asInsetCommand();
3203                         oldkey = olditem->getParam("key");
3204                         oldlabel = olditem->getParam("label");
3205                         erasedInsetPosition = it->pos;
3206                         eraseChar(erasedInsetPosition, track_changes);
3207                         break;
3208         }
3209
3210         // There was an InsetBibitem at the beginning, and we didn't
3211         // have to erase one.
3212         if (hasbibitem && erasedInsetPosition < 0)
3213                         return 0;
3214
3215         // There was an InsetBibitem at the beginning and we did have to
3216         // erase one. So we give its properties to the beginning inset.
3217         if (hasbibitem) {
3218                 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3219                 if (!oldkey.empty())
3220                         inset->setParam("key", oldkey);
3221                 inset->setParam("label", oldlabel);
3222                 return -erasedInsetPosition;
3223         }
3224
3225         // There was no inset at the beginning, so we need to create one with
3226         // the key and label of the one we erased.
3227         InsetBibitem * inset =
3228                 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3229         // restore values of previously deleted item in this par.
3230         if (!oldkey.empty())
3231                 inset->setParam("key", oldkey);
3232         inset->setParam("label", oldlabel);
3233         insertInset(0, inset,
3234                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3235
3236         return 1;
3237 }
3238
3239
3240 void Paragraph::checkAuthors(AuthorList const & authorList)
3241 {
3242         d->changes_.checkAuthors(authorList);
3243 }
3244
3245
3246 bool Paragraph::isChanged(pos_type pos) const
3247 {
3248         return lookupChange(pos).changed();
3249 }
3250
3251
3252 bool Paragraph::isInserted(pos_type pos) const
3253 {
3254         return lookupChange(pos).inserted();
3255 }
3256
3257
3258 bool Paragraph::isDeleted(pos_type pos) const
3259 {
3260         return lookupChange(pos).deleted();
3261 }
3262
3263
3264 InsetList const & Paragraph::insetList() const
3265 {
3266         return d->insetlist_;
3267 }
3268
3269
3270 void Paragraph::setBuffer(Buffer & b)
3271 {
3272         d->insetlist_.setBuffer(b);
3273 }
3274
3275
3276 Inset * Paragraph::releaseInset(pos_type pos)
3277 {
3278         Inset * inset = d->insetlist_.release(pos);
3279         /// does not honour change tracking!
3280         eraseChar(pos, false);
3281         return inset;
3282 }
3283
3284
3285 Inset * Paragraph::getInset(pos_type pos)
3286 {
3287         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3288                  ? d->insetlist_.get(pos) : 0;
3289 }
3290
3291
3292 Inset const * Paragraph::getInset(pos_type pos) const
3293 {
3294         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3295                  ? d->insetlist_.get(pos) : 0;
3296 }
3297
3298
3299 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3300                 pos_type & right, TextCase action)
3301 {
3302         // process sequences of modified characters; in change
3303         // tracking mode, this approach results in much better
3304         // usability than changing case on a char-by-char basis
3305         docstring changes;
3306
3307         bool const trackChanges = bparams.trackChanges;
3308
3309         bool capitalize = true;
3310
3311         for (; pos < right; ++pos) {
3312                 char_type oldChar = d->text_[pos];
3313                 char_type newChar = oldChar;
3314
3315                 // ignore insets and don't play with deleted text!
3316                 if (oldChar != META_INSET && !isDeleted(pos)) {
3317                         switch (action) {
3318                                 case text_lowercase:
3319                                         newChar = lowercase(oldChar);
3320                                         break;
3321                                 case text_capitalization:
3322                                         if (capitalize) {
3323                                                 newChar = uppercase(oldChar);
3324                                                 capitalize = false;
3325                                         }
3326                                         break;
3327                                 case text_uppercase:
3328                                         newChar = uppercase(oldChar);
3329                                         break;
3330                         }
3331                 }
3332
3333                 if (isWordSeparator(pos) || isDeleted(pos)) {
3334                         // permit capitalization again
3335                         capitalize = true;
3336                 }
3337
3338                 if (oldChar != newChar) {
3339                         changes += newChar;
3340                         if (pos != right - 1)
3341                                 continue;
3342                         // step behind the changing area
3343                         pos++;
3344                 }
3345
3346                 int erasePos = pos - changes.size();
3347                 for (size_t i = 0; i < changes.size(); i++) {
3348                         insertChar(pos, changes[i],
3349                                    getFontSettings(bparams,
3350                                                    erasePos),
3351                                    trackChanges);
3352                         if (!eraseChar(erasePos, trackChanges)) {
3353                                 ++erasePos;
3354                                 ++pos; // advance
3355                                 ++right; // expand selection
3356                         }
3357                 }
3358                 changes.clear();
3359         }
3360 }
3361
3362
3363 int Paragraph::find(docstring const & str, bool cs, bool mw,
3364                 pos_type start_pos, bool del) const
3365 {
3366         pos_type pos = start_pos;
3367         int const strsize = str.length();
3368         int i = 0;
3369         pos_type const parsize = d->text_.size();
3370         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3371                 // Ignore "invisible" letters such as ligature breaks
3372                 // and hyphenation chars while searching
3373                 while (pos < parsize - 1 && isInset(pos)) {
3374                         odocstringstream os;
3375                         getInset(pos)->toString(os);
3376                         if (!getInset(pos)->isLetter() || !os.str().empty())
3377                                 break;
3378                         pos++;
3379                 }
3380                 if (cs && str[i] != d->text_[pos])
3381                         break;
3382                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3383                         break;
3384                 if (!del && isDeleted(pos))
3385                         break;
3386         }
3387
3388         if (i != strsize)
3389                 return 0;
3390
3391         // if necessary, check whether string matches word
3392         if (mw) {
3393                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3394                         return 0;
3395                 if (pos < parsize
3396                         && !isWordSeparator(pos))
3397                         return 0;
3398         }
3399
3400         return pos - start_pos;
3401 }
3402
3403
3404 char_type Paragraph::getChar(pos_type pos) const
3405 {
3406         return d->text_[pos];
3407 }
3408
3409
3410 pos_type Paragraph::size() const
3411 {
3412         return d->text_.size();
3413 }
3414
3415
3416 bool Paragraph::empty() const
3417 {
3418         return d->text_.empty();
3419 }
3420
3421
3422 bool Paragraph::isInset(pos_type pos) const
3423 {
3424         return d->text_[pos] == META_INSET;
3425 }
3426
3427
3428 bool Paragraph::isSeparator(pos_type pos) const
3429 {
3430         //FIXME: Are we sure this can be the only separator?
3431         return d->text_[pos] == ' ';
3432 }
3433
3434
3435 void Paragraph::deregisterWords()
3436 {
3437         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3438         Private::LangWordsMap::const_iterator ite = d->words_.end();
3439         for (; itl != ite; ++itl) {
3440                 WordList * wl = theWordList(itl->first);
3441                 Private::Words::const_iterator it = (itl->second).begin();
3442                 Private::Words::const_iterator et = (itl->second).end();
3443                 for (; it != et; ++it)
3444                         wl->remove(*it);
3445         }
3446         d->words_.clear();
3447 }
3448
3449
3450 void Paragraph::locateWord(pos_type & from, pos_type & to,
3451         word_location const loc) const
3452 {
3453         switch (loc) {
3454         case WHOLE_WORD_STRICT:
3455                 if (from == 0 || from == size()
3456                     || isWordSeparator(from)
3457                     || isWordSeparator(from - 1)) {
3458                         to = from;
3459                         return;
3460                 }
3461                 // no break here, we go to the next
3462
3463         case WHOLE_WORD:
3464                 // If we are already at the beginning of a word, do nothing
3465                 if (!from || isWordSeparator(from - 1))
3466                         break;
3467                 // no break here, we go to the next
3468
3469         case PREVIOUS_WORD:
3470                 // always move the cursor to the beginning of previous word
3471                 while (from && !isWordSeparator(from - 1))
3472                         --from;
3473                 break;
3474         case NEXT_WORD:
3475                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3476                 break;
3477         case PARTIAL_WORD:
3478                 // no need to move the 'from' cursor
3479                 break;
3480         }
3481         to = from;
3482         while (to < size() && !isWordSeparator(to))
3483                 ++to;
3484 }
3485
3486
3487 void Paragraph::collectWords()
3488 {
3489         // This is the value that needs to be exposed in the preferences
3490         // to resolve bug #6760.
3491         static int minlength = 6;
3492         pos_type n = size();
3493         for (pos_type pos = 0; pos < n; ++pos) {
3494                 if (isWordSeparator(pos))
3495                         continue;
3496                 pos_type from = pos;
3497                 locateWord(from, pos, WHOLE_WORD);
3498                 if (pos - from >= minlength) {
3499                         docstring word = asString(from, pos, AS_STR_NONE);
3500                         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3501                         if (cit == d->fontlist_.end())
3502                                 return;
3503                         Language const * lang = cit->font().language();
3504                         d->words_[*lang].insert(word);
3505                 }
3506         }
3507 }
3508
3509
3510 void Paragraph::registerWords()
3511 {
3512         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3513         Private::LangWordsMap::const_iterator ite = d->words_.end();
3514         for (; itl != ite; ++itl) {
3515                 WordList * wl = theWordList(itl->first);
3516                 Private::Words::const_iterator it = (itl->second).begin();
3517                 Private::Words::const_iterator et = (itl->second).end();
3518                 for (; it != et; ++it)
3519                         wl->insert(*it);
3520         }
3521 }
3522
3523
3524 void Paragraph::updateWords()
3525 {
3526         deregisterWords();
3527         collectWords();
3528         registerWords();
3529 }
3530
3531
3532 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3533 {
3534         SkipPositionsIterator begin = skips.begin();
3535         SkipPositions::iterator end = skips.end();
3536         if (pos > 0 && begin < end) {
3537                 --end;
3538                 if (end->last == pos - 1) {
3539                         end->last = pos;
3540                         return;
3541                 }
3542         }
3543         skips.insert(end, FontSpan(pos, pos));
3544 }
3545
3546
3547 Language * Paragraph::Private::locateSpellRange(
3548         pos_type & from, pos_type & to,
3549         SkipPositions & skips) const
3550 {
3551         // skip leading white space
3552         while (from < to && owner_->isWordSeparator(from))
3553                 ++from;
3554         // don't check empty range
3555         if (from >= to)
3556                 return 0;
3557         // get current language
3558         Language * lang = getSpellLanguage(from);
3559         pos_type last = from;
3560         bool samelang = true;
3561         bool sameinset = true;
3562         while (last < to && samelang && sameinset) {
3563                 // hop to end of word
3564                 while (last < to && !owner_->isWordSeparator(last)) {
3565                         if (owner_->getInset(last)) {
3566                                 appendSkipPosition(skips, last);
3567                         } else if (owner_->isDeleted(last)) {
3568                                 appendSkipPosition(skips, last);
3569                         }
3570                         ++last;
3571                 }
3572                 // hop to next word while checking for insets
3573                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3574                         if (Inset const * inset = owner_->getInset(last))
3575                                 sameinset = inset->isChar() && inset->isLetter();
3576                         if (sameinset && owner_->isDeleted(last)) {
3577                                 appendSkipPosition(skips, last);
3578                         }
3579                         if (sameinset)
3580                                 last++;
3581                 }
3582                 if (sameinset && last < to) {
3583                         // now check for language change
3584                         samelang = lang == getSpellLanguage(last);
3585                 }
3586         }
3587         // if language change detected backstep is needed
3588         if (!samelang)
3589                 --last;
3590         to = last;
3591         return lang;
3592 }
3593
3594
3595 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3596 {
3597         Language * lang =
3598                 const_cast<Language *>(owner_->getFontSettings(
3599                         inset_owner_->buffer().params(), from).language());
3600         if (lang == inset_owner_->buffer().params().language
3601                 && !lyxrc.spellchecker_alt_lang.empty()) {
3602                 string lang_code;
3603                 string const lang_variety =
3604                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3605                 lang->setCode(lang_code);
3606                 lang->setVariety(lang_variety);
3607         }
3608         return lang;
3609 }
3610
3611
3612 void Paragraph::requestSpellCheck(pos_type pos)
3613 {
3614         d->requestSpellCheck(pos);
3615 }
3616
3617
3618 bool Paragraph::needsSpellCheck() const
3619 {
3620         SpellChecker::ChangeNumber speller_change_number = 0;
3621         if (theSpellChecker())
3622                 speller_change_number = theSpellChecker()->changeNumber();
3623         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3624                 d->speller_state_.needsCompleteRefresh(speller_change_number);
3625         }
3626         return d->needsSpellCheck();
3627 }
3628
3629
3630 bool Paragraph::Private::ignoreWord(docstring const & word) const
3631 {
3632         // Ignore words with digits
3633         // FIXME: make this customizable
3634         // (note that some checkers ignore words with digits by default)
3635         docstring::const_iterator cit = word.begin();
3636         docstring::const_iterator const end = word.end();
3637         for (; cit != end; ++cit) {
3638                 if (isNumber((*cit)))
3639                         return true;
3640         }
3641         return false;
3642 }
3643
3644
3645 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3646         WordLangTuple & wl, docstring_list & suggestions,
3647         bool do_suggestion, bool check_learned) const
3648 {
3649         SpellChecker::Result result = SpellChecker::WORD_OK;
3650         SpellChecker * speller = theSpellChecker();
3651         if (!speller)
3652                 return result;
3653
3654         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3655                 return result;
3656
3657         locateWord(from, to, WHOLE_WORD);
3658         if (from == to || from >= size())
3659                 return result;
3660
3661         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3662         Language * lang = d->getSpellLanguage(from);
3663
3664         wl = WordLangTuple(word, lang);
3665
3666         if (!word.size())
3667                 return result;
3668
3669         if (needsSpellCheck() || check_learned) {
3670                 pos_type end = to;
3671                 if (!d->ignoreWord(word)) {
3672                         bool const trailing_dot = to < size() && d->text_[to] == '.';
3673                         result = speller->check(wl);
3674                         if (SpellChecker::misspelled(result) && trailing_dot) {
3675                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3676                                 result = speller->check(wl);
3677                                 if (!SpellChecker::misspelled(result)) {
3678                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3679                                            word << "\" [" <<
3680                                            from << ".." << to << "]");
3681                                 } else {
3682                                         // spell check with dot appended failed too
3683                                         // restore original word/lang value
3684                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3685                                         wl = WordLangTuple(word, lang);
3686                                 }
3687                         }
3688                 }
3689                 if (!SpellChecker::misspelled(result)) {
3690                         // area up to the begin of the next word is not misspelled
3691                         while (end < size() && isWordSeparator(end))
3692                                 ++end;
3693                 }
3694                 d->setMisspelled(from, end, result);
3695         } else {
3696                 result = d->speller_state_.getState(from);
3697         }
3698
3699         if (do_suggestion)
3700                 suggestions.clear();
3701
3702         if (SpellChecker::misspelled(result)) {
3703                 LYXERR(Debug::GUI, "misspelled word: \"" <<
3704                            word << "\" [" <<
3705                            from << ".." << to << "]");
3706                 if (do_suggestion)
3707                         speller->suggest(wl, suggestions);
3708         }
3709         return result;
3710 }
3711
3712
3713 void Paragraph::Private::markMisspelledWords(
3714         pos_type const & first, pos_type const & last,
3715         SpellChecker::Result result,
3716         docstring const & word,
3717         SkipPositions const & skips)
3718 {
3719         if (!SpellChecker::misspelled(result)) {
3720                 setMisspelled(first, last, SpellChecker::WORD_OK);
3721                 return;
3722         }
3723         int snext = first;
3724         SpellChecker * speller = theSpellChecker();
3725         // locate and enumerate the error positions
3726         int nerrors = speller->numMisspelledWords();
3727         int numskipped = 0;
3728         SkipPositionsIterator it = skips.begin();
3729         SkipPositionsIterator et = skips.end();
3730         for (int index = 0; index < nerrors; ++index) {
3731                 int wstart;
3732                 int wlen = 0;
3733                 speller->misspelledWord(index, wstart, wlen);
3734                 /// should not happen if speller supports range checks
3735                 if (!wlen) continue;
3736                 docstring const misspelled = word.substr(wstart, wlen);
3737                 wstart += first + numskipped;
3738                 if (snext < wstart) {
3739                         /// mark the range of correct spelling
3740                         numskipped += countSkips(it, et, wstart);
3741                         setMisspelled(snext,
3742                                 wstart - 1, SpellChecker::WORD_OK);
3743                 }
3744                 snext = wstart + wlen;
3745                 numskipped += countSkips(it, et, snext);
3746                 /// mark the range of misspelling
3747                 setMisspelled(wstart, snext, result);
3748                 LYXERR(Debug::GUI, "misspelled word: \"" <<
3749                            misspelled << "\" [" <<
3750                            wstart << ".." << (snext-1) << "]");
3751                 ++snext;
3752         }
3753         if (snext <= last) {
3754                 /// mark the range of correct spelling at end
3755                 setMisspelled(snext, last, SpellChecker::WORD_OK);
3756         }
3757 }
3758
3759
3760 void Paragraph::spellCheck() const
3761 {
3762         SpellChecker * speller = theSpellChecker();
3763         if (!speller || !size() ||!needsSpellCheck())
3764                 return;
3765         pos_type start;
3766         pos_type endpos;
3767         d->rangeOfSpellCheck(start, endpos);
3768         if (speller->canCheckParagraph()) {
3769                 // loop until we leave the range
3770                 for (pos_type first = start; first < endpos; ) {
3771                         pos_type last = endpos;
3772                         Private::SkipPositions skips;
3773                         Language * lang = d->locateSpellRange(first, last, skips);
3774                         if (first >= endpos)
3775                                 break;
3776                         // start the spell checker on the unit of meaning
3777                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3778                         WordLangTuple wl = WordLangTuple(word, lang);
3779                         SpellChecker::Result result = word.size() ?
3780                                 speller->check(wl) : SpellChecker::WORD_OK;
3781                         d->markMisspelledWords(first, last, result, word, skips);
3782                         first = ++last;
3783                 }
3784         } else {
3785                 static docstring_list suggestions;
3786                 pos_type to = endpos;
3787                 while (start < endpos) {
3788                         WordLangTuple wl;
3789                         spellCheck(start, to, wl, suggestions, false);
3790                         start = to + 1;
3791                 }
3792         }
3793         d->readySpellCheck();
3794 }
3795
3796
3797 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3798 {
3799         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3800         if (result || pos <= 0 || pos > size())
3801                 return result;
3802         if (check_boundary && (pos == size() || isWordSeparator(pos)))
3803                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3804         return result;
3805 }
3806
3807
3808 string Paragraph::magicLabel() const
3809 {
3810         stringstream ss;
3811         ss << "magicparlabel-" << id();
3812         return ss.str();
3813 }
3814
3815
3816 } // namespace lyx