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