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