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