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