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