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