]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
reorder.
[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                 return d->params_.labelWidthString();
1594         else
1595                 return _("Senseless with this layout!");
1596 }
1597
1598
1599 void Paragraph::setLabelWidthString(docstring const & s)
1600 {
1601         d->params_.labelWidthString(s);
1602 }
1603
1604
1605 docstring const Paragraph::translateIfPossible(docstring const & s,
1606                 BufferParams const & bparams) const
1607 {
1608         if (!isAscii(s) || s.empty()) {
1609                 // This must be a user defined layout. We cannot translate
1610                 // this, since gettext accepts only ascii keys.
1611                 return s;
1612         }
1613         // Probably standard layout, try to translate
1614         Messages & m = getMessages(getParLanguage(bparams)->code());
1615         return m.get(to_ascii(s));
1616 }
1617
1618
1619 docstring Paragraph::expandLabel(Layout const & layout,
1620                 BufferParams const & bparams, bool process_appendix) const
1621 {
1622         DocumentClass const & tclass = bparams.documentClass();
1623
1624         docstring fmt;
1625         if (process_appendix && d->params_.appendix())
1626                 fmt = translateIfPossible(layout.labelstring_appendix(),
1627                         bparams);
1628         else
1629                 fmt = translateIfPossible(layout.labelstring(), bparams);
1630
1631         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1632             && !layout.counter.empty())
1633                 return tclass.counters().theCounter(layout.counter);
1634
1635         // handle 'inherited level parts' in 'fmt',
1636         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1637         size_t const i = fmt.find('@', 0);
1638         if (i != docstring::npos) {
1639                 size_t const j = fmt.find('@', i + 1);
1640                 if (j != docstring::npos) {
1641                         docstring parent(fmt, i + 1, j - i - 1);
1642                         docstring label = from_ascii("??");
1643                         if (tclass.hasLayout(parent))
1644                                 docstring label = expandLabel(tclass[parent], bparams,
1645                                                       process_appendix);
1646                         fmt = docstring(fmt, 0, i) + label 
1647                                 + docstring(fmt, j + 1, docstring::npos);
1648                 }
1649         }
1650
1651         return tclass.counters().counterLabel(fmt);
1652 }
1653
1654
1655 void Paragraph::applyLayout(Layout const & new_layout)
1656 {
1657         d->layout_ = &new_layout;
1658         LyXAlignment const oldAlign = d->params_.align();
1659         
1660         if (!(oldAlign & d->layout_->alignpossible)) {
1661                 frontend::Alert::warning(_("Alignment not permitted"), 
1662                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1663                 d->params_.align(LYX_ALIGN_LAYOUT);
1664         }
1665 }
1666
1667
1668 pos_type Paragraph::beginOfBody() const
1669 {
1670         return d->begin_of_body_;
1671 }
1672
1673
1674 void Paragraph::setBeginOfBody()
1675 {
1676         if (d->layout_->labeltype != LABEL_MANUAL) {
1677                 d->begin_of_body_ = 0;
1678                 return;
1679         }
1680
1681         // Unroll the first two cycles of the loop
1682         // and remember the previous character to
1683         // remove unnecessary getChar() calls
1684         pos_type i = 0;
1685         pos_type end = size();
1686         if (i < end && !isNewline(i)) {
1687                 ++i;
1688                 char_type previous_char = 0;
1689                 char_type temp = 0;
1690                 if (i < end) {
1691                         previous_char = d->text_[i];
1692                         if (!isNewline(i)) {
1693                                 ++i;
1694                                 while (i < end && previous_char != ' ') {
1695                                         temp = d->text_[i];
1696                                         if (isNewline(i))
1697                                                 break;
1698                                         ++i;
1699                                         previous_char = temp;
1700                                 }
1701                         }
1702                 }
1703         }
1704
1705         d->begin_of_body_ = i;
1706 }
1707
1708
1709 bool Paragraph::forcePlainLayout() const
1710 {
1711         return inInset().forcePlainLayout();
1712 }
1713
1714
1715 bool Paragraph::allowParagraphCustomization() const
1716 {
1717         return inInset().allowParagraphCustomization();
1718 }
1719
1720
1721 bool Paragraph::usePlainLayout() const
1722 {
1723         return inInset().usePlainLayout();
1724 }
1725
1726
1727 namespace {
1728
1729 // paragraphs inside floats need different alignment tags to avoid
1730 // unwanted space
1731
1732 bool noTrivlistCentering(InsetCode code)
1733 {
1734         return code == FLOAT_CODE
1735                || code == WRAP_CODE
1736                || code == CELL_CODE;
1737 }
1738
1739
1740 string correction(string const & orig)
1741 {
1742         if (orig == "flushleft")
1743                 return "raggedright";
1744         if (orig == "flushright")
1745                 return "raggedleft";
1746         if (orig == "center")
1747                 return "centering";
1748         return orig;
1749 }
1750
1751
1752 string const corrected_env(string const & suffix, string const & env,
1753         InsetCode code, bool const lastpar)
1754 {
1755         string output = suffix + "{";
1756         if (noTrivlistCentering(code)) {
1757                 if (lastpar) {
1758                         // the last paragraph in non-trivlist-aligned
1759                         // context is special (to avoid unwanted whitespace)
1760                         if (suffix == "\\begin")
1761                                 return "\\" + correction(env) + "{}";
1762                         return string();
1763                 }
1764                 output += correction(env);
1765         } else
1766                 output += env;
1767         output += "}";
1768         if (suffix == "\\begin")
1769                 output += "\n";
1770         return output;
1771 }
1772
1773
1774 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1775 {
1776         if (!contains(str, "\n"))
1777                 column += str.size();
1778         else {
1779                 string tmp;
1780                 texrow.newline();
1781                 column = rsplit(str, tmp, '\n').size();
1782         }
1783 }
1784
1785 } // namespace anon
1786
1787
1788 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1789                                  odocstream & os, TexRow & texrow,
1790                                  OutputParams const & runparams) const
1791 {
1792         int column = 0;
1793
1794         if (params_.noindent()) {
1795                 os << "\\noindent ";
1796                 column += 10;
1797         }
1798         
1799         LyXAlignment const curAlign = params_.align();
1800
1801         if (curAlign == layout_->align)
1802                 return column;
1803
1804         switch (curAlign) {
1805         case LYX_ALIGN_NONE:
1806         case LYX_ALIGN_BLOCK:
1807         case LYX_ALIGN_LAYOUT:
1808         case LYX_ALIGN_SPECIAL:
1809                 break;
1810         case LYX_ALIGN_LEFT:
1811         case LYX_ALIGN_RIGHT:
1812         case LYX_ALIGN_CENTER:
1813                 if (runparams.moving_arg) {
1814                         os << "\\protect";
1815                         column += 8;
1816                 }
1817                 break;
1818         }
1819
1820         string const begin_tag = "\\begin";
1821         InsetCode code = owner_->ownerCode();
1822         bool const lastpar = runparams.isLastPar;
1823
1824         switch (curAlign) {
1825         case LYX_ALIGN_NONE:
1826         case LYX_ALIGN_BLOCK:
1827         case LYX_ALIGN_LAYOUT:
1828         case LYX_ALIGN_SPECIAL:
1829                 break;
1830         case LYX_ALIGN_LEFT: {
1831                 string output;
1832                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1833                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1834                 else
1835                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1836                 os << from_ascii(output);
1837                 adjust_row_column(output, texrow, column);
1838                 break;
1839         } case LYX_ALIGN_RIGHT: {
1840                 string output;
1841                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1842                         output = corrected_env(begin_tag, "flushright", code, lastpar);
1843                 else
1844                         output = corrected_env(begin_tag, "flushleft", code, lastpar);
1845                 os << from_ascii(output);
1846                 adjust_row_column(output, texrow, column);
1847                 break;
1848         } case LYX_ALIGN_CENTER: {
1849                 string output;
1850                 output = corrected_env(begin_tag, "center", code, lastpar);
1851                 os << from_ascii(output);
1852                 adjust_row_column(output, texrow, column);
1853                 break;
1854         }
1855         }
1856
1857         return column;
1858 }
1859
1860
1861 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1862                                odocstream & os, TexRow & texrow,
1863                                OutputParams const & runparams) const
1864 {
1865         int column = 0;
1866
1867         switch (params_.align()) {
1868         case LYX_ALIGN_NONE:
1869         case LYX_ALIGN_BLOCK:
1870         case LYX_ALIGN_LAYOUT:
1871         case LYX_ALIGN_SPECIAL:
1872                 break;
1873         case LYX_ALIGN_LEFT:
1874         case LYX_ALIGN_RIGHT:
1875         case LYX_ALIGN_CENTER:
1876                 if (runparams.moving_arg) {
1877                         os << "\\protect";
1878                         column = 8;
1879                 }
1880                 break;
1881         }
1882
1883         string const end_tag = "\n\\par\\end";
1884         InsetCode code = owner_->ownerCode();
1885         bool const lastpar = runparams.isLastPar;
1886
1887         switch (params_.align()) {
1888         case LYX_ALIGN_NONE:
1889         case LYX_ALIGN_BLOCK:
1890         case LYX_ALIGN_LAYOUT:
1891         case LYX_ALIGN_SPECIAL:
1892                 break;
1893         case LYX_ALIGN_LEFT: {
1894                 string output;
1895                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1896                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1897                 else
1898                         output = corrected_env(end_tag, "flushright", code, lastpar);
1899                 os << from_ascii(output);
1900                 adjust_row_column(output, texrow, column);
1901                 break;
1902         } case LYX_ALIGN_RIGHT: {
1903                 string output;
1904                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1905                         output = corrected_env(end_tag, "flushright", code, lastpar);
1906                 else
1907                         output = corrected_env(end_tag, "flushleft", code, lastpar);
1908                 os << from_ascii(output);
1909                 adjust_row_column(output, texrow, column);
1910                 break;
1911         } case LYX_ALIGN_CENTER: {
1912                 string output;
1913                 output = corrected_env(end_tag, "center", code, lastpar);
1914                 os << from_ascii(output);
1915                 adjust_row_column(output, texrow, column);
1916                 break;
1917         }
1918         }
1919
1920         return column;
1921 }
1922
1923
1924 // This one spits out the text of the paragraph
1925 bool Paragraph::latex(BufferParams const & bparams,
1926         Font const & outerfont,
1927         odocstream & os, TexRow & texrow,
1928         OutputParams const & runparams,
1929         int start_pos, int end_pos) const
1930 {
1931         LYXERR(Debug::LATEX, "Paragraph::latex...     " << this);
1932
1933         bool return_value = false;
1934
1935         bool const allowcust = allowParagraphCustomization();
1936
1937         // FIXME This check should not be needed. Perhaps issue an
1938         // error if it triggers.
1939         Layout const & style = forcePlainLayout() ?
1940                 bparams.documentClass().plainLayout() : *d->layout_;
1941
1942         // Current base font for all inherited font changes, without any
1943         // change caused by an individual character, except for the language:
1944         // It is set to the language of the first character.
1945         // As long as we are in the label, this font is the base font of the
1946         // label. Before the first body character it is set to the base font
1947         // of the body.
1948         Font basefont;
1949
1950         // Maybe we have to create a optional argument.
1951         pos_type body_pos = beginOfBody();
1952         unsigned int column = 0;
1953
1954         if (body_pos > 0) {
1955                 // the optional argument is kept in curly brackets in
1956                 // case it contains a ']'
1957                 os << "[{";
1958                 column += 2;
1959                 basefont = getLabelFont(bparams, outerfont);
1960         } else {
1961                 basefont = getLayoutFont(bparams, outerfont);
1962         }
1963
1964         // Which font is currently active?
1965         Font running_font(basefont);
1966         // Do we have an open font change?
1967         bool open_font = false;
1968
1969         Change runningChange = Change(Change::UNCHANGED);
1970
1971         texrow.start(id(), 0);
1972
1973         // if the paragraph is empty, the loop will not be entered at all
1974         if (empty()) {
1975                 if (style.isCommand()) {
1976                         os << '{';
1977                         ++column;
1978                 }
1979                 if (allowcust)
1980                         column += d->startTeXParParams(bparams, os, texrow,
1981                                                     runparams);
1982         }
1983
1984         for (pos_type i = 0; i < size(); ++i) {
1985                 // First char in paragraph or after label?
1986                 if (i == body_pos) {
1987                         if (body_pos > 0) {
1988                                 if (open_font) {
1989                                         column += running_font.latexWriteEndChanges(
1990                                                 os, bparams, runparams,
1991                                                 basefont, basefont);
1992                                         open_font = false;
1993                                 }
1994                                 basefont = getLayoutFont(bparams, outerfont);
1995                                 running_font = basefont;
1996
1997                                 column += Changes::latexMarkChange(os, bparams,
1998                                                 runningChange, Change(Change::UNCHANGED));
1999                                 runningChange = Change(Change::UNCHANGED);
2000
2001                                 os << "}] ";
2002                                 column +=3;
2003                         }
2004                         if (style.isCommand()) {
2005                                 os << '{';
2006                                 ++column;
2007                         }
2008
2009                         if (allowcust)
2010                                 column += d->startTeXParParams(bparams, os,
2011                                                             texrow,
2012                                                             runparams);
2013                 }
2014
2015                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2016                                                                  : lookupChange(i);
2017
2018                 if (bparams.outputChanges && runningChange != change) {
2019                         if (open_font) {
2020                                 column += running_font.latexWriteEndChanges(
2021                                                 os, bparams, runparams, basefont, basefont);
2022                                 open_font = false;
2023                         }
2024                         basefont = getLayoutFont(bparams, outerfont);
2025                         running_font = basefont;
2026
2027                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
2028                         runningChange = change;
2029                 }
2030
2031                 // do not output text which is marked deleted
2032                 // if change tracking output is disabled
2033                 if (!bparams.outputChanges && change.type == Change::DELETED) {
2034                         continue;
2035                 }
2036
2037                 ++column;
2038
2039                 // Fully instantiated font
2040                 Font const font = getFont(bparams, i, outerfont);
2041
2042                 Font const last_font = running_font;
2043
2044                 // Do we need to close the previous font?
2045                 if (open_font &&
2046                     (font != running_font ||
2047                      font.language() != running_font.language()))
2048                 {
2049                         column += running_font.latexWriteEndChanges(
2050                                         os, bparams, runparams, basefont,
2051                                         (i == body_pos-1) ? basefont : font);
2052                         running_font = basefont;
2053                         open_font = false;
2054                 }
2055
2056                 // close babel's font environment before opening CJK.
2057                 if (!running_font.language()->babel().empty() &&
2058                     font.language()->encoding()->package() == Encoding::CJK) {
2059                                 string end_tag = subst(lyxrc.language_command_end,
2060                                                         "$$lang",
2061                                                         running_font.language()->babel());
2062                                 os << from_ascii(end_tag);
2063                                 column += end_tag.length();
2064                 }
2065
2066                 // Switch file encoding if necessary (and allowed)
2067                 if (!runparams.verbatim && 
2068                     runparams.encoding->package() != Encoding::none &&
2069                     font.language()->encoding()->package() != Encoding::none) {
2070                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2071                                         runparams, *(font.language()->encoding()));
2072                         if (enc_switch.first) {
2073                                 column += enc_switch.second;
2074                                 runparams.encoding = font.language()->encoding();
2075                         }
2076                 }
2077
2078                 char_type const c = d->text_[i];
2079
2080                 // Do we need to change font?
2081                 if ((font != running_font ||
2082                      font.language() != running_font.language()) &&
2083                         i != body_pos - 1)
2084                 {
2085                         odocstringstream ods;
2086                         column += font.latexWriteStartChanges(ods, bparams,
2087                                                               runparams, basefont,
2088                                                               last_font);
2089                         running_font = font;
2090                         open_font = true;
2091                         docstring fontchange = ods.str();
2092                         // check if the fontchange ends with a trailing blank
2093                         // (like "\small " (see bug 3382)
2094                         if (suffixIs(fontchange, ' ') && c == ' ')
2095                                 os << fontchange.substr(0, fontchange.size() - 1) 
2096                                    << from_ascii("{}");
2097                         else
2098                                 os << fontchange;
2099                 }
2100
2101                 // FIXME: think about end_pos implementation...
2102                 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2103                         // FIXME: integrate this case in latexSpecialChar
2104                         // Do not print the separation of the optional argument
2105                         // if style.pass_thru is false. This works because
2106                         // latexSpecialChar ignores spaces if
2107                         // style.pass_thru is false.
2108                         if (i != body_pos - 1) {
2109                                 if (d->simpleTeXBlanks(
2110                                                 runparams, os, texrow,
2111                                                 i, column, font, style)) {
2112                                         // A surrogate pair was output. We
2113                                         // must not call latexSpecialChar
2114                                         // in this iteration, since it would output
2115                                         // the combining character again.
2116                                         ++i;
2117                                         continue;
2118                                 }
2119                         }
2120                 }
2121
2122                 OutputParams rp = runparams;
2123                 rp.free_spacing = style.free_spacing;
2124                 rp.local_font = &font;
2125                 rp.intitle = style.intitle;
2126
2127                 // Two major modes:  LaTeX or plain
2128                 // Handle here those cases common to both modes
2129                 // and then split to handle the two modes separately.
2130                 if (c == META_INSET) {
2131                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2132                                 d->latexInset(bparams, os,
2133                                                 texrow, rp, running_font,
2134                                                 basefont, outerfont, open_font,
2135                                                 runningChange, style, i, column);
2136                         }
2137                 } else {
2138                         if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2139                                 try {
2140                                         d->latexSpecialChar(os, rp, running_font, runningChange,
2141                                                 style, i, column);
2142                                 } catch (EncodingException & e) {
2143                                 if (runparams.dryrun) {
2144                                         os << "<" << _("LyX Warning: ")
2145                                            << _("uncodable character") << " '";
2146                                         os.put(c);
2147                                         os << "'>";
2148                                 } else {
2149                                         // add location information and throw again.
2150                                         e.par_id = id();
2151                                         e.pos = i;
2152                                         throw(e);
2153                                 }
2154                         }
2155                 }
2156                 }
2157
2158                 // Set the encoding to that returned from latexSpecialChar (see
2159                 // comment for encoding member in OutputParams.h)
2160                 runparams.encoding = rp.encoding;
2161         }
2162
2163         // If we have an open font definition, we have to close it
2164         if (open_font) {
2165 #ifdef FIXED_LANGUAGE_END_DETECTION
2166                 if (next_) {
2167                         running_font
2168                                 .latexWriteEndChanges(os, bparams, runparams,
2169                                         basefont,
2170                                         next_->getFont(bparams, 0, outerfont));
2171                 } else {
2172                         running_font.latexWriteEndChanges(os, bparams,
2173                                         runparams, basefont, basefont);
2174                 }
2175 #else
2176 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2177 //FIXME: there as we start another \selectlanguage with the next paragraph if
2178 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2179                 running_font.latexWriteEndChanges(os, bparams, runparams,
2180                                 basefont, basefont);
2181 #endif
2182         }
2183
2184         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2185
2186         // Needed if there is an optional argument but no contents.
2187         if (body_pos > 0 && body_pos == size()) {
2188                 os << "}]~";
2189                 return_value = false;
2190         }
2191
2192         if (allowcust) {
2193                 column += d->endTeXParParams(bparams, os, texrow,
2194                                           runparams);
2195         }
2196
2197         LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2198         return return_value;
2199 }
2200
2201
2202 bool Paragraph::emptyTag() const
2203 {
2204         for (pos_type i = 0; i < size(); ++i) {
2205                 if (Inset const * inset = getInset(i)) {
2206                         InsetCode lyx_code = inset->lyxCode();
2207                         if (lyx_code != TOC_CODE &&
2208                             lyx_code != INCLUDE_CODE &&
2209                             lyx_code != GRAPHICS_CODE &&
2210                             lyx_code != ERT_CODE &&
2211                             lyx_code != LISTINGS_CODE &&
2212                             lyx_code != FLOAT_CODE &&
2213                             lyx_code != TABULAR_CODE) {
2214                                 return false;
2215                         }
2216                 } else {
2217                         char_type c = d->text_[i];
2218                         if (c != ' ' && c != '\t')
2219                                 return false;
2220                 }
2221         }
2222         return true;
2223 }
2224
2225
2226 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2227         const
2228 {
2229         for (pos_type i = 0; i < size(); ++i) {
2230                 if (Inset const * inset = getInset(i)) {
2231                         InsetCode lyx_code = inset->lyxCode();
2232                         if (lyx_code == LABEL_CODE) {
2233                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2234                                 docstring const & id = il->getParam("name");
2235                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2236                         }
2237                 }
2238         }
2239         return string();
2240 }
2241
2242
2243 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2244         const
2245 {
2246         pos_type i;
2247         for (i = 0; i < size(); ++i) {
2248                 if (Inset const * inset = getInset(i)) {
2249                         inset->docbook(os, runparams);
2250                 } else {
2251                         char_type c = d->text_[i];
2252                         if (c == ' ')
2253                                 break;
2254                         os << sgml::escapeChar(c);
2255                 }
2256         }
2257         return i;
2258 }
2259
2260
2261 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2262 {
2263         Font font_old;
2264         pos_type size = text_.size();
2265         for (pos_type i = initial; i < size; ++i) {
2266                 Font font = owner_->getFont(buf.params(), i, outerfont);
2267                 if (text_[i] == META_INSET)
2268                         return false;
2269                 if (i != initial && font != font_old)
2270                         return false;
2271                 font_old = font;
2272         }
2273
2274         return true;
2275 }
2276
2277
2278 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2279                                     odocstream & os,
2280                                     OutputParams const & runparams,
2281                                     Font const & outerfont,
2282                                     pos_type initial) const
2283 {
2284         bool emph_flag = false;
2285
2286         Layout const & style = *d->layout_;
2287         FontInfo font_old =
2288                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2289
2290         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2291                 os << "]]>";
2292
2293         // parsing main loop
2294         for (pos_type i = initial; i < size(); ++i) {
2295                 Font font = getFont(buf.params(), i, outerfont);
2296
2297                 // handle <emphasis> tag
2298                 if (font_old.emph() != font.fontInfo().emph()) {
2299                         if (font.fontInfo().emph() == FONT_ON) {
2300                                 os << "<emphasis>";
2301                                 emph_flag = true;
2302                         } else if (i != initial) {
2303                                 os << "</emphasis>";
2304                                 emph_flag = false;
2305                         }
2306                 }
2307
2308                 if (Inset const * inset = getInset(i)) {
2309                         inset->docbook(os, runparams);
2310                 } else {
2311                         char_type c = d->text_[i];
2312
2313                         if (style.pass_thru)
2314                                 os.put(c);
2315                         else
2316                                 os << sgml::escapeChar(c);
2317                 }
2318                 font_old = font.fontInfo();
2319         }
2320
2321         if (emph_flag) {
2322                 os << "</emphasis>";
2323         }
2324
2325         if (style.free_spacing)
2326                 os << '\n';
2327         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2328                 os << "<![CDATA[";
2329 }
2330
2331
2332 bool Paragraph::isHfill(pos_type pos) const
2333 {
2334         Inset const * inset = getInset(pos);
2335         return inset && (inset->lyxCode() == SPACE_CODE &&
2336                          inset->isStretchableSpace());
2337 }
2338
2339
2340 bool Paragraph::isNewline(pos_type pos) const
2341 {
2342         Inset const * inset = getInset(pos);
2343         return inset && inset->lyxCode() == NEWLINE_CODE;
2344 }
2345
2346
2347 bool Paragraph::isLineSeparator(pos_type pos) const
2348 {
2349         char_type const c = d->text_[pos];
2350         if (isLineSeparatorChar(c))
2351                 return true;
2352         Inset const * inset = getInset(pos);
2353         return inset && inset->isLineSeparator();
2354 }
2355
2356
2357 /// Used by the spellchecker
2358 bool Paragraph::isLetter(pos_type pos) const
2359 {
2360         if (Inset const * inset = getInset(pos))
2361                 return inset->isLetter();
2362         char_type const c = d->text_[pos];
2363     // We want to pass the ' and escape chars to the spellchecker
2364         static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2365         return (isLetterChar(c) || isDigit(c) || contains(quote, c))
2366                 && (!d->inset_owner_ || d->inset_owner_->allowSpellCheck())
2367                 && pos != size()
2368                 && !isDeleted(pos);
2369 }
2370
2371
2372 bool Paragraph::isChar(pos_type pos) const
2373 {
2374         if (Inset const * inset = getInset(pos))
2375                 return inset->isChar();
2376         char_type const c = d->text_[pos];
2377         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2378 }
2379
2380
2381 bool Paragraph::isSpace(pos_type pos) const
2382 {
2383         if (Inset const * inset = getInset(pos))
2384                 return inset->isSpace();
2385         char_type const c = d->text_[pos];
2386         return lyx::isSpace(c);
2387 }
2388
2389
2390 Language const *
2391 Paragraph::getParLanguage(BufferParams const & bparams) const
2392 {
2393         if (!empty())
2394                 return getFirstFontSettings(bparams).language();
2395         // FIXME: we should check the prev par as well (Lgb)
2396         return bparams.language;
2397 }
2398
2399
2400 bool Paragraph::isRTL(BufferParams const & bparams) const
2401 {
2402         return lyxrc.rtl_support
2403                 && getParLanguage(bparams)->rightToLeft()
2404                 && ownerCode() != ERT_CODE
2405                 && ownerCode() != LISTINGS_CODE;
2406 }
2407
2408
2409 void Paragraph::changeLanguage(BufferParams const & bparams,
2410                                Language const * from, Language const * to)
2411 {
2412         // change language including dummy font change at the end
2413         for (pos_type i = 0; i <= size(); ++i) {
2414                 Font font = getFontSettings(bparams, i);
2415                 if (font.language() == from) {
2416                         font.setLanguage(to);
2417                         setFont(i, font);
2418                 }
2419         }
2420 }
2421
2422
2423 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2424 {
2425         Language const * doc_language = bparams.language;
2426         FontList::const_iterator cit = d->fontlist_.begin();
2427         FontList::const_iterator end = d->fontlist_.end();
2428
2429         for (; cit != end; ++cit)
2430                 if (cit->font().language() != ignore_language &&
2431                     cit->font().language() != latex_language &&
2432                     cit->font().language() != doc_language)
2433                         return true;
2434         return false;
2435 }
2436
2437
2438 docstring Paragraph::asString(int options) const
2439 {
2440         return asString(0, size(), options);
2441 }
2442
2443
2444 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2445 {
2446         odocstringstream os;
2447
2448         if (beg == 0 
2449                 && options & AS_STR_LABEL
2450                 && !d->params_.labelString().empty())
2451                 os << d->params_.labelString() << ' ';
2452
2453         for (pos_type i = beg; i < end; ++i) {
2454                 char_type const c = d->text_[i];
2455                 if (isPrintable(c) || c == '\t'
2456                     || (c == '\n' && options & AS_STR_NEWLINES))
2457                         os.put(c);
2458                 else if (c == META_INSET && options & AS_STR_INSETS)
2459                         getInset(i)->tocString(os);
2460         }
2461
2462         return os.str();
2463 }
2464
2465
2466 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2467 {
2468         odocstringstream os;
2469
2470         if (beg == 0 
2471                 && options & AS_STR_LABEL
2472                 && !d->params_.labelString().empty())
2473                 os << d->params_.labelString() << ' ';
2474
2475         for (pos_type i = beg; i < end; ++i) {
2476                 char_type const c = d->text_[i];
2477                 if (isPrintable(c) || c == '\t'
2478                     || (c == '\n' && options & AS_STR_NEWLINES))
2479                         os.put(c);
2480                 else if (c == META_INSET && options & AS_STR_INSETS) {
2481                         getInset(i)->plaintext(os, runparams);
2482                 }
2483         }
2484
2485         return os.str();
2486 }
2487
2488
2489 void Paragraph::setInsetOwner(Inset const * inset)
2490 {
2491         d->inset_owner_ = inset;
2492 }
2493
2494
2495 int Paragraph::id() const
2496 {
2497         return d->id_;
2498 }
2499
2500
2501 Layout const & Paragraph::layout() const
2502 {
2503         return *d->layout_;
2504 }
2505
2506
2507 void Paragraph::setLayout(Layout const & layout)
2508 {
2509         d->layout_ = &layout;
2510 }
2511
2512
2513 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2514
2515         setLayout(tc.defaultLayout()); 
2516 }
2517
2518
2519 void Paragraph::setPlainLayout(DocumentClass const & tc)
2520
2521         setLayout(tc.plainLayout()); 
2522 }
2523
2524
2525 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2526 {
2527         if (usePlainLayout())
2528                 setPlainLayout(tclass);
2529         else
2530                 setDefaultLayout(tclass);
2531 }
2532
2533
2534 Inset const & Paragraph::inInset() const
2535 {
2536         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2537                 _("Memory problem"), _("Paragraph not properly initialized")));
2538         return *d->inset_owner_;
2539 }
2540
2541
2542 InsetCode Paragraph::ownerCode() const
2543 {
2544         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2545 }
2546
2547
2548 ParagraphParameters & Paragraph::params()
2549 {
2550         return d->params_;
2551 }
2552
2553
2554 ParagraphParameters const & Paragraph::params() const
2555 {
2556         return d->params_;
2557 }
2558
2559
2560 bool Paragraph::isFreeSpacing() const
2561 {
2562         if (d->layout_->free_spacing)
2563                 return true;
2564         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2565 }
2566
2567
2568 bool Paragraph::allowEmpty() const
2569 {
2570         if (d->layout_->keepempty)
2571                 return true;
2572         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2573 }
2574
2575
2576 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2577 {
2578         if (!Encodings::isArabicChar(c))
2579                 return c;
2580
2581         char_type prev_char = ' ';
2582         char_type next_char = ' ';
2583
2584         for (pos_type i = pos - 1; i >= 0; --i) {
2585                 char_type const par_char = d->text_[i];
2586                 if (!Encodings::isArabicComposeChar(par_char)) {
2587                         prev_char = par_char;
2588                         break;
2589                 }
2590         }
2591
2592         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2593                 char_type const par_char = d->text_[i];
2594                 if (!Encodings::isArabicComposeChar(par_char)) {
2595                         next_char = par_char;
2596                         break;
2597                 }
2598         }
2599
2600         if (Encodings::isArabicChar(next_char)) {
2601                 if (Encodings::isArabicChar(prev_char) &&
2602                         !Encodings::isArabicSpecialChar(prev_char))
2603                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2604                 else
2605                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2606         } else {
2607                 if (Encodings::isArabicChar(prev_char) &&
2608                         !Encodings::isArabicSpecialChar(prev_char))
2609                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2610                 else
2611                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2612         }
2613 }
2614
2615
2616 int Paragraph::checkBiblio(Buffer const & buffer)
2617 {
2618         // FIXME From JS:
2619         // This is getting more and more a mess. ...We really should clean
2620         // up this bibitem issue for 1.6. See also bug 2743.
2621
2622         // Add bibitem insets if necessary
2623         if (d->layout_->labeltype != LABEL_BIBLIO)
2624                 return 0;
2625
2626         bool hasbibitem = !d->insetlist_.empty()
2627                 // Insist on it being in pos 0
2628                 && d->text_[0] == META_INSET
2629                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2630
2631         bool track_changes = buffer.params().trackChanges;
2632
2633         docstring oldkey;
2634         docstring oldlabel;
2635
2636         // remove a bibitem in pos != 0
2637         // restore it later in pos 0 if necessary
2638         // (e.g. if a user inserts contents _before_ the item)
2639         // we're assuming there's only one of these, which there
2640         // should be.
2641         int erasedInsetPosition = -1;
2642         InsetList::iterator it = d->insetlist_.begin();
2643         InsetList::iterator end = d->insetlist_.end();
2644         for (; it != end; ++it)
2645                 if (it->inset->lyxCode() == BIBITEM_CODE
2646                     && it->pos > 0) {
2647                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2648                         oldkey = olditem->getParam("key");
2649                         oldlabel = olditem->getParam("label");
2650                         erasedInsetPosition = it->pos;
2651                         eraseChar(erasedInsetPosition, track_changes);
2652                         break;
2653         }
2654
2655         // There was an InsetBibitem at the beginning, and we didn't
2656         // have to erase one.
2657         if (hasbibitem && erasedInsetPosition < 0)
2658                         return 0;
2659
2660         // There was an InsetBibitem at the beginning and we did have to
2661         // erase one. So we give its properties to the beginning inset.
2662         if (hasbibitem) {
2663                 InsetBibitem * inset =
2664                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2665                 if (!oldkey.empty())
2666                         inset->setParam("key", oldkey);
2667                 inset->setParam("label", oldlabel);
2668                 return -erasedInsetPosition;
2669         }
2670
2671         // There was no inset at the beginning, so we need to create one with
2672         // the key and label of the one we erased.
2673         InsetBibitem * inset = 
2674                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2675         // restore values of previously deleted item in this par.
2676         if (!oldkey.empty())
2677                 inset->setParam("key", oldkey);
2678         inset->setParam("label", oldlabel);
2679         insertInset(0, static_cast<Inset *>(inset),
2680                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2681
2682         return 1;
2683 }
2684
2685
2686 void Paragraph::checkAuthors(AuthorList const & authorList)
2687 {
2688         d->changes_.checkAuthors(authorList);
2689 }
2690
2691
2692 bool Paragraph::isUnchanged(pos_type pos) const
2693 {
2694         return lookupChange(pos).type == Change::UNCHANGED;
2695 }
2696
2697
2698 bool Paragraph::isInserted(pos_type pos) const
2699 {
2700         return lookupChange(pos).type == Change::INSERTED;
2701 }
2702
2703
2704 bool Paragraph::isDeleted(pos_type pos) const
2705 {
2706         return lookupChange(pos).type == Change::DELETED;
2707 }
2708
2709
2710 InsetList const & Paragraph::insetList() const
2711 {
2712         return d->insetlist_;
2713 }
2714
2715
2716 void Paragraph::setBuffer(Buffer & b)
2717 {
2718         d->insetlist_.setBuffer(b);
2719 }
2720
2721
2722 Inset * Paragraph::releaseInset(pos_type pos)
2723 {
2724         Inset * inset = d->insetlist_.release(pos);
2725         /// does not honour change tracking!
2726         eraseChar(pos, false);
2727         return inset;
2728 }
2729
2730
2731 Inset * Paragraph::getInset(pos_type pos)
2732 {
2733         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2734                  ? d->insetlist_.get(pos) : 0;
2735 }
2736
2737
2738 Inset const * Paragraph::getInset(pos_type pos) const
2739 {
2740         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2741                  ? d->insetlist_.get(pos) : 0;
2742 }
2743
2744
2745 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2746                 pos_type & right, TextCase action)
2747 {
2748         // process sequences of modified characters; in change
2749         // tracking mode, this approach results in much better
2750         // usability than changing case on a char-by-char basis
2751         docstring changes;
2752
2753         bool const trackChanges = bparams.trackChanges;
2754
2755         bool capitalize = true;
2756
2757         for (; pos < right; ++pos) {
2758                 char_type oldChar = d->text_[pos];
2759                 char_type newChar = oldChar;
2760
2761                 // ignore insets and don't play with deleted text!
2762                 if (oldChar != META_INSET && !isDeleted(pos)) {
2763                         switch (action) {
2764                                 case text_lowercase:
2765                                         newChar = lowercase(oldChar);
2766                                         break;
2767                                 case text_capitalization:
2768                                         if (capitalize) {
2769                                                 newChar = uppercase(oldChar);
2770                                                 capitalize = false;
2771                                         }
2772                                         break;
2773                                 case text_uppercase:
2774                                         newChar = uppercase(oldChar);
2775                                         break;
2776                         }
2777                 }
2778
2779                 if (!isLetter(pos) || isDeleted(pos)) {
2780                         // permit capitalization again
2781                         capitalize = true;
2782                 }
2783
2784                 if (oldChar != newChar)
2785                         changes += newChar;
2786
2787                 if (oldChar == newChar || pos == right - 1) {
2788                         if (oldChar != newChar) {
2789                                 // step behind the changing area
2790                                 pos++;
2791                         }
2792                         int erasePos = pos - changes.size();
2793                         for (size_t i = 0; i < changes.size(); i++) {
2794                                 insertChar(pos, changes[i],
2795                                         getFontSettings(bparams,
2796                                         erasePos),
2797                                         trackChanges);
2798                                 if (!eraseChar(erasePos, trackChanges)) {
2799                                         ++erasePos;
2800                                         ++pos; // advance
2801                                         ++right; // expand selection
2802                                 }
2803                         }
2804                         changes.clear();
2805                 }
2806         }
2807 }
2808
2809
2810 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2811                 pos_type pos, bool del) const
2812 {
2813         int const strsize = str.length();
2814         int i = 0;
2815         pos_type const parsize = d->text_.size();
2816         for (i = 0; pos + i < parsize; ++i) {
2817                 if (i >= strsize)
2818                         break;
2819                 if (cs && str[i] != d->text_[pos + i])
2820                         break;
2821                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2822                         break;
2823                 if (!del && isDeleted(pos + i))
2824                         break;
2825         }
2826
2827         if (i != strsize)
2828                 return false;
2829
2830         // if necessary, check whether string matches word
2831         if (mw) {
2832                 if (pos > 0 && isLetter(pos - 1))
2833                         return false;
2834                 if (pos + strsize < parsize
2835                         && isLetter(pos + strsize))
2836                         return false;
2837         }
2838
2839         return true;
2840 }
2841
2842
2843 char_type Paragraph::getChar(pos_type pos) const
2844 {
2845         return d->text_[pos];
2846 }
2847
2848
2849 pos_type Paragraph::size() const
2850 {
2851         return d->text_.size();
2852 }
2853
2854
2855 bool Paragraph::empty() const
2856 {
2857         return d->text_.empty();
2858 }
2859
2860
2861 bool Paragraph::isInset(pos_type pos) const
2862 {
2863         return d->text_[pos] == META_INSET;
2864 }
2865
2866
2867 bool Paragraph::isSeparator(pos_type pos) const
2868 {
2869         //FIXME: Are we sure this can be the only separator?
2870         return d->text_[pos] == ' ';
2871 }
2872
2873
2874 void Paragraph::deregisterWords()
2875 {
2876         Private::Words::const_iterator it;
2877         WordList & wl = theWordList();
2878         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2879                 wl.remove(*it);
2880         d->words_.clear();
2881 }
2882
2883
2884 void Paragraph::locateWord(pos_type & from, pos_type & to,
2885         word_location const loc) const
2886 {
2887         switch (loc) {
2888         case WHOLE_WORD_STRICT:
2889                 if (from == 0 || from == size()
2890                     || !isLetter(from)
2891                     || !isLetter(from - 1)) {
2892                         to = from;
2893                         return;
2894                 }
2895                 // no break here, we go to the next
2896
2897         case WHOLE_WORD:
2898                 // If we are already at the beginning of a word, do nothing
2899                 if (!from || !isLetter(from - 1))
2900                         break;
2901                 // no break here, we go to the next
2902
2903         case PREVIOUS_WORD:
2904                 // always move the cursor to the beginning of previous word
2905                 while (from && isLetter(from - 1))
2906                         --from;
2907                 break;
2908         case NEXT_WORD:
2909                 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
2910                 break;
2911         case PARTIAL_WORD:
2912                 // no need to move the 'from' cursor
2913                 break;
2914         }
2915         to = from;
2916         while (to < size() && isLetter(to))
2917                 ++to;
2918 }
2919
2920
2921 void Paragraph::collectWords()
2922 {
2923         SpellChecker * speller = theSpellChecker();
2924
2925         //lyxerr << "Words: ";
2926         pos_type n = size();
2927         for (pos_type pos = 0; pos < n; ++pos) {
2928                 if (!isLetter(pos))
2929                         continue;
2930                 pos_type from = pos;
2931                 locateWord(from, pos, WHOLE_WORD);
2932                 if (!lyxrc.spellcheck_continuously && pos - from < 6)
2933                         continue;
2934
2935                 docstring word = asString(from, pos, false);
2936                 if (pos - from >= 6)
2937                         d->words_.insert(word);
2938
2939                 if (!lyxrc.spellcheck_continuously || !speller)
2940                         continue;
2941                 
2942                 string lang_code = lyxrc.spellchecker_use_alt_lang
2943                       ? lyxrc.spellchecker_alt_lang
2944                       : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2945                 WordLangTuple wl(word, lang_code);
2946                 SpellChecker::Result res = speller->check(wl);
2947                 // ... just ignore any error that the spellchecker reports.
2948                 if (!speller->error().empty())
2949                         continue;
2950                 bool const misspelled = res != SpellChecker::OK
2951                         && res != SpellChecker::IGNORED_WORD;
2952                 d->fontlist_.setMisspelled(from, pos, misspelled);
2953
2954                 //lyxerr << word << " ";
2955         }
2956         //lyxerr << std::endl;
2957 }
2958
2959
2960 void Paragraph::registerWords()
2961 {
2962         Private::Words::const_iterator it;
2963         WordList & wl = theWordList();
2964         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2965                 wl.insert(*it);
2966 }
2967
2968
2969 void Paragraph::updateWords()
2970 {
2971         deregisterWords();
2972         collectWords();
2973         registerWords();
2974 }
2975
2976
2977 bool Paragraph::isMisspelled(pos_type pos) const
2978 {
2979         SpellChecker * speller = theSpellChecker();
2980         pos_type from = pos;
2981         pos_type to = pos;
2982         locateWord(from, to, WHOLE_WORD);
2983         docstring word = asString(from, to, false);
2984         if (!speller)
2985                 return false;
2986                 
2987         string lang_code = lyxrc.spellchecker_use_alt_lang
2988               ? lyxrc.spellchecker_alt_lang
2989               : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2990         WordLangTuple wl(word, lang_code);
2991         SpellChecker::Result res = speller->check(wl);
2992         // ... just ignore any error that the spellchecker reports.
2993         if (!speller->error().empty())
2994                 return false;
2995
2996         bool const misspelled = res != SpellChecker::OK
2997                 && res != SpellChecker::IGNORED_WORD;
2998         if (lyxrc.spellcheck_continuously)
2999                 d->fontlist_.setMisspelled(from, pos, misspelled);
3000         return misspelled;
3001 }
3002
3003
3004 } // namespace lyx