]> git.lyx.org Git - features.git/blob - src/Paragraph.cpp
Execute lyx2lyx unit test when running tests
[features.git] / src / Paragraph.cpp
1 /**
2  * \file Paragraph.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Richard Heck (XHTML output)
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Paragraph.h"
22
23 #include "LayoutFile.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "Changes.h"
27 #include "Counters.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "Font.h"
35 #include "FontList.h"
36 #include "LyXRC.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TexRow.h"
45 #include "Text.h"
46 #include "WordLangTuple.h"
47 #include "WordList.h"
48
49 #include "frontends/alert.h"
50
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
54
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
62
63 #include <sstream>
64 #include <vector>
65
66 using namespace std;
67 using namespace lyx::support;
68
69 namespace lyx {
70
71 namespace {
72
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
75
76 }
77
78
79 /////////////////////////////////////////////////////////////////////
80 //
81 // SpellResultRange
82 //
83 /////////////////////////////////////////////////////////////////////
84
85 class SpellResultRange {
86 public:
87         SpellResultRange(FontSpan range, SpellChecker::Result result)
88         : range_(range), result_(result)
89         {}
90         ///
91         FontSpan const & range() const { return range_; }
92         ///
93         void range(FontSpan const & r) { range_ = r; }
94         ///
95         SpellChecker::Result result() const { return result_; }
96         ///
97         void result(SpellChecker::Result r) { result_ = r; }
98         ///
99         bool 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<string, 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         setFont(pos, font);
789         return true;
790 }
791
792
793 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
794 {
795         LASSERT(pos >= 0 && pos <= size(), return false);
796
797         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
798
799         if (trackChanges) {
800                 Change change = d->changes_.lookup(pos);
801
802                 // set the character to DELETED if
803                 //  a) it was previously unchanged or
804                 //  b) it was inserted by a co-author
805
806                 if (!change.changed() ||
807                       (change.inserted() && !change.currentAuthor())) {
808                         setChange(pos, Change(Change::DELETED));
809                         // request run of spell checker
810                         requestSpellCheck(pos);
811                         return false;
812                 }
813
814                 if (change.deleted())
815                         return false;
816         }
817
818         // Don't physically access the imaginary end-of-paragraph character.
819         // eraseChar() can only mark it as DELETED. A physical deletion of
820         // end-of-par must be handled externally.
821         if (pos == size()) {
822                 return false;
823         }
824
825         // track change
826         d->changes_.erase(pos);
827
828         // if it is an inset, delete the inset entry
829         if (d->text_[pos] == META_INSET)
830                 d->insetlist_.erase(pos);
831
832         d->text_.erase(d->text_.begin() + pos);
833
834         // Update the fontlist_
835         d->fontlist_.erase(pos);
836
837         // Update the insetlist_
838         d->insetlist_.decreasePosAfterPos(pos);
839
840         // Update list of misspelled positions
841         d->speller_state_.decreasePosAfterPos(pos);
842         d->speller_state_.refreshLast(size());
843
844         return true;
845 }
846
847
848 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
849 {
850         LASSERT(start >= 0 && start <= size(), return 0);
851         LASSERT(end >= start && end <= size() + 1, return 0);
852
853         pos_type i = start;
854         for (pos_type count = end - start; count; --count) {
855                 if (!eraseChar(i, trackChanges))
856                         ++i;
857         }
858         return end - i;
859 }
860
861
862 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
863                 char_type next, OutputParams const & runparams)
864 {
865         // Writing next here may circumvent a possible font change between
866         // c and next. Since next is only output if it forms a surrogate pair
867         // with c we can ignore this:
868         // A font change inside a surrogate pair does not make sense and is
869         // hopefully impossible to input.
870         // FIXME: change tracking
871         // Is this correct WRT change tracking?
872         Encoding const & encoding = *(runparams.encoding);
873         docstring latex1 = encoding.latexChar(next).first;
874         if (runparams.inIPA) {
875                 string const tipashortcut = Encodings::TIPAShortcut(next);
876                 if (!tipashortcut.empty()) {
877                         latex1 = from_ascii(tipashortcut);
878                 }
879         }
880         docstring const latex2 = encoding.latexChar(c).first;
881         if (docstring(1, next) == latex1) {
882                 // the encoding supports the combination
883                 os << latex2 << latex1;
884                 return latex1.length() + latex2.length();
885         } else if (runparams.local_font &&
886                    runparams.local_font->language()->lang() == "polutonikogreek") {
887                 // polutonikogreek only works without the brackets
888                 os << latex1 << latex2;
889                 return latex1.length() + latex2.length();
890         } else
891                 os << latex1 << '{' << latex2 << '}';
892         return latex1.length() + latex2.length() + 2;
893 }
894
895
896 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
897                                        otexstream & os,
898                                        pos_type i,
899                                        unsigned int & column,
900                                        Font const & font,
901                                        Layout const & style)
902 {
903         if (style.pass_thru || runparams.pass_thru)
904                 return false;
905
906         if (i + 1 < int(text_.size())) {
907                 char_type next = text_[i + 1];
908                 if (Encodings::isCombiningChar(next)) {
909                         // This space has an accent, so we must always output it.
910                         column += latexSurrogatePair(os, ' ', next, runparams) - 1;
911                         return true;
912                 }
913         }
914
915         if (runparams.linelen > 0
916             && column > runparams.linelen
917             && i
918             && text_[i - 1] != ' '
919             && (i + 1 < int(text_.size()))
920             // same in FreeSpacing mode
921             && !owner_->isFreeSpacing()
922             // In typewriter mode, we want to avoid
923             // ! . ? : at the end of a line
924             && !(font.fontInfo().family() == TYPEWRITER_FAMILY
925                  && (text_[i - 1] == '.'
926                      || text_[i - 1] == '?'
927                      || text_[i - 1] == ':'
928                      || text_[i - 1] == '!'))) {
929                 os << '\n';
930                 os.texrow().start(owner_->id(), i + 1);
931                 column = 0;
932         } else if (style.free_spacing) {
933                 os << '~';
934         } else {
935                 os << ' ';
936         }
937         return false;
938 }
939
940
941 int Paragraph::Private::writeScriptChars(otexstream & os,
942                                          docstring const & ltx,
943                                          Change const & runningChange,
944                                          Encoding const & encoding,
945                                          pos_type & i)
946 {
947         // FIXME: modifying i here is not very nice...
948
949         // We only arrive here when a proper language for character text_[i] has
950         // not been specified (i.e., it could not be translated in the current
951         // latex encoding) or its latex translation has been forced, and it
952         // belongs to a known script.
953         // Parameter ltx contains the latex translation of text_[i] as specified
954         // in the unicodesymbols file and is something like "\textXXX{<spec>}".
955         // The latex macro name "textXXX" specifies the script to which text_[i]
956         // belongs and we use it in order to check whether characters from the
957         // same script immediately follow, such that we can collect them in a
958         // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
959         // for the first char but only "<spec>" for all subsequent chars.
960         docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
961         docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
962         string script = to_ascii(ltx.substr(1, brace1 - 1));
963         int pos = 0;
964         int length = brace2;
965         bool closing_brace = true;
966         if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
967                 // Correct encoding is being used, so we can avoid \textgreek.
968                 pos = brace1 + 1;
969                 length -= pos;
970                 closing_brace = false;
971         }
972         os << ltx.substr(pos, length);
973         int size = text_.size();
974         while (i + 1 < size) {
975                 char_type const next = text_[i + 1];
976                 // Stop here if next character belongs to another script
977                 // or there is a change in change tracking status.
978                 if (!Encodings::isKnownScriptChar(next, script) ||
979                     runningChange != owner_->lookupChange(i + 1))
980                         break;
981                 Font prev_font;
982                 bool found = false;
983                 FontList::const_iterator cit = fontlist_.begin();
984                 FontList::const_iterator end = fontlist_.end();
985                 for (; cit != end; ++cit) {
986                         if (cit->pos() >= i && !found) {
987                                 prev_font = cit->font();
988                                 found = true;
989                         }
990                         if (cit->pos() >= i + 1)
991                                 break;
992                 }
993                 // Stop here if there is a font attribute or encoding change.
994                 if (found && cit != end && prev_font != cit->font())
995                         break;
996                 docstring const latex = encoding.latexChar(next).first;
997                 docstring::size_type const b1 =
998                                         latex.find_first_of(from_ascii("{"));
999                 docstring::size_type const b2 =
1000                                         latex.find_last_of(from_ascii("}"));
1001                 int const len = b2 - b1 - 1;
1002                 os << latex.substr(b1 + 1, len);
1003                 length += len;
1004                 ++i;
1005         }
1006         if (closing_brace) {
1007                 os << '}';
1008                 ++length;
1009         }
1010         return length;
1011 }
1012
1013
1014 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1015 {
1016         pos_type const len = str.length();
1017
1018         // is the paragraph large enough?
1019         if (pos + len > int(text_.size()))
1020                 return false;
1021
1022         // does the wanted text start at point?
1023         for (string::size_type i = 0; i < str.length(); ++i) {
1024                 // Caution: direct comparison of characters works only
1025                 // because str is pure ASCII.
1026                 if (str[i] != text_[pos + i])
1027                         return false;
1028         }
1029
1030         return fontlist_.hasChangeInRange(pos, len);
1031 }
1032
1033
1034 void Paragraph::Private::latexInset(BufferParams const & bparams,
1035                                     otexstream & os,
1036                                     OutputParams & runparams,
1037                                     Font & running_font,
1038                                     Font & basefont,
1039                                     Font const & outerfont,
1040                                     bool & open_font,
1041                                     Change & running_change,
1042                                     Layout const & style,
1043                                     pos_type & i,
1044                                     unsigned int & column)
1045 {
1046         Inset * inset = owner_->getInset(i);
1047         LBUFERR(inset);
1048
1049         if (style.pass_thru) {
1050                 odocstringstream ods;
1051                 inset->plaintext(ods, runparams);
1052                 os << ods.str();
1053                 return;
1054         }
1055
1056         // FIXME: move this to InsetNewline::latex
1057         if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1058                 // newlines are handled differently here than
1059                 // the default in simpleTeXSpecialChars().
1060                 if (!style.newline_allowed) {
1061                         os << '\n';
1062                 } else {
1063                         if (open_font) {
1064                                 column += running_font.latexWriteEndChanges(
1065                                         os, bparams, runparams,
1066                                         basefont, basefont);
1067                                 open_font = false;
1068                         }
1069
1070                         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1071                                 os << '~';
1072
1073                         basefont = owner_->getLayoutFont(bparams, outerfont);
1074                         running_font = basefont;
1075
1076                         if (runparams.moving_arg)
1077                                 os << "\\protect ";
1078
1079                 }
1080                 os.texrow().start(owner_->id(), i + 1);
1081                 column = 0;
1082         }
1083
1084         if (owner_->isDeleted(i)) {
1085                 if( ++runparams.inDeletedInset == 1)
1086                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
1087         }
1088
1089         if (inset->canTrackChanges()) {
1090                 column += Changes::latexMarkChange(os, bparams, running_change,
1091                         Change(Change::UNCHANGED), runparams);
1092                 running_change = Change(Change::UNCHANGED);
1093         }
1094
1095         bool close = false;
1096         odocstream::pos_type const len = os.os().tellp();
1097
1098         if (inset->forceLTR()
1099             && !runparams.use_polyglossia
1100             && running_font.isRightToLeft()
1101             // ERT is an exception, it should be output with no
1102             // decorations at all
1103             && inset->lyxCode() != ERT_CODE) {
1104                 if (running_font.language()->lang() == "farsi")
1105                         os << "\\beginL{}";
1106                 else
1107                         os << "\\L{";
1108                 close = true;
1109         }
1110
1111         // FIXME: Bug: we can have an empty font change here!
1112         // if there has just been a font change, we are going to close it
1113         // right now, which means stupid latex code like \textsf{}. AFAIK,
1114         // this does not harm dvi output. A minor bug, thus (JMarc)
1115
1116         // Some insets cannot be inside a font change command.
1117         // However, even such insets *can* be placed in \L or \R
1118         // or their equivalents (for RTL language switches), so we don't
1119         // close the language in those cases.
1120         // ArabTeX, though, cannot handle this special behavior, it seems.
1121         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1122                 || running_font.language()->lang() == "arabic_arabtex";
1123         if (open_font && !inset->inheritFont()) {
1124                 bool closeLanguage = arabtex
1125                         || basefont.isRightToLeft() == running_font.isRightToLeft();
1126                 unsigned int count = running_font.latexWriteEndChanges(os,
1127                         bparams, runparams, basefont, basefont, closeLanguage);
1128                 column += count;
1129                 // if any font properties were closed, update the running_font,
1130                 // making sure, however, to leave the language as it was
1131                 if (count > 0) {
1132                         // FIXME: probably a better way to keep track of the old
1133                         // language, than copying the entire font?
1134                         Font const copy_font(running_font);
1135                         basefont = owner_->getLayoutFont(bparams, outerfont);
1136                         running_font = basefont;
1137                         if (!closeLanguage)
1138                                 running_font.setLanguage(copy_font.language());
1139                         // leave font open if language is still open
1140                         open_font = (running_font.language() == basefont.language());
1141                         if (closeLanguage)
1142                                 runparams.local_font = &basefont;
1143                 }
1144         }
1145
1146         int prev_rows = os.texrow().rows();
1147
1148         try {
1149                 runparams.lastid = id_;
1150                 runparams.lastpos = i;
1151                 inset->latex(os, runparams);
1152         } catch (EncodingException & e) {
1153                 // add location information and throw again.
1154                 e.par_id = id_;
1155                 e.pos = i;
1156                 throw(e);
1157         }
1158
1159         if (close) {
1160                 if (running_font.language()->lang() == "farsi")
1161                                 os << "\\endL{}";
1162                         else
1163                                 os << '}';
1164         }
1165
1166         if (os.texrow().rows() > prev_rows) {
1167                 os.texrow().start(owner_->id(), i + 1);
1168                 column = 0;
1169         } else {
1170                 column += (unsigned int)(os.os().tellp() - len);
1171         }
1172
1173         if (owner_->isDeleted(i))
1174                 --runparams.inDeletedInset;
1175 }
1176
1177
1178 void Paragraph::Private::latexSpecialChar(otexstream & os,
1179                                           BufferParams const & bparams,
1180                                           OutputParams const & runparams,
1181                                           Font const & running_font,
1182                                           Change const & running_change,
1183                                           Layout const & style,
1184                                           pos_type & i,
1185                                           pos_type end_pos,
1186                                           unsigned int & column)
1187 {
1188         // With polyglossia, brackets and stuff need not be reversed
1189         // in RTL scripts (see bug #8251)
1190         char_type const c = (runparams.use_polyglossia) ?
1191                 owner_->getUChar(bparams, i) : text_[i];
1192
1193         if (style.pass_thru || runparams.pass_thru) {
1194                 if (c != '\0') {
1195                         Encoding const * const enc = runparams.encoding;
1196                         if (enc && !enc->encodable(c))
1197                                 throw EncodingException(c);
1198                         os.put(c);
1199                 }
1200                 return;
1201         }
1202
1203         // TIPA uses its own T3 encoding
1204         if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1205                 return;
1206         // If T1 font encoding is used, use the special
1207         // characters it provides.
1208         // NOTE: some languages reset the font encoding
1209         // internally
1210         if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1211             && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1212                 return;
1213
1214         // \tt font needs special treatment
1215         if (!runparams.inIPA
1216              && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1217              && latexSpecialTypewriter(c, os, i, column))
1218                 return;
1219
1220         // Otherwise, we use what LaTeX provides us.
1221         switch (c) {
1222         case '\\':
1223                 os << "\\textbackslash{}";
1224                 column += 15;
1225                 break;
1226         case '<':
1227                 os << "\\textless{}";
1228                 column += 10;
1229                 break;
1230         case '>':
1231                 os << "\\textgreater{}";
1232                 column += 13;
1233                 break;
1234         case '|':
1235                 os << "\\textbar{}";
1236                 column += 9;
1237                 break;
1238         case '-':
1239                 os << '-';
1240                 break;
1241         case '\"':
1242                 os << "\\char`\\\"{}";
1243                 column += 9;
1244                 break;
1245
1246         case '$': case '&':
1247         case '%': case '#': case '{':
1248         case '}': case '_':
1249                 os << '\\';
1250                 os.put(c);
1251                 column += 1;
1252                 break;
1253
1254         case '~':
1255                 os << "\\textasciitilde{}";
1256                 column += 16;
1257                 break;
1258
1259         case '^':
1260                 os << "\\textasciicircum{}";
1261                 column += 17;
1262                 break;
1263
1264         case '*':
1265         case '[':
1266         case ']':
1267                 // avoid being mistaken for optional arguments
1268                 os << '{';
1269                 os.put(c);
1270                 os << '}';
1271                 column += 2;
1272                 break;
1273
1274         case ' ':
1275                 // Blanks are printed before font switching.
1276                 // Sure? I am not! (try nice-latex)
1277                 // I am sure it's correct. LyX might be smarter
1278                 // in the future, but for now, nothing wrong is
1279                 // written. (Asger)
1280                 break;
1281
1282         default:
1283                 // LyX, LaTeX etc.
1284                 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1285                         return;
1286
1287                 if (c == '\0')
1288                         return;
1289
1290                 Encoding const & encoding = *(runparams.encoding);
1291                 char_type next = '\0';
1292                 if (i + 1 < int(text_.size())) {
1293                         next = text_[i + 1];
1294                         if (Encodings::isCombiningChar(next)) {
1295                                 column += latexSurrogatePair(os, c, next, runparams) - 1;
1296                                 ++i;
1297                                 break;
1298                         }
1299                 }
1300                 string script;
1301                 pair<docstring, bool> latex = encoding.latexChar(c);
1302                 docstring nextlatex;
1303                 bool nexttipas = false;
1304                 string nexttipashortcut;
1305                 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1306                         nextlatex = encoding.latexChar(next).first;
1307                         if (runparams.inIPA) {
1308                                 nexttipashortcut = Encodings::TIPAShortcut(next);
1309                                 nexttipas = !nexttipashortcut.empty();
1310                         }
1311                 }
1312                 bool tipas = false;
1313                 if (runparams.inIPA) {
1314                         string const tipashortcut = Encodings::TIPAShortcut(c);
1315                         if (!tipashortcut.empty()) {
1316                                 latex.first = from_ascii(tipashortcut);
1317                                 latex.second = false;
1318                                 tipas = true;
1319                         }
1320                 }
1321                 if (Encodings::isKnownScriptChar(c, script)
1322                     && prefixIs(latex.first, from_ascii("\\" + script)))
1323                         column += writeScriptChars(os, latex.first,
1324                                         running_change, encoding, i) - 1;
1325                 else if (latex.second
1326                          && ((!prefixIs(nextlatex, '\\')
1327                                && !prefixIs(nextlatex, '{')
1328                                && !prefixIs(nextlatex, '}'))
1329                              || (nexttipas
1330                                  && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1331                          && !tipas) {
1332                         // Prevent eating of a following
1333                         // space or command corruption by
1334                         // following characters
1335                         if (next == ' ' || next == '\0') {
1336                                 column += latex.first.length() + 1;
1337                                 os << latex.first << "{}";
1338                         } else {
1339                                 column += latex.first.length();
1340                                 os << latex.first << " ";
1341                         }
1342                 } else {
1343                         column += latex.first.length() - 1;
1344                         os << latex.first;
1345                 }
1346                 break;
1347         }
1348 }
1349
1350
1351 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1352         pos_type i, unsigned int & column)
1353 {
1354         switch (c) {
1355         case '>':
1356         case '<':
1357                 os.put(c);
1358                 // In T1 encoding, these characters exist
1359                 // but we should avoid ligatures
1360                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1361                         return true;
1362                 os << "\\textcompwordmark{}";
1363                 column += 19;
1364                 return true;
1365         case '|':
1366                 os.put(c);
1367                 return true;
1368         case '\"':
1369                 // soul.sty breaks with \char`\"
1370                 os << "\\textquotedbl{}";
1371                 column += 14;
1372                 return true;
1373         default:
1374                 return false;
1375         }
1376 }
1377
1378
1379 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1380         pos_type /*i*/, unsigned int & column)
1381 {
1382         switch (c) {
1383         case '*':
1384         case '[':
1385         case ']':
1386         case '\"':
1387                 os.put(c);
1388                 return true;
1389         case '|':
1390                 os << "\\textvertline{}";
1391                 column += 14;
1392                 return true;
1393         default:
1394                 return false;
1395         }
1396 }
1397
1398
1399 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1400         pos_type i, unsigned int & column)
1401 {
1402         switch (c) {
1403         case '-':
1404                 // within \ttfamily, "--" is merged to "-" (no endash)
1405                 // so we avoid this rather irritating ligature
1406                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1407                         os << "-{}";
1408                         column += 2;
1409                 } else
1410                         os << '-';
1411                 return true;
1412
1413         // everything else has to be checked separately
1414         // (depending on the encoding)
1415         default:
1416                 return false;
1417         }
1418 }
1419
1420
1421 /// \param end_pos
1422 ///   If [start_pos, end_pos) does not include entirely the special phrase, then
1423 ///   do not apply the macro transformation.
1424 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1425         unsigned int & column, OutputParams const & runparams)
1426 {
1427         // FIXME: if we have "LaTeX" with a font
1428         // change in the middle (before the 'T', then
1429         // the "TeX" part is still special cased.
1430         // Really we should only operate this on
1431         // "words" for some definition of word
1432
1433         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1434                 if (!isTextAt(special_phrases[pnr].phrase, i)
1435                     || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1436                         continue;
1437                 if (runparams.moving_arg)
1438                         os << "\\protect";
1439                 os << special_phrases[pnr].macro;
1440                 i += special_phrases[pnr].phrase.length() - 1;
1441                 column += special_phrases[pnr].macro.length() - 1;
1442                 return true;
1443         }
1444         return false;
1445 }
1446
1447
1448 void Paragraph::Private::validate(LaTeXFeatures & features) const
1449 {
1450         if (layout_->inpreamble && inset_owner_) {
1451                 bool const is_command = layout_->latextype == LATEX_COMMAND;
1452                 Buffer const & buf = inset_owner_->buffer();
1453                 BufferParams const & bp = features.runparams().is_child
1454                         ? buf.masterParams() : 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                 BufferEncodings::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 void Paragraph::resetFonts(Font const & font)
1788 {
1789         d->fontlist_.clear();
1790         d->fontlist_.set(0, font);
1791         d->fontlist_.set(d->text_.size() - 1, font);
1792 }
1793
1794 // Gets uninstantiated font setting at position.
1795 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1796                                          pos_type pos) const
1797 {
1798         if (pos > size()) {
1799                 LYXERR0("pos: " << pos << " size: " << size());
1800                 LBUFERR(false);
1801         }
1802
1803         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1804         if (cit != d->fontlist_.end())
1805                 return cit->font();
1806
1807         if (pos == size() && !empty())
1808                 return getFontSettings(bparams, pos - 1);
1809
1810         // Optimisation: avoid a full font instantiation if there is no
1811         // language change from previous call.
1812         static Font previous_font;
1813         static Language const * previous_lang = 0;
1814         Language const * lang = getParLanguage(bparams);
1815         if (lang != previous_lang) {
1816                 previous_lang = lang;
1817                 previous_font = Font(inherit_font, lang);
1818         }
1819         return previous_font;
1820 }
1821
1822
1823 FontSpan Paragraph::fontSpan(pos_type pos) const
1824 {
1825         LBUFERR(pos < size());
1826
1827         pos_type start = 0;
1828         FontList::const_iterator cit = d->fontlist_.begin();
1829         FontList::const_iterator end = d->fontlist_.end();
1830         for (; cit != end; ++cit) {
1831                 if (cit->pos() >= pos) {
1832                         if (pos >= beginOfBody())
1833                                 return FontSpan(max(start, beginOfBody()),
1834                                                 cit->pos());
1835                         else
1836                                 return FontSpan(start,
1837                                                 min(beginOfBody() - 1,
1838                                                          cit->pos()));
1839                 }
1840                 start = cit->pos() + 1;
1841         }
1842
1843         // This should not happen, but if so, we take no chances.
1844         LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1845         LASSERT(false, return FontSpan(pos, pos));
1846 }
1847
1848
1849 // Gets uninstantiated font setting at position 0
1850 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1851 {
1852         if (!empty() && !d->fontlist_.empty())
1853                 return d->fontlist_.begin()->font();
1854
1855         // Optimisation: avoid a full font instantiation if there is no
1856         // language change from previous call.
1857         static Font previous_font;
1858         static Language const * previous_lang = 0;
1859         if (bparams.language != previous_lang) {
1860                 previous_lang = bparams.language;
1861                 previous_font = Font(inherit_font, bparams.language);
1862         }
1863
1864         return previous_font;
1865 }
1866
1867
1868 // Gets the fully instantiated font at a given position in a paragraph
1869 // This is basically the same function as Text::GetFont() in text2.cpp.
1870 // The difference is that this one is used for generating the LaTeX file,
1871 // and thus cosmetic "improvements" are disallowed: This has to deliver
1872 // the true picture of the buffer. (Asger)
1873 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1874                                  Font const & outerfont) const
1875 {
1876         LBUFERR(pos >= 0);
1877
1878         Font font = getFontSettings(bparams, pos);
1879
1880         pos_type const body_pos = beginOfBody();
1881         FontInfo & fi = font.fontInfo();
1882         if (pos < body_pos)
1883                 fi.realize(d->layout_->labelfont);
1884         else
1885                 fi.realize(d->layout_->font);
1886
1887         fi.realize(outerfont.fontInfo());
1888         fi.realize(bparams.getFont().fontInfo());
1889
1890         return font;
1891 }
1892
1893
1894 Font const Paragraph::getLabelFont
1895         (BufferParams const & bparams, Font const & outerfont) const
1896 {
1897         FontInfo tmpfont = d->layout_->labelfont;
1898         tmpfont.realize(outerfont.fontInfo());
1899         tmpfont.realize(bparams.getFont().fontInfo());
1900         return Font(tmpfont, getParLanguage(bparams));
1901 }
1902
1903
1904 Font const Paragraph::getLayoutFont
1905         (BufferParams const & bparams, Font const & outerfont) const
1906 {
1907         FontInfo tmpfont = d->layout_->font;
1908         tmpfont.realize(outerfont.fontInfo());
1909         tmpfont.realize(bparams.getFont().fontInfo());
1910         return Font(tmpfont, getParLanguage(bparams));
1911 }
1912
1913
1914 /// Returns the height of the highest font in range
1915 FontSize Paragraph::highestFontInRange
1916         (pos_type startpos, pos_type endpos, FontSize def_size) const
1917 {
1918         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1919 }
1920
1921
1922 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1923 {
1924         char_type c = d->text_[pos];
1925         if (!lyxrc.rtl_support || !getFontSettings(bparams, pos).isRightToLeft())
1926                 return c;
1927
1928         // FIXME: The arabic special casing is due to the difference of arabic
1929         // round brackets input introduced in r18599. Check if this should be
1930         // unified with Hebrew or at least if all bracket types should be
1931         // handled the same (file format change in either case).
1932         string const & lang = getFontSettings(bparams, pos).language()->lang();
1933         bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1934                 || lang == "farsi";
1935         char_type uc = c;
1936         switch (c) {
1937         case '(':
1938                 uc = arabic ? c : ')';
1939                 break;
1940         case ')':
1941                 uc = arabic ? c : '(';
1942                 break;
1943         case '[':
1944                 uc = ']';
1945                 break;
1946         case ']':
1947                 uc = '[';
1948                 break;
1949         case '{':
1950                 uc = '}';
1951                 break;
1952         case '}':
1953                 uc = '{';
1954                 break;
1955         case '<':
1956                 uc = '>';
1957                 break;
1958         case '>':
1959                 uc = '<';
1960                 break;
1961         }
1962
1963         return uc;
1964 }
1965
1966
1967 void Paragraph::setFont(pos_type pos, Font const & font)
1968 {
1969         LASSERT(pos <= size(), return);
1970
1971         // First, reduce font against layout/label font
1972         // Update: The setCharFont() routine in text2.cpp already
1973         // reduces font, so we don't need to do that here. (Asger)
1974
1975         d->fontlist_.set(pos, font);
1976 }
1977
1978
1979 void Paragraph::makeSameLayout(Paragraph const & par)
1980 {
1981         d->layout_ = par.d->layout_;
1982         d->params_ = par.d->params_;
1983 }
1984
1985
1986 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1987 {
1988         if (isFreeSpacing())
1989                 return false;
1990
1991         int pos = 0;
1992         int count = 0;
1993
1994         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1995                 if (eraseChar(pos, trackChanges))
1996                         ++count;
1997                 else
1998                         ++pos;
1999         }
2000
2001         return count > 0 || pos > 0;
2002 }
2003
2004
2005 bool Paragraph::hasSameLayout(Paragraph const & par) const
2006 {
2007         return par.d->layout_ == d->layout_
2008                 && d->params_.sameLayout(par.d->params_);
2009 }
2010
2011
2012 depth_type Paragraph::getDepth() const
2013 {
2014         return d->params_.depth();
2015 }
2016
2017
2018 depth_type Paragraph::getMaxDepthAfter() const
2019 {
2020         if (d->layout_->isEnvironment())
2021                 return d->params_.depth() + 1;
2022         else
2023                 return d->params_.depth();
2024 }
2025
2026
2027 char Paragraph::getAlign() const
2028 {
2029         if (d->params_.align() == LYX_ALIGN_LAYOUT)
2030                 return d->layout_->align;
2031         else
2032                 return d->params_.align();
2033 }
2034
2035
2036 docstring const & Paragraph::labelString() const
2037 {
2038         return d->params_.labelString();
2039 }
2040
2041
2042 // the next two functions are for the manual labels
2043 docstring const Paragraph::getLabelWidthString() const
2044 {
2045         if (d->layout_->margintype == MARGIN_MANUAL
2046             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2047                 return d->params_.labelWidthString();
2048         else
2049                 return _("Senseless with this layout!");
2050 }
2051
2052
2053 void Paragraph::setLabelWidthString(docstring const & s)
2054 {
2055         d->params_.labelWidthString(s);
2056 }
2057
2058
2059 docstring Paragraph::expandLabel(Layout const & layout,
2060                 BufferParams const & bparams) const
2061 {
2062         return expandParagraphLabel(layout, bparams, true);
2063 }
2064
2065
2066 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2067                 BufferParams const & bparams) const
2068 {
2069         return expandParagraphLabel(layout, bparams, false);
2070 }
2071
2072
2073 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2074                 BufferParams const & bparams, bool process_appendix) const
2075 {
2076         DocumentClass const & tclass = bparams.documentClass();
2077         string const & lang = getParLanguage(bparams)->code();
2078         bool const in_appendix = process_appendix && d->params_.appendix();
2079         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2080
2081         if (fmt.empty() && !layout.counter.empty())
2082                 return tclass.counters().theCounter(layout.counter, lang);
2083
2084         // handle 'inherited level parts' in 'fmt',
2085         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
2086         size_t const i = fmt.find('@', 0);
2087         if (i != docstring::npos) {
2088                 size_t const j = fmt.find('@', i + 1);
2089                 if (j != docstring::npos) {
2090                         docstring parent(fmt, i + 1, j - i - 1);
2091                         docstring label = from_ascii("??");
2092                         if (tclass.hasLayout(parent))
2093                                 docstring label = expandParagraphLabel(tclass[parent], bparams,
2094                                                       process_appendix);
2095                         fmt = docstring(fmt, 0, i) + label
2096                                 + docstring(fmt, j + 1, docstring::npos);
2097                 }
2098         }
2099
2100         return tclass.counters().counterLabel(fmt, lang);
2101 }
2102
2103
2104 void Paragraph::applyLayout(Layout const & new_layout)
2105 {
2106         d->layout_ = &new_layout;
2107         LyXAlignment const oldAlign = d->params_.align();
2108
2109         if (!(oldAlign & d->layout_->alignpossible)) {
2110                 frontend::Alert::warning(_("Alignment not permitted"),
2111                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
2112                 d->params_.align(LYX_ALIGN_LAYOUT);
2113         }
2114 }
2115
2116
2117 pos_type Paragraph::beginOfBody() const
2118 {
2119         return d->begin_of_body_;
2120 }
2121
2122
2123 void Paragraph::setBeginOfBody()
2124 {
2125         if (d->layout_->labeltype != LABEL_MANUAL) {
2126                 d->begin_of_body_ = 0;
2127                 return;
2128         }
2129
2130         // Unroll the first two cycles of the loop
2131         // and remember the previous character to
2132         // remove unnecessary getChar() calls
2133         pos_type i = 0;
2134         pos_type end = size();
2135         if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2136                 ++i;
2137                 char_type previous_char = 0;
2138                 char_type temp = 0;
2139                 if (i < end) {
2140                         previous_char = d->text_[i];
2141                         if (!(isNewline(i) || isEnvSeparator(i))) {
2142                                 ++i;
2143                                 while (i < end && previous_char != ' ') {
2144                                         temp = d->text_[i];
2145                                         if (isNewline(i) || isEnvSeparator(i))
2146                                                 break;
2147                                         ++i;
2148                                         previous_char = temp;
2149                                 }
2150                         }
2151                 }
2152         }
2153
2154         d->begin_of_body_ = i;
2155 }
2156
2157
2158 bool Paragraph::allowParagraphCustomization() const
2159 {
2160         return inInset().allowParagraphCustomization();
2161 }
2162
2163
2164 bool Paragraph::usePlainLayout() const
2165 {
2166         return inInset().usePlainLayout();
2167 }
2168
2169
2170 bool Paragraph::isPassThru() const
2171 {
2172         return inInset().isPassThru() || d->layout_->pass_thru;
2173 }
2174
2175 namespace {
2176
2177 // paragraphs inside floats need different alignment tags to avoid
2178 // unwanted space
2179
2180 bool noTrivlistCentering(InsetCode code)
2181 {
2182         return code == FLOAT_CODE
2183                || code == WRAP_CODE
2184                || code == CELL_CODE;
2185 }
2186
2187
2188 string correction(string const & orig)
2189 {
2190         if (orig == "flushleft")
2191                 return "raggedright";
2192         if (orig == "flushright")
2193                 return "raggedleft";
2194         if (orig == "center")
2195                 return "centering";
2196         return orig;
2197 }
2198
2199
2200 string const corrected_env(string const & suffix, string const & env,
2201         InsetCode code, bool const lastpar)
2202 {
2203         string output = suffix + "{";
2204         if (noTrivlistCentering(code)) {
2205                 if (lastpar) {
2206                         // the last paragraph in non-trivlist-aligned
2207                         // context is special (to avoid unwanted whitespace)
2208                         if (suffix == "\\begin")
2209                                 return "\\" + correction(env) + "{}";
2210                         return string();
2211                 }
2212                 output += correction(env);
2213         } else
2214                 output += env;
2215         output += "}";
2216         if (suffix == "\\begin")
2217                 output += "\n";
2218         return output;
2219 }
2220
2221
2222 void adjust_column(string const & str, int & column)
2223 {
2224         if (!contains(str, "\n"))
2225                 column += str.size();
2226         else {
2227                 string tmp;
2228                 column = rsplit(str, tmp, '\n').size();
2229         }
2230 }
2231
2232 } // namespace anon
2233
2234
2235 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2236                         otexstream & os, OutputParams const & runparams) const
2237 {
2238         int column = 0;
2239
2240         if (params_.noindent() && !layout_->pass_thru
2241             && (layout_->toggle_indent != ITOGGLE_NEVER)) {
2242                 os << "\\noindent ";
2243                 column += 10;
2244         }
2245
2246         LyXAlignment const curAlign = params_.align();
2247
2248         if (curAlign == layout_->align)
2249                 return column;
2250
2251         switch (curAlign) {
2252         case LYX_ALIGN_NONE:
2253         case LYX_ALIGN_BLOCK:
2254         case LYX_ALIGN_LAYOUT:
2255         case LYX_ALIGN_SPECIAL:
2256         case LYX_ALIGN_DECIMAL:
2257                 break;
2258         case LYX_ALIGN_LEFT:
2259         case LYX_ALIGN_RIGHT:
2260         case LYX_ALIGN_CENTER:
2261                 if (runparams.moving_arg) {
2262                         os << "\\protect";
2263                         column += 8;
2264                 }
2265                 break;
2266         }
2267
2268         string const begin_tag = "\\begin";
2269         InsetCode code = ownerCode();
2270         bool const lastpar = runparams.isLastPar;
2271
2272         switch (curAlign) {
2273         case LYX_ALIGN_NONE:
2274         case LYX_ALIGN_BLOCK:
2275         case LYX_ALIGN_LAYOUT:
2276         case LYX_ALIGN_SPECIAL:
2277         case LYX_ALIGN_DECIMAL:
2278                 break;
2279         case LYX_ALIGN_LEFT: {
2280                 string output;
2281                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2282                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2283                 else
2284                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2285                 os << from_ascii(output);
2286                 adjust_column(output, column);
2287                 break;
2288         } case LYX_ALIGN_RIGHT: {
2289                 string output;
2290                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2291                         output = corrected_env(begin_tag, "flushright", code, lastpar);
2292                 else
2293                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
2294                 os << from_ascii(output);
2295                 adjust_column(output, column);
2296                 break;
2297         } case LYX_ALIGN_CENTER: {
2298                 string output;
2299                 output = corrected_env(begin_tag, "center", code, lastpar);
2300                 os << from_ascii(output);
2301                 adjust_column(output, column);
2302                 break;
2303         }
2304         }
2305
2306         return column;
2307 }
2308
2309
2310 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2311                         otexstream & os, OutputParams const & runparams) const
2312 {
2313         LyXAlignment const curAlign = params_.align();
2314
2315         if (curAlign == layout_->align)
2316                 return false;
2317
2318         switch (curAlign) {
2319         case LYX_ALIGN_NONE:
2320         case LYX_ALIGN_BLOCK:
2321         case LYX_ALIGN_LAYOUT:
2322         case LYX_ALIGN_SPECIAL:
2323         case LYX_ALIGN_DECIMAL:
2324                 break;
2325         case LYX_ALIGN_LEFT:
2326         case LYX_ALIGN_RIGHT:
2327         case LYX_ALIGN_CENTER:
2328                 if (runparams.moving_arg)
2329                         os << "\\protect";
2330                 break;
2331         }
2332
2333         string output;
2334         string const end_tag = "\n\\par\\end";
2335         InsetCode code = ownerCode();
2336         bool const lastpar = runparams.isLastPar;
2337
2338         switch (curAlign) {
2339         case LYX_ALIGN_NONE:
2340         case LYX_ALIGN_BLOCK:
2341         case LYX_ALIGN_LAYOUT:
2342         case LYX_ALIGN_SPECIAL:
2343         case LYX_ALIGN_DECIMAL:
2344                 break;
2345         case LYX_ALIGN_LEFT: {
2346                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2347                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2348                 else
2349                         output = corrected_env(end_tag, "flushright", code, lastpar);
2350                 os << from_ascii(output);
2351                 break;
2352         } case LYX_ALIGN_RIGHT: {
2353                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2354                         output = corrected_env(end_tag, "flushright", code, lastpar);
2355                 else
2356                         output = corrected_env(end_tag, "flushleft", code, lastpar);
2357                 os << from_ascii(output);
2358                 break;
2359         } case LYX_ALIGN_CENTER: {
2360                 output = corrected_env(end_tag, "center", code, lastpar);
2361                 os << from_ascii(output);
2362                 break;
2363         }
2364         }
2365
2366         return !output.empty() || lastpar;
2367 }
2368
2369
2370 // This one spits out the text of the paragraph
2371 void Paragraph::latex(BufferParams const & bparams,
2372         Font const & outerfont,
2373         otexstream & os,
2374         OutputParams const & runparams,
2375         int start_pos, int end_pos, bool force) const
2376 {
2377         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
2378
2379         // FIXME This check should not be needed. Perhaps issue an
2380         // error if it triggers.
2381         Layout const & style = inInset().forcePlainLayout() ?
2382                 bparams.documentClass().plainLayout() : *d->layout_;
2383
2384         if (!force && style.inpreamble)
2385                 return;
2386
2387         bool const allowcust = allowParagraphCustomization();
2388
2389         // Current base font for all inherited font changes, without any
2390         // change caused by an individual character, except for the language:
2391         // It is set to the language of the first character.
2392         // As long as we are in the label, this font is the base font of the
2393         // label. Before the first body character it is set to the base font
2394         // of the body.
2395         Font basefont;
2396
2397         // Maybe we have to create a optional argument.
2398         pos_type body_pos = beginOfBody();
2399         unsigned int column = 0;
2400
2401         if (body_pos > 0) {
2402                 // the optional argument is kept in curly brackets in
2403                 // case it contains a ']'
2404                 // This is not strictly needed, but if this is changed it
2405                 // would be a file format change, and tex2lyx would need
2406                 // to be adjusted, since it unconditionally removes the
2407                 // braces when it parses \item.
2408                 os << "[{";
2409                 column += 2;
2410                 basefont = getLabelFont(bparams, outerfont);
2411         } else {
2412                 basefont = getLayoutFont(bparams, outerfont);
2413         }
2414
2415         // Which font is currently active?
2416         Font running_font(basefont);
2417         // Do we have an open font change?
2418         bool open_font = false;
2419
2420         Change runningChange = Change(Change::UNCHANGED);
2421
2422         Encoding const * const prev_encoding = runparams.encoding;
2423
2424         os.texrow().start(id(), 0);
2425
2426         // if the paragraph is empty, the loop will not be entered at all
2427         if (empty()) {
2428                 if (style.isCommand()) {
2429                         os << '{';
2430                         ++column;
2431                 }
2432                 if (!style.leftdelim().empty()) {
2433                         os << style.leftdelim();
2434                         column += style.leftdelim().size();
2435                 }
2436                 if (allowcust)
2437                         column += d->startTeXParParams(bparams, os, runparams);
2438         }
2439
2440         for (pos_type i = 0; i < size(); ++i) {
2441                 // First char in paragraph or after label?
2442                 if (i == body_pos) {
2443                         if (body_pos > 0) {
2444                                 if (open_font) {
2445                                         column += running_font.latexWriteEndChanges(
2446                                                 os, bparams, runparams,
2447                                                 basefont, basefont);
2448                                         open_font = false;
2449                                 }
2450                                 basefont = getLayoutFont(bparams, outerfont);
2451                                 running_font = basefont;
2452
2453                                 column += Changes::latexMarkChange(os, bparams,
2454                                                 runningChange, Change(Change::UNCHANGED),
2455                                                 runparams);
2456                                 runningChange = Change(Change::UNCHANGED);
2457
2458                                 os << "}] ";
2459                                 column +=3;
2460                         }
2461                         if (style.isCommand()) {
2462                                 os << '{';
2463                                 ++column;
2464                         }
2465
2466                         if (!style.leftdelim().empty()) {
2467                                 os << style.leftdelim();
2468                                 column += style.leftdelim().size();
2469                         }
2470
2471                         if (allowcust)
2472                                 column += d->startTeXParParams(bparams, os,
2473                                                             runparams);
2474                 }
2475
2476                 Change const & change = runparams.inDeletedInset
2477                         ? runparams.changeOfDeletedInset : lookupChange(i);
2478
2479                 if (bparams.output_changes && runningChange != change) {
2480                         if (open_font) {
2481                                 column += running_font.latexWriteEndChanges(
2482                                                 os, bparams, runparams, basefont, basefont);
2483                                 open_font = false;
2484                         }
2485                         basefont = getLayoutFont(bparams, outerfont);
2486                         running_font = basefont;
2487
2488                         column += Changes::latexMarkChange(os, bparams, runningChange,
2489                                                            change, runparams);
2490                         runningChange = change;
2491                 }
2492
2493                 // do not output text which is marked deleted
2494                 // if change tracking output is disabled
2495                 if (!bparams.output_changes && change.deleted()) {
2496                         continue;
2497                 }
2498
2499                 ++column;
2500
2501                 // Fully instantiated font
2502                 Font const font = getFont(bparams, i, outerfont);
2503
2504                 Font const last_font = running_font;
2505
2506                 // Do we need to close the previous font?
2507                 if (open_font &&
2508                     (font != running_font ||
2509                      font.language() != running_font.language()))
2510                 {
2511                         column += running_font.latexWriteEndChanges(
2512                                         os, bparams, runparams, basefont,
2513                                         (i == body_pos-1) ? basefont : font);
2514                         running_font = basefont;
2515                         open_font = false;
2516                 }
2517
2518                 string const running_lang = runparams.use_polyglossia ?
2519                         running_font.language()->polyglossia() : running_font.language()->babel();
2520                 // close babel's font environment before opening CJK.
2521                 string const lang_end_command = runparams.use_polyglossia ?
2522                         "\\end{$$lang}" : lyxrc.language_command_end;
2523                 if (!running_lang.empty() &&
2524                     font.language()->encoding()->package() == Encoding::CJK) {
2525                                 string end_tag = subst(lang_end_command,
2526                                                         "$$lang",
2527                                                         running_lang);
2528                                 os << from_ascii(end_tag);
2529                                 column += end_tag.length();
2530                 }
2531
2532                 // Switch file encoding if necessary (and allowed)
2533                 if (!runparams.pass_thru && !style.pass_thru &&
2534                     runparams.encoding->package() != Encoding::none &&
2535                     font.language()->encoding()->package() != Encoding::none) {
2536                         pair<bool, int> const enc_switch =
2537                                 switchEncoding(os.os(), bparams, runparams,
2538                                         *(font.language()->encoding()));
2539                         if (enc_switch.first) {
2540                                 column += enc_switch.second;
2541                                 runparams.encoding = font.language()->encoding();
2542                         }
2543                 }
2544
2545                 char_type const c = d->text_[i];
2546
2547                 // Do we need to change font?
2548                 if ((font != running_font ||
2549                      font.language() != running_font.language()) &&
2550                         i != body_pos - 1)
2551                 {
2552                         odocstringstream ods;
2553                         column += font.latexWriteStartChanges(ods, bparams,
2554                                                               runparams, basefont,
2555                                                               last_font);
2556                         running_font = font;
2557                         open_font = true;
2558                         docstring fontchange = ods.str();
2559                         // check whether the fontchange ends with a \\textcolor
2560                         // modifier and the text starts with a space (bug 4473)
2561                         docstring const last_modifier = rsplit(fontchange, '\\');
2562                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2563                                 os << fontchange << from_ascii("{}");
2564                         // check if the fontchange ends with a trailing blank
2565                         // (like "\small " (see bug 3382)
2566                         else if (suffixIs(fontchange, ' ') && c == ' ')
2567                                 os << fontchange.substr(0, fontchange.size() - 1)
2568                                    << from_ascii("{}");
2569                         else
2570                                 os << fontchange;
2571                 }
2572
2573                 // FIXME: think about end_pos implementation...
2574                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2575                         // FIXME: integrate this case in latexSpecialChar
2576                         // Do not print the separation of the optional argument
2577                         // if style.pass_thru is false. This works because
2578                         // latexSpecialChar ignores spaces if
2579                         // style.pass_thru is false.
2580                         if (i != body_pos - 1) {
2581                                 if (d->simpleTeXBlanks(runparams, os,
2582                                                 i, column, font, style)) {
2583                                         // A surrogate pair was output. We
2584                                         // must not call latexSpecialChar
2585                                         // in this iteration, since it would output
2586                                         // the combining character again.
2587                                         ++i;
2588                                         continue;
2589                                 }
2590                         }
2591                 }
2592
2593                 OutputParams rp = runparams;
2594                 rp.free_spacing = style.free_spacing;
2595                 rp.local_font = &font;
2596                 rp.intitle = style.intitle;
2597
2598                 // Two major modes:  LaTeX or plain
2599                 // Handle here those cases common to both modes
2600                 // and then split to handle the two modes separately.
2601                 if (c == META_INSET) {
2602                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2603                                 d->latexInset(bparams, os, rp, running_font,
2604                                                 basefont, outerfont, open_font,
2605                                                 runningChange, style, i, column);
2606                         }
2607                 } else {
2608                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2609                                 try {
2610                                         d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2611                                                             style, i, end_pos, column);
2612                                 } catch (EncodingException & e) {
2613                                 if (runparams.dryrun) {
2614                                         os << "<" << _("LyX Warning: ")
2615                                            << _("uncodable character") << " '";
2616                                         os.put(c);
2617                                         os << "'>";
2618                                 } else {
2619                                         // add location information and throw again.
2620                                         e.par_id = id();
2621                                         e.pos = i;
2622                                         throw(e);
2623                                 }
2624                         }
2625                 }
2626                 }
2627
2628                 // Set the encoding to that returned from latexSpecialChar (see
2629                 // comment for encoding member in OutputParams.h)
2630                 runparams.encoding = rp.encoding;
2631         }
2632
2633         // If we have an open font definition, we have to close it
2634         if (open_font) {
2635 #ifdef FIXED_LANGUAGE_END_DETECTION
2636                 if (next_) {
2637                         running_font.latexWriteEndChanges(os, bparams,
2638                                         runparams, basefont,
2639                                         next_->getFont(bparams, 0, outerfont));
2640                 } else {
2641                         running_font.latexWriteEndChanges(os, bparams,
2642                                         runparams, basefont, basefont);
2643                 }
2644 #else
2645 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2646 //FIXME: there as we start another \selectlanguage with the next paragraph if
2647 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2648                 running_font.latexWriteEndChanges(os, bparams, runparams,
2649                                 basefont, basefont);
2650 #endif
2651         }
2652
2653         column += Changes::latexMarkChange(os, bparams, runningChange,
2654                                            Change(Change::UNCHANGED), runparams);
2655
2656         // Needed if there is an optional argument but no contents.
2657         if (body_pos > 0 && body_pos == size()) {
2658                 os << "}]~";
2659         }
2660
2661         if (!style.rightdelim().empty()) {
2662                 os << style.rightdelim();
2663                 column += style.rightdelim().size();
2664         }
2665
2666         if (allowcust && d->endTeXParParams(bparams, os, runparams)
2667             && runparams.encoding != prev_encoding) {
2668                 runparams.encoding = prev_encoding;
2669                 if (!runparams.isFullUnicode())
2670                         os << setEncoding(prev_encoding->iconvName());
2671         }
2672
2673         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2674 }
2675
2676
2677 bool Paragraph::emptyTag() const
2678 {
2679         for (pos_type i = 0; i < size(); ++i) {
2680                 if (Inset const * inset = getInset(i)) {
2681                         InsetCode lyx_code = inset->lyxCode();
2682                         // FIXME testing like that is wrong. What is
2683                         // the intent?
2684                         if (lyx_code != TOC_CODE &&
2685                             lyx_code != INCLUDE_CODE &&
2686                             lyx_code != GRAPHICS_CODE &&
2687                             lyx_code != ERT_CODE &&
2688                             lyx_code != LISTINGS_CODE &&
2689                             lyx_code != FLOAT_CODE &&
2690                             lyx_code != TABULAR_CODE) {
2691                                 return false;
2692                         }
2693                 } else {
2694                         char_type c = d->text_[i];
2695                         if (c != ' ' && c != '\t')
2696                                 return false;
2697                 }
2698         }
2699         return true;
2700 }
2701
2702
2703 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2704         const
2705 {
2706         for (pos_type i = 0; i < size(); ++i) {
2707                 if (Inset const * inset = getInset(i)) {
2708                         InsetCode lyx_code = inset->lyxCode();
2709                         if (lyx_code == LABEL_CODE) {
2710                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2711                                 docstring const & id = il->getParam("name");
2712                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2713                         }
2714                 }
2715         }
2716         return string();
2717 }
2718
2719
2720 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2721         const
2722 {
2723         pos_type i;
2724         for (i = 0; i < size(); ++i) {
2725                 if (Inset const * inset = getInset(i)) {
2726                         inset->docbook(os, runparams);
2727                 } else {
2728                         char_type c = d->text_[i];
2729                         if (c == ' ')
2730                                 break;
2731                         os << sgml::escapeChar(c);
2732                 }
2733         }
2734         return i;
2735 }
2736
2737
2738 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2739         const
2740 {
2741         pos_type i;
2742         for (i = 0; i < size(); ++i) {
2743                 if (Inset const * inset = getInset(i)) {
2744                         inset->xhtml(xs, runparams);
2745                 } else {
2746                         char_type c = d->text_[i];
2747                         if (c == ' ')
2748                                 break;
2749                         xs << c;
2750                 }
2751         }
2752         return i;
2753 }
2754
2755
2756 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2757 {
2758         Font font_old;
2759         pos_type size = text_.size();
2760         for (pos_type i = initial; i < size; ++i) {
2761                 Font font = owner_->getFont(buf.params(), i, outerfont);
2762                 if (text_[i] == META_INSET)
2763                         return false;
2764                 if (i != initial && font != font_old)
2765                         return false;
2766                 font_old = font;
2767         }
2768
2769         return true;
2770 }
2771
2772
2773 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2774                                     odocstream & os,
2775                                     OutputParams const & runparams,
2776                                     Font const & outerfont,
2777                                     pos_type initial) const
2778 {
2779         bool emph_flag = false;
2780
2781         Layout const & style = *d->layout_;
2782         FontInfo font_old =
2783                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2784
2785         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2786                 os << "]]>";
2787
2788         // parsing main loop
2789         for (pos_type i = initial; i < size(); ++i) {
2790                 Font font = getFont(buf.params(), i, outerfont);
2791
2792                 // handle <emphasis> tag
2793                 if (font_old.emph() != font.fontInfo().emph()) {
2794                         if (font.fontInfo().emph() == FONT_ON) {
2795                                 os << "<emphasis>";
2796                                 emph_flag = true;
2797                         } else if (i != initial) {
2798                                 os << "</emphasis>";
2799                                 emph_flag = false;
2800                         }
2801                 }
2802
2803                 if (Inset const * inset = getInset(i)) {
2804                         inset->docbook(os, runparams);
2805                 } else {
2806                         char_type c = d->text_[i];
2807
2808                         if (style.pass_thru)
2809                                 os.put(c);
2810                         else
2811                                 os << sgml::escapeChar(c);
2812                 }
2813                 font_old = font.fontInfo();
2814         }
2815
2816         if (emph_flag) {
2817                 os << "</emphasis>";
2818         }
2819
2820         if (style.free_spacing)
2821                 os << '\n';
2822         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2823                 os << "<![CDATA[";
2824 }
2825
2826
2827 namespace {
2828 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2829                   vector<html::EndFontTag> & tagsToClose,
2830                   bool & flag, FontState curstate, html::FontTypes type)
2831 {
2832         if (curstate == FONT_ON) {
2833                 tagsToOpen.push_back(html::FontTag(type));
2834                 flag = true;
2835         } else if (flag) {
2836                 tagsToClose.push_back(html::EndFontTag(type));
2837                 flag = false;
2838         }
2839 }
2840 }
2841
2842
2843 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2844                                     XHTMLStream & xs,
2845                                     OutputParams const & runparams,
2846                                     Font const & outerfont,
2847                                     pos_type initial) const
2848 {
2849         docstring retval;
2850
2851         // track whether we have opened these tags
2852         bool emph_flag = false;
2853         bool bold_flag = false;
2854         bool noun_flag = false;
2855         bool ubar_flag = false;
2856         bool dbar_flag = false;
2857         bool sout_flag = false;
2858         bool wave_flag = false;
2859         // shape tags
2860         bool shap_flag = false;
2861         // family tags
2862         bool faml_flag = false;
2863         // size tags
2864         bool size_flag = false;
2865
2866         Layout const & style = *d->layout_;
2867
2868         xs.startParagraph(allowEmpty());
2869
2870         FontInfo font_old =
2871                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2872
2873         FontShape  curr_fs   = INHERIT_SHAPE;
2874         FontFamily curr_fam  = INHERIT_FAMILY;
2875         FontSize   curr_size = FONT_SIZE_INHERIT;
2876         
2877         string const default_family = 
2878                 buf.masterBuffer()->params().fonts_default_family;              
2879
2880         vector<html::FontTag> tagsToOpen;
2881         vector<html::EndFontTag> tagsToClose;
2882         
2883         // parsing main loop
2884         for (pos_type i = initial; i < size(); ++i) {
2885                 // let's not show deleted material in the output
2886                 if (isDeleted(i))
2887                         continue;
2888
2889                 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2890
2891                 // emphasis
2892                 FontState curstate = font.fontInfo().emph();
2893                 if (font_old.emph() != curstate)
2894                         doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2895
2896                 // noun
2897                 curstate = font.fontInfo().noun();
2898                 if (font_old.noun() != curstate)
2899                         doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2900
2901                 // underbar
2902                 curstate = font.fontInfo().underbar();
2903                 if (font_old.underbar() != curstate)
2904                         doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2905         
2906                 // strikeout
2907                 curstate = font.fontInfo().strikeout();
2908                 if (font_old.strikeout() != curstate)
2909                         doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2910
2911                 // double underbar
2912                 curstate = font.fontInfo().uuline();
2913                 if (font_old.uuline() != curstate)
2914                         doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2915
2916                 // wavy line
2917                 curstate = font.fontInfo().uwave();
2918                 if (font_old.uwave() != curstate)
2919                         doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2920
2921                 // bold
2922                 // a little hackish, but allows us to reuse what we have.
2923                 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2924                 if (font_old.series() != font.fontInfo().series())
2925                         doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2926
2927                 // Font shape
2928                 curr_fs = font.fontInfo().shape();
2929                 FontShape old_fs = font_old.shape();
2930                 if (old_fs != curr_fs) {
2931                         if (shap_flag) {
2932                                 switch (old_fs) {
2933                                 case ITALIC_SHAPE:
2934                                         tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2935                                         break;
2936                                 case SLANTED_SHAPE:
2937                                         tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2938                                         break;
2939                                 case SMALLCAPS_SHAPE:
2940                                         tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2941                                         break;
2942                                 case UP_SHAPE:
2943                                 case INHERIT_SHAPE:
2944                                         break;
2945                                 default:
2946                                         // the other tags are for internal use
2947                                         LATTEST(false);
2948                                         break;
2949                                 }
2950                                 shap_flag = false;
2951                         }
2952                         switch (curr_fs) {
2953                         case ITALIC_SHAPE:
2954                                 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2955                                 shap_flag = true;
2956                                 break;
2957                         case SLANTED_SHAPE:
2958                                 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2959                                 shap_flag = true;
2960                                 break;
2961                         case SMALLCAPS_SHAPE:
2962                                 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2963                                 shap_flag = true;
2964                                 break;
2965                         case UP_SHAPE:
2966                         case INHERIT_SHAPE:
2967                                 break;
2968                         default:
2969                                 // the other tags are for internal use
2970                                 LATTEST(false);
2971                                 break;
2972                         }
2973                 }
2974
2975                 // Font family
2976                 curr_fam = font.fontInfo().family();
2977                 FontFamily old_fam = font_old.family();
2978                 if (old_fam != curr_fam) {
2979                         if (faml_flag) {
2980                                 switch (old_fam) {
2981                                 case ROMAN_FAMILY:
2982                                         tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2983                                         break;
2984                                 case SANS_FAMILY:
2985                                         tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2986                                         break;
2987                                 case TYPEWRITER_FAMILY:
2988                                         tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2989                                         break;
2990                                 case INHERIT_FAMILY:
2991                                         break;
2992                                 default:
2993                                         // the other tags are for internal use
2994                                         LATTEST(false);
2995                                         break;
2996                                 }
2997                                 faml_flag = false;
2998                         }
2999                         switch (curr_fam) {
3000                         case ROMAN_FAMILY:
3001                                 // we will treat a "default" font family as roman, since we have
3002                                 // no other idea what to do.
3003                                 if (default_family != "rmdefault" && default_family != "default") {
3004                                         tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3005                                         faml_flag = true;
3006                                 }
3007                                 break;
3008                         case SANS_FAMILY:
3009                                 if (default_family != "sfdefault") {
3010                                         tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3011                                         faml_flag = true;
3012                                 }
3013                                 break;
3014                         case TYPEWRITER_FAMILY:
3015                                 if (default_family != "ttdefault") {
3016                                         tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3017                                         faml_flag = true;
3018                                 }
3019                                 break;
3020                         case INHERIT_FAMILY:
3021                                 break;
3022                         default:
3023                                 // the other tags are for internal use
3024                                 LATTEST(false);
3025                                 break;
3026                         }
3027                 }
3028
3029                 // Font size
3030                 curr_size = font.fontInfo().size();
3031                 FontSize old_size = font_old.size();
3032                 if (old_size != curr_size) {
3033                         if (size_flag) {
3034                                 switch (old_size) {
3035                                 case FONT_SIZE_TINY:
3036                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3037                                         break;
3038                                 case FONT_SIZE_SCRIPT:
3039                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3040                                         break;
3041                                 case FONT_SIZE_FOOTNOTE:
3042                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3043                                         break;
3044                                 case FONT_SIZE_SMALL:
3045                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3046                                         break;
3047                                 case FONT_SIZE_LARGE:
3048                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3049                                         break;
3050                                 case FONT_SIZE_LARGER:
3051                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3052                                         break;
3053                                 case FONT_SIZE_LARGEST:
3054                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3055                                         break;
3056                                 case FONT_SIZE_HUGE:
3057                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3058                                         break;
3059                                 case FONT_SIZE_HUGER:
3060                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3061                                         break;
3062                                 case FONT_SIZE_INCREASE:
3063                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3064                                         break;
3065                                 case FONT_SIZE_DECREASE:
3066                                         tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3067                                         break;
3068                                 case FONT_SIZE_INHERIT:
3069                                 case FONT_SIZE_NORMAL:
3070                                         break;
3071                                 default:
3072                                         // the other tags are for internal use
3073                                         LATTEST(false);
3074                                         break;
3075                                 }
3076                                 size_flag = false;
3077                         }
3078                         switch (curr_size) {
3079                         case FONT_SIZE_TINY:
3080                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3081                                 size_flag = true;
3082                                 break;
3083                         case FONT_SIZE_SCRIPT:
3084                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3085                                 size_flag = true;
3086                                 break;
3087                         case FONT_SIZE_FOOTNOTE:
3088                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3089                                 size_flag = true;
3090                                 break;
3091                         case FONT_SIZE_SMALL:
3092                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3093                                 size_flag = true;
3094                                 break;
3095                         case FONT_SIZE_LARGE:
3096                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3097                                 size_flag = true;
3098                                 break;
3099                         case FONT_SIZE_LARGER:
3100                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3101                                 size_flag = true;
3102                                 break;
3103                         case FONT_SIZE_LARGEST:
3104                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3105                                 size_flag = true;
3106                                 break;
3107                         case FONT_SIZE_HUGE:
3108                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3109                                 size_flag = true;
3110                                 break;
3111                         case FONT_SIZE_HUGER:
3112                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3113                                 size_flag = true;
3114                                 break;
3115                         case FONT_SIZE_INCREASE:
3116                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3117                                 size_flag = true;
3118                                 break;
3119                         case FONT_SIZE_DECREASE:
3120                                 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3121                                 size_flag = true;
3122                                 break;
3123                         case FONT_SIZE_NORMAL:
3124                         case FONT_SIZE_INHERIT:
3125                                 break;
3126                         default:
3127                                 // the other tags are for internal use
3128                                 LATTEST(false);
3129                                 break;
3130                         }
3131                 }
3132
3133                 // FIXME XHTML
3134                 // Other such tags? What about the other text ranges?
3135
3136                 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3137                 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3138                 for (; cit != cen; ++cit)
3139                         xs << *cit;
3140
3141                 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3142                 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3143                 for (; sit != sen; ++sit)
3144                         xs << *sit;
3145
3146                 tagsToClose.clear();
3147                 tagsToOpen.clear();
3148
3149                 Inset const * inset = getInset(i);
3150                 if (inset) {
3151                         if (!runparams.for_toc || inset->isInToc()) {
3152                                 OutputParams np = runparams;
3153                                 np.local_font = &font;
3154                                 if (!inset->getLayout().htmlisblock())
3155                                         np.html_in_par = true;
3156                                 retval += inset->xhtml(xs, np);
3157                         }
3158                 } else {
3159                         char_type c = getUChar(buf.masterBuffer()->params(), i);
3160
3161                         if (style.pass_thru || runparams.pass_thru)
3162                                 xs << c;
3163                         else if (c == '-') {
3164                                 docstring str;
3165                                 int j = i + 1;
3166                                 if (j < size() && d->text_[j] == '-') {
3167                                         j += 1;
3168                                         if (j < size() && d->text_[j] == '-') {
3169                                                 str += from_ascii("&mdash;");
3170                                                 i += 2;
3171                                         } else {
3172                                                 str += from_ascii("&ndash;");
3173                                                 i += 1;
3174                                         }
3175                                 }
3176                                 else
3177                                         str += c;
3178                                 // We don't want to escape the entities. Note that
3179                                 // it is safe to do this, since str can otherwise
3180                                 // only be "-". E.g., it can't be "<".
3181                                 xs << XHTMLStream::ESCAPE_NONE << str;
3182                         } else
3183                                 xs << c;
3184                 }
3185                 font_old = font.fontInfo();
3186         }
3187
3188         xs.closeFontTags();
3189         xs.endParagraph();
3190         return retval;
3191 }
3192
3193
3194 bool Paragraph::isHfill(pos_type pos) const
3195 {
3196         Inset const * inset = getInset(pos);
3197         return inset && (inset->lyxCode() == SPACE_CODE &&
3198                          inset->isStretchableSpace());
3199 }
3200
3201
3202 bool Paragraph::isNewline(pos_type pos) const
3203 {
3204         Inset const * inset = getInset(pos);
3205         return inset && inset->lyxCode() == NEWLINE_CODE;
3206 }
3207
3208
3209 bool Paragraph::isEnvSeparator(pos_type pos) const
3210 {
3211         Inset const * inset = getInset(pos);
3212         return inset && inset->lyxCode() == SEPARATOR_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 OutputParams *runparams) 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                         if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3376                                 LASSERT(runparams != 0, return docstring());
3377                                 getInset(i)->plaintext(os, *runparams);
3378                         } else {
3379                                 getInset(i)->toString(os);
3380                                 if (getInset(i)->asInsetMath())
3381                                         os << " ";
3382                         }
3383                 }
3384         }
3385
3386         return os.str();
3387 }
3388
3389
3390 void Paragraph::forOutliner(docstring & os, size_t maxlen) const
3391 {
3392         if (!d->params_.labelString().empty())
3393                 os += d->params_.labelString() + ' ';
3394         for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3395                 if (isDeleted(i))
3396                         continue;
3397                 char_type const c = d->text_[i];
3398                 if (isPrintable(c))
3399                         os += c;
3400                 else if (c == '\t' || c == '\n')
3401                         os += ' ';
3402                 else if (c == META_INSET)
3403                         getInset(i)->forOutliner(os, maxlen);
3404         }
3405 }
3406
3407
3408 void Paragraph::setInsetOwner(Inset const * inset)
3409 {
3410         d->inset_owner_ = inset;
3411 }
3412
3413
3414 int Paragraph::id() const
3415 {
3416         return d->id_;
3417 }
3418
3419
3420 void Paragraph::setId(int id)
3421 {
3422         d->id_ = id;
3423 }
3424
3425
3426 Layout const & Paragraph::layout() const
3427 {
3428         return *d->layout_;
3429 }
3430
3431
3432 void Paragraph::setLayout(Layout const & layout)
3433 {
3434         d->layout_ = &layout;
3435 }
3436
3437
3438 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3439 {
3440         setLayout(tc.defaultLayout());
3441 }
3442
3443
3444 void Paragraph::setPlainLayout(DocumentClass const & tc)
3445 {
3446         setLayout(tc.plainLayout());
3447 }
3448
3449
3450 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3451 {
3452         if (usePlainLayout())
3453                 setPlainLayout(tclass);
3454         else
3455                 setDefaultLayout(tclass);
3456 }
3457
3458
3459 Inset const & Paragraph::inInset() const
3460 {
3461         LBUFERR(d->inset_owner_);
3462         return *d->inset_owner_;
3463 }
3464
3465
3466 ParagraphParameters & Paragraph::params()
3467 {
3468         return d->params_;
3469 }
3470
3471
3472 ParagraphParameters const & Paragraph::params() const
3473 {
3474         return d->params_;
3475 }
3476
3477
3478 bool Paragraph::isFreeSpacing() const
3479 {
3480         if (d->layout_->free_spacing)
3481                 return true;
3482         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3483 }
3484
3485
3486 bool Paragraph::allowEmpty() const
3487 {
3488         if (d->layout_->keepempty)
3489                 return true;
3490         return d->inset_owner_ && d->inset_owner_->allowEmpty();
3491 }
3492
3493
3494 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3495 {
3496         if (!Encodings::isArabicChar(c))
3497                 return c;
3498
3499         char_type prev_char = ' ';
3500         char_type next_char = ' ';
3501
3502         for (pos_type i = pos - 1; i >= 0; --i) {
3503                 char_type const par_char = d->text_[i];
3504                 if (!Encodings::isArabicComposeChar(par_char)) {
3505                         prev_char = par_char;
3506                         break;
3507                 }
3508         }
3509
3510         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3511                 char_type const par_char = d->text_[i];
3512                 if (!Encodings::isArabicComposeChar(par_char)) {
3513                         next_char = par_char;
3514                         break;
3515                 }
3516         }
3517
3518         if (Encodings::isArabicChar(next_char)) {
3519                 if (Encodings::isArabicChar(prev_char) &&
3520                         !Encodings::isArabicSpecialChar(prev_char))
3521                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3522                 else
3523                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3524         } else {
3525                 if (Encodings::isArabicChar(prev_char) &&
3526                         !Encodings::isArabicSpecialChar(prev_char))
3527                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
3528                 else
3529                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3530         }
3531 }
3532
3533
3534 bool Paragraph::brokenBiblio() const
3535 {
3536         // there is a problem if there is no bibitem at position 0 or
3537         // if there is another bibitem in the paragraph.
3538         return d->layout_->labeltype == LABEL_BIBLIO
3539                 && (d->insetlist_.find(BIBITEM_CODE) != 0
3540                     || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3541 }
3542
3543
3544 int Paragraph::fixBiblio(Buffer const & buffer)
3545 {
3546         // FIXME: What about the case where paragraph is not BIBLIO
3547         // but there is an InsetBibitem?
3548         // FIXME: when there was already an inset at 0, the return value is 1,
3549         // which does not tell whether another inset has been remove; the
3550         // cursor cannot be correctly updated.
3551
3552         if (d->layout_->labeltype != LABEL_BIBLIO)
3553                 return 0;
3554
3555         bool const track_changes = buffer.params().track_changes;
3556         int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3557         bool const hasbibitem0 = bibitem_pos == 0;
3558
3559         if (hasbibitem0) {
3560                 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3561                 // There was an InsetBibitem at pos 0, and no other one => OK
3562                 if (bibitem_pos == -1)
3563                         return 0;
3564                 // there is a bibitem at the 0 position, but since
3565                 // there is a second one, we copy the second on the
3566                 // first. We're assuming there are at most two of
3567                 // these, which there should be.
3568                 // FIXME: why does it make sense to do that rather
3569                 // than keep the first? (JMarc)
3570                 Inset * inset = releaseInset(bibitem_pos);
3571                 d->insetlist_.begin()->inset = inset;
3572                 return -bibitem_pos;
3573         }
3574
3575         // We need to create an inset at the beginning
3576         Inset * inset = 0;
3577         if (bibitem_pos > 0) {
3578                 // there was one somewhere in the paragraph, let's move it
3579                 inset = d->insetlist_.release(bibitem_pos);
3580                 eraseChar(bibitem_pos, track_changes);
3581         } else
3582                 // make a fresh one
3583                 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3584                                          InsetCommandParams(BIBITEM_CODE));
3585
3586         Font font(inherit_font, buffer.params().language);
3587         insertInset(0, inset, font, Change(track_changes ? Change::INSERTED 
3588                                                    : Change::UNCHANGED));
3589
3590         return 1;
3591 }
3592
3593
3594 void Paragraph::checkAuthors(AuthorList const & authorList)
3595 {
3596         d->changes_.checkAuthors(authorList);
3597 }
3598
3599
3600 bool Paragraph::isChanged(pos_type pos) const
3601 {
3602         return lookupChange(pos).changed();
3603 }
3604
3605
3606 bool Paragraph::isInserted(pos_type pos) const
3607 {
3608         return lookupChange(pos).inserted();
3609 }
3610
3611
3612 bool Paragraph::isDeleted(pos_type pos) const
3613 {
3614         return lookupChange(pos).deleted();
3615 }
3616
3617
3618 InsetList const & Paragraph::insetList() const
3619 {
3620         return d->insetlist_;
3621 }
3622
3623
3624 void Paragraph::setBuffer(Buffer & b)
3625 {
3626         d->insetlist_.setBuffer(b);
3627 }
3628
3629
3630 Inset * Paragraph::releaseInset(pos_type pos)
3631 {
3632         Inset * inset = d->insetlist_.release(pos);
3633         /// does not honour change tracking!
3634         eraseChar(pos, false);
3635         return inset;
3636 }
3637
3638
3639 Inset * Paragraph::getInset(pos_type pos)
3640 {
3641         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3642                  ? d->insetlist_.get(pos) : 0;
3643 }
3644
3645
3646 Inset const * Paragraph::getInset(pos_type pos) const
3647 {
3648         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3649                  ? d->insetlist_.get(pos) : 0;
3650 }
3651
3652
3653 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3654                 pos_type & right, TextCase action)
3655 {
3656         // process sequences of modified characters; in change
3657         // tracking mode, this approach results in much better
3658         // usability than changing case on a char-by-char basis
3659         // We also need to track the current font, since font
3660         // changes within sequences can occur.
3661         vector<pair<char_type, Font> > changes;
3662
3663         bool const trackChanges = bparams.track_changes;
3664
3665         bool capitalize = true;
3666
3667         for (; pos < right; ++pos) {
3668                 char_type oldChar = d->text_[pos];
3669                 char_type newChar = oldChar;
3670
3671                 // ignore insets and don't play with deleted text!
3672                 if (oldChar != META_INSET && !isDeleted(pos)) {
3673                         switch (action) {
3674                                 case text_lowercase:
3675                                         newChar = lowercase(oldChar);
3676                                         break;
3677                                 case text_capitalization:
3678                                         if (capitalize) {
3679                                                 newChar = uppercase(oldChar);
3680                                                 capitalize = false;
3681                                         }
3682                                         break;
3683                                 case text_uppercase:
3684                                         newChar = uppercase(oldChar);
3685                                         break;
3686                         }
3687                 }
3688
3689                 if (isWordSeparator(pos) || isDeleted(pos)) {
3690                         // permit capitalization again
3691                         capitalize = true;
3692                 }
3693
3694                 if (oldChar != newChar) {
3695                         changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3696                         if (pos != right - 1)
3697                                 continue;
3698                         // step behind the changing area
3699                         pos++;
3700                 }
3701
3702                 int erasePos = pos - changes.size();
3703                 for (size_t i = 0; i < changes.size(); i++) {
3704                         insertChar(pos, changes[i].first,
3705                                    changes[i].second,
3706                                    trackChanges);
3707                         if (!eraseChar(erasePos, trackChanges)) {
3708                                 ++erasePos;
3709                                 ++pos; // advance
3710                                 ++right; // expand selection
3711                         }
3712                 }
3713                 changes.clear();
3714         }
3715 }
3716
3717
3718 int Paragraph::find(docstring const & str, bool cs, bool mw,
3719                 pos_type start_pos, bool del) const
3720 {
3721         pos_type pos = start_pos;
3722         int const strsize = str.length();
3723         int i = 0;
3724         pos_type const parsize = d->text_.size();
3725         for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3726                 // Ignore "invisible" letters such as ligature breaks
3727                 // and hyphenation chars while searching
3728                 while (pos < parsize - 1 && isInset(pos)) {
3729                         odocstringstream os;
3730                         getInset(pos)->toString(os);
3731                         if (!getInset(pos)->isLetter() || !os.str().empty())
3732                                 break;
3733                         pos++;
3734                 }
3735                 if (cs && str[i] != d->text_[pos])
3736                         break;
3737                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3738                         break;
3739                 if (!del && isDeleted(pos))
3740                         break;
3741         }
3742
3743         if (i != strsize)
3744                 return 0;
3745
3746         // if necessary, check whether string matches word
3747         if (mw) {
3748                 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3749                         return 0;
3750                 if (pos < parsize
3751                         && !isWordSeparator(pos))
3752                         return 0;
3753         }
3754
3755         return pos - start_pos;
3756 }
3757
3758
3759 char_type Paragraph::getChar(pos_type pos) const
3760 {
3761         return d->text_[pos];
3762 }
3763
3764
3765 pos_type Paragraph::size() const
3766 {
3767         return d->text_.size();
3768 }
3769
3770
3771 bool Paragraph::empty() const
3772 {
3773         return d->text_.empty();
3774 }
3775
3776
3777 bool Paragraph::isInset(pos_type pos) const
3778 {
3779         return d->text_[pos] == META_INSET;
3780 }
3781
3782
3783 bool Paragraph::isSeparator(pos_type pos) const
3784 {
3785         //FIXME: Are we sure this can be the only separator?
3786         return d->text_[pos] == ' ';
3787 }
3788
3789
3790 void Paragraph::deregisterWords()
3791 {
3792         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3793         Private::LangWordsMap::const_iterator ite = d->words_.end();
3794         for (; itl != ite; ++itl) {
3795                 WordList * wl = theWordList(itl->first);
3796                 Private::Words::const_iterator it = (itl->second).begin();
3797                 Private::Words::const_iterator et = (itl->second).end();
3798                 for (; it != et; ++it)
3799                         wl->remove(*it);
3800         }
3801         d->words_.clear();
3802 }
3803
3804
3805 void Paragraph::locateWord(pos_type & from, pos_type & to,
3806         word_location const loc) const
3807 {
3808         switch (loc) {
3809         case WHOLE_WORD_STRICT:
3810                 if (from == 0 || from == size()
3811                     || isWordSeparator(from)
3812                     || isWordSeparator(from - 1)) {
3813                         to = from;
3814                         return;
3815                 }
3816                 // no break here, we go to the next
3817
3818         case WHOLE_WORD:
3819                 // If we are already at the beginning of a word, do nothing
3820                 if (!from || isWordSeparator(from - 1))
3821                         break;
3822                 // no break here, we go to the next
3823
3824         case PREVIOUS_WORD:
3825                 // always move the cursor to the beginning of previous word
3826                 while (from && !isWordSeparator(from - 1))
3827                         --from;
3828                 break;
3829         case NEXT_WORD:
3830                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3831                 break;
3832         case PARTIAL_WORD:
3833                 // no need to move the 'from' cursor
3834                 break;
3835         }
3836         to = from;
3837         while (to < size() && !isWordSeparator(to))
3838                 ++to;
3839 }
3840
3841
3842 void Paragraph::collectWords()
3843 {
3844         for (pos_type pos = 0; pos < size(); ++pos) {
3845                 if (isWordSeparator(pos))
3846                         continue;
3847                 pos_type from = pos;
3848                 locateWord(from, pos, WHOLE_WORD);
3849                 if (pos < from + lyxrc.completion_minlength)
3850                         continue;
3851                 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3852                 if (cit == d->fontlist_.end())
3853                         return;
3854                 Language const * lang = cit->font().language();
3855                 docstring const word = asString(from, pos, AS_STR_NONE);
3856                 d->words_[lang->lang()].insert(word);
3857         }
3858 }
3859
3860
3861 void Paragraph::registerWords()
3862 {
3863         Private::LangWordsMap::const_iterator itl = d->words_.begin();
3864         Private::LangWordsMap::const_iterator ite = d->words_.end();
3865         for (; itl != ite; ++itl) {
3866                 WordList * wl = theWordList(itl->first);
3867                 Private::Words::const_iterator it = (itl->second).begin();
3868                 Private::Words::const_iterator et = (itl->second).end();
3869                 for (; it != et; ++it)
3870                         wl->insert(*it);
3871         }
3872 }
3873
3874
3875 void Paragraph::updateWords()
3876 {
3877         deregisterWords();
3878         collectWords();
3879         registerWords();
3880 }
3881
3882
3883 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3884 {
3885         SkipPositionsIterator begin = skips.begin();
3886         SkipPositions::iterator end = skips.end();
3887         if (pos > 0 && begin < end) {
3888                 --end;
3889                 if (end->last == pos - 1) {
3890                         end->last = pos;
3891                         return;
3892                 }
3893         }
3894         skips.insert(end, FontSpan(pos, pos));
3895 }
3896
3897
3898 Language * Paragraph::Private::locateSpellRange(
3899         pos_type & from, pos_type & to,
3900         SkipPositions & skips) const
3901 {
3902         // skip leading white space
3903         while (from < to && owner_->isWordSeparator(from))
3904                 ++from;
3905         // don't check empty range
3906         if (from >= to)
3907                 return 0;
3908         // get current language
3909         Language * lang = getSpellLanguage(from);
3910         pos_type last = from;
3911         bool samelang = true;
3912         bool sameinset = true;
3913         while (last < to && samelang && sameinset) {
3914                 // hop to end of word
3915                 while (last < to && !owner_->isWordSeparator(last)) {
3916                         if (owner_->getInset(last)) {
3917                                 appendSkipPosition(skips, last);
3918                         } else if (owner_->isDeleted(last)) {
3919                                 appendSkipPosition(skips, last);
3920                         }
3921                         ++last;
3922                 }
3923                 // hop to next word while checking for insets
3924                 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3925                         if (Inset const * inset = owner_->getInset(last))
3926                                 sameinset = inset->isChar() && inset->isLetter();
3927                         if (sameinset && owner_->isDeleted(last)) {
3928                                 appendSkipPosition(skips, last);
3929                         }
3930                         if (sameinset)
3931                                 last++;
3932                 }
3933                 if (sameinset && last < to) {
3934                         // now check for language change
3935                         samelang = lang == getSpellLanguage(last);
3936                 }
3937         }
3938         // if language change detected backstep is needed
3939         if (!samelang)
3940                 --last;
3941         to = last;
3942         return lang;
3943 }
3944
3945
3946 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3947 {
3948         Language * lang =
3949                 const_cast<Language *>(owner_->getFontSettings(
3950                         inset_owner_->buffer().params(), from).language());
3951         if (lang == inset_owner_->buffer().params().language
3952                 && !lyxrc.spellchecker_alt_lang.empty()) {
3953                 string lang_code;
3954                 string const lang_variety =
3955                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3956                 lang->setCode(lang_code);
3957                 lang->setVariety(lang_variety);
3958         }
3959         return lang;
3960 }
3961
3962
3963 void Paragraph::requestSpellCheck(pos_type pos)
3964 {
3965         d->requestSpellCheck(pos);
3966 }
3967
3968
3969 bool Paragraph::needsSpellCheck() const
3970 {
3971         SpellChecker::ChangeNumber speller_change_number = 0;
3972         if (theSpellChecker())
3973                 speller_change_number = theSpellChecker()->changeNumber();
3974         if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3975                 d->speller_state_.needsCompleteRefresh(speller_change_number);
3976         }
3977         return d->needsSpellCheck();
3978 }
3979
3980
3981 bool Paragraph::Private::ignoreWord(docstring const & word) const
3982 {
3983         // Ignore words with digits
3984         // FIXME: make this customizable
3985         // (note that some checkers ignore words with digits by default)
3986         docstring::const_iterator cit = word.begin();
3987         docstring::const_iterator const end = word.end();
3988         for (; cit != end; ++cit) {
3989                 if (isNumber((*cit)))
3990                         return true;
3991         }
3992         return false;
3993 }
3994
3995
3996 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3997         WordLangTuple & wl, docstring_list & suggestions,
3998         bool do_suggestion, bool check_learned) const
3999 {
4000         SpellChecker::Result result = SpellChecker::WORD_OK;
4001         SpellChecker * speller = theSpellChecker();
4002         if (!speller)
4003                 return result;
4004
4005         if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4006                 return result;
4007
4008         locateWord(from, to, WHOLE_WORD);
4009         if (from == to || from >= size())
4010                 return result;
4011
4012         docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4013         Language * lang = d->getSpellLanguage(from);
4014
4015         wl = WordLangTuple(word, lang);
4016
4017         if (word.empty())
4018                 return result;
4019
4020         if (needsSpellCheck() || check_learned) {
4021                 pos_type end = to;
4022                 if (!d->ignoreWord(word)) {
4023                         bool const trailing_dot = to < size() && d->text_[to] == '.';
4024                         result = speller->check(wl);
4025                         if (SpellChecker::misspelled(result) && trailing_dot) {
4026                                 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4027                                 result = speller->check(wl);
4028                                 if (!SpellChecker::misspelled(result)) {
4029                                         LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4030                                            word << "\" [" <<
4031                                            from << ".." << to << "]");
4032                                 } else {
4033                                         // spell check with dot appended failed too
4034                                         // restore original word/lang value
4035                                         word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4036                                         wl = WordLangTuple(word, lang);
4037                                 }
4038                         }
4039                 }
4040                 if (!SpellChecker::misspelled(result)) {
4041                         // area up to the begin of the next word is not misspelled
4042                         while (end < size() && isWordSeparator(end))
4043                                 ++end;
4044                 }
4045                 d->setMisspelled(from, end, result);
4046         } else {
4047                 result = d->speller_state_.getState(from);
4048         }
4049
4050         if (do_suggestion)
4051                 suggestions.clear();
4052
4053         if (SpellChecker::misspelled(result)) {
4054                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4055                            word << "\" [" <<
4056                            from << ".." << to << "]");
4057                 if (do_suggestion)
4058                         speller->suggest(wl, suggestions);
4059         }
4060         return result;
4061 }
4062
4063
4064 void Paragraph::Private::markMisspelledWords(
4065         pos_type const & first, pos_type const & last,
4066         SpellChecker::Result result,
4067         docstring const & word,
4068         SkipPositions const & skips)
4069 {
4070         if (!SpellChecker::misspelled(result)) {
4071                 setMisspelled(first, last, SpellChecker::WORD_OK);
4072                 return;
4073         }
4074         int snext = first;
4075         SpellChecker * speller = theSpellChecker();
4076         // locate and enumerate the error positions
4077         int nerrors = speller->numMisspelledWords();
4078         int numskipped = 0;
4079         SkipPositionsIterator it = skips.begin();
4080         SkipPositionsIterator et = skips.end();
4081         for (int index = 0; index < nerrors; ++index) {
4082                 int wstart;
4083                 int wlen = 0;
4084                 speller->misspelledWord(index, wstart, wlen);
4085                 /// should not happen if speller supports range checks
4086                 if (!wlen) continue;
4087                 docstring const misspelled = word.substr(wstart, wlen);
4088                 wstart += first + numskipped;
4089                 if (snext < wstart) {
4090                         /// mark the range of correct spelling
4091                         numskipped += countSkips(it, et, wstart);
4092                         setMisspelled(snext,
4093                                 wstart - 1, SpellChecker::WORD_OK);
4094                 }
4095                 snext = wstart + wlen;
4096                 numskipped += countSkips(it, et, snext);
4097                 /// mark the range of misspelling
4098                 setMisspelled(wstart, snext, result);
4099                 LYXERR(Debug::GUI, "misspelled word: \"" <<
4100                            misspelled << "\" [" <<
4101                            wstart << ".." << (snext-1) << "]");
4102                 ++snext;
4103         }
4104         if (snext <= last) {
4105                 /// mark the range of correct spelling at end
4106                 setMisspelled(snext, last, SpellChecker::WORD_OK);
4107         }
4108 }
4109
4110
4111 void Paragraph::spellCheck() const
4112 {
4113         SpellChecker * speller = theSpellChecker();
4114         if (!speller || empty() ||!needsSpellCheck())
4115                 return;
4116         pos_type start;
4117         pos_type endpos;
4118         d->rangeOfSpellCheck(start, endpos);
4119         if (speller->canCheckParagraph()) {
4120                 // loop until we leave the range
4121                 for (pos_type first = start; first < endpos; ) {
4122                         pos_type last = endpos;
4123                         Private::SkipPositions skips;
4124                         Language * lang = d->locateSpellRange(first, last, skips);
4125                         if (first >= endpos)
4126                                 break;
4127                         // start the spell checker on the unit of meaning
4128                         docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4129                         WordLangTuple wl = WordLangTuple(word, lang);
4130                         SpellChecker::Result result = word.size() ?
4131                                 speller->check(wl) : SpellChecker::WORD_OK;
4132                         d->markMisspelledWords(first, last, result, word, skips);
4133                         first = ++last;
4134                 }
4135         } else {
4136                 static docstring_list suggestions;
4137                 pos_type to = endpos;
4138                 while (start < endpos) {
4139                         WordLangTuple wl;
4140                         spellCheck(start, to, wl, suggestions, false);
4141                         start = to + 1;
4142                 }
4143         }
4144         d->readySpellCheck();
4145 }
4146
4147
4148 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4149 {
4150         bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4151         if (result || pos <= 0 || pos > size())
4152                 return result;
4153         if (check_boundary && (pos == size() || isWordSeparator(pos)))
4154                 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4155         return result;
4156 }
4157
4158
4159 string Paragraph::magicLabel() const
4160 {
4161         stringstream ss;
4162         ss << "magicparlabel-" << id();
4163         return ss.str();
4164 }
4165
4166
4167 } // namespace lyx