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