]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
b760c9df0e09d3238d4c483156c1aa08c85c64a2
[lyx.git] / src / Paragraph.cpp
1 /**
2  * \file Paragraph.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Asger Alstrup
7  * \author Lars Gullik Bjønnes
8  * \author Jean-Marc Lasgouttes
9  * \author Angus Leeming
10  * \author John Levon
11  * \author André Pönitz
12  * \author Dekel Tsur
13  * \author Jürgen Vigna
14  *
15  * Full author contact details are available in file CREDITS.
16  */
17
18 #include <config.h>
19
20 #include "Paragraph.h"
21
22 #include "Buffer.h"
23 #include "BufferParams.h"
24 #include "Changes.h"
25 #include "Counters.h"
26 #include "Encoding.h"
27 #include "debug.h"
28 #include "gettext.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Color.h"
33 #include "Layout.h"
34 #include "Length.h"
35 #include "Font.h"
36 #include "FontList.h"
37 #include "LyXRC.h"
38 #include "Messages.h"
39 #include "OutputParams.h"
40 #include "output_latex.h"
41 #include "paragraph_funcs.h"
42 #include "ParagraphParameters.h"
43 #include "sgml.h"
44 #include "TexRow.h"
45 #include "VSpace.h"
46
47 #include "frontends/alert.h"
48 #include "frontends/FontMetrics.h"
49
50 #include "insets/InsetBibitem.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetOptArg.h"
53
54 #include "support/lstrings.h"
55 #include "support/textutils.h"
56 #include "support/convert.h"
57 #include "support/unicode.h"
58
59 #include <sstream>
60 #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::lowercase;
70 using support::prefixIs;
71 using support::suffixIs;
72 using support::rsplit;
73 using support::rtrim;
74 using support::uppercase;
75
76 namespace {
77 /// Inset identifier (above 0x10ffff, for ucs-4)
78 char_type const META_INSET = 0x200001;
79 };
80
81 /////////////////////////////////////////////////////////////////////
82 //
83 // Paragraph::Private
84 //
85 /////////////////////////////////////////////////////////////////////
86
87 class Paragraph::Private
88 {
89 public:
90         ///
91         Private(Paragraph * owner);
92         /// "Copy constructor"
93         Private(Private const &, Paragraph * owner);
94
95         ///
96         void insertChar(pos_type pos, char_type c, Change const & change);
97
98         /// Output the surrogate pair formed by \p c and \p next to \p os.
99         /// \return the number of characters written.
100         int latexSurrogatePair(odocstream & os, char_type c, char_type next,
101                                Encoding const &);
102
103         /// Output a space in appropriate formatting (or a surrogate pair
104         /// if the next character is a combining character).
105         /// \return whether a surrogate pair was output.
106         bool simpleTeXBlanks(Encoding const &,
107                              odocstream &, TexRow & texrow,
108                              pos_type i,
109                              unsigned int & column,
110                              Font const & font,
111                              Layout const & style);
112
113         /// Output consecutive known unicode chars, belonging to the same
114         /// language as specified by \p preamble, to \p os starting from \p c.
115         /// \return the number of characters written.
116         int knownLangChars(odocstream & os, char_type c, string & preamble,
117                            Change &, Encoding const &, pos_type &);
118
119         /// This could go to ParagraphParameters if we want to.
120         int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
121                               bool) const;
122
123         /// This could go to ParagraphParameters if we want to.
124         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
125                             bool) const;
126
127         ///
128         void latexInset(Buffer const &, BufferParams const &,
129                                    odocstream &,
130                                    TexRow & texrow, OutputParams &,
131                                    Font & running_font,
132                                    Font & basefont,
133                                    Font const & outerfont,
134                                    bool & open_font,
135                                    Change & running_change,
136                                    Layout const & style,
137                                    pos_type & i,
138                                    unsigned int & column);
139
140         ///
141         void latexSpecialChar(
142                                    odocstream & os,
143                                    OutputParams & runparams,
144                                    Font & running_font,
145                                    Change & running_change,
146                                    Layout const & style,
147                                    pos_type & i,
148                                    unsigned int & column);
149
150         ///
151         bool latexSpecialT1(
152                 char_type const c,
153                 odocstream & os,
154                 pos_type & i,
155                 unsigned int & column);
156         ///
157         bool latexSpecialTypewriter(
158                 char_type const c,
159                 odocstream & os,
160                 pos_type & i,
161                 unsigned int & column);
162         ///
163         bool latexSpecialPhrase(
164                 odocstream & os,
165                 pos_type & i,
166                 unsigned int & column);
167
168         ///
169         void validate(LaTeXFeatures & features,
170                       Layout const & layout) const;
171
172         /// match a string against a particular point in the paragraph
173         bool isTextAt(std::string const & str, pos_type pos) const;
174         
175         /// Which Paragraph owns us?
176         Paragraph * owner_;
177
178         /// In which Inset?
179         Inset * inset_owner_;
180
181         ///
182         FontList fontlist_;
183
184         ///
185         unsigned int id_;
186         ///
187         static unsigned int paragraph_id;
188         ///
189         ParagraphParameters params_;
190
191         /// for recording and looking up changes
192         Changes changes_;
193
194         ///
195         InsetList insetlist_;
196
197         ///
198         LayoutPtr layout_;
199
200         /// end of label
201         pos_type begin_of_body_;
202
203         typedef docstring TextContainer;
204         ///
205         TextContainer text_;
206 };
207
208
209
210
211 using std::endl;
212 using std::upper_bound;
213 using std::lower_bound;
214 using std::string;
215
216
217 // Initialization of the counter for the paragraph id's,
218 unsigned int Paragraph::Private::paragraph_id = 0;
219
220 namespace {
221
222 struct special_phrase {
223         string phrase;
224         docstring macro;
225         bool builtin;
226 };
227
228 special_phrase const special_phrases[] = {
229         { "LyX", from_ascii("\\protect\\LyX{}"), false },
230         { "TeX", from_ascii("\\protect\\TeX{}"), true },
231         { "LaTeX2e", from_ascii("\\protect\\LaTeXe{}"), true },
232         { "LaTeX", from_ascii("\\protect\\LaTeX{}"), true },
233 };
234
235 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
236
237 } // namespace anon
238
239
240 Paragraph::Private::Private(Paragraph * owner)
241         : owner_(owner), inset_owner_(0), begin_of_body_(0)
242 {
243         id_ = paragraph_id++;
244         text_.reserve(100);
245 }
246
247
248 Paragraph::Private::Private(Private const & p, Paragraph * owner)
249         : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_), 
250           params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
251           layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
252 {
253         id_ = paragraph_id++;
254 }
255
256
257 bool Paragraph::isChanged(pos_type start, pos_type end) const
258 {
259         BOOST_ASSERT(start >= 0 && start <= size());
260         BOOST_ASSERT(end > start && end <= size() + 1);
261
262         return d->changes_.isChanged(start, end);
263 }
264
265
266 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
267         // keep the logic here in sync with the logic of eraseChars()
268
269         if (!trackChanges) {
270                 return true;
271         }
272
273         Change change = d->changes_.lookup(size());
274
275         return change.type == Change::INSERTED && change.author == 0;
276 }
277
278
279 void Paragraph::setChange(Change const & change)
280 {
281         // beware of the imaginary end-of-par character!
282         d->changes_.set(change, 0, size() + 1);
283
284         /*
285          * Propagate the change recursively - but not in case of DELETED!
286          *
287          * Imagine that your co-author makes changes in an existing inset. He
288          * sends your document to you and you come to the conclusion that the
289          * inset should go completely. If you erase it, LyX must not delete all
290          * text within the inset. Otherwise, the change tracked insertions of
291          * your co-author get lost and there is no way to restore them later.
292          *
293          * Conclusion: An inset's content should remain untouched if you delete it
294          */
295
296         if (change.type != Change::DELETED) {
297                 for (pos_type pos = 0; pos < size(); ++pos) {
298                         if (isInset(pos))
299                                 getInset(pos)->setChange(change);
300                 }
301         }
302 }
303
304
305 void Paragraph::setChange(pos_type pos, Change const & change)
306 {
307         BOOST_ASSERT(pos >= 0 && pos <= size());
308
309         d->changes_.set(change, pos);
310
311         // see comment in setChange(Change const &) above
312
313         if (change.type != Change::DELETED &&
314             pos < size() && isInset(pos)) {
315                 getInset(pos)->setChange(change);
316         }
317 }
318
319
320 Change const & Paragraph::lookupChange(pos_type pos) const
321 {
322         BOOST_ASSERT(pos >= 0 && pos <= size());
323
324         return d->changes_.lookup(pos);
325 }
326
327
328 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
329                 pos_type end)
330 {
331         BOOST_ASSERT(start >= 0 && start <= size());
332         BOOST_ASSERT(end > start && end <= size() + 1);
333
334         for (pos_type pos = start; pos < end; ++pos) {
335                 switch (lookupChange(pos).type) {
336                         case Change::UNCHANGED:
337                                 // accept changes in nested inset
338                                 if (pos < size() && isInset(pos))
339                                         getInset(pos)->acceptChanges(bparams);
340
341                                 break;
342
343                         case Change::INSERTED:
344                                 d->changes_.set(Change(Change::UNCHANGED), pos);
345                                 // also accept changes in nested inset
346                                 if (pos < size() && isInset(pos)) {
347                                         getInset(pos)->acceptChanges(bparams);
348                                 }
349                                 break;
350
351                         case Change::DELETED:
352                                 // Suppress access to non-existent
353                                 // "end-of-paragraph char"
354                                 if (pos < size()) {
355                                         eraseChar(pos, false);
356                                         --end;
357                                         --pos;
358                                 }
359                                 break;
360                 }
361
362         }
363 }
364
365
366 void Paragraph::rejectChanges(BufferParams const & bparams,
367                 pos_type start, pos_type end)
368 {
369         BOOST_ASSERT(start >= 0 && start <= size());
370         BOOST_ASSERT(end > start && end <= size() + 1);
371
372         for (pos_type pos = start; pos < end; ++pos) {
373                 switch (lookupChange(pos).type) {
374                         case Change::UNCHANGED:
375                                 // reject changes in nested inset
376                                 if (pos < size() && isInset(pos)) {
377                                         getInset(pos)->rejectChanges(bparams);
378                                 }
379                                 break;
380
381                         case Change::INSERTED:
382                                 // Suppress access to non-existent
383                                 // "end-of-paragraph char"
384                                 if (pos < size()) {
385                                         eraseChar(pos, false);
386                                         --end;
387                                         --pos;
388                                 }
389                                 break;
390
391                         case Change::DELETED:
392                                 d->changes_.set(Change(Change::UNCHANGED), pos);
393
394                                 // Do NOT reject changes within a deleted inset!
395                                 // There may be insertions of a co-author inside of it!
396
397                                 break;
398                 }
399         }
400 }
401
402
403 void Paragraph::Private::insertChar(pos_type pos, char_type c,
404                 Change const & change)
405 {
406         BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
407
408         // track change
409         changes_.insert(change, pos);
410
411         // This is actually very common when parsing buffers (and
412         // maybe inserting ascii text)
413         if (pos == text_.size()) {
414                 // when appending characters, no need to update tables
415                 text_.push_back(c);
416                 return;
417         }
418
419         text_.insert(text_.begin() + pos, c);
420
421         // Update the font table.
422         fontlist_.increasePosAfterPos(pos);
423
424         // Update the insets
425         insetlist_.increasePosAfterPos(pos);
426 }
427
428
429 void Paragraph::insertInset(pos_type pos, Inset * inset,
430                                    Change const & change)
431 {
432         BOOST_ASSERT(inset);
433         BOOST_ASSERT(pos >= 0 && pos <= size());
434
435         d->insertChar(pos, META_INSET, change);
436         BOOST_ASSERT(d->text_[pos] == META_INSET);
437
438         // Add a new entry in the insetlist_.
439         d->insetlist_.insert(inset, pos);
440 }
441
442
443 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
444 {
445         BOOST_ASSERT(pos >= 0 && pos <= size());
446
447         // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
448
449         if (trackChanges) {
450                 Change change = d->changes_.lookup(pos);
451
452                 // set the character to DELETED if
453                 //  a) it was previously unchanged or
454                 //  b) it was inserted by a co-author
455
456                 if (change.type == Change::UNCHANGED ||
457                     (change.type == Change::INSERTED && change.author != 0)) {
458                         setChange(pos, Change(Change::DELETED));
459                         return false;
460                 }
461
462                 if (change.type == Change::DELETED)
463                         return false;
464         }
465
466         // Don't physically access the imaginary end-of-paragraph character.
467         // eraseChar() can only mark it as DELETED. A physical deletion of
468         // end-of-par must be handled externally.
469         if (pos == size()) {
470                 return false;
471         }
472
473         // track change
474         d->changes_.erase(pos);
475
476         // if it is an inset, delete the inset entry
477         if (d->text_[pos] == META_INSET)
478                 d->insetlist_.erase(pos);
479
480         d->text_.erase(d->text_.begin() + pos);
481
482         // Update the fontlist_
483         d->fontlist_.erase(pos);
484
485         // Update the insetlist_
486         d->insetlist_.decreasePosAfterPos(pos);
487
488         return true;
489 }
490
491
492 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
493 {
494         BOOST_ASSERT(start >= 0 && start <= size());
495         BOOST_ASSERT(end >= start && end <= size() + 1);
496
497         pos_type i = start;
498         for (pos_type count = end - start; count; --count) {
499                 if (!eraseChar(i, trackChanges))
500                         ++i;
501         }
502         return end - i;
503 }
504
505
506 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
507                 char_type next, Encoding const & encoding)
508 {
509         // Writing next here may circumvent a possible font change between
510         // c and next. Since next is only output if it forms a surrogate pair
511         // with c we can ignore this:
512         // A font change inside a surrogate pair does not make sense and is
513         // hopefully impossible to input.
514         // FIXME: change tracking
515         // Is this correct WRT change tracking?
516         docstring const latex1 = encoding.latexChar(next);
517         docstring const latex2 = encoding.latexChar(c);
518         os << latex1 << '{' << latex2 << '}';
519         return latex1.length() + latex2.length() + 2;
520 }
521
522
523 bool Paragraph::Private::simpleTeXBlanks(Encoding const & encoding,
524                                        odocstream & os, TexRow & texrow,
525                                        pos_type i,
526                                        unsigned int & column,
527                                        Font const & font,
528                                        Layout const & style)
529 {
530         if (style.pass_thru)
531                 return false;
532
533         if (i + 1 < int(text_.size())) {
534                 char_type next = text_[i + 1];
535                 if (Encodings::isCombiningChar(next)) {
536                         // This space has an accent, so we must always output it.
537                         column += latexSurrogatePair(os, ' ', next, encoding) - 1;
538                         return true;
539                 }
540         }
541
542         if (lyxrc.plaintext_linelen > 0
543             && column > lyxrc.plaintext_linelen
544             && i
545             && text_[i - 1] != ' '
546             && (i + 1 < int(text_.size()))
547             // same in FreeSpacing mode
548             && !owner_->isFreeSpacing()
549             // In typewriter mode, we want to avoid
550             // ! . ? : at the end of a line
551             && !(font.family() == Font::TYPEWRITER_FAMILY
552                  && (text_[i - 1] == '.'
553                      || text_[i - 1] == '?'
554                      || text_[i - 1] == ':'
555                      || text_[i - 1] == '!'))) {
556                 os << '\n';
557                 texrow.newline();
558                 texrow.start(owner_->id(), i + 1);
559                 column = 0;
560         } else if (style.free_spacing) {
561                 os << '~';
562         } else {
563                 os << ' ';
564         }
565         return false;
566 }
567
568
569 int Paragraph::Private::knownLangChars(odocstream & os,
570                                      char_type c,
571                                      string & preamble,
572                                      Change & runningChange,
573                                      Encoding const & encoding,
574                                      pos_type & i)
575 {
576         // When the character is marked by the proper language, we simply
577         // get its code point in some encoding, otherwise we get the
578         // translation specified in the unicodesymbols file, which is
579         // something like "\textLANG{<spec>}". So, we have to retain
580         // "\textLANG{<spec>" for the first char but only "<spec>" for
581         // all subsequent chars.
582         docstring const latex1 = rtrim(encoding.latexChar(c), "}");
583         int length = latex1.length();
584         os << latex1;
585         int size = text_.size();
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 > int(text_.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 < int(text_.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 > int(text_.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 < int(text_.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 < int(text_.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         // when appending characters, no need to update tables
1224         d->text_.append(s);
1225
1226         // FIXME: Optimize this!
1227         for (pos_type i = 0; i != end; ++i) {
1228                 // track change
1229                 d->changes_.insert(change, i);
1230         }
1231         d->fontlist_.setRange(oldsize, newsize, font);
1232 }
1233
1234
1235 void Paragraph::insertChar(pos_type pos, char_type c,
1236                            bool trackChanges)
1237 {
1238         d->insertChar(pos, c, Change(trackChanges ?
1239                            Change::INSERTED : Change::UNCHANGED));
1240 }
1241
1242
1243 void Paragraph::insertChar(pos_type pos, char_type c,
1244                            Font const & font, bool trackChanges)
1245 {
1246         d->insertChar(pos, c, Change(trackChanges ?
1247                            Change::INSERTED : Change::UNCHANGED));
1248         setFont(pos, font);
1249 }
1250
1251
1252 void Paragraph::insertChar(pos_type pos, char_type c,
1253                            Font const & font, Change const & change)
1254 {
1255         d->insertChar(pos, c, change);
1256         setFont(pos, font);
1257 }
1258
1259
1260 void Paragraph::insertInset(pos_type pos, Inset * inset,
1261                             Font const & font, Change const & change)
1262 {
1263         insertInset(pos, inset, change);
1264         // Set the font/language of the inset...
1265         setFont(pos, font);
1266 }
1267
1268
1269 bool Paragraph::insetAllowed(InsetCode code)
1270 {
1271         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1272 }
1273
1274
1275 // Gets uninstantiated font setting at position.
1276 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1277                                          pos_type pos) const
1278 {
1279         if (pos > size()) {
1280                 lyxerr << " pos: " << pos << " size: " << size() << endl;
1281                 BOOST_ASSERT(pos <= size());
1282         }
1283
1284         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1285         if (cit != d->fontlist_.end())
1286                 return cit->font();
1287
1288         if (pos == size() && !empty())
1289                 return getFontSettings(bparams, pos - 1);
1290
1291         return Font(Font::ALL_INHERIT, getParLanguage(bparams));
1292 }
1293
1294
1295 FontSpan Paragraph::fontSpan(pos_type pos) const
1296 {
1297         BOOST_ASSERT(pos <= size());
1298         pos_type start = 0;
1299
1300         FontList::const_iterator cit = d->fontlist_.begin();
1301         FontList::const_iterator end = d->fontlist_.end();
1302         for (; cit != end; ++cit) {
1303                 if (cit->pos() >= pos) {
1304                         if (pos >= beginOfBody())
1305                                 return FontSpan(std::max(start, beginOfBody()),
1306                                                 cit->pos());
1307                         else
1308                                 return FontSpan(start,
1309                                                 std::min(beginOfBody() - 1,
1310                                                          cit->pos()));
1311                 }
1312                 start = cit->pos() + 1;
1313         }
1314
1315         // This should not happen, but if so, we take no chances.
1316         //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1317         //      << endl;
1318         return FontSpan(pos, pos);
1319 }
1320
1321
1322 // Gets uninstantiated font setting at position 0
1323 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1324 {
1325         if (!empty() && !d->fontlist_.empty())
1326                 return d->fontlist_.begin()->font();
1327
1328         return Font(Font::ALL_INHERIT, bparams.language);
1329 }
1330
1331
1332 // Gets the fully instantiated font at a given position in a paragraph
1333 // This is basically the same function as Text::GetFont() in text2.cpp.
1334 // The difference is that this one is used for generating the LaTeX file,
1335 // and thus cosmetic "improvements" are disallowed: This has to deliver
1336 // the true picture of the buffer. (Asger)
1337 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1338                                  Font const & outerfont) const
1339 {
1340         BOOST_ASSERT(pos >= 0);
1341
1342         Font font = getFontSettings(bparams, pos);
1343
1344         pos_type const body_pos = beginOfBody();
1345         if (pos < body_pos)
1346                 font.realize(d->layout_->labelfont);
1347         else
1348                 font.realize(d->layout_->font);
1349
1350         font.realize(outerfont);
1351         font.realize(bparams.getFont());
1352
1353         return font;
1354 }
1355
1356
1357 Font const Paragraph::getLabelFont
1358         (BufferParams const & bparams, Font const & outerfont) const
1359 {
1360         Font tmpfont = layout()->labelfont;
1361         tmpfont.setLanguage(getParLanguage(bparams));
1362         tmpfont.realize(outerfont);
1363         tmpfont.realize(bparams.getFont());
1364         return tmpfont;
1365 }
1366
1367
1368 Font const Paragraph::getLayoutFont
1369         (BufferParams const & bparams, Font const & outerfont) const
1370 {
1371         Font tmpfont = layout()->font;
1372         tmpfont.setLanguage(getParLanguage(bparams));
1373         tmpfont.realize(outerfont);
1374         tmpfont.realize(bparams.getFont());
1375         return tmpfont;
1376 }
1377
1378
1379 /// Returns the height of the highest font in range
1380 Font_size Paragraph::highestFontInRange
1381         (pos_type startpos, pos_type endpos, Font_size def_size) const
1382 {
1383         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1384 }
1385
1386
1387 char_type
1388 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1389 {
1390         char_type c = d->text_[pos];
1391         if (!lyxrc.rtl_support)
1392                 return c;
1393
1394         char_type uc = c;
1395         switch (c) {
1396         case '(':
1397                 uc = ')';
1398                 break;
1399         case ')':
1400                 uc = '(';
1401                 break;
1402         case '[':
1403                 uc = ']';
1404                 break;
1405         case ']':
1406                 uc = '[';
1407                 break;
1408         case '{':
1409                 uc = '}';
1410                 break;
1411         case '}':
1412                 uc = '{';
1413                 break;
1414         case '<':
1415                 uc = '>';
1416                 break;
1417         case '>':
1418                 uc = '<';
1419                 break;
1420         }
1421         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1422                 return uc;
1423         else
1424                 return c;
1425 }
1426
1427
1428 void Paragraph::setFont(pos_type pos, Font const & font)
1429 {
1430         BOOST_ASSERT(pos <= size());
1431
1432         // First, reduce font against layout/label font
1433         // Update: The setCharFont() routine in text2.cpp already
1434         // reduces font, so we don't need to do that here. (Asger)
1435         
1436         d->fontlist_.set(pos, font);
1437 }
1438
1439
1440 void Paragraph::makeSameLayout(Paragraph const & par)
1441 {
1442         layout(par.layout());
1443         // move to pimpl?
1444         d->params_ = par.params();
1445 }
1446
1447
1448 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1449 {
1450         if (isFreeSpacing())
1451                 return false;
1452
1453         int pos = 0;
1454         int count = 0;
1455
1456         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1457                 if (eraseChar(pos, trackChanges))
1458                         ++count;
1459                 else
1460                         ++pos;
1461         }
1462
1463         return count > 0 || pos > 0;
1464 }
1465
1466
1467 bool Paragraph::hasSameLayout(Paragraph const & par) const
1468 {
1469         return par.layout() == layout() && d->params_.sameLayout(par.params());
1470 }
1471
1472
1473 depth_type Paragraph::getDepth() const
1474 {
1475         return params().depth();
1476 }
1477
1478
1479 depth_type Paragraph::getMaxDepthAfter() const
1480 {
1481         if (layout()->isEnvironment())
1482                 return params().depth() + 1;
1483         else
1484                 return params().depth();
1485 }
1486
1487
1488 char Paragraph::getAlign() const
1489 {
1490         if (params().align() == LYX_ALIGN_LAYOUT)
1491                 return layout()->align;
1492         else
1493                 return params().align();
1494 }
1495
1496
1497 docstring const & Paragraph::getLabelstring() const
1498 {
1499         return params().labelString();
1500 }
1501
1502
1503 // the next two functions are for the manual labels
1504 docstring const Paragraph::getLabelWidthString() const
1505 {
1506         if (layout()->margintype == MARGIN_MANUAL)
1507                 return params().labelWidthString();
1508         else
1509                 return _("Senseless with this layout!");
1510 }
1511
1512
1513 void Paragraph::setLabelWidthString(docstring const & s)
1514 {
1515         params().labelWidthString(s);
1516 }
1517
1518
1519 docstring const Paragraph::translateIfPossible(docstring const & s,
1520                 BufferParams const & bparams) const
1521 {
1522         if (!support::isAscii(s) || s.empty()) {
1523                 // This must be a user defined layout. We cannot translate
1524                 // this, since gettext accepts only ascii keys.
1525                 return s;
1526         }
1527         // Probably standard layout, try to translate
1528         Messages & m = getMessages(getParLanguage(bparams)->code());
1529         return m.get(to_ascii(s));
1530 }
1531
1532
1533 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1534                 BufferParams const & bparams, bool process_appendix) const
1535 {
1536         TextClass const & tclass = bparams.getTextClass();
1537
1538         docstring fmt;
1539         if (process_appendix && params().appendix())
1540                 fmt = translateIfPossible(layout->labelstring_appendix(),
1541                         bparams);
1542         else
1543                 fmt = translateIfPossible(layout->labelstring(), bparams);
1544
1545         if (fmt.empty() && layout->labeltype == LABEL_COUNTER 
1546             && !layout->counter.empty())
1547                 fmt = "\\the" + layout->counter;
1548
1549         // handle 'inherited level parts' in 'fmt',
1550         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1551         size_t const i = fmt.find('@', 0);
1552         if (i != docstring::npos) {
1553                 size_t const j = fmt.find('@', i + 1);
1554                 if (j != docstring::npos) {
1555                         docstring parent(fmt, i + 1, j - i - 1);
1556                         docstring label = from_ascii("??");
1557                         if (tclass.hasLayout(parent))
1558                                 docstring label = expandLabel(tclass[parent], bparams,
1559                                                       process_appendix);
1560                         fmt = docstring(fmt, 0, i) + label 
1561                                 + docstring(fmt, j + 1, docstring::npos);
1562                 }
1563         }
1564
1565         return tclass.counters().counterLabel(fmt);
1566 }
1567
1568
1569 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1570 {
1571         layout(new_layout);
1572         LyXAlignment const oldAlign = params().align();
1573         
1574         if (!(oldAlign & layout()->alignpossible)) {
1575                 frontend::Alert::warning(_("Alignment not permitted"), 
1576                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1577                 params().align(LYX_ALIGN_LAYOUT);
1578         }
1579 }
1580
1581
1582 pos_type Paragraph::beginOfBody() const
1583 {
1584         return d->begin_of_body_;
1585 }
1586
1587
1588 void Paragraph::setBeginOfBody()
1589 {
1590         if (layout()->labeltype != LABEL_MANUAL) {
1591                 d->begin_of_body_ = 0;
1592                 return;
1593         }
1594
1595         // Unroll the first two cycles of the loop
1596         // and remember the previous character to
1597         // remove unnecessary getChar() calls
1598         pos_type i = 0;
1599         pos_type end = size();
1600         if (i < end && !isNewline(i)) {
1601                 ++i;
1602                 char_type previous_char = 0;
1603                 char_type temp = 0;
1604                 if (i < end) {
1605                         previous_char = d->text_[i];
1606                         if (!isNewline(i)) {
1607                                 ++i;
1608                                 while (i < end && previous_char != ' ') {
1609                                         temp = d->text_[i];
1610                                         if (isNewline(i))
1611                                                 break;
1612                                         ++i;
1613                                         previous_char = temp;
1614                                 }
1615                         }
1616                 }
1617         }
1618
1619         d->begin_of_body_ = i;
1620 }
1621
1622
1623 InsetBibitem * Paragraph::bibitem() const
1624 {
1625         if (!d->insetlist_.empty()) {
1626                 Inset * inset = d->insetlist_.begin()->inset;
1627                 if (inset->lyxCode() == BIBITEM_CODE)
1628                         return static_cast<InsetBibitem *>(inset);
1629         }
1630         return 0;
1631 }
1632
1633
1634 bool Paragraph::forceDefaultParagraphs() const
1635 {
1636         return inInset() && inInset()->forceDefaultParagraphs(0);
1637 }
1638
1639
1640 namespace {
1641
1642 // paragraphs inside floats need different alignment tags to avoid
1643 // unwanted space
1644
1645 bool noTrivlistCentering(InsetCode code)
1646 {
1647         return code == FLOAT_CODE || code == WRAP_CODE;
1648 }
1649
1650
1651 string correction(string const & orig)
1652 {
1653         if (orig == "flushleft")
1654                 return "raggedright";
1655         if (orig == "flushright")
1656                 return "raggedleft";
1657         if (orig == "center")
1658                 return "centering";
1659         return orig;
1660 }
1661
1662
1663 string const corrected_env(string const & suffix, string const & env,
1664         InsetCode code)
1665 {
1666         string output = suffix + "{";
1667         if (noTrivlistCentering(code))
1668                 output += correction(env);
1669         else
1670                 output += env;
1671         output += "}";
1672         if (suffix == "\\begin")
1673                 output += "\n";
1674         return output;
1675 }
1676
1677
1678 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1679 {
1680         if (!contains(str, "\n"))
1681                 column += str.size();
1682         else {
1683                 string tmp;
1684                 texrow.newline();
1685                 column = rsplit(str, tmp, '\n').size();
1686         }
1687 }
1688
1689 } // namespace anon
1690
1691
1692 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1693                                  odocstream & os, TexRow & texrow,
1694                                  bool moving_arg) const
1695 {
1696         int column = 0;
1697
1698         if (params_.noindent()) {
1699                 os << "\\noindent ";
1700                 column += 10;
1701         }
1702         
1703         LyXAlignment const curAlign = params_.align();
1704
1705         if (curAlign == layout_->align)
1706                 return column;
1707
1708         switch (curAlign) {
1709         case LYX_ALIGN_NONE:
1710         case LYX_ALIGN_BLOCK:
1711         case LYX_ALIGN_LAYOUT:
1712         case LYX_ALIGN_SPECIAL:
1713                 break;
1714         case LYX_ALIGN_LEFT:
1715         case LYX_ALIGN_RIGHT:
1716         case LYX_ALIGN_CENTER:
1717                 if (moving_arg) {
1718                         os << "\\protect";
1719                         column += 8;
1720                 }
1721                 break;
1722         }
1723
1724         switch (curAlign) {
1725         case LYX_ALIGN_NONE:
1726         case LYX_ALIGN_BLOCK:
1727         case LYX_ALIGN_LAYOUT:
1728         case LYX_ALIGN_SPECIAL:
1729                 break;
1730         case LYX_ALIGN_LEFT: {
1731                 string output;
1732                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1733                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1734                 else
1735                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1736                 os << from_ascii(output);
1737                 adjust_row_column(output, texrow, column);
1738                 break;
1739         } case LYX_ALIGN_RIGHT: {
1740                 string output;
1741                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1742                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1743                 else
1744                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1745                 os << from_ascii(output);
1746                 adjust_row_column(output, texrow, column);
1747                 break;
1748         } case LYX_ALIGN_CENTER: {
1749                 string output;
1750                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1751                 os << from_ascii(output);
1752                 adjust_row_column(output, texrow, column);
1753                 break;
1754         }
1755         }
1756
1757         return column;
1758 }
1759
1760
1761 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1762                                odocstream & os, TexRow & texrow,
1763                                bool moving_arg) const
1764 {
1765         int column = 0;
1766
1767         switch (params_.align()) {
1768         case LYX_ALIGN_NONE:
1769         case LYX_ALIGN_BLOCK:
1770         case LYX_ALIGN_LAYOUT:
1771         case LYX_ALIGN_SPECIAL:
1772                 break;
1773         case LYX_ALIGN_LEFT:
1774         case LYX_ALIGN_RIGHT:
1775         case LYX_ALIGN_CENTER:
1776                 if (moving_arg) {
1777                         os << "\\protect";
1778                         column = 8;
1779                 }
1780                 break;
1781         }
1782
1783         switch (params_.align()) {
1784         case LYX_ALIGN_NONE:
1785         case LYX_ALIGN_BLOCK:
1786         case LYX_ALIGN_LAYOUT:
1787         case LYX_ALIGN_SPECIAL:
1788                 break;
1789         case LYX_ALIGN_LEFT: {
1790                 string output;
1791                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1792                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1793                 else
1794                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1795                 os << from_ascii(output);
1796                 adjust_row_column(output, texrow, column);
1797                 break;
1798         } case LYX_ALIGN_RIGHT: {
1799                 string output;
1800                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1801                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1802                 else
1803                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1804                 os << from_ascii(output);
1805                 adjust_row_column(output, texrow, column);
1806                 break;
1807         } case LYX_ALIGN_CENTER: {
1808                 string output;
1809                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1810                 os << from_ascii(output);
1811                 adjust_row_column(output, texrow, column);
1812                 break;
1813         }
1814         }
1815
1816         return column;
1817 }
1818
1819
1820 // This one spits out the text of the paragraph
1821 bool Paragraph::latex(Buffer const & buf,
1822                                 BufferParams const & bparams,
1823                                 Font const & outerfont,
1824                                 odocstream & os, TexRow & texrow,
1825                                 OutputParams const & runparams) const
1826 {
1827         LYXERR(Debug::LATEX) << "SimpleTeXOnePar...     " << this << endl;
1828
1829         bool return_value = false;
1830
1831         LayoutPtr style;
1832
1833         // well we have to check if we are in an inset with unlimited
1834         // length (all in one row) if that is true then we don't allow
1835         // any special options in the paragraph and also we don't allow
1836         // any environment other than the default layout of the text class
1837         // to be valid!
1838         bool asdefault = forceDefaultParagraphs();
1839
1840         if (asdefault) {
1841                 style = bparams.getTextClass().defaultLayout();
1842         } else {
1843                 style = layout();
1844         }
1845
1846         // Current base font for all inherited font changes, without any
1847         // change caused by an individual character, except for the language:
1848         // It is set to the language of the first character.
1849         // As long as we are in the label, this font is the base font of the
1850         // label. Before the first body character it is set to the base font
1851         // of the body.
1852         Font basefont;
1853
1854         // Maybe we have to create a optional argument.
1855         pos_type body_pos = beginOfBody();
1856         unsigned int column = 0;
1857
1858         if (body_pos > 0) {
1859                 // the optional argument is kept in curly brackets in
1860                 // case it contains a ']'
1861                 os << "[{";
1862                 column += 2;
1863                 basefont = getLabelFont(bparams, outerfont);
1864         } else {
1865                 basefont = getLayoutFont(bparams, outerfont);
1866         }
1867
1868         // Which font is currently active?
1869         Font running_font(basefont);
1870         // Do we have an open font change?
1871         bool open_font = false;
1872
1873         Change runningChange = Change(Change::UNCHANGED);
1874
1875         texrow.start(id(), 0);
1876
1877         // if the paragraph is empty, the loop will not be entered at all
1878         if (empty()) {
1879                 if (style->isCommand()) {
1880                         os << '{';
1881                         ++column;
1882                 }
1883                 if (!asdefault)
1884                         column += d->startTeXParParams(bparams, os, texrow,
1885                                                     runparams.moving_arg);
1886         }
1887
1888         for (pos_type i = 0; i < size(); ++i) {
1889                 // First char in paragraph or after label?
1890                 if (i == body_pos) {
1891                         if (body_pos > 0) {
1892                                 if (open_font) {
1893                                         column += running_font.latexWriteEndChanges(
1894                                                 os, bparams, runparams,
1895                                                 basefont, basefont);
1896                                         open_font = false;
1897                                 }
1898                                 basefont = getLayoutFont(bparams, outerfont);
1899                                 running_font = basefont;
1900
1901                                 column += Changes::latexMarkChange(os, bparams,
1902                                                 runningChange, Change(Change::UNCHANGED));
1903                                 runningChange = Change(Change::UNCHANGED);
1904
1905                                 os << "}] ";
1906                                 column +=3;
1907                         }
1908                         if (style->isCommand()) {
1909                                 os << '{';
1910                                 ++column;
1911                         }
1912
1913                         if (!asdefault)
1914                                 column += d->startTeXParParams(bparams, os,
1915                                                             texrow,
1916                                                             runparams.moving_arg);
1917                 }
1918
1919                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1920                                                                  : lookupChange(i);
1921
1922                 if (bparams.outputChanges && runningChange != change) {
1923                         if (open_font) {
1924                                 column += running_font.latexWriteEndChanges(
1925                                                 os, bparams, runparams, basefont, basefont);
1926                                 open_font = false;
1927                         }
1928                         basefont = getLayoutFont(bparams, outerfont);
1929                         running_font = basefont;
1930
1931                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1932                         runningChange = change;
1933                 }
1934
1935                 // do not output text which is marked deleted
1936                 // if change tracking output is disabled
1937                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1938                         continue;
1939                 }
1940
1941                 ++column;
1942
1943                 // Fully instantiated font
1944                 Font const font = getFont(bparams, i, outerfont);
1945
1946                 Font const last_font = running_font;
1947
1948                 // Do we need to close the previous font?
1949                 if (open_font &&
1950                     (font != running_font ||
1951                      font.language() != running_font.language()))
1952                 {
1953                         column += running_font.latexWriteEndChanges(
1954                                         os, bparams, runparams, basefont,
1955                                         (i == body_pos-1) ? basefont : font);
1956                         running_font = basefont;
1957                         open_font = false;
1958                 }
1959
1960                 // Switch file encoding if necessary (and allowed)
1961                 if (!runparams.verbatim && 
1962                     runparams.encoding->package() == Encoding::inputenc &&
1963                     font.language()->encoding()->package() == Encoding::inputenc) {
1964                         std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1965                                         runparams.moving_arg, *(runparams.encoding),
1966                                         *(font.language()->encoding()));
1967                         if (enc_switch.first) {
1968                                 column += enc_switch.second;
1969                                 runparams.encoding = font.language()->encoding();
1970                         }
1971                 }
1972
1973                 char_type const c = d->text_[i];
1974
1975                 // Do we need to change font?
1976                 if ((font != running_font ||
1977                      font.language() != running_font.language()) &&
1978                         i != body_pos - 1)
1979                 {
1980                         odocstringstream ods;
1981                         column += font.latexWriteStartChanges(ods, bparams,
1982                                                               runparams, basefont,
1983                                                               last_font);
1984                         running_font = font;
1985                         open_font = true;
1986                         docstring fontchange = ods.str();
1987                         // check if the fontchange ends with a trailing blank
1988                         // (like "\small " (see bug 3382)
1989                         if (suffixIs(fontchange, ' ') && c == ' ')
1990                                 os << fontchange.substr(0, fontchange.size() - 1) 
1991                                    << from_ascii("{}");
1992                         else
1993                                 os << fontchange;
1994                 }
1995
1996                 if (c == ' ') {
1997                         // FIXME: integrate this case in latexSpecialChar
1998                         // Do not print the separation of the optional argument
1999                         // if style->pass_thru is false. This works because
2000                         // latexSpecialChar ignores spaces if
2001                         // style->pass_thru is false.
2002                         if (i != body_pos - 1) {
2003                                 if (d->simpleTeXBlanks(
2004                                                 *(runparams.encoding), os, texrow,
2005                                                 i, column, font, *style)) {
2006                                         // A surrogate pair was output. We
2007                                         // must not call latexSpecialChar
2008                                         // in this iteration, since it would output
2009                                         // the combining character again.
2010                                         ++i;
2011                                         continue;
2012                                 }
2013                         }
2014                 }
2015
2016                 OutputParams rp = runparams;
2017                 rp.free_spacing = style->free_spacing;
2018                 rp.local_font = &font;
2019                 rp.intitle = style->intitle;
2020
2021                 // Two major modes:  LaTeX or plain
2022                 // Handle here those cases common to both modes
2023                 // and then split to handle the two modes separately.
2024                 if (c == META_INSET)
2025                         d->latexInset(buf, bparams, os,
2026                                         texrow, rp, running_font,
2027                                         basefont, outerfont, open_font,
2028                                         runningChange, *style, i, column);
2029                 else
2030                         d->latexSpecialChar(os, rp, running_font, runningChange,
2031                                 *style, i, column);
2032
2033                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2034                 // comment for encoding member in OutputParams.h)
2035                 runparams.encoding = rp.encoding;
2036         }
2037
2038         // If we have an open font definition, we have to close it
2039         if (open_font) {
2040 #ifdef FIXED_LANGUAGE_END_DETECTION
2041                 if (next_) {
2042                         running_font
2043                                 .latexWriteEndChanges(os, bparams, runparams,
2044                                         basefont,
2045                                         next_->getFont(bparams, 0, outerfont));
2046                 } else {
2047                         running_font.latexWriteEndChanges(os, bparams,
2048                                         runparams, basefont, basefont);
2049                 }
2050 #else
2051 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2052 //FIXME: there as we start another \selectlanguage with the next paragraph if
2053 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2054                 running_font.latexWriteEndChanges(os, bparams, runparams,
2055                                 basefont, basefont);
2056 #endif
2057         }
2058
2059         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2060
2061         // Needed if there is an optional argument but no contents.
2062         if (body_pos > 0 && body_pos == size()) {
2063                 os << "}]~";
2064                 return_value = false;
2065         }
2066
2067         if (!asdefault) {
2068                 column += d->endTeXParParams(bparams, os, texrow,
2069                                           runparams.moving_arg);
2070         }
2071
2072         LYXERR(Debug::LATEX) << "SimpleTeXOnePar...done " << this << endl;
2073         return return_value;
2074 }
2075
2076
2077 namespace {
2078
2079 enum PAR_TAG {
2080         PAR_NONE=0,
2081         TT = 1,
2082         SF = 2,
2083         BF = 4,
2084         IT = 8,
2085         SL = 16,
2086         EM = 32
2087 };
2088
2089
2090 string tag_name(PAR_TAG const & pt) {
2091         switch (pt) {
2092         case PAR_NONE: return "!-- --";
2093         case TT: return "tt";
2094         case SF: return "sf";
2095         case BF: return "bf";
2096         case IT: return "it";
2097         case SL: return "sl";
2098         case EM: return "em";
2099         }
2100         return "";
2101 }
2102
2103
2104 inline
2105 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2106 {
2107         p1 = static_cast<PAR_TAG>(p1 | p2);
2108 }
2109
2110
2111 inline
2112 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2113 {
2114         p1 = static_cast<PAR_TAG>(p1 & ~p2);
2115 }
2116
2117 } // anon
2118
2119
2120 bool Paragraph::emptyTag() const
2121 {
2122         for (pos_type i = 0; i < size(); ++i) {
2123                 if (isInset(i)) {
2124                         Inset const * inset = getInset(i);
2125                         InsetCode lyx_code = inset->lyxCode();
2126                         if (lyx_code != TOC_CODE &&
2127                             lyx_code != INCLUDE_CODE &&
2128                             lyx_code != GRAPHICS_CODE &&
2129                             lyx_code != ERT_CODE &&
2130                             lyx_code != LISTINGS_CODE &&
2131                             lyx_code != FLOAT_CODE &&
2132                             lyx_code != TABULAR_CODE) {
2133                                 return false;
2134                         }
2135                 } else {
2136                         char_type c = d->text_[i];
2137                         if (c != ' ' && c != '\t')
2138                                 return false;
2139                 }
2140         }
2141         return true;
2142 }
2143
2144
2145 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2146 {
2147         for (pos_type i = 0; i < size(); ++i) {
2148                 if (isInset(i)) {
2149                         Inset const * inset = getInset(i);
2150                         InsetCode lyx_code = inset->lyxCode();
2151                         if (lyx_code == LABEL_CODE) {
2152                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2153                                 docstring const & id = il->getParam("name");
2154                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2155                         }
2156                 }
2157
2158         }
2159         return string();
2160 }
2161
2162
2163 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2164 {
2165         pos_type i;
2166         for (i = 0; i < size(); ++i) {
2167                 if (isInset(i)) {
2168                         Inset const * inset = getInset(i);
2169                         inset->docbook(buf, os, runparams);
2170                 } else {
2171                         char_type c = d->text_[i];
2172                         if (c == ' ')
2173                                 break;
2174                         os << sgml::escapeChar(c);
2175                 }
2176         }
2177         return i;
2178 }
2179
2180
2181 bool Paragraph::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2182 {
2183         Font font_old;
2184
2185         for (pos_type i = initial; i < size(); ++i) {
2186                 Font font = getFont(buf.params(), i, outerfont);
2187                 if (isInset(i))
2188                         return false;
2189                 if (i != initial && font != font_old)
2190                         return false;
2191                 font_old = font;
2192         }
2193
2194         return true;
2195 }
2196
2197
2198 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2199                                     odocstream & os,
2200                                     OutputParams const & runparams,
2201                                     Font const & outerfont,
2202                                     pos_type initial) const
2203 {
2204         bool emph_flag = false;
2205
2206         LayoutPtr const & style = layout();
2207         Font font_old =
2208                 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2209
2210         if (style->pass_thru && !onlyText(buf, outerfont, initial))
2211                 os << "]]>";
2212
2213         // parsing main loop
2214         for (pos_type i = initial; i < size(); ++i) {
2215                 Font font = getFont(buf.params(), i, outerfont);
2216
2217                 // handle <emphasis> tag
2218                 if (font_old.emph() != font.emph()) {
2219                         if (font.emph() == Font::ON) {
2220                                 os << "<emphasis>";
2221                                 emph_flag = true;
2222                         } else if (i != initial) {
2223                                 os << "</emphasis>";
2224                                 emph_flag = false;
2225                         }
2226                 }
2227
2228                 if (isInset(i)) {
2229                         Inset const * inset = getInset(i);
2230                         inset->docbook(buf, os, runparams);
2231                 } else {
2232                         char_type c = d->text_[i];
2233
2234                         if (style->pass_thru)
2235                                 os.put(c);
2236                         else
2237                                 os << sgml::escapeChar(c);
2238                 }
2239                 font_old = font;
2240         }
2241
2242         if (emph_flag) {
2243                 os << "</emphasis>";
2244         }
2245
2246         if (style->free_spacing)
2247                 os << '\n';
2248         if (style->pass_thru && !onlyText(buf, outerfont, initial))
2249                 os << "<![CDATA[";
2250 }
2251
2252
2253 bool Paragraph::isHfill(pos_type pos) const
2254 {
2255         return isInset(pos)
2256                 && getInset(pos)->lyxCode() == HFILL_CODE;
2257 }
2258
2259
2260 bool Paragraph::isNewline(pos_type pos) const
2261 {
2262         return isInset(pos)
2263                 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2264 }
2265
2266
2267 bool Paragraph::isLineSeparator(pos_type pos) const
2268 {
2269         char_type const c = d->text_[pos];
2270         return isLineSeparatorChar(c)
2271                 || (c == META_INSET && getInset(pos) &&
2272                 getInset(pos)->isLineSeparator());
2273 }
2274
2275
2276 /// Used by the spellchecker
2277 bool Paragraph::isLetter(pos_type pos) const
2278 {
2279         if (isInset(pos))
2280                 return getInset(pos)->isLetter();
2281         else {
2282                 char_type const c = d->text_[pos];
2283                 return isLetterChar(c) || isDigit(c);
2284         }
2285 }
2286
2287
2288 Language const *
2289 Paragraph::getParLanguage(BufferParams const & bparams) const
2290 {
2291         if (!empty())
2292                 return getFirstFontSettings(bparams).language();
2293         // FIXME: we should check the prev par as well (Lgb)
2294         return bparams.language;
2295 }
2296
2297
2298 bool Paragraph::isRTL(BufferParams const & bparams) const
2299 {
2300         return lyxrc.rtl_support
2301                 && getParLanguage(bparams)->rightToLeft()
2302                 && ownerCode() != ERT_CODE
2303                 && ownerCode() != LISTINGS_CODE;
2304 }
2305
2306
2307 void Paragraph::changeLanguage(BufferParams const & bparams,
2308                                Language const * from, Language const * to)
2309 {
2310         // change language including dummy font change at the end
2311         for (pos_type i = 0; i <= size(); ++i) {
2312                 Font font = getFontSettings(bparams, i);
2313                 if (font.language() == from) {
2314                         font.setLanguage(to);
2315                         setFont(i, font);
2316                 }
2317         }
2318 }
2319
2320
2321 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2322 {
2323         Language const * doc_language = bparams.language;
2324         FontList::const_iterator cit = d->fontlist_.begin();
2325         FontList::const_iterator end = d->fontlist_.end();
2326
2327         for (; cit != end; ++cit)
2328                 if (cit->font().language() != ignore_language &&
2329                     cit->font().language() != latex_language &&
2330                     cit->font().language() != doc_language)
2331                         return true;
2332         return false;
2333 }
2334
2335
2336 // Convert the paragraph to a string.
2337 // Used for building the table of contents
2338 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2339 {
2340         return asString(buffer, 0, size(), label);
2341 }
2342
2343
2344 docstring const Paragraph::asString(Buffer const & buffer,
2345                                  pos_type beg, pos_type end, bool label) const
2346 {
2347
2348         odocstringstream os;
2349
2350         if (beg == 0 && label && !params().labelString().empty())
2351                 os << params().labelString() << ' ';
2352
2353         for (pos_type i = beg; i < end; ++i) {
2354                 char_type const c = d->text_[i];
2355                 if (isPrintable(c))
2356                         os.put(c);
2357                 else if (c == META_INSET)
2358                         getInset(i)->textString(buffer, os);
2359         }
2360
2361         return os.str();
2362 }
2363
2364
2365 void Paragraph::setInsetOwner(Inset * inset)
2366 {
2367         d->inset_owner_ = inset;
2368 }
2369
2370
2371 int Paragraph::id() const
2372 {
2373         return d->id_;
2374 }
2375
2376
2377 LayoutPtr const & Paragraph::layout() const
2378 {
2379         return d->layout_;
2380 }
2381
2382
2383 void Paragraph::layout(LayoutPtr const & new_layout)
2384 {
2385         d->layout_ = new_layout;
2386 }
2387
2388
2389 Inset * Paragraph::inInset() const
2390 {
2391         return d->inset_owner_;
2392 }
2393
2394
2395 InsetCode Paragraph::ownerCode() const
2396 {
2397         return d->inset_owner_ ?
2398                 d->inset_owner_->lyxCode() : NO_CODE;
2399 }
2400
2401
2402 ParagraphParameters & Paragraph::params()
2403 {
2404         return d->params_;
2405 }
2406
2407
2408 ParagraphParameters const & Paragraph::params() const
2409 {
2410         return d->params_;
2411 }
2412
2413
2414 bool Paragraph::isFreeSpacing() const
2415 {
2416         if (layout()->free_spacing)
2417                 return true;
2418
2419         // for now we just need this, later should we need this in some
2420         // other way we can always add a function to Inset too.
2421         return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2422 }
2423
2424
2425 bool Paragraph::allowEmpty() const
2426 {
2427         if (layout()->keepempty)
2428                 return true;
2429         return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2430 }
2431
2432
2433 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2434 {
2435         if (!Encodings::is_arabic(c))
2436                 return c;
2437
2438         char_type prev_char = ' ';
2439         char_type next_char = ' ';
2440
2441         for (pos_type i = pos - 1; i >= 0; --i) {
2442                 char_type const par_char = d->text_[i];
2443                 if (!Encodings::isComposeChar_arabic(par_char)) {
2444                         prev_char = par_char;
2445                         break;
2446                 }
2447         }
2448
2449         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2450                 char_type const par_char = d->text_[i];
2451                 if (!Encodings::isComposeChar_arabic(par_char)) {
2452                         next_char = par_char;
2453                         break;
2454                 }
2455         }
2456
2457         if (Encodings::is_arabic(next_char)) {
2458                 if (Encodings::is_arabic(prev_char) &&
2459                         !Encodings::is_arabic_special(prev_char))
2460                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2461                 else
2462                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2463         } else {
2464                 if (Encodings::is_arabic(prev_char) &&
2465                         !Encodings::is_arabic_special(prev_char))
2466                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2467                 else
2468                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2469         }
2470 }
2471
2472
2473 int Paragraph::checkBiblio(bool track_changes)
2474 {
2475         //FIXME From JS:
2476         //This is getting more and more a mess. ...We really should clean
2477         //up this bibitem issue for 1.6. See also bug 2743.
2478
2479         // Add bibitem insets if necessary
2480         if (layout()->labeltype != LABEL_BIBLIO)
2481                 return 0;
2482
2483         bool hasbibitem = !d->insetlist_.empty()
2484                 // Insist on it being in pos 0
2485                 && d->text_[0] == META_INSET
2486                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2487
2488         docstring oldkey;
2489         docstring oldlabel;
2490
2491         // remove a bibitem in pos != 0
2492         // restore it later in pos 0 if necessary
2493         // (e.g. if a user inserts contents _before_ the item)
2494         // we're assuming there's only one of these, which there
2495         // should be.
2496         int erasedInsetPosition = -1;
2497         InsetList::iterator it = d->insetlist_.begin();
2498         InsetList::iterator end = d->insetlist_.end();
2499         for (; it != end; ++it)
2500                 if (it->inset->lyxCode() == BIBITEM_CODE
2501                     && it->pos > 0) {
2502                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2503                         oldkey = olditem->getParam("key");
2504                         oldlabel = olditem->getParam("label");
2505                         erasedInsetPosition = it->pos;
2506                         eraseChar(erasedInsetPosition, track_changes);
2507                         break;
2508         }
2509
2510         //There was an InsetBibitem at the beginning, and we didn't
2511         //have to erase one.
2512         if (hasbibitem && erasedInsetPosition < 0)
2513                         return 0;
2514
2515         //There was an InsetBibitem at the beginning and we did have to
2516         //erase one. So we give its properties to the beginning inset.
2517         if (hasbibitem) {
2518                 InsetBibitem * inset =
2519                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2520                 if (!oldkey.empty())
2521                         inset->setParam("key", oldkey);
2522                 inset->setParam("label", oldlabel);
2523                 return -erasedInsetPosition;
2524         }
2525
2526         //There was no inset at the beginning, so we need to create one with
2527         //the key and label of the one we erased.
2528         InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2529         // restore values of previously deleted item in this par.
2530         if (!oldkey.empty())
2531                 inset->setParam("key", oldkey);
2532         inset->setParam("label", oldlabel);
2533         insertInset(0, static_cast<Inset *>(inset),
2534                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2535
2536         return 1;
2537 }
2538
2539
2540 void Paragraph::checkAuthors(AuthorList const & authorList)
2541 {
2542         d->changes_.checkAuthors(authorList);
2543 }
2544
2545
2546 bool Paragraph::isUnchanged(pos_type pos) const
2547 {
2548         return lookupChange(pos).type == Change::UNCHANGED;
2549 }
2550
2551
2552 bool Paragraph::isInserted(pos_type pos) const
2553 {
2554         return lookupChange(pos).type == Change::INSERTED;
2555 }
2556
2557
2558 bool Paragraph::isDeleted(pos_type pos) const
2559 {
2560         return lookupChange(pos).type == Change::DELETED;
2561 }
2562
2563
2564 InsetList const & Paragraph::insetList() const
2565 {
2566         return d->insetlist_;
2567 }
2568
2569
2570 Inset * Paragraph::releaseInset(pos_type pos)
2571 {
2572         Inset * inset = d->insetlist_.release(pos);
2573         /// does not honour change tracking!
2574         eraseChar(pos, false);
2575         return inset;
2576 }
2577
2578
2579 Inset * Paragraph::getInset(pos_type pos)
2580 {
2581         return d->insetlist_.get(pos);
2582 }
2583
2584
2585 Inset const * Paragraph::getInset(pos_type pos) const
2586 {
2587         return d->insetlist_.get(pos);
2588 }
2589
2590
2591 int Paragraph::numberOfOptArgs() const
2592 {
2593         int num = 0;
2594         InsetList::const_iterator it = insetList().begin();
2595         InsetList::const_iterator end = insetList().end();
2596         for (; it != end ; ++it) {
2597                 if (it->inset->lyxCode() == OPTARG_CODE)
2598                         ++num;
2599         }
2600         return num;
2601 }
2602
2603
2604 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2605                 pos_type right, TextCase action)
2606 {
2607         // process sequences of modified characters; in change
2608         // tracking mode, this approach results in much better
2609         // usability than changing case on a char-by-char basis
2610         docstring changes;
2611
2612         bool const trackChanges = bparams.trackChanges;
2613
2614         bool capitalize = true;
2615
2616         for (; pos < right; ++pos) {
2617                 char_type oldChar = d->text_[pos];
2618                 char_type newChar = oldChar;
2619
2620                 // ignore insets and don't play with deleted text!
2621                 if (isInset(pos) && !isDeleted(pos)) {
2622                         switch (action) {
2623                                 case text_lowercase:
2624                                         newChar = lowercase(oldChar);
2625                                         break;
2626                                 case text_capitalization:
2627                                         if (capitalize) {
2628                                                 newChar = uppercase(oldChar);
2629                                                 capitalize = false;
2630                                         }
2631                                         break;
2632                                 case text_uppercase:
2633                                         newChar = uppercase(oldChar);
2634                                         break;
2635                         }
2636                 }
2637
2638                 if (!isLetter(pos) || isDeleted(pos)) {
2639                         // permit capitalization again
2640                         capitalize = true;
2641                 }
2642
2643                 if (oldChar != newChar)
2644                         changes += newChar;
2645
2646                 if (oldChar == newChar || pos == right - 1) {
2647                         if (oldChar != newChar) {
2648                                 // step behind the changing area
2649                                 pos++;
2650                         }
2651                         int erasePos = pos - changes.size();
2652                         for (size_t i = 0; i < changes.size(); i++) {
2653                                 insertChar(pos, changes[i],
2654                                         getFontSettings(bparams,
2655                                         erasePos),
2656                                         trackChanges);
2657                                 if (!eraseChar(erasePos, trackChanges)) {
2658                                         ++erasePos;
2659                                         ++pos; // advance
2660                                         ++right; // expand selection
2661                                 }
2662                         }
2663                         changes.clear();
2664                 }
2665         }
2666 }
2667
2668
2669 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2670                 pos_type pos, bool del) const
2671 {
2672         int const strsize = str.length();
2673         int i = 0;
2674         pos_type const parsize = d->text_.size();
2675         for (i = 0; pos + i < parsize; ++i) {
2676                 if (i >= strsize)
2677                         break;
2678                 if (cs && str[i] != d->text_[pos + i])
2679                         break;
2680                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2681                         break;
2682                 if (!del && isDeleted(pos + i))
2683                         break;
2684         }
2685
2686         if (i != strsize)
2687                 return false;
2688
2689         // if necessary, check whether string matches word
2690         if (mw) {
2691                 if (pos > 0 && isLetter(pos - 1))
2692                         return false;
2693                 if (pos + strsize < parsize
2694                         && isLetter(pos + strsize))
2695                         return false;
2696         }
2697
2698         return true;
2699 }
2700
2701
2702 char_type Paragraph::getChar(pos_type pos) const
2703 {
2704         return d->text_[pos];
2705 }
2706
2707
2708 pos_type Paragraph::size() const
2709 {
2710         return d->text_.size();
2711 }
2712
2713
2714 bool Paragraph::empty() const
2715 {
2716         return d->text_.empty();
2717 }
2718
2719
2720 bool Paragraph::isInset(pos_type pos) const
2721 {
2722         return d->text_[pos] == META_INSET;
2723 }
2724
2725
2726 bool Paragraph::isSeparator(pos_type pos) const
2727 {
2728         //FIXME: Are we sure this can be the only separator?
2729         return d->text_[pos] == ' ';
2730 }
2731
2732
2733 } // namespace lyx