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