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