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