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