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