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