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