]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
this was not intended to go in.
[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         if (features.runparams().flavor == OutputParams::HTML 
1090             && layout_->htmltitle()) {
1091                 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1092         }
1093         
1094         // check the params.
1095         if (!params_.spacing().isDefault())
1096                 features.require("setspace");
1097
1098         // then the layouts
1099         features.useLayout(layout_->name());
1100
1101         // then the fonts
1102         fontlist_.validate(features);
1103
1104         // then the indentation
1105         if (!params_.leftIndent().zero())
1106                 features.require("ParagraphLeftIndent");
1107
1108         // then the insets
1109         InsetList::const_iterator icit = insetlist_.begin();
1110         InsetList::const_iterator iend = insetlist_.end();
1111         for (; icit != iend; ++icit) {
1112                 if (icit->inset) {
1113                         icit->inset->validate(features);
1114                         if (layout_->needprotect &&
1115                             icit->inset->lyxCode() == FOOT_CODE)
1116                                 features.require("NeedLyXFootnoteCode");
1117                 }
1118         }
1119
1120         // then the contents
1121         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1122                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1123                         if (!special_phrases[pnr].builtin
1124                             && isTextAt(special_phrases[pnr].phrase, i)) {
1125                                 features.require(special_phrases[pnr].phrase);
1126                                 break;
1127                         }
1128                 }
1129                 Encodings::validate(text_[i], features);
1130         }
1131 }
1132
1133 /////////////////////////////////////////////////////////////////////
1134 //
1135 // Paragraph
1136 //
1137 /////////////////////////////////////////////////////////////////////
1138
1139 namespace {
1140         Layout const emptyParagraphLayout;
1141 }
1142
1143 Paragraph::Paragraph() 
1144         : d(new Paragraph::Private(this, emptyParagraphLayout))
1145 {
1146         itemdepth = 0;
1147         d->params_.clear();
1148 }
1149
1150
1151 Paragraph::Paragraph(Paragraph const & par)
1152         : itemdepth(par.itemdepth),
1153         d(new Paragraph::Private(*par.d, this))
1154 {
1155         registerWords();
1156 }
1157
1158
1159 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1160         : itemdepth(par.itemdepth),
1161         d(new Paragraph::Private(*par.d, this, beg, end))
1162 {
1163         registerWords();
1164 }
1165
1166
1167 Paragraph & Paragraph::operator=(Paragraph const & par)
1168 {
1169         // needed as we will destroy the private part before copying it
1170         if (&par != this) {
1171                 itemdepth = par.itemdepth;
1172
1173                 deregisterWords();
1174                 delete d;
1175                 d = new Private(*par.d, this);
1176                 registerWords();
1177         }
1178         return *this;
1179 }
1180
1181
1182 Paragraph::~Paragraph()
1183 {
1184         deregisterWords();
1185         delete d;
1186 }
1187
1188
1189 namespace {
1190
1191 // this shall be called just before every "os << ..." action.
1192 void flushString(ostream & os, docstring & s)
1193 {
1194         os << to_utf8(s);
1195         s.erase();
1196 }
1197
1198 }
1199
1200
1201 void Paragraph::write(ostream & os, BufferParams const & bparams,
1202         depth_type & dth) const
1203 {
1204         // The beginning or end of a deeper (i.e. nested) area?
1205         if (dth != d->params_.depth()) {
1206                 if (d->params_.depth() > dth) {
1207                         while (d->params_.depth() > dth) {
1208                                 os << "\n\\begin_deeper";
1209                                 ++dth;
1210                         }
1211                 } else {
1212                         while (d->params_.depth() < dth) {
1213                                 os << "\n\\end_deeper";
1214                                 --dth;
1215                         }
1216                 }
1217         }
1218
1219         // First write the layout
1220         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1221
1222         d->params_.write(os);
1223
1224         Font font1(inherit_font, bparams.language);
1225
1226         Change running_change = Change(Change::UNCHANGED);
1227
1228         // this string is used as a buffer to avoid repetitive calls
1229         // to to_utf8(), which turn out to be expensive (JMarc)
1230         docstring write_buffer;
1231
1232         int column = 0;
1233         for (pos_type i = 0; i <= size(); ++i) {
1234
1235                 Change const change = lookupChange(i);
1236                 if (change != running_change)
1237                         flushString(os, write_buffer);
1238                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1239                 running_change = change;
1240
1241                 if (i == size())
1242                         break;
1243
1244                 // Write font changes (ignore spelling markers)
1245                 Font font2 = getFontSettings(bparams, i);
1246                 font2.setMisspelled(false);
1247                 if (font2 != font1) {
1248                         flushString(os, write_buffer);
1249                         font2.lyxWriteChanges(font1, os);
1250                         column = 0;
1251                         font1 = font2;
1252                 }
1253
1254                 char_type const c = d->text_[i];
1255                 switch (c) {
1256                 case META_INSET:
1257                         if (Inset const * inset = getInset(i)) {
1258                                 flushString(os, write_buffer);
1259                                 if (inset->directWrite()) {
1260                                         // international char, let it write
1261                                         // code directly so it's shorter in
1262                                         // the file
1263                                         inset->write(os);
1264                                 } else {
1265                                         if (i)
1266                                                 os << '\n';
1267                                         os << "\\begin_inset ";
1268                                         inset->write(os);
1269                                         os << "\n\\end_inset\n\n";
1270                                         column = 0;
1271                                 }
1272                         }
1273                         break;
1274                 case '\\':
1275                         flushString(os, write_buffer);
1276                         os << "\n\\backslash\n";
1277                         column = 0;
1278                         break;
1279                 case '.':
1280                         flushString(os, write_buffer);
1281                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1282                                 os << ".\n";
1283                                 column = 0;
1284                         } else
1285                                 os << '.';
1286                         break;
1287                 default:
1288                         if ((column > 70 && c == ' ')
1289                             || column > 79) {
1290                                 flushString(os, write_buffer);
1291                                 os << '\n';
1292                                 column = 0;
1293                         }
1294                         // this check is to amend a bug. LyX sometimes
1295                         // inserts '\0' this could cause problems.
1296                         if (c != '\0')
1297                                 write_buffer.push_back(c);
1298                         else
1299                                 LYXERR0("NUL char in structure.");
1300                         ++column;
1301                         break;
1302                 }
1303         }
1304
1305         flushString(os, write_buffer);
1306         os << "\n\\end_layout\n";
1307 }
1308
1309
1310 void Paragraph::validate(LaTeXFeatures & features) const
1311 {
1312         d->validate(features);
1313 }
1314
1315
1316 void Paragraph::insert(pos_type start, docstring const & str,
1317                        Font const & font, Change const & change)
1318 {
1319         for (size_t i = 0, n = str.size(); i != n ; ++i)
1320                 insertChar(start + i, str[i], font, change);
1321 }
1322
1323
1324 void Paragraph::appendChar(char_type c, Font const & font,
1325                 Change const & change)
1326 {
1327         // track change
1328         d->changes_.insert(change, d->text_.size());
1329         // when appending characters, no need to update tables
1330         d->text_.push_back(c);
1331         setFont(d->text_.size() - 1, font);
1332 }
1333
1334
1335 void Paragraph::appendString(docstring const & s, Font const & font,
1336                 Change const & change)
1337 {
1338         pos_type end = s.size();
1339         size_t oldsize = d->text_.size();
1340         size_t newsize = oldsize + end;
1341         size_t capacity = d->text_.capacity();
1342         if (newsize >= capacity)
1343                 d->text_.reserve(max(capacity + 100, newsize));
1344
1345         // when appending characters, no need to update tables
1346         d->text_.append(s);
1347
1348         // FIXME: Optimize this!
1349         for (size_t i = oldsize; i != newsize; ++i) {
1350                 // track change
1351                 d->changes_.insert(change, i);
1352         }
1353         d->fontlist_.set(oldsize, font);
1354         d->fontlist_.set(newsize - 1, font);
1355 }
1356
1357
1358 void Paragraph::insertChar(pos_type pos, char_type c,
1359                            bool trackChanges)
1360 {
1361         d->insertChar(pos, c, Change(trackChanges ?
1362                            Change::INSERTED : Change::UNCHANGED));
1363 }
1364
1365
1366 void Paragraph::insertChar(pos_type pos, char_type c,
1367                            Font const & font, bool trackChanges)
1368 {
1369         d->insertChar(pos, c, Change(trackChanges ?
1370                            Change::INSERTED : Change::UNCHANGED));
1371         setFont(pos, font);
1372 }
1373
1374
1375 void Paragraph::insertChar(pos_type pos, char_type c,
1376                            Font const & font, Change const & change)
1377 {
1378         d->insertChar(pos, c, change);
1379         setFont(pos, font);
1380 }
1381
1382
1383 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1384                             Font const & font, Change const & change)
1385 {
1386         bool const success = insertInset(pos, inset, change);
1387         // Set the font/language of the inset...
1388         setFont(pos, font);
1389         return success;
1390 }
1391
1392
1393 void Paragraph::resetFonts(Font const & font)
1394 {
1395         d->fontlist_.clear();
1396         d->fontlist_.set(0, font);
1397         d->fontlist_.set(d->text_.size() - 1, font);
1398 }
1399
1400 // Gets uninstantiated font setting at position.
1401 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1402                                          pos_type pos) const
1403 {
1404         if (pos > size()) {
1405                 LYXERR0("pos: " << pos << " size: " << size());
1406                 LASSERT(pos <= size(), /**/);
1407         }
1408
1409         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1410         if (cit != d->fontlist_.end())
1411                 return cit->font();
1412
1413         if (pos == size() && !empty())
1414                 return getFontSettings(bparams, pos - 1);
1415
1416         // Optimisation: avoid a full font instantiation if there is no
1417         // language change from previous call.
1418         static Font previous_font;
1419         static Language const * previous_lang = 0;
1420         Language const * lang = getParLanguage(bparams);
1421         if (lang != previous_lang) {
1422                 previous_lang = lang;
1423                 previous_font = Font(inherit_font, lang);
1424         }
1425         return previous_font;
1426 }
1427
1428
1429 FontSpan Paragraph::fontSpan(pos_type pos) const
1430 {
1431         LASSERT(pos <= size(), /**/);
1432         pos_type start = 0;
1433
1434         FontList::const_iterator cit = d->fontlist_.begin();
1435         FontList::const_iterator end = d->fontlist_.end();
1436         for (; cit != end; ++cit) {
1437                 if (cit->pos() >= pos) {
1438                         if (pos >= beginOfBody())
1439                                 return FontSpan(max(start, beginOfBody()),
1440                                                 cit->pos());
1441                         else
1442                                 return FontSpan(start,
1443                                                 min(beginOfBody() - 1,
1444                                                          cit->pos()));
1445                 }
1446                 start = cit->pos() + 1;
1447         }
1448
1449         // This should not happen, but if so, we take no chances.
1450         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1451         return FontSpan(pos, pos);
1452 }
1453
1454
1455 // Gets uninstantiated font setting at position 0
1456 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1457 {
1458         if (!empty() && !d->fontlist_.empty())
1459                 return d->fontlist_.begin()->font();
1460
1461         // Optimisation: avoid a full font instantiation if there is no
1462         // language change from previous call.
1463         static Font previous_font;
1464         static Language const * previous_lang = 0;
1465         if (bparams.language != previous_lang) {
1466                 previous_lang = bparams.language;
1467                 previous_font = Font(inherit_font, bparams.language);
1468         }
1469
1470         return previous_font;
1471 }
1472
1473
1474 // Gets the fully instantiated font at a given position in a paragraph
1475 // This is basically the same function as Text::GetFont() in text2.cpp.
1476 // The difference is that this one is used for generating the LaTeX file,
1477 // and thus cosmetic "improvements" are disallowed: This has to deliver
1478 // the true picture of the buffer. (Asger)
1479 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1480                                  Font const & outerfont) const
1481 {
1482         LASSERT(pos >= 0, /**/);
1483
1484         Font font = getFontSettings(bparams, pos);
1485
1486         pos_type const body_pos = beginOfBody();
1487         FontInfo & fi = font.fontInfo();
1488         if (pos < body_pos)
1489                 fi.realize(d->layout_->labelfont);
1490         else
1491                 fi.realize(d->layout_->font);
1492
1493         fi.realize(outerfont.fontInfo());
1494         fi.realize(bparams.getFont().fontInfo());
1495
1496         return font;
1497 }
1498
1499
1500 Font const Paragraph::getLabelFont
1501         (BufferParams const & bparams, Font const & outerfont) const
1502 {
1503         FontInfo tmpfont = d->layout_->labelfont;
1504         tmpfont.realize(outerfont.fontInfo());
1505         tmpfont.realize(bparams.getFont().fontInfo());
1506         return Font(tmpfont, getParLanguage(bparams));
1507 }
1508
1509
1510 Font const Paragraph::getLayoutFont
1511         (BufferParams const & bparams, Font const & outerfont) const
1512 {
1513         FontInfo tmpfont = d->layout_->font;
1514         tmpfont.realize(outerfont.fontInfo());
1515         tmpfont.realize(bparams.getFont().fontInfo());
1516         return Font(tmpfont, getParLanguage(bparams));
1517 }
1518
1519
1520 /// Returns the height of the highest font in range
1521 FontSize Paragraph::highestFontInRange
1522         (pos_type startpos, pos_type endpos, FontSize def_size) const
1523 {
1524         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1525 }
1526
1527
1528 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1529 {
1530         char_type c = d->text_[pos];
1531         if (!lyxrc.rtl_support)
1532                 return c;
1533
1534         char_type uc = c;
1535         switch (c) {
1536         case '(':
1537                 uc = ')';
1538                 break;
1539         case ')':
1540                 uc = '(';
1541                 break;
1542         case '[':
1543                 uc = ']';
1544                 break;
1545         case ']':
1546                 uc = '[';
1547                 break;
1548         case '{':
1549                 uc = '}';
1550                 break;
1551         case '}':
1552                 uc = '{';
1553                 break;
1554         case '<':
1555                 uc = '>';
1556                 break;
1557         case '>':
1558                 uc = '<';
1559                 break;
1560         }
1561         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1562                 return uc;
1563         return c;
1564 }
1565
1566
1567 void Paragraph::setFont(pos_type pos, Font const & font)
1568 {
1569         LASSERT(pos <= size(), /**/);
1570
1571         // First, reduce font against layout/label font
1572         // Update: The setCharFont() routine in text2.cpp already
1573         // reduces font, so we don't need to do that here. (Asger)
1574         
1575         d->fontlist_.set(pos, font);
1576 }
1577
1578
1579 void Paragraph::makeSameLayout(Paragraph const & par)
1580 {
1581         d->layout_ = par.d->layout_;
1582         d->params_ = par.d->params_;
1583 }
1584
1585
1586 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1587 {
1588         if (isFreeSpacing())
1589                 return false;
1590
1591         int pos = 0;
1592         int count = 0;
1593
1594         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1595                 if (eraseChar(pos, trackChanges))
1596                         ++count;
1597                 else
1598                         ++pos;
1599         }
1600
1601         return count > 0 || pos > 0;
1602 }
1603
1604
1605 bool Paragraph::hasSameLayout(Paragraph const & par) const
1606 {
1607         return par.d->layout_ == d->layout_
1608                 && d->params_.sameLayout(par.d->params_);
1609 }
1610
1611
1612 depth_type Paragraph::getDepth() const
1613 {
1614         return d->params_.depth();
1615 }
1616
1617
1618 depth_type Paragraph::getMaxDepthAfter() const
1619 {
1620         if (d->layout_->isEnvironment())
1621                 return d->params_.depth() + 1;
1622         else
1623                 return d->params_.depth();
1624 }
1625
1626
1627 char Paragraph::getAlign() const
1628 {
1629         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1630                 return d->layout_->align;
1631         else
1632                 return d->params_.align();
1633 }
1634
1635
1636 docstring const & Paragraph::labelString() const
1637 {
1638         return d->params_.labelString();
1639 }
1640
1641
1642 // the next two functions are for the manual labels
1643 docstring const Paragraph::getLabelWidthString() const
1644 {
1645         if (d->layout_->margintype == MARGIN_MANUAL
1646             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1647                 return d->params_.labelWidthString();
1648         else
1649                 return _("Senseless with this layout!");
1650 }
1651
1652
1653 void Paragraph::setLabelWidthString(docstring const & s)
1654 {
1655         d->params_.labelWidthString(s);
1656 }
1657
1658
1659 docstring Paragraph::expandLabel(Layout const & layout, 
1660                 BufferParams const & bparams) const
1661
1662         return expandParagraphLabel(layout, bparams, true); 
1663 }
1664
1665
1666 docstring Paragraph::expandDocBookLabel(Layout const & layout, 
1667                 BufferParams const & bparams) const
1668 {
1669         return expandParagraphLabel(layout, bparams, false);
1670 }
1671
1672
1673 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1674                 BufferParams const & bparams, bool process_appendix) const
1675 {
1676         DocumentClass const & tclass = bparams.documentClass();
1677         string const & lang = getParLanguage(bparams)->code();
1678         bool const in_appendix = process_appendix && d->params_.appendix();
1679         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1680
1681         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1682             && !layout.counter.empty())
1683                 return tclass.counters().theCounter(layout.counter, lang);
1684
1685         // handle 'inherited level parts' in 'fmt',
1686         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1687         size_t const i = fmt.find('@', 0);
1688         if (i != docstring::npos) {
1689                 size_t const j = fmt.find('@', i + 1);
1690                 if (j != docstring::npos) {
1691                         docstring parent(fmt, i + 1, j - i - 1);
1692                         docstring label = from_ascii("??");
1693                         if (tclass.hasLayout(parent))
1694                                 docstring label = expandParagraphLabel(tclass[parent], bparams,
1695                                                       process_appendix);
1696                         fmt = docstring(fmt, 0, i) + label 
1697                                 + docstring(fmt, j + 1, docstring::npos);
1698                 }
1699         }
1700
1701         return tclass.counters().counterLabel(fmt, lang);
1702 }
1703
1704
1705 void Paragraph::applyLayout(Layout const & new_layout)
1706 {
1707         d->layout_ = &new_layout;
1708         LyXAlignment const oldAlign = d->params_.align();
1709         
1710         if (!(oldAlign & d->layout_->alignpossible)) {
1711                 frontend::Alert::warning(_("Alignment not permitted"), 
1712                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1713                 d->params_.align(LYX_ALIGN_LAYOUT);
1714         }
1715 }
1716
1717
1718 pos_type Paragraph::beginOfBody() const
1719 {
1720         return d->begin_of_body_;
1721 }
1722
1723
1724 void Paragraph::setBeginOfBody()
1725 {
1726         if (d->layout_->labeltype != LABEL_MANUAL) {
1727                 d->begin_of_body_ = 0;
1728                 return;
1729         }
1730
1731         // Unroll the first two cycles of the loop
1732         // and remember the previous character to
1733         // remove unnecessary getChar() calls
1734         pos_type i = 0;
1735         pos_type end = size();
1736         if (i < end && !isNewline(i)) {
1737                 ++i;
1738                 char_type previous_char = 0;
1739                 char_type temp = 0;
1740                 if (i < end) {
1741                         previous_char = d->text_[i];
1742                         if (!isNewline(i)) {
1743                                 ++i;
1744                                 while (i < end && previous_char != ' ') {
1745                                         temp = d->text_[i];
1746                                         if (isNewline(i))
1747                                                 break;
1748                                         ++i;
1749                                         previous_char = temp;
1750                                 }
1751                         }
1752                 }
1753         }
1754
1755         d->begin_of_body_ = i;
1756 }
1757
1758
1759 bool Paragraph::allowParagraphCustomization() const
1760 {
1761         return inInset().allowParagraphCustomization();
1762 }
1763
1764
1765 bool Paragraph::usePlainLayout() const
1766 {
1767         return inInset().usePlainLayout();
1768 }
1769
1770
1771 namespace {
1772
1773 // paragraphs inside floats need different alignment tags to avoid
1774 // unwanted space
1775
1776 bool noTrivlistCentering(InsetCode code)
1777 {
1778         return code == FLOAT_CODE
1779                || code == WRAP_CODE
1780                || code == CELL_CODE;
1781 }
1782
1783
1784 string correction(string const & orig)
1785 {
1786         if (orig == "flushleft")
1787                 return "raggedright";
1788         if (orig == "flushright")
1789                 return "raggedleft";
1790         if (orig == "center")
1791                 return "centering";
1792         return orig;
1793 }
1794
1795
1796 string const corrected_env(string const & suffix, string const & env,
1797         InsetCode code, bool const lastpar)
1798 {
1799         string output = suffix + "{";
1800         if (noTrivlistCentering(code)) {
1801                 if (lastpar) {
1802                         // the last paragraph in non-trivlist-aligned
1803                         // context is special (to avoid unwanted whitespace)
1804                         if (suffix == "\\begin")
1805                                 return "\\" + correction(env) + "{}";
1806                         return string();
1807                 }
1808                 output += correction(env);
1809         } else
1810                 output += env;
1811         output += "}";
1812         if (suffix == "\\begin")
1813                 output += "\n";
1814         return output;
1815 }
1816
1817
1818 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1819 {
1820         if (!contains(str, "\n"))
1821                 column += str.size();
1822         else {
1823                 string tmp;
1824                 texrow.newline();
1825                 column = rsplit(str, tmp, '\n').size();
1826         }
1827 }
1828
1829 } // namespace anon
1830
1831
1832 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1833                                  odocstream & os, TexRow & texrow,
1834                                  OutputParams const & runparams) const
1835 {
1836         int column = 0;
1837
1838         if (params_.noindent()) {
1839                 os << "\\noindent ";
1840                 column += 10;
1841         }
1842         
1843         LyXAlignment const curAlign = params_.align();
1844
1845         if (curAlign == layout_->align)
1846                 return column;
1847
1848         switch (curAlign) {
1849         case LYX_ALIGN_NONE:
1850         case LYX_ALIGN_BLOCK:
1851         case LYX_ALIGN_LAYOUT:
1852         case LYX_ALIGN_SPECIAL:
1853                 break;
1854         case LYX_ALIGN_LEFT:
1855         case LYX_ALIGN_RIGHT:
1856         case LYX_ALIGN_CENTER:
1857                 if (runparams.moving_arg) {
1858                         os << "\\protect";
1859                         column += 8;
1860                 }
1861                 break;
1862         }
1863
1864         string const begin_tag = "\\begin";
1865         InsetCode code = ownerCode();
1866         bool const lastpar = runparams.isLastPar;
1867
1868         switch (curAlign) {
1869         case LYX_ALIGN_NONE:
1870         case LYX_ALIGN_BLOCK:
1871         case LYX_ALIGN_LAYOUT:
1872         case LYX_ALIGN_SPECIAL:
1873                 break;
1874         case LYX_ALIGN_LEFT: {
1875                 string output;
1876                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1877                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1878                 else
1879                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1880                 os << from_ascii(output);
1881                 adjust_row_column(output, texrow, column);
1882                 break;
1883         } case LYX_ALIGN_RIGHT: {
1884                 string output;
1885                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1886                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1887                 else
1888                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1889                 os << from_ascii(output);
1890                 adjust_row_column(output, texrow, column);
1891                 break;
1892         } case LYX_ALIGN_CENTER: {
1893                 string output;
1894                 output = corrected_env(begin_tag, "center", code, lastpar);
1895                 os << from_ascii(output);
1896                 adjust_row_column(output, texrow, column);
1897                 break;
1898         }
1899         }
1900
1901         return column;
1902 }
1903
1904
1905 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1906                                odocstream & os, TexRow & texrow,
1907                                OutputParams const & runparams) const
1908 {
1909         int column = 0;
1910
1911         LyXAlignment const curAlign = params_.align();
1912
1913         if (curAlign == layout_->align)
1914                 return column;
1915
1916         switch (curAlign) {
1917         case LYX_ALIGN_NONE:
1918         case LYX_ALIGN_BLOCK:
1919         case LYX_ALIGN_LAYOUT:
1920         case LYX_ALIGN_SPECIAL:
1921                 break;
1922         case LYX_ALIGN_LEFT:
1923         case LYX_ALIGN_RIGHT:
1924         case LYX_ALIGN_CENTER:
1925                 if (runparams.moving_arg) {
1926                         os << "\\protect";
1927                         column = 8;
1928                 }
1929                 break;
1930         }
1931
1932         string const end_tag = "\n\\par\\end";
1933         InsetCode code = ownerCode();
1934         bool const lastpar = runparams.isLastPar;
1935
1936         switch (curAlign) {
1937         case LYX_ALIGN_NONE:
1938         case LYX_ALIGN_BLOCK:
1939         case LYX_ALIGN_LAYOUT:
1940         case LYX_ALIGN_SPECIAL:
1941                 break;
1942         case LYX_ALIGN_LEFT: {
1943                 string output;
1944                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1945                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1946                 else
1947                         output = corrected_env(end_tag, "flushright", code, lastpar);
1948                 os << from_ascii(output);
1949                 adjust_row_column(output, texrow, column);
1950                 break;
1951         } case LYX_ALIGN_RIGHT: {
1952                 string output;
1953                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1954                         output = corrected_env(end_tag, "flushright", code, lastpar);
1955                 else
1956                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1957                 os << from_ascii(output);
1958                 adjust_row_column(output, texrow, column);
1959                 break;
1960         } case LYX_ALIGN_CENTER: {
1961                 string output;
1962                 output = corrected_env(end_tag, "center", code, lastpar);
1963                 os << from_ascii(output);
1964                 adjust_row_column(output, texrow, column);
1965                 break;
1966         }
1967         }
1968
1969         return column;
1970 }
1971
1972
1973 // This one spits out the text of the paragraph
1974 bool Paragraph::latex(BufferParams const & bparams,
1975         Font const & outerfont,
1976         odocstream & os, TexRow & texrow,
1977         OutputParams const & runparams,
1978         int start_pos, int end_pos) const
1979 {
1980         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
1981
1982         if (layout().inpreamble)
1983                 return true;
1984
1985         bool return_value = false;
1986
1987         bool const allowcust = allowParagraphCustomization();
1988
1989         // FIXME This check should not be needed. Perhaps issue an
1990         // error if it triggers.
1991         Layout const & style = inInset().forcePlainLayout() ?
1992                 bparams.documentClass().plainLayout() : *d->layout_;
1993
1994         // Current base font for all inherited font changes, without any
1995         // change caused by an individual character, except for the language:
1996         // It is set to the language of the first character.
1997         // As long as we are in the label, this font is the base font of the
1998         // label. Before the first body character it is set to the base font
1999         // of the body.
2000         Font basefont;
2001
2002         // Maybe we have to create a optional argument.
2003         pos_type body_pos = beginOfBody();
2004         unsigned int column = 0;
2005
2006         if (body_pos > 0) {
2007                 // the optional argument is kept in curly brackets in
2008                 // case it contains a ']'
2009                 os << "[{";
2010                 column += 2;
2011                 basefont = getLabelFont(bparams, outerfont);
2012         } else {
2013                 basefont = getLayoutFont(bparams, outerfont);
2014         }
2015
2016         // Which font is currently active?
2017         Font running_font(basefont);
2018         // Do we have an open font change?
2019         bool open_font = false;
2020
2021         Change runningChange = Change(Change::UNCHANGED);
2022
2023         Encoding const * const prev_encoding = runparams.encoding;
2024
2025         texrow.start(id(), 0);
2026
2027         // if the paragraph is empty, the loop will not be entered at all
2028         if (empty()) {
2029                 if (style.isCommand()) {
2030                         os << '{';
2031                         ++column;
2032                 }
2033                 if (allowcust)
2034                         column += d->startTeXParParams(bparams, os, texrow,
2035                                                     runparams);
2036         }
2037
2038         for (pos_type i = 0; i < size(); ++i) {
2039                 // First char in paragraph or after label?
2040                 if (i == body_pos) {
2041                         if (body_pos > 0) {
2042                                 if (open_font) {
2043                                         column += running_font.latexWriteEndChanges(
2044                                                 os, bparams, runparams,
2045                                                 basefont, basefont);
2046                                         open_font = false;
2047                                 }
2048                                 basefont = getLayoutFont(bparams, outerfont);
2049                                 running_font = basefont;
2050
2051                                 column += Changes::latexMarkChange(os, bparams,
2052                                                 runningChange, Change(Change::UNCHANGED),
2053                                                 runparams);
2054                                 runningChange = Change(Change::UNCHANGED);
2055
2056                                 os << "}] ";
2057                                 column +=3;
2058                         }
2059                         if (style.isCommand()) {
2060                                 os << '{';
2061                                 ++column;
2062                         }
2063
2064                         if (allowcust)
2065                                 column += d->startTeXParParams(bparams, os,
2066                                                             texrow,
2067                                                             runparams);
2068                 }
2069
2070                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2071                                                                  : lookupChange(i);
2072
2073                 if (bparams.outputChanges && runningChange != change) {
2074                         if (open_font) {
2075                                 column += running_font.latexWriteEndChanges(
2076                                                 os, bparams, runparams, basefont, basefont);
2077                                 open_font = false;
2078                         }
2079                         basefont = getLayoutFont(bparams, outerfont);
2080                         running_font = basefont;
2081
2082                         column += Changes::latexMarkChange(os, bparams, runningChange,
2083                                                            change, runparams);
2084                         runningChange = change;
2085                 }
2086
2087                 // do not output text which is marked deleted
2088                 // if change tracking output is disabled
2089                 if (!bparams.outputChanges && change.deleted()) {
2090                         continue;
2091                 }
2092
2093                 ++column;
2094
2095                 // Fully instantiated font
2096                 Font const font = getFont(bparams, i, outerfont);
2097
2098                 Font const last_font = running_font;
2099
2100                 // Do we need to close the previous font?
2101                 if (open_font &&
2102                     (font != running_font ||
2103                      font.language() != running_font.language()))
2104                 {
2105                         column += running_font.latexWriteEndChanges(
2106                                         os, bparams, runparams, basefont,
2107                                         (i == body_pos-1) ? basefont : font);
2108                         running_font = basefont;
2109                         open_font = false;
2110                 }
2111
2112                 // close babel's font environment before opening CJK.
2113                 if (!running_font.language()->babel().empty() &&
2114                     font.language()->encoding()->package() == Encoding::CJK) {
2115                                 string end_tag = subst(lyxrc.language_command_end,
2116                                                         "$$lang",
2117                                                         running_font.language()->babel());
2118                                 os << from_ascii(end_tag);
2119                                 column += end_tag.length();
2120                 }
2121
2122                 // Switch file encoding if necessary (and allowed)
2123                 if (!runparams.verbatim && 
2124                     runparams.encoding->package() != Encoding::none &&
2125                     font.language()->encoding()->package() != Encoding::none) {
2126                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2127                                         runparams, *(font.language()->encoding()));
2128                         if (enc_switch.first) {
2129                                 column += enc_switch.second;
2130                                 runparams.encoding = font.language()->encoding();
2131                         }
2132                 }
2133
2134                 char_type const c = d->text_[i];
2135
2136                 // Do we need to change font?
2137                 if ((font != running_font ||
2138                      font.language() != running_font.language()) &&
2139                         i != body_pos - 1)
2140                 {
2141                         odocstringstream ods;
2142                         column += font.latexWriteStartChanges(ods, bparams,
2143                                                               runparams, basefont,
2144                                                               last_font);
2145                         running_font = font;
2146                         open_font = true;
2147                         docstring fontchange = ods.str();
2148                         // check whether the fontchange ends with a \\textcolor
2149                         // modifier and the text starts with a space (bug 4473)
2150                         docstring const last_modifier = rsplit(fontchange, '\\');
2151                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2152                                 os << fontchange << from_ascii("{}");
2153                         // check if the fontchange ends with a trailing blank
2154                         // (like "\small " (see bug 3382)
2155                         else if (suffixIs(fontchange, ' ') && c == ' ')
2156                                 os << fontchange.substr(0, fontchange.size() - 1) 
2157                                    << from_ascii("{}");
2158                         else
2159                                 os << fontchange;
2160                 }
2161
2162                 // FIXME: think about end_pos implementation...
2163                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2164                         // FIXME: integrate this case in latexSpecialChar
2165                         // Do not print the separation of the optional argument
2166                         // if style.pass_thru is false. This works because
2167                         // latexSpecialChar ignores spaces if
2168                         // style.pass_thru is false.
2169                         if (i != body_pos - 1) {
2170                                 if (d->simpleTeXBlanks(
2171                                                 runparams, os, texrow,
2172                                                 i, column, font, style)) {
2173                                         // A surrogate pair was output. We
2174                                         // must not call latexSpecialChar
2175                                         // in this iteration, since it would output
2176                                         // the combining character again.
2177                                         ++i;
2178                                         continue;
2179                                 }
2180                         }
2181                 }
2182
2183                 OutputParams rp = runparams;
2184                 rp.free_spacing = style.free_spacing;
2185                 rp.local_font = &font;
2186                 rp.intitle = style.intitle;
2187
2188                 // Two major modes:  LaTeX or plain
2189                 // Handle here those cases common to both modes
2190                 // and then split to handle the two modes separately.
2191                 if (c == META_INSET) {
2192                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2193                                 d->latexInset(bparams, os,
2194                                                 texrow, rp, running_font,
2195                                                 basefont, outerfont, open_font,
2196                                                 runningChange, style, i, column);
2197                         }
2198                 } else {
2199                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2200                                 try {
2201                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2202                                                 style, i, column);
2203                                 } catch (EncodingException & e) {
2204                                 if (runparams.dryrun) {
2205                                         os << "<" << _("LyX Warning: ")
2206                                            << _("uncodable character") << " '";
2207                                         os.put(c);
2208                                         os << "'>";
2209                                 } else {
2210                                         // add location information and throw again.
2211                                         e.par_id = id();
2212                                         e.pos = i;
2213                                         throw(e);
2214                                 }
2215                         }
2216                 }
2217                 }
2218
2219                 // Set the encoding to that returned from latexSpecialChar (see
2220                 // comment for encoding member in OutputParams.h)
2221                 runparams.encoding = rp.encoding;
2222         }
2223
2224         // If we have an open font definition, we have to close it
2225         if (open_font) {
2226 #ifdef FIXED_LANGUAGE_END_DETECTION
2227                 if (next_) {
2228                         running_font
2229                                 .latexWriteEndChanges(os, bparams, runparams,
2230                                         basefont,
2231                                         next_->getFont(bparams, 0, outerfont));
2232                 } else {
2233                         running_font.latexWriteEndChanges(os, bparams,
2234                                         runparams, basefont, basefont);
2235                 }
2236 #else
2237 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2238 //FIXME: there as we start another \selectlanguage with the next paragraph if
2239 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2240                 running_font.latexWriteEndChanges(os, bparams, runparams,
2241                                 basefont, basefont);
2242 #endif
2243         }
2244
2245         column += Changes::latexMarkChange(os, bparams, runningChange,
2246                                            Change(Change::UNCHANGED), runparams);
2247
2248         // Needed if there is an optional argument but no contents.
2249         if (body_pos > 0 && body_pos == size()) {
2250                 os << "}]~";
2251                 return_value = false;
2252         }
2253
2254         if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2255             && runparams.encoding != prev_encoding) {
2256                 runparams.encoding = prev_encoding;
2257                 if (!bparams.useXetex)
2258                         os << setEncoding(prev_encoding->iconvName());
2259         }
2260
2261         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2262         return return_value;
2263 }
2264
2265
2266 bool Paragraph::emptyTag() const
2267 {
2268         for (pos_type i = 0; i < size(); ++i) {
2269                 if (Inset const * inset = getInset(i)) {
2270                         InsetCode lyx_code = inset->lyxCode();
2271                         // FIXME testing like that is wrong. What is
2272                         // the intent?
2273                         if (lyx_code != TOC_CODE &&
2274                             lyx_code != INCLUDE_CODE &&
2275                             lyx_code != GRAPHICS_CODE &&
2276                             lyx_code != ERT_CODE &&
2277                             lyx_code != LISTINGS_CODE &&
2278                             lyx_code != FLOAT_CODE &&
2279                             lyx_code != TABULAR_CODE) {
2280                                 return false;
2281                         }
2282                 } else {
2283                         char_type c = d->text_[i];
2284                         if (c != ' ' && c != '\t')
2285                                 return false;
2286                 }
2287         }
2288         return true;
2289 }
2290
2291
2292 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2293         const
2294 {
2295         for (pos_type i = 0; i < size(); ++i) {
2296                 if (Inset const * inset = getInset(i)) {
2297                         InsetCode lyx_code = inset->lyxCode();
2298                         if (lyx_code == LABEL_CODE) {
2299                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2300                                 docstring const & id = il->getParam("name");
2301                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2302                         }
2303                 }
2304         }
2305         return string();
2306 }
2307
2308
2309 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2310         const
2311 {
2312         pos_type i;
2313         for (i = 0; i < size(); ++i) {
2314                 if (Inset const * inset = getInset(i)) {
2315                         inset->docbook(os, runparams);
2316                 } else {
2317                         char_type c = d->text_[i];
2318                         if (c == ' ')
2319                                 break;
2320                         os << sgml::escapeChar(c);
2321                 }
2322         }
2323         return i;
2324 }
2325
2326
2327 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2328         const
2329 {
2330         pos_type i;
2331         for (i = 0; i < size(); ++i) {
2332                 if (Inset const * inset = getInset(i)) {
2333                         inset->xhtml(xs, runparams);
2334                 } else {
2335                         char_type c = d->text_[i];
2336                         if (c == ' ')
2337                                 break;
2338                         xs << c;
2339                 }
2340         }
2341         return i;
2342 }
2343
2344
2345 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2346 {
2347         Font font_old;
2348         pos_type size = text_.size();
2349         for (pos_type i = initial; i < size; ++i) {
2350                 Font font = owner_->getFont(buf.params(), i, outerfont);
2351                 if (text_[i] == META_INSET)
2352                         return false;
2353                 if (i != initial && font != font_old)
2354                         return false;
2355                 font_old = font;
2356         }
2357
2358         return true;
2359 }
2360
2361
2362 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2363                                     odocstream & os,
2364                                     OutputParams const & runparams,
2365                                     Font const & outerfont,
2366                                     pos_type initial) const
2367 {
2368         bool emph_flag = false;
2369
2370         Layout const & style = *d->layout_;
2371         FontInfo font_old =
2372                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2373
2374         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2375                 os << "]]>";
2376
2377         // parsing main loop
2378         for (pos_type i = initial; i < size(); ++i) {
2379                 Font font = getFont(buf.params(), i, outerfont);
2380
2381                 // handle <emphasis> tag
2382                 if (font_old.emph() != font.fontInfo().emph()) {
2383                         if (font.fontInfo().emph() == FONT_ON) {
2384                                 os << "<emphasis>";
2385                                 emph_flag = true;
2386                         } else if (i != initial) {
2387                                 os << "</emphasis>";
2388                                 emph_flag = false;
2389                         }
2390                 }
2391
2392                 if (Inset const * inset = getInset(i)) {
2393                         inset->docbook(os, runparams);
2394                 } else {
2395                         char_type c = d->text_[i];
2396
2397                         if (style.pass_thru)
2398                                 os.put(c);
2399                         else
2400                                 os << sgml::escapeChar(c);
2401                 }
2402                 font_old = font.fontInfo();
2403         }
2404
2405         if (emph_flag) {
2406                 os << "</emphasis>";
2407         }
2408
2409         if (style.free_spacing)
2410                 os << '\n';
2411         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2412                 os << "<![CDATA[";
2413 }
2414
2415
2416 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2417                                     XHTMLStream & xs,
2418                                     OutputParams const & runparams,
2419                                     Font const & outerfont,
2420                                     pos_type initial) const
2421 {
2422         docstring retval;
2423
2424         bool emph_flag = false;
2425         bool bold_flag = false;
2426         string closing_tag;
2427
2428         Layout const & style = *d->layout_;
2429
2430         if (!runparams.for_toc && runparams.html_make_pars) {
2431                 // generate a magic label for this paragraph
2432                 string const attr = "id='" + magicLabel() + "'";
2433                 xs << html::CompTag("a", attr);
2434         }
2435
2436         FontInfo font_old =
2437                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2438
2439         // parsing main loop
2440         for (pos_type i = initial; i < size(); ++i) {
2441                 // let's not show deleted material in the output
2442                 if (isDeleted(i))
2443                         continue;
2444         
2445                 Font font = getFont(buf.params(), i, outerfont);
2446
2447                 // emphasis
2448                 if (font_old.emph() != font.fontInfo().emph()) {
2449                         if (font.fontInfo().emph() == FONT_ON) {
2450                                 xs << html::StartTag("em");
2451                                 emph_flag = true;
2452                         } else if (emph_flag && i != initial) {
2453                                 xs << html::EndTag("em");
2454                                 emph_flag = false;
2455                         }
2456                 }
2457                 // bold
2458                 if (font_old.series() != font.fontInfo().series()) {
2459                         if (font.fontInfo().series() == BOLD_SERIES) {
2460                                 xs << html::StartTag("strong");
2461                                 bold_flag = true;
2462                         } else if (bold_flag && i != initial) {
2463                                 xs << html::EndTag("strong");
2464                                 bold_flag = false;
2465                         }
2466                 }
2467                 // FIXME XHTML
2468                 // Other such tags? What about the other text ranges?
2469
2470                 Inset const * inset = getInset(i);
2471                 if (inset) {
2472                         InsetCommand const * ic = inset->asInsetCommand();
2473                         InsetLayout const & il = inset->getLayout();
2474                         InsetMath const * im = inset->asInsetMath();
2475                         if (!runparams.for_toc 
2476                             || im || il.isInToc() || (ic && ic->isInToc())) {
2477                                 OutputParams np = runparams;
2478                                 if (!il.htmlisblock())
2479                                         np.html_in_par = true;
2480                                 retval += inset->xhtml(xs, np);
2481                         }
2482                 } else {
2483                         char_type c = d->text_[i];
2484
2485                         if (style.pass_thru)
2486                                 xs << c;
2487                         else if (c == '-') {
2488                                 docstring str;
2489                                 int j = i + 1;
2490                                 if (j < size() && d->text_[j] == '-') {
2491                                         j += 1;
2492                                         if (j < size() && d->text_[j] == '-') {
2493                                                 str += from_ascii("&mdash;");
2494                                                 i += 2;
2495                                         } else {
2496                                                 str += from_ascii("&ndash;");
2497                                                 i += 1;
2498                                         }
2499                                 }
2500                                 else
2501                                         str += c;
2502                                 // We don't want to escape the entities. Note that
2503                                 // it is safe to do this, since str can otherwise
2504                                 // only be "-". E.g., it can't be "<".
2505                                 xs << XHTMLStream::NextRaw() << str;
2506                         } else
2507                                 xs << c;
2508                 }
2509                 font_old = font.fontInfo();
2510         }
2511
2512         xs.closeFontTags();
2513         return retval;
2514 }
2515
2516
2517 bool Paragraph::isHfill(pos_type pos) const
2518 {
2519         Inset const * inset = getInset(pos);
2520         return inset && (inset->lyxCode() == SPACE_CODE &&
2521                          inset->isStretchableSpace());
2522 }
2523
2524
2525 bool Paragraph::isNewline(pos_type pos) const
2526 {
2527         Inset const * inset = getInset(pos);
2528         return inset && inset->lyxCode() == NEWLINE_CODE;
2529 }
2530
2531
2532 bool Paragraph::isLineSeparator(pos_type pos) const
2533 {
2534         char_type const c = d->text_[pos];
2535         if (isLineSeparatorChar(c))
2536                 return true;
2537         Inset const * inset = getInset(pos);
2538         return inset && inset->isLineSeparator();
2539 }
2540
2541
2542 bool Paragraph::isWordSeparator(pos_type pos) const
2543 {
2544         if (Inset const * inset = getInset(pos))
2545                 return !inset->isLetter();
2546         char_type const c = d->text_[pos];
2547         // We want to pass the ' and escape chars to the spellchecker
2548         static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2549         return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2550                 || pos == size();
2551 }
2552
2553
2554 bool Paragraph::isChar(pos_type pos) const
2555 {
2556         if (Inset const * inset = getInset(pos))
2557                 return inset->isChar();
2558         char_type const c = d->text_[pos];
2559         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2560 }
2561
2562
2563 bool Paragraph::isSpace(pos_type pos) const
2564 {
2565         if (Inset const * inset = getInset(pos))
2566                 return inset->isSpace();
2567         char_type const c = d->text_[pos];
2568         return lyx::isSpace(c);
2569 }
2570
2571
2572 Language const *
2573 Paragraph::getParLanguage(BufferParams const & bparams) const
2574 {
2575         if (!empty())
2576                 return getFirstFontSettings(bparams).language();
2577         // FIXME: we should check the prev par as well (Lgb)
2578         return bparams.language;
2579 }
2580
2581
2582 bool Paragraph::isRTL(BufferParams const & bparams) const
2583 {
2584         return lyxrc.rtl_support
2585                 && getParLanguage(bparams)->rightToLeft()
2586                 && !inInset().getLayout().forceLTR();
2587 }
2588
2589
2590 void Paragraph::changeLanguage(BufferParams const & bparams,
2591                                Language const * from, Language const * to)
2592 {
2593         // change language including dummy font change at the end
2594         for (pos_type i = 0; i <= size(); ++i) {
2595                 Font font = getFontSettings(bparams, i);
2596                 if (font.language() == from) {
2597                         font.setLanguage(to);
2598                         setFont(i, font);
2599                 }
2600         }
2601 }
2602
2603
2604 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2605 {
2606         Language const * doc_language = bparams.language;
2607         FontList::const_iterator cit = d->fontlist_.begin();
2608         FontList::const_iterator end = d->fontlist_.end();
2609
2610         for (; cit != end; ++cit)
2611                 if (cit->font().language() != ignore_language &&
2612                     cit->font().language() != latex_language &&
2613                     cit->font().language() != doc_language)
2614                         return true;
2615         return false;
2616 }
2617
2618
2619 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2620 {
2621         FontList::const_iterator cit = d->fontlist_.begin();
2622         FontList::const_iterator end = d->fontlist_.end();
2623
2624         for (; cit != end; ++cit) {
2625                 Language const * lang = cit->font().language();
2626                 if (lang != ignore_language &&
2627                     lang != latex_language)
2628                         languages.insert(lang);
2629         }
2630 }
2631
2632
2633 docstring Paragraph::asString(int options) const
2634 {
2635         return asString(0, size(), options);
2636 }
2637
2638
2639 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2640 {
2641         odocstringstream os;
2642
2643         if (beg == 0 
2644                 && options & AS_STR_LABEL
2645                 && !d->params_.labelString().empty())
2646                 os << d->params_.labelString() << ' ';
2647
2648         for (pos_type i = beg; i < end; ++i) {
2649                 char_type const c = d->text_[i];
2650                 if (isPrintable(c) || c == '\t'
2651                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2652                         os.put(c);
2653                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2654                         getInset(i)->tocString(os);
2655                         if (getInset(i)->asInsetMath())
2656                                 os << " ";
2657                 }
2658         }
2659
2660         return os.str();
2661 }
2662
2663
2664 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2665 {
2666         odocstringstream os;
2667
2668         if (beg == 0 
2669                 && options & AS_STR_LABEL
2670                 && !d->params_.labelString().empty())
2671                 os << d->params_.labelString() << ' ';
2672
2673         for (pos_type i = beg; i < end; ++i) {
2674                 char_type const c = d->text_[i];
2675                 if (isPrintable(c) || c == '\t'
2676                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2677                         os.put(c);
2678                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2679                         getInset(i)->plaintext(os, runparams);
2680                 }
2681         }
2682
2683         return os.str();
2684 }
2685
2686
2687 void Paragraph::setInsetOwner(Inset const * inset)
2688 {
2689         d->inset_owner_ = inset;
2690 }
2691
2692
2693 int Paragraph::id() const
2694 {
2695         return d->id_;
2696 }
2697
2698
2699 void Paragraph::setId(int id)
2700 {
2701         d->id_ = id;
2702 }
2703
2704
2705 Layout const & Paragraph::layout() const
2706 {
2707         return *d->layout_;
2708 }
2709
2710
2711 void Paragraph::setLayout(Layout const & layout)
2712 {
2713         d->layout_ = &layout;
2714 }
2715
2716
2717 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2718
2719         setLayout(tc.defaultLayout()); 
2720 }
2721
2722
2723 void Paragraph::setPlainLayout(DocumentClass const & tc)
2724
2725         setLayout(tc.plainLayout()); 
2726 }
2727
2728
2729 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2730 {
2731         if (usePlainLayout())
2732                 setPlainLayout(tclass);
2733         else
2734                 setDefaultLayout(tclass);
2735 }
2736
2737
2738 Inset const & Paragraph::inInset() const
2739 {
2740         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2741                 _("Memory problem"), _("Paragraph not properly initialized")));
2742         return *d->inset_owner_;
2743 }
2744
2745
2746 ParagraphParameters & Paragraph::params()
2747 {
2748         return d->params_;
2749 }
2750
2751
2752 ParagraphParameters const & Paragraph::params() const
2753 {
2754         return d->params_;
2755 }
2756
2757
2758 bool Paragraph::isFreeSpacing() const
2759 {
2760         if (d->layout_->free_spacing)
2761                 return true;
2762         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2763 }
2764
2765
2766 bool Paragraph::allowEmpty() const
2767 {
2768         if (d->layout_->keepempty)
2769                 return true;
2770         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2771 }
2772
2773
2774 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2775 {
2776         if (!Encodings::isArabicChar(c))
2777                 return c;
2778
2779         char_type prev_char = ' ';
2780         char_type next_char = ' ';
2781
2782         for (pos_type i = pos - 1; i >= 0; --i) {
2783                 char_type const par_char = d->text_[i];
2784                 if (!Encodings::isArabicComposeChar(par_char)) {
2785                         prev_char = par_char;
2786                         break;
2787                 }
2788         }
2789
2790         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2791                 char_type const par_char = d->text_[i];
2792                 if (!Encodings::isArabicComposeChar(par_char)) {
2793                         next_char = par_char;
2794                         break;
2795                 }
2796         }
2797
2798         if (Encodings::isArabicChar(next_char)) {
2799                 if (Encodings::isArabicChar(prev_char) &&
2800                         !Encodings::isArabicSpecialChar(prev_char))
2801                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2802                 else
2803                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2804         } else {
2805                 if (Encodings::isArabicChar(prev_char) &&
2806                         !Encodings::isArabicSpecialChar(prev_char))
2807                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2808                 else
2809                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2810         }
2811 }
2812
2813
2814 int Paragraph::checkBiblio(Buffer const & buffer)
2815 {
2816         // FIXME From JS:
2817         // This is getting more and more a mess. ...We really should clean
2818         // up this bibitem issue for 1.6. See also bug 2743.
2819
2820         // Add bibitem insets if necessary
2821         if (d->layout_->labeltype != LABEL_BIBLIO)
2822                 return 0;
2823
2824         bool hasbibitem = !d->insetlist_.empty()
2825                 // Insist on it being in pos 0
2826                 && d->text_[0] == META_INSET
2827                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2828
2829         bool track_changes = buffer.params().trackChanges;
2830
2831         docstring oldkey;
2832         docstring oldlabel;
2833
2834         // remove a bibitem in pos != 0
2835         // restore it later in pos 0 if necessary
2836         // (e.g. if a user inserts contents _before_ the item)
2837         // we're assuming there's only one of these, which there
2838         // should be.
2839         int erasedInsetPosition = -1;
2840         InsetList::iterator it = d->insetlist_.begin();
2841         InsetList::iterator end = d->insetlist_.end();
2842         for (; it != end; ++it)
2843                 if (it->inset->lyxCode() == BIBITEM_CODE
2844                     && it->pos > 0) {
2845                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2846                         oldkey = olditem->getParam("key");
2847                         oldlabel = olditem->getParam("label");
2848                         erasedInsetPosition = it->pos;
2849                         eraseChar(erasedInsetPosition, track_changes);
2850                         break;
2851         }
2852
2853         // There was an InsetBibitem at the beginning, and we didn't
2854         // have to erase one.
2855         if (hasbibitem && erasedInsetPosition < 0)
2856                         return 0;
2857
2858         // There was an InsetBibitem at the beginning and we did have to
2859         // erase one. So we give its properties to the beginning inset.
2860         if (hasbibitem) {
2861                 InsetBibitem * inset =
2862                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2863                 if (!oldkey.empty())
2864                         inset->setParam("key", oldkey);
2865                 inset->setParam("label", oldlabel);
2866                 return -erasedInsetPosition;
2867         }
2868
2869         // There was no inset at the beginning, so we need to create one with
2870         // the key and label of the one we erased.
2871         InsetBibitem * inset = 
2872                 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
2873         // restore values of previously deleted item in this par.
2874         if (!oldkey.empty())
2875                 inset->setParam("key", oldkey);
2876         inset->setParam("label", oldlabel);
2877         insertInset(0, static_cast<Inset *>(inset),
2878                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2879
2880         return 1;
2881 }
2882
2883
2884 void Paragraph::checkAuthors(AuthorList const & authorList)
2885 {
2886         d->changes_.checkAuthors(authorList);
2887 }
2888
2889
2890 bool Paragraph::isChanged(pos_type pos) const
2891 {
2892         return lookupChange(pos).changed();
2893 }
2894
2895
2896 bool Paragraph::isInserted(pos_type pos) const
2897 {
2898         return lookupChange(pos).inserted();
2899 }
2900
2901
2902 bool Paragraph::isDeleted(pos_type pos) const
2903 {
2904         return lookupChange(pos).deleted();
2905 }
2906
2907
2908 InsetList const & Paragraph::insetList() const
2909 {
2910         return d->insetlist_;
2911 }
2912
2913
2914 void Paragraph::setBuffer(Buffer & b)
2915 {
2916         d->insetlist_.setBuffer(b);
2917 }
2918
2919
2920 Inset * Paragraph::releaseInset(pos_type pos)
2921 {
2922         Inset * inset = d->insetlist_.release(pos);
2923         /// does not honour change tracking!
2924         eraseChar(pos, false);
2925         return inset;
2926 }
2927
2928
2929 Inset * Paragraph::getInset(pos_type pos)
2930 {
2931         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2932                  ? d->insetlist_.get(pos) : 0;
2933 }
2934
2935
2936 Inset const * Paragraph::getInset(pos_type pos) const
2937 {
2938         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2939                  ? d->insetlist_.get(pos) : 0;
2940 }
2941
2942
2943 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2944                 pos_type & right, TextCase action)
2945 {
2946         // process sequences of modified characters; in change
2947         // tracking mode, this approach results in much better
2948         // usability than changing case on a char-by-char basis
2949         docstring changes;
2950
2951         bool const trackChanges = bparams.trackChanges;
2952
2953         bool capitalize = true;
2954
2955         for (; pos < right; ++pos) {
2956                 char_type oldChar = d->text_[pos];
2957                 char_type newChar = oldChar;
2958
2959                 // ignore insets and don't play with deleted text!
2960                 if (oldChar != META_INSET && !isDeleted(pos)) {
2961                         switch (action) {
2962                                 case text_lowercase:
2963                                         newChar = lowercase(oldChar);
2964                                         break;
2965                                 case text_capitalization:
2966                                         if (capitalize) {
2967                                                 newChar = uppercase(oldChar);
2968                                                 capitalize = false;
2969                                         }
2970                                         break;
2971                                 case text_uppercase:
2972                                         newChar = uppercase(oldChar);
2973                                         break;
2974                         }
2975                 }
2976
2977                 if (isWordSeparator(pos) || isDeleted(pos)) {
2978                         // permit capitalization again
2979                         capitalize = true;
2980                 }
2981
2982                 if (oldChar != newChar) {
2983                         changes += newChar;
2984                         if (pos != right - 1)
2985                                 continue;
2986                         // step behind the changing area
2987                         pos++;
2988                 }
2989
2990                 int erasePos = pos - changes.size();
2991                 for (size_t i = 0; i < changes.size(); i++) {
2992                         insertChar(pos, changes[i],
2993                                    getFontSettings(bparams,
2994                                                    erasePos),
2995                                    trackChanges);
2996                         if (!eraseChar(erasePos, trackChanges)) {
2997                                 ++erasePos;
2998                                 ++pos; // advance
2999                                 ++right; // expand selection
3000                         }
3001                 }
3002                 changes.clear();
3003         }
3004 }
3005
3006
3007 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3008                 pos_type pos, bool del) const
3009 {
3010         int const strsize = str.length();
3011         int i = 0;
3012         pos_type const parsize = d->text_.size();
3013         for (i = 0; pos + i < parsize; ++i) {
3014                 if (i >= strsize)
3015                         break;
3016                 if (cs && str[i] != d->text_[pos + i])
3017                         break;
3018                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3019                         break;
3020                 if (!del && isDeleted(pos + i))
3021                         break;
3022         }
3023
3024         if (i != strsize)
3025                 return false;
3026
3027         // if necessary, check whether string matches word
3028         if (mw) {
3029                 if (pos > 0 && !isWordSeparator(pos - 1))
3030                         return false;
3031                 if (pos + strsize < parsize
3032                         && !isWordSeparator(pos + strsize))
3033                         return false;
3034         }
3035
3036         return true;
3037 }
3038
3039
3040 char_type Paragraph::getChar(pos_type pos) const
3041 {
3042         return d->text_[pos];
3043 }
3044
3045
3046 pos_type Paragraph::size() const
3047 {
3048         return d->text_.size();
3049 }
3050
3051
3052 bool Paragraph::empty() const
3053 {
3054         return d->text_.empty();
3055 }
3056
3057
3058 bool Paragraph::isInset(pos_type pos) const
3059 {
3060         return d->text_[pos] == META_INSET;
3061 }
3062
3063
3064 bool Paragraph::isSeparator(pos_type pos) const
3065 {
3066         //FIXME: Are we sure this can be the only separator?
3067         return d->text_[pos] == ' ';
3068 }
3069
3070
3071 void Paragraph::deregisterWords()
3072 {
3073         map<Language, Private::Words>::const_iterator itl;
3074         Private::Words::const_iterator it;
3075         for (itl = d->words_.begin(); itl != d->words_.end(); ++itl) {
3076                 WordList * wl = theWordList(itl->first);
3077                 for (it = (itl->second).begin(); it != (itl->second).end(); ++it)
3078                         wl->remove(*it);
3079         }
3080         d->words_.clear();
3081 }
3082
3083
3084 void Paragraph::locateWord(pos_type & from, pos_type & to,
3085         word_location const loc) const
3086 {
3087         switch (loc) {
3088         case WHOLE_WORD_STRICT:
3089                 if (from == 0 || from == size()
3090                     || isWordSeparator(from)
3091                     || isWordSeparator(from - 1)) {
3092                         to = from;
3093                         return;
3094                 }
3095                 // no break here, we go to the next
3096
3097         case WHOLE_WORD:
3098                 // If we are already at the beginning of a word, do nothing
3099                 if (!from || isWordSeparator(from - 1))
3100                         break;
3101                 // no break here, we go to the next
3102
3103         case PREVIOUS_WORD:
3104                 // always move the cursor to the beginning of previous word
3105                 while (from && !isWordSeparator(from - 1))
3106                         --from;
3107                 break;
3108         case NEXT_WORD:
3109                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3110                 break;
3111         case PARTIAL_WORD:
3112                 // no need to move the 'from' cursor
3113                 break;
3114         }
3115         to = from;
3116         while (to < size() && !isWordSeparator(to))
3117                 ++to;
3118 }
3119
3120
3121 void Paragraph::collectWords()
3122 {
3123         pos_type n = size();
3124         for (pos_type pos = 0; pos < n; ++pos) {
3125                 if (isWordSeparator(pos))
3126                         continue;
3127                 pos_type from = pos;
3128                 locateWord(from, pos, WHOLE_WORD);
3129                 if (pos - from >= 6) {
3130                         docstring word = asString(from, pos, AS_STR_NONE);
3131                         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3132                         if (cit == d->fontlist_.end())
3133                                 return;
3134                         Language const * lang = cit->font().language();
3135                         d->words_[*lang].insert(word);
3136                 }
3137         }
3138 }
3139
3140
3141 void Paragraph::registerWords()
3142 {
3143         map<Language, Private::Words>::const_iterator itl;
3144         Private::Words::const_iterator it;
3145         for (itl = d->words_.begin(); itl != d->words_.end(); ++itl) {
3146                 WordList * wl = theWordList(itl->first);
3147                 for (it = (itl->second).begin(); it != (itl->second).end(); ++it)
3148                         wl->insert(*it);
3149         }
3150 }
3151
3152
3153 void Paragraph::updateWords()
3154 {
3155         deregisterWords();
3156         collectWords();
3157         registerWords();
3158 }
3159
3160
3161 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3162         docstring_list & suggestions, bool do_suggestion) const
3163 {
3164         SpellChecker * speller = theSpellChecker();
3165         if (!speller)
3166                 return false;
3167
3168         locateWord(from, to, WHOLE_WORD);
3169         if (from == to || from >= pos_type(d->text_.size()))
3170                 return false;
3171
3172         docstring word = asString(from, to, AS_STR_INSETS);
3173         Language * lang = const_cast<Language *>(getFontSettings(
3174                     d->inset_owner_->buffer().params(), from).language());
3175         if (lang == d->inset_owner_->buffer().params().language
3176             && !lyxrc.spellchecker_alt_lang.empty()) {
3177                 string lang_code;
3178                 string const lang_variety =
3179                         split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3180                 lang->setCode(lang_code);
3181                 lang->setVariety(lang_variety);
3182         }
3183         wl = WordLangTuple(word, lang);
3184         SpellChecker::Result res = speller->check(wl);
3185 #if 0
3186 // FIXME: the code below makes aspell abort if a word in an unknown
3187 //        language is checked.
3188         // Just ignore any error that the spellchecker reports.
3189         // FIXME: we should through out an exception and catch it in the GUI to
3190         // display the error.
3191         if (!speller->error().empty())
3192                 return false;
3193 #endif
3194
3195         bool const misspelled = res != SpellChecker::OK
3196                 && res != SpellChecker::IGNORED_WORD;
3197
3198         if (lyxrc.spellcheck_continuously)
3199                 d->fontlist_.setMisspelled(from, to, misspelled);
3200
3201         if (misspelled && do_suggestion)
3202                 speller->suggest(wl, suggestions);
3203         else
3204                 suggestions.clear();
3205
3206         return misspelled;
3207 }
3208
3209
3210 bool Paragraph::isMisspelled(pos_type pos) const
3211 {
3212         pos_type from = pos;
3213         pos_type to = pos;
3214         WordLangTuple wl;
3215         docstring_list suggestions;
3216         return spellCheck(from, to, wl, suggestions, false);
3217 }
3218
3219
3220 string Paragraph::magicLabel() const
3221 {
3222         stringstream ss;
3223         ss << "magicparlabel-" << id();
3224         return ss.str();
3225 }
3226
3227
3228 } // namespace lyx