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