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