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