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