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