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