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