]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Only step counters we have.
[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 Richard Heck (XHTML output)
9  * \author Jean-Marc Lasgouttes
10  * \author Angus Leeming
11  * \author John Levon
12  * \author André Pönitz
13  * \author Dekel Tsur
14  * \author Jürgen Vigna
15  *
16  * Full author contact details are available in file CREDITS.
17  */
18
19 #include <config.h>
20
21 #include "Paragraph.h"
22
23 #include "LayoutFile.h"
24 #include "Buffer.h"
25 #include "BufferParams.h"
26 #include "Changes.h"
27 #include "Counters.h"
28 #include "Encoding.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "Font.h"
35 #include "FontList.h"
36 #include "LyXRC.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TexRow.h"
45 #include "Text.h"
46 #include "VSpace.h"
47 #include "WordLangTuple.h"
48 #include "WordList.h"
49
50 #include "frontends/alert.h"
51
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
62
63 #include <sstream>
64 #include <vector>
65
66 using namespace std;
67 using namespace lyx::support;
68
69 namespace lyx {
70
71 namespace {
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
74 };
75
76 /////////////////////////////////////////////////////////////////////
77 //
78 // Paragraph::Private
79 //
80 /////////////////////////////////////////////////////////////////////
81
82 class Paragraph::Private
83 {
84 public:
85         ///
86         Private(Paragraph * owner, Layout const & layout);
87         /// "Copy constructor"
88         Private(Private const &, Paragraph * owner);
89         /// Copy constructor from \p beg  to \p end
90         Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
91
92         ///
93         void insertChar(pos_type pos, char_type c, Change const & change);
94
95         /// Output the surrogate pair formed by \p c and \p next to \p os.
96         /// \return the number of characters written.
97         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98                                OutputParams const &);
99
100         /// Output a space in appropriate formatting (or a surrogate pair
101         /// if the next character is a combining character).
102         /// \return whether a surrogate pair was output.
103         bool simpleTeXBlanks(OutputParams const &,
104                              odocstream &, TexRow & texrow,
105                              pos_type i,
106                              unsigned int & column,
107                              Font const & font,
108                              Layout const & style);
109
110         /// Output consecutive unicode chars, belonging to the same script as
111         /// specified by the latex macro \p ltx, to \p os starting from \p i.
112         /// \return the number of characters written.
113         int writeScriptChars(odocstream & os, docstring const & ltx,
114                            Change const &, Encoding const &, pos_type & i);
115
116         /// This could go to ParagraphParameters if we want to.
117         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118                               OutputParams const &) const;
119
120         /// This could go to ParagraphParameters if we want to.
121         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122                             OutputParams const &) const;
123
124         ///
125         void latexInset(BufferParams const &,
126                                    odocstream &,
127                                    TexRow & texrow, OutputParams &,
128                                    Font & running_font,
129                                    Font & basefont,
130                                    Font const & outerfont,
131                                    bool & open_font,
132                                    Change & running_change,
133                                    Layout const & style,
134                                    pos_type & i,
135                                    unsigned int & column);
136
137         ///
138         void latexSpecialChar(
139                                    odocstream & os,
140                                    OutputParams const & runparams,
141                                    Font const & running_font,
142                                    Change const & running_change,
143                                    Layout const & style,
144                                    pos_type & i,
145                                    unsigned int & column);
146
147         ///
148         bool latexSpecialT1(
149                 char_type const c,
150                 odocstream & os,
151                 pos_type i,
152                 unsigned int & column);
153         ///
154         bool latexSpecialTypewriter(
155                 char_type const c,
156                 odocstream & os,
157                 pos_type i,
158                 unsigned int & column);
159         ///
160         bool latexSpecialPhrase(
161                 odocstream & os,
162                 pos_type & i,
163                 unsigned int & column,
164                 OutputParams const & runparams);
165
166         ///
167         void validate(LaTeXFeatures & features) 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) const
1074 {
1075         if (layout_->inpreamble && inset_owner_) {
1076                 Buffer const & buf = inset_owner_->buffer();
1077                 BufferParams const & bp = buf.params();
1078                 Font f;
1079                 TexRow tr;
1080                 // FIXME We probably would like actually to know about this.
1081                 odocstringstream ods;
1082                 owner_->latex(bp, f, ods, tr, features.runparams());
1083                 docstring d = ods.str();
1084                 if (!d.empty())
1085                         features.addPreambleSnippet(to_utf8(d));
1086         }
1087         
1088         // check the params.
1089         if (!params_.spacing().isDefault())
1090                 features.require("setspace");
1091
1092         // then the layouts
1093         features.useLayout(layout_->name());
1094
1095         // then the fonts
1096         fontlist_.validate(features);
1097
1098         // then the indentation
1099         if (!params_.leftIndent().zero())
1100                 features.require("ParagraphLeftIndent");
1101
1102         // then the insets
1103         InsetList::const_iterator icit = insetlist_.begin();
1104         InsetList::const_iterator iend = insetlist_.end();
1105         for (; icit != iend; ++icit) {
1106                 if (icit->inset) {
1107                         icit->inset->validate(features);
1108                         if (layout_->needprotect &&
1109                             icit->inset->lyxCode() == FOOT_CODE)
1110                                 features.require("NeedLyXFootnoteCode");
1111                 }
1112         }
1113
1114         // then the contents
1115         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1116                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1117                         if (!special_phrases[pnr].builtin
1118                             && isTextAt(special_phrases[pnr].phrase, i)) {
1119                                 features.require(special_phrases[pnr].phrase);
1120                                 break;
1121                         }
1122                 }
1123                 Encodings::validate(text_[i], features);
1124         }
1125 }
1126
1127 /////////////////////////////////////////////////////////////////////
1128 //
1129 // Paragraph
1130 //
1131 /////////////////////////////////////////////////////////////////////
1132
1133 namespace {
1134         Layout const emptyParagraphLayout;
1135 }
1136
1137 Paragraph::Paragraph() 
1138         : d(new Paragraph::Private(this, emptyParagraphLayout))
1139 {
1140         itemdepth = 0;
1141         d->params_.clear();
1142 }
1143
1144
1145 Paragraph::Paragraph(Paragraph const & par)
1146         : itemdepth(par.itemdepth),
1147         d(new Paragraph::Private(*par.d, this))
1148 {
1149         registerWords();
1150 }
1151
1152
1153 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1154         : itemdepth(par.itemdepth),
1155         d(new Paragraph::Private(*par.d, this, beg, end))
1156 {
1157         registerWords();
1158 }
1159
1160
1161 Paragraph & Paragraph::operator=(Paragraph const & par)
1162 {
1163         // needed as we will destroy the private part before copying it
1164         if (&par != this) {
1165                 itemdepth = par.itemdepth;
1166
1167                 deregisterWords();
1168                 delete d;
1169                 d = new Private(*par.d, this);
1170                 registerWords();
1171         }
1172         return *this;
1173 }
1174
1175
1176 Paragraph::~Paragraph()
1177 {
1178         deregisterWords();
1179         delete d;
1180 }
1181
1182
1183 namespace {
1184
1185 // this shall be called just before every "os << ..." action.
1186 void flushString(ostream & os, docstring & s)
1187 {
1188         os << to_utf8(s);
1189         s.erase();
1190 }
1191
1192 }
1193
1194
1195 void Paragraph::write(ostream & os, BufferParams const & bparams,
1196         depth_type & dth) const
1197 {
1198         // The beginning or end of a deeper (i.e. nested) area?
1199         if (dth != d->params_.depth()) {
1200                 if (d->params_.depth() > dth) {
1201                         while (d->params_.depth() > dth) {
1202                                 os << "\n\\begin_deeper";
1203                                 ++dth;
1204                         }
1205                 } else {
1206                         while (d->params_.depth() < dth) {
1207                                 os << "\n\\end_deeper";
1208                                 --dth;
1209                         }
1210                 }
1211         }
1212
1213         // First write the layout
1214         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1215
1216         d->params_.write(os);
1217
1218         Font font1(inherit_font, bparams.language);
1219
1220         Change running_change = Change(Change::UNCHANGED);
1221
1222         // this string is used as a buffer to avoid repetitive calls
1223         // to to_utf8(), which turn out to be expensive (JMarc)
1224         docstring write_buffer;
1225
1226         int column = 0;
1227         for (pos_type i = 0; i <= size(); ++i) {
1228
1229                 Change const change = lookupChange(i);
1230                 if (change != running_change)
1231                         flushString(os, write_buffer);
1232                 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1233                 running_change = change;
1234
1235                 if (i == size())
1236                         break;
1237
1238                 // Write font changes (ignore spelling markers)
1239                 Font font2 = getFontSettings(bparams, i);
1240                 font2.setMisspelled(false);
1241                 if (font2 != font1) {
1242                         flushString(os, write_buffer);
1243                         font2.lyxWriteChanges(font1, os);
1244                         column = 0;
1245                         font1 = font2;
1246                 }
1247
1248                 char_type const c = d->text_[i];
1249                 switch (c) {
1250                 case META_INSET:
1251                         if (Inset const * inset = getInset(i)) {
1252                                 flushString(os, write_buffer);
1253                                 if (inset->directWrite()) {
1254                                         // international char, let it write
1255                                         // code directly so it's shorter in
1256                                         // the file
1257                                         inset->write(os);
1258                                 } else {
1259                                         if (i)
1260                                                 os << '\n';
1261                                         os << "\\begin_inset ";
1262                                         inset->write(os);
1263                                         os << "\n\\end_inset\n\n";
1264                                         column = 0;
1265                                 }
1266                         }
1267                         break;
1268                 case '\\':
1269                         flushString(os, write_buffer);
1270                         os << "\n\\backslash\n";
1271                         column = 0;
1272                         break;
1273                 case '.':
1274                         flushString(os, write_buffer);
1275                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1276                                 os << ".\n";
1277                                 column = 0;
1278                         } else
1279                                 os << '.';
1280                         break;
1281                 default:
1282                         if ((column > 70 && c == ' ')
1283                             || column > 79) {
1284                                 flushString(os, write_buffer);
1285                                 os << '\n';
1286                                 column = 0;
1287                         }
1288                         // this check is to amend a bug. LyX sometimes
1289                         // inserts '\0' this could cause problems.
1290                         if (c != '\0')
1291                                 write_buffer.push_back(c);
1292                         else
1293                                 LYXERR0("NUL char in structure.");
1294                         ++column;
1295                         break;
1296                 }
1297         }
1298
1299         flushString(os, write_buffer);
1300         os << "\n\\end_layout\n";
1301 }
1302
1303
1304 void Paragraph::validate(LaTeXFeatures & features) const
1305 {
1306         d->validate(features);
1307 }
1308
1309
1310 void Paragraph::insert(pos_type start, docstring const & str,
1311                        Font const & font, Change const & change)
1312 {
1313         for (size_t i = 0, n = str.size(); i != n ; ++i)
1314                 insertChar(start + i, str[i], font, change);
1315 }
1316
1317
1318 void Paragraph::appendChar(char_type c, Font const & font,
1319                 Change const & change)
1320 {
1321         // track change
1322         d->changes_.insert(change, d->text_.size());
1323         // when appending characters, no need to update tables
1324         d->text_.push_back(c);
1325         setFont(d->text_.size() - 1, font);
1326 }
1327
1328
1329 void Paragraph::appendString(docstring const & s, Font const & font,
1330                 Change const & change)
1331 {
1332         pos_type end = s.size();
1333         size_t oldsize = d->text_.size();
1334         size_t newsize = oldsize + end;
1335         size_t capacity = d->text_.capacity();
1336         if (newsize >= capacity)
1337                 d->text_.reserve(max(capacity + 100, newsize));
1338
1339         // when appending characters, no need to update tables
1340         d->text_.append(s);
1341
1342         // FIXME: Optimize this!
1343         for (size_t i = oldsize; i != newsize; ++i) {
1344                 // track change
1345                 d->changes_.insert(change, i);
1346         }
1347         d->fontlist_.set(oldsize, font);
1348         d->fontlist_.set(newsize - 1, font);
1349 }
1350
1351
1352 void Paragraph::insertChar(pos_type pos, char_type c,
1353                            bool trackChanges)
1354 {
1355         d->insertChar(pos, c, Change(trackChanges ?
1356                            Change::INSERTED : Change::UNCHANGED));
1357 }
1358
1359
1360 void Paragraph::insertChar(pos_type pos, char_type c,
1361                            Font const & font, bool trackChanges)
1362 {
1363         d->insertChar(pos, c, Change(trackChanges ?
1364                            Change::INSERTED : Change::UNCHANGED));
1365         setFont(pos, font);
1366 }
1367
1368
1369 void Paragraph::insertChar(pos_type pos, char_type c,
1370                            Font const & font, Change const & change)
1371 {
1372         d->insertChar(pos, c, change);
1373         setFont(pos, font);
1374 }
1375
1376
1377 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1378                             Font const & font, Change const & change)
1379 {
1380         bool const success = insertInset(pos, inset, change);
1381         // Set the font/language of the inset...
1382         setFont(pos, font);
1383         return success;
1384 }
1385
1386
1387 void Paragraph::resetFonts(Font const & font)
1388 {
1389         d->fontlist_.clear();
1390         d->fontlist_.set(0, font);
1391         d->fontlist_.set(d->text_.size() - 1, font);
1392 }
1393
1394 // Gets uninstantiated font setting at position.
1395 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1396                                          pos_type pos) const
1397 {
1398         if (pos > size()) {
1399                 LYXERR0("pos: " << pos << " size: " << size());
1400                 LASSERT(pos <= size(), /**/);
1401         }
1402
1403         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1404         if (cit != d->fontlist_.end())
1405                 return cit->font();
1406
1407         if (pos == size() && !empty())
1408                 return getFontSettings(bparams, pos - 1);
1409
1410         // Optimisation: avoid a full font instantiation if there is no
1411         // language change from previous call.
1412         static Font previous_font;
1413         static Language const * previous_lang = 0;
1414         Language const * lang = getParLanguage(bparams);
1415         if (lang != previous_lang) {
1416                 previous_lang = lang;
1417                 previous_font = Font(inherit_font, lang);
1418         }
1419         return previous_font;
1420 }
1421
1422
1423 FontSpan Paragraph::fontSpan(pos_type pos) const
1424 {
1425         LASSERT(pos <= size(), /**/);
1426         pos_type start = 0;
1427
1428         FontList::const_iterator cit = d->fontlist_.begin();
1429         FontList::const_iterator end = d->fontlist_.end();
1430         for (; cit != end; ++cit) {
1431                 if (cit->pos() >= pos) {
1432                         if (pos >= beginOfBody())
1433                                 return FontSpan(max(start, beginOfBody()),
1434                                                 cit->pos());
1435                         else
1436                                 return FontSpan(start,
1437                                                 min(beginOfBody() - 1,
1438                                                          cit->pos()));
1439                 }
1440                 start = cit->pos() + 1;
1441         }
1442
1443         // This should not happen, but if so, we take no chances.
1444         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1445         return FontSpan(pos, pos);
1446 }
1447
1448
1449 // Gets uninstantiated font setting at position 0
1450 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1451 {
1452         if (!empty() && !d->fontlist_.empty())
1453                 return d->fontlist_.begin()->font();
1454
1455         // Optimisation: avoid a full font instantiation if there is no
1456         // language change from previous call.
1457         static Font previous_font;
1458         static Language const * previous_lang = 0;
1459         if (bparams.language != previous_lang) {
1460                 previous_lang = bparams.language;
1461                 previous_font = Font(inherit_font, bparams.language);
1462         }
1463
1464         return previous_font;
1465 }
1466
1467
1468 // Gets the fully instantiated font at a given position in a paragraph
1469 // This is basically the same function as Text::GetFont() in text2.cpp.
1470 // The difference is that this one is used for generating the LaTeX file,
1471 // and thus cosmetic "improvements" are disallowed: This has to deliver
1472 // the true picture of the buffer. (Asger)
1473 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1474                                  Font const & outerfont) const
1475 {
1476         LASSERT(pos >= 0, /**/);
1477
1478         Font font = getFontSettings(bparams, pos);
1479
1480         pos_type const body_pos = beginOfBody();
1481         FontInfo & fi = font.fontInfo();
1482         if (pos < body_pos)
1483                 fi.realize(d->layout_->labelfont);
1484         else
1485                 fi.realize(d->layout_->font);
1486
1487         fi.realize(outerfont.fontInfo());
1488         fi.realize(bparams.getFont().fontInfo());
1489
1490         return font;
1491 }
1492
1493
1494 Font const Paragraph::getLabelFont
1495         (BufferParams const & bparams, Font const & outerfont) const
1496 {
1497         FontInfo tmpfont = d->layout_->labelfont;
1498         tmpfont.realize(outerfont.fontInfo());
1499         tmpfont.realize(bparams.getFont().fontInfo());
1500         return Font(tmpfont, getParLanguage(bparams));
1501 }
1502
1503
1504 Font const Paragraph::getLayoutFont
1505         (BufferParams const & bparams, Font const & outerfont) const
1506 {
1507         FontInfo tmpfont = d->layout_->font;
1508         tmpfont.realize(outerfont.fontInfo());
1509         tmpfont.realize(bparams.getFont().fontInfo());
1510         return Font(tmpfont, getParLanguage(bparams));
1511 }
1512
1513
1514 /// Returns the height of the highest font in range
1515 FontSize Paragraph::highestFontInRange
1516         (pos_type startpos, pos_type endpos, FontSize def_size) const
1517 {
1518         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1519 }
1520
1521
1522 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1523 {
1524         char_type c = d->text_[pos];
1525         if (!lyxrc.rtl_support)
1526                 return c;
1527
1528         char_type uc = c;
1529         switch (c) {
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         case '{':
1543                 uc = '}';
1544                 break;
1545         case '}':
1546                 uc = '{';
1547                 break;
1548         case '<':
1549                 uc = '>';
1550                 break;
1551         case '>':
1552                 uc = '<';
1553                 break;
1554         }
1555         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1556                 return uc;
1557         return c;
1558 }
1559
1560
1561 void Paragraph::setFont(pos_type pos, Font const & font)
1562 {
1563         LASSERT(pos <= size(), /**/);
1564
1565         // First, reduce font against layout/label font
1566         // Update: The setCharFont() routine in text2.cpp already
1567         // reduces font, so we don't need to do that here. (Asger)
1568         
1569         d->fontlist_.set(pos, font);
1570 }
1571
1572
1573 void Paragraph::makeSameLayout(Paragraph const & par)
1574 {
1575         d->layout_ = par.d->layout_;
1576         d->params_ = par.d->params_;
1577 }
1578
1579
1580 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1581 {
1582         if (isFreeSpacing())
1583                 return false;
1584
1585         int pos = 0;
1586         int count = 0;
1587
1588         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1589                 if (eraseChar(pos, trackChanges))
1590                         ++count;
1591                 else
1592                         ++pos;
1593         }
1594
1595         return count > 0 || pos > 0;
1596 }
1597
1598
1599 bool Paragraph::hasSameLayout(Paragraph const & par) const
1600 {
1601         return par.d->layout_ == d->layout_
1602                 && d->params_.sameLayout(par.d->params_);
1603 }
1604
1605
1606 depth_type Paragraph::getDepth() const
1607 {
1608         return d->params_.depth();
1609 }
1610
1611
1612 depth_type Paragraph::getMaxDepthAfter() const
1613 {
1614         if (d->layout_->isEnvironment())
1615                 return d->params_.depth() + 1;
1616         else
1617                 return d->params_.depth();
1618 }
1619
1620
1621 char Paragraph::getAlign() const
1622 {
1623         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1624                 return d->layout_->align;
1625         else
1626                 return d->params_.align();
1627 }
1628
1629
1630 docstring const & Paragraph::labelString() const
1631 {
1632         return d->params_.labelString();
1633 }
1634
1635
1636 // the next two functions are for the manual labels
1637 docstring const Paragraph::getLabelWidthString() const
1638 {
1639         if (d->layout_->margintype == MARGIN_MANUAL
1640             || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1641                 return d->params_.labelWidthString();
1642         else
1643                 return _("Senseless with this layout!");
1644 }
1645
1646
1647 void Paragraph::setLabelWidthString(docstring const & s)
1648 {
1649         d->params_.labelWidthString(s);
1650 }
1651
1652
1653 docstring Paragraph::expandLabel(Layout const & layout,
1654                 BufferParams const & bparams, bool process_appendix) const
1655 {
1656         DocumentClass const & tclass = bparams.documentClass();
1657         string const & lang = getParLanguage(bparams)->code();
1658         bool const in_appendix = process_appendix && d->params_.appendix();
1659         docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1660
1661         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1662             && !layout.counter.empty())
1663                 return tclass.counters().theCounter(layout.counter, lang);
1664
1665         // handle 'inherited level parts' in 'fmt',
1666         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1667         size_t const i = fmt.find('@', 0);
1668         if (i != docstring::npos) {
1669                 size_t const j = fmt.find('@', i + 1);
1670                 if (j != docstring::npos) {
1671                         docstring parent(fmt, i + 1, j - i - 1);
1672                         docstring label = from_ascii("??");
1673                         if (tclass.hasLayout(parent))
1674                                 docstring label = expandLabel(tclass[parent], bparams,
1675                                                       process_appendix);
1676                         fmt = docstring(fmt, 0, i) + label 
1677                                 + docstring(fmt, j + 1, docstring::npos);
1678                 }
1679         }
1680
1681         return tclass.counters().counterLabel(fmt, lang);
1682 }
1683
1684
1685 void Paragraph::applyLayout(Layout const & new_layout)
1686 {
1687         d->layout_ = &new_layout;
1688         LyXAlignment const oldAlign = d->params_.align();
1689         
1690         if (!(oldAlign & d->layout_->alignpossible)) {
1691                 frontend::Alert::warning(_("Alignment not permitted"), 
1692                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1693                 d->params_.align(LYX_ALIGN_LAYOUT);
1694         }
1695 }
1696
1697
1698 pos_type Paragraph::beginOfBody() const
1699 {
1700         return d->begin_of_body_;
1701 }
1702
1703
1704 void Paragraph::setBeginOfBody()
1705 {
1706         if (d->layout_->labeltype != LABEL_MANUAL) {
1707                 d->begin_of_body_ = 0;
1708                 return;
1709         }
1710
1711         // Unroll the first two cycles of the loop
1712         // and remember the previous character to
1713         // remove unnecessary getChar() calls
1714         pos_type i = 0;
1715         pos_type end = size();
1716         if (i < end && !isNewline(i)) {
1717                 ++i;
1718                 char_type previous_char = 0;
1719                 char_type temp = 0;
1720                 if (i < end) {
1721                         previous_char = d->text_[i];
1722                         if (!isNewline(i)) {
1723                                 ++i;
1724                                 while (i < end && previous_char != ' ') {
1725                                         temp = d->text_[i];
1726                                         if (isNewline(i))
1727                                                 break;
1728                                         ++i;
1729                                         previous_char = temp;
1730                                 }
1731                         }
1732                 }
1733         }
1734
1735         d->begin_of_body_ = i;
1736 }
1737
1738
1739 bool Paragraph::allowParagraphCustomization() const
1740 {
1741         return inInset().allowParagraphCustomization();
1742 }
1743
1744
1745 bool Paragraph::usePlainLayout() const
1746 {
1747         return inInset().usePlainLayout();
1748 }
1749
1750
1751 namespace {
1752
1753 // paragraphs inside floats need different alignment tags to avoid
1754 // unwanted space
1755
1756 bool noTrivlistCentering(InsetCode code)
1757 {
1758         return code == FLOAT_CODE
1759                || code == WRAP_CODE
1760                || code == CELL_CODE;
1761 }
1762
1763
1764 string correction(string const & orig)
1765 {
1766         if (orig == "flushleft")
1767                 return "raggedright";
1768         if (orig == "flushright")
1769                 return "raggedleft";
1770         if (orig == "center")
1771                 return "centering";
1772         return orig;
1773 }
1774
1775
1776 string const corrected_env(string const & suffix, string const & env,
1777         InsetCode code, bool const lastpar)
1778 {
1779         string output = suffix + "{";
1780         if (noTrivlistCentering(code)) {
1781                 if (lastpar) {
1782                         // the last paragraph in non-trivlist-aligned
1783                         // context is special (to avoid unwanted whitespace)
1784                         if (suffix == "\\begin")
1785                                 return "\\" + correction(env) + "{}";
1786                         return string();
1787                 }
1788                 output += correction(env);
1789         } else
1790                 output += env;
1791         output += "}";
1792         if (suffix == "\\begin")
1793                 output += "\n";
1794         return output;
1795 }
1796
1797
1798 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1799 {
1800         if (!contains(str, "\n"))
1801                 column += str.size();
1802         else {
1803                 string tmp;
1804                 texrow.newline();
1805                 column = rsplit(str, tmp, '\n').size();
1806         }
1807 }
1808
1809 } // namespace anon
1810
1811
1812 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1813                                  odocstream & os, TexRow & texrow,
1814                                  OutputParams const & runparams) const
1815 {
1816         int column = 0;
1817
1818         if (params_.noindent()) {
1819                 os << "\\noindent ";
1820                 column += 10;
1821         }
1822         
1823         LyXAlignment const curAlign = params_.align();
1824
1825         if (curAlign == layout_->align)
1826                 return column;
1827
1828         switch (curAlign) {
1829         case LYX_ALIGN_NONE:
1830         case LYX_ALIGN_BLOCK:
1831         case LYX_ALIGN_LAYOUT:
1832         case LYX_ALIGN_SPECIAL:
1833                 break;
1834         case LYX_ALIGN_LEFT:
1835         case LYX_ALIGN_RIGHT:
1836         case LYX_ALIGN_CENTER:
1837                 if (runparams.moving_arg) {
1838                         os << "\\protect";
1839                         column += 8;
1840                 }
1841                 break;
1842         }
1843
1844         string const begin_tag = "\\begin";
1845         InsetCode code = ownerCode();
1846         bool const lastpar = runparams.isLastPar;
1847
1848         switch (curAlign) {
1849         case LYX_ALIGN_NONE:
1850         case LYX_ALIGN_BLOCK:
1851         case LYX_ALIGN_LAYOUT:
1852         case LYX_ALIGN_SPECIAL:
1853                 break;
1854         case LYX_ALIGN_LEFT: {
1855                 string output;
1856                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1857                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1858                 else
1859                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1860                 os << from_ascii(output);
1861                 adjust_row_column(output, texrow, column);
1862                 break;
1863         } case LYX_ALIGN_RIGHT: {
1864                 string output;
1865                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1866                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1867                 else
1868                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1869                 os << from_ascii(output);
1870                 adjust_row_column(output, texrow, column);
1871                 break;
1872         } case LYX_ALIGN_CENTER: {
1873                 string output;
1874                 output = corrected_env(begin_tag, "center", code, lastpar);
1875                 os << from_ascii(output);
1876                 adjust_row_column(output, texrow, column);
1877                 break;
1878         }
1879         }
1880
1881         return column;
1882 }
1883
1884
1885 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1886                                odocstream & os, TexRow & texrow,
1887                                OutputParams const & runparams) const
1888 {
1889         int column = 0;
1890
1891         LyXAlignment const curAlign = params_.align();
1892
1893         if (curAlign == layout_->align)
1894                 return column;
1895
1896         switch (curAlign) {
1897         case LYX_ALIGN_NONE:
1898         case LYX_ALIGN_BLOCK:
1899         case LYX_ALIGN_LAYOUT:
1900         case LYX_ALIGN_SPECIAL:
1901                 break;
1902         case LYX_ALIGN_LEFT:
1903         case LYX_ALIGN_RIGHT:
1904         case LYX_ALIGN_CENTER:
1905                 if (runparams.moving_arg) {
1906                         os << "\\protect";
1907                         column = 8;
1908                 }
1909                 break;
1910         }
1911
1912         string const end_tag = "\n\\par\\end";
1913         InsetCode code = ownerCode();
1914         bool const lastpar = runparams.isLastPar;
1915
1916         switch (curAlign) {
1917         case LYX_ALIGN_NONE:
1918         case LYX_ALIGN_BLOCK:
1919         case LYX_ALIGN_LAYOUT:
1920         case LYX_ALIGN_SPECIAL:
1921                 break;
1922         case LYX_ALIGN_LEFT: {
1923                 string output;
1924                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1925                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1926                 else
1927                         output = corrected_env(end_tag, "flushright", code, lastpar);
1928                 os << from_ascii(output);
1929                 adjust_row_column(output, texrow, column);
1930                 break;
1931         } case LYX_ALIGN_RIGHT: {
1932                 string output;
1933                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1934                         output = corrected_env(end_tag, "flushright", code, lastpar);
1935                 else
1936                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1937                 os << from_ascii(output);
1938                 adjust_row_column(output, texrow, column);
1939                 break;
1940         } case LYX_ALIGN_CENTER: {
1941                 string output;
1942                 output = corrected_env(end_tag, "center", code, lastpar);
1943                 os << from_ascii(output);
1944                 adjust_row_column(output, texrow, column);
1945                 break;
1946         }
1947         }
1948
1949         return column;
1950 }
1951
1952
1953 // This one spits out the text of the paragraph
1954 bool Paragraph::latex(BufferParams const & bparams,
1955         Font const & outerfont,
1956         odocstream & os, TexRow & texrow,
1957         OutputParams const & runparams,
1958         int start_pos, int end_pos) const
1959 {
1960         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
1961
1962         if (layout().inpreamble)
1963                 return true;
1964
1965         bool return_value = false;
1966
1967         bool const allowcust = allowParagraphCustomization();
1968
1969         // FIXME This check should not be needed. Perhaps issue an
1970         // error if it triggers.
1971         Layout const & style = inInset().forcePlainLayout() ?
1972                 bparams.documentClass().plainLayout() : *d->layout_;
1973
1974         // Current base font for all inherited font changes, without any
1975         // change caused by an individual character, except for the language:
1976         // It is set to the language of the first character.
1977         // As long as we are in the label, this font is the base font of the
1978         // label. Before the first body character it is set to the base font
1979         // of the body.
1980         Font basefont;
1981
1982         // Maybe we have to create a optional argument.
1983         pos_type body_pos = beginOfBody();
1984         unsigned int column = 0;
1985
1986         if (body_pos > 0) {
1987                 os << '[';
1988                 column += 1;
1989                 basefont = getLabelFont(bparams, outerfont);
1990         } else {
1991                 basefont = getLayoutFont(bparams, outerfont);
1992         }
1993
1994         // Which font is currently active?
1995         Font running_font(basefont);
1996         // Do we have an open font change?
1997         bool open_font = false;
1998
1999         Change runningChange = Change(Change::UNCHANGED);
2000
2001         Encoding const * const prev_encoding = runparams.encoding;
2002
2003         texrow.start(id(), 0);
2004
2005         // if the paragraph is empty, the loop will not be entered at all
2006         if (empty()) {
2007                 if (style.isCommand()) {
2008                         os << '{';
2009                         ++column;
2010                 }
2011                 if (allowcust)
2012                         column += d->startTeXParParams(bparams, os, texrow,
2013                                                     runparams);
2014         }
2015
2016         for (pos_type i = 0; i < size(); ++i) {
2017                 // First char in paragraph or after label?
2018                 if (i == body_pos) {
2019                         if (body_pos > 0) {
2020                                 if (open_font) {
2021                                         column += running_font.latexWriteEndChanges(
2022                                                 os, bparams, runparams,
2023                                                 basefont, basefont);
2024                                         open_font = false;
2025                                 }
2026                                 basefont = getLayoutFont(bparams, outerfont);
2027                                 running_font = basefont;
2028
2029                                 column += Changes::latexMarkChange(os, bparams,
2030                                                 runningChange, Change(Change::UNCHANGED),
2031                                                 runparams);
2032                                 runningChange = Change(Change::UNCHANGED);
2033
2034                                 os << "] ";
2035                                 column +=2;
2036                         }
2037                         if (style.isCommand()) {
2038                                 os << '{';
2039                                 ++column;
2040                         }
2041
2042                         if (allowcust)
2043                                 column += d->startTeXParParams(bparams, os,
2044                                                             texrow,
2045                                                             runparams);
2046                 }
2047
2048                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2049                                                                  : lookupChange(i);
2050
2051                 if (bparams.outputChanges && runningChange != change) {
2052                         if (open_font) {
2053                                 column += running_font.latexWriteEndChanges(
2054                                                 os, bparams, runparams, basefont, basefont);
2055                                 open_font = false;
2056                         }
2057                         basefont = getLayoutFont(bparams, outerfont);
2058                         running_font = basefont;
2059
2060                         column += Changes::latexMarkChange(os, bparams, runningChange,
2061                                                            change, runparams);
2062                         runningChange = change;
2063                 }
2064
2065                 // do not output text which is marked deleted
2066                 // if change tracking output is disabled
2067                 if (!bparams.outputChanges && change.deleted()) {
2068                         continue;
2069                 }
2070
2071                 ++column;
2072
2073                 // Fully instantiated font
2074                 Font const font = getFont(bparams, i, outerfont);
2075
2076                 Font const last_font = running_font;
2077
2078                 // Do we need to close the previous font?
2079                 if (open_font &&
2080                     (font != running_font ||
2081                      font.language() != running_font.language()))
2082                 {
2083                         column += running_font.latexWriteEndChanges(
2084                                         os, bparams, runparams, basefont,
2085                                         (i == body_pos-1) ? basefont : font);
2086                         running_font = basefont;
2087                         open_font = false;
2088                 }
2089
2090                 // close babel's font environment before opening CJK.
2091                 if (!running_font.language()->babel().empty() &&
2092                     font.language()->encoding()->package() == Encoding::CJK) {
2093                                 string end_tag = subst(lyxrc.language_command_end,
2094                                                         "$$lang",
2095                                                         running_font.language()->babel());
2096                                 os << from_ascii(end_tag);
2097                                 column += end_tag.length();
2098                 }
2099
2100                 // Switch file encoding if necessary (and allowed)
2101                 if (!runparams.verbatim && 
2102                     runparams.encoding->package() != Encoding::none &&
2103                     font.language()->encoding()->package() != Encoding::none) {
2104                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2105                                         runparams, *(font.language()->encoding()));
2106                         if (enc_switch.first) {
2107                                 column += enc_switch.second;
2108                                 runparams.encoding = font.language()->encoding();
2109                         }
2110                 }
2111
2112                 char_type const c = d->text_[i];
2113
2114                 // Do we need to change font?
2115                 if ((font != running_font ||
2116                      font.language() != running_font.language()) &&
2117                         i != body_pos - 1)
2118                 {
2119                         odocstringstream ods;
2120                         column += font.latexWriteStartChanges(ods, bparams,
2121                                                               runparams, basefont,
2122                                                               last_font);
2123                         running_font = font;
2124                         open_font = true;
2125                         docstring fontchange = ods.str();
2126                         // check whether the fontchange ends with a \\textcolor
2127                         // modifier and the text starts with a space (bug 4473)
2128                         docstring const last_modifier = rsplit(fontchange, '\\');
2129                         if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2130                                 os << fontchange << from_ascii("{}");
2131                         // check if the fontchange ends with a trailing blank
2132                         // (like "\small " (see bug 3382)
2133                         else if (suffixIs(fontchange, ' ') && c == ' ')
2134                                 os << fontchange.substr(0, fontchange.size() - 1) 
2135                                    << from_ascii("{}");
2136                         else
2137                                 os << fontchange;
2138                 }
2139
2140                 // FIXME: think about end_pos implementation...
2141                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2142                         // FIXME: integrate this case in latexSpecialChar
2143                         // Do not print the separation of the optional argument
2144                         // if style.pass_thru is false. This works because
2145                         // latexSpecialChar ignores spaces if
2146                         // style.pass_thru is false.
2147                         if (i != body_pos - 1) {
2148                                 if (d->simpleTeXBlanks(
2149                                                 runparams, os, texrow,
2150                                                 i, column, font, style)) {
2151                                         // A surrogate pair was output. We
2152                                         // must not call latexSpecialChar
2153                                         // in this iteration, since it would output
2154                                         // the combining character again.
2155                                         ++i;
2156                                         continue;
2157                                 }
2158                         }
2159                 }
2160
2161                 OutputParams rp = runparams;
2162                 rp.free_spacing = style.free_spacing;
2163                 rp.local_font = &font;
2164                 rp.intitle = style.intitle;
2165
2166                 // Two major modes:  LaTeX or plain
2167                 // Handle here those cases common to both modes
2168                 // and then split to handle the two modes separately.
2169                 if (c == META_INSET) {
2170                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2171                                 d->latexInset(bparams, os,
2172                                                 texrow, rp, running_font,
2173                                                 basefont, outerfont, open_font,
2174                                                 runningChange, style, i, column);
2175                         }
2176                 } else {
2177                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2178                                 try {
2179                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2180                                                 style, i, column);
2181                                 } catch (EncodingException & e) {
2182                                 if (runparams.dryrun) {
2183                                         os << "<" << _("LyX Warning: ")
2184                                            << _("uncodable character") << " '";
2185                                         os.put(c);
2186                                         os << "'>";
2187                                 } else {
2188                                         // add location information and throw again.
2189                                         e.par_id = id();
2190                                         e.pos = i;
2191                                         throw(e);
2192                                 }
2193                         }
2194                 }
2195                 }
2196
2197                 // Set the encoding to that returned from latexSpecialChar (see
2198                 // comment for encoding member in OutputParams.h)
2199                 runparams.encoding = rp.encoding;
2200         }
2201
2202         // If we have an open font definition, we have to close it
2203         if (open_font) {
2204 #ifdef FIXED_LANGUAGE_END_DETECTION
2205                 if (next_) {
2206                         running_font
2207                                 .latexWriteEndChanges(os, bparams, runparams,
2208                                         basefont,
2209                                         next_->getFont(bparams, 0, outerfont));
2210                 } else {
2211                         running_font.latexWriteEndChanges(os, bparams,
2212                                         runparams, basefont, basefont);
2213                 }
2214 #else
2215 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2216 //FIXME: there as we start another \selectlanguage with the next paragraph if
2217 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2218                 running_font.latexWriteEndChanges(os, bparams, runparams,
2219                                 basefont, basefont);
2220 #endif
2221         }
2222
2223         column += Changes::latexMarkChange(os, bparams, runningChange,
2224                                            Change(Change::UNCHANGED), runparams);
2225
2226         // Needed if there is an optional argument but no contents.
2227         if (body_pos > 0 && body_pos == size()) {
2228                 os << "]~";
2229                 return_value = false;
2230         }
2231
2232         if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2233             && runparams.encoding != prev_encoding) {
2234                 runparams.encoding = prev_encoding;
2235                 if (!bparams.useXetex)
2236                         os << setEncoding(prev_encoding->iconvName());
2237         }
2238
2239         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2240         return return_value;
2241 }
2242
2243
2244 bool Paragraph::emptyTag() const
2245 {
2246         for (pos_type i = 0; i < size(); ++i) {
2247                 if (Inset const * inset = getInset(i)) {
2248                         InsetCode lyx_code = inset->lyxCode();
2249                         // FIXME testing like that is wrong. What is
2250                         // the intent?
2251                         if (lyx_code != TOC_CODE &&
2252                             lyx_code != INCLUDE_CODE &&
2253                             lyx_code != GRAPHICS_CODE &&
2254                             lyx_code != ERT_CODE &&
2255                             lyx_code != LISTINGS_CODE &&
2256                             lyx_code != FLOAT_CODE &&
2257                             lyx_code != TABULAR_CODE) {
2258                                 return false;
2259                         }
2260                 } else {
2261                         char_type c = d->text_[i];
2262                         if (c != ' ' && c != '\t')
2263                                 return false;
2264                 }
2265         }
2266         return true;
2267 }
2268
2269
2270 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2271         const
2272 {
2273         for (pos_type i = 0; i < size(); ++i) {
2274                 if (Inset const * inset = getInset(i)) {
2275                         InsetCode lyx_code = inset->lyxCode();
2276                         if (lyx_code == LABEL_CODE) {
2277                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2278                                 docstring const & id = il->getParam("name");
2279                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2280                         }
2281                 }
2282         }
2283         return string();
2284 }
2285
2286
2287 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2288         const
2289 {
2290         pos_type i;
2291         for (i = 0; i < size(); ++i) {
2292                 if (Inset const * inset = getInset(i)) {
2293                         inset->docbook(os, runparams);
2294                 } else {
2295                         char_type c = d->text_[i];
2296                         if (c == ' ')
2297                                 break;
2298                         os << sgml::escapeChar(c);
2299                 }
2300         }
2301         return i;
2302 }
2303
2304
2305 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2306         const
2307 {
2308         pos_type i;
2309         for (i = 0; i < size(); ++i) {
2310                 if (Inset const * inset = getInset(i)) {
2311                         inset->xhtml(xs, runparams);
2312                 } else {
2313                         char_type c = d->text_[i];
2314                         if (c == ' ')
2315                                 break;
2316                         xs << html::escapeChar(c);
2317                 }
2318         }
2319         return i;
2320 }
2321
2322
2323 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2324 {
2325         Font font_old;
2326         pos_type size = text_.size();
2327         for (pos_type i = initial; i < size; ++i) {
2328                 Font font = owner_->getFont(buf.params(), i, outerfont);
2329                 if (text_[i] == META_INSET)
2330                         return false;
2331                 if (i != initial && font != font_old)
2332                         return false;
2333                 font_old = font;
2334         }
2335
2336         return true;
2337 }
2338
2339
2340 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2341                                     odocstream & os,
2342                                     OutputParams const & runparams,
2343                                     Font const & outerfont,
2344                                     pos_type initial) const
2345 {
2346         bool emph_flag = false;
2347
2348         Layout const & style = *d->layout_;
2349         FontInfo font_old =
2350                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2351
2352         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2353                 os << "]]>";
2354
2355         // parsing main loop
2356         for (pos_type i = initial; i < size(); ++i) {
2357                 Font font = getFont(buf.params(), i, outerfont);
2358
2359                 // handle <emphasis> tag
2360                 if (font_old.emph() != font.fontInfo().emph()) {
2361                         if (font.fontInfo().emph() == FONT_ON) {
2362                                 os << "<emphasis>";
2363                                 emph_flag = true;
2364                         } else if (i != initial) {
2365                                 os << "</emphasis>";
2366                                 emph_flag = false;
2367                         }
2368                 }
2369
2370                 if (Inset const * inset = getInset(i)) {
2371                         inset->docbook(os, runparams);
2372                 } else {
2373                         char_type c = d->text_[i];
2374
2375                         if (style.pass_thru)
2376                                 os.put(c);
2377                         else
2378                                 os << sgml::escapeChar(c);
2379                 }
2380                 font_old = font.fontInfo();
2381         }
2382
2383         if (emph_flag) {
2384                 os << "</emphasis>";
2385         }
2386
2387         if (style.free_spacing)
2388                 os << '\n';
2389         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2390                 os << "<![CDATA[";
2391 }
2392
2393
2394 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2395                                     XHTMLStream & xs,
2396                                     OutputParams const & runparams,
2397                                     Font const & outerfont,
2398                                     pos_type initial) const
2399 {
2400         docstring retval;
2401
2402         bool emph_flag = false;
2403         bool bold_flag = false;
2404         std::string closing_tag;
2405
2406         Layout const & style = *d->layout_;
2407         FontInfo font_old =
2408                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2409
2410         // parsing main loop
2411         for (pos_type i = initial; i < size(); ++i) {
2412                 Font font = getFont(buf.params(), i, outerfont);
2413
2414                 // emphasis
2415                 if (font_old.emph() != font.fontInfo().emph()) {
2416                         if (font.fontInfo().emph() == FONT_ON) {
2417                                 xs << StartTag("em");
2418                                 emph_flag = true;
2419                         } else if (emph_flag && i != initial) {
2420                                 xs << EndTag("em");
2421                                 emph_flag = false;
2422                         }
2423                 }
2424                 // bold
2425                 if (font_old.series() != font.fontInfo().series()) {
2426                         if (font.fontInfo().series() == BOLD_SERIES) {
2427                                 xs << StartTag("strong");
2428                                 bold_flag = true;
2429                         } else if (bold_flag && i != initial) {
2430                                 xs << EndTag("strong");
2431                                 bold_flag = false;
2432                         }
2433                 }
2434                 // FIXME XHTML
2435                 // Other such tags? What about the other text ranges?
2436
2437                 Inset const * inset = getInset(i);
2438                 if (inset) {
2439                         InsetLayout const & il = inset->getLayout();
2440                         OutputParams np = runparams;
2441                         if (!il.htmlisblock())
2442                                 np.html_in_par = true;
2443                         retval += inset->xhtml(xs, np);
2444                 } else {
2445                         char_type c = d->text_[i];
2446
2447                         if (style.pass_thru)
2448                                 xs << c;
2449                         else if (c == '-') {
2450                                 docstring str;
2451                                 int j = i + 1;
2452                                 if (j < size() && d->text_[j] == '-') {
2453                                         j += 1;
2454                                         if (j < size() && d->text_[j] == '-') {
2455                                                 str += from_ascii("&mdash;");
2456                                                 i += 2;
2457                                         } else {
2458                                                 str += from_ascii("&ndash;");
2459                                                 i += 1;
2460                                         }
2461                                 }
2462                                 else
2463                                         str += c;
2464                                 // We don't want to escape the entities. Note that
2465                                 // it is safe to do this, since str can otherwise
2466                                 // only be "-". E.g., it can't be "<".
2467                                 xs << XHTMLStream::NextRaw() << str;
2468                         } else
2469                                 xs << c;
2470                 }
2471                 font_old = font.fontInfo();
2472         }
2473
2474         xs.closeFontTags();
2475         return retval;
2476 }
2477
2478
2479 bool Paragraph::isHfill(pos_type pos) const
2480 {
2481         Inset const * inset = getInset(pos);
2482         return inset && (inset->lyxCode() == SPACE_CODE &&
2483                          inset->isStretchableSpace());
2484 }
2485
2486
2487 bool Paragraph::isNewline(pos_type pos) const
2488 {
2489         Inset const * inset = getInset(pos);
2490         return inset && inset->lyxCode() == NEWLINE_CODE;
2491 }
2492
2493
2494 bool Paragraph::isLineSeparator(pos_type pos) const
2495 {
2496         char_type const c = d->text_[pos];
2497         if (isLineSeparatorChar(c))
2498                 return true;
2499         Inset const * inset = getInset(pos);
2500         return inset && inset->isLineSeparator();
2501 }
2502
2503
2504 bool Paragraph::isWordSeparator(pos_type pos) const
2505 {
2506         if (Inset const * inset = getInset(pos))
2507                 return !inset->isLetter();
2508         char_type const c = d->text_[pos];
2509         // We want to pass the ' and escape chars to the spellchecker
2510         static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2511         return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2512                 || pos == size();
2513 }
2514
2515
2516 bool Paragraph::isChar(pos_type pos) const
2517 {
2518         if (Inset const * inset = getInset(pos))
2519                 return inset->isChar();
2520         char_type const c = d->text_[pos];
2521         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2522 }
2523
2524
2525 bool Paragraph::isSpace(pos_type pos) const
2526 {
2527         if (Inset const * inset = getInset(pos))
2528                 return inset->isSpace();
2529         char_type const c = d->text_[pos];
2530         return lyx::isSpace(c);
2531 }
2532
2533
2534 Language const *
2535 Paragraph::getParLanguage(BufferParams const & bparams) const
2536 {
2537         if (!empty())
2538                 return getFirstFontSettings(bparams).language();
2539         // FIXME: we should check the prev par as well (Lgb)
2540         return bparams.language;
2541 }
2542
2543
2544 bool Paragraph::isRTL(BufferParams const & bparams) const
2545 {
2546         return lyxrc.rtl_support
2547                 && getParLanguage(bparams)->rightToLeft()
2548                 && !inInset().getLayout().forceLTR();
2549 }
2550
2551
2552 void Paragraph::changeLanguage(BufferParams const & bparams,
2553                                Language const * from, Language const * to)
2554 {
2555         // change language including dummy font change at the end
2556         for (pos_type i = 0; i <= size(); ++i) {
2557                 Font font = getFontSettings(bparams, i);
2558                 if (font.language() == from) {
2559                         font.setLanguage(to);
2560                         setFont(i, font);
2561                 }
2562         }
2563 }
2564
2565
2566 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2567 {
2568         Language const * doc_language = bparams.language;
2569         FontList::const_iterator cit = d->fontlist_.begin();
2570         FontList::const_iterator end = d->fontlist_.end();
2571
2572         for (; cit != end; ++cit)
2573                 if (cit->font().language() != ignore_language &&
2574                     cit->font().language() != latex_language &&
2575                     cit->font().language() != doc_language)
2576                         return true;
2577         return false;
2578 }
2579
2580
2581 docstring Paragraph::asString(int options) const
2582 {
2583         return asString(0, size(), options);
2584 }
2585
2586
2587 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2588 {
2589         odocstringstream os;
2590
2591         if (beg == 0 
2592                 && options & AS_STR_LABEL
2593                 && !d->params_.labelString().empty())
2594                 os << d->params_.labelString() << ' ';
2595
2596         for (pos_type i = beg; i < end; ++i) {
2597                 char_type const c = d->text_[i];
2598                 if (isPrintable(c) || c == '\t'
2599                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2600                         os.put(c);
2601                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2602                         getInset(i)->tocString(os);
2603                         if (getInset(i)->asInsetMath())
2604                                 os << " ";
2605                 }
2606         }
2607
2608         return os.str();
2609 }
2610
2611
2612 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2613 {
2614         odocstringstream os;
2615
2616         if (beg == 0 
2617                 && options & AS_STR_LABEL
2618                 && !d->params_.labelString().empty())
2619                 os << d->params_.labelString() << ' ';
2620
2621         for (pos_type i = beg; i < end; ++i) {
2622                 char_type const c = d->text_[i];
2623                 if (isPrintable(c) || c == '\t'
2624                     || (c == '\n' && (options & AS_STR_NEWLINES)))
2625                         os.put(c);
2626                 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2627                         getInset(i)->plaintext(os, runparams);
2628                 }
2629         }
2630
2631         return os.str();
2632 }
2633
2634
2635 void Paragraph::setInsetOwner(Inset const * inset)
2636 {
2637         d->inset_owner_ = inset;
2638 }
2639
2640
2641 int Paragraph::id() const
2642 {
2643         return d->id_;
2644 }
2645
2646
2647 Layout const & Paragraph::layout() const
2648 {
2649         return *d->layout_;
2650 }
2651
2652
2653 void Paragraph::setLayout(Layout const & layout)
2654 {
2655         d->layout_ = &layout;
2656 }
2657
2658
2659 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2660
2661         setLayout(tc.defaultLayout()); 
2662 }
2663
2664
2665 void Paragraph::setPlainLayout(DocumentClass const & tc)
2666
2667         setLayout(tc.plainLayout()); 
2668 }
2669
2670
2671 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2672 {
2673         if (usePlainLayout())
2674                 setPlainLayout(tclass);
2675         else
2676                 setDefaultLayout(tclass);
2677 }
2678
2679
2680 Inset const & Paragraph::inInset() const
2681 {
2682         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2683                 _("Memory problem"), _("Paragraph not properly initialized")));
2684         return *d->inset_owner_;
2685 }
2686
2687
2688 ParagraphParameters & Paragraph::params()
2689 {
2690         return d->params_;
2691 }
2692
2693
2694 ParagraphParameters const & Paragraph::params() const
2695 {
2696         return d->params_;
2697 }
2698
2699
2700 bool Paragraph::isFreeSpacing() const
2701 {
2702         if (d->layout_->free_spacing)
2703                 return true;
2704         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2705 }
2706
2707
2708 bool Paragraph::allowEmpty() const
2709 {
2710         if (d->layout_->keepempty)
2711                 return true;
2712         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2713 }
2714
2715
2716 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2717 {
2718         if (!Encodings::isArabicChar(c))
2719                 return c;
2720
2721         char_type prev_char = ' ';
2722         char_type next_char = ' ';
2723
2724         for (pos_type i = pos - 1; i >= 0; --i) {
2725                 char_type const par_char = d->text_[i];
2726                 if (!Encodings::isArabicComposeChar(par_char)) {
2727                         prev_char = par_char;
2728                         break;
2729                 }
2730         }
2731
2732         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2733                 char_type const par_char = d->text_[i];
2734                 if (!Encodings::isArabicComposeChar(par_char)) {
2735                         next_char = par_char;
2736                         break;
2737                 }
2738         }
2739
2740         if (Encodings::isArabicChar(next_char)) {
2741                 if (Encodings::isArabicChar(prev_char) &&
2742                         !Encodings::isArabicSpecialChar(prev_char))
2743                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2744                 else
2745                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2746         } else {
2747                 if (Encodings::isArabicChar(prev_char) &&
2748                         !Encodings::isArabicSpecialChar(prev_char))
2749                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2750                 else
2751                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2752         }
2753 }
2754
2755
2756 int Paragraph::checkBiblio(Buffer const & buffer)
2757 {
2758         // FIXME From JS:
2759         // This is getting more and more a mess. ...We really should clean
2760         // up this bibitem issue for 1.6. See also bug 2743.
2761
2762         // Add bibitem insets if necessary
2763         if (d->layout_->labeltype != LABEL_BIBLIO)
2764                 return 0;
2765
2766         bool hasbibitem = !d->insetlist_.empty()
2767                 // Insist on it being in pos 0
2768                 && d->text_[0] == META_INSET
2769                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2770
2771         bool track_changes = buffer.params().trackChanges;
2772
2773         docstring oldkey;
2774         docstring oldlabel;
2775
2776         // remove a bibitem in pos != 0
2777         // restore it later in pos 0 if necessary
2778         // (e.g. if a user inserts contents _before_ the item)
2779         // we're assuming there's only one of these, which there
2780         // should be.
2781         int erasedInsetPosition = -1;
2782         InsetList::iterator it = d->insetlist_.begin();
2783         InsetList::iterator end = d->insetlist_.end();
2784         for (; it != end; ++it)
2785                 if (it->inset->lyxCode() == BIBITEM_CODE
2786                     && it->pos > 0) {
2787                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2788                         oldkey = olditem->getParam("key");
2789                         oldlabel = olditem->getParam("label");
2790                         erasedInsetPosition = it->pos;
2791                         eraseChar(erasedInsetPosition, track_changes);
2792                         break;
2793         }
2794
2795         // There was an InsetBibitem at the beginning, and we didn't
2796         // have to erase one.
2797         if (hasbibitem && erasedInsetPosition < 0)
2798                         return 0;
2799
2800         // There was an InsetBibitem at the beginning and we did have to
2801         // erase one. So we give its properties to the beginning inset.
2802         if (hasbibitem) {
2803                 InsetBibitem * inset =
2804                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2805                 if (!oldkey.empty())
2806                         inset->setParam("key", oldkey);
2807                 inset->setParam("label", oldlabel);
2808                 return -erasedInsetPosition;
2809         }
2810
2811         // There was no inset at the beginning, so we need to create one with
2812         // the key and label of the one we erased.
2813         InsetBibitem * inset = 
2814                 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
2815         // restore values of previously deleted item in this par.
2816         if (!oldkey.empty())
2817                 inset->setParam("key", oldkey);
2818         inset->setParam("label", oldlabel);
2819         insertInset(0, static_cast<Inset *>(inset),
2820                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2821
2822         return 1;
2823 }
2824
2825
2826 void Paragraph::checkAuthors(AuthorList const & authorList)
2827 {
2828         d->changes_.checkAuthors(authorList);
2829 }
2830
2831
2832 bool Paragraph::isChanged(pos_type pos) const
2833 {
2834         return lookupChange(pos).changed();
2835 }
2836
2837
2838 bool Paragraph::isInserted(pos_type pos) const
2839 {
2840         return lookupChange(pos).inserted();
2841 }
2842
2843
2844 bool Paragraph::isDeleted(pos_type pos) const
2845 {
2846         return lookupChange(pos).deleted();
2847 }
2848
2849
2850 InsetList const & Paragraph::insetList() const
2851 {
2852         return d->insetlist_;
2853 }
2854
2855
2856 void Paragraph::setBuffer(Buffer & b)
2857 {
2858         d->insetlist_.setBuffer(b);
2859 }
2860
2861
2862 Inset * Paragraph::releaseInset(pos_type pos)
2863 {
2864         Inset * inset = d->insetlist_.release(pos);
2865         /// does not honour change tracking!
2866         eraseChar(pos, false);
2867         return inset;
2868 }
2869
2870
2871 Inset * Paragraph::getInset(pos_type pos)
2872 {
2873         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2874                  ? d->insetlist_.get(pos) : 0;
2875 }
2876
2877
2878 Inset const * Paragraph::getInset(pos_type pos) const
2879 {
2880         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2881                  ? d->insetlist_.get(pos) : 0;
2882 }
2883
2884
2885 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2886                 pos_type & right, TextCase action)
2887 {
2888         // process sequences of modified characters; in change
2889         // tracking mode, this approach results in much better
2890         // usability than changing case on a char-by-char basis
2891         docstring changes;
2892
2893         bool const trackChanges = bparams.trackChanges;
2894
2895         bool capitalize = true;
2896
2897         for (; pos < right; ++pos) {
2898                 char_type oldChar = d->text_[pos];
2899                 char_type newChar = oldChar;
2900
2901                 // ignore insets and don't play with deleted text!
2902                 if (oldChar != META_INSET && !isDeleted(pos)) {
2903                         switch (action) {
2904                                 case text_lowercase:
2905                                         newChar = lowercase(oldChar);
2906                                         break;
2907                                 case text_capitalization:
2908                                         if (capitalize) {
2909                                                 newChar = uppercase(oldChar);
2910                                                 capitalize = false;
2911                                         }
2912                                         break;
2913                                 case text_uppercase:
2914                                         newChar = uppercase(oldChar);
2915                                         break;
2916                         }
2917                 }
2918
2919                 if (isWordSeparator(pos) || isDeleted(pos)) {
2920                         // permit capitalization again
2921                         capitalize = true;
2922                 }
2923
2924                 if (oldChar != newChar) {
2925                         changes += newChar;
2926                         if (pos != right - 1)
2927                                 continue;
2928                         // step behind the changing area
2929                         pos++;
2930                 }
2931
2932                 int erasePos = pos - changes.size();
2933                 for (size_t i = 0; i < changes.size(); i++) {
2934                         insertChar(pos, changes[i],
2935                                    getFontSettings(bparams,
2936                                                    erasePos),
2937                                    trackChanges);
2938                         if (!eraseChar(erasePos, trackChanges)) {
2939                                 ++erasePos;
2940                                 ++pos; // advance
2941                                 ++right; // expand selection
2942                         }
2943                 }
2944                 changes.clear();
2945         }
2946 }
2947
2948
2949 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2950                 pos_type pos, bool del) const
2951 {
2952         int const strsize = str.length();
2953         int i = 0;
2954         pos_type const parsize = d->text_.size();
2955         for (i = 0; pos + i < parsize; ++i) {
2956                 if (i >= strsize)
2957                         break;
2958                 if (cs && str[i] != d->text_[pos + i])
2959                         break;
2960                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2961                         break;
2962                 if (!del && isDeleted(pos + i))
2963                         break;
2964         }
2965
2966         if (i != strsize)
2967                 return false;
2968
2969         // if necessary, check whether string matches word
2970         if (mw) {
2971                 if (pos > 0 && !isWordSeparator(pos - 1))
2972                         return false;
2973                 if (pos + strsize < parsize
2974                         && !isWordSeparator(pos + strsize))
2975                         return false;
2976         }
2977
2978         return true;
2979 }
2980
2981
2982 char_type Paragraph::getChar(pos_type pos) const
2983 {
2984         return d->text_[pos];
2985 }
2986
2987
2988 pos_type Paragraph::size() const
2989 {
2990         return d->text_.size();
2991 }
2992
2993
2994 bool Paragraph::empty() const
2995 {
2996         return d->text_.empty();
2997 }
2998
2999
3000 bool Paragraph::isInset(pos_type pos) const
3001 {
3002         return d->text_[pos] == META_INSET;
3003 }
3004
3005
3006 bool Paragraph::isSeparator(pos_type pos) const
3007 {
3008         //FIXME: Are we sure this can be the only separator?
3009         return d->text_[pos] == ' ';
3010 }
3011
3012
3013 void Paragraph::deregisterWords()
3014 {
3015         Private::Words::const_iterator it;
3016         WordList & wl = theWordList();
3017         for (it = d->words_.begin(); it != d->words_.end(); ++it)
3018                 wl.remove(*it);
3019         d->words_.clear();
3020 }
3021
3022
3023 void Paragraph::locateWord(pos_type & from, pos_type & to,
3024         word_location const loc) const
3025 {
3026         switch (loc) {
3027         case WHOLE_WORD_STRICT:
3028                 if (from == 0 || from == size()
3029                     || isWordSeparator(from)
3030                     || isWordSeparator(from - 1)) {
3031                         to = from;
3032                         return;
3033                 }
3034                 // no break here, we go to the next
3035
3036         case WHOLE_WORD:
3037                 // If we are already at the beginning of a word, do nothing
3038                 if (!from || isWordSeparator(from - 1))
3039                         break;
3040                 // no break here, we go to the next
3041
3042         case PREVIOUS_WORD:
3043                 // always move the cursor to the beginning of previous word
3044                 while (from && !isWordSeparator(from - 1))
3045                         --from;
3046                 break;
3047         case NEXT_WORD:
3048                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3049                 break;
3050         case PARTIAL_WORD:
3051                 // no need to move the 'from' cursor
3052                 break;
3053         }
3054         to = from;
3055         while (to < size() && !isWordSeparator(to))
3056                 ++to;
3057 }
3058
3059
3060 void Paragraph::collectWords()
3061 {
3062         pos_type n = size();
3063         for (pos_type pos = 0; pos < n; ++pos) {
3064                 if (isWordSeparator(pos))
3065                         continue;
3066                 pos_type from = pos;
3067                 locateWord(from, pos, WHOLE_WORD);
3068                 if (pos - from >= 6) {
3069                         docstring word = asString(from, pos, AS_STR_NONE);
3070                         d->words_.insert(word);
3071                 }
3072         }
3073 }
3074
3075
3076 void Paragraph::registerWords()
3077 {
3078         Private::Words::const_iterator it;
3079         WordList & wl = theWordList();
3080         for (it = d->words_.begin(); it != d->words_.end(); ++it)
3081                 wl.insert(*it);
3082 }
3083
3084
3085 void Paragraph::updateWords()
3086 {
3087         deregisterWords();
3088         collectWords();
3089         registerWords();
3090 }
3091
3092
3093 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3094         docstring_list & suggestions, bool do_suggestion) const
3095 {
3096         SpellChecker * speller = theSpellChecker();
3097         if (!speller)
3098                 return false;
3099
3100         locateWord(from, to, WHOLE_WORD);
3101         if (from == to || from >= pos_type(d->text_.size()))
3102                 return false;
3103
3104         docstring word = asString(from, to, AS_STR_INSETS);
3105         string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3106                 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3107                 : lyxrc.spellchecker_alt_lang;
3108         wl = WordLangTuple(word, lang_code);
3109         SpellChecker::Result res = speller->check(wl);
3110         // Just ignore any error that the spellchecker reports.
3111         // FIXME: we should through out an exception and catch it in the GUI to
3112         // display the error.
3113         if (!speller->error().empty())
3114                 return false;
3115
3116         bool const misspelled = res != SpellChecker::OK
3117                 && res != SpellChecker::IGNORED_WORD;
3118
3119         if (lyxrc.spellcheck_continuously)
3120                 d->fontlist_.setMisspelled(from, to, misspelled);
3121
3122         if (misspelled && do_suggestion)
3123                 speller->suggest(wl, suggestions);
3124         else
3125                 suggestions.clear();
3126
3127         return misspelled;
3128 }
3129
3130
3131 bool Paragraph::isMisspelled(pos_type pos) const
3132 {
3133         pos_type from = pos;
3134         pos_type to = pos;
3135         WordLangTuple wl;
3136         docstring_list suggestions;
3137         return spellCheck(from, to, wl, suggestions, false);
3138 }
3139
3140
3141 } // namespace lyx