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