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