]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Update it.po
[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                               bool) const;
117
118         /// This could go to ParagraphParameters if we want to.
119         int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
120                             bool) 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 || code == WRAP_CODE;
1684 }
1685
1686
1687 string correction(string const & orig)
1688 {
1689         if (orig == "flushleft")
1690                 return "raggedright";
1691         if (orig == "flushright")
1692                 return "raggedleft";
1693         if (orig == "center")
1694                 return "centering";
1695         return orig;
1696 }
1697
1698
1699 string const corrected_env(string const & suffix, string const & env,
1700         InsetCode code)
1701 {
1702         string output = suffix + "{";
1703         if (noTrivlistCentering(code))
1704                 output += correction(env);
1705         else
1706                 output += env;
1707         output += "}";
1708         if (suffix == "\\begin")
1709                 output += "\n";
1710         return output;
1711 }
1712
1713
1714 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1715 {
1716         if (!contains(str, "\n"))
1717                 column += str.size();
1718         else {
1719                 string tmp;
1720                 texrow.newline();
1721                 column = rsplit(str, tmp, '\n').size();
1722         }
1723 }
1724
1725 } // namespace anon
1726
1727
1728 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1729                                  odocstream & os, TexRow & texrow,
1730                                  bool moving_arg) const
1731 {
1732         int column = 0;
1733
1734         if (params_.noindent()) {
1735                 os << "\\noindent ";
1736                 column += 10;
1737         }
1738         
1739         LyXAlignment const curAlign = params_.align();
1740
1741         if (curAlign == layout_->align)
1742                 return column;
1743
1744         switch (curAlign) {
1745         case LYX_ALIGN_NONE:
1746         case LYX_ALIGN_BLOCK:
1747         case LYX_ALIGN_LAYOUT:
1748         case LYX_ALIGN_SPECIAL:
1749                 break;
1750         case LYX_ALIGN_LEFT:
1751         case LYX_ALIGN_RIGHT:
1752         case LYX_ALIGN_CENTER:
1753                 if (moving_arg) {
1754                         os << "\\protect";
1755                         column += 8;
1756                 }
1757                 break;
1758         }
1759
1760         switch (curAlign) {
1761         case LYX_ALIGN_NONE:
1762         case LYX_ALIGN_BLOCK:
1763         case LYX_ALIGN_LAYOUT:
1764         case LYX_ALIGN_SPECIAL:
1765                 break;
1766         case LYX_ALIGN_LEFT: {
1767                 string output;
1768                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1769                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1770                 else
1771                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1772                 os << from_ascii(output);
1773                 adjust_row_column(output, texrow, column);
1774                 break;
1775         } case LYX_ALIGN_RIGHT: {
1776                 string output;
1777                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1778                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1779                 else
1780                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1781                 os << from_ascii(output);
1782                 adjust_row_column(output, texrow, column);
1783                 break;
1784         } case LYX_ALIGN_CENTER: {
1785                 string output;
1786                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1787                 os << from_ascii(output);
1788                 adjust_row_column(output, texrow, column);
1789                 break;
1790         }
1791         }
1792
1793         return column;
1794 }
1795
1796
1797 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1798                                odocstream & os, TexRow & texrow,
1799                                bool moving_arg) const
1800 {
1801         int column = 0;
1802
1803         switch (params_.align()) {
1804         case LYX_ALIGN_NONE:
1805         case LYX_ALIGN_BLOCK:
1806         case LYX_ALIGN_LAYOUT:
1807         case LYX_ALIGN_SPECIAL:
1808                 break;
1809         case LYX_ALIGN_LEFT:
1810         case LYX_ALIGN_RIGHT:
1811         case LYX_ALIGN_CENTER:
1812                 if (moving_arg) {
1813                         os << "\\protect";
1814                         column = 8;
1815                 }
1816                 break;
1817         }
1818
1819         switch (params_.align()) {
1820         case LYX_ALIGN_NONE:
1821         case LYX_ALIGN_BLOCK:
1822         case LYX_ALIGN_LAYOUT:
1823         case LYX_ALIGN_SPECIAL:
1824                 break;
1825         case LYX_ALIGN_LEFT: {
1826                 string output;
1827                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1828                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1829                 else
1830                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1831                 os << from_ascii(output);
1832                 adjust_row_column(output, texrow, column);
1833                 break;
1834         } case LYX_ALIGN_RIGHT: {
1835                 string output;
1836                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1838                 else
1839                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1840                 os << from_ascii(output);
1841                 adjust_row_column(output, texrow, column);
1842                 break;
1843         } case LYX_ALIGN_CENTER: {
1844                 string output;
1845                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1846                 os << from_ascii(output);
1847                 adjust_row_column(output, texrow, column);
1848                 break;
1849         }
1850         }
1851
1852         return column;
1853 }
1854
1855
1856 // This one spits out the text of the paragraph
1857 bool Paragraph::latex(BufferParams const & bparams,
1858                                 Font const & outerfont,
1859                                 odocstream & os, TexRow & texrow,
1860                                 OutputParams const & runparams) const
1861 {
1862         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1863
1864         bool return_value = false;
1865
1866         bool asdefault = forcePlainLayout();
1867
1868         Layout const & style = asdefault ?
1869                 bparams.documentClass().plainLayout() :
1870                 *d->layout_;
1871
1872         // Current base font for all inherited font changes, without any
1873         // change caused by an individual character, except for the language:
1874         // It is set to the language of the first character.
1875         // As long as we are in the label, this font is the base font of the
1876         // label. Before the first body character it is set to the base font
1877         // of the body.
1878         Font basefont;
1879
1880         // Maybe we have to create a optional argument.
1881         pos_type body_pos = beginOfBody();
1882         unsigned int column = 0;
1883
1884         if (body_pos > 0) {
1885                 // the optional argument is kept in curly brackets in
1886                 // case it contains a ']'
1887                 os << "[{";
1888                 column += 2;
1889                 basefont = getLabelFont(bparams, outerfont);
1890         } else {
1891                 basefont = getLayoutFont(bparams, outerfont);
1892         }
1893
1894         // Which font is currently active?
1895         Font running_font(basefont);
1896         // Do we have an open font change?
1897         bool open_font = false;
1898
1899         Change runningChange = Change(Change::UNCHANGED);
1900
1901         texrow.start(id(), 0);
1902
1903         // if the paragraph is empty, the loop will not be entered at all
1904         if (empty()) {
1905                 if (style.isCommand()) {
1906                         os << '{';
1907                         ++column;
1908                 }
1909                 if (!asdefault)
1910                         column += d->startTeXParParams(bparams, os, texrow,
1911                                                     runparams.moving_arg);
1912         }
1913
1914         for (pos_type i = 0; i < size(); ++i) {
1915                 // First char in paragraph or after label?
1916                 if (i == body_pos) {
1917                         if (body_pos > 0) {
1918                                 if (open_font) {
1919                                         column += running_font.latexWriteEndChanges(
1920                                                 os, bparams, runparams,
1921                                                 basefont, basefont);
1922                                         open_font = false;
1923                                 }
1924                                 basefont = getLayoutFont(bparams, outerfont);
1925                                 running_font = basefont;
1926
1927                                 column += Changes::latexMarkChange(os, bparams,
1928                                                 runningChange, Change(Change::UNCHANGED));
1929                                 runningChange = Change(Change::UNCHANGED);
1930
1931                                 os << "}] ";
1932                                 column +=3;
1933                         }
1934                         if (style.isCommand()) {
1935                                 os << '{';
1936                                 ++column;
1937                         }
1938
1939                         if (!asdefault)
1940                                 column += d->startTeXParParams(bparams, os,
1941                                                             texrow,
1942                                                             runparams.moving_arg);
1943                 }
1944
1945                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1946                                                                  : lookupChange(i);
1947
1948                 if (bparams.outputChanges && runningChange != change) {
1949                         if (open_font) {
1950                                 column += running_font.latexWriteEndChanges(
1951                                                 os, bparams, runparams, basefont, basefont);
1952                                 open_font = false;
1953                         }
1954                         basefont = getLayoutFont(bparams, outerfont);
1955                         running_font = basefont;
1956
1957                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1958                         runningChange = change;
1959                 }
1960
1961                 // do not output text which is marked deleted
1962                 // if change tracking output is disabled
1963                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1964                         continue;
1965                 }
1966
1967                 ++column;
1968
1969                 // Fully instantiated font
1970                 Font const font = getFont(bparams, i, outerfont);
1971
1972                 Font const last_font = running_font;
1973
1974                 // Do we need to close the previous font?
1975                 if (open_font &&
1976                     (font != running_font ||
1977                      font.language() != running_font.language()))
1978                 {
1979                         column += running_font.latexWriteEndChanges(
1980                                         os, bparams, runparams, basefont,
1981                                         (i == body_pos-1) ? basefont : font);
1982                         running_font = basefont;
1983                         open_font = false;
1984                 }
1985
1986                 // close babel's font environment before opening CJK.
1987                 if (!running_font.language()->babel().empty() &&
1988                     font.language()->encoding()->package() == Encoding::CJK) {
1989                                 string end_tag = subst(lyxrc.language_command_end,
1990                                                         "$$lang",
1991                                                         running_font.language()->babel());
1992                                 os << from_ascii(end_tag);
1993                                 column += end_tag.length();
1994                 }
1995
1996                 // Switch file encoding if necessary (and allowed)
1997                 if (!runparams.verbatim && 
1998                     runparams.encoding->package() != Encoding::none &&
1999                     font.language()->encoding()->package() != Encoding::none) {
2000                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2001                                         runparams, *(font.language()->encoding()));
2002                         if (enc_switch.first) {
2003                                 column += enc_switch.second;
2004                                 runparams.encoding = font.language()->encoding();
2005                         }
2006                 }
2007
2008                 char_type const c = d->text_[i];
2009
2010                 // Do we need to change font?
2011                 if ((font != running_font ||
2012                      font.language() != running_font.language()) &&
2013                         i != body_pos - 1)
2014                 {
2015                         odocstringstream ods;
2016                         column += font.latexWriteStartChanges(ods, bparams,
2017                                                               runparams, basefont,
2018                                                               last_font);
2019                         running_font = font;
2020                         open_font = true;
2021                         docstring fontchange = ods.str();
2022                         // check if the fontchange ends with a trailing blank
2023                         // (like "\small " (see bug 3382)
2024                         if (suffixIs(fontchange, ' ') && c == ' ')
2025                                 os << fontchange.substr(0, fontchange.size() - 1) 
2026                                    << from_ascii("{}");
2027                         else
2028                                 os << fontchange;
2029                 }
2030
2031                 if (c == ' ') {
2032                         // FIXME: integrate this case in latexSpecialChar
2033                         // Do not print the separation of the optional argument
2034                         // if style.pass_thru is false. This works because
2035                         // latexSpecialChar ignores spaces if
2036                         // style.pass_thru is false.
2037                         if (i != body_pos - 1) {
2038                                 if (d->simpleTeXBlanks(
2039                                                 runparams, os, texrow,
2040                                                 i, column, font, style)) {
2041                                         // A surrogate pair was output. We
2042                                         // must not call latexSpecialChar
2043                                         // in this iteration, since it would output
2044                                         // the combining character again.
2045                                         ++i;
2046                                         continue;
2047                                 }
2048                         }
2049                 }
2050
2051                 OutputParams rp = runparams;
2052                 rp.free_spacing = style.free_spacing;
2053                 rp.local_font = &font;
2054                 rp.intitle = style.intitle;
2055
2056                 // Two major modes:  LaTeX or plain
2057                 // Handle here those cases common to both modes
2058                 // and then split to handle the two modes separately.
2059                 if (c == META_INSET)
2060                         d->latexInset(bparams, os,
2061                                         texrow, rp, running_font,
2062                                         basefont, outerfont, open_font,
2063                                         runningChange, style, i, column);
2064                 else {
2065                         try {
2066                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2067                                         style, i, column);
2068                         } catch (EncodingException & e) {
2069                                 if (runparams.dryrun) {
2070                                         os << "<" << _("LyX Warning: ")
2071                                            << _("uncodable character") << " '";
2072                                         os.put(c);
2073                                         os << "'>";
2074                                 } else {
2075                                         // add location information and throw again.
2076                                         e.par_id = id();
2077                                         e.pos = i;
2078                                         throw(e);
2079                                 }
2080                         }
2081                 }
2082
2083                 // Set the encoding to that returned from latexSpecialChar (see
2084                 // comment for encoding member in OutputParams.h)
2085                 runparams.encoding = rp.encoding;
2086         }
2087
2088         // If we have an open font definition, we have to close it
2089         if (open_font) {
2090 #ifdef FIXED_LANGUAGE_END_DETECTION
2091                 if (next_) {
2092                         running_font
2093                                 .latexWriteEndChanges(os, bparams, runparams,
2094                                         basefont,
2095                                         next_->getFont(bparams, 0, outerfont));
2096                 } else {
2097                         running_font.latexWriteEndChanges(os, bparams,
2098                                         runparams, basefont, basefont);
2099                 }
2100 #else
2101 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2102 //FIXME: there as we start another \selectlanguage with the next paragraph if
2103 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2104                 running_font.latexWriteEndChanges(os, bparams, runparams,
2105                                 basefont, basefont);
2106 #endif
2107         }
2108
2109         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2110
2111         // Needed if there is an optional argument but no contents.
2112         if (body_pos > 0 && body_pos == size()) {
2113                 os << "}]~";
2114                 return_value = false;
2115         }
2116
2117         if (!asdefault) {
2118                 column += d->endTeXParParams(bparams, os, texrow,
2119                                           runparams.moving_arg);
2120         }
2121
2122         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2123         return return_value;
2124 }
2125
2126
2127 bool Paragraph::emptyTag() const
2128 {
2129         for (pos_type i = 0; i < size(); ++i) {
2130                 if (Inset const * inset = getInset(i)) {
2131                         InsetCode lyx_code = inset->lyxCode();
2132                         if (lyx_code != TOC_CODE &&
2133                             lyx_code != INCLUDE_CODE &&
2134                             lyx_code != GRAPHICS_CODE &&
2135                             lyx_code != ERT_CODE &&
2136                             lyx_code != LISTINGS_CODE &&
2137                             lyx_code != FLOAT_CODE &&
2138                             lyx_code != TABULAR_CODE) {
2139                                 return false;
2140                         }
2141                 } else {
2142                         char_type c = d->text_[i];
2143                         if (c != ' ' && c != '\t')
2144                                 return false;
2145                 }
2146         }
2147         return true;
2148 }
2149
2150
2151 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2152         const
2153 {
2154         for (pos_type i = 0; i < size(); ++i) {
2155                 if (Inset const * inset = getInset(i)) {
2156                         InsetCode lyx_code = inset->lyxCode();
2157                         if (lyx_code == LABEL_CODE) {
2158                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2159                                 docstring const & id = il->getParam("name");
2160                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2161                         }
2162                 }
2163         }
2164         return string();
2165 }
2166
2167
2168 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2169         const
2170 {
2171         pos_type i;
2172         for (i = 0; i < size(); ++i) {
2173                 if (Inset const * inset = getInset(i)) {
2174                         inset->docbook(os, runparams);
2175                 } else {
2176                         char_type c = d->text_[i];
2177                         if (c == ' ')
2178                                 break;
2179                         os << sgml::escapeChar(c);
2180                 }
2181         }
2182         return i;
2183 }
2184
2185
2186 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2187 {
2188         Font font_old;
2189         pos_type size = text_.size();
2190         for (pos_type i = initial; i < size; ++i) {
2191                 Font font = owner_->getFont(buf.params(), i, outerfont);
2192                 if (text_[i] == META_INSET)
2193                         return false;
2194                 if (i != initial && font != font_old)
2195                         return false;
2196                 font_old = font;
2197         }
2198
2199         return true;
2200 }
2201
2202
2203 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2204                                     odocstream & os,
2205                                     OutputParams const & runparams,
2206                                     Font const & outerfont,
2207                                     pos_type initial) const
2208 {
2209         bool emph_flag = false;
2210
2211         Layout const & style = *d->layout_;
2212         FontInfo font_old =
2213                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2214
2215         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2216                 os << "]]>";
2217
2218         // parsing main loop
2219         for (pos_type i = initial; i < size(); ++i) {
2220                 Font font = getFont(buf.params(), i, outerfont);
2221
2222                 // handle <emphasis> tag
2223                 if (font_old.emph() != font.fontInfo().emph()) {
2224                         if (font.fontInfo().emph() == FONT_ON) {
2225                                 os << "<emphasis>";
2226                                 emph_flag = true;
2227                         } else if (i != initial) {
2228                                 os << "</emphasis>";
2229                                 emph_flag = false;
2230                         }
2231                 }
2232
2233                 if (Inset const * inset = getInset(i)) {
2234                         inset->docbook(os, runparams);
2235                 } else {
2236                         char_type c = d->text_[i];
2237
2238                         if (style.pass_thru)
2239                                 os.put(c);
2240                         else
2241                                 os << sgml::escapeChar(c);
2242                 }
2243                 font_old = font.fontInfo();
2244         }
2245
2246         if (emph_flag) {
2247                 os << "</emphasis>";
2248         }
2249
2250         if (style.free_spacing)
2251                 os << '\n';
2252         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2253                 os << "<![CDATA[";
2254 }
2255
2256
2257 bool Paragraph::isHfill(pos_type pos) const
2258 {
2259         Inset const * inset = getInset(pos);
2260         return inset && (inset->lyxCode() == SPACE_CODE &&
2261                          inset->isStretchableSpace());
2262 }
2263
2264
2265 bool Paragraph::isNewline(pos_type pos) const
2266 {
2267         Inset const * inset = getInset(pos);
2268         return inset && inset->lyxCode() == NEWLINE_CODE;
2269 }
2270
2271
2272 bool Paragraph::isLineSeparator(pos_type pos) const
2273 {
2274         char_type const c = d->text_[pos];
2275         if (isLineSeparatorChar(c))
2276                 return true;
2277         Inset const * inset = getInset(pos);
2278         return inset && inset->isLineSeparator();
2279 }
2280
2281
2282 /// Used by the spellchecker
2283 bool Paragraph::isLetter(pos_type pos) const
2284 {
2285         if (Inset const * inset = getInset(pos))
2286                 return inset->isLetter();
2287         char_type const c = d->text_[pos];
2288         return isLetterChar(c) || isDigit(c);
2289 }
2290
2291
2292 bool Paragraph::isChar(pos_type pos) const
2293 {
2294         if (Inset const * inset = getInset(pos))
2295                 return inset->isChar();
2296         char_type const c = d->text_[pos];
2297         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2298 }
2299
2300
2301 bool Paragraph::isSpace(pos_type pos) const
2302 {
2303         if (Inset const * inset = getInset(pos))
2304                 return inset->isSpace();
2305         char_type const c = d->text_[pos];
2306         return lyx::isSpace(c);
2307 }
2308
2309
2310 Language const *
2311 Paragraph::getParLanguage(BufferParams const & bparams) const
2312 {
2313         if (!empty())
2314                 return getFirstFontSettings(bparams).language();
2315         // FIXME: we should check the prev par as well (Lgb)
2316         return bparams.language;
2317 }
2318
2319
2320 bool Paragraph::isRTL(BufferParams const & bparams) const
2321 {
2322         return lyxrc.rtl_support
2323                 && getParLanguage(bparams)->rightToLeft()
2324                 && ownerCode() != ERT_CODE
2325                 && ownerCode() != LISTINGS_CODE;
2326 }
2327
2328
2329 void Paragraph::changeLanguage(BufferParams const & bparams,
2330                                Language const * from, Language const * to)
2331 {
2332         // change language including dummy font change at the end
2333         for (pos_type i = 0; i <= size(); ++i) {
2334                 Font font = getFontSettings(bparams, i);
2335                 if (font.language() == from) {
2336                         font.setLanguage(to);
2337                         setFont(i, font);
2338                 }
2339         }
2340 }
2341
2342
2343 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2344 {
2345         Language const * doc_language = bparams.language;
2346         FontList::const_iterator cit = d->fontlist_.begin();
2347         FontList::const_iterator end = d->fontlist_.end();
2348
2349         for (; cit != end; ++cit)
2350                 if (cit->font().language() != ignore_language &&
2351                     cit->font().language() != latex_language &&
2352                     cit->font().language() != doc_language)
2353                         return true;
2354         return false;
2355 }
2356
2357
2358 docstring Paragraph::asString(int options) const
2359 {
2360         return asString(0, size(), options);
2361 }
2362
2363
2364 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2365 {
2366         odocstringstream os;
2367
2368         if (beg == 0 
2369                 && options & AS_STR_LABEL
2370                 && !d->params_.labelString().empty())
2371                 os << d->params_.labelString() << ' ';
2372
2373         for (pos_type i = beg; i < end; ++i) {
2374                 char_type const c = d->text_[i];
2375                 if (isPrintable(c))
2376                         os.put(c);
2377                 else if (c == META_INSET && options & AS_STR_INSETS)
2378                         getInset(i)->textString(os);
2379         }
2380
2381         return os.str();
2382 }
2383
2384
2385 void Paragraph::setInsetOwner(Inset const * inset)
2386 {
2387         d->inset_owner_ = inset;
2388 }
2389
2390
2391 int Paragraph::id() const
2392 {
2393         return d->id_;
2394 }
2395
2396
2397 Layout const & Paragraph::layout() const
2398 {
2399         return *d->layout_;
2400 }
2401
2402
2403 void Paragraph::setLayout(Layout const & layout)
2404 {
2405         d->layout_ = &layout;
2406 }
2407
2408
2409 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2410 {
2411         if (usePlainLayout())
2412                 setLayout(tclass.plainLayout());
2413         else
2414                 setLayout(tclass.defaultLayout());
2415 }
2416
2417
2418 Inset const & Paragraph::inInset() const
2419 {
2420         LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2421                 _("Memory problem"), _("Paragraph not properly initiliazed")));
2422         return *d->inset_owner_;
2423 }
2424
2425
2426 InsetCode Paragraph::ownerCode() const
2427 {
2428         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2429 }
2430
2431
2432 ParagraphParameters & Paragraph::params()
2433 {
2434         return d->params_;
2435 }
2436
2437
2438 ParagraphParameters const & Paragraph::params() const
2439 {
2440         return d->params_;
2441 }
2442
2443
2444 bool Paragraph::isFreeSpacing() const
2445 {
2446         if (d->layout_->free_spacing)
2447                 return true;
2448         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2449 }
2450
2451
2452 bool Paragraph::allowEmpty() const
2453 {
2454         if (d->layout_->keepempty)
2455                 return true;
2456         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2457 }
2458
2459
2460 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2461 {
2462         if (!Encodings::isArabicChar(c))
2463                 return c;
2464
2465         char_type prev_char = ' ';
2466         char_type next_char = ' ';
2467
2468         for (pos_type i = pos - 1; i >= 0; --i) {
2469                 char_type const par_char = d->text_[i];
2470                 if (!Encodings::isArabicComposeChar(par_char)) {
2471                         prev_char = par_char;
2472                         break;
2473                 }
2474         }
2475
2476         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2477                 char_type const par_char = d->text_[i];
2478                 if (!Encodings::isArabicComposeChar(par_char)) {
2479                         next_char = par_char;
2480                         break;
2481                 }
2482         }
2483
2484         if (Encodings::isArabicChar(next_char)) {
2485                 if (Encodings::isArabicChar(prev_char) &&
2486                         !Encodings::isArabicSpecialChar(prev_char))
2487                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2488                 else
2489                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2490         } else {
2491                 if (Encodings::isArabicChar(prev_char) &&
2492                         !Encodings::isArabicSpecialChar(prev_char))
2493                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2494                 else
2495                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2496         }
2497 }
2498
2499
2500 int Paragraph::checkBiblio(Buffer const & buffer)
2501 {
2502         // FIXME From JS:
2503         // This is getting more and more a mess. ...We really should clean
2504         // up this bibitem issue for 1.6. See also bug 2743.
2505
2506         // Add bibitem insets if necessary
2507         if (d->layout_->labeltype != LABEL_BIBLIO)
2508                 return 0;
2509
2510         bool hasbibitem = !d->insetlist_.empty()
2511                 // Insist on it being in pos 0
2512                 && d->text_[0] == META_INSET
2513                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2514
2515         bool track_changes = buffer.params().trackChanges;
2516
2517         docstring oldkey;
2518         docstring oldlabel;
2519
2520         // remove a bibitem in pos != 0
2521         // restore it later in pos 0 if necessary
2522         // (e.g. if a user inserts contents _before_ the item)
2523         // we're assuming there's only one of these, which there
2524         // should be.
2525         int erasedInsetPosition = -1;
2526         InsetList::iterator it = d->insetlist_.begin();
2527         InsetList::iterator end = d->insetlist_.end();
2528         for (; it != end; ++it)
2529                 if (it->inset->lyxCode() == BIBITEM_CODE
2530                     && it->pos > 0) {
2531                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2532                         oldkey = olditem->getParam("key");
2533                         oldlabel = olditem->getParam("label");
2534                         erasedInsetPosition = it->pos;
2535                         eraseChar(erasedInsetPosition, track_changes);
2536                         break;
2537         }
2538
2539         // There was an InsetBibitem at the beginning, and we didn't
2540         // have to erase one.
2541         if (hasbibitem && erasedInsetPosition < 0)
2542                         return 0;
2543
2544         // There was an InsetBibitem at the beginning and we did have to
2545         // erase one. So we give its properties to the beginning inset.
2546         if (hasbibitem) {
2547                 InsetBibitem * inset =
2548                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2549                 if (!oldkey.empty())
2550                         inset->setParam("key", oldkey);
2551                 inset->setParam("label", oldlabel);
2552                 return -erasedInsetPosition;
2553         }
2554
2555         // There was no inset at the beginning, so we need to create one with
2556         // the key and label of the one we erased.
2557         InsetBibitem * inset = 
2558                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2559         // restore values of previously deleted item in this par.
2560         if (!oldkey.empty())
2561                 inset->setParam("key", oldkey);
2562         inset->setParam("label", oldlabel);
2563         insertInset(0, static_cast<Inset *>(inset),
2564                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2565
2566         return 1;
2567 }
2568
2569
2570 void Paragraph::checkAuthors(AuthorList const & authorList)
2571 {
2572         d->changes_.checkAuthors(authorList);
2573 }
2574
2575
2576 bool Paragraph::isUnchanged(pos_type pos) const
2577 {
2578         return lookupChange(pos).type == Change::UNCHANGED;
2579 }
2580
2581
2582 bool Paragraph::isInserted(pos_type pos) const
2583 {
2584         return lookupChange(pos).type == Change::INSERTED;
2585 }
2586
2587
2588 bool Paragraph::isDeleted(pos_type pos) const
2589 {
2590         return lookupChange(pos).type == Change::DELETED;
2591 }
2592
2593
2594 InsetList const & Paragraph::insetList() const
2595 {
2596         return d->insetlist_;
2597 }
2598
2599
2600 void Paragraph::setBuffer(Buffer & b)
2601 {
2602         d->insetlist_.setBuffer(b);
2603 }
2604
2605
2606 Inset * Paragraph::releaseInset(pos_type pos)
2607 {
2608         Inset * inset = d->insetlist_.release(pos);
2609         /// does not honour change tracking!
2610         eraseChar(pos, false);
2611         return inset;
2612 }
2613
2614
2615 Inset * Paragraph::getInset(pos_type pos)
2616 {
2617         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2618                  ? d->insetlist_.get(pos) : 0;
2619 }
2620
2621
2622 Inset const * Paragraph::getInset(pos_type pos) const
2623 {
2624         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2625                  ? d->insetlist_.get(pos) : 0;
2626 }
2627
2628
2629 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2630                 pos_type & right, TextCase action)
2631 {
2632         // process sequences of modified characters; in change
2633         // tracking mode, this approach results in much better
2634         // usability than changing case on a char-by-char basis
2635         docstring changes;
2636
2637         bool const trackChanges = bparams.trackChanges;
2638
2639         bool capitalize = true;
2640
2641         for (; pos < right; ++pos) {
2642                 char_type oldChar = d->text_[pos];
2643                 char_type newChar = oldChar;
2644
2645                 // ignore insets and don't play with deleted text!
2646                 if (oldChar != META_INSET && !isDeleted(pos)) {
2647                         switch (action) {
2648                                 case text_lowercase:
2649                                         newChar = lowercase(oldChar);
2650                                         break;
2651                                 case text_capitalization:
2652                                         if (capitalize) {
2653                                                 newChar = uppercase(oldChar);
2654                                                 capitalize = false;
2655                                         }
2656                                         break;
2657                                 case text_uppercase:
2658                                         newChar = uppercase(oldChar);
2659                                         break;
2660                         }
2661                 }
2662
2663                 if (!isLetter(pos) || isDeleted(pos)) {
2664                         // permit capitalization again
2665                         capitalize = true;
2666                 }
2667
2668                 if (oldChar != newChar)
2669                         changes += newChar;
2670
2671                 if (oldChar == newChar || pos == right - 1) {
2672                         if (oldChar != newChar) {
2673                                 // step behind the changing area
2674                                 pos++;
2675                         }
2676                         int erasePos = pos - changes.size();
2677                         for (size_t i = 0; i < changes.size(); i++) {
2678                                 insertChar(pos, changes[i],
2679                                         getFontSettings(bparams,
2680                                         erasePos),
2681                                         trackChanges);
2682                                 if (!eraseChar(erasePos, trackChanges)) {
2683                                         ++erasePos;
2684                                         ++pos; // advance
2685                                         ++right; // expand selection
2686                                 }
2687                         }
2688                         changes.clear();
2689                 }
2690         }
2691 }
2692
2693
2694 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2695                 pos_type pos, bool del) const
2696 {
2697         int const strsize = str.length();
2698         int i = 0;
2699         pos_type const parsize = d->text_.size();
2700         for (i = 0; pos + i < parsize; ++i) {
2701                 if (i >= strsize)
2702                         break;
2703                 if (cs && str[i] != d->text_[pos + i])
2704                         break;
2705                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2706                         break;
2707                 if (!del && isDeleted(pos + i))
2708                         break;
2709         }
2710
2711         if (i != strsize)
2712                 return false;
2713
2714         // if necessary, check whether string matches word
2715         if (mw) {
2716                 if (pos > 0 && isLetter(pos - 1))
2717                         return false;
2718                 if (pos + strsize < parsize
2719                         && isLetter(pos + strsize))
2720                         return false;
2721         }
2722
2723         return true;
2724 }
2725
2726
2727 char_type Paragraph::getChar(pos_type pos) const
2728 {
2729         return d->text_[pos];
2730 }
2731
2732
2733 pos_type Paragraph::size() const
2734 {
2735         return d->text_.size();
2736 }
2737
2738
2739 bool Paragraph::empty() const
2740 {
2741         return d->text_.empty();
2742 }
2743
2744
2745 bool Paragraph::isInset(pos_type pos) const
2746 {
2747         return d->text_[pos] == META_INSET;
2748 }
2749
2750
2751 bool Paragraph::isSeparator(pos_type pos) const
2752 {
2753         //FIXME: Are we sure this can be the only separator?
2754         return d->text_[pos] == ' ';
2755 }
2756
2757
2758 void Paragraph::deregisterWords()
2759 {
2760         Private::Words::const_iterator it;
2761         WordList & wl = theWordList();
2762         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2763                 wl.remove(*it);
2764         d->words_.clear();
2765 }
2766
2767
2768 void Paragraph::collectWords(CursorSlice const & sl)
2769 {
2770         // find new words
2771         bool inword = false;
2772
2773         //lyxerr << "Words: ";
2774         pos_type n = size();
2775         for (pos_type pos = 0; pos != n; ++pos) {
2776                 if (isDeleted(pos))
2777                         continue;
2778
2779                 if (!isLetter(pos)) {
2780                         inword = false;
2781                         continue;
2782                 }
2783
2784                 if (inword)
2785                         continue;
2786
2787                 inword = true;
2788                 CursorSlice from = sl;
2789                 CursorSlice to = sl;
2790                 from.pos() = pos;
2791                 to.pos() = pos;
2792                 from.text()->getWord(from, to, WHOLE_WORD);
2793                 if (to.pos() - from.pos() < 6)
2794                         continue;
2795                 docstring word = asString(from.pos(), to.pos(), false);
2796                 d->words_.insert(word);
2797                 //lyxerr << word << " ";
2798         }
2799         //lyxerr << std::endl;
2800 }
2801
2802
2803 void Paragraph::registerWords()
2804 {
2805         Private::Words::const_iterator it;
2806         WordList & wl = theWordList();
2807         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2808                 wl.insert(*it);
2809 }
2810
2811
2812 void Paragraph::updateWords(CursorSlice const & sl)
2813 {
2814         LASSERT(&sl.paragraph() == this, /**/);
2815         deregisterWords();
2816         collectWords(sl);
2817         registerWords();
2818 }
2819
2820 } // namespace lyx