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