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