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