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