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