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