]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
comment
[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                 // FIXME UNICODE: This can fail if c cannot
806                 // be encoded in the current encoding.
807                 os.put(c);
808                 return;
809         }
810
811         if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
812                 return;
813
814         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
815                 && latexSpecialTypewriter(c, os, i, column))
816                 return;
817
818         // Otherwise, we use what LaTeX provides us.
819         switch (c) {
820         case '\\':
821                 os << "\\textbackslash{}";
822                 column += 15;
823                 break;
824         case '<':
825                 os << "\\textless{}";
826                 column += 10;
827                 break;
828         case '>':
829                 os << "\\textgreater{}";
830                 column += 13;
831                 break;
832         case '|':
833                 os << "\\textbar{}";
834                 column += 9;
835                 break;
836         case '-':
837                 os << '-';
838                 break;
839         case '\"':
840                 os << "\\char`\\\"{}";
841                 column += 9;
842                 break;
843
844         case '$': case '&':
845         case '%': case '#': case '{':
846         case '}': case '_':
847                 os << '\\';
848                 os.put(c);
849                 column += 1;
850                 break;
851
852         case '~':
853                 os << "\\textasciitilde{}";
854                 column += 16;
855                 break;
856
857         case '^':
858                 os << "\\textasciicircum{}";
859                 column += 17;
860                 break;
861
862         case '*': case '[':
863                 // avoid being mistaken for optional arguments
864                 os << '{';
865                 os.put(c);
866                 os << '}';
867                 column += 2;
868                 break;
869
870         case ' ':
871                 // Blanks are printed before font switching.
872                 // Sure? I am not! (try nice-latex)
873                 // I am sure it's correct. LyX might be smarter
874                 // in the future, but for now, nothing wrong is
875                 // written. (Asger)
876                 break;
877
878         default:
879                 // LyX, LaTeX etc.
880                 if (latexSpecialPhrase(os, i, column, runparams))
881                         return;
882
883                 if (c == '\0')
884                         return;
885
886                 Encoding const & encoding = *(runparams.encoding);
887                 if (i + 1 < int(text_.size())) {
888                         char_type next = text_[i + 1];
889                         if (Encodings::isCombiningChar(next)) {
890                                 column += latexSurrogatePair(os, c, next, encoding) - 1;
891                                 ++i;
892                                 break;
893                         }
894                 }
895                 string script;
896                 docstring const latex = encoding.latexChar(c);
897                 if (Encodings::isKnownScriptChar(c, script)
898                     && prefixIs(latex, from_ascii("\\" + script)))
899                         column += writeScriptChars(os, latex,
900                                         running_change, encoding, i) - 1;
901                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
902                         // Prevent eating of a following
903                         // space or command corruption by
904                         // following characters
905                         column += latex.length() + 1;
906                         os << latex << "{}";
907                 } else {
908                         column += latex.length() - 1;
909                         os << latex;
910                 }
911                 break;
912         }
913 }
914
915
916 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
917         pos_type & i, unsigned int & column)
918 {
919         switch (c) {
920         case '>':
921         case '<':
922                 os.put(c);
923                 // In T1 encoding, these characters exist
924                 // but we should avoid ligatures
925                 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
926                         return true;
927                 os << "\\textcompwordmark{}";
928                 column += 19;
929                 return true;
930         case '|':
931                 os.put(c);
932                 return true;
933         default:
934                 return false;
935         }
936 }
937
938
939 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
940         pos_type & i, unsigned int & column)
941 {
942         switch (c) {
943         case '-':
944                 // within \ttfamily, "--" is merged to "-" (no endash)
945                 // so we avoid this rather irritating ligature
946                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
947                         os << "-{}";
948                         column += 2;
949                 } else
950                         os << '-';
951                 return true;
952
953         // everything else has to be checked separately
954         // (depending on the encoding)
955         default:
956                 return false;
957         }
958 }
959
960
961 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
962         unsigned int & column, OutputParams & runparams)
963 {
964         // FIXME: if we have "LaTeX" with a font
965         // change in the middle (before the 'T', then
966         // the "TeX" part is still special cased.
967         // Really we should only operate this on
968         // "words" for some definition of word
969
970         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
971                 if (!isTextAt(special_phrases[pnr].phrase, i))
972                         continue;
973                 if (runparams.moving_arg)
974                         os << "\\protect";
975                 os << special_phrases[pnr].macro;
976                 i += special_phrases[pnr].phrase.length() - 1;
977                 column += special_phrases[pnr].macro.length() - 1;
978                 return true;
979         }
980         return false;
981 }
982
983
984 void Paragraph::Private::validate(LaTeXFeatures & features,
985                                 Layout const & layout) const
986 {
987         // check the params.
988         if (!params_.spacing().isDefault())
989                 features.require("setspace");
990
991         // then the layouts
992         features.useLayout(layout.name());
993
994         // then the fonts
995         fontlist_.validate(features);
996
997         // then the indentation
998         if (!params_.leftIndent().zero())
999                 features.require("ParagraphLeftIndent");
1000
1001         // then the insets
1002         InsetList::const_iterator icit = insetlist_.begin();
1003         InsetList::const_iterator iend = insetlist_.end();
1004         for (; icit != iend; ++icit) {
1005                 if (icit->inset) {
1006                         icit->inset->validate(features);
1007                         if (layout.needprotect &&
1008                             icit->inset->lyxCode() == FOOT_CODE)
1009                                 features.require("NeedLyXFootnoteCode");
1010                 }
1011         }
1012
1013         // then the contents
1014         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1015                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1016                         if (!special_phrases[pnr].builtin
1017                             && isTextAt(special_phrases[pnr].phrase, i)) {
1018                                 features.require(special_phrases[pnr].phrase);
1019                                 break;
1020                         }
1021                 }
1022                 Encodings::validate(text_[i], features);
1023         }
1024 }
1025
1026 /////////////////////////////////////////////////////////////////////
1027 //
1028 // Paragraph
1029 //
1030 /////////////////////////////////////////////////////////////////////
1031
1032 namespace {
1033         Layout const emptyParagraphLayout;
1034 }
1035
1036 Paragraph::Paragraph() 
1037         : d(new Paragraph::Private(this, emptyParagraphLayout))
1038 {
1039         itemdepth = 0;
1040         d->params_.clear();
1041 }
1042
1043
1044 Paragraph::Paragraph(Paragraph const & par)
1045         : itemdepth(par.itemdepth),
1046         d(new Paragraph::Private(*par.d, this))
1047 {
1048         registerWords();
1049 }
1050
1051
1052 Paragraph & Paragraph::operator=(Paragraph const & par)
1053 {
1054         // needed as we will destroy the private part before copying it
1055         if (&par != this) {
1056                 itemdepth = par.itemdepth;
1057
1058                 deregisterWords();
1059                 delete d;
1060                 d = new Private(*par.d, this);
1061                 registerWords();
1062         }
1063         return *this;
1064 }
1065
1066
1067 Paragraph::~Paragraph()
1068 {
1069         deregisterWords();
1070         delete d;
1071 }
1072
1073
1074 void Paragraph::write(ostream & os, BufferParams const & bparams,
1075         depth_type & dth) const
1076 {
1077         // The beginning or end of a deeper (i.e. nested) area?
1078         if (dth != d->params_.depth()) {
1079                 if (d->params_.depth() > dth) {
1080                         while (d->params_.depth() > dth) {
1081                                 os << "\n\\begin_deeper";
1082                                 ++dth;
1083                         }
1084                 } else {
1085                         while (d->params_.depth() < dth) {
1086                                 os << "\n\\end_deeper";
1087                                 --dth;
1088                         }
1089                 }
1090         }
1091
1092         // First write the layout
1093         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1094
1095         d->params_.write(os);
1096
1097         Font font1(inherit_font, bparams.language);
1098
1099         Change running_change = Change(Change::UNCHANGED);
1100
1101         int column = 0;
1102         for (pos_type i = 0; i <= size(); ++i) {
1103
1104                 Change change = lookupChange(i);
1105                 Changes::lyxMarkChange(os, column, running_change, change);
1106                 running_change = change;
1107
1108                 if (i == size())
1109                         break;
1110
1111                 // Write font changes
1112                 Font font2 = getFontSettings(bparams, i);
1113                 if (font2 != font1) {
1114                         font2.lyxWriteChanges(font1, os);
1115                         column = 0;
1116                         font1 = font2;
1117                 }
1118
1119                 char_type const c = d->text_[i];
1120                 switch (c) {
1121                 case META_INSET:
1122                         if (Inset const * inset = getInset(i)) {
1123                                 if (inset->directWrite()) {
1124                                         // international char, let it write
1125                                         // code directly so it's shorter in
1126                                         // the file
1127                                         inset->write(os);
1128                                 } else {
1129                                         if (i)
1130                                                 os << '\n';
1131                                         os << "\\begin_inset ";
1132                                         inset->write(os);
1133                                         os << "\n\\end_inset\n\n";
1134                                         column = 0;
1135                                 }
1136                         }
1137                         break;
1138                 case '\\':
1139                         os << "\n\\backslash\n";
1140                         column = 0;
1141                         break;
1142                 case '.':
1143                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1144                                 os << ".\n";
1145                                 column = 0;
1146                         } else
1147                                 os << '.';
1148                         break;
1149                 default:
1150                         if ((column > 70 && c == ' ')
1151                             || column > 79) {
1152                                 os << '\n';
1153                                 column = 0;
1154                         }
1155                         // this check is to amend a bug. LyX sometimes
1156                         // inserts '\0' this could cause problems.
1157                         if (c != '\0')
1158                                 os << to_utf8(docstring(1, c));
1159                         else
1160                                 LYXERR0("NUL char in structure.");
1161                         ++column;
1162                         break;
1163                 }
1164         }
1165
1166         os << "\n\\end_layout\n";
1167 }
1168
1169
1170 void Paragraph::validate(LaTeXFeatures & features) const
1171 {
1172         d->validate(features, *d->layout_);
1173 }
1174
1175
1176 void Paragraph::insert(pos_type start, docstring const & str,
1177                        Font const & font, Change const & change)
1178 {
1179         for (size_t i = 0, n = str.size(); i != n ; ++i)
1180                 insertChar(start + i, str[i], font, change);
1181 }
1182
1183
1184 void Paragraph::appendChar(char_type c, Font const & font,
1185                 Change const & change)
1186 {
1187         // track change
1188         d->changes_.insert(change, d->text_.size());
1189         // when appending characters, no need to update tables
1190         d->text_.push_back(c);
1191         setFont(d->text_.size() - 1, font);
1192 }
1193
1194
1195 void Paragraph::appendString(docstring const & s, Font const & font,
1196                 Change const & change)
1197 {
1198         pos_type end = s.size();
1199         size_t oldsize = d->text_.size();
1200         size_t newsize = oldsize + end;
1201         size_t capacity = d->text_.capacity();
1202         if (newsize >= capacity)
1203                 d->text_.reserve(max(capacity + 100, newsize));
1204
1205         // when appending characters, no need to update tables
1206         d->text_.append(s);
1207
1208         // FIXME: Optimize this!
1209         for (pos_type i = oldsize; i != newsize; ++i) {
1210                 // track change
1211                 d->changes_.insert(change, i);
1212         }
1213         d->fontlist_.set(oldsize, font);
1214         d->fontlist_.set(newsize - 1, font);
1215 }
1216
1217
1218 void Paragraph::insertChar(pos_type pos, char_type c,
1219                            bool trackChanges)
1220 {
1221         d->insertChar(pos, c, Change(trackChanges ?
1222                            Change::INSERTED : Change::UNCHANGED));
1223 }
1224
1225
1226 void Paragraph::insertChar(pos_type pos, char_type c,
1227                            Font const & font, bool trackChanges)
1228 {
1229         d->insertChar(pos, c, Change(trackChanges ?
1230                            Change::INSERTED : Change::UNCHANGED));
1231         setFont(pos, font);
1232 }
1233
1234
1235 void Paragraph::insertChar(pos_type pos, char_type c,
1236                            Font const & font, Change const & change)
1237 {
1238         d->insertChar(pos, c, change);
1239         setFont(pos, font);
1240 }
1241
1242
1243 void Paragraph::insertInset(pos_type pos, Inset * inset,
1244                             Font const & font, Change const & change)
1245 {
1246         insertInset(pos, inset, change);
1247         // Set the font/language of the inset...
1248         setFont(pos, font);
1249 }
1250
1251
1252 bool Paragraph::insetAllowed(InsetCode code)
1253 {
1254         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1255 }
1256
1257
1258 void Paragraph::resetFonts(Font const & font)
1259 {
1260         d->fontlist_.clear();
1261         d->fontlist_.set(0, font);
1262         d->fontlist_.set(d->text_.size() - 1, font);
1263 }
1264
1265 // Gets uninstantiated font setting at position.
1266 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1267                                          pos_type pos) const
1268 {
1269         if (pos > size()) {
1270                 LYXERR0("pos: " << pos << " size: " << size());
1271                 LASSERT(pos <= size(), /**/);
1272         }
1273
1274         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1275         if (cit != d->fontlist_.end())
1276                 return cit->font();
1277
1278         if (pos == size() && !empty())
1279                 return getFontSettings(bparams, pos - 1);
1280
1281         return Font(inherit_font, getParLanguage(bparams));
1282 }
1283
1284
1285 FontSpan Paragraph::fontSpan(pos_type pos) const
1286 {
1287         LASSERT(pos <= size(), /**/);
1288         pos_type start = 0;
1289
1290         FontList::const_iterator cit = d->fontlist_.begin();
1291         FontList::const_iterator end = d->fontlist_.end();
1292         for (; cit != end; ++cit) {
1293                 if (cit->pos() >= pos) {
1294                         if (pos >= beginOfBody())
1295                                 return FontSpan(max(start, beginOfBody()),
1296                                                 cit->pos());
1297                         else
1298                                 return FontSpan(start,
1299                                                 min(beginOfBody() - 1,
1300                                                          cit->pos()));
1301                 }
1302                 start = cit->pos() + 1;
1303         }
1304
1305         // This should not happen, but if so, we take no chances.
1306         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1307         return FontSpan(pos, pos);
1308 }
1309
1310
1311 // Gets uninstantiated font setting at position 0
1312 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1313 {
1314         if (!empty() && !d->fontlist_.empty())
1315                 return d->fontlist_.begin()->font();
1316
1317         return Font(inherit_font, bparams.language);
1318 }
1319
1320
1321 // Gets the fully instantiated font at a given position in a paragraph
1322 // This is basically the same function as Text::GetFont() in text2.cpp.
1323 // The difference is that this one is used for generating the LaTeX file,
1324 // and thus cosmetic "improvements" are disallowed: This has to deliver
1325 // the true picture of the buffer. (Asger)
1326 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1327                                  Font const & outerfont) const
1328 {
1329         LASSERT(pos >= 0, /**/);
1330
1331         Font font = getFontSettings(bparams, pos);
1332
1333         pos_type const body_pos = beginOfBody();
1334         if (pos < body_pos)
1335                 font.fontInfo().realize(d->layout_->labelfont);
1336         else
1337                 font.fontInfo().realize(d->layout_->font);
1338
1339         font.fontInfo().realize(outerfont.fontInfo());
1340         font.fontInfo().realize(bparams.getFont().fontInfo());
1341
1342         return font;
1343 }
1344
1345
1346 Font const Paragraph::getLabelFont
1347         (BufferParams const & bparams, Font const & outerfont) const
1348 {
1349         FontInfo tmpfont = d->layout_->labelfont;
1350         tmpfont.realize(outerfont.fontInfo());
1351         tmpfont.realize(bparams.getFont().fontInfo());
1352         return Font(tmpfont, getParLanguage(bparams));
1353 }
1354
1355
1356 Font const Paragraph::getLayoutFont
1357         (BufferParams const & bparams, Font const & outerfont) const
1358 {
1359         FontInfo tmpfont = d->layout_->font;
1360         tmpfont.realize(outerfont.fontInfo());
1361         tmpfont.realize(bparams.getFont().fontInfo());
1362         return Font(tmpfont, getParLanguage(bparams));
1363 }
1364
1365
1366 /// Returns the height of the highest font in range
1367 FontSize Paragraph::highestFontInRange
1368         (pos_type startpos, pos_type endpos, FontSize def_size) const
1369 {
1370         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1371 }
1372
1373
1374 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1375 {
1376         char_type c = d->text_[pos];
1377         if (!lyxrc.rtl_support)
1378                 return c;
1379
1380         char_type uc = c;
1381         switch (c) {
1382         case '(':
1383                 uc = ')';
1384                 break;
1385         case ')':
1386                 uc = '(';
1387                 break;
1388         case '[':
1389                 uc = ']';
1390                 break;
1391         case ']':
1392                 uc = '[';
1393                 break;
1394         case '{':
1395                 uc = '}';
1396                 break;
1397         case '}':
1398                 uc = '{';
1399                 break;
1400         case '<':
1401                 uc = '>';
1402                 break;
1403         case '>':
1404                 uc = '<';
1405                 break;
1406         }
1407         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1408                 return uc;
1409         return c;
1410 }
1411
1412
1413 void Paragraph::setFont(pos_type pos, Font const & font)
1414 {
1415         LASSERT(pos <= size(), /**/);
1416
1417         // First, reduce font against layout/label font
1418         // Update: The setCharFont() routine in text2.cpp already
1419         // reduces font, so we don't need to do that here. (Asger)
1420         
1421         d->fontlist_.set(pos, font);
1422 }
1423
1424
1425 void Paragraph::makeSameLayout(Paragraph const & par)
1426 {
1427         d->layout_ = par.d->layout_;
1428         d->params_ = par.d->params_;
1429 }
1430
1431
1432 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1433 {
1434         if (isFreeSpacing())
1435                 return false;
1436
1437         int pos = 0;
1438         int count = 0;
1439
1440         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1441                 if (eraseChar(pos, trackChanges))
1442                         ++count;
1443                 else
1444                         ++pos;
1445         }
1446
1447         return count > 0 || pos > 0;
1448 }
1449
1450
1451 bool Paragraph::hasSameLayout(Paragraph const & par) const
1452 {
1453         return par.d->layout_ == d->layout_
1454                 && d->params_.sameLayout(par.d->params_);
1455 }
1456
1457
1458 depth_type Paragraph::getDepth() const
1459 {
1460         return d->params_.depth();
1461 }
1462
1463
1464 depth_type Paragraph::getMaxDepthAfter() const
1465 {
1466         if (d->layout_->isEnvironment())
1467                 return d->params_.depth() + 1;
1468         else
1469                 return d->params_.depth();
1470 }
1471
1472
1473 char Paragraph::getAlign() const
1474 {
1475         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1476                 return d->layout_->align;
1477         else
1478                 return d->params_.align();
1479 }
1480
1481
1482 docstring const & Paragraph::labelString() const
1483 {
1484         return d->params_.labelString();
1485 }
1486
1487
1488 // the next two functions are for the manual labels
1489 docstring const Paragraph::getLabelWidthString() const
1490 {
1491         if (d->layout_->margintype == MARGIN_MANUAL)
1492                 return d->params_.labelWidthString();
1493         else
1494                 return _("Senseless with this layout!");
1495 }
1496
1497
1498 void Paragraph::setLabelWidthString(docstring const & s)
1499 {
1500         d->params_.labelWidthString(s);
1501 }
1502
1503
1504 docstring const Paragraph::translateIfPossible(docstring const & s,
1505                 BufferParams const & bparams) const
1506 {
1507         if (!isAscii(s) || s.empty()) {
1508                 // This must be a user defined layout. We cannot translate
1509                 // this, since gettext accepts only ascii keys.
1510                 return s;
1511         }
1512         // Probably standard layout, try to translate
1513         Messages & m = getMessages(getParLanguage(bparams)->code());
1514         return m.get(to_ascii(s));
1515 }
1516
1517
1518 docstring Paragraph::expandLabel(Layout const & layout,
1519                 BufferParams const & bparams, bool process_appendix) const
1520 {
1521         DocumentClass const & tclass = bparams.documentClass();
1522
1523         docstring fmt;
1524         if (process_appendix && d->params_.appendix())
1525                 fmt = translateIfPossible(layout.labelstring_appendix(),
1526                         bparams);
1527         else
1528                 fmt = translateIfPossible(layout.labelstring(), bparams);
1529
1530         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1531             && !layout.counter.empty())
1532                 fmt = "\\the" + layout.counter;
1533
1534         // handle 'inherited level parts' in 'fmt',
1535         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1536         size_t const i = fmt.find('@', 0);
1537         if (i != docstring::npos) {
1538                 size_t const j = fmt.find('@', i + 1);
1539                 if (j != docstring::npos) {
1540                         docstring parent(fmt, i + 1, j - i - 1);
1541                         docstring label = from_ascii("??");
1542                         if (tclass.hasLayout(parent))
1543                                 docstring label = expandLabel(tclass[parent], bparams,
1544                                                       process_appendix);
1545                         fmt = docstring(fmt, 0, i) + label 
1546                                 + docstring(fmt, j + 1, docstring::npos);
1547                 }
1548         }
1549
1550         return tclass.counters().counterLabel(fmt);
1551 }
1552
1553
1554 void Paragraph::applyLayout(Layout const & new_layout)
1555 {
1556         d->layout_ = &new_layout;
1557         LyXAlignment const oldAlign = d->params_.align();
1558         
1559         if (!(oldAlign & d->layout_->alignpossible)) {
1560                 frontend::Alert::warning(_("Alignment not permitted"), 
1561                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1562                 d->params_.align(LYX_ALIGN_LAYOUT);
1563         }
1564 }
1565
1566
1567 pos_type Paragraph::beginOfBody() const
1568 {
1569         return d->begin_of_body_;
1570 }
1571
1572
1573 void Paragraph::setBeginOfBody()
1574 {
1575         if (d->layout_->labeltype != LABEL_MANUAL) {
1576                 d->begin_of_body_ = 0;
1577                 return;
1578         }
1579
1580         // Unroll the first two cycles of the loop
1581         // and remember the previous character to
1582         // remove unnecessary getChar() calls
1583         pos_type i = 0;
1584         pos_type end = size();
1585         if (i < end && !isNewline(i)) {
1586                 ++i;
1587                 char_type previous_char = 0;
1588                 char_type temp = 0;
1589                 if (i < end) {
1590                         previous_char = d->text_[i];
1591                         if (!isNewline(i)) {
1592                                 ++i;
1593                                 while (i < end && previous_char != ' ') {
1594                                         temp = d->text_[i];
1595                                         if (isNewline(i))
1596                                                 break;
1597                                         ++i;
1598                                         previous_char = temp;
1599                                 }
1600                         }
1601                 }
1602         }
1603
1604         d->begin_of_body_ = i;
1605 }
1606
1607
1608 bool Paragraph::forcePlainLayout() const
1609 {
1610         Inset const * const inset = inInset();
1611         if (!inset)
1612                 return true;
1613         return inset->forcePlainLayout();
1614 }
1615
1616
1617 bool Paragraph::allowParagraphCustomization() const
1618 {
1619         Inset const * const inset = inInset();
1620         if (!inset)
1621                 return true;
1622         return inset->allowParagraphCustomization();
1623 }
1624
1625
1626 bool Paragraph::usePlainLayout() const
1627 {
1628         Inset const * const inset = inInset();
1629         if (!inset)
1630                 return false;
1631         return inset->usePlainLayout();
1632 }
1633
1634
1635 namespace {
1636
1637 // paragraphs inside floats need different alignment tags to avoid
1638 // unwanted space
1639
1640 bool noTrivlistCentering(InsetCode code)
1641 {
1642         return code == FLOAT_CODE || code == WRAP_CODE;
1643 }
1644
1645
1646 string correction(string const & orig)
1647 {
1648         if (orig == "flushleft")
1649                 return "raggedright";
1650         if (orig == "flushright")
1651                 return "raggedleft";
1652         if (orig == "center")
1653                 return "centering";
1654         return orig;
1655 }
1656
1657
1658 string const corrected_env(string const & suffix, string const & env,
1659         InsetCode code)
1660 {
1661         string output = suffix + "{";
1662         if (noTrivlistCentering(code))
1663                 output += correction(env);
1664         else
1665                 output += env;
1666         output += "}";
1667         if (suffix == "\\begin")
1668                 output += "\n";
1669         return output;
1670 }
1671
1672
1673 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1674 {
1675         if (!contains(str, "\n"))
1676                 column += str.size();
1677         else {
1678                 string tmp;
1679                 texrow.newline();
1680                 column = rsplit(str, tmp, '\n').size();
1681         }
1682 }
1683
1684 } // namespace anon
1685
1686
1687 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1688                                  odocstream & os, TexRow & texrow,
1689                                  bool moving_arg) const
1690 {
1691         int column = 0;
1692
1693         if (params_.noindent()) {
1694                 os << "\\noindent ";
1695                 column += 10;
1696         }
1697         
1698         LyXAlignment const curAlign = params_.align();
1699
1700         if (curAlign == layout_->align)
1701                 return column;
1702
1703         switch (curAlign) {
1704         case LYX_ALIGN_NONE:
1705         case LYX_ALIGN_BLOCK:
1706         case LYX_ALIGN_LAYOUT:
1707         case LYX_ALIGN_SPECIAL:
1708                 break;
1709         case LYX_ALIGN_LEFT:
1710         case LYX_ALIGN_RIGHT:
1711         case LYX_ALIGN_CENTER:
1712                 if (moving_arg) {
1713                         os << "\\protect";
1714                         column += 8;
1715                 }
1716                 break;
1717         }
1718
1719         switch (curAlign) {
1720         case LYX_ALIGN_NONE:
1721         case LYX_ALIGN_BLOCK:
1722         case LYX_ALIGN_LAYOUT:
1723         case LYX_ALIGN_SPECIAL:
1724                 break;
1725         case LYX_ALIGN_LEFT: {
1726                 string output;
1727                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1728                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1729                 else
1730                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1731                 os << from_ascii(output);
1732                 adjust_row_column(output, texrow, column);
1733                 break;
1734         } case LYX_ALIGN_RIGHT: {
1735                 string output;
1736                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1737                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1738                 else
1739                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1740                 os << from_ascii(output);
1741                 adjust_row_column(output, texrow, column);
1742                 break;
1743         } case LYX_ALIGN_CENTER: {
1744                 string output;
1745                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1746                 os << from_ascii(output);
1747                 adjust_row_column(output, texrow, column);
1748                 break;
1749         }
1750         }
1751
1752         return column;
1753 }
1754
1755
1756 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1757                                odocstream & os, TexRow & texrow,
1758                                bool moving_arg) const
1759 {
1760         int column = 0;
1761
1762         switch (params_.align()) {
1763         case LYX_ALIGN_NONE:
1764         case LYX_ALIGN_BLOCK:
1765         case LYX_ALIGN_LAYOUT:
1766         case LYX_ALIGN_SPECIAL:
1767                 break;
1768         case LYX_ALIGN_LEFT:
1769         case LYX_ALIGN_RIGHT:
1770         case LYX_ALIGN_CENTER:
1771                 if (moving_arg) {
1772                         os << "\\protect";
1773                         column = 8;
1774                 }
1775                 break;
1776         }
1777
1778         switch (params_.align()) {
1779         case LYX_ALIGN_NONE:
1780         case LYX_ALIGN_BLOCK:
1781         case LYX_ALIGN_LAYOUT:
1782         case LYX_ALIGN_SPECIAL:
1783                 break;
1784         case LYX_ALIGN_LEFT: {
1785                 string output;
1786                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1787                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1788                 else
1789                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1790                 os << from_ascii(output);
1791                 adjust_row_column(output, texrow, column);
1792                 break;
1793         } case LYX_ALIGN_RIGHT: {
1794                 string output;
1795                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1796                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1797                 else
1798                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1799                 os << from_ascii(output);
1800                 adjust_row_column(output, texrow, column);
1801                 break;
1802         } case LYX_ALIGN_CENTER: {
1803                 string output;
1804                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1805                 os << from_ascii(output);
1806                 adjust_row_column(output, texrow, column);
1807                 break;
1808         }
1809         }
1810
1811         return column;
1812 }
1813
1814
1815 // This one spits out the text of the paragraph
1816 bool Paragraph::latex(BufferParams const & bparams,
1817                                 Font const & outerfont,
1818                                 odocstream & os, TexRow & texrow,
1819                                 OutputParams const & runparams) const
1820 {
1821         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1822
1823         bool return_value = false;
1824
1825         bool asdefault = forcePlainLayout();
1826
1827         Layout const & style = asdefault ?
1828                 bparams.documentClass().emptyLayout() :
1829                 *d->layout_;
1830
1831         // Current base font for all inherited font changes, without any
1832         // change caused by an individual character, except for the language:
1833         // It is set to the language of the first character.
1834         // As long as we are in the label, this font is the base font of the
1835         // label. Before the first body character it is set to the base font
1836         // of the body.
1837         Font basefont;
1838
1839         // Maybe we have to create a optional argument.
1840         pos_type body_pos = beginOfBody();
1841         unsigned int column = 0;
1842
1843         if (body_pos > 0) {
1844                 // the optional argument is kept in curly brackets in
1845                 // case it contains a ']'
1846                 os << "[{";
1847                 column += 2;
1848                 basefont = getLabelFont(bparams, outerfont);
1849         } else {
1850                 basefont = getLayoutFont(bparams, outerfont);
1851         }
1852
1853         // Which font is currently active?
1854         Font running_font(basefont);
1855         // Do we have an open font change?
1856         bool open_font = false;
1857
1858         Change runningChange = Change(Change::UNCHANGED);
1859
1860         texrow.start(id(), 0);
1861
1862         // if the paragraph is empty, the loop will not be entered at all
1863         if (empty()) {
1864                 if (style.isCommand()) {
1865                         os << '{';
1866                         ++column;
1867                 }
1868                 if (!asdefault)
1869                         column += d->startTeXParParams(bparams, os, texrow,
1870                                                     runparams.moving_arg);
1871         }
1872
1873         for (pos_type i = 0; i < size(); ++i) {
1874                 // First char in paragraph or after label?
1875                 if (i == body_pos) {
1876                         if (body_pos > 0) {
1877                                 if (open_font) {
1878                                         column += running_font.latexWriteEndChanges(
1879                                                 os, bparams, runparams,
1880                                                 basefont, basefont);
1881                                         open_font = false;
1882                                 }
1883                                 basefont = getLayoutFont(bparams, outerfont);
1884                                 running_font = basefont;
1885
1886                                 column += Changes::latexMarkChange(os, bparams,
1887                                                 runningChange, Change(Change::UNCHANGED));
1888                                 runningChange = Change(Change::UNCHANGED);
1889
1890                                 os << "}] ";
1891                                 column +=3;
1892                         }
1893                         if (style.isCommand()) {
1894                                 os << '{';
1895                                 ++column;
1896                         }
1897
1898                         if (!asdefault)
1899                                 column += d->startTeXParParams(bparams, os,
1900                                                             texrow,
1901                                                             runparams.moving_arg);
1902                 }
1903
1904                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1905                                                                  : lookupChange(i);
1906
1907                 if (bparams.outputChanges && runningChange != change) {
1908                         if (open_font) {
1909                                 column += running_font.latexWriteEndChanges(
1910                                                 os, bparams, runparams, basefont, basefont);
1911                                 open_font = false;
1912                         }
1913                         basefont = getLayoutFont(bparams, outerfont);
1914                         running_font = basefont;
1915
1916                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1917                         runningChange = change;
1918                 }
1919
1920                 // do not output text which is marked deleted
1921                 // if change tracking output is disabled
1922                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1923                         continue;
1924                 }
1925
1926                 ++column;
1927
1928                 // Fully instantiated font
1929                 Font const font = getFont(bparams, i, outerfont);
1930
1931                 Font const last_font = running_font;
1932
1933                 // Do we need to close the previous font?
1934                 if (open_font &&
1935                     (font != running_font ||
1936                      font.language() != running_font.language()))
1937                 {
1938                         column += running_font.latexWriteEndChanges(
1939                                         os, bparams, runparams, basefont,
1940                                         (i == body_pos-1) ? basefont : font);
1941                         running_font = basefont;
1942                         open_font = false;
1943                 }
1944
1945                 // close babel's font environment before opening CJK.
1946                 if (!running_font.language()->babel().empty() &&
1947                     font.language()->encoding()->package() == Encoding::CJK) {
1948                                 string end_tag = subst(lyxrc.language_command_end,
1949                                                         "$$lang",
1950                                                         running_font.language()->babel());
1951                                 os << from_ascii(end_tag);
1952                                 column += end_tag.length();
1953                 }
1954
1955                 // Switch file encoding if necessary (and allowed)
1956                 if (!runparams.verbatim && 
1957                     runparams.encoding->package() != Encoding::none &&
1958                     font.language()->encoding()->package() != Encoding::none) {
1959                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1960                                         runparams, *(font.language()->encoding()));
1961                         if (enc_switch.first) {
1962                                 column += enc_switch.second;
1963                                 runparams.encoding = font.language()->encoding();
1964                         }
1965                 }
1966
1967                 char_type const c = d->text_[i];
1968
1969                 // Do we need to change font?
1970                 if ((font != running_font ||
1971                      font.language() != running_font.language()) &&
1972                         i != body_pos - 1)
1973                 {
1974                         odocstringstream ods;
1975                         column += font.latexWriteStartChanges(ods, bparams,
1976                                                               runparams, basefont,
1977                                                               last_font);
1978                         running_font = font;
1979                         open_font = true;
1980                         docstring fontchange = ods.str();
1981                         // check if the fontchange ends with a trailing blank
1982                         // (like "\small " (see bug 3382)
1983                         if (suffixIs(fontchange, ' ') && c == ' ')
1984                                 os << fontchange.substr(0, fontchange.size() - 1) 
1985                                    << from_ascii("{}");
1986                         else
1987                                 os << fontchange;
1988                 }
1989
1990                 if (c == ' ') {
1991                         // FIXME: integrate this case in latexSpecialChar
1992                         // Do not print the separation of the optional argument
1993                         // if style.pass_thru is false. This works because
1994                         // latexSpecialChar ignores spaces if
1995                         // style.pass_thru is false.
1996                         if (i != body_pos - 1) {
1997                                 if (d->simpleTeXBlanks(
1998                                                 runparams, os, texrow,
1999                                                 i, column, font, style)) {
2000                                         // A surrogate pair was output. We
2001                                         // must not call latexSpecialChar
2002                                         // in this iteration, since it would output
2003                                         // the combining character again.
2004                                         ++i;
2005                                         continue;
2006                                 }
2007                         }
2008                 }
2009
2010                 OutputParams rp = runparams;
2011                 rp.free_spacing = style.free_spacing;
2012                 rp.local_font = &font;
2013                 rp.intitle = style.intitle;
2014
2015                 // Two major modes:  LaTeX or plain
2016                 // Handle here those cases common to both modes
2017                 // and then split to handle the two modes separately.
2018                 if (c == META_INSET)
2019                         d->latexInset(bparams, os,
2020                                         texrow, rp, running_font,
2021                                         basefont, outerfont, open_font,
2022                                         runningChange, style, i, column);
2023                 else {
2024                         try {
2025                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2026                                         style, i, column);
2027                         } catch (EncodingException & e) {
2028                                 if (runparams.dryrun) {
2029                                         os << "<" << _("LyX Warning: ")
2030                                            << _("uncodable character") << " '";
2031                                         os.put(c);
2032                                         os << "'>";
2033                                 } else {
2034                                         // add location information and throw again.
2035                                         e.par_id = id();
2036                                         e.pos = i;
2037                                         throw(e);
2038                                 }
2039                         }
2040                 }
2041
2042                 // Set the encoding to that returned from latexSpecialChar (see
2043                 // comment for encoding member in OutputParams.h)
2044                 runparams.encoding = rp.encoding;
2045         }
2046
2047         // If we have an open font definition, we have to close it
2048         if (open_font) {
2049 #ifdef FIXED_LANGUAGE_END_DETECTION
2050                 if (next_) {
2051                         running_font
2052                                 .latexWriteEndChanges(os, bparams, runparams,
2053                                         basefont,
2054                                         next_->getFont(bparams, 0, outerfont));
2055                 } else {
2056                         running_font.latexWriteEndChanges(os, bparams,
2057                                         runparams, basefont, basefont);
2058                 }
2059 #else
2060 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2061 //FIXME: there as we start another \selectlanguage with the next paragraph if
2062 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2063                 running_font.latexWriteEndChanges(os, bparams, runparams,
2064                                 basefont, basefont);
2065 #endif
2066         }
2067
2068         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2069
2070         // Needed if there is an optional argument but no contents.
2071         if (body_pos > 0 && body_pos == size()) {
2072                 os << "}]~";
2073                 return_value = false;
2074         }
2075
2076         if (!asdefault) {
2077                 column += d->endTeXParParams(bparams, os, texrow,
2078                                           runparams.moving_arg);
2079         }
2080
2081         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2082         return return_value;
2083 }
2084
2085
2086 bool Paragraph::emptyTag() const
2087 {
2088         for (pos_type i = 0; i < size(); ++i) {
2089                 if (Inset const * inset = getInset(i)) {
2090                         InsetCode lyx_code = inset->lyxCode();
2091                         if (lyx_code != TOC_CODE &&
2092                             lyx_code != INCLUDE_CODE &&
2093                             lyx_code != GRAPHICS_CODE &&
2094                             lyx_code != ERT_CODE &&
2095                             lyx_code != LISTINGS_CODE &&
2096                             lyx_code != FLOAT_CODE &&
2097                             lyx_code != TABULAR_CODE) {
2098                                 return false;
2099                         }
2100                 } else {
2101                         char_type c = d->text_[i];
2102                         if (c != ' ' && c != '\t')
2103                                 return false;
2104                 }
2105         }
2106         return true;
2107 }
2108
2109
2110 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2111         const
2112 {
2113         for (pos_type i = 0; i < size(); ++i) {
2114                 if (Inset const * inset = getInset(i)) {
2115                         InsetCode lyx_code = inset->lyxCode();
2116                         if (lyx_code == LABEL_CODE) {
2117                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2118                                 docstring const & id = il->getParam("name");
2119                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2120                         }
2121                 }
2122         }
2123         return string();
2124 }
2125
2126
2127 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2128         const
2129 {
2130         pos_type i;
2131         for (i = 0; i < size(); ++i) {
2132                 if (Inset const * inset = getInset(i)) {
2133                         inset->docbook(os, runparams);
2134                 } else {
2135                         char_type c = d->text_[i];
2136                         if (c == ' ')
2137                                 break;
2138                         os << sgml::escapeChar(c);
2139                 }
2140         }
2141         return i;
2142 }
2143
2144
2145 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2146 {
2147         Font font_old;
2148         pos_type size = text_.size();
2149         for (pos_type i = initial; i < size; ++i) {
2150                 Font font = owner_->getFont(buf.params(), i, outerfont);
2151                 if (text_[i] == META_INSET)
2152                         return false;
2153                 if (i != initial && font != font_old)
2154                         return false;
2155                 font_old = font;
2156         }
2157
2158         return true;
2159 }
2160
2161
2162 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2163                                     odocstream & os,
2164                                     OutputParams const & runparams,
2165                                     Font const & outerfont,
2166                                     pos_type initial) const
2167 {
2168         bool emph_flag = false;
2169
2170         Layout const & style = *d->layout_;
2171         FontInfo font_old =
2172                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2173
2174         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2175                 os << "]]>";
2176
2177         // parsing main loop
2178         for (pos_type i = initial; i < size(); ++i) {
2179                 Font font = getFont(buf.params(), i, outerfont);
2180
2181                 // handle <emphasis> tag
2182                 if (font_old.emph() != font.fontInfo().emph()) {
2183                         if (font.fontInfo().emph() == FONT_ON) {
2184                                 os << "<emphasis>";
2185                                 emph_flag = true;
2186                         } else if (i != initial) {
2187                                 os << "</emphasis>";
2188                                 emph_flag = false;
2189                         }
2190                 }
2191
2192                 if (Inset const * inset = getInset(i)) {
2193                         inset->docbook(os, runparams);
2194                 } else {
2195                         char_type c = d->text_[i];
2196
2197                         if (style.pass_thru)
2198                                 os.put(c);
2199                         else
2200                                 os << sgml::escapeChar(c);
2201                 }
2202                 font_old = font.fontInfo();
2203         }
2204
2205         if (emph_flag) {
2206                 os << "</emphasis>";
2207         }
2208
2209         if (style.free_spacing)
2210                 os << '\n';
2211         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2212                 os << "<![CDATA[";
2213 }
2214
2215
2216 bool Paragraph::isHfill(pos_type pos) const
2217 {
2218         Inset const * inset = getInset(pos);
2219         return inset && (inset->lyxCode() == SPACE_CODE &&
2220                          inset->isStretchableSpace());
2221 }
2222
2223
2224 bool Paragraph::isNewline(pos_type pos) const
2225 {
2226         Inset const * inset = getInset(pos);
2227         return inset && inset->lyxCode() == NEWLINE_CODE;
2228 }
2229
2230
2231 bool Paragraph::isLineSeparator(pos_type pos) const
2232 {
2233         char_type const c = d->text_[pos];
2234         if (isLineSeparatorChar(c))
2235                 return true;
2236         Inset const * inset = getInset(pos);
2237         return inset && inset->isLineSeparator();
2238 }
2239
2240
2241 /// Used by the spellchecker
2242 bool Paragraph::isLetter(pos_type pos) const
2243 {
2244         if (Inset const * inset = getInset(pos))
2245                 return inset->isLetter();
2246         char_type const c = d->text_[pos];
2247         return isLetterChar(c) || isDigit(c);
2248 }
2249
2250
2251 bool Paragraph::isChar(pos_type pos) const
2252 {
2253         if (Inset const * inset = getInset(pos))
2254                 return inset->isChar();
2255         char_type const c = d->text_[pos];
2256         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2257 }
2258
2259
2260 bool Paragraph::isSpace(pos_type pos) const
2261 {
2262         if (Inset const * inset = getInset(pos))
2263                 return inset->isSpace();
2264         char_type const c = d->text_[pos];
2265         return lyx::isSpace(c);
2266 }
2267
2268
2269 Language const *
2270 Paragraph::getParLanguage(BufferParams const & bparams) const
2271 {
2272         if (!empty())
2273                 return getFirstFontSettings(bparams).language();
2274         // FIXME: we should check the prev par as well (Lgb)
2275         return bparams.language;
2276 }
2277
2278
2279 bool Paragraph::isRTL(BufferParams const & bparams) const
2280 {
2281         return lyxrc.rtl_support
2282                 && getParLanguage(bparams)->rightToLeft()
2283                 && ownerCode() != ERT_CODE
2284                 && ownerCode() != LISTINGS_CODE;
2285 }
2286
2287
2288 void Paragraph::changeLanguage(BufferParams const & bparams,
2289                                Language const * from, Language const * to)
2290 {
2291         // change language including dummy font change at the end
2292         for (pos_type i = 0; i <= size(); ++i) {
2293                 Font font = getFontSettings(bparams, i);
2294                 if (font.language() == from) {
2295                         font.setLanguage(to);
2296                         setFont(i, font);
2297                 }
2298         }
2299 }
2300
2301
2302 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2303 {
2304         Language const * doc_language = bparams.language;
2305         FontList::const_iterator cit = d->fontlist_.begin();
2306         FontList::const_iterator end = d->fontlist_.end();
2307
2308         for (; cit != end; ++cit)
2309                 if (cit->font().language() != ignore_language &&
2310                     cit->font().language() != latex_language &&
2311                     cit->font().language() != doc_language)
2312                         return true;
2313         return false;
2314 }
2315
2316
2317 docstring Paragraph::asString(int options) const
2318 {
2319         return asString(0, size(), options);
2320 }
2321
2322
2323 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2324 {
2325         odocstringstream os;
2326
2327         if (beg == 0 
2328                 && options & AS_STR_LABEL
2329                 && !d->params_.labelString().empty())
2330                 os << d->params_.labelString() << ' ';
2331
2332         for (pos_type i = beg; i < end; ++i) {
2333                 char_type const c = d->text_[i];
2334                 if (isPrintable(c))
2335                         os.put(c);
2336                 else if (c == META_INSET && options & AS_STR_INSETS)
2337                         getInset(i)->textString(os);
2338         }
2339
2340         return os.str();
2341 }
2342
2343
2344 void Paragraph::setInsetOwner(Inset * inset)
2345 {
2346         d->inset_owner_ = inset;
2347 }
2348
2349
2350 int Paragraph::id() const
2351 {
2352         return d->id_;
2353 }
2354
2355
2356 Layout const & Paragraph::layout() const
2357 {
2358         return *d->layout_;
2359 }
2360
2361
2362 void Paragraph::setLayout(Layout const & layout)
2363 {
2364         d->layout_ = &layout;
2365 }
2366
2367
2368 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2369 {
2370         if (usePlainLayout())
2371                 setLayout(tclass.emptyLayout());
2372         else
2373                 setLayout(tclass.defaultLayout());
2374 }
2375
2376
2377 Inset * Paragraph::inInset() const
2378 {
2379         return d->inset_owner_;
2380 }
2381
2382
2383 InsetCode Paragraph::ownerCode() const
2384 {
2385         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2386 }
2387
2388
2389 ParagraphParameters & Paragraph::params()
2390 {
2391         return d->params_;
2392 }
2393
2394
2395 ParagraphParameters const & Paragraph::params() const
2396 {
2397         return d->params_;
2398 }
2399
2400
2401 bool Paragraph::isFreeSpacing() const
2402 {
2403         if (d->layout_->free_spacing)
2404                 return true;
2405         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2406 }
2407
2408
2409 bool Paragraph::allowEmpty() const
2410 {
2411         if (d->layout_->keepempty)
2412                 return true;
2413         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2414 }
2415
2416
2417 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2418 {
2419         if (!Encodings::isArabicChar(c))
2420                 return c;
2421
2422         char_type prev_char = ' ';
2423         char_type next_char = ' ';
2424
2425         for (pos_type i = pos - 1; i >= 0; --i) {
2426                 char_type const par_char = d->text_[i];
2427                 if (!Encodings::isArabicComposeChar(par_char)) {
2428                         prev_char = par_char;
2429                         break;
2430                 }
2431         }
2432
2433         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2434                 char_type const par_char = d->text_[i];
2435                 if (!Encodings::isArabicComposeChar(par_char)) {
2436                         next_char = par_char;
2437                         break;
2438                 }
2439         }
2440
2441         if (Encodings::isArabicChar(next_char)) {
2442                 if (Encodings::isArabicChar(prev_char) &&
2443                         !Encodings::isArabicSpecialChar(prev_char))
2444                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2445                 else
2446                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2447         } else {
2448                 if (Encodings::isArabicChar(prev_char) &&
2449                         !Encodings::isArabicSpecialChar(prev_char))
2450                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2451                 else
2452                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2453         }
2454 }
2455
2456
2457 int Paragraph::checkBiblio(Buffer const & buffer)
2458 {
2459         // FIXME From JS:
2460         // This is getting more and more a mess. ...We really should clean
2461         // up this bibitem issue for 1.6. See also bug 2743.
2462
2463         // Add bibitem insets if necessary
2464         if (d->layout_->labeltype != LABEL_BIBLIO)
2465                 return 0;
2466
2467         bool hasbibitem = !d->insetlist_.empty()
2468                 // Insist on it being in pos 0
2469                 && d->text_[0] == META_INSET
2470                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2471
2472         bool track_changes = buffer.params().trackChanges;
2473
2474         docstring oldkey;
2475         docstring oldlabel;
2476
2477         // remove a bibitem in pos != 0
2478         // restore it later in pos 0 if necessary
2479         // (e.g. if a user inserts contents _before_ the item)
2480         // we're assuming there's only one of these, which there
2481         // should be.
2482         int erasedInsetPosition = -1;
2483         InsetList::iterator it = d->insetlist_.begin();
2484         InsetList::iterator end = d->insetlist_.end();
2485         for (; it != end; ++it)
2486                 if (it->inset->lyxCode() == BIBITEM_CODE
2487                     && it->pos > 0) {
2488                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2489                         oldkey = olditem->getParam("key");
2490                         oldlabel = olditem->getParam("label");
2491                         erasedInsetPosition = it->pos;
2492                         eraseChar(erasedInsetPosition, track_changes);
2493                         break;
2494         }
2495
2496         // There was an InsetBibitem at the beginning, and we didn't
2497         // have to erase one.
2498         if (hasbibitem && erasedInsetPosition < 0)
2499                         return 0;
2500
2501         // There was an InsetBibitem at the beginning and we did have to
2502         // erase one. So we give its properties to the beginning inset.
2503         if (hasbibitem) {
2504                 InsetBibitem * inset =
2505                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2506                 if (!oldkey.empty())
2507                         inset->setParam("key", oldkey);
2508                 inset->setParam("label", oldlabel);
2509                 return -erasedInsetPosition;
2510         }
2511
2512         // There was no inset at the beginning, so we need to create one with
2513         // the key and label of the one we erased.
2514         InsetBibitem * inset = 
2515                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2516         // restore values of previously deleted item in this par.
2517         if (!oldkey.empty())
2518                 inset->setParam("key", oldkey);
2519         inset->setParam("label", oldlabel);
2520         insertInset(0, static_cast<Inset *>(inset),
2521                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2522
2523         return 1;
2524 }
2525
2526
2527 void Paragraph::checkAuthors(AuthorList const & authorList)
2528 {
2529         d->changes_.checkAuthors(authorList);
2530 }
2531
2532
2533 bool Paragraph::isUnchanged(pos_type pos) const
2534 {
2535         return lookupChange(pos).type == Change::UNCHANGED;
2536 }
2537
2538
2539 bool Paragraph::isInserted(pos_type pos) const
2540 {
2541         return lookupChange(pos).type == Change::INSERTED;
2542 }
2543
2544
2545 bool Paragraph::isDeleted(pos_type pos) const
2546 {
2547         return lookupChange(pos).type == Change::DELETED;
2548 }
2549
2550
2551 InsetList const & Paragraph::insetList() const
2552 {
2553         return d->insetlist_;
2554 }
2555
2556
2557 Inset * Paragraph::releaseInset(pos_type pos)
2558 {
2559         Inset * inset = d->insetlist_.release(pos);
2560         /// does not honour change tracking!
2561         eraseChar(pos, false);
2562         return inset;
2563 }
2564
2565
2566 Inset * Paragraph::getInset(pos_type pos)
2567 {
2568         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2569                  ? d->insetlist_.get(pos) : 0;
2570 }
2571
2572
2573 Inset const * Paragraph::getInset(pos_type pos) const
2574 {
2575         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2576                  ? d->insetlist_.get(pos) : 0;
2577 }
2578
2579
2580 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2581                 pos_type & right, TextCase action)
2582 {
2583         // process sequences of modified characters; in change
2584         // tracking mode, this approach results in much better
2585         // usability than changing case on a char-by-char basis
2586         docstring changes;
2587
2588         bool const trackChanges = bparams.trackChanges;
2589
2590         bool capitalize = true;
2591
2592         for (; pos < right; ++pos) {
2593                 char_type oldChar = d->text_[pos];
2594                 char_type newChar = oldChar;
2595
2596                 // ignore insets and don't play with deleted text!
2597                 if (oldChar != META_INSET && !isDeleted(pos)) {
2598                         switch (action) {
2599                                 case text_lowercase:
2600                                         newChar = lowercase(oldChar);
2601                                         break;
2602                                 case text_capitalization:
2603                                         if (capitalize) {
2604                                                 newChar = uppercase(oldChar);
2605                                                 capitalize = false;
2606                                         }
2607                                         break;
2608                                 case text_uppercase:
2609                                         newChar = uppercase(oldChar);
2610                                         break;
2611                         }
2612                 }
2613
2614                 if (!isLetter(pos) || isDeleted(pos)) {
2615                         // permit capitalization again
2616                         capitalize = true;
2617                 }
2618
2619                 if (oldChar != newChar)
2620                         changes += newChar;
2621
2622                 if (oldChar == newChar || pos == right - 1) {
2623                         if (oldChar != newChar) {
2624                                 // step behind the changing area
2625                                 pos++;
2626                         }
2627                         int erasePos = pos - changes.size();
2628                         for (size_t i = 0; i < changes.size(); i++) {
2629                                 insertChar(pos, changes[i],
2630                                         getFontSettings(bparams,
2631                                         erasePos),
2632                                         trackChanges);
2633                                 if (!eraseChar(erasePos, trackChanges)) {
2634                                         ++erasePos;
2635                                         ++pos; // advance
2636                                         ++right; // expand selection
2637                                 }
2638                         }
2639                         changes.clear();
2640                 }
2641         }
2642 }
2643
2644
2645 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2646                 pos_type pos, bool del) const
2647 {
2648         int const strsize = str.length();
2649         int i = 0;
2650         pos_type const parsize = d->text_.size();
2651         for (i = 0; pos + i < parsize; ++i) {
2652                 if (i >= strsize)
2653                         break;
2654                 if (cs && str[i] != d->text_[pos + i])
2655                         break;
2656                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2657                         break;
2658                 if (!del && isDeleted(pos + i))
2659                         break;
2660         }
2661
2662         if (i != strsize)
2663                 return false;
2664
2665         // if necessary, check whether string matches word
2666         if (mw) {
2667                 if (pos > 0 && isLetter(pos - 1))
2668                         return false;
2669                 if (pos + strsize < parsize
2670                         && isLetter(pos + strsize))
2671                         return false;
2672         }
2673
2674         return true;
2675 }
2676
2677
2678 char_type Paragraph::getChar(pos_type pos) const
2679 {
2680         return d->text_[pos];
2681 }
2682
2683
2684 pos_type Paragraph::size() const
2685 {
2686         return d->text_.size();
2687 }
2688
2689
2690 bool Paragraph::empty() const
2691 {
2692         return d->text_.empty();
2693 }
2694
2695
2696 bool Paragraph::isInset(pos_type pos) const
2697 {
2698         return d->text_[pos] == META_INSET;
2699 }
2700
2701
2702 bool Paragraph::isSeparator(pos_type pos) const
2703 {
2704         //FIXME: Are we sure this can be the only separator?
2705         return d->text_[pos] == ' ';
2706 }
2707
2708
2709 void Paragraph::deregisterWords()
2710 {
2711         Private::Words::const_iterator it;
2712         WordList & wl = theWordList();
2713         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2714                 wl.remove(*it);
2715         d->words_.clear();
2716 }
2717
2718
2719 void Paragraph::collectWords(CursorSlice const & sl)
2720 {
2721         // find new words
2722         bool inword = false;
2723
2724         //lyxerr << "Words: ";
2725         pos_type n = size();
2726         for (pos_type pos = 0; pos != n; ++pos) {
2727                 if (isDeleted(pos))
2728                         continue;
2729
2730                 if (!isLetter(pos)) {
2731                         inword = false;
2732                         continue;
2733                 }
2734
2735                 if (inword)
2736                         continue;
2737
2738                 inword = true;
2739                 CursorSlice from = sl;
2740                 CursorSlice to = sl;
2741                 from.pos() = pos;
2742                 to.pos() = pos;
2743                 from.text()->getWord(from, to, WHOLE_WORD);
2744                 if (to.pos() - from.pos() < 6)
2745                         continue;
2746                 docstring word = asString(from.pos(), to.pos(), false);
2747                 d->words_.insert(word);
2748                 //lyxerr << word << " ";
2749         }
2750         //lyxerr << std::endl;
2751 }
2752
2753
2754 void Paragraph::registerWords()
2755 {
2756         Private::Words::const_iterator it;
2757         WordList & wl = theWordList();
2758         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2759                 wl.insert(*it);
2760 }
2761
2762
2763 void Paragraph::updateWords(CursorSlice const & sl)
2764 {
2765         LASSERT(&sl.paragraph() == this, /**/);
2766         deregisterWords();
2767         collectWords(sl);
2768         registerWords();
2769 }
2770
2771 } // namespace lyx