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