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