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