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