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