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