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