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