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