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