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