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