]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Get rid of Paragraph::insetAllowed()
[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 void Paragraph::resetFonts(Font const & font)
1308 {
1309         d->fontlist_.clear();
1310         d->fontlist_.set(0, font);
1311         d->fontlist_.set(d->text_.size() - 1, font);
1312 }
1313
1314 // Gets uninstantiated font setting at position.
1315 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1316                                          pos_type pos) const
1317 {
1318         if (pos > size()) {
1319                 LYXERR0("pos: " << pos << " size: " << size());
1320                 LASSERT(pos <= size(), /**/);
1321         }
1322
1323         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1324         if (cit != d->fontlist_.end())
1325                 return cit->font();
1326
1327         if (pos == size() && !empty())
1328                 return getFontSettings(bparams, pos - 1);
1329
1330         return Font(inherit_font, getParLanguage(bparams));
1331 }
1332
1333
1334 FontSpan Paragraph::fontSpan(pos_type pos) const
1335 {
1336         LASSERT(pos <= size(), /**/);
1337         pos_type start = 0;
1338
1339         FontList::const_iterator cit = d->fontlist_.begin();
1340         FontList::const_iterator end = d->fontlist_.end();
1341         for (; cit != end; ++cit) {
1342                 if (cit->pos() >= pos) {
1343                         if (pos >= beginOfBody())
1344                                 return FontSpan(max(start, beginOfBody()),
1345                                                 cit->pos());
1346                         else
1347                                 return FontSpan(start,
1348                                                 min(beginOfBody() - 1,
1349                                                          cit->pos()));
1350                 }
1351                 start = cit->pos() + 1;
1352         }
1353
1354         // This should not happen, but if so, we take no chances.
1355         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1356         return FontSpan(pos, pos);
1357 }
1358
1359
1360 // Gets uninstantiated font setting at position 0
1361 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1362 {
1363         if (!empty() && !d->fontlist_.empty())
1364                 return d->fontlist_.begin()->font();
1365
1366         return Font(inherit_font, bparams.language);
1367 }
1368
1369
1370 // Gets the fully instantiated font at a given position in a paragraph
1371 // This is basically the same function as Text::GetFont() in text2.cpp.
1372 // The difference is that this one is used for generating the LaTeX file,
1373 // and thus cosmetic "improvements" are disallowed: This has to deliver
1374 // the true picture of the buffer. (Asger)
1375 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1376                                  Font const & outerfont) const
1377 {
1378         LASSERT(pos >= 0, /**/);
1379
1380         Font font = getFontSettings(bparams, pos);
1381
1382         pos_type const body_pos = beginOfBody();
1383         if (pos < body_pos)
1384                 font.fontInfo().realize(d->layout_->labelfont);
1385         else
1386                 font.fontInfo().realize(d->layout_->font);
1387
1388         font.fontInfo().realize(outerfont.fontInfo());
1389         font.fontInfo().realize(bparams.getFont().fontInfo());
1390
1391         return font;
1392 }
1393
1394
1395 Font const Paragraph::getLabelFont
1396         (BufferParams const & bparams, Font const & outerfont) const
1397 {
1398         FontInfo tmpfont = d->layout_->labelfont;
1399         tmpfont.realize(outerfont.fontInfo());
1400         tmpfont.realize(bparams.getFont().fontInfo());
1401         return Font(tmpfont, getParLanguage(bparams));
1402 }
1403
1404
1405 Font const Paragraph::getLayoutFont
1406         (BufferParams const & bparams, Font const & outerfont) const
1407 {
1408         FontInfo tmpfont = d->layout_->font;
1409         tmpfont.realize(outerfont.fontInfo());
1410         tmpfont.realize(bparams.getFont().fontInfo());
1411         return Font(tmpfont, getParLanguage(bparams));
1412 }
1413
1414
1415 /// Returns the height of the highest font in range
1416 FontSize Paragraph::highestFontInRange
1417         (pos_type startpos, pos_type endpos, FontSize def_size) const
1418 {
1419         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1420 }
1421
1422
1423 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1424 {
1425         char_type c = d->text_[pos];
1426         if (!lyxrc.rtl_support)
1427                 return c;
1428
1429         char_type uc = c;
1430         switch (c) {
1431         case '(':
1432                 uc = ')';
1433                 break;
1434         case ')':
1435                 uc = '(';
1436                 break;
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         }
1456         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1457                 return uc;
1458         return c;
1459 }
1460
1461
1462 void Paragraph::setFont(pos_type pos, Font const & font)
1463 {
1464         LASSERT(pos <= size(), /**/);
1465
1466         // First, reduce font against layout/label font
1467         // Update: The setCharFont() routine in text2.cpp already
1468         // reduces font, so we don't need to do that here. (Asger)
1469         
1470         d->fontlist_.set(pos, font);
1471 }
1472
1473
1474 void Paragraph::makeSameLayout(Paragraph const & par)
1475 {
1476         d->layout_ = par.d->layout_;
1477         d->params_ = par.d->params_;
1478 }
1479
1480
1481 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1482 {
1483         if (isFreeSpacing())
1484                 return false;
1485
1486         int pos = 0;
1487         int count = 0;
1488
1489         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1490                 if (eraseChar(pos, trackChanges))
1491                         ++count;
1492                 else
1493                         ++pos;
1494         }
1495
1496         return count > 0 || pos > 0;
1497 }
1498
1499
1500 bool Paragraph::hasSameLayout(Paragraph const & par) const
1501 {
1502         return par.d->layout_ == d->layout_
1503                 && d->params_.sameLayout(par.d->params_);
1504 }
1505
1506
1507 depth_type Paragraph::getDepth() const
1508 {
1509         return d->params_.depth();
1510 }
1511
1512
1513 depth_type Paragraph::getMaxDepthAfter() const
1514 {
1515         if (d->layout_->isEnvironment())
1516                 return d->params_.depth() + 1;
1517         else
1518                 return d->params_.depth();
1519 }
1520
1521
1522 char Paragraph::getAlign() const
1523 {
1524         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1525                 return d->layout_->align;
1526         else
1527                 return d->params_.align();
1528 }
1529
1530
1531 docstring const & Paragraph::labelString() const
1532 {
1533         return d->params_.labelString();
1534 }
1535
1536
1537 // the next two functions are for the manual labels
1538 docstring const Paragraph::getLabelWidthString() const
1539 {
1540         if (d->layout_->margintype == MARGIN_MANUAL)
1541                 return d->params_.labelWidthString();
1542         else
1543                 return _("Senseless with this layout!");
1544 }
1545
1546
1547 void Paragraph::setLabelWidthString(docstring const & s)
1548 {
1549         d->params_.labelWidthString(s);
1550 }
1551
1552
1553 docstring const Paragraph::translateIfPossible(docstring const & s,
1554                 BufferParams const & bparams) const
1555 {
1556         if (!isAscii(s) || s.empty()) {
1557                 // This must be a user defined layout. We cannot translate
1558                 // this, since gettext accepts only ascii keys.
1559                 return s;
1560         }
1561         // Probably standard layout, try to translate
1562         Messages & m = getMessages(getParLanguage(bparams)->code());
1563         return m.get(to_ascii(s));
1564 }
1565
1566
1567 docstring Paragraph::expandLabel(Layout const & layout,
1568                 BufferParams const & bparams, bool process_appendix) const
1569 {
1570         DocumentClass const & tclass = bparams.documentClass();
1571
1572         docstring fmt;
1573         if (process_appendix && d->params_.appendix())
1574                 fmt = translateIfPossible(layout.labelstring_appendix(),
1575                         bparams);
1576         else
1577                 fmt = translateIfPossible(layout.labelstring(), bparams);
1578
1579         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1580             && !layout.counter.empty())
1581                 fmt = "\\the" + layout.counter;
1582
1583         // handle 'inherited level parts' in 'fmt',
1584         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1585         size_t const i = fmt.find('@', 0);
1586         if (i != docstring::npos) {
1587                 size_t const j = fmt.find('@', i + 1);
1588                 if (j != docstring::npos) {
1589                         docstring parent(fmt, i + 1, j - i - 1);
1590                         docstring label = from_ascii("??");
1591                         if (tclass.hasLayout(parent))
1592                                 docstring label = expandLabel(tclass[parent], bparams,
1593                                                       process_appendix);
1594                         fmt = docstring(fmt, 0, i) + label 
1595                                 + docstring(fmt, j + 1, docstring::npos);
1596                 }
1597         }
1598
1599         return tclass.counters().counterLabel(fmt);
1600 }
1601
1602
1603 void Paragraph::applyLayout(Layout const & new_layout)
1604 {
1605         d->layout_ = &new_layout;
1606         LyXAlignment const oldAlign = d->params_.align();
1607         
1608         if (!(oldAlign & d->layout_->alignpossible)) {
1609                 frontend::Alert::warning(_("Alignment not permitted"), 
1610                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1611                 d->params_.align(LYX_ALIGN_LAYOUT);
1612         }
1613 }
1614
1615
1616 pos_type Paragraph::beginOfBody() const
1617 {
1618         return d->begin_of_body_;
1619 }
1620
1621
1622 void Paragraph::setBeginOfBody()
1623 {
1624         if (d->layout_->labeltype != LABEL_MANUAL) {
1625                 d->begin_of_body_ = 0;
1626                 return;
1627         }
1628
1629         // Unroll the first two cycles of the loop
1630         // and remember the previous character to
1631         // remove unnecessary getChar() calls
1632         pos_type i = 0;
1633         pos_type end = size();
1634         if (i < end && !isNewline(i)) {
1635                 ++i;
1636                 char_type previous_char = 0;
1637                 char_type temp = 0;
1638                 if (i < end) {
1639                         previous_char = d->text_[i];
1640                         if (!isNewline(i)) {
1641                                 ++i;
1642                                 while (i < end && previous_char != ' ') {
1643                                         temp = d->text_[i];
1644                                         if (isNewline(i))
1645                                                 break;
1646                                         ++i;
1647                                         previous_char = temp;
1648                                 }
1649                         }
1650                 }
1651         }
1652
1653         d->begin_of_body_ = i;
1654 }
1655
1656
1657 bool Paragraph::forcePlainLayout() const
1658 {
1659         Inset const * const inset = inInset();
1660         if (!inset)
1661                 return true;
1662         return inset->forcePlainLayout();
1663 }
1664
1665
1666 bool Paragraph::allowParagraphCustomization() const
1667 {
1668         Inset const * const inset = inInset();
1669         if (!inset)
1670                 return true;
1671         return inset->allowParagraphCustomization();
1672 }
1673
1674
1675 bool Paragraph::usePlainLayout() const
1676 {
1677         Inset const * const inset = inInset();
1678         if (!inset)
1679                 return false;
1680         return inset->usePlainLayout();
1681 }
1682
1683
1684 namespace {
1685
1686 // paragraphs inside floats need different alignment tags to avoid
1687 // unwanted space
1688
1689 bool noTrivlistCentering(InsetCode code)
1690 {
1691         return code == FLOAT_CODE || code == WRAP_CODE;
1692 }
1693
1694
1695 string correction(string const & orig)
1696 {
1697         if (orig == "flushleft")
1698                 return "raggedright";
1699         if (orig == "flushright")
1700                 return "raggedleft";
1701         if (orig == "center")
1702                 return "centering";
1703         return orig;
1704 }
1705
1706
1707 string const corrected_env(string const & suffix, string const & env,
1708         InsetCode code)
1709 {
1710         string output = suffix + "{";
1711         if (noTrivlistCentering(code))
1712                 output += correction(env);
1713         else
1714                 output += env;
1715         output += "}";
1716         if (suffix == "\\begin")
1717                 output += "\n";
1718         return output;
1719 }
1720
1721
1722 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1723 {
1724         if (!contains(str, "\n"))
1725                 column += str.size();
1726         else {
1727                 string tmp;
1728                 texrow.newline();
1729                 column = rsplit(str, tmp, '\n').size();
1730         }
1731 }
1732
1733 } // namespace anon
1734
1735
1736 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1737                                  odocstream & os, TexRow & texrow,
1738                                  bool moving_arg) const
1739 {
1740         int column = 0;
1741
1742         if (params_.noindent()) {
1743                 os << "\\noindent ";
1744                 column += 10;
1745         }
1746         
1747         LyXAlignment const curAlign = params_.align();
1748
1749         if (curAlign == layout_->align)
1750                 return column;
1751
1752         switch (curAlign) {
1753         case LYX_ALIGN_NONE:
1754         case LYX_ALIGN_BLOCK:
1755         case LYX_ALIGN_LAYOUT:
1756         case LYX_ALIGN_SPECIAL:
1757                 break;
1758         case LYX_ALIGN_LEFT:
1759         case LYX_ALIGN_RIGHT:
1760         case LYX_ALIGN_CENTER:
1761                 if (moving_arg) {
1762                         os << "\\protect";
1763                         column += 8;
1764                 }
1765                 break;
1766         }
1767
1768         switch (curAlign) {
1769         case LYX_ALIGN_NONE:
1770         case LYX_ALIGN_BLOCK:
1771         case LYX_ALIGN_LAYOUT:
1772         case LYX_ALIGN_SPECIAL:
1773                 break;
1774         case LYX_ALIGN_LEFT: {
1775                 string output;
1776                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1777                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1778                 else
1779                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1780                 os << from_ascii(output);
1781                 adjust_row_column(output, texrow, column);
1782                 break;
1783         } case LYX_ALIGN_RIGHT: {
1784                 string output;
1785                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1786                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1787                 else
1788                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1789                 os << from_ascii(output);
1790                 adjust_row_column(output, texrow, column);
1791                 break;
1792         } case LYX_ALIGN_CENTER: {
1793                 string output;
1794                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1795                 os << from_ascii(output);
1796                 adjust_row_column(output, texrow, column);
1797                 break;
1798         }
1799         }
1800
1801         return column;
1802 }
1803
1804
1805 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1806                                odocstream & os, TexRow & texrow,
1807                                bool moving_arg) const
1808 {
1809         int column = 0;
1810
1811         switch (params_.align()) {
1812         case LYX_ALIGN_NONE:
1813         case LYX_ALIGN_BLOCK:
1814         case LYX_ALIGN_LAYOUT:
1815         case LYX_ALIGN_SPECIAL:
1816                 break;
1817         case LYX_ALIGN_LEFT:
1818         case LYX_ALIGN_RIGHT:
1819         case LYX_ALIGN_CENTER:
1820                 if (moving_arg) {
1821                         os << "\\protect";
1822                         column = 8;
1823                 }
1824                 break;
1825         }
1826
1827         switch (params_.align()) {
1828         case LYX_ALIGN_NONE:
1829         case LYX_ALIGN_BLOCK:
1830         case LYX_ALIGN_LAYOUT:
1831         case LYX_ALIGN_SPECIAL:
1832                 break;
1833         case LYX_ALIGN_LEFT: {
1834                 string output;
1835                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1836                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1837                 else
1838                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1839                 os << from_ascii(output);
1840                 adjust_row_column(output, texrow, column);
1841                 break;
1842         } case LYX_ALIGN_RIGHT: {
1843                 string output;
1844                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1845                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1846                 else
1847                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1848                 os << from_ascii(output);
1849                 adjust_row_column(output, texrow, column);
1850                 break;
1851         } case LYX_ALIGN_CENTER: {
1852                 string output;
1853                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1854                 os << from_ascii(output);
1855                 adjust_row_column(output, texrow, column);
1856                 break;
1857         }
1858         }
1859
1860         return column;
1861 }
1862
1863
1864 // This one spits out the text of the paragraph
1865 bool Paragraph::latex(BufferParams const & bparams,
1866                                 Font const & outerfont,
1867                                 odocstream & os, TexRow & texrow,
1868                                 OutputParams const & runparams) const
1869 {
1870         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1871
1872         bool return_value = false;
1873
1874         bool asdefault = forcePlainLayout();
1875
1876         Layout const & style = asdefault ?
1877                 bparams.documentClass().plainLayout() :
1878                 *d->layout_;
1879
1880         // Current base font for all inherited font changes, without any
1881         // change caused by an individual character, except for the language:
1882         // It is set to the language of the first character.
1883         // As long as we are in the label, this font is the base font of the
1884         // label. Before the first body character it is set to the base font
1885         // of the body.
1886         Font basefont;
1887
1888         // Maybe we have to create a optional argument.
1889         pos_type body_pos = beginOfBody();
1890         unsigned int column = 0;
1891
1892         if (body_pos > 0) {
1893                 // the optional argument is kept in curly brackets in
1894                 // case it contains a ']'
1895                 os << "[{";
1896                 column += 2;
1897                 basefont = getLabelFont(bparams, outerfont);
1898         } else {
1899                 basefont = getLayoutFont(bparams, outerfont);
1900         }
1901
1902         // Which font is currently active?
1903         Font running_font(basefont);
1904         // Do we have an open font change?
1905         bool open_font = false;
1906
1907         Change runningChange = Change(Change::UNCHANGED);
1908
1909         texrow.start(id(), 0);
1910
1911         // if the paragraph is empty, the loop will not be entered at all
1912         if (empty()) {
1913                 if (style.isCommand()) {
1914                         os << '{';
1915                         ++column;
1916                 }
1917                 if (!asdefault)
1918                         column += d->startTeXParParams(bparams, os, texrow,
1919                                                     runparams.moving_arg);
1920         }
1921
1922         for (pos_type i = 0; i < size(); ++i) {
1923                 // First char in paragraph or after label?
1924                 if (i == body_pos) {
1925                         if (body_pos > 0) {
1926                                 if (open_font) {
1927                                         column += running_font.latexWriteEndChanges(
1928                                                 os, bparams, runparams,
1929                                                 basefont, basefont);
1930                                         open_font = false;
1931                                 }
1932                                 basefont = getLayoutFont(bparams, outerfont);
1933                                 running_font = basefont;
1934
1935                                 column += Changes::latexMarkChange(os, bparams,
1936                                                 runningChange, Change(Change::UNCHANGED));
1937                                 runningChange = Change(Change::UNCHANGED);
1938
1939                                 os << "}] ";
1940                                 column +=3;
1941                         }
1942                         if (style.isCommand()) {
1943                                 os << '{';
1944                                 ++column;
1945                         }
1946
1947                         if (!asdefault)
1948                                 column += d->startTeXParParams(bparams, os,
1949                                                             texrow,
1950                                                             runparams.moving_arg);
1951                 }
1952
1953                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1954                                                                  : lookupChange(i);
1955
1956                 if (bparams.outputChanges && runningChange != change) {
1957                         if (open_font) {
1958                                 column += running_font.latexWriteEndChanges(
1959                                                 os, bparams, runparams, basefont, basefont);
1960                                 open_font = false;
1961                         }
1962                         basefont = getLayoutFont(bparams, outerfont);
1963                         running_font = basefont;
1964
1965                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1966                         runningChange = change;
1967                 }
1968
1969                 // do not output text which is marked deleted
1970                 // if change tracking output is disabled
1971                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1972                         continue;
1973                 }
1974
1975                 ++column;
1976
1977                 // Fully instantiated font
1978                 Font const font = getFont(bparams, i, outerfont);
1979
1980                 Font const last_font = running_font;
1981
1982                 // Do we need to close the previous font?
1983                 if (open_font &&
1984                     (font != running_font ||
1985                      font.language() != running_font.language()))
1986                 {
1987                         column += running_font.latexWriteEndChanges(
1988                                         os, bparams, runparams, basefont,
1989                                         (i == body_pos-1) ? basefont : font);
1990                         running_font = basefont;
1991                         open_font = false;
1992                 }
1993
1994                 // close babel's font environment before opening CJK.
1995                 if (!running_font.language()->babel().empty() &&
1996                     font.language()->encoding()->package() == Encoding::CJK) {
1997                                 string end_tag = subst(lyxrc.language_command_end,
1998                                                         "$$lang",
1999                                                         running_font.language()->babel());
2000                                 os << from_ascii(end_tag);
2001                                 column += end_tag.length();
2002                 }
2003
2004                 // Switch file encoding if necessary (and allowed)
2005                 if (!runparams.verbatim && 
2006                     runparams.encoding->package() != Encoding::none &&
2007                     font.language()->encoding()->package() != Encoding::none) {
2008                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2009                                         runparams, *(font.language()->encoding()));
2010                         if (enc_switch.first) {
2011                                 column += enc_switch.second;
2012                                 runparams.encoding = font.language()->encoding();
2013                         }
2014                 }
2015
2016                 char_type const c = d->text_[i];
2017
2018                 // Do we need to change font?
2019                 if ((font != running_font ||
2020                      font.language() != running_font.language()) &&
2021                         i != body_pos - 1)
2022                 {
2023                         odocstringstream ods;
2024                         column += font.latexWriteStartChanges(ods, bparams,
2025                                                               runparams, basefont,
2026                                                               last_font);
2027                         running_font = font;
2028                         open_font = true;
2029                         docstring fontchange = ods.str();
2030                         // check if the fontchange ends with a trailing blank
2031                         // (like "\small " (see bug 3382)
2032                         if (suffixIs(fontchange, ' ') && c == ' ')
2033                                 os << fontchange.substr(0, fontchange.size() - 1) 
2034                                    << from_ascii("{}");
2035                         else
2036                                 os << fontchange;
2037                 }
2038
2039                 if (c == ' ') {
2040                         // FIXME: integrate this case in latexSpecialChar
2041                         // Do not print the separation of the optional argument
2042                         // if style.pass_thru is false. This works because
2043                         // latexSpecialChar ignores spaces if
2044                         // style.pass_thru is false.
2045                         if (i != body_pos - 1) {
2046                                 if (d->simpleTeXBlanks(
2047                                                 runparams, os, texrow,
2048                                                 i, column, font, style)) {
2049                                         // A surrogate pair was output. We
2050                                         // must not call latexSpecialChar
2051                                         // in this iteration, since it would output
2052                                         // the combining character again.
2053                                         ++i;
2054                                         continue;
2055                                 }
2056                         }
2057                 }
2058
2059                 OutputParams rp = runparams;
2060                 rp.free_spacing = style.free_spacing;
2061                 rp.local_font = &font;
2062                 rp.intitle = style.intitle;
2063
2064                 // Two major modes:  LaTeX or plain
2065                 // Handle here those cases common to both modes
2066                 // and then split to handle the two modes separately.
2067                 if (c == META_INSET)
2068                         d->latexInset(bparams, os,
2069                                         texrow, rp, running_font,
2070                                         basefont, outerfont, open_font,
2071                                         runningChange, style, i, column);
2072                 else {
2073                         try {
2074                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2075                                         style, i, column);
2076                         } catch (EncodingException & e) {
2077                                 if (runparams.dryrun) {
2078                                         os << "<" << _("LyX Warning: ")
2079                                            << _("uncodable character") << " '";
2080                                         os.put(c);
2081                                         os << "'>";
2082                                 } else {
2083                                         // add location information and throw again.
2084                                         e.par_id = id();
2085                                         e.pos = i;
2086                                         throw(e);
2087                                 }
2088                         }
2089                 }
2090
2091                 // Set the encoding to that returned from latexSpecialChar (see
2092                 // comment for encoding member in OutputParams.h)
2093                 runparams.encoding = rp.encoding;
2094         }
2095
2096         // If we have an open font definition, we have to close it
2097         if (open_font) {
2098 #ifdef FIXED_LANGUAGE_END_DETECTION
2099                 if (next_) {
2100                         running_font
2101                                 .latexWriteEndChanges(os, bparams, runparams,
2102                                         basefont,
2103                                         next_->getFont(bparams, 0, outerfont));
2104                 } else {
2105                         running_font.latexWriteEndChanges(os, bparams,
2106                                         runparams, basefont, basefont);
2107                 }
2108 #else
2109 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2110 //FIXME: there as we start another \selectlanguage with the next paragraph if
2111 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2112                 running_font.latexWriteEndChanges(os, bparams, runparams,
2113                                 basefont, basefont);
2114 #endif
2115         }
2116
2117         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2118
2119         // Needed if there is an optional argument but no contents.
2120         if (body_pos > 0 && body_pos == size()) {
2121                 os << "}]~";
2122                 return_value = false;
2123         }
2124
2125         if (!asdefault) {
2126                 column += d->endTeXParParams(bparams, os, texrow,
2127                                           runparams.moving_arg);
2128         }
2129
2130         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2131         return return_value;
2132 }
2133
2134
2135 bool Paragraph::emptyTag() const
2136 {
2137         for (pos_type i = 0; i < size(); ++i) {
2138                 if (Inset const * inset = getInset(i)) {
2139                         InsetCode lyx_code = inset->lyxCode();
2140                         if (lyx_code != TOC_CODE &&
2141                             lyx_code != INCLUDE_CODE &&
2142                             lyx_code != GRAPHICS_CODE &&
2143                             lyx_code != ERT_CODE &&
2144                             lyx_code != LISTINGS_CODE &&
2145                             lyx_code != FLOAT_CODE &&
2146                             lyx_code != TABULAR_CODE) {
2147                                 return false;
2148                         }
2149                 } else {
2150                         char_type c = d->text_[i];
2151                         if (c != ' ' && c != '\t')
2152                                 return false;
2153                 }
2154         }
2155         return true;
2156 }
2157
2158
2159 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2160         const
2161 {
2162         for (pos_type i = 0; i < size(); ++i) {
2163                 if (Inset const * inset = getInset(i)) {
2164                         InsetCode lyx_code = inset->lyxCode();
2165                         if (lyx_code == LABEL_CODE) {
2166                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2167                                 docstring const & id = il->getParam("name");
2168                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2169                         }
2170                 }
2171         }
2172         return string();
2173 }
2174
2175
2176 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2177         const
2178 {
2179         pos_type i;
2180         for (i = 0; i < size(); ++i) {
2181                 if (Inset const * inset = getInset(i)) {
2182                         inset->docbook(os, runparams);
2183                 } else {
2184                         char_type c = d->text_[i];
2185                         if (c == ' ')
2186                                 break;
2187                         os << sgml::escapeChar(c);
2188                 }
2189         }
2190         return i;
2191 }
2192
2193
2194 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2195 {
2196         Font font_old;
2197         pos_type size = text_.size();
2198         for (pos_type i = initial; i < size; ++i) {
2199                 Font font = owner_->getFont(buf.params(), i, outerfont);
2200                 if (text_[i] == META_INSET)
2201                         return false;
2202                 if (i != initial && font != font_old)
2203                         return false;
2204                 font_old = font;
2205         }
2206
2207         return true;
2208 }
2209
2210
2211 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2212                                     odocstream & os,
2213                                     OutputParams const & runparams,
2214                                     Font const & outerfont,
2215                                     pos_type initial) const
2216 {
2217         bool emph_flag = false;
2218
2219         Layout const & style = *d->layout_;
2220         FontInfo font_old =
2221                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2222
2223         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2224                 os << "]]>";
2225
2226         // parsing main loop
2227         for (pos_type i = initial; i < size(); ++i) {
2228                 Font font = getFont(buf.params(), i, outerfont);
2229
2230                 // handle <emphasis> tag
2231                 if (font_old.emph() != font.fontInfo().emph()) {
2232                         if (font.fontInfo().emph() == FONT_ON) {
2233                                 os << "<emphasis>";
2234                                 emph_flag = true;
2235                         } else if (i != initial) {
2236                                 os << "</emphasis>";
2237                                 emph_flag = false;
2238                         }
2239                 }
2240
2241                 if (Inset const * inset = getInset(i)) {
2242                         inset->docbook(os, runparams);
2243                 } else {
2244                         char_type c = d->text_[i];
2245
2246                         if (style.pass_thru)
2247                                 os.put(c);
2248                         else
2249                                 os << sgml::escapeChar(c);
2250                 }
2251                 font_old = font.fontInfo();
2252         }
2253
2254         if (emph_flag) {
2255                 os << "</emphasis>";
2256         }
2257
2258         if (style.free_spacing)
2259                 os << '\n';
2260         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2261                 os << "<![CDATA[";
2262 }
2263
2264
2265 bool Paragraph::isHfill(pos_type pos) const
2266 {
2267         Inset const * inset = getInset(pos);
2268         return inset && (inset->lyxCode() == SPACE_CODE &&
2269                          inset->isStretchableSpace());
2270 }
2271
2272
2273 bool Paragraph::isNewline(pos_type pos) const
2274 {
2275         Inset const * inset = getInset(pos);
2276         return inset && inset->lyxCode() == NEWLINE_CODE;
2277 }
2278
2279
2280 bool Paragraph::isLineSeparator(pos_type pos) const
2281 {
2282         char_type const c = d->text_[pos];
2283         if (isLineSeparatorChar(c))
2284                 return true;
2285         Inset const * inset = getInset(pos);
2286         return inset && inset->isLineSeparator();
2287 }
2288
2289
2290 /// Used by the spellchecker
2291 bool Paragraph::isLetter(pos_type pos) const
2292 {
2293         if (Inset const * inset = getInset(pos))
2294                 return inset->isLetter();
2295         char_type const c = d->text_[pos];
2296         return isLetterChar(c) || isDigit(c);
2297 }
2298
2299
2300 bool Paragraph::isChar(pos_type pos) const
2301 {
2302         if (Inset const * inset = getInset(pos))
2303                 return inset->isChar();
2304         char_type const c = d->text_[pos];
2305         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2306 }
2307
2308
2309 bool Paragraph::isSpace(pos_type pos) const
2310 {
2311         if (Inset const * inset = getInset(pos))
2312                 return inset->isSpace();
2313         char_type const c = d->text_[pos];
2314         return lyx::isSpace(c);
2315 }
2316
2317
2318 Language const *
2319 Paragraph::getParLanguage(BufferParams const & bparams) const
2320 {
2321         if (!empty())
2322                 return getFirstFontSettings(bparams).language();
2323         // FIXME: we should check the prev par as well (Lgb)
2324         return bparams.language;
2325 }
2326
2327
2328 bool Paragraph::isRTL(BufferParams const & bparams) const
2329 {
2330         return lyxrc.rtl_support
2331                 && getParLanguage(bparams)->rightToLeft()
2332                 && ownerCode() != ERT_CODE
2333                 && ownerCode() != LISTINGS_CODE;
2334 }
2335
2336
2337 void Paragraph::changeLanguage(BufferParams const & bparams,
2338                                Language const * from, Language const * to)
2339 {
2340         // change language including dummy font change at the end
2341         for (pos_type i = 0; i <= size(); ++i) {
2342                 Font font = getFontSettings(bparams, i);
2343                 if (font.language() == from) {
2344                         font.setLanguage(to);
2345                         setFont(i, font);
2346                 }
2347         }
2348 }
2349
2350
2351 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2352 {
2353         Language const * doc_language = bparams.language;
2354         FontList::const_iterator cit = d->fontlist_.begin();
2355         FontList::const_iterator end = d->fontlist_.end();
2356
2357         for (; cit != end; ++cit)
2358                 if (cit->font().language() != ignore_language &&
2359                     cit->font().language() != latex_language &&
2360                     cit->font().language() != doc_language)
2361                         return true;
2362         return false;
2363 }
2364
2365
2366 docstring Paragraph::asString(int options) const
2367 {
2368         return asString(0, size(), options);
2369 }
2370
2371
2372 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2373 {
2374         odocstringstream os;
2375
2376         if (beg == 0 
2377                 && options & AS_STR_LABEL
2378                 && !d->params_.labelString().empty())
2379                 os << d->params_.labelString() << ' ';
2380
2381         for (pos_type i = beg; i < end; ++i) {
2382                 char_type const c = d->text_[i];
2383                 if (isPrintable(c))
2384                         os.put(c);
2385                 else if (c == META_INSET && options & AS_STR_INSETS)
2386                         getInset(i)->textString(os);
2387         }
2388
2389         return os.str();
2390 }
2391
2392
2393 void Paragraph::setInsetOwner(Inset * inset)
2394 {
2395         d->inset_owner_ = inset;
2396 }
2397
2398
2399 int Paragraph::id() const
2400 {
2401         return d->id_;
2402 }
2403
2404
2405 Layout const & Paragraph::layout() const
2406 {
2407         return *d->layout_;
2408 }
2409
2410
2411 void Paragraph::setLayout(Layout const & layout)
2412 {
2413         d->layout_ = &layout;
2414 }
2415
2416
2417 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2418 {
2419         if (usePlainLayout())
2420                 setLayout(tclass.plainLayout());
2421         else
2422                 setLayout(tclass.defaultLayout());
2423 }
2424
2425
2426 Inset * Paragraph::inInset() const
2427 {
2428         return d->inset_owner_;
2429 }
2430
2431
2432 InsetCode Paragraph::ownerCode() const
2433 {
2434         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2435 }
2436
2437
2438 ParagraphParameters & Paragraph::params()
2439 {
2440         return d->params_;
2441 }
2442
2443
2444 ParagraphParameters const & Paragraph::params() const
2445 {
2446         return d->params_;
2447 }
2448
2449
2450 bool Paragraph::isFreeSpacing() const
2451 {
2452         if (d->layout_->free_spacing)
2453                 return true;
2454         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2455 }
2456
2457
2458 bool Paragraph::allowEmpty() const
2459 {
2460         if (d->layout_->keepempty)
2461                 return true;
2462         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2463 }
2464
2465
2466 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2467 {
2468         if (!Encodings::isArabicChar(c))
2469                 return c;
2470
2471         char_type prev_char = ' ';
2472         char_type next_char = ' ';
2473
2474         for (pos_type i = pos - 1; i >= 0; --i) {
2475                 char_type const par_char = d->text_[i];
2476                 if (!Encodings::isArabicComposeChar(par_char)) {
2477                         prev_char = par_char;
2478                         break;
2479                 }
2480         }
2481
2482         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2483                 char_type const par_char = d->text_[i];
2484                 if (!Encodings::isArabicComposeChar(par_char)) {
2485                         next_char = par_char;
2486                         break;
2487                 }
2488         }
2489
2490         if (Encodings::isArabicChar(next_char)) {
2491                 if (Encodings::isArabicChar(prev_char) &&
2492                         !Encodings::isArabicSpecialChar(prev_char))
2493                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2494                 else
2495                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2496         } else {
2497                 if (Encodings::isArabicChar(prev_char) &&
2498                         !Encodings::isArabicSpecialChar(prev_char))
2499                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2500                 else
2501                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2502         }
2503 }
2504
2505
2506 int Paragraph::checkBiblio(Buffer const & buffer)
2507 {
2508         // FIXME From JS:
2509         // This is getting more and more a mess. ...We really should clean
2510         // up this bibitem issue for 1.6. See also bug 2743.
2511
2512         // Add bibitem insets if necessary
2513         if (d->layout_->labeltype != LABEL_BIBLIO)
2514                 return 0;
2515
2516         bool hasbibitem = !d->insetlist_.empty()
2517                 // Insist on it being in pos 0
2518                 && d->text_[0] == META_INSET
2519                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2520
2521         bool track_changes = buffer.params().trackChanges;
2522
2523         docstring oldkey;
2524         docstring oldlabel;
2525
2526         // remove a bibitem in pos != 0
2527         // restore it later in pos 0 if necessary
2528         // (e.g. if a user inserts contents _before_ the item)
2529         // we're assuming there's only one of these, which there
2530         // should be.
2531         int erasedInsetPosition = -1;
2532         InsetList::iterator it = d->insetlist_.begin();
2533         InsetList::iterator end = d->insetlist_.end();
2534         for (; it != end; ++it)
2535                 if (it->inset->lyxCode() == BIBITEM_CODE
2536                     && it->pos > 0) {
2537                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2538                         oldkey = olditem->getParam("key");
2539                         oldlabel = olditem->getParam("label");
2540                         erasedInsetPosition = it->pos;
2541                         eraseChar(erasedInsetPosition, track_changes);
2542                         break;
2543         }
2544
2545         // There was an InsetBibitem at the beginning, and we didn't
2546         // have to erase one.
2547         if (hasbibitem && erasedInsetPosition < 0)
2548                         return 0;
2549
2550         // There was an InsetBibitem at the beginning and we did have to
2551         // erase one. So we give its properties to the beginning inset.
2552         if (hasbibitem) {
2553                 InsetBibitem * inset =
2554                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2555                 if (!oldkey.empty())
2556                         inset->setParam("key", oldkey);
2557                 inset->setParam("label", oldlabel);
2558                 return -erasedInsetPosition;
2559         }
2560
2561         // There was no inset at the beginning, so we need to create one with
2562         // the key and label of the one we erased.
2563         InsetBibitem * inset = 
2564                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2565         // restore values of previously deleted item in this par.
2566         if (!oldkey.empty())
2567                 inset->setParam("key", oldkey);
2568         inset->setParam("label", oldlabel);
2569         insertInset(0, static_cast<Inset *>(inset),
2570                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2571
2572         return 1;
2573 }
2574
2575
2576 void Paragraph::checkAuthors(AuthorList const & authorList)
2577 {
2578         d->changes_.checkAuthors(authorList);
2579 }
2580
2581
2582 bool Paragraph::isUnchanged(pos_type pos) const
2583 {
2584         return lookupChange(pos).type == Change::UNCHANGED;
2585 }
2586
2587
2588 bool Paragraph::isInserted(pos_type pos) const
2589 {
2590         return lookupChange(pos).type == Change::INSERTED;
2591 }
2592
2593
2594 bool Paragraph::isDeleted(pos_type pos) const
2595 {
2596         return lookupChange(pos).type == Change::DELETED;
2597 }
2598
2599
2600 InsetList const & Paragraph::insetList() const
2601 {
2602         return d->insetlist_;
2603 }
2604
2605
2606 void Paragraph::setBuffer(Buffer & b)
2607 {
2608         d->insetlist_.setBuffer(b);
2609 }
2610
2611
2612 Inset * Paragraph::releaseInset(pos_type pos)
2613 {
2614         Inset * inset = d->insetlist_.release(pos);
2615         /// does not honour change tracking!
2616         eraseChar(pos, false);
2617         return inset;
2618 }
2619
2620
2621 Inset * Paragraph::getInset(pos_type pos)
2622 {
2623         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2624                  ? d->insetlist_.get(pos) : 0;
2625 }
2626
2627
2628 Inset const * Paragraph::getInset(pos_type pos) const
2629 {
2630         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2631                  ? d->insetlist_.get(pos) : 0;
2632 }
2633
2634
2635 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2636                 pos_type & right, TextCase action)
2637 {
2638         // process sequences of modified characters; in change
2639         // tracking mode, this approach results in much better
2640         // usability than changing case on a char-by-char basis
2641         docstring changes;
2642
2643         bool const trackChanges = bparams.trackChanges;
2644
2645         bool capitalize = true;
2646
2647         for (; pos < right; ++pos) {
2648                 char_type oldChar = d->text_[pos];
2649                 char_type newChar = oldChar;
2650
2651                 // ignore insets and don't play with deleted text!
2652                 if (oldChar != META_INSET && !isDeleted(pos)) {
2653                         switch (action) {
2654                                 case text_lowercase:
2655                                         newChar = lowercase(oldChar);
2656                                         break;
2657                                 case text_capitalization:
2658                                         if (capitalize) {
2659                                                 newChar = uppercase(oldChar);
2660                                                 capitalize = false;
2661                                         }
2662                                         break;
2663                                 case text_uppercase:
2664                                         newChar = uppercase(oldChar);
2665                                         break;
2666                         }
2667                 }
2668
2669                 if (!isLetter(pos) || isDeleted(pos)) {
2670                         // permit capitalization again
2671                         capitalize = true;
2672                 }
2673
2674                 if (oldChar != newChar)
2675                         changes += newChar;
2676
2677                 if (oldChar == newChar || pos == right - 1) {
2678                         if (oldChar != newChar) {
2679                                 // step behind the changing area
2680                                 pos++;
2681                         }
2682                         int erasePos = pos - changes.size();
2683                         for (size_t i = 0; i < changes.size(); i++) {
2684                                 insertChar(pos, changes[i],
2685                                         getFontSettings(bparams,
2686                                         erasePos),
2687                                         trackChanges);
2688                                 if (!eraseChar(erasePos, trackChanges)) {
2689                                         ++erasePos;
2690                                         ++pos; // advance
2691                                         ++right; // expand selection
2692                                 }
2693                         }
2694                         changes.clear();
2695                 }
2696         }
2697 }
2698
2699
2700 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2701                 pos_type pos, bool del) const
2702 {
2703         int const strsize = str.length();
2704         int i = 0;
2705         pos_type const parsize = d->text_.size();
2706         for (i = 0; pos + i < parsize; ++i) {
2707                 if (i >= strsize)
2708                         break;
2709                 if (cs && str[i] != d->text_[pos + i])
2710                         break;
2711                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2712                         break;
2713                 if (!del && isDeleted(pos + i))
2714                         break;
2715         }
2716
2717         if (i != strsize)
2718                 return false;
2719
2720         // if necessary, check whether string matches word
2721         if (mw) {
2722                 if (pos > 0 && isLetter(pos - 1))
2723                         return false;
2724                 if (pos + strsize < parsize
2725                         && isLetter(pos + strsize))
2726                         return false;
2727         }
2728
2729         return true;
2730 }
2731
2732
2733 char_type Paragraph::getChar(pos_type pos) const
2734 {
2735         return d->text_[pos];
2736 }
2737
2738
2739 pos_type Paragraph::size() const
2740 {
2741         return d->text_.size();
2742 }
2743
2744
2745 bool Paragraph::empty() const
2746 {
2747         return d->text_.empty();
2748 }
2749
2750
2751 bool Paragraph::isInset(pos_type pos) const
2752 {
2753         return d->text_[pos] == META_INSET;
2754 }
2755
2756
2757 bool Paragraph::isSeparator(pos_type pos) const
2758 {
2759         //FIXME: Are we sure this can be the only separator?
2760         return d->text_[pos] == ' ';
2761 }
2762
2763
2764 void Paragraph::deregisterWords()
2765 {
2766         Private::Words::const_iterator it;
2767         WordList & wl = theWordList();
2768         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2769                 wl.remove(*it);
2770         d->words_.clear();
2771 }
2772
2773
2774 void Paragraph::collectWords(CursorSlice const & sl)
2775 {
2776         // find new words
2777         bool inword = false;
2778
2779         //lyxerr << "Words: ";
2780         pos_type n = size();
2781         for (pos_type pos = 0; pos != n; ++pos) {
2782                 if (isDeleted(pos))
2783                         continue;
2784
2785                 if (!isLetter(pos)) {
2786                         inword = false;
2787                         continue;
2788                 }
2789
2790                 if (inword)
2791                         continue;
2792
2793                 inword = true;
2794                 CursorSlice from = sl;
2795                 CursorSlice to = sl;
2796                 from.pos() = pos;
2797                 to.pos() = pos;
2798                 from.text()->getWord(from, to, WHOLE_WORD);
2799                 if (to.pos() - from.pos() < 6)
2800                         continue;
2801                 docstring word = asString(from.pos(), to.pos(), false);
2802                 d->words_.insert(word);
2803                 //lyxerr << word << " ";
2804         }
2805         //lyxerr << std::endl;
2806 }
2807
2808
2809 void Paragraph::registerWords()
2810 {
2811         Private::Words::const_iterator it;
2812         WordList & wl = theWordList();
2813         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2814                 wl.insert(*it);
2815 }
2816
2817
2818 void Paragraph::updateWords(CursorSlice const & sl)
2819 {
2820         LASSERT(&sl.paragraph() == this, /**/);
2821         deregisterWords();
2822         collectWords(sl);
2823         registerWords();
2824 }
2825
2826 } // namespace lyx