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