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