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