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