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