]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
* LaTeXFeatures.cpp (useLanguage):
[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 "debug.h"
28 #include "gettext.h"
29 #include "InsetList.h"
30 #include "Language.h"
31 #include "LaTeXFeatures.h"
32 #include "Layout.h"
33 #include "Length.h"
34 #include "Font.h"
35 #include "FontList.h"
36 #include "LyXRC.h"
37 #include "Messages.h"
38 #include "OutputParams.h"
39 #include "output_latex.h"
40 #include "paragraph_funcs.h"
41 #include "ParagraphParameters.h"
42 #include "sgml.h"
43 #include "TextClass.h"
44 #include "TexRow.h"
45 #include "VSpace.h"
46
47 #include "frontends/alert.h"
48 #include "frontends/FontMetrics.h"
49
50 #include "insets/InsetBibitem.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetOptArg.h"
53
54 #include "support/lstrings.h"
55 #include "support/textutils.h"
56 #include "support/convert.h"
57 #include "support/unicode.h"
58
59 #include <sstream>
60 #include <vector>
61
62 using std::endl;
63 using std::string;
64 using std::ostream;
65
66 namespace lyx {
67
68 using support::contains;
69 using support::lowercase;
70 using support::prefixIs;
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                         os << "\\\\\n";
707                 }
708                 texrow.newline();
709                 texrow.start(owner_->id(), i + 1);
710                 column = 0;
711         }
712
713         if (owner_->lookupChange(i).type == Change::DELETED) {
714                 if( ++runparams.inDeletedInset == 1)
715                         runparams.changeOfDeletedInset = owner_->lookupChange(i);
716         }
717
718         if (inset->canTrackChanges()) {
719                 column += Changes::latexMarkChange(os, bparams, running_change,
720                         Change(Change::UNCHANGED));
721                 running_change = Change(Change::UNCHANGED);
722         }
723
724         bool close = false;
725         odocstream::pos_type const len = os.tellp();
726
727         if (inset->forceLTR() 
728             && running_font.isRightToLeft()
729                 // ERT is an exception, it should be output with no decorations at all
730                 && inset->lyxCode() != ERT_CODE) {
731                 if (running_font.language()->lang() == "farsi")
732                         os << "\\beginL{}";
733                 else
734                         os << "\\L{";
735                 close = true;
736         }
737
738         // FIXME: Bug: we can have an empty font change here!
739         // if there has just been a font change, we are going to close it
740         // right now, which means stupid latex code like \textsf{}. AFAIK,
741         // this does not harm dvi output. A minor bug, thus (JMarc)
742
743         // Some insets cannot be inside a font change command.
744         // However, even such insets *can* be placed in \L or \R
745         // or their equivalents (for RTL language switches), so we don't
746         // close the language in those cases.
747         // ArabTeX, though, cannot handle this special behavior, it seems.
748         bool arabtex = basefont.language()->lang() == "arabic_arabtex"
749                 || running_font.language()->lang() == "arabic_arabtex";
750         if (open_font && inset->noFontChange()) {
751                 bool closeLanguage = arabtex
752                         || basefont.isRightToLeft() == running_font.isRightToLeft();
753                 unsigned int count = running_font.latexWriteEndChanges(os,
754                         bparams, runparams, basefont, basefont, closeLanguage);
755                 column += count;
756                 // if any font properties were closed, update the running_font, 
757                 // making sure, however, to leave the language as it was
758                 if (count > 0) {
759                         // FIXME: probably a better way to keep track of the old 
760                         // language, than copying the entire font?
761                         Font const copy_font(running_font);
762                         basefont = owner_->getLayoutFont(bparams, outerfont);
763                         running_font = basefont;
764                         if (!closeLanguage)
765                                 running_font.setLanguage(copy_font.language());
766                         // leave font open if language is still open
767                         open_font = (running_font.language() == basefont.language());
768                         if (closeLanguage)
769                                 runparams.local_font = &basefont;
770                 }
771         }
772
773         int tmp = inset->latex(buf, os, runparams);
774
775         if (close) {
776         if (running_font.language()->lang() == "farsi")
777                         os << "\\endL{}";
778                 else
779                         os << '}';
780         }
781
782         if (tmp) {
783                 for (int j = 0; j < tmp; ++j)
784                         texrow.newline();
785
786                 texrow.start(owner_->id(), i + 1);
787                 column = 0;
788         } else {
789                 column += os.tellp() - len;
790         }
791
792         if (owner_->lookupChange(i).type == Change::DELETED)
793                 --runparams.inDeletedInset;
794 }
795
796
797 void Paragraph::Private::latexSpecialChar(
798                                              odocstream & os,
799                                              OutputParams & runparams,
800                                              Font & running_font,
801                                              Change & running_change,
802                                              Layout const & style,
803                                              pos_type & i,
804                                              unsigned int & column)
805 {
806         char_type const c = text_[i];
807
808         if (style.pass_thru) {
809                 if (c != '\0')
810                         // FIXME UNICODE: This can fail if c cannot
811                         // be encoded in the current encoding.
812                         os.put(c);
813                 return;
814         }
815
816         if (runparams.verbatim) {
817                 os.put(c);
818                 return;
819         }
820
821         if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
822                 return;
823
824         if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
825                 && latexSpecialTypewriter(c, os, i, column))
826                 return;
827
828         // Otherwise, we use what LaTeX provides us.
829         switch (c) {
830         case '\\':
831                 os << "\\textbackslash{}";
832                 column += 15;
833                 break;
834         case '<':
835                 os << "\\textless{}";
836                 column += 10;
837                 break;
838         case '>':
839                 os << "\\textgreater{}";
840                 column += 13;
841                 break;
842         case '|':
843                 os << "\\textbar{}";
844                 column += 9;
845                 break;
846         case '-':
847                 os << '-';
848                 break;
849         case '\"':
850                 os << "\\char`\\\"{}";
851                 column += 9;
852                 break;
853
854         case '$': case '&':
855         case '%': case '#': case '{':
856         case '}': case '_':
857                 os << '\\';
858                 os.put(c);
859                 column += 1;
860                 break;
861
862         case '~':
863                 os << "\\textasciitilde{}";
864                 column += 16;
865                 break;
866
867         case '^':
868                 os << "\\textasciicircum{}";
869                 column += 17;
870                 break;
871
872         case '*': case '[':
873                 // avoid being mistaken for optional arguments
874                 os << '{';
875                 os.put(c);
876                 os << '}';
877                 column += 2;
878                 break;
879
880         case ' ':
881                 // Blanks are printed before font switching.
882                 // Sure? I am not! (try nice-latex)
883                 // I am sure it's correct. LyX might be smarter
884                 // in the future, but for now, nothing wrong is
885                 // written. (Asger)
886                 break;
887
888         default:
889
890                 // LyX, LaTeX etc.
891                 if (latexSpecialPhrase(os, i, column, runparams))
892                         return;
893
894                 if (c == '\0')
895                         return;
896
897                 Encoding const & encoding = *(runparams.encoding);
898                 if (i + 1 < int(text_.size())) {
899                         char_type next = text_[i + 1];
900                         if (Encodings::isCombiningChar(next)) {
901                                 column += latexSurrogatePair(os, c, next, encoding) - 1;
902                                 ++i;
903                                 break;
904                         }
905                 }
906                 string script;
907                 docstring const latex = encoding.latexChar(c);
908                 if (Encodings::isKnownScriptChar(c, script)
909                     && prefixIs(latex, from_ascii("\\" + script)))
910                         column += writeScriptChars(os, latex,
911                                         running_change, encoding, i) - 1;
912                 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
913                         // Prevent eating of a following
914                         // space or command corruption by
915                         // following characters
916                         column += latex.length() + 1;
917                         os << latex << "{}";
918                 } else {
919                         column += latex.length() - 1;
920                         os << latex;
921                 }
922                 break;
923         }
924 }
925
926
927 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
928         pos_type & i, unsigned int & column)
929 {
930         switch (c) {
931         case '>':
932         case '<':
933                 os.put(c);
934                 // In T1 encoding, these characters exist
935                 // but we should avoid ligatures
936                 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
937                         return true;
938                 os << "\\,{}";
939                 column += 3;
940                 // Alternative code:
941                 //os << "\\textcompwordmark{}";
942                 //column += 19;
943                 return true;
944         case '|':
945                 os.put(c);
946                 return true;
947         default:
948                 return false;
949         }
950 }
951
952
953 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
954         pos_type & i, unsigned int & column)
955 {
956         switch (c) {
957         case '-':
958                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
959                         // "--" in Typewriter mode -> "-{}-"
960                         os << "-{}";
961                         column += 2;
962                 } else
963                         os << '-';
964                 return true;
965
966         // I assume this is hack treating typewriter as verbatim
967         // FIXME UNICODE: This can fail if c cannot be encoded
968         // in the current encoding.
969
970         case '\0':
971                 return true;
972
973         // Those characters are not directly supported.
974         case '\\':
975         case '\"':
976         case '$': case '&':
977         case '%': case '#': case '{':
978         case '}': case '_':
979         case '~':
980         case '^':
981         case '*': case '[':
982         case ' ':
983                 return false;
984
985         default:
986                 // With Typewriter font, these characters exist.
987                 os.put(c);
988                 return true;
989         }
990 }
991
992
993 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
994         unsigned int & column, OutputParams & runparams)
995 {
996         // FIXME: if we have "LaTeX" with a font
997         // change in the middle (before the 'T', then
998         // the "TeX" part is still special cased.
999         // Really we should only operate this on
1000         // "words" for some definition of word
1001
1002         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1003                 if (!isTextAt(special_phrases[pnr].phrase, i))
1004                         continue;
1005                 if (runparams.moving_arg)
1006                         os << "\\protect";
1007                 os << special_phrases[pnr].macro;
1008                 i += special_phrases[pnr].phrase.length() - 1;
1009                 column += special_phrases[pnr].macro.length() - 1;
1010                 return true;
1011         }
1012         return false;
1013 }
1014
1015
1016 void Paragraph::Private::validate(LaTeXFeatures & features,
1017                                 Layout const & layout) const
1018 {
1019         // check the params.
1020         if (!params_.spacing().isDefault())
1021                 features.require("setspace");
1022
1023         // then the layouts
1024         features.useLayout(layout.name());
1025
1026         // then the fonts
1027         fontlist_.validate(features);
1028
1029         // then the indentation
1030         if (!params_.leftIndent().zero())
1031                 features.require("ParagraphLeftIndent");
1032
1033         // then the insets
1034         InsetList::const_iterator icit = insetlist_.begin();
1035         InsetList::const_iterator iend = insetlist_.end();
1036         for (; icit != iend; ++icit) {
1037                 if (icit->inset) {
1038                         icit->inset->validate(features);
1039                         if (layout.needprotect &&
1040                             icit->inset->lyxCode() == FOOT_CODE)
1041                                 features.require("NeedLyXFootnoteCode");
1042                 }
1043         }
1044
1045         // then the contents
1046         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1047                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1048                         if (!special_phrases[pnr].builtin
1049                             && isTextAt(special_phrases[pnr].phrase, i)) {
1050                                 features.require(special_phrases[pnr].phrase);
1051                                 break;
1052                         }
1053                 }
1054                 Encodings::validate(text_[i], features);
1055         }
1056 }
1057
1058 /////////////////////////////////////////////////////////////////////
1059 //
1060 // Paragraph
1061 //
1062 /////////////////////////////////////////////////////////////////////
1063
1064 Paragraph::Paragraph()
1065         : d(new Paragraph::Private(this))
1066 {
1067         itemdepth = 0;
1068         d->params_.clear();
1069 }
1070
1071
1072 Paragraph::Paragraph(Paragraph const & par)
1073         : itemdepth(par.itemdepth),
1074         d(new Paragraph::Private(*par.d, this))
1075 {
1076 }
1077
1078
1079 Paragraph & Paragraph::operator=(Paragraph const & par)
1080 {
1081         // needed as we will destroy the private part before copying it
1082         if (&par != this) {
1083                 itemdepth = par.itemdepth;
1084
1085                 delete d;
1086                 d = new Private(*par.d, this);
1087         }
1088         return *this;
1089 }
1090
1091
1092 Paragraph::~Paragraph()
1093 {
1094         delete d;
1095 }
1096
1097
1098 void Paragraph::write(Buffer const & buf, ostream & os,
1099                           BufferParams const & bparams,
1100                           depth_type & dth) const
1101 {
1102         // The beginning or end of a deeper (i.e. nested) area?
1103         if (dth != params().depth()) {
1104                 if (params().depth() > dth) {
1105                         while (params().depth() > dth) {
1106                                 os << "\n\\begin_deeper";
1107                                 ++dth;
1108                         }
1109                 } else {
1110                         while (params().depth() < dth) {
1111                                 os << "\n\\end_deeper";
1112                                 --dth;
1113                         }
1114                 }
1115         }
1116
1117         // First write the layout
1118         os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1119
1120         params().write(os);
1121
1122         Font font1(inherit_font, bparams.language);
1123
1124         Change running_change = Change(Change::UNCHANGED);
1125
1126         int column = 0;
1127         for (pos_type i = 0; i <= size(); ++i) {
1128
1129                 Change change = lookupChange(i);
1130                 Changes::lyxMarkChange(os, column, running_change, change);
1131                 running_change = change;
1132
1133                 if (i == size())
1134                         break;
1135
1136                 // Write font changes
1137                 Font font2 = getFontSettings(bparams, i);
1138                 if (font2 != font1) {
1139                         font2.lyxWriteChanges(font1, os);
1140                         column = 0;
1141                         font1 = font2;
1142                 }
1143
1144                 char_type const c = d->text_[i];
1145                 switch (c) {
1146                 case META_INSET:
1147                 {
1148                         Inset const * inset = getInset(i);
1149                         if (inset)
1150                                 if (inset->directWrite()) {
1151                                         // international char, let it write
1152                                         // code directly so it's shorter in
1153                                         // the file
1154                                         inset->write(buf, os);
1155                                 } else {
1156                                         if (i)
1157                                                 os << '\n';
1158                                         os << "\\begin_inset ";
1159                                         inset->write(buf, os);
1160                                         os << "\n\\end_inset\n\n";
1161                                         column = 0;
1162                                 }
1163                 }
1164                 break;
1165                 case '\\':
1166                         os << "\n\\backslash\n";
1167                         column = 0;
1168                         break;
1169                 case '.':
1170                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1171                                 os << ".\n";
1172                                 column = 0;
1173                         } else
1174                                 os << '.';
1175                         break;
1176                 default:
1177                         if ((column > 70 && c == ' ')
1178                             || column > 79) {
1179                                 os << '\n';
1180                                 column = 0;
1181                         }
1182                         // this check is to amend a bug. LyX sometimes
1183                         // inserts '\0' this could cause problems.
1184                         if (c != '\0') {
1185                                 std::vector<char> tmp = ucs4_to_utf8(c);
1186                                 tmp.push_back('\0');
1187                                 os << &tmp[0];
1188                         } else
1189                                 lyxerr << "ERROR (Paragraph::writeFile):"
1190                                         " NULL char in structure." << endl;
1191                         ++column;
1192                         break;
1193                 }
1194         }
1195
1196         os << "\n\\end_layout\n";
1197 }
1198
1199
1200 void Paragraph::validate(LaTeXFeatures & features) const
1201 {
1202         d->validate(features, *layout());
1203 }
1204
1205
1206 void Paragraph::insert(pos_type start, docstring const & str,
1207                        Font const & font, Change const & change)
1208 {
1209         for (size_t i = 0, n = str.size(); i != n ; ++i)
1210                 insertChar(start + i, str[i], font, change);
1211 }
1212
1213
1214 void Paragraph::appendChar(char_type c, Font const & font,
1215                 Change const & change)
1216 {
1217         // track change
1218         d->changes_.insert(change, d->text_.size());
1219         // when appending characters, no need to update tables
1220         d->text_.push_back(c);
1221         setFont(d->text_.size() - 1, font);
1222 }
1223
1224
1225 void Paragraph::appendString(docstring const & s, Font const & font,
1226                 Change const & change)
1227 {
1228         pos_type end = s.size();
1229         size_t oldsize = d->text_.size();
1230         size_t newsize = oldsize + end;
1231         size_t capacity = d->text_.capacity();
1232         if (newsize >= capacity)
1233                 d->text_.reserve(std::max(capacity + 100, newsize));
1234
1235         // when appending characters, no need to update tables
1236         d->text_.append(s);
1237
1238         // FIXME: Optimize this!
1239         for (pos_type i = 0; i != end; ++i) {
1240                 // track change
1241                 d->changes_.insert(change, i);
1242         }
1243         d->fontlist_.set(oldsize, font);
1244         d->fontlist_.set(newsize - 1, font);
1245 }
1246
1247
1248 void Paragraph::insertChar(pos_type pos, char_type c,
1249                            bool trackChanges)
1250 {
1251         d->insertChar(pos, c, Change(trackChanges ?
1252                            Change::INSERTED : Change::UNCHANGED));
1253 }
1254
1255
1256 void Paragraph::insertChar(pos_type pos, char_type c,
1257                            Font const & font, bool trackChanges)
1258 {
1259         d->insertChar(pos, c, Change(trackChanges ?
1260                            Change::INSERTED : Change::UNCHANGED));
1261         setFont(pos, font);
1262 }
1263
1264
1265 void Paragraph::insertChar(pos_type pos, char_type c,
1266                            Font const & font, Change const & change)
1267 {
1268         d->insertChar(pos, c, change);
1269         setFont(pos, font);
1270 }
1271
1272
1273 void Paragraph::insertInset(pos_type pos, Inset * inset,
1274                             Font const & font, Change const & change)
1275 {
1276         insertInset(pos, inset, change);
1277         // Set the font/language of the inset...
1278         setFont(pos, font);
1279 }
1280
1281
1282 bool Paragraph::insetAllowed(InsetCode code)
1283 {
1284         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1285 }
1286
1287
1288 void Paragraph::resetFonts(Font const & font)
1289 {
1290         d->fontlist_.clear();
1291         d->fontlist_.set(0, font);
1292         d->fontlist_.set(d->text_.size() - 1, font);
1293 }
1294
1295 // Gets uninstantiated font setting at position.
1296 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1297                                          pos_type pos) const
1298 {
1299         if (pos > size()) {
1300                 lyxerr << " pos: " << pos << " size: " << size() << endl;
1301                 BOOST_ASSERT(pos <= size());
1302         }
1303
1304         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1305         if (cit != d->fontlist_.end())
1306                 return cit->font();
1307
1308         if (pos == size() && !empty())
1309                 return getFontSettings(bparams, pos - 1);
1310
1311         return Font(inherit_font, getParLanguage(bparams));
1312 }
1313
1314
1315 FontSpan Paragraph::fontSpan(pos_type pos) const
1316 {
1317         BOOST_ASSERT(pos <= size());
1318         pos_type start = 0;
1319
1320         FontList::const_iterator cit = d->fontlist_.begin();
1321         FontList::const_iterator end = d->fontlist_.end();
1322         for (; cit != end; ++cit) {
1323                 if (cit->pos() >= pos) {
1324                         if (pos >= beginOfBody())
1325                                 return FontSpan(std::max(start, beginOfBody()),
1326                                                 cit->pos());
1327                         else
1328                                 return FontSpan(start,
1329                                                 std::min(beginOfBody() - 1,
1330                                                          cit->pos()));
1331                 }
1332                 start = cit->pos() + 1;
1333         }
1334
1335         // This should not happen, but if so, we take no chances.
1336         //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1337         //      << endl;
1338         return FontSpan(pos, pos);
1339 }
1340
1341
1342 // Gets uninstantiated font setting at position 0
1343 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1344 {
1345         if (!empty() && !d->fontlist_.empty())
1346                 return d->fontlist_.begin()->font();
1347
1348         return Font(inherit_font, bparams.language);
1349 }
1350
1351
1352 // Gets the fully instantiated font at a given position in a paragraph
1353 // This is basically the same function as Text::GetFont() in text2.cpp.
1354 // The difference is that this one is used for generating the LaTeX file,
1355 // and thus cosmetic "improvements" are disallowed: This has to deliver
1356 // the true picture of the buffer. (Asger)
1357 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1358                                  Font const & outerfont) const
1359 {
1360         BOOST_ASSERT(pos >= 0);
1361
1362         Font font = getFontSettings(bparams, pos);
1363
1364         pos_type const body_pos = beginOfBody();
1365         if (pos < body_pos)
1366                 font.fontInfo().realize(d->layout_->labelfont);
1367         else
1368                 font.fontInfo().realize(d->layout_->font);
1369
1370         font.fontInfo().realize(outerfont.fontInfo());
1371         font.fontInfo().realize(bparams.getFont().fontInfo());
1372
1373         return font;
1374 }
1375
1376
1377 Font const Paragraph::getLabelFont
1378         (BufferParams const & bparams, Font const & outerfont) const
1379 {
1380         FontInfo tmpfont = layout()->labelfont;
1381         tmpfont.realize(outerfont.fontInfo());
1382         tmpfont.realize(bparams.getFont().fontInfo());
1383         return Font(tmpfont, getParLanguage(bparams));
1384 }
1385
1386
1387 Font const Paragraph::getLayoutFont
1388         (BufferParams const & bparams, Font const & outerfont) const
1389 {
1390         FontInfo tmpfont = layout()->font;
1391         tmpfont.realize(outerfont.fontInfo());
1392         tmpfont.realize(bparams.getFont().fontInfo());
1393         return Font(tmpfont, getParLanguage(bparams));
1394 }
1395
1396
1397 /// Returns the height of the highest font in range
1398 FontSize Paragraph::highestFontInRange
1399         (pos_type startpos, pos_type endpos, FontSize def_size) const
1400 {
1401         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1402 }
1403
1404
1405 char_type
1406 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1407 {
1408         char_type c = d->text_[pos];
1409         if (!lyxrc.rtl_support)
1410                 return c;
1411
1412         char_type uc = c;
1413         switch (c) {
1414         case '(':
1415                 uc = ')';
1416                 break;
1417         case ')':
1418                 uc = '(';
1419                 break;
1420         case '[':
1421                 uc = ']';
1422                 break;
1423         case ']':
1424                 uc = '[';
1425                 break;
1426         case '{':
1427                 uc = '}';
1428                 break;
1429         case '}':
1430                 uc = '{';
1431                 break;
1432         case '<':
1433                 uc = '>';
1434                 break;
1435         case '>':
1436                 uc = '<';
1437                 break;
1438         }
1439         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1440                 return uc;
1441         else
1442                 return c;
1443 }
1444
1445
1446 void Paragraph::setFont(pos_type pos, Font const & font)
1447 {
1448         BOOST_ASSERT(pos <= size());
1449
1450         // First, reduce font against layout/label font
1451         // Update: The setCharFont() routine in text2.cpp already
1452         // reduces font, so we don't need to do that here. (Asger)
1453         
1454         d->fontlist_.set(pos, font);
1455 }
1456
1457
1458 void Paragraph::makeSameLayout(Paragraph const & par)
1459 {
1460         layout(par.layout());
1461         // move to pimpl?
1462         d->params_ = par.params();
1463 }
1464
1465
1466 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1467 {
1468         if (isFreeSpacing())
1469                 return false;
1470
1471         int pos = 0;
1472         int count = 0;
1473
1474         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1475                 if (eraseChar(pos, trackChanges))
1476                         ++count;
1477                 else
1478                         ++pos;
1479         }
1480
1481         return count > 0 || pos > 0;
1482 }
1483
1484
1485 bool Paragraph::hasSameLayout(Paragraph const & par) const
1486 {
1487         return par.layout() == layout() && d->params_.sameLayout(par.params());
1488 }
1489
1490
1491 depth_type Paragraph::getDepth() const
1492 {
1493         return params().depth();
1494 }
1495
1496
1497 depth_type Paragraph::getMaxDepthAfter() const
1498 {
1499         if (layout()->isEnvironment())
1500                 return params().depth() + 1;
1501         else
1502                 return params().depth();
1503 }
1504
1505
1506 char Paragraph::getAlign() const
1507 {
1508         if (params().align() == LYX_ALIGN_LAYOUT)
1509                 return layout()->align;
1510         else
1511                 return params().align();
1512 }
1513
1514
1515 docstring const & Paragraph::getLabelstring() const
1516 {
1517         return params().labelString();
1518 }
1519
1520
1521 // the next two functions are for the manual labels
1522 docstring const Paragraph::getLabelWidthString() const
1523 {
1524         if (layout()->margintype == MARGIN_MANUAL)
1525                 return params().labelWidthString();
1526         else
1527                 return _("Senseless with this layout!");
1528 }
1529
1530
1531 void Paragraph::setLabelWidthString(docstring const & s)
1532 {
1533         params().labelWidthString(s);
1534 }
1535
1536
1537 docstring const Paragraph::translateIfPossible(docstring const & s,
1538                 BufferParams const & bparams) const
1539 {
1540         if (!support::isAscii(s) || s.empty()) {
1541                 // This must be a user defined layout. We cannot translate
1542                 // this, since gettext accepts only ascii keys.
1543                 return s;
1544         }
1545         // Probably standard layout, try to translate
1546         Messages & m = getMessages(getParLanguage(bparams)->code());
1547         return m.get(to_ascii(s));
1548 }
1549
1550
1551 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1552                 BufferParams const & bparams, bool process_appendix) const
1553 {
1554         TextClass const & tclass = bparams.getTextClass();
1555
1556         docstring fmt;
1557         if (process_appendix && params().appendix())
1558                 fmt = translateIfPossible(layout->labelstring_appendix(),
1559                         bparams);
1560         else
1561                 fmt = translateIfPossible(layout->labelstring(), bparams);
1562
1563         if (fmt.empty() && layout->labeltype == LABEL_COUNTER 
1564             && !layout->counter.empty())
1565                 fmt = "\\the" + layout->counter;
1566
1567         // handle 'inherited level parts' in 'fmt',
1568         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1569         size_t const i = fmt.find('@', 0);
1570         if (i != docstring::npos) {
1571                 size_t const j = fmt.find('@', i + 1);
1572                 if (j != docstring::npos) {
1573                         docstring parent(fmt, i + 1, j - i - 1);
1574                         docstring label = from_ascii("??");
1575                         if (tclass.hasLayout(parent))
1576                                 docstring label = expandLabel(tclass[parent], bparams,
1577                                                       process_appendix);
1578                         fmt = docstring(fmt, 0, i) + label 
1579                                 + docstring(fmt, j + 1, docstring::npos);
1580                 }
1581         }
1582
1583         return tclass.counters().counterLabel(fmt);
1584 }
1585
1586
1587 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1588 {
1589         layout(new_layout);
1590         LyXAlignment const oldAlign = params().align();
1591         
1592         if (!(oldAlign & layout()->alignpossible)) {
1593                 frontend::Alert::warning(_("Alignment not permitted"), 
1594                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1595                 params().align(LYX_ALIGN_LAYOUT);
1596         }
1597 }
1598
1599
1600 pos_type Paragraph::beginOfBody() const
1601 {
1602         return d->begin_of_body_;
1603 }
1604
1605
1606 void Paragraph::setBeginOfBody()
1607 {
1608         if (layout()->labeltype != LABEL_MANUAL) {
1609                 d->begin_of_body_ = 0;
1610                 return;
1611         }
1612
1613         // Unroll the first two cycles of the loop
1614         // and remember the previous character to
1615         // remove unnecessary getChar() calls
1616         pos_type i = 0;
1617         pos_type end = size();
1618         if (i < end && !isNewline(i)) {
1619                 ++i;
1620                 char_type previous_char = 0;
1621                 char_type temp = 0;
1622                 if (i < end) {
1623                         previous_char = d->text_[i];
1624                         if (!isNewline(i)) {
1625                                 ++i;
1626                                 while (i < end && previous_char != ' ') {
1627                                         temp = d->text_[i];
1628                                         if (isNewline(i))
1629                                                 break;
1630                                         ++i;
1631                                         previous_char = temp;
1632                                 }
1633                         }
1634                 }
1635         }
1636
1637         d->begin_of_body_ = i;
1638 }
1639
1640
1641 bool Paragraph::forceDefaultParagraphs() const
1642 {
1643         return inInset() && inInset()->forceDefaultParagraphs(0);
1644 }
1645
1646
1647 namespace {
1648
1649 // paragraphs inside floats need different alignment tags to avoid
1650 // unwanted space
1651
1652 bool noTrivlistCentering(InsetCode code)
1653 {
1654         return code == FLOAT_CODE || code == WRAP_CODE;
1655 }
1656
1657
1658 string correction(string const & orig)
1659 {
1660         if (orig == "flushleft")
1661                 return "raggedright";
1662         if (orig == "flushright")
1663                 return "raggedleft";
1664         if (orig == "center")
1665                 return "centering";
1666         return orig;
1667 }
1668
1669
1670 string const corrected_env(string const & suffix, string const & env,
1671         InsetCode code)
1672 {
1673         string output = suffix + "{";
1674         if (noTrivlistCentering(code))
1675                 output += correction(env);
1676         else
1677                 output += env;
1678         output += "}";
1679         if (suffix == "\\begin")
1680                 output += "\n";
1681         return output;
1682 }
1683
1684
1685 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1686 {
1687         if (!contains(str, "\n"))
1688                 column += str.size();
1689         else {
1690                 string tmp;
1691                 texrow.newline();
1692                 column = rsplit(str, tmp, '\n').size();
1693         }
1694 }
1695
1696 } // namespace anon
1697
1698
1699 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1700                                  odocstream & os, TexRow & texrow,
1701                                  bool moving_arg) const
1702 {
1703         int column = 0;
1704
1705         if (params_.noindent()) {
1706                 os << "\\noindent ";
1707                 column += 10;
1708         }
1709         
1710         LyXAlignment const curAlign = params_.align();
1711
1712         if (curAlign == layout_->align)
1713                 return column;
1714
1715         switch (curAlign) {
1716         case LYX_ALIGN_NONE:
1717         case LYX_ALIGN_BLOCK:
1718         case LYX_ALIGN_LAYOUT:
1719         case LYX_ALIGN_SPECIAL:
1720                 break;
1721         case LYX_ALIGN_LEFT:
1722         case LYX_ALIGN_RIGHT:
1723         case LYX_ALIGN_CENTER:
1724                 if (moving_arg) {
1725                         os << "\\protect";
1726                         column += 8;
1727                 }
1728                 break;
1729         }
1730
1731         switch (curAlign) {
1732         case LYX_ALIGN_NONE:
1733         case LYX_ALIGN_BLOCK:
1734         case LYX_ALIGN_LAYOUT:
1735         case LYX_ALIGN_SPECIAL:
1736                 break;
1737         case LYX_ALIGN_LEFT: {
1738                 string output;
1739                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1740                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1741                 else
1742                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1743                 os << from_ascii(output);
1744                 adjust_row_column(output, texrow, column);
1745                 break;
1746         } case LYX_ALIGN_RIGHT: {
1747                 string output;
1748                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1749                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1750                 else
1751                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1752                 os << from_ascii(output);
1753                 adjust_row_column(output, texrow, column);
1754                 break;
1755         } case LYX_ALIGN_CENTER: {
1756                 string output;
1757                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1758                 os << from_ascii(output);
1759                 adjust_row_column(output, texrow, column);
1760                 break;
1761         }
1762         }
1763
1764         return column;
1765 }
1766
1767
1768 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1769                                odocstream & os, TexRow & texrow,
1770                                bool moving_arg) const
1771 {
1772         int column = 0;
1773
1774         switch (params_.align()) {
1775         case LYX_ALIGN_NONE:
1776         case LYX_ALIGN_BLOCK:
1777         case LYX_ALIGN_LAYOUT:
1778         case LYX_ALIGN_SPECIAL:
1779                 break;
1780         case LYX_ALIGN_LEFT:
1781         case LYX_ALIGN_RIGHT:
1782         case LYX_ALIGN_CENTER:
1783                 if (moving_arg) {
1784                         os << "\\protect";
1785                         column = 8;
1786                 }
1787                 break;
1788         }
1789
1790         switch (params_.align()) {
1791         case LYX_ALIGN_NONE:
1792         case LYX_ALIGN_BLOCK:
1793         case LYX_ALIGN_LAYOUT:
1794         case LYX_ALIGN_SPECIAL:
1795                 break;
1796         case LYX_ALIGN_LEFT: {
1797                 string output;
1798                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1799                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1800                 else
1801                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1802                 os << from_ascii(output);
1803                 adjust_row_column(output, texrow, column);
1804                 break;
1805         } case LYX_ALIGN_RIGHT: {
1806                 string output;
1807                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1808                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1809                 else
1810                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1811                 os << from_ascii(output);
1812                 adjust_row_column(output, texrow, column);
1813                 break;
1814         } case LYX_ALIGN_CENTER: {
1815                 string output;
1816                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1817                 os << from_ascii(output);
1818                 adjust_row_column(output, texrow, column);
1819                 break;
1820         }
1821         }
1822
1823         return column;
1824 }
1825
1826
1827 // This one spits out the text of the paragraph
1828 bool Paragraph::latex(Buffer const & buf,
1829                                 BufferParams const & bparams,
1830                                 Font const & outerfont,
1831                                 odocstream & os, TexRow & texrow,
1832                                 OutputParams const & runparams) const
1833 {
1834         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1835
1836         bool return_value = false;
1837
1838         LayoutPtr style;
1839
1840         // well we have to check if we are in an inset with unlimited
1841         // length (all in one row) if that is true then we don't allow
1842         // any special options in the paragraph and also we don't allow
1843         // any environment other than the default layout of the text class
1844         // to be valid!
1845         bool asdefault = forceDefaultParagraphs();
1846
1847         if (asdefault) {
1848                 style = bparams.getTextClass().defaultLayout();
1849         } else {
1850                 style = layout();
1851         }
1852
1853         // Current base font for all inherited font changes, without any
1854         // change caused by an individual character, except for the language:
1855         // It is set to the language of the first character.
1856         // As long as we are in the label, this font is the base font of the
1857         // label. Before the first body character it is set to the base font
1858         // of the body.
1859         Font basefont;
1860
1861         // Maybe we have to create a optional argument.
1862         pos_type body_pos = beginOfBody();
1863         unsigned int column = 0;
1864
1865         if (body_pos > 0) {
1866                 // the optional argument is kept in curly brackets in
1867                 // case it contains a ']'
1868                 os << "[{";
1869                 column += 2;
1870                 basefont = getLabelFont(bparams, outerfont);
1871         } else {
1872                 basefont = getLayoutFont(bparams, outerfont);
1873         }
1874
1875         // Which font is currently active?
1876         Font running_font(basefont);
1877         // Do we have an open font change?
1878         bool open_font = false;
1879
1880         Change runningChange = Change(Change::UNCHANGED);
1881
1882         texrow.start(id(), 0);
1883
1884         // if the paragraph is empty, the loop will not be entered at all
1885         if (empty()) {
1886                 if (style->isCommand()) {
1887                         os << '{';
1888                         ++column;
1889                 }
1890                 if (!asdefault)
1891                         column += d->startTeXParParams(bparams, os, texrow,
1892                                                     runparams.moving_arg);
1893         }
1894
1895         for (pos_type i = 0; i < size(); ++i) {
1896                 // First char in paragraph or after label?
1897                 if (i == body_pos) {
1898                         if (body_pos > 0) {
1899                                 if (open_font) {
1900                                         column += running_font.latexWriteEndChanges(
1901                                                 os, bparams, runparams,
1902                                                 basefont, basefont);
1903                                         open_font = false;
1904                                 }
1905                                 basefont = getLayoutFont(bparams, outerfont);
1906                                 running_font = basefont;
1907
1908                                 column += Changes::latexMarkChange(os, bparams,
1909                                                 runningChange, Change(Change::UNCHANGED));
1910                                 runningChange = Change(Change::UNCHANGED);
1911
1912                                 os << "}] ";
1913                                 column +=3;
1914                         }
1915                         if (style->isCommand()) {
1916                                 os << '{';
1917                                 ++column;
1918                         }
1919
1920                         if (!asdefault)
1921                                 column += d->startTeXParParams(bparams, os,
1922                                                             texrow,
1923                                                             runparams.moving_arg);
1924                 }
1925
1926                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1927                                                                  : lookupChange(i);
1928
1929                 if (bparams.outputChanges && runningChange != change) {
1930                         if (open_font) {
1931                                 column += running_font.latexWriteEndChanges(
1932                                                 os, bparams, runparams, basefont, basefont);
1933                                 open_font = false;
1934                         }
1935                         basefont = getLayoutFont(bparams, outerfont);
1936                         running_font = basefont;
1937
1938                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1939                         runningChange = change;
1940                 }
1941
1942                 // do not output text which is marked deleted
1943                 // if change tracking output is disabled
1944                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1945                         continue;
1946                 }
1947
1948                 ++column;
1949
1950                 // Fully instantiated font
1951                 Font const font = getFont(bparams, i, outerfont);
1952
1953                 Font const last_font = running_font;
1954
1955                 // Do we need to close the previous font?
1956                 if (open_font &&
1957                     (font != running_font ||
1958                      font.language() != running_font.language()))
1959                 {
1960                         column += running_font.latexWriteEndChanges(
1961                                         os, bparams, runparams, basefont,
1962                                         (i == body_pos-1) ? basefont : font);
1963                         running_font = basefont;
1964                         open_font = false;
1965                 }
1966
1967                 // Switch file encoding if necessary (and allowed)
1968                 if (!runparams.verbatim && 
1969                     runparams.encoding->package() == Encoding::inputenc &&
1970                     font.language()->encoding()->package() == Encoding::inputenc) {
1971                         std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1972                                         runparams.moving_arg, *(runparams.encoding),
1973                                         *(font.language()->encoding()));
1974                         if (enc_switch.first) {
1975                                 column += enc_switch.second;
1976                                 runparams.encoding = font.language()->encoding();
1977                         }
1978                 }
1979
1980                 char_type const c = d->text_[i];
1981
1982                 // Do we need to change font?
1983                 if ((font != running_font ||
1984                      font.language() != running_font.language()) &&
1985                         i != body_pos - 1)
1986                 {
1987                         odocstringstream ods;
1988                         column += font.latexWriteStartChanges(ods, bparams,
1989                                                               runparams, basefont,
1990                                                               last_font);
1991                         running_font = font;
1992                         open_font = true;
1993                         docstring fontchange = ods.str();
1994                         // check if the fontchange ends with a trailing blank
1995                         // (like "\small " (see bug 3382)
1996                         if (suffixIs(fontchange, ' ') && c == ' ')
1997                                 os << fontchange.substr(0, fontchange.size() - 1) 
1998                                    << from_ascii("{}");
1999                         else
2000                                 os << fontchange;
2001                 }
2002
2003                 if (c == ' ') {
2004                         // FIXME: integrate this case in latexSpecialChar
2005                         // Do not print the separation of the optional argument
2006                         // if style->pass_thru is false. This works because
2007                         // latexSpecialChar ignores spaces if
2008                         // style->pass_thru is false.
2009                         if (i != body_pos - 1) {
2010                                 if (d->simpleTeXBlanks(
2011                                                 runparams, os, texrow,
2012                                                 i, column, font, *style)) {
2013                                         // A surrogate pair was output. We
2014                                         // must not call latexSpecialChar
2015                                         // in this iteration, since it would output
2016                                         // the combining character again.
2017                                         ++i;
2018                                         continue;
2019                                 }
2020                         }
2021                 }
2022
2023                 OutputParams rp = runparams;
2024                 rp.free_spacing = style->free_spacing;
2025                 rp.local_font = &font;
2026                 rp.intitle = style->intitle;
2027
2028                 // Two major modes:  LaTeX or plain
2029                 // Handle here those cases common to both modes
2030                 // and then split to handle the two modes separately.
2031                 if (c == META_INSET)
2032                         d->latexInset(buf, bparams, os,
2033                                         texrow, rp, running_font,
2034                                         basefont, outerfont, open_font,
2035                                         runningChange, *style, i, column);
2036                 else
2037                         d->latexSpecialChar(os, rp, running_font, runningChange,
2038                                 *style, i, column);
2039
2040                 // Set the encoding to that returned from simpleTeXSpecialChars (see
2041                 // comment for encoding member in OutputParams.h)
2042                 runparams.encoding = rp.encoding;
2043         }
2044
2045         // If we have an open font definition, we have to close it
2046         if (open_font) {
2047 #ifdef FIXED_LANGUAGE_END_DETECTION
2048                 if (next_) {
2049                         running_font
2050                                 .latexWriteEndChanges(os, bparams, runparams,
2051                                         basefont,
2052                                         next_->getFont(bparams, 0, outerfont));
2053                 } else {
2054                         running_font.latexWriteEndChanges(os, bparams,
2055                                         runparams, basefont, basefont);
2056                 }
2057 #else
2058 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2059 //FIXME: there as we start another \selectlanguage with the next paragraph if
2060 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2061                 running_font.latexWriteEndChanges(os, bparams, runparams,
2062                                 basefont, basefont);
2063 #endif
2064         }
2065
2066         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2067
2068         // Needed if there is an optional argument but no contents.
2069         if (body_pos > 0 && body_pos == size()) {
2070                 os << "}]~";
2071                 return_value = false;
2072         }
2073
2074         if (!asdefault) {
2075                 column += d->endTeXParParams(bparams, os, texrow,
2076                                           runparams.moving_arg);
2077         }
2078
2079         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2080         return return_value;
2081 }
2082
2083
2084 bool Paragraph::emptyTag() const
2085 {
2086         for (pos_type i = 0; i < size(); ++i) {
2087                 if (isInset(i)) {
2088                         Inset const * inset = getInset(i);
2089                         InsetCode lyx_code = inset->lyxCode();
2090                         if (lyx_code != TOC_CODE &&
2091                             lyx_code != INCLUDE_CODE &&
2092                             lyx_code != GRAPHICS_CODE &&
2093                             lyx_code != ERT_CODE &&
2094                             lyx_code != LISTINGS_CODE &&
2095                             lyx_code != FLOAT_CODE &&
2096                             lyx_code != TABULAR_CODE) {
2097                                 return false;
2098                         }
2099                 } else {
2100                         char_type c = d->text_[i];
2101                         if (c != ' ' && c != '\t')
2102                                 return false;
2103                 }
2104         }
2105         return true;
2106 }
2107
2108
2109 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2110 {
2111         for (pos_type i = 0; i < size(); ++i) {
2112                 if (isInset(i)) {
2113                         Inset const * inset = getInset(i);
2114                         InsetCode lyx_code = inset->lyxCode();
2115                         if (lyx_code == LABEL_CODE) {
2116                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2117                                 docstring const & id = il->getParam("name");
2118                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2119                         }
2120                 }
2121
2122         }
2123         return string();
2124 }
2125
2126
2127 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2128 {
2129         pos_type i;
2130         for (i = 0; i < size(); ++i) {
2131                 if (isInset(i)) {
2132                         Inset const * inset = getInset(i);
2133                         inset->docbook(buf, os, runparams);
2134                 } else {
2135                         char_type c = d->text_[i];
2136                         if (c == ' ')
2137                                 break;
2138                         os << sgml::escapeChar(c);
2139                 }
2140         }
2141         return i;
2142 }
2143
2144
2145 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2146 {
2147         Font font_old;
2148         pos_type size = text_.size();
2149         for (pos_type i = initial; i < size; ++i) {
2150                 Font font = owner_->getFont(buf.params(), i, outerfont);
2151                 if (text_[i] == META_INSET)
2152                         return false;
2153                 if (i != initial && font != font_old)
2154                         return false;
2155                 font_old = font;
2156         }
2157
2158         return true;
2159 }
2160
2161
2162 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2163                                     odocstream & os,
2164                                     OutputParams const & runparams,
2165                                     Font const & outerfont,
2166                                     pos_type initial) const
2167 {
2168         bool emph_flag = false;
2169
2170         LayoutPtr const & style = layout();
2171         FontInfo font_old =
2172                 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2173
2174         if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2175                 os << "]]>";
2176
2177         // parsing main loop
2178         for (pos_type i = initial; i < size(); ++i) {
2179                 Font font = getFont(buf.params(), i, outerfont);
2180
2181                 // handle <emphasis> tag
2182                 if (font_old.emph() != font.fontInfo().emph()) {
2183                         if (font.fontInfo().emph() == FONT_ON) {
2184                                 os << "<emphasis>";
2185                                 emph_flag = true;
2186                         } else if (i != initial) {
2187                                 os << "</emphasis>";
2188                                 emph_flag = false;
2189                         }
2190                 }
2191
2192                 if (isInset(i)) {
2193                         Inset const * inset = getInset(i);
2194                         inset->docbook(buf, os, runparams);
2195                 } else {
2196                         char_type c = d->text_[i];
2197
2198                         if (style->pass_thru)
2199                                 os.put(c);
2200                         else
2201                                 os << sgml::escapeChar(c);
2202                 }
2203                 font_old = font.fontInfo();
2204         }
2205
2206         if (emph_flag) {
2207                 os << "</emphasis>";
2208         }
2209
2210         if (style->free_spacing)
2211                 os << '\n';
2212         if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2213                 os << "<![CDATA[";
2214 }
2215
2216
2217 bool Paragraph::isHfill(pos_type pos) const
2218 {
2219         return isInset(pos)
2220                 && getInset(pos)->lyxCode() == HFILL_CODE;
2221 }
2222
2223
2224 bool Paragraph::isNewline(pos_type pos) const
2225 {
2226         return isInset(pos)
2227                 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2228 }
2229
2230
2231 bool Paragraph::isLineSeparator(pos_type pos) const
2232 {
2233         char_type const c = d->text_[pos];
2234         return isLineSeparatorChar(c)
2235                 || (c == META_INSET && getInset(pos) &&
2236                 getInset(pos)->isLineSeparator());
2237 }
2238
2239
2240 /// Used by the spellchecker
2241 bool Paragraph::isLetter(pos_type pos) const
2242 {
2243         if (isInset(pos))
2244                 return getInset(pos)->isLetter();
2245         else {
2246                 char_type const c = d->text_[pos];
2247                 return isLetterChar(c) || isDigit(c);
2248         }
2249 }
2250
2251
2252 Language const *
2253 Paragraph::getParLanguage(BufferParams const & bparams) const
2254 {
2255         if (!empty())
2256                 return getFirstFontSettings(bparams).language();
2257         // FIXME: we should check the prev par as well (Lgb)
2258         return bparams.language;
2259 }
2260
2261
2262 bool Paragraph::isRTL(BufferParams const & bparams) const
2263 {
2264         return lyxrc.rtl_support
2265                 && getParLanguage(bparams)->rightToLeft()
2266                 && ownerCode() != ERT_CODE
2267                 && ownerCode() != LISTINGS_CODE;
2268 }
2269
2270
2271 void Paragraph::changeLanguage(BufferParams const & bparams,
2272                                Language const * from, Language const * to)
2273 {
2274         // change language including dummy font change at the end
2275         for (pos_type i = 0; i <= size(); ++i) {
2276                 Font font = getFontSettings(bparams, i);
2277                 if (font.language() == from) {
2278                         font.setLanguage(to);
2279                         setFont(i, font);
2280                 }
2281         }
2282 }
2283
2284
2285 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2286 {
2287         Language const * doc_language = bparams.language;
2288         FontList::const_iterator cit = d->fontlist_.begin();
2289         FontList::const_iterator end = d->fontlist_.end();
2290
2291         for (; cit != end; ++cit)
2292                 if (cit->font().language() != ignore_language &&
2293                     cit->font().language() != latex_language &&
2294                     cit->font().language() != doc_language)
2295                         return true;
2296         return false;
2297 }
2298
2299
2300 // Convert the paragraph to a string.
2301 // Used for building the table of contents
2302 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2303 {
2304         return asString(buffer, 0, size(), label);
2305 }
2306
2307
2308 docstring const Paragraph::asString(Buffer const & buffer,
2309                                  pos_type beg, pos_type end, bool label) const
2310 {
2311
2312         odocstringstream os;
2313
2314         if (beg == 0 && label && !params().labelString().empty())
2315                 os << params().labelString() << ' ';
2316
2317         for (pos_type i = beg; i < end; ++i) {
2318                 char_type const c = d->text_[i];
2319                 if (isPrintable(c))
2320                         os.put(c);
2321                 else if (c == META_INSET)
2322                         getInset(i)->textString(buffer, os);
2323         }
2324
2325         return os.str();
2326 }
2327
2328
2329 void Paragraph::setInsetOwner(Inset * inset)
2330 {
2331         d->inset_owner_ = inset;
2332 }
2333
2334
2335 int Paragraph::id() const
2336 {
2337         return d->id_;
2338 }
2339
2340
2341 LayoutPtr const & Paragraph::layout() const
2342 {
2343         return d->layout_;
2344 }
2345
2346
2347 void Paragraph::layout(LayoutPtr const & new_layout)
2348 {
2349         d->layout_ = new_layout;
2350 }
2351
2352
2353 Inset * Paragraph::inInset() const
2354 {
2355         return d->inset_owner_;
2356 }
2357
2358
2359 InsetCode Paragraph::ownerCode() const
2360 {
2361         return d->inset_owner_ ?
2362                 d->inset_owner_->lyxCode() : NO_CODE;
2363 }
2364
2365
2366 ParagraphParameters & Paragraph::params()
2367 {
2368         return d->params_;
2369 }
2370
2371
2372 ParagraphParameters const & Paragraph::params() const
2373 {
2374         return d->params_;
2375 }
2376
2377
2378 bool Paragraph::isFreeSpacing() const
2379 {
2380         if (layout()->free_spacing)
2381                 return true;
2382         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2383 }
2384
2385
2386 bool Paragraph::allowEmpty() const
2387 {
2388         if (layout()->keepempty)
2389                 return true;
2390         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2391 }
2392
2393
2394 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2395 {
2396         if (!Encodings::is_arabic(c))
2397                 return c;
2398
2399         char_type prev_char = ' ';
2400         char_type next_char = ' ';
2401
2402         for (pos_type i = pos - 1; i >= 0; --i) {
2403                 char_type const par_char = d->text_[i];
2404                 if (!Encodings::isComposeChar_arabic(par_char)) {
2405                         prev_char = par_char;
2406                         break;
2407                 }
2408         }
2409
2410         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2411                 char_type const par_char = d->text_[i];
2412                 if (!Encodings::isComposeChar_arabic(par_char)) {
2413                         next_char = par_char;
2414                         break;
2415                 }
2416         }
2417
2418         if (Encodings::is_arabic(next_char)) {
2419                 if (Encodings::is_arabic(prev_char) &&
2420                         !Encodings::is_arabic_special(prev_char))
2421                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2422                 else
2423                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2424         } else {
2425                 if (Encodings::is_arabic(prev_char) &&
2426                         !Encodings::is_arabic_special(prev_char))
2427                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2428                 else
2429                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2430         }
2431 }
2432
2433
2434 int Paragraph::checkBiblio(bool track_changes)
2435 {
2436         //FIXME From JS:
2437         //This is getting more and more a mess. ...We really should clean
2438         //up this bibitem issue for 1.6. See also bug 2743.
2439
2440         // Add bibitem insets if necessary
2441         if (layout()->labeltype != LABEL_BIBLIO)
2442                 return 0;
2443
2444         bool hasbibitem = !d->insetlist_.empty()
2445                 // Insist on it being in pos 0
2446                 && d->text_[0] == META_INSET
2447                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2448
2449         docstring oldkey;
2450         docstring oldlabel;
2451
2452         // remove a bibitem in pos != 0
2453         // restore it later in pos 0 if necessary
2454         // (e.g. if a user inserts contents _before_ the item)
2455         // we're assuming there's only one of these, which there
2456         // should be.
2457         int erasedInsetPosition = -1;
2458         InsetList::iterator it = d->insetlist_.begin();
2459         InsetList::iterator end = d->insetlist_.end();
2460         for (; it != end; ++it)
2461                 if (it->inset->lyxCode() == BIBITEM_CODE
2462                     && it->pos > 0) {
2463                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2464                         oldkey = olditem->getParam("key");
2465                         oldlabel = olditem->getParam("label");
2466                         erasedInsetPosition = it->pos;
2467                         eraseChar(erasedInsetPosition, track_changes);
2468                         break;
2469         }
2470
2471         //There was an InsetBibitem at the beginning, and we didn't
2472         //have to erase one.
2473         if (hasbibitem && erasedInsetPosition < 0)
2474                         return 0;
2475
2476         //There was an InsetBibitem at the beginning and we did have to
2477         //erase one. So we give its properties to the beginning inset.
2478         if (hasbibitem) {
2479                 InsetBibitem * inset =
2480                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2481                 if (!oldkey.empty())
2482                         inset->setParam("key", oldkey);
2483                 inset->setParam("label", oldlabel);
2484                 return -erasedInsetPosition;
2485         }
2486
2487         //There was no inset at the beginning, so we need to create one with
2488         //the key and label of the one we erased.
2489         InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2490         // restore values of previously deleted item in this par.
2491         if (!oldkey.empty())
2492                 inset->setParam("key", oldkey);
2493         inset->setParam("label", oldlabel);
2494         insertInset(0, static_cast<Inset *>(inset),
2495                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2496
2497         return 1;
2498 }
2499
2500
2501 unsigned int Paragraph::macrocontextPosition() const
2502 {
2503         return d->macrocontext_position_;
2504 }
2505
2506
2507 void Paragraph::setMacrocontextPosition(unsigned int pos)
2508 {
2509         d->macrocontext_position_ = pos;
2510 }
2511
2512
2513 void Paragraph::checkAuthors(AuthorList const & authorList)
2514 {
2515         d->changes_.checkAuthors(authorList);
2516 }
2517
2518
2519 bool Paragraph::isUnchanged(pos_type pos) const
2520 {
2521         return lookupChange(pos).type == Change::UNCHANGED;
2522 }
2523
2524
2525 bool Paragraph::isInserted(pos_type pos) const
2526 {
2527         return lookupChange(pos).type == Change::INSERTED;
2528 }
2529
2530
2531 bool Paragraph::isDeleted(pos_type pos) const
2532 {
2533         return lookupChange(pos).type == Change::DELETED;
2534 }
2535
2536
2537 InsetList const & Paragraph::insetList() const
2538 {
2539         return d->insetlist_;
2540 }
2541
2542
2543 Inset * Paragraph::releaseInset(pos_type pos)
2544 {
2545         Inset * inset = d->insetlist_.release(pos);
2546         /// does not honour change tracking!
2547         eraseChar(pos, false);
2548         return inset;
2549 }
2550
2551
2552 Inset * Paragraph::getInset(pos_type pos)
2553 {
2554         return d->insetlist_.get(pos);
2555 }
2556
2557
2558 Inset const * Paragraph::getInset(pos_type pos) const
2559 {
2560         return d->insetlist_.get(pos);
2561 }
2562
2563
2564 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2565                 pos_type right, TextCase action)
2566 {
2567         // process sequences of modified characters; in change
2568         // tracking mode, this approach results in much better
2569         // usability than changing case on a char-by-char basis
2570         docstring changes;
2571
2572         bool const trackChanges = bparams.trackChanges;
2573
2574         bool capitalize = true;
2575
2576         for (; pos < right; ++pos) {
2577                 char_type oldChar = d->text_[pos];
2578                 char_type newChar = oldChar;
2579
2580                 // ignore insets and don't play with deleted text!
2581                 if (oldChar != META_INSET && !isDeleted(pos)) {
2582                         switch (action) {
2583                                 case text_lowercase:
2584                                         newChar = lowercase(oldChar);
2585                                         break;
2586                                 case text_capitalization:
2587                                         if (capitalize) {
2588                                                 newChar = uppercase(oldChar);
2589                                                 capitalize = false;
2590                                         }
2591                                         break;
2592                                 case text_uppercase:
2593                                         newChar = uppercase(oldChar);
2594                                         break;
2595                         }
2596                 }
2597
2598                 if (!isLetter(pos) || isDeleted(pos)) {
2599                         // permit capitalization again
2600                         capitalize = true;
2601                 }
2602
2603                 if (oldChar != newChar)
2604                         changes += newChar;
2605
2606                 if (oldChar == newChar || pos == right - 1) {
2607                         if (oldChar != newChar) {
2608                                 // step behind the changing area
2609                                 pos++;
2610                         }
2611                         int erasePos = pos - changes.size();
2612                         for (size_t i = 0; i < changes.size(); i++) {
2613                                 insertChar(pos, changes[i],
2614                                         getFontSettings(bparams,
2615                                         erasePos),
2616                                         trackChanges);
2617                                 if (!eraseChar(erasePos, trackChanges)) {
2618                                         ++erasePos;
2619                                         ++pos; // advance
2620                                         ++right; // expand selection
2621                                 }
2622                         }
2623                         changes.clear();
2624                 }
2625         }
2626 }
2627
2628
2629 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2630                 pos_type pos, bool del) const
2631 {
2632         int const strsize = str.length();
2633         int i = 0;
2634         pos_type const parsize = d->text_.size();
2635         for (i = 0; pos + i < parsize; ++i) {
2636                 if (i >= strsize)
2637                         break;
2638                 if (cs && str[i] != d->text_[pos + i])
2639                         break;
2640                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2641                         break;
2642                 if (!del && isDeleted(pos + i))
2643                         break;
2644         }
2645
2646         if (i != strsize)
2647                 return false;
2648
2649         // if necessary, check whether string matches word
2650         if (mw) {
2651                 if (pos > 0 && isLetter(pos - 1))
2652                         return false;
2653                 if (pos + strsize < parsize
2654                         && isLetter(pos + strsize))
2655                         return false;
2656         }
2657
2658         return true;
2659 }
2660
2661
2662 char_type Paragraph::getChar(pos_type pos) const
2663 {
2664         return d->text_[pos];
2665 }
2666
2667
2668 pos_type Paragraph::size() const
2669 {
2670         return d->text_.size();
2671 }
2672
2673
2674 bool Paragraph::empty() const
2675 {
2676         return d->text_.empty();
2677 }
2678
2679
2680 bool Paragraph::isInset(pos_type pos) const
2681 {
2682         return d->text_[pos] == META_INSET;
2683 }
2684
2685
2686 bool Paragraph::isSeparator(pos_type pos) const
2687 {
2688         //FIXME: Are we sure this can be the only separator?
2689         return d->text_[pos] == ' ';
2690 }
2691
2692
2693 } // namespace lyx