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