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