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