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