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