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