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