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