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