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