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