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