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