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