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