]> git.lyx.org Git - features.git/blob - src/Paragraph.cpp
21b02b8a50ed79ed3d87a394bbb74e14750babed
[features.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 #include <vector>
61
62 using std::endl;
63 using std::string;
64 using std::ostream;
65
66 namespace lyx {
67
68 using support::contains;
69 using support::prefixIs;
70 using support::suffixIs;
71 using support::rsplit;
72 using support::rtrim;
73
74 namespace {
75 /// Inset identifier (above 0x10ffff, for ucs-4)
76 char_type const META_INSET = 0x200001;
77 };
78
79 /////////////////////////////////////////////////////////////////////
80 //
81 // Paragraph::Private
82 //
83 /////////////////////////////////////////////////////////////////////
84
85 class Paragraph::Private
86 {
87 public:
88         ///
89         Private(Paragraph * owner);
90         /// "Copy constructor"
91         Private(Private const &, Paragraph * owner);
92
93         ///
94         void insertChar(pos_type pos, char_type c, Change const & change);
95
96         /// Output the surrogate pair formed by \p c and \p next to \p os.
97         /// \return the number of characters written.
98         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
99                                Encoding const &);
100
101         /// Output a space in appropriate formatting (or a surrogate pair
102         /// if the next character is a combining character).
103         /// \return whether a surrogate pair was output.
104         bool simpleTeXBlanks(Encoding const &,
105                              odocstream &, TexRow & texrow,
106                              pos_type i,
107                              unsigned int & column,
108                              Font const & font,
109                              Layout const & style);
110
111         /// Output consecutive known unicode chars, belonging to the same
112         /// language as specified by \p preamble, to \p os starting from \p c.
113         /// \return the number of characters written.
114         int knownLangChars(odocstream & os, char_type c, string & preamble,
115                            Change &, Encoding const &, pos_type &);
116
117         /// This could go to ParagraphParameters if we want to.
118         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
119                               bool) const;
120
121         /// This could go to ParagraphParameters if we want to.
122         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
123                             bool) const;
124
125         ///
126         void latexInset(Buffer const &, BufferParams const &,
127                                    odocstream &,
128                                    TexRow & texrow, OutputParams &,
129                                    Font & running_font,
130                                    Font & basefont,
131                                    Font const & outerfont,
132                                    bool & open_font,
133                                    Change & running_change,
134                                    Layout const & style,
135                                    pos_type & i,
136                                    unsigned int & column);
137
138         ///
139         void latexSpecialChar(
140                                    odocstream & os,
141                                    OutputParams & runparams,
142                                    Font & running_font,
143                                    Change & running_change,
144                                    Layout const & style,
145                                    pos_type & i,
146                                    unsigned int & column);
147
148         ///
149         bool latexSpecialT1(
150                 char_type const c,
151                 odocstream & os,
152                 pos_type & i,
153                 unsigned int & column);
154         ///
155         bool latexSpecialTypewriter(
156                 char_type const c,
157                 odocstream & os,
158                 pos_type & i,
159                 unsigned int & column);
160         ///
161         bool latexSpecialPhrase(
162                 odocstream & os,
163                 pos_type & i,
164                 unsigned int & column);
165
166         ///
167         void validate(LaTeXFeatures & features,
168                       Layout const & layout) const;
169
170         ///
171         pos_type size() const { return owner_->size(); }
172
173         /// match a string against a particular point in the paragraph
174         bool isTextAt(std::string const & str, pos_type pos) const;
175         
176         /// Which Paragraph owns us?
177         Paragraph * owner_;
178
179         /// In which Inset?
180         Inset * inset_owner_;
181
182         ///
183         FontList fontlist_;
184
185         ///
186         unsigned int id_;
187         ///
188         static unsigned int paragraph_id;
189         ///
190         ParagraphParameters params_;
191
192         /// for recording and looking up changes
193         Changes changes_;
194
195         ///
196         InsetList insetlist_;
197
198         ///
199         LayoutPtr layout_;
200
201         /// end of label
202         pos_type begin_of_body_;
203
204         typedef std::vector<char_type> TextContainer;
205         ///
206         TextContainer text_;
207 };
208
209
210
211
212 using std::endl;
213 using std::upper_bound;
214 using std::lower_bound;
215 using std::string;
216
217
218 // Initialization of the counter for the paragraph id's,
219 unsigned int Paragraph::Private::paragraph_id = 0;
220
221 namespace {
222
223 struct special_phrase {
224         string phrase;
225         docstring macro;
226         bool builtin;
227 };
228
229 special_phrase const special_phrases[] = {
230         { "LyX", from_ascii("\\protect\\LyX{}"), false },
231         { "TeX", from_ascii("\\protect\\TeX{}"), true },
232         { "LaTeX2e", from_ascii("\\protect\\LaTeXe{}"), true },
233         { "LaTeX", from_ascii("\\protect\\LaTeX{}"), true },
234 };
235
236 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
237
238 } // namespace anon
239
240
241 Paragraph::Private::Private(Paragraph * owner)
242         : owner_(owner), inset_owner_(0), begin_of_body_(0)
243 {
244         id_ = paragraph_id++;
245         text_.reserve(100);
246 }
247
248
249 Paragraph::Private::Private(Private const & p, Paragraph * owner)
250         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_), 
251           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
252           layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
253 {
254         id_ = paragraph_id++;
255 }
256
257
258 bool Paragraph::isChanged(pos_type start, pos_type end) const
259 {
260         BOOST_ASSERT(start >= 0 && start <= size());
261         BOOST_ASSERT(end > start && end <= size() + 1);
262
263         return d->changes_.isChanged(start, end);
264 }
265
266
267 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
268         // keep the logic here in sync with the logic of eraseChars()
269
270         if (!trackChanges) {
271                 return true;
272         }
273
274         Change change = d->changes_.lookup(size());
275
276         return change.type == Change::INSERTED && change.author == 0;
277 }
278
279
280 void Paragraph::setChange(Change const & change)
281 {
282         // beware of the imaginary end-of-par character!
283         d->changes_.set(change, 0, size() + 1);
284
285         /*
286          * Propagate the change recursively - but not in case of DELETED!
287          *
288          * Imagine that your co-author makes changes in an existing inset. He
289          * sends your document to you and you come to the conclusion that the
290          * inset should go completely. If you erase it, LyX must not delete all
291          * text within the inset. Otherwise, the change tracked insertions of
292          * your co-author get lost and there is no way to restore them later.
293          *
294          * Conclusion: An inset's content should remain untouched if you delete it
295          */
296
297         if (change.type != Change::DELETED) {
298                 for (pos_type pos = 0; pos < size(); ++pos) {
299                         if (isInset(pos))
300                                 getInset(pos)->setChange(change);
301                 }
302         }
303 }
304
305
306 void Paragraph::setChange(pos_type pos, Change const & change)
307 {
308         BOOST_ASSERT(pos >= 0 && pos <= size());
309
310         d->changes_.set(change, pos);
311
312         // see comment in setChange(Change const &) above
313
314         if (change.type != Change::DELETED &&
315             pos < size() && isInset(pos)) {
316                 getInset(pos)->setChange(change);
317         }
318 }
319
320
321 Change const & Paragraph::lookupChange(pos_type pos) const
322 {
323         BOOST_ASSERT(pos >= 0 && pos <= size());
324
325         return d->changes_.lookup(pos);
326 }
327
328
329 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
330                 pos_type end)
331 {
332         BOOST_ASSERT(start >= 0 && start <= size());
333         BOOST_ASSERT(end > start && end <= size() + 1);
334
335         for (pos_type pos = start; pos < end; ++pos) {
336                 switch (lookupChange(pos).type) {
337                         case Change::UNCHANGED:
338                                 // accept changes in nested inset
339                                 if (pos < size() && isInset(pos))
340                                         getInset(pos)->acceptChanges(bparams);
341
342                                 break;
343
344                         case Change::INSERTED:
345                                 d->changes_.set(Change(Change::UNCHANGED), pos);
346                                 // also accept changes in nested inset
347                                 if (pos < size() && isInset(pos)) {
348                                         getInset(pos)->acceptChanges(bparams);
349                                 }
350                                 break;
351
352                         case Change::DELETED:
353                                 // Suppress access to non-existent
354                                 // "end-of-paragraph char"
355                                 if (pos < size()) {
356                                         eraseChar(pos, false);
357                                         --end;
358                                         --pos;
359                                 }
360                                 break;
361                 }
362
363         }
364 }
365
366
367 void Paragraph::rejectChanges(BufferParams const & bparams,
368                 pos_type start, pos_type end)
369 {
370         BOOST_ASSERT(start >= 0 && start <= size());
371         BOOST_ASSERT(end > start && end <= size() + 1);
372
373         for (pos_type pos = start; pos < end; ++pos) {
374                 switch (lookupChange(pos).type) {
375                         case Change::UNCHANGED:
376                                 // reject changes in nested inset
377                                 if (pos < size() && isInset(pos)) {
378                                         getInset(pos)->rejectChanges(bparams);
379                                 }
380                                 break;
381
382                         case Change::INSERTED:
383                                 // Suppress access to non-existent
384                                 // "end-of-paragraph char"
385                                 if (pos < size()) {
386                                         eraseChar(pos, false);
387                                         --end;
388                                         --pos;
389                                 }
390                                 break;
391
392                         case Change::DELETED:
393                                 d->changes_.set(Change(Change::UNCHANGED), pos);
394
395                                 // Do NOT reject changes within a deleted inset!
396                                 // There may be insertions of a co-author inside of it!
397
398                                 break;
399                 }
400         }
401 }
402
403
404 void Paragraph::Private::insertChar(pos_type pos, char_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                 text_.push_back(c);
417                 return;
418         }
419
420         text_.insert(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(d->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 (d->text_[pos] == META_INSET)
479                 d->insetlist_.erase(pos);
480
481         d->text_.erase(d->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, char_type c,
508                 char_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 = text_[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             && text_[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                  && (text_[i - 1] == '.'
554                      || text_[i - 1] == '?'
555                      || text_[i - 1] == ':'
556                      || text_[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                                      char_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 = text_[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] != 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         char_type const c = text_[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 = text_[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() || text_[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() && text_[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(text_[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 }
1058
1059
1060 Paragraph::Paragraph(Paragraph const & par)
1061         : itemdepth(par.itemdepth),
1062         d(new Paragraph::Private(*par.d, this))
1063 {
1064 }
1065
1066
1067 Paragraph & Paragraph::operator=(Paragraph const & par)
1068 {
1069         // needed as we will destroy the private part before copying it
1070         if (&par != this) {
1071                 itemdepth = par.itemdepth;
1072
1073                 delete d;
1074                 d = new Private(*par.d, this);
1075         }
1076         return *this;
1077 }
1078
1079
1080 Paragraph::~Paragraph()
1081 {
1082         delete d;
1083 }
1084
1085
1086 void Paragraph::write(Buffer const & buf, ostream & os,
1087                           BufferParams const & bparams,
1088                           depth_type & dth) const
1089 {
1090         // The beginning or end of a deeper (i.e. nested) area?
1091         if (dth != params().depth()) {
1092                 if (params().depth() > dth) {
1093                         while (params().depth() > dth) {
1094                                 os << "\n\\begin_deeper";
1095                                 ++dth;
1096                         }
1097                 } else {
1098                         while (params().depth() < dth) {
1099                                 os << "\n\\end_deeper";
1100                                 --dth;
1101                         }
1102                 }
1103         }
1104
1105         // First write the layout
1106         os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1107
1108         params().write(os);
1109
1110         Font font1(Font::ALL_INHERIT, bparams.language);
1111
1112         Change running_change = Change(Change::UNCHANGED);
1113
1114         int column = 0;
1115         for (pos_type i = 0; i <= size(); ++i) {
1116
1117                 Change change = lookupChange(i);
1118                 Changes::lyxMarkChange(os, column, running_change, change);
1119                 running_change = change;
1120
1121                 if (i == size())
1122                         break;
1123
1124                 // Write font changes
1125                 Font font2 = getFontSettings(bparams, i);
1126                 if (font2 != font1) {
1127                         font2.lyxWriteChanges(font1, os);
1128                         column = 0;
1129                         font1 = font2;
1130                 }
1131
1132                 char_type const c = d->text_[i];
1133                 switch (c) {
1134                 case META_INSET:
1135                 {
1136                         Inset const * inset = getInset(i);
1137                         if (inset)
1138                                 if (inset->directWrite()) {
1139                                         // international char, let it write
1140                                         // code directly so it's shorter in
1141                                         // the file
1142                                         inset->write(buf, os);
1143                                 } else {
1144                                         if (i)
1145                                                 os << '\n';
1146                                         os << "\\begin_inset ";
1147                                         inset->write(buf, os);
1148                                         os << "\n\\end_inset\n\n";
1149                                         column = 0;
1150                                 }
1151                 }
1152                 break;
1153                 case '\\':
1154                         os << "\n\\backslash\n";
1155                         column = 0;
1156                         break;
1157                 case '.':
1158                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1159                                 os << ".\n";
1160                                 column = 0;
1161                         } else
1162                                 os << '.';
1163                         break;
1164                 default:
1165                         if ((column > 70 && c == ' ')
1166                             || column > 79) {
1167                                 os << '\n';
1168                                 column = 0;
1169                         }
1170                         // this check is to amend a bug. LyX sometimes
1171                         // inserts '\0' this could cause problems.
1172                         if (c != '\0') {
1173                                 std::vector<char> tmp = ucs4_to_utf8(c);
1174                                 tmp.push_back('\0');
1175                                 os << &tmp[0];
1176                         } else
1177                                 lyxerr << "ERROR (Paragraph::writeFile):"
1178                                         " NULL char in structure." << endl;
1179                         ++column;
1180                         break;
1181                 }
1182         }
1183
1184         os << "\n\\end_layout\n";
1185 }
1186
1187
1188 void Paragraph::validate(LaTeXFeatures & features) const
1189 {
1190         d->validate(features, *layout());
1191 }
1192
1193
1194 void Paragraph::insert(pos_type start, docstring const & str,
1195                        Font const & font, Change const & change)
1196 {
1197         for (size_t i = 0, n = str.size(); i != n ; ++i)
1198                 insertChar(start + i, str[i], font, change);
1199 }
1200
1201
1202 void Paragraph::appendChar(char_type c, Font const & font,
1203                 Change const & change)
1204 {
1205         // track change
1206         d->changes_.insert(change, d->text_.size());
1207         // when appending characters, no need to update tables
1208         d->text_.push_back(c);
1209         setFont(d->text_.size() - 1, font);
1210 }
1211
1212
1213 void Paragraph::appendString(docstring const & s, Font const & font,
1214                 Change const & change)
1215 {
1216         size_t end = s.size();
1217         size_t oldsize = d->text_.size();
1218         size_t newsize = oldsize + end;
1219         size_t capacity = d->text_.capacity();
1220         if (newsize >= capacity)
1221                 d->text_.reserve(std::max(capacity + 100, newsize));
1222
1223         // FIXME: Optimize this!
1224         for (pos_type i = 0; i != end; ++i) {
1225                 // track change
1226                 d->changes_.insert(change, i);
1227                 // when appending characters, no need to update tables
1228                 d->text_.push_back(s[i]);
1229         }
1230         d->fontlist_.setRange(oldsize, newsize, font);
1231 }
1232
1233
1234 void Paragraph::insertChar(pos_type pos, char_type c,
1235                            bool trackChanges)
1236 {
1237         d->insertChar(pos, c, Change(trackChanges ?
1238                            Change::INSERTED : Change::UNCHANGED));
1239 }
1240
1241
1242 void Paragraph::insertChar(pos_type pos, char_type c,
1243                            Font const & font, bool trackChanges)
1244 {
1245         d->insertChar(pos, c, Change(trackChanges ?
1246                            Change::INSERTED : Change::UNCHANGED));
1247         setFont(pos, font);
1248 }
1249
1250
1251 void Paragraph::insertChar(pos_type pos, char_type c,
1252                            Font const & font, Change const & change)
1253 {
1254         d->insertChar(pos, c, change);
1255         setFont(pos, font);
1256 }
1257
1258
1259 void Paragraph::insertInset(pos_type pos, Inset * inset,
1260                             Font const & font, Change const & change)
1261 {
1262         insertInset(pos, inset, change);
1263         // Set the font/language of the inset...
1264         setFont(pos, font);
1265 }
1266
1267
1268 bool Paragraph::insetAllowed(InsetCode code)
1269 {
1270         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1271 }
1272
1273
1274 // Gets uninstantiated font setting at position.
1275 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1276                                          pos_type pos) const
1277 {
1278         if (pos > size()) {
1279                 lyxerr << " pos: " << pos << " size: " << size() << endl;
1280                 BOOST_ASSERT(pos <= size());
1281         }
1282
1283         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1284         if (cit != d->fontlist_.end())
1285                 return cit->font();
1286
1287         if (pos == size() && !empty())
1288                 return getFontSettings(bparams, pos - 1);
1289
1290         return Font(Font::ALL_INHERIT, getParLanguage(bparams));
1291 }
1292
1293
1294 FontSpan Paragraph::fontSpan(pos_type pos) const
1295 {
1296         BOOST_ASSERT(pos <= size());
1297         pos_type start = 0;
1298
1299         FontList::const_iterator cit = d->fontlist_.begin();
1300         FontList::const_iterator end = d->fontlist_.end();
1301         for (; cit != end; ++cit) {
1302                 if (cit->pos() >= pos) {
1303                         if (pos >= beginOfBody())
1304                                 return FontSpan(std::max(start, beginOfBody()),
1305                                                 cit->pos());
1306                         else
1307                                 return FontSpan(start,
1308                                                 std::min(beginOfBody() - 1,
1309                                                          cit->pos()));
1310                 }
1311                 start = cit->pos() + 1;
1312         }
1313
1314         // This should not happen, but if so, we take no chances.
1315         //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1316         //      << endl;
1317         return FontSpan(pos, pos);
1318 }
1319
1320
1321 // Gets uninstantiated font setting at position 0
1322 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1323 {
1324         if (!empty() && !d->fontlist_.empty())
1325                 return d->fontlist_.begin()->font();
1326
1327         return Font(Font::ALL_INHERIT, bparams.language);
1328 }
1329
1330
1331 // Gets the fully instantiated font at a given position in a paragraph
1332 // This is basically the same function as Text::GetFont() in text2.cpp.
1333 // The difference is that this one is used for generating the LaTeX file,
1334 // and thus cosmetic "improvements" are disallowed: This has to deliver
1335 // the true picture of the buffer. (Asger)
1336 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1337                                  Font const & outerfont) const
1338 {
1339         BOOST_ASSERT(pos >= 0);
1340
1341         Font font = getFontSettings(bparams, pos);
1342
1343         pos_type const body_pos = beginOfBody();
1344         if (pos < body_pos)
1345                 font.realize(d->layout_->labelfont);
1346         else
1347                 font.realize(d->layout_->font);
1348
1349         font.realize(outerfont);
1350         font.realize(bparams.getFont());
1351
1352         return font;
1353 }
1354
1355
1356 Font const Paragraph::getLabelFont
1357         (BufferParams const & bparams, Font const & outerfont) const
1358 {
1359         Font tmpfont = layout()->labelfont;
1360         tmpfont.setLanguage(getParLanguage(bparams));
1361         tmpfont.realize(outerfont);
1362         tmpfont.realize(bparams.getFont());
1363         return tmpfont;
1364 }
1365
1366
1367 Font const Paragraph::getLayoutFont
1368         (BufferParams const & bparams, Font const & outerfont) const
1369 {
1370         Font tmpfont = layout()->font;
1371         tmpfont.setLanguage(getParLanguage(bparams));
1372         tmpfont.realize(outerfont);
1373         tmpfont.realize(bparams.getFont());
1374         return tmpfont;
1375 }
1376
1377
1378 /// Returns the height of the highest font in range
1379 Font_size Paragraph::highestFontInRange
1380         (pos_type startpos, pos_type endpos, Font_size def_size) const
1381 {
1382         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1383 }
1384
1385
1386 char_type
1387 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1388 {
1389         char_type c = d->text_[pos];
1390         if (!lyxrc.rtl_support)
1391                 return c;
1392
1393         char_type uc = c;
1394         switch (c) {
1395         case '(':
1396                 uc = ')';
1397                 break;
1398         case ')':
1399                 uc = '(';
1400                 break;
1401         case '[':
1402                 uc = ']';
1403                 break;
1404         case ']':
1405                 uc = '[';
1406                 break;
1407         case '{':
1408                 uc = '}';
1409                 break;
1410         case '}':
1411                 uc = '{';
1412                 break;
1413         case '<':
1414                 uc = '>';
1415                 break;
1416         case '>':
1417                 uc = '<';
1418                 break;
1419         }
1420         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1421                 return uc;
1422         else
1423                 return c;
1424 }
1425
1426
1427 void Paragraph::setFont(pos_type pos, Font const & font)
1428 {
1429         BOOST_ASSERT(pos <= size());
1430
1431         // First, reduce font against layout/label font
1432         // Update: The setCharFont() routine in text2.cpp already
1433         // reduces font, so we don't need to do that here. (Asger)
1434         
1435         d->fontlist_.set(pos, font);
1436 }
1437
1438
1439 void Paragraph::makeSameLayout(Paragraph const & par)
1440 {
1441         layout(par.layout());
1442         // move to pimpl?
1443         d->params_ = par.params();
1444 }
1445
1446
1447 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1448 {
1449         if (isFreeSpacing())
1450                 return false;
1451
1452         int pos = 0;
1453         int count = 0;
1454
1455         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1456                 if (eraseChar(pos, trackChanges))
1457                         ++count;
1458                 else
1459                         ++pos;
1460         }
1461
1462         return count > 0 || pos > 0;
1463 }
1464
1465
1466 bool Paragraph::hasSameLayout(Paragraph const & par) const
1467 {
1468         return par.layout() == layout() && d->params_.sameLayout(par.params());
1469 }
1470
1471
1472 depth_type Paragraph::getDepth() const
1473 {
1474         return params().depth();
1475 }
1476
1477
1478 depth_type Paragraph::getMaxDepthAfter() const
1479 {
1480         if (layout()->isEnvironment())
1481                 return params().depth() + 1;
1482         else
1483                 return params().depth();
1484 }
1485
1486
1487 char Paragraph::getAlign() const
1488 {
1489         if (params().align() == LYX_ALIGN_LAYOUT)
1490                 return layout()->align;
1491         else
1492                 return params().align();
1493 }
1494
1495
1496 docstring const & Paragraph::getLabelstring() const
1497 {
1498         return params().labelString();
1499 }
1500
1501
1502 // the next two functions are for the manual labels
1503 docstring const Paragraph::getLabelWidthString() const
1504 {
1505         if (layout()->margintype == MARGIN_MANUAL)
1506                 return params().labelWidthString();
1507         else
1508                 return _("Senseless with this layout!");
1509 }
1510
1511
1512 void Paragraph::setLabelWidthString(docstring const & s)
1513 {
1514         params().labelWidthString(s);
1515 }
1516
1517
1518 docstring const Paragraph::translateIfPossible(docstring const & s,
1519                 BufferParams const & bparams) const
1520 {
1521         if (!support::isAscii(s) || s.empty()) {
1522                 // This must be a user defined layout. We cannot translate
1523                 // this, since gettext accepts only ascii keys.
1524                 return s;
1525         }
1526         // Probably standard layout, try to translate
1527         Messages & m = getMessages(getParLanguage(bparams)->code());
1528         return m.get(to_ascii(s));
1529 }
1530
1531
1532 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1533                 BufferParams const & bparams, bool process_appendix) const
1534 {
1535         TextClass const & tclass = bparams.getTextClass();
1536
1537         docstring fmt;
1538         if (process_appendix && params().appendix())
1539                 fmt = translateIfPossible(layout->labelstring_appendix(),
1540                         bparams);
1541         else
1542                 fmt = translateIfPossible(layout->labelstring(), bparams);
1543
1544         if (fmt.empty() && layout->labeltype == LABEL_COUNTER 
1545             && !layout->counter.empty())
1546                 fmt = "\\the" + layout->counter;
1547
1548         // handle 'inherited level parts' in 'fmt',
1549         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1550         size_t const i = fmt.find('@', 0);
1551         if (i != docstring::npos) {
1552                 size_t const j = fmt.find('@', i + 1);
1553                 if (j != docstring::npos) {
1554                         docstring parent(fmt, i + 1, j - i - 1);
1555                         docstring label = from_ascii("??");
1556                         if (tclass.hasLayout(parent))
1557                                 docstring label = expandLabel(tclass[parent], bparams,
1558                                                       process_appendix);
1559                         fmt = docstring(fmt, 0, i) + label 
1560                                 + docstring(fmt, j + 1, docstring::npos);
1561                 }
1562         }
1563
1564         return tclass.counters().counterLabel(fmt);
1565 }
1566
1567
1568 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1569 {
1570         layout(new_layout);
1571         LyXAlignment const oldAlign = params().align();
1572         
1573         if (!(oldAlign & layout()->alignpossible)) {
1574                 frontend::Alert::warning(_("Alignment not permitted"), 
1575                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1576                 params().align(LYX_ALIGN_LAYOUT);
1577         }
1578 }
1579
1580
1581 pos_type Paragraph::beginOfBody() const
1582 {
1583         return d->begin_of_body_;
1584 }
1585
1586
1587 void Paragraph::setBeginOfBody()
1588 {
1589         if (layout()->labeltype != LABEL_MANUAL) {
1590                 d->begin_of_body_ = 0;
1591                 return;
1592         }
1593
1594         // Unroll the first two cycles of the loop
1595         // and remember the previous character to
1596         // remove unnecessary getChar() calls
1597         pos_type i = 0;
1598         pos_type end = size();
1599         if (i < end && !isNewline(i)) {
1600                 ++i;
1601                 char_type previous_char = 0;
1602                 char_type temp = 0;
1603                 if (i < end) {
1604                         previous_char = d->text_[i];
1605                         if (!isNewline(i)) {
1606                                 ++i;
1607                                 while (i < end && previous_char != ' ') {
1608                                         temp = d->text_[i];
1609                                         if (isNewline(i))
1610                                                 break;
1611                                         ++i;
1612                                         previous_char = temp;
1613                                 }
1614                         }
1615                 }
1616         }
1617
1618         d->begin_of_body_ = i;
1619 }
1620
1621
1622 InsetBibitem * Paragraph::bibitem() const
1623 {
1624         if (!d->insetlist_.empty()) {
1625                 Inset * inset = d->insetlist_.begin()->inset;
1626                 if (inset->lyxCode() == BIBITEM_CODE)
1627                         return static_cast<InsetBibitem *>(inset);
1628         }
1629         return 0;
1630 }
1631
1632
1633 bool Paragraph::forceDefaultParagraphs() const
1634 {
1635         return inInset() && inInset()->forceDefaultParagraphs(0);
1636 }
1637
1638
1639 namespace {
1640
1641 // paragraphs inside floats need different alignment tags to avoid
1642 // unwanted space
1643
1644 bool noTrivlistCentering(InsetCode code)
1645 {
1646         return code == FLOAT_CODE || code == WRAP_CODE;
1647 }
1648
1649
1650 string correction(string const & orig)
1651 {
1652         if (orig == "flushleft")
1653                 return "raggedright";
1654         if (orig == "flushright")
1655                 return "raggedleft";
1656         if (orig == "center")
1657                 return "centering";
1658         return orig;
1659 }
1660
1661
1662 string const corrected_env(string const & suffix, string const & env,
1663         InsetCode code)
1664 {
1665         string output = suffix + "{";
1666         if (noTrivlistCentering(code))
1667                 output += correction(env);
1668         else
1669                 output += env;
1670         output += "}";
1671         if (suffix == "\\begin")
1672                 output += "\n";
1673         return output;
1674 }
1675
1676
1677 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1678 {
1679         if (!contains(str, "\n"))
1680                 column += str.size();
1681         else {
1682                 string tmp;
1683                 texrow.newline();
1684                 column = rsplit(str, tmp, '\n').size();
1685         }
1686 }
1687
1688 } // namespace anon
1689
1690
1691 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1692                                  odocstream & os, TexRow & texrow,
1693                                  bool moving_arg) const
1694 {
1695         int column = 0;
1696
1697         if (params_.noindent()) {
1698                 os << "\\noindent ";
1699                 column += 10;
1700         }
1701         
1702         LyXAlignment const curAlign = params_.align();
1703
1704         if (curAlign == layout_->align)
1705                 return column;
1706
1707         switch (curAlign) {
1708         case LYX_ALIGN_NONE:
1709         case LYX_ALIGN_BLOCK:
1710         case LYX_ALIGN_LAYOUT:
1711         case LYX_ALIGN_SPECIAL:
1712                 break;
1713         case LYX_ALIGN_LEFT:
1714         case LYX_ALIGN_RIGHT:
1715         case LYX_ALIGN_CENTER:
1716                 if (moving_arg) {
1717                         os << "\\protect";
1718                         column += 8;
1719                 }
1720                 break;
1721         }
1722
1723         switch (curAlign) {
1724         case LYX_ALIGN_NONE:
1725         case LYX_ALIGN_BLOCK:
1726         case LYX_ALIGN_LAYOUT:
1727         case LYX_ALIGN_SPECIAL:
1728                 break;
1729         case LYX_ALIGN_LEFT: {
1730                 string output;
1731                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1732                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1733                 else
1734                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1735                 os << from_ascii(output);
1736                 adjust_row_column(output, texrow, column);
1737                 break;
1738         } case LYX_ALIGN_RIGHT: {
1739                 string output;
1740                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1741                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1742                 else
1743                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1744                 os << from_ascii(output);
1745                 adjust_row_column(output, texrow, column);
1746                 break;
1747         } case LYX_ALIGN_CENTER: {
1748                 string output;
1749                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1750                 os << from_ascii(output);
1751                 adjust_row_column(output, texrow, column);
1752                 break;
1753         }
1754         }
1755
1756         return column;
1757 }
1758
1759
1760 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1761                                odocstream & os, TexRow & texrow,
1762                                bool moving_arg) const
1763 {
1764         int column = 0;
1765
1766         switch (params_.align()) {
1767         case LYX_ALIGN_NONE:
1768         case LYX_ALIGN_BLOCK:
1769         case LYX_ALIGN_LAYOUT:
1770         case LYX_ALIGN_SPECIAL:
1771                 break;
1772         case LYX_ALIGN_LEFT:
1773         case LYX_ALIGN_RIGHT:
1774         case LYX_ALIGN_CENTER:
1775                 if (moving_arg) {
1776                         os << "\\protect";
1777                         column = 8;
1778                 }
1779                 break;
1780         }
1781
1782         switch (params_.align()) {
1783         case LYX_ALIGN_NONE:
1784         case LYX_ALIGN_BLOCK:
1785         case LYX_ALIGN_LAYOUT:
1786         case LYX_ALIGN_SPECIAL:
1787                 break;
1788         case LYX_ALIGN_LEFT: {
1789                 string output;
1790                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1791                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1792                 else
1793                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1794                 os << from_ascii(output);
1795                 adjust_row_column(output, texrow, column);
1796                 break;
1797         } case LYX_ALIGN_RIGHT: {
1798                 string output;
1799                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1800                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1801                 else
1802                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1803                 os << from_ascii(output);
1804                 adjust_row_column(output, texrow, column);
1805                 break;
1806         } case LYX_ALIGN_CENTER: {
1807                 string output;
1808                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1809                 os << from_ascii(output);
1810                 adjust_row_column(output, texrow, column);
1811                 break;
1812         }
1813         }
1814
1815         return column;
1816 }
1817
1818
1819 // This one spits out the text of the paragraph
1820 bool Paragraph::latex(Buffer const & buf,
1821                                 BufferParams const & bparams,
1822                                 Font const & outerfont,
1823                                 odocstream & os, TexRow & texrow,
1824                                 OutputParams const & runparams) const
1825 {
1826         LYXERR(Debug::LATEX) << "SimpleTeXOnePar...     " << this << endl;
1827
1828         bool return_value = false;
1829
1830         LayoutPtr style;
1831
1832         // well we have to check if we are in an inset with unlimited
1833         // length (all in one row) if that is true then we don't allow
1834         // any special options in the paragraph and also we don't allow
1835         // any environment other than the default layout of the text class
1836         // to be valid!
1837         bool asdefault = forceDefaultParagraphs();
1838
1839         if (asdefault) {
1840                 style = bparams.getTextClass().defaultLayout();
1841         } else {
1842                 style = layout();
1843         }
1844
1845         // Current base font for all inherited font changes, without any
1846         // change caused by an individual character, except for the language:
1847         // It is set to the language of the first character.
1848         // As long as we are in the label, this font is the base font of the
1849         // label. Before the first body character it is set to the base font
1850         // of the body.
1851         Font basefont;
1852
1853         // Maybe we have to create a optional argument.
1854         pos_type body_pos = beginOfBody();
1855         unsigned int column = 0;
1856
1857         if (body_pos > 0) {
1858                 // the optional argument is kept in curly brackets in
1859                 // case it contains a ']'
1860                 os << "[{";
1861                 column += 2;
1862                 basefont = getLabelFont(bparams, outerfont);
1863         } else {
1864                 basefont = getLayoutFont(bparams, outerfont);
1865         }
1866
1867         // Which font is currently active?
1868         Font running_font(basefont);
1869         // Do we have an open font change?
1870         bool open_font = false;
1871
1872         Change runningChange = Change(Change::UNCHANGED);
1873
1874         texrow.start(id(), 0);
1875
1876         // if the paragraph is empty, the loop will not be entered at all
1877         if (empty()) {
1878                 if (style->isCommand()) {
1879                         os << '{';
1880                         ++column;
1881                 }
1882                 if (!asdefault)
1883                         column += d->startTeXParParams(bparams, os, texrow,
1884                                                     runparams.moving_arg);
1885         }
1886
1887         for (pos_type i = 0; i < size(); ++i) {
1888                 // First char in paragraph or after label?
1889                 if (i == body_pos) {
1890                         if (body_pos > 0) {
1891                                 if (open_font) {
1892                                         column += running_font.latexWriteEndChanges(
1893                                                 os, bparams, runparams,
1894                                                 basefont, basefont);
1895                                         open_font = false;
1896                                 }
1897                                 basefont = getLayoutFont(bparams, outerfont);
1898                                 running_font = basefont;
1899
1900                                 column += Changes::latexMarkChange(os, bparams,
1901                                                 runningChange, Change(Change::UNCHANGED));
1902                                 runningChange = Change(Change::UNCHANGED);
1903
1904                                 os << "}] ";
1905                                 column +=3;
1906                         }
1907                         if (style->isCommand()) {
1908                                 os << '{';
1909                                 ++column;
1910                         }
1911
1912                         if (!asdefault)
1913                                 column += d->startTeXParParams(bparams, os,
1914                                                             texrow,
1915                                                             runparams.moving_arg);
1916                 }
1917
1918                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1919                                                                  : lookupChange(i);
1920
1921                 if (bparams.outputChanges && runningChange != change) {
1922                         if (open_font) {
1923                                 column += running_font.latexWriteEndChanges(
1924                                                 os, bparams, runparams, basefont, basefont);
1925                                 open_font = false;
1926                         }
1927                         basefont = getLayoutFont(bparams, outerfont);
1928                         running_font = basefont;
1929
1930                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1931                         runningChange = change;
1932                 }
1933
1934                 // do not output text which is marked deleted
1935                 // if change tracking output is disabled
1936                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1937                         continue;
1938                 }
1939
1940                 ++column;
1941
1942                 // Fully instantiated font
1943                 Font const font = getFont(bparams, i, outerfont);
1944
1945                 Font const last_font = running_font;
1946
1947                 // Do we need to close the previous font?
1948                 if (open_font &&
1949                     (font != running_font ||
1950                      font.language() != running_font.language()))
1951                 {
1952                         column += running_font.latexWriteEndChanges(
1953                                         os, bparams, runparams, basefont,
1954                                         (i == body_pos-1) ? basefont : font);
1955                         running_font = basefont;
1956                         open_font = false;
1957                 }
1958
1959                 // Switch file encoding if necessary (and allowed)
1960                 if (!runparams.verbatim && 
1961                     runparams.encoding->package() == Encoding::inputenc &&
1962                     font.language()->encoding()->package() == Encoding::inputenc) {
1963                         std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1964                                         runparams.moving_arg, *(runparams.encoding),
1965                                         *(font.language()->encoding()));
1966                         if (enc_switch.first) {
1967                                 column += enc_switch.second;
1968                                 runparams.encoding = font.language()->encoding();
1969                         }
1970                 }
1971
1972                 char_type const c = d->text_[i];
1973
1974                 // Do we need to change font?
1975                 if ((font != running_font ||
1976                      font.language() != running_font.language()) &&
1977                         i != body_pos - 1)
1978                 {
1979                         odocstringstream ods;
1980                         column += font.latexWriteStartChanges(ods, bparams,
1981                                                               runparams, basefont,
1982                                                               last_font);
1983                         running_font = font;
1984                         open_font = true;
1985                         docstring fontchange = ods.str();
1986                         // check if the fontchange ends with a trailing blank
1987                         // (like "\small " (see bug 3382)
1988                         if (suffixIs(fontchange, ' ') && c == ' ')
1989                                 os << fontchange.substr(0, fontchange.size() - 1) 
1990                                    << from_ascii("{}");
1991                         else
1992                                 os << fontchange;
1993                 }
1994
1995                 if (c == ' ') {
1996                         // FIXME: integrate this case in latexSpecialChar
1997                         // Do not print the separation of the optional argument
1998                         // if style->pass_thru is false. This works because
1999                         // latexSpecialChar ignores spaces if
2000                         // style->pass_thru is false.
2001                         if (i != body_pos - 1) {
2002                                 if (d->simpleTeXBlanks(
2003                                                 *(runparams.encoding), os, texrow,
2004                                                 i, column, font, *style)) {
2005                                         // A surrogate pair was output. We
2006                                         // must not call latexSpecialChar
2007                                         // in this iteration, since it would output
2008                                         // the combining character again.
2009                                         ++i;
2010                                         continue;
2011                                 }
2012                         }
2013                 }
2014
2015                 OutputParams rp = runparams;
2016                 rp.free_spacing = style->free_spacing;
2017                 rp.local_font = &font;
2018                 rp.intitle = style->intitle;
2019
2020                 // Two major modes:  LaTeX or plain
2021                 // Handle here those cases common to both modes
2022                 // and then split to handle the two modes separately.
2023                 if (c == META_INSET)
2024                         d->latexInset(buf, bparams, os,
2025                                         texrow, rp, running_font,
2026                                         basefont, outerfont, open_font,
2027                                         runningChange, *style, i, column);
2028                 else
2029                         d->latexSpecialChar(os, rp, running_font, runningChange,
2030                                 *style, i, column);
2031
2032                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2033                 // comment for encoding member in OutputParams.h)
2034                 runparams.encoding = rp.encoding;
2035         }
2036
2037         // If we have an open font definition, we have to close it
2038         if (open_font) {
2039 #ifdef FIXED_LANGUAGE_END_DETECTION
2040                 if (next_) {
2041                         running_font
2042                                 .latexWriteEndChanges(os, bparams, runparams,
2043                                         basefont,
2044                                         next_->getFont(bparams, 0, outerfont));
2045                 } else {
2046                         running_font.latexWriteEndChanges(os, bparams,
2047                                         runparams, basefont, basefont);
2048                 }
2049 #else
2050 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2051 //FIXME: there as we start another \selectlanguage with the next paragraph if
2052 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2053                 running_font.latexWriteEndChanges(os, bparams, runparams,
2054                                 basefont, basefont);
2055 #endif
2056         }
2057
2058         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2059
2060         // Needed if there is an optional argument but no contents.
2061         if (body_pos > 0 && body_pos == size()) {
2062                 os << "}]~";
2063                 return_value = false;
2064         }
2065
2066         if (!asdefault) {
2067                 column += d->endTeXParParams(bparams, os, texrow,
2068                                           runparams.moving_arg);
2069         }
2070
2071         LYXERR(Debug::LATEX) << "SimpleTeXOnePar...done " << this << endl;
2072         return return_value;
2073 }
2074
2075
2076 namespace {
2077
2078 enum PAR_TAG {
2079         PAR_NONE=0,
2080         TT = 1,
2081         SF = 2,
2082         BF = 4,
2083         IT = 8,
2084         SL = 16,
2085         EM = 32
2086 };
2087
2088
2089 string tag_name(PAR_TAG const & pt) {
2090         switch (pt) {
2091         case PAR_NONE: return "!-- --";
2092         case TT: return "tt";
2093         case SF: return "sf";
2094         case BF: return "bf";
2095         case IT: return "it";
2096         case SL: return "sl";
2097         case EM: return "em";
2098         }
2099         return "";
2100 }
2101
2102
2103 inline
2104 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2105 {
2106         p1 = static_cast<PAR_TAG>(p1 | p2);
2107 }
2108
2109
2110 inline
2111 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2112 {
2113         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2114 }
2115
2116 } // anon
2117
2118
2119 bool Paragraph::emptyTag() const
2120 {
2121         for (pos_type i = 0; i < size(); ++i) {
2122                 if (isInset(i)) {
2123                         Inset const * inset = getInset(i);
2124                         InsetCode lyx_code = inset->lyxCode();
2125                         if (lyx_code != TOC_CODE &&
2126                             lyx_code != INCLUDE_CODE &&
2127                             lyx_code != GRAPHICS_CODE &&
2128                             lyx_code != ERT_CODE &&
2129                             lyx_code != LISTINGS_CODE &&
2130                             lyx_code != FLOAT_CODE &&
2131                             lyx_code != TABULAR_CODE) {
2132                                 return false;
2133                         }
2134                 } else {
2135                         char_type c = d->text_[i];
2136                         if (c != ' ' && c != '\t')
2137                                 return false;
2138                 }
2139         }
2140         return true;
2141 }
2142
2143
2144 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2145 {
2146         for (pos_type i = 0; i < size(); ++i) {
2147                 if (isInset(i)) {
2148                         Inset const * inset = getInset(i);
2149                         InsetCode lyx_code = inset->lyxCode();
2150                         if (lyx_code == LABEL_CODE) {
2151                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2152                                 docstring const & id = il->getParam("name");
2153                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2154                         }
2155                 }
2156
2157         }
2158         return string();
2159 }
2160
2161
2162 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2163 {
2164         pos_type i;
2165         for (i = 0; i < size(); ++i) {
2166                 if (isInset(i)) {
2167                         Inset const * inset = getInset(i);
2168                         inset->docbook(buf, os, runparams);
2169                 } else {
2170                         char_type c = d->text_[i];
2171                         if (c == ' ')
2172                                 break;
2173                         os << sgml::escapeChar(c);
2174                 }
2175         }
2176         return i;
2177 }
2178
2179
2180 bool Paragraph::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2181 {
2182         Font font_old;
2183
2184         for (pos_type i = initial; i < size(); ++i) {
2185                 Font font = getFont(buf.params(), i, outerfont);
2186                 if (isInset(i))
2187                         return false;
2188                 if (i != initial && font != font_old)
2189                         return false;
2190                 font_old = font;
2191         }
2192
2193         return true;
2194 }
2195
2196
2197 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2198                                     odocstream & os,
2199                                     OutputParams const & runparams,
2200                                     Font const & outerfont,
2201                                     pos_type initial) const
2202 {
2203         bool emph_flag = false;
2204
2205         LayoutPtr const & style = layout();
2206         Font font_old =
2207                 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2208
2209         if (style->pass_thru && !onlyText(buf, outerfont, initial))
2210                 os << "]]>";
2211
2212         // parsing main loop
2213         for (pos_type i = initial; i < size(); ++i) {
2214                 Font font = getFont(buf.params(), i, outerfont);
2215
2216                 // handle <emphasis> tag
2217                 if (font_old.emph() != font.emph()) {
2218                         if (font.emph() == Font::ON) {
2219                                 os << "<emphasis>";
2220                                 emph_flag = true;
2221                         } else if (i != initial) {
2222                                 os << "</emphasis>";
2223                                 emph_flag = false;
2224                         }
2225                 }
2226
2227                 if (isInset(i)) {
2228                         Inset const * inset = getInset(i);
2229                         inset->docbook(buf, os, runparams);
2230                 } else {
2231                         char_type c = d->text_[i];
2232
2233                         if (style->pass_thru)
2234                                 os.put(c);
2235                         else
2236                                 os << sgml::escapeChar(c);
2237                 }
2238                 font_old = font;
2239         }
2240
2241         if (emph_flag) {
2242                 os << "</emphasis>";
2243         }
2244
2245         if (style->free_spacing)
2246                 os << '\n';
2247         if (style->pass_thru && !onlyText(buf, outerfont, initial))
2248                 os << "<![CDATA[";
2249 }
2250
2251
2252 bool Paragraph::isHfill(pos_type pos) const
2253 {
2254         return isInset(pos)
2255                 && getInset(pos)->lyxCode() == HFILL_CODE;
2256 }
2257
2258
2259 bool Paragraph::isNewline(pos_type pos) const
2260 {
2261         return isInset(pos)
2262                 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2263 }
2264
2265
2266 bool Paragraph::isLineSeparator(pos_type pos) const
2267 {
2268         char_type const c = d->text_[pos];
2269         return isLineSeparatorChar(c)
2270                 || (c == META_INSET && getInset(pos) &&
2271                 getInset(pos)->isLineSeparator());
2272 }
2273
2274
2275 /// Used by the spellchecker
2276 bool Paragraph::isLetter(pos_type pos) const
2277 {
2278         if (isInset(pos))
2279                 return getInset(pos)->isLetter();
2280         else {
2281                 char_type const c = d->text_[pos];
2282                 return isLetterChar(c) || isDigit(c);
2283         }
2284 }
2285
2286
2287 Language const *
2288 Paragraph::getParLanguage(BufferParams const & bparams) const
2289 {
2290         if (!empty())
2291                 return getFirstFontSettings(bparams).language();
2292         // FIXME: we should check the prev par as well (Lgb)
2293         return bparams.language;
2294 }
2295
2296
2297 bool Paragraph::isRTL(BufferParams const & bparams) const
2298 {
2299         return lyxrc.rtl_support
2300                 && getParLanguage(bparams)->rightToLeft()
2301                 && ownerCode() != ERT_CODE
2302                 && ownerCode() != LISTINGS_CODE;
2303 }
2304
2305
2306 void Paragraph::changeLanguage(BufferParams const & bparams,
2307                                Language const * from, Language const * to)
2308 {
2309         // change language including dummy font change at the end
2310         for (pos_type i = 0; i <= size(); ++i) {
2311                 Font font = getFontSettings(bparams, i);
2312                 if (font.language() == from) {
2313                         font.setLanguage(to);
2314                         setFont(i, font);
2315                 }
2316         }
2317 }
2318
2319
2320 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2321 {
2322         Language const * doc_language = bparams.language;
2323         FontList::const_iterator cit = d->fontlist_.begin();
2324         FontList::const_iterator end = d->fontlist_.end();
2325
2326         for (; cit != end; ++cit)
2327                 if (cit->font().language() != ignore_language &&
2328                     cit->font().language() != latex_language &&
2329                     cit->font().language() != doc_language)
2330                         return true;
2331         return false;
2332 }
2333
2334
2335 // Convert the paragraph to a string.
2336 // Used for building the table of contents
2337 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2338 {
2339         return asString(buffer, 0, size(), label);
2340 }
2341
2342
2343 docstring const Paragraph::asString(Buffer const & buffer,
2344                                  pos_type beg, pos_type end, bool label) const
2345 {
2346
2347         odocstringstream os;
2348
2349         if (beg == 0 && label && !params().labelString().empty())
2350                 os << params().labelString() << ' ';
2351
2352         for (pos_type i = beg; i < end; ++i) {
2353                 char_type const c = d->text_[i];
2354                 if (isPrintable(c))
2355                         os.put(c);
2356                 else if (c == META_INSET)
2357                         getInset(i)->textString(buffer, os);
2358         }
2359
2360         return os.str();
2361 }
2362
2363
2364 void Paragraph::setInsetOwner(Inset * inset)
2365 {
2366         d->inset_owner_ = inset;
2367 }
2368
2369
2370 int Paragraph::id() const
2371 {
2372         return d->id_;
2373 }
2374
2375
2376 LayoutPtr const & Paragraph::layout() const
2377 {
2378         return d->layout_;
2379 }
2380
2381
2382 void Paragraph::layout(LayoutPtr const & new_layout)
2383 {
2384         d->layout_ = new_layout;
2385 }
2386
2387
2388 Inset * Paragraph::inInset() const
2389 {
2390         return d->inset_owner_;
2391 }
2392
2393
2394 InsetCode Paragraph::ownerCode() const
2395 {
2396         return d->inset_owner_ ?
2397                 d->inset_owner_->lyxCode() : NO_CODE;
2398 }
2399
2400
2401 ParagraphParameters & Paragraph::params()
2402 {
2403         return d->params_;
2404 }
2405
2406
2407 ParagraphParameters const & Paragraph::params() const
2408 {
2409         return d->params_;
2410 }
2411
2412
2413 bool Paragraph::isFreeSpacing() const
2414 {
2415         if (layout()->free_spacing)
2416                 return true;
2417
2418         // for now we just need this, later should we need this in some
2419         // other way we can always add a function to Inset too.
2420         return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2421 }
2422
2423
2424 bool Paragraph::allowEmpty() const
2425 {
2426         if (layout()->keepempty)
2427                 return true;
2428         return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2429 }
2430
2431
2432 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2433 {
2434         if (!Encodings::is_arabic(c))
2435                 return c;
2436
2437         char_type prev_char = ' ';
2438         char_type next_char = ' ';
2439
2440         for (pos_type i = pos - 1; i >= 0; --i) {
2441                 char_type const par_char = d->text_[i];
2442                 if (!Encodings::isComposeChar_arabic(par_char)) {
2443                         prev_char = par_char;
2444                         break;
2445                 }
2446         }
2447
2448         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2449                 char_type const par_char = d->text_[i];
2450                 if (!Encodings::isComposeChar_arabic(par_char)) {
2451                         next_char = par_char;
2452                         break;
2453                 }
2454         }
2455
2456         if (Encodings::is_arabic(next_char)) {
2457                 if (Encodings::is_arabic(prev_char) &&
2458                         !Encodings::is_arabic_special(prev_char))
2459                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2460                 else
2461                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2462         } else {
2463                 if (Encodings::is_arabic(prev_char) &&
2464                         !Encodings::is_arabic_special(prev_char))
2465                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2466                 else
2467                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2468         }
2469 }
2470
2471
2472 int Paragraph::checkBiblio(bool track_changes)
2473 {
2474         //FIXME From JS:
2475         //This is getting more and more a mess. ...We really should clean
2476         //up this bibitem issue for 1.6. See also bug 2743.
2477
2478         // Add bibitem insets if necessary
2479         if (layout()->labeltype != LABEL_BIBLIO)
2480                 return 0;
2481
2482         bool hasbibitem = !d->insetlist_.empty()
2483                 // Insist on it being in pos 0
2484                 && d->text_[0] == META_INSET
2485                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2486
2487         docstring oldkey;
2488         docstring oldlabel;
2489
2490         // remove a bibitem in pos != 0
2491         // restore it later in pos 0 if necessary
2492         // (e.g. if a user inserts contents _before_ the item)
2493         // we're assuming there's only one of these, which there
2494         // should be.
2495         int erasedInsetPosition = -1;
2496         InsetList::iterator it = d->insetlist_.begin();
2497         InsetList::iterator end = d->insetlist_.end();
2498         for (; it != end; ++it)
2499                 if (it->inset->lyxCode() == BIBITEM_CODE
2500                     && it->pos > 0) {
2501                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2502                         oldkey = olditem->getParam("key");
2503                         oldlabel = olditem->getParam("label");
2504                         erasedInsetPosition = it->pos;
2505                         eraseChar(erasedInsetPosition, track_changes);
2506                         break;
2507         }
2508
2509         //There was an InsetBibitem at the beginning, and we didn't
2510         //have to erase one.
2511         if (hasbibitem && erasedInsetPosition < 0)
2512                         return 0;
2513
2514         //There was an InsetBibitem at the beginning and we did have to
2515         //erase one. So we give its properties to the beginning inset.
2516         if (hasbibitem) {
2517                 InsetBibitem * inset =
2518                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2519                 if (!oldkey.empty())
2520                         inset->setParam("key", oldkey);
2521                 inset->setParam("label", oldlabel);
2522                 return -erasedInsetPosition;
2523         }
2524
2525         //There was no inset at the beginning, so we need to create one with
2526         //the key and label of the one we erased.
2527         InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2528         // restore values of previously deleted item in this par.
2529         if (!oldkey.empty())
2530                 inset->setParam("key", oldkey);
2531         inset->setParam("label", oldlabel);
2532         insertInset(0, static_cast<Inset *>(inset),
2533                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2534
2535         return 1;
2536 }
2537
2538
2539 void Paragraph::checkAuthors(AuthorList const & authorList)
2540 {
2541         d->changes_.checkAuthors(authorList);
2542 }
2543
2544
2545 bool Paragraph::isUnchanged(pos_type pos) const
2546 {
2547         return lookupChange(pos).type == Change::UNCHANGED;
2548 }
2549
2550
2551 bool Paragraph::isInserted(pos_type pos) const
2552 {
2553         return lookupChange(pos).type == Change::INSERTED;
2554 }
2555
2556
2557 bool Paragraph::isDeleted(pos_type pos) const
2558 {
2559         return lookupChange(pos).type == Change::DELETED;
2560 }
2561
2562
2563 InsetList const & Paragraph::insetList() const
2564 {
2565         return d->insetlist_;
2566 }
2567
2568
2569 Inset * Paragraph::releaseInset(pos_type pos)
2570 {
2571         Inset * inset = d->insetlist_.release(pos);
2572         /// does not honour change tracking!
2573         eraseChar(pos, false);
2574         return inset;
2575 }
2576
2577
2578 Inset * Paragraph::getInset(pos_type pos)
2579 {
2580         return d->insetlist_.get(pos);
2581 }
2582
2583
2584 Inset const * Paragraph::getInset(pos_type pos) const
2585 {
2586         return d->insetlist_.get(pos);
2587 }
2588
2589
2590 int Paragraph::numberOfOptArgs() const
2591 {
2592         int num = 0;
2593         InsetList::const_iterator it = insetList().begin();
2594         InsetList::const_iterator end = insetList().end();
2595         for (; it != end ; ++it) {
2596                 if (it->inset->lyxCode() == OPTARG_CODE)
2597                         ++num;
2598         }
2599         return num;
2600 }
2601
2602
2603 char_type Paragraph::getChar(pos_type pos) const
2604 {
2605         return d->text_[pos];
2606 }
2607
2608
2609 pos_type Paragraph::size() const
2610 {
2611         return d->text_.size();
2612 }
2613
2614
2615 bool Paragraph::empty() const
2616 {
2617         return d->text_.empty();
2618 }
2619
2620
2621 bool Paragraph::isInset(pos_type pos) const
2622 {
2623         return d->text_[pos] == META_INSET;
2624 }
2625
2626
2627 bool Paragraph::isSeparator(pos_type pos) const
2628 {
2629         //FIXME: Are we sure this can be the only separator?
2630         return d->text_[pos] == ' ';
2631 }
2632
2633
2634 } // namespace lyx