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