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