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