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