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