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