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