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