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