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