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