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