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