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