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