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