]> git.lyx.org Git - lyx.git/blob - src/Paragraph.cpp
Fix bug 4166: Crash when middle button click on inset label
[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 * 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           insetlist_(p.insetlist_, beg, end),
256           params_(p.params_), changes_(p.changes_),
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         default:
976                 return false;
977         }
978 }
979
980
981 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
982         pos_type & i, unsigned int & column)
983 {
984         switch (c) {
985         case '-':
986                 // within \ttfamily, "--" is merged to "-" (no endash)
987                 // so we avoid this rather irritating ligature
988                 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
989                         os << "-{}";
990                         column += 2;
991                 } else
992                         os << '-';
993                 return true;
994
995         // everything else has to be checked separately
996         // (depending on the encoding)
997         default:
998                 return false;
999         }
1000 }
1001
1002
1003 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1004         unsigned int & column, OutputParams & runparams)
1005 {
1006         // FIXME: if we have "LaTeX" with a font
1007         // change in the middle (before the 'T', then
1008         // the "TeX" part is still special cased.
1009         // Really we should only operate this on
1010         // "words" for some definition of word
1011
1012         for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1013                 if (!isTextAt(special_phrases[pnr].phrase, i))
1014                         continue;
1015                 if (runparams.moving_arg)
1016                         os << "\\protect";
1017                 os << special_phrases[pnr].macro;
1018                 i += special_phrases[pnr].phrase.length() - 1;
1019                 column += special_phrases[pnr].macro.length() - 1;
1020                 return true;
1021         }
1022         return false;
1023 }
1024
1025
1026 void Paragraph::Private::validate(LaTeXFeatures & features,
1027                                 Layout const & layout) const
1028 {
1029         // check the params.
1030         if (!params_.spacing().isDefault())
1031                 features.require("setspace");
1032
1033         // then the layouts
1034         features.useLayout(layout.name());
1035
1036         // then the fonts
1037         fontlist_.validate(features);
1038
1039         // then the indentation
1040         if (!params_.leftIndent().zero())
1041                 features.require("ParagraphLeftIndent");
1042
1043         // then the insets
1044         InsetList::const_iterator icit = insetlist_.begin();
1045         InsetList::const_iterator iend = insetlist_.end();
1046         for (; icit != iend; ++icit) {
1047                 if (icit->inset) {
1048                         icit->inset->validate(features);
1049                         if (layout.needprotect &&
1050                             icit->inset->lyxCode() == FOOT_CODE)
1051                                 features.require("NeedLyXFootnoteCode");
1052                 }
1053         }
1054
1055         // then the contents
1056         for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1057                 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1058                         if (!special_phrases[pnr].builtin
1059                             && isTextAt(special_phrases[pnr].phrase, i)) {
1060                                 features.require(special_phrases[pnr].phrase);
1061                                 break;
1062                         }
1063                 }
1064                 Encodings::validate(text_[i], features);
1065         }
1066 }
1067
1068 /////////////////////////////////////////////////////////////////////
1069 //
1070 // Paragraph
1071 //
1072 /////////////////////////////////////////////////////////////////////
1073
1074 namespace {
1075         Layout const emptyParagraphLayout;
1076 }
1077
1078 Paragraph::Paragraph() 
1079         : d(new Paragraph::Private(this, emptyParagraphLayout))
1080 {
1081         itemdepth = 0;
1082         d->params_.clear();
1083 }
1084
1085
1086 Paragraph::Paragraph(Paragraph const & par)
1087         : itemdepth(par.itemdepth),
1088         d(new Paragraph::Private(*par.d, this))
1089 {
1090         registerWords();
1091 }
1092
1093
1094 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1095         : itemdepth(par.itemdepth),
1096         d(new Paragraph::Private(*par.d, this, beg, end))
1097 {
1098         registerWords();
1099 }
1100
1101
1102 Paragraph & Paragraph::operator=(Paragraph const & par)
1103 {
1104         // needed as we will destroy the private part before copying it
1105         if (&par != this) {
1106                 itemdepth = par.itemdepth;
1107
1108                 deregisterWords();
1109                 delete d;
1110                 d = new Private(*par.d, this);
1111                 registerWords();
1112         }
1113         return *this;
1114 }
1115
1116
1117 Paragraph::~Paragraph()
1118 {
1119         deregisterWords();
1120         delete d;
1121 }
1122
1123
1124 void Paragraph::write(ostream & os, BufferParams const & bparams,
1125         depth_type & dth) const
1126 {
1127         // The beginning or end of a deeper (i.e. nested) area?
1128         if (dth != d->params_.depth()) {
1129                 if (d->params_.depth() > dth) {
1130                         while (d->params_.depth() > dth) {
1131                                 os << "\n\\begin_deeper";
1132                                 ++dth;
1133                         }
1134                 } else {
1135                         while (d->params_.depth() < dth) {
1136                                 os << "\n\\end_deeper";
1137                                 --dth;
1138                         }
1139                 }
1140         }
1141
1142         // First write the layout
1143         os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1144
1145         d->params_.write(os);
1146
1147         Font font1(inherit_font, bparams.language);
1148
1149         Change running_change = Change(Change::UNCHANGED);
1150
1151         int column = 0;
1152         for (pos_type i = 0; i <= size(); ++i) {
1153
1154                 Change change = lookupChange(i);
1155                 Changes::lyxMarkChange(os, column, running_change, change);
1156                 running_change = change;
1157
1158                 if (i == size())
1159                         break;
1160
1161                 // Write font changes
1162                 Font font2 = getFontSettings(bparams, i);
1163                 if (font2 != font1) {
1164                         font2.lyxWriteChanges(font1, os);
1165                         column = 0;
1166                         font1 = font2;
1167                 }
1168
1169                 char_type const c = d->text_[i];
1170                 switch (c) {
1171                 case META_INSET:
1172                         if (Inset const * inset = getInset(i)) {
1173                                 if (inset->directWrite()) {
1174                                         // international char, let it write
1175                                         // code directly so it's shorter in
1176                                         // the file
1177                                         inset->write(os);
1178                                 } else {
1179                                         if (i)
1180                                                 os << '\n';
1181                                         os << "\\begin_inset ";
1182                                         inset->write(os);
1183                                         os << "\n\\end_inset\n\n";
1184                                         column = 0;
1185                                 }
1186                         }
1187                         break;
1188                 case '\\':
1189                         os << "\n\\backslash\n";
1190                         column = 0;
1191                         break;
1192                 case '.':
1193                         if (i + 1 < size() && d->text_[i + 1] == ' ') {
1194                                 os << ".\n";
1195                                 column = 0;
1196                         } else
1197                                 os << '.';
1198                         break;
1199                 default:
1200                         if ((column > 70 && c == ' ')
1201                             || column > 79) {
1202                                 os << '\n';
1203                                 column = 0;
1204                         }
1205                         // this check is to amend a bug. LyX sometimes
1206                         // inserts '\0' this could cause problems.
1207                         if (c != '\0')
1208                                 os << to_utf8(docstring(1, c));
1209                         else
1210                                 LYXERR0("NUL char in structure.");
1211                         ++column;
1212                         break;
1213                 }
1214         }
1215
1216         os << "\n\\end_layout\n";
1217 }
1218
1219
1220 void Paragraph::validate(LaTeXFeatures & features) const
1221 {
1222         d->validate(features, *d->layout_);
1223 }
1224
1225
1226 void Paragraph::insert(pos_type start, docstring const & str,
1227                        Font const & font, Change const & change)
1228 {
1229         for (size_t i = 0, n = str.size(); i != n ; ++i)
1230                 insertChar(start + i, str[i], font, change);
1231 }
1232
1233
1234 void Paragraph::appendChar(char_type c, Font const & font,
1235                 Change const & change)
1236 {
1237         // track change
1238         d->changes_.insert(change, d->text_.size());
1239         // when appending characters, no need to update tables
1240         d->text_.push_back(c);
1241         setFont(d->text_.size() - 1, font);
1242 }
1243
1244
1245 void Paragraph::appendString(docstring const & s, Font const & font,
1246                 Change const & change)
1247 {
1248         pos_type end = s.size();
1249         size_t oldsize = d->text_.size();
1250         size_t newsize = oldsize + end;
1251         size_t capacity = d->text_.capacity();
1252         if (newsize >= capacity)
1253                 d->text_.reserve(max(capacity + 100, newsize));
1254
1255         // when appending characters, no need to update tables
1256         d->text_.append(s);
1257
1258         // FIXME: Optimize this!
1259         for (pos_type i = oldsize; i != newsize; ++i) {
1260                 // track change
1261                 d->changes_.insert(change, i);
1262         }
1263         d->fontlist_.set(oldsize, font);
1264         d->fontlist_.set(newsize - 1, font);
1265 }
1266
1267
1268 void Paragraph::insertChar(pos_type pos, char_type c,
1269                            bool trackChanges)
1270 {
1271         d->insertChar(pos, c, Change(trackChanges ?
1272                            Change::INSERTED : Change::UNCHANGED));
1273 }
1274
1275
1276 void Paragraph::insertChar(pos_type pos, char_type c,
1277                            Font const & font, bool trackChanges)
1278 {
1279         d->insertChar(pos, c, Change(trackChanges ?
1280                            Change::INSERTED : Change::UNCHANGED));
1281         setFont(pos, font);
1282 }
1283
1284
1285 void Paragraph::insertChar(pos_type pos, char_type c,
1286                            Font const & font, Change const & change)
1287 {
1288         d->insertChar(pos, c, change);
1289         setFont(pos, font);
1290 }
1291
1292
1293 void Paragraph::insertInset(pos_type pos, Inset * inset,
1294                             Font const & font, Change const & change)
1295 {
1296         insertInset(pos, inset, change);
1297         // Set the font/language of the inset...
1298         setFont(pos, font);
1299 }
1300
1301
1302 bool Paragraph::insetAllowed(InsetCode code)
1303 {
1304         return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1305 }
1306
1307
1308 void Paragraph::resetFonts(Font const & font)
1309 {
1310         d->fontlist_.clear();
1311         d->fontlist_.set(0, font);
1312         d->fontlist_.set(d->text_.size() - 1, font);
1313 }
1314
1315 // Gets uninstantiated font setting at position.
1316 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1317                                          pos_type pos) const
1318 {
1319         if (pos > size()) {
1320                 LYXERR0("pos: " << pos << " size: " << size());
1321                 LASSERT(pos <= size(), /**/);
1322         }
1323
1324         FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1325         if (cit != d->fontlist_.end())
1326                 return cit->font();
1327
1328         if (pos == size() && !empty())
1329                 return getFontSettings(bparams, pos - 1);
1330
1331         return Font(inherit_font, getParLanguage(bparams));
1332 }
1333
1334
1335 FontSpan Paragraph::fontSpan(pos_type pos) const
1336 {
1337         LASSERT(pos <= size(), /**/);
1338         pos_type start = 0;
1339
1340         FontList::const_iterator cit = d->fontlist_.begin();
1341         FontList::const_iterator end = d->fontlist_.end();
1342         for (; cit != end; ++cit) {
1343                 if (cit->pos() >= pos) {
1344                         if (pos >= beginOfBody())
1345                                 return FontSpan(max(start, beginOfBody()),
1346                                                 cit->pos());
1347                         else
1348                                 return FontSpan(start,
1349                                                 min(beginOfBody() - 1,
1350                                                          cit->pos()));
1351                 }
1352                 start = cit->pos() + 1;
1353         }
1354
1355         // This should not happen, but if so, we take no chances.
1356         // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1357         return FontSpan(pos, pos);
1358 }
1359
1360
1361 // Gets uninstantiated font setting at position 0
1362 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1363 {
1364         if (!empty() && !d->fontlist_.empty())
1365                 return d->fontlist_.begin()->font();
1366
1367         return Font(inherit_font, bparams.language);
1368 }
1369
1370
1371 // Gets the fully instantiated font at a given position in a paragraph
1372 // This is basically the same function as Text::GetFont() in text2.cpp.
1373 // The difference is that this one is used for generating the LaTeX file,
1374 // and thus cosmetic "improvements" are disallowed: This has to deliver
1375 // the true picture of the buffer. (Asger)
1376 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1377                                  Font const & outerfont) const
1378 {
1379         LASSERT(pos >= 0, /**/);
1380
1381         Font font = getFontSettings(bparams, pos);
1382
1383         pos_type const body_pos = beginOfBody();
1384         if (pos < body_pos)
1385                 font.fontInfo().realize(d->layout_->labelfont);
1386         else
1387                 font.fontInfo().realize(d->layout_->font);
1388
1389         font.fontInfo().realize(outerfont.fontInfo());
1390         font.fontInfo().realize(bparams.getFont().fontInfo());
1391
1392         return font;
1393 }
1394
1395
1396 Font const Paragraph::getLabelFont
1397         (BufferParams const & bparams, Font const & outerfont) const
1398 {
1399         FontInfo tmpfont = d->layout_->labelfont;
1400         tmpfont.realize(outerfont.fontInfo());
1401         tmpfont.realize(bparams.getFont().fontInfo());
1402         return Font(tmpfont, getParLanguage(bparams));
1403 }
1404
1405
1406 Font const Paragraph::getLayoutFont
1407         (BufferParams const & bparams, Font const & outerfont) const
1408 {
1409         FontInfo tmpfont = d->layout_->font;
1410         tmpfont.realize(outerfont.fontInfo());
1411         tmpfont.realize(bparams.getFont().fontInfo());
1412         return Font(tmpfont, getParLanguage(bparams));
1413 }
1414
1415
1416 /// Returns the height of the highest font in range
1417 FontSize Paragraph::highestFontInRange
1418         (pos_type startpos, pos_type endpos, FontSize def_size) const
1419 {
1420         return d->fontlist_.highestInRange(startpos, endpos, def_size);
1421 }
1422
1423
1424 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1425 {
1426         char_type c = d->text_[pos];
1427         if (!lyxrc.rtl_support)
1428                 return c;
1429
1430         char_type uc = c;
1431         switch (c) {
1432         case '(':
1433                 uc = ')';
1434                 break;
1435         case ')':
1436                 uc = '(';
1437                 break;
1438         case '[':
1439                 uc = ']';
1440                 break;
1441         case ']':
1442                 uc = '[';
1443                 break;
1444         case '{':
1445                 uc = '}';
1446                 break;
1447         case '}':
1448                 uc = '{';
1449                 break;
1450         case '<':
1451                 uc = '>';
1452                 break;
1453         case '>':
1454                 uc = '<';
1455                 break;
1456         }
1457         if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1458                 return uc;
1459         return c;
1460 }
1461
1462
1463 void Paragraph::setFont(pos_type pos, Font const & font)
1464 {
1465         LASSERT(pos <= size(), /**/);
1466
1467         // First, reduce font against layout/label font
1468         // Update: The setCharFont() routine in text2.cpp already
1469         // reduces font, so we don't need to do that here. (Asger)
1470         
1471         d->fontlist_.set(pos, font);
1472 }
1473
1474
1475 void Paragraph::makeSameLayout(Paragraph const & par)
1476 {
1477         d->layout_ = par.d->layout_;
1478         d->params_ = par.d->params_;
1479 }
1480
1481
1482 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1483 {
1484         if (isFreeSpacing())
1485                 return false;
1486
1487         int pos = 0;
1488         int count = 0;
1489
1490         while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1491                 if (eraseChar(pos, trackChanges))
1492                         ++count;
1493                 else
1494                         ++pos;
1495         }
1496
1497         return count > 0 || pos > 0;
1498 }
1499
1500
1501 bool Paragraph::hasSameLayout(Paragraph const & par) const
1502 {
1503         return par.d->layout_ == d->layout_
1504                 && d->params_.sameLayout(par.d->params_);
1505 }
1506
1507
1508 depth_type Paragraph::getDepth() const
1509 {
1510         return d->params_.depth();
1511 }
1512
1513
1514 depth_type Paragraph::getMaxDepthAfter() const
1515 {
1516         if (d->layout_->isEnvironment())
1517                 return d->params_.depth() + 1;
1518         else
1519                 return d->params_.depth();
1520 }
1521
1522
1523 char Paragraph::getAlign() const
1524 {
1525         if (d->params_.align() == LYX_ALIGN_LAYOUT)
1526                 return d->layout_->align;
1527         else
1528                 return d->params_.align();
1529 }
1530
1531
1532 docstring const & Paragraph::labelString() const
1533 {
1534         return d->params_.labelString();
1535 }
1536
1537
1538 // the next two functions are for the manual labels
1539 docstring const Paragraph::getLabelWidthString() const
1540 {
1541         if (d->layout_->margintype == MARGIN_MANUAL)
1542                 return d->params_.labelWidthString();
1543         else
1544                 return _("Senseless with this layout!");
1545 }
1546
1547
1548 void Paragraph::setLabelWidthString(docstring const & s)
1549 {
1550         d->params_.labelWidthString(s);
1551 }
1552
1553
1554 docstring const Paragraph::translateIfPossible(docstring const & s,
1555                 BufferParams const & bparams) const
1556 {
1557         if (!isAscii(s) || s.empty()) {
1558                 // This must be a user defined layout. We cannot translate
1559                 // this, since gettext accepts only ascii keys.
1560                 return s;
1561         }
1562         // Probably standard layout, try to translate
1563         Messages & m = getMessages(getParLanguage(bparams)->code());
1564         return m.get(to_ascii(s));
1565 }
1566
1567
1568 docstring Paragraph::expandLabel(Layout const & layout,
1569                 BufferParams const & bparams, bool process_appendix) const
1570 {
1571         DocumentClass const & tclass = bparams.documentClass();
1572
1573         docstring fmt;
1574         if (process_appendix && d->params_.appendix())
1575                 fmt = translateIfPossible(layout.labelstring_appendix(),
1576                         bparams);
1577         else
1578                 fmt = translateIfPossible(layout.labelstring(), bparams);
1579
1580         if (fmt.empty() && layout.labeltype == LABEL_COUNTER 
1581             && !layout.counter.empty())
1582                 fmt = "\\the" + layout.counter;
1583
1584         // handle 'inherited level parts' in 'fmt',
1585         // i.e. the stuff between '@' in   '@Section@.\arabic{subsection}'
1586         size_t const i = fmt.find('@', 0);
1587         if (i != docstring::npos) {
1588                 size_t const j = fmt.find('@', i + 1);
1589                 if (j != docstring::npos) {
1590                         docstring parent(fmt, i + 1, j - i - 1);
1591                         docstring label = from_ascii("??");
1592                         if (tclass.hasLayout(parent))
1593                                 docstring label = expandLabel(tclass[parent], bparams,
1594                                                       process_appendix);
1595                         fmt = docstring(fmt, 0, i) + label 
1596                                 + docstring(fmt, j + 1, docstring::npos);
1597                 }
1598         }
1599
1600         return tclass.counters().counterLabel(fmt);
1601 }
1602
1603
1604 void Paragraph::applyLayout(Layout const & new_layout)
1605 {
1606         d->layout_ = &new_layout;
1607         LyXAlignment const oldAlign = d->params_.align();
1608         
1609         if (!(oldAlign & d->layout_->alignpossible)) {
1610                 frontend::Alert::warning(_("Alignment not permitted"), 
1611                         _("The new layout does not permit the alignment previously used.\nSetting to default."));
1612                 d->params_.align(LYX_ALIGN_LAYOUT);
1613         }
1614 }
1615
1616
1617 pos_type Paragraph::beginOfBody() const
1618 {
1619         return d->begin_of_body_;
1620 }
1621
1622
1623 void Paragraph::setBeginOfBody()
1624 {
1625         if (d->layout_->labeltype != LABEL_MANUAL) {
1626                 d->begin_of_body_ = 0;
1627                 return;
1628         }
1629
1630         // Unroll the first two cycles of the loop
1631         // and remember the previous character to
1632         // remove unnecessary getChar() calls
1633         pos_type i = 0;
1634         pos_type end = size();
1635         if (i < end && !isNewline(i)) {
1636                 ++i;
1637                 char_type previous_char = 0;
1638                 char_type temp = 0;
1639                 if (i < end) {
1640                         previous_char = d->text_[i];
1641                         if (!isNewline(i)) {
1642                                 ++i;
1643                                 while (i < end && previous_char != ' ') {
1644                                         temp = d->text_[i];
1645                                         if (isNewline(i))
1646                                                 break;
1647                                         ++i;
1648                                         previous_char = temp;
1649                                 }
1650                         }
1651                 }
1652         }
1653
1654         d->begin_of_body_ = i;
1655 }
1656
1657
1658 bool Paragraph::forcePlainLayout() const
1659 {
1660         Inset const * const inset = inInset();
1661         if (!inset)
1662                 return true;
1663         return inset->forcePlainLayout();
1664 }
1665
1666
1667 bool Paragraph::allowParagraphCustomization() const
1668 {
1669         Inset const * const inset = inInset();
1670         if (!inset)
1671                 return true;
1672         return inset->allowParagraphCustomization();
1673 }
1674
1675
1676 bool Paragraph::usePlainLayout() const
1677 {
1678         Inset const * const inset = inInset();
1679         if (!inset)
1680                 return false;
1681         return inset->usePlainLayout();
1682 }
1683
1684
1685 namespace {
1686
1687 // paragraphs inside floats need different alignment tags to avoid
1688 // unwanted space
1689
1690 bool noTrivlistCentering(InsetCode code)
1691 {
1692         return code == FLOAT_CODE || code == WRAP_CODE;
1693 }
1694
1695
1696 string correction(string const & orig)
1697 {
1698         if (orig == "flushleft")
1699                 return "raggedright";
1700         if (orig == "flushright")
1701                 return "raggedleft";
1702         if (orig == "center")
1703                 return "centering";
1704         return orig;
1705 }
1706
1707
1708 string const corrected_env(string const & suffix, string const & env,
1709         InsetCode code)
1710 {
1711         string output = suffix + "{";
1712         if (noTrivlistCentering(code))
1713                 output += correction(env);
1714         else
1715                 output += env;
1716         output += "}";
1717         if (suffix == "\\begin")
1718                 output += "\n";
1719         return output;
1720 }
1721
1722
1723 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1724 {
1725         if (!contains(str, "\n"))
1726                 column += str.size();
1727         else {
1728                 string tmp;
1729                 texrow.newline();
1730                 column = rsplit(str, tmp, '\n').size();
1731         }
1732 }
1733
1734 } // namespace anon
1735
1736
1737 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1738                                  odocstream & os, TexRow & texrow,
1739                                  bool moving_arg) const
1740 {
1741         int column = 0;
1742
1743         if (params_.noindent()) {
1744                 os << "\\noindent ";
1745                 column += 10;
1746         }
1747         
1748         LyXAlignment const curAlign = params_.align();
1749
1750         if (curAlign == layout_->align)
1751                 return column;
1752
1753         switch (curAlign) {
1754         case LYX_ALIGN_NONE:
1755         case LYX_ALIGN_BLOCK:
1756         case LYX_ALIGN_LAYOUT:
1757         case LYX_ALIGN_SPECIAL:
1758                 break;
1759         case LYX_ALIGN_LEFT:
1760         case LYX_ALIGN_RIGHT:
1761         case LYX_ALIGN_CENTER:
1762                 if (moving_arg) {
1763                         os << "\\protect";
1764                         column += 8;
1765                 }
1766                 break;
1767         }
1768
1769         switch (curAlign) {
1770         case LYX_ALIGN_NONE:
1771         case LYX_ALIGN_BLOCK:
1772         case LYX_ALIGN_LAYOUT:
1773         case LYX_ALIGN_SPECIAL:
1774                 break;
1775         case LYX_ALIGN_LEFT: {
1776                 string output;
1777                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1778                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1779                 else
1780                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1781                 os << from_ascii(output);
1782                 adjust_row_column(output, texrow, column);
1783                 break;
1784         } case LYX_ALIGN_RIGHT: {
1785                 string output;
1786                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1787                         output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1788                 else
1789                         output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1790                 os << from_ascii(output);
1791                 adjust_row_column(output, texrow, column);
1792                 break;
1793         } case LYX_ALIGN_CENTER: {
1794                 string output;
1795                 output = corrected_env("\\begin", "center", owner_->ownerCode());
1796                 os << from_ascii(output);
1797                 adjust_row_column(output, texrow, column);
1798                 break;
1799         }
1800         }
1801
1802         return column;
1803 }
1804
1805
1806 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1807                                odocstream & os, TexRow & texrow,
1808                                bool moving_arg) const
1809 {
1810         int column = 0;
1811
1812         switch (params_.align()) {
1813         case LYX_ALIGN_NONE:
1814         case LYX_ALIGN_BLOCK:
1815         case LYX_ALIGN_LAYOUT:
1816         case LYX_ALIGN_SPECIAL:
1817                 break;
1818         case LYX_ALIGN_LEFT:
1819         case LYX_ALIGN_RIGHT:
1820         case LYX_ALIGN_CENTER:
1821                 if (moving_arg) {
1822                         os << "\\protect";
1823                         column = 8;
1824                 }
1825                 break;
1826         }
1827
1828         switch (params_.align()) {
1829         case LYX_ALIGN_NONE:
1830         case LYX_ALIGN_BLOCK:
1831         case LYX_ALIGN_LAYOUT:
1832         case LYX_ALIGN_SPECIAL:
1833                 break;
1834         case LYX_ALIGN_LEFT: {
1835                 string output;
1836                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1838                 else
1839                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1840                 os << from_ascii(output);
1841                 adjust_row_column(output, texrow, column);
1842                 break;
1843         } case LYX_ALIGN_RIGHT: {
1844                 string output;
1845                 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1846                         output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1847                 else
1848                         output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1849                 os << from_ascii(output);
1850                 adjust_row_column(output, texrow, column);
1851                 break;
1852         } case LYX_ALIGN_CENTER: {
1853                 string output;
1854                 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1855                 os << from_ascii(output);
1856                 adjust_row_column(output, texrow, column);
1857                 break;
1858         }
1859         }
1860
1861         return column;
1862 }
1863
1864
1865 // This one spits out the text of the paragraph
1866 bool Paragraph::latex(BufferParams const & bparams,
1867                                 Font const & outerfont,
1868                                 odocstream & os, TexRow & texrow,
1869                                 OutputParams const & runparams) const
1870 {
1871         LYXERR(Debug::LATEX, "SimpleTeXOnePar...     " << this);
1872
1873         bool return_value = false;
1874
1875         bool asdefault = forcePlainLayout();
1876
1877         Layout const & style = asdefault ?
1878                 bparams.documentClass().plainLayout() :
1879                 *d->layout_;
1880
1881         // Current base font for all inherited font changes, without any
1882         // change caused by an individual character, except for the language:
1883         // It is set to the language of the first character.
1884         // As long as we are in the label, this font is the base font of the
1885         // label. Before the first body character it is set to the base font
1886         // of the body.
1887         Font basefont;
1888
1889         // Maybe we have to create a optional argument.
1890         pos_type body_pos = beginOfBody();
1891         unsigned int column = 0;
1892
1893         if (body_pos > 0) {
1894                 // the optional argument is kept in curly brackets in
1895                 // case it contains a ']'
1896                 os << "[{";
1897                 column += 2;
1898                 basefont = getLabelFont(bparams, outerfont);
1899         } else {
1900                 basefont = getLayoutFont(bparams, outerfont);
1901         }
1902
1903         // Which font is currently active?
1904         Font running_font(basefont);
1905         // Do we have an open font change?
1906         bool open_font = false;
1907
1908         Change runningChange = Change(Change::UNCHANGED);
1909
1910         texrow.start(id(), 0);
1911
1912         // if the paragraph is empty, the loop will not be entered at all
1913         if (empty()) {
1914                 if (style.isCommand()) {
1915                         os << '{';
1916                         ++column;
1917                 }
1918                 if (!asdefault)
1919                         column += d->startTeXParParams(bparams, os, texrow,
1920                                                     runparams.moving_arg);
1921         }
1922
1923         for (pos_type i = 0; i < size(); ++i) {
1924                 // First char in paragraph or after label?
1925                 if (i == body_pos) {
1926                         if (body_pos > 0) {
1927                                 if (open_font) {
1928                                         column += running_font.latexWriteEndChanges(
1929                                                 os, bparams, runparams,
1930                                                 basefont, basefont);
1931                                         open_font = false;
1932                                 }
1933                                 basefont = getLayoutFont(bparams, outerfont);
1934                                 running_font = basefont;
1935
1936                                 column += Changes::latexMarkChange(os, bparams,
1937                                                 runningChange, Change(Change::UNCHANGED));
1938                                 runningChange = Change(Change::UNCHANGED);
1939
1940                                 os << "}] ";
1941                                 column +=3;
1942                         }
1943                         if (style.isCommand()) {
1944                                 os << '{';
1945                                 ++column;
1946                         }
1947
1948                         if (!asdefault)
1949                                 column += d->startTeXParParams(bparams, os,
1950                                                             texrow,
1951                                                             runparams.moving_arg);
1952                 }
1953
1954                 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1955                                                                  : lookupChange(i);
1956
1957                 if (bparams.outputChanges && runningChange != change) {
1958                         if (open_font) {
1959                                 column += running_font.latexWriteEndChanges(
1960                                                 os, bparams, runparams, basefont, basefont);
1961                                 open_font = false;
1962                         }
1963                         basefont = getLayoutFont(bparams, outerfont);
1964                         running_font = basefont;
1965
1966                         column += Changes::latexMarkChange(os, bparams, runningChange, change);
1967                         runningChange = change;
1968                 }
1969
1970                 // do not output text which is marked deleted
1971                 // if change tracking output is disabled
1972                 if (!bparams.outputChanges && change.type == Change::DELETED) {
1973                         continue;
1974                 }
1975
1976                 ++column;
1977
1978                 // Fully instantiated font
1979                 Font const font = getFont(bparams, i, outerfont);
1980
1981                 Font const last_font = running_font;
1982
1983                 // Do we need to close the previous font?
1984                 if (open_font &&
1985                     (font != running_font ||
1986                      font.language() != running_font.language()))
1987                 {
1988                         column += running_font.latexWriteEndChanges(
1989                                         os, bparams, runparams, basefont,
1990                                         (i == body_pos-1) ? basefont : font);
1991                         running_font = basefont;
1992                         open_font = false;
1993                 }
1994
1995                 // close babel's font environment before opening CJK.
1996                 if (!running_font.language()->babel().empty() &&
1997                     font.language()->encoding()->package() == Encoding::CJK) {
1998                                 string end_tag = subst(lyxrc.language_command_end,
1999                                                         "$$lang",
2000                                                         running_font.language()->babel());
2001                                 os << from_ascii(end_tag);
2002                                 column += end_tag.length();
2003                 }
2004
2005                 // Switch file encoding if necessary (and allowed)
2006                 if (!runparams.verbatim && 
2007                     runparams.encoding->package() != Encoding::none &&
2008                     font.language()->encoding()->package() != Encoding::none) {
2009                         pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2010                                         runparams, *(font.language()->encoding()));
2011                         if (enc_switch.first) {
2012                                 column += enc_switch.second;
2013                                 runparams.encoding = font.language()->encoding();
2014                         }
2015                 }
2016
2017                 char_type const c = d->text_[i];
2018
2019                 // Do we need to change font?
2020                 if ((font != running_font ||
2021                      font.language() != running_font.language()) &&
2022                         i != body_pos - 1)
2023                 {
2024                         odocstringstream ods;
2025                         column += font.latexWriteStartChanges(ods, bparams,
2026                                                               runparams, basefont,
2027                                                               last_font);
2028                         running_font = font;
2029                         open_font = true;
2030                         docstring fontchange = ods.str();
2031                         // check if the fontchange ends with a trailing blank
2032                         // (like "\small " (see bug 3382)
2033                         if (suffixIs(fontchange, ' ') && c == ' ')
2034                                 os << fontchange.substr(0, fontchange.size() - 1) 
2035                                    << from_ascii("{}");
2036                         else
2037                                 os << fontchange;
2038                 }
2039
2040                 if (c == ' ') {
2041                         // FIXME: integrate this case in latexSpecialChar
2042                         // Do not print the separation of the optional argument
2043                         // if style.pass_thru is false. This works because
2044                         // latexSpecialChar ignores spaces if
2045                         // style.pass_thru is false.
2046                         if (i != body_pos - 1) {
2047                                 if (d->simpleTeXBlanks(
2048                                                 runparams, os, texrow,
2049                                                 i, column, font, style)) {
2050                                         // A surrogate pair was output. We
2051                                         // must not call latexSpecialChar
2052                                         // in this iteration, since it would output
2053                                         // the combining character again.
2054                                         ++i;
2055                                         continue;
2056                                 }
2057                         }
2058                 }
2059
2060                 OutputParams rp = runparams;
2061                 rp.free_spacing = style.free_spacing;
2062                 rp.local_font = &font;
2063                 rp.intitle = style.intitle;
2064
2065                 // Two major modes:  LaTeX or plain
2066                 // Handle here those cases common to both modes
2067                 // and then split to handle the two modes separately.
2068                 if (c == META_INSET)
2069                         d->latexInset(bparams, os,
2070                                         texrow, rp, running_font,
2071                                         basefont, outerfont, open_font,
2072                                         runningChange, style, i, column);
2073                 else {
2074                         try {
2075                                 d->latexSpecialChar(os, rp, running_font, runningChange,
2076                                         style, i, column);
2077                         } catch (EncodingException & e) {
2078                                 if (runparams.dryrun) {
2079                                         os << "<" << _("LyX Warning: ")
2080                                            << _("uncodable character") << " '";
2081                                         os.put(c);
2082                                         os << "'>";
2083                                 } else {
2084                                         // add location information and throw again.
2085                                         e.par_id = id();
2086                                         e.pos = i;
2087                                         throw(e);
2088                                 }
2089                         }
2090                 }
2091
2092                 // Set the encoding to that returned from latexSpecialChar (see
2093                 // comment for encoding member in OutputParams.h)
2094                 runparams.encoding = rp.encoding;
2095         }
2096
2097         // If we have an open font definition, we have to close it
2098         if (open_font) {
2099 #ifdef FIXED_LANGUAGE_END_DETECTION
2100                 if (next_) {
2101                         running_font
2102                                 .latexWriteEndChanges(os, bparams, runparams,
2103                                         basefont,
2104                                         next_->getFont(bparams, 0, outerfont));
2105                 } else {
2106                         running_font.latexWriteEndChanges(os, bparams,
2107                                         runparams, basefont, basefont);
2108                 }
2109 #else
2110 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2111 //FIXME: there as we start another \selectlanguage with the next paragraph if
2112 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2113                 running_font.latexWriteEndChanges(os, bparams, runparams,
2114                                 basefont, basefont);
2115 #endif
2116         }
2117
2118         column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2119
2120         // Needed if there is an optional argument but no contents.
2121         if (body_pos > 0 && body_pos == size()) {
2122                 os << "}]~";
2123                 return_value = false;
2124         }
2125
2126         if (!asdefault) {
2127                 column += d->endTeXParParams(bparams, os, texrow,
2128                                           runparams.moving_arg);
2129         }
2130
2131         LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2132         return return_value;
2133 }
2134
2135
2136 bool Paragraph::emptyTag() const
2137 {
2138         for (pos_type i = 0; i < size(); ++i) {
2139                 if (Inset const * inset = getInset(i)) {
2140                         InsetCode lyx_code = inset->lyxCode();
2141                         if (lyx_code != TOC_CODE &&
2142                             lyx_code != INCLUDE_CODE &&
2143                             lyx_code != GRAPHICS_CODE &&
2144                             lyx_code != ERT_CODE &&
2145                             lyx_code != LISTINGS_CODE &&
2146                             lyx_code != FLOAT_CODE &&
2147                             lyx_code != TABULAR_CODE) {
2148                                 return false;
2149                         }
2150                 } else {
2151                         char_type c = d->text_[i];
2152                         if (c != ' ' && c != '\t')
2153                                 return false;
2154                 }
2155         }
2156         return true;
2157 }
2158
2159
2160 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2161         const
2162 {
2163         for (pos_type i = 0; i < size(); ++i) {
2164                 if (Inset const * inset = getInset(i)) {
2165                         InsetCode lyx_code = inset->lyxCode();
2166                         if (lyx_code == LABEL_CODE) {
2167                                 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2168                                 docstring const & id = il->getParam("name");
2169                                 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2170                         }
2171                 }
2172         }
2173         return string();
2174 }
2175
2176
2177 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2178         const
2179 {
2180         pos_type i;
2181         for (i = 0; i < size(); ++i) {
2182                 if (Inset const * inset = getInset(i)) {
2183                         inset->docbook(os, runparams);
2184                 } else {
2185                         char_type c = d->text_[i];
2186                         if (c == ' ')
2187                                 break;
2188                         os << sgml::escapeChar(c);
2189                 }
2190         }
2191         return i;
2192 }
2193
2194
2195 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2196 {
2197         Font font_old;
2198         pos_type size = text_.size();
2199         for (pos_type i = initial; i < size; ++i) {
2200                 Font font = owner_->getFont(buf.params(), i, outerfont);
2201                 if (text_[i] == META_INSET)
2202                         return false;
2203                 if (i != initial && font != font_old)
2204                         return false;
2205                 font_old = font;
2206         }
2207
2208         return true;
2209 }
2210
2211
2212 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2213                                     odocstream & os,
2214                                     OutputParams const & runparams,
2215                                     Font const & outerfont,
2216                                     pos_type initial) const
2217 {
2218         bool emph_flag = false;
2219
2220         Layout const & style = *d->layout_;
2221         FontInfo font_old =
2222                 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2223
2224         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2225                 os << "]]>";
2226
2227         // parsing main loop
2228         for (pos_type i = initial; i < size(); ++i) {
2229                 Font font = getFont(buf.params(), i, outerfont);
2230
2231                 // handle <emphasis> tag
2232                 if (font_old.emph() != font.fontInfo().emph()) {
2233                         if (font.fontInfo().emph() == FONT_ON) {
2234                                 os << "<emphasis>";
2235                                 emph_flag = true;
2236                         } else if (i != initial) {
2237                                 os << "</emphasis>";
2238                                 emph_flag = false;
2239                         }
2240                 }
2241
2242                 if (Inset const * inset = getInset(i)) {
2243                         inset->docbook(os, runparams);
2244                 } else {
2245                         char_type c = d->text_[i];
2246
2247                         if (style.pass_thru)
2248                                 os.put(c);
2249                         else
2250                                 os << sgml::escapeChar(c);
2251                 }
2252                 font_old = font.fontInfo();
2253         }
2254
2255         if (emph_flag) {
2256                 os << "</emphasis>";
2257         }
2258
2259         if (style.free_spacing)
2260                 os << '\n';
2261         if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2262                 os << "<![CDATA[";
2263 }
2264
2265
2266 bool Paragraph::isHfill(pos_type pos) const
2267 {
2268         Inset const * inset = getInset(pos);
2269         return inset && (inset->lyxCode() == SPACE_CODE &&
2270                          inset->isStretchableSpace());
2271 }
2272
2273
2274 bool Paragraph::isNewline(pos_type pos) const
2275 {
2276         Inset const * inset = getInset(pos);
2277         return inset && inset->lyxCode() == NEWLINE_CODE;
2278 }
2279
2280
2281 bool Paragraph::isLineSeparator(pos_type pos) const
2282 {
2283         char_type const c = d->text_[pos];
2284         if (isLineSeparatorChar(c))
2285                 return true;
2286         Inset const * inset = getInset(pos);
2287         return inset && inset->isLineSeparator();
2288 }
2289
2290
2291 /// Used by the spellchecker
2292 bool Paragraph::isLetter(pos_type pos) const
2293 {
2294         if (Inset const * inset = getInset(pos))
2295                 return inset->isLetter();
2296         char_type const c = d->text_[pos];
2297         return isLetterChar(c) || isDigit(c);
2298 }
2299
2300
2301 bool Paragraph::isChar(pos_type pos) const
2302 {
2303         if (Inset const * inset = getInset(pos))
2304                 return inset->isChar();
2305         char_type const c = d->text_[pos];
2306         return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2307 }
2308
2309
2310 bool Paragraph::isSpace(pos_type pos) const
2311 {
2312         if (Inset const * inset = getInset(pos))
2313                 return inset->isSpace();
2314         char_type const c = d->text_[pos];
2315         return lyx::isSpace(c);
2316 }
2317
2318
2319 Language const *
2320 Paragraph::getParLanguage(BufferParams const & bparams) const
2321 {
2322         if (!empty())
2323                 return getFirstFontSettings(bparams).language();
2324         // FIXME: we should check the prev par as well (Lgb)
2325         return bparams.language;
2326 }
2327
2328
2329 bool Paragraph::isRTL(BufferParams const & bparams) const
2330 {
2331         return lyxrc.rtl_support
2332                 && getParLanguage(bparams)->rightToLeft()
2333                 && ownerCode() != ERT_CODE
2334                 && ownerCode() != LISTINGS_CODE;
2335 }
2336
2337
2338 void Paragraph::changeLanguage(BufferParams const & bparams,
2339                                Language const * from, Language const * to)
2340 {
2341         // change language including dummy font change at the end
2342         for (pos_type i = 0; i <= size(); ++i) {
2343                 Font font = getFontSettings(bparams, i);
2344                 if (font.language() == from) {
2345                         font.setLanguage(to);
2346                         setFont(i, font);
2347                 }
2348         }
2349 }
2350
2351
2352 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2353 {
2354         Language const * doc_language = bparams.language;
2355         FontList::const_iterator cit = d->fontlist_.begin();
2356         FontList::const_iterator end = d->fontlist_.end();
2357
2358         for (; cit != end; ++cit)
2359                 if (cit->font().language() != ignore_language &&
2360                     cit->font().language() != latex_language &&
2361                     cit->font().language() != doc_language)
2362                         return true;
2363         return false;
2364 }
2365
2366
2367 docstring Paragraph::asString(int options) const
2368 {
2369         return asString(0, size(), options);
2370 }
2371
2372
2373 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2374 {
2375         odocstringstream os;
2376
2377         if (beg == 0 
2378                 && options & AS_STR_LABEL
2379                 && !d->params_.labelString().empty())
2380                 os << d->params_.labelString() << ' ';
2381
2382         for (pos_type i = beg; i < end; ++i) {
2383                 char_type const c = d->text_[i];
2384                 if (isPrintable(c))
2385                         os.put(c);
2386                 else if (c == META_INSET && options & AS_STR_INSETS)
2387                         getInset(i)->textString(os);
2388         }
2389
2390         return os.str();
2391 }
2392
2393
2394 void Paragraph::setInsetOwner(Inset * inset)
2395 {
2396         d->inset_owner_ = inset;
2397 }
2398
2399
2400 int Paragraph::id() const
2401 {
2402         return d->id_;
2403 }
2404
2405
2406 Layout const & Paragraph::layout() const
2407 {
2408         return *d->layout_;
2409 }
2410
2411
2412 void Paragraph::setLayout(Layout const & layout)
2413 {
2414         d->layout_ = &layout;
2415 }
2416
2417
2418 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2419 {
2420         if (usePlainLayout())
2421                 setLayout(tclass.plainLayout());
2422         else
2423                 setLayout(tclass.defaultLayout());
2424 }
2425
2426
2427 Inset * Paragraph::inInset() const
2428 {
2429         return d->inset_owner_;
2430 }
2431
2432
2433 InsetCode Paragraph::ownerCode() const
2434 {
2435         return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2436 }
2437
2438
2439 ParagraphParameters & Paragraph::params()
2440 {
2441         return d->params_;
2442 }
2443
2444
2445 ParagraphParameters const & Paragraph::params() const
2446 {
2447         return d->params_;
2448 }
2449
2450
2451 bool Paragraph::isFreeSpacing() const
2452 {
2453         if (d->layout_->free_spacing)
2454                 return true;
2455         return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2456 }
2457
2458
2459 bool Paragraph::allowEmpty() const
2460 {
2461         if (d->layout_->keepempty)
2462                 return true;
2463         return d->inset_owner_ && d->inset_owner_->allowEmpty();
2464 }
2465
2466
2467 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2468 {
2469         if (!Encodings::isArabicChar(c))
2470                 return c;
2471
2472         char_type prev_char = ' ';
2473         char_type next_char = ' ';
2474
2475         for (pos_type i = pos - 1; i >= 0; --i) {
2476                 char_type const par_char = d->text_[i];
2477                 if (!Encodings::isArabicComposeChar(par_char)) {
2478                         prev_char = par_char;
2479                         break;
2480                 }
2481         }
2482
2483         for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2484                 char_type const par_char = d->text_[i];
2485                 if (!Encodings::isArabicComposeChar(par_char)) {
2486                         next_char = par_char;
2487                         break;
2488                 }
2489         }
2490
2491         if (Encodings::isArabicChar(next_char)) {
2492                 if (Encodings::isArabicChar(prev_char) &&
2493                         !Encodings::isArabicSpecialChar(prev_char))
2494                         return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2495                 else
2496                         return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2497         } else {
2498                 if (Encodings::isArabicChar(prev_char) &&
2499                         !Encodings::isArabicSpecialChar(prev_char))
2500                         return Encodings::transformChar(c, Encodings::FORM_FINAL);
2501                 else
2502                         return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2503         }
2504 }
2505
2506
2507 int Paragraph::checkBiblio(Buffer const & buffer)
2508 {
2509         // FIXME From JS:
2510         // This is getting more and more a mess. ...We really should clean
2511         // up this bibitem issue for 1.6. See also bug 2743.
2512
2513         // Add bibitem insets if necessary
2514         if (d->layout_->labeltype != LABEL_BIBLIO)
2515                 return 0;
2516
2517         bool hasbibitem = !d->insetlist_.empty()
2518                 // Insist on it being in pos 0
2519                 && d->text_[0] == META_INSET
2520                 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2521
2522         bool track_changes = buffer.params().trackChanges;
2523
2524         docstring oldkey;
2525         docstring oldlabel;
2526
2527         // remove a bibitem in pos != 0
2528         // restore it later in pos 0 if necessary
2529         // (e.g. if a user inserts contents _before_ the item)
2530         // we're assuming there's only one of these, which there
2531         // should be.
2532         int erasedInsetPosition = -1;
2533         InsetList::iterator it = d->insetlist_.begin();
2534         InsetList::iterator end = d->insetlist_.end();
2535         for (; it != end; ++it)
2536                 if (it->inset->lyxCode() == BIBITEM_CODE
2537                     && it->pos > 0) {
2538                         InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2539                         oldkey = olditem->getParam("key");
2540                         oldlabel = olditem->getParam("label");
2541                         erasedInsetPosition = it->pos;
2542                         eraseChar(erasedInsetPosition, track_changes);
2543                         break;
2544         }
2545
2546         // There was an InsetBibitem at the beginning, and we didn't
2547         // have to erase one.
2548         if (hasbibitem && erasedInsetPosition < 0)
2549                         return 0;
2550
2551         // There was an InsetBibitem at the beginning and we did have to
2552         // erase one. So we give its properties to the beginning inset.
2553         if (hasbibitem) {
2554                 InsetBibitem * inset =
2555                         static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2556                 if (!oldkey.empty())
2557                         inset->setParam("key", oldkey);
2558                 inset->setParam("label", oldlabel);
2559                 return -erasedInsetPosition;
2560         }
2561
2562         // There was no inset at the beginning, so we need to create one with
2563         // the key and label of the one we erased.
2564         InsetBibitem * inset = 
2565                 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2566         // restore values of previously deleted item in this par.
2567         if (!oldkey.empty())
2568                 inset->setParam("key", oldkey);
2569         inset->setParam("label", oldlabel);
2570         insertInset(0, static_cast<Inset *>(inset),
2571                     Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2572
2573         return 1;
2574 }
2575
2576
2577 void Paragraph::checkAuthors(AuthorList const & authorList)
2578 {
2579         d->changes_.checkAuthors(authorList);
2580 }
2581
2582
2583 bool Paragraph::isUnchanged(pos_type pos) const
2584 {
2585         return lookupChange(pos).type == Change::UNCHANGED;
2586 }
2587
2588
2589 bool Paragraph::isInserted(pos_type pos) const
2590 {
2591         return lookupChange(pos).type == Change::INSERTED;
2592 }
2593
2594
2595 bool Paragraph::isDeleted(pos_type pos) const
2596 {
2597         return lookupChange(pos).type == Change::DELETED;
2598 }
2599
2600
2601 InsetList const & Paragraph::insetList() const
2602 {
2603         return d->insetlist_;
2604 }
2605
2606
2607 void Paragraph::setBuffer(Buffer & b)
2608 {
2609         d->insetlist_.setBuffer(b);
2610 }
2611
2612
2613 Inset * Paragraph::releaseInset(pos_type pos)
2614 {
2615         Inset * inset = d->insetlist_.release(pos);
2616         /// does not honour change tracking!
2617         eraseChar(pos, false);
2618         return inset;
2619 }
2620
2621
2622 Inset * Paragraph::getInset(pos_type pos)
2623 {
2624         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2625                  ? d->insetlist_.get(pos) : 0;
2626 }
2627
2628
2629 Inset const * Paragraph::getInset(pos_type pos) const
2630 {
2631         return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2632                  ? d->insetlist_.get(pos) : 0;
2633 }
2634
2635
2636 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2637                 pos_type & right, TextCase action)
2638 {
2639         // process sequences of modified characters; in change
2640         // tracking mode, this approach results in much better
2641         // usability than changing case on a char-by-char basis
2642         docstring changes;
2643
2644         bool const trackChanges = bparams.trackChanges;
2645
2646         bool capitalize = true;
2647
2648         for (; pos < right; ++pos) {
2649                 char_type oldChar = d->text_[pos];
2650                 char_type newChar = oldChar;
2651
2652                 // ignore insets and don't play with deleted text!
2653                 if (oldChar != META_INSET && !isDeleted(pos)) {
2654                         switch (action) {
2655                                 case text_lowercase:
2656                                         newChar = lowercase(oldChar);
2657                                         break;
2658                                 case text_capitalization:
2659                                         if (capitalize) {
2660                                                 newChar = uppercase(oldChar);
2661                                                 capitalize = false;
2662                                         }
2663                                         break;
2664                                 case text_uppercase:
2665                                         newChar = uppercase(oldChar);
2666                                         break;
2667                         }
2668                 }
2669
2670                 if (!isLetter(pos) || isDeleted(pos)) {
2671                         // permit capitalization again
2672                         capitalize = true;
2673                 }
2674
2675                 if (oldChar != newChar)
2676                         changes += newChar;
2677
2678                 if (oldChar == newChar || pos == right - 1) {
2679                         if (oldChar != newChar) {
2680                                 // step behind the changing area
2681                                 pos++;
2682                         }
2683                         int erasePos = pos - changes.size();
2684                         for (size_t i = 0; i < changes.size(); i++) {
2685                                 insertChar(pos, changes[i],
2686                                         getFontSettings(bparams,
2687                                         erasePos),
2688                                         trackChanges);
2689                                 if (!eraseChar(erasePos, trackChanges)) {
2690                                         ++erasePos;
2691                                         ++pos; // advance
2692                                         ++right; // expand selection
2693                                 }
2694                         }
2695                         changes.clear();
2696                 }
2697         }
2698 }
2699
2700
2701 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2702                 pos_type pos, bool del) const
2703 {
2704         int const strsize = str.length();
2705         int i = 0;
2706         pos_type const parsize = d->text_.size();
2707         for (i = 0; pos + i < parsize; ++i) {
2708                 if (i >= strsize)
2709                         break;
2710                 if (cs && str[i] != d->text_[pos + i])
2711                         break;
2712                 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2713                         break;
2714                 if (!del && isDeleted(pos + i))
2715                         break;
2716         }
2717
2718         if (i != strsize)
2719                 return false;
2720
2721         // if necessary, check whether string matches word
2722         if (mw) {
2723                 if (pos > 0 && isLetter(pos - 1))
2724                         return false;
2725                 if (pos + strsize < parsize
2726                         && isLetter(pos + strsize))
2727                         return false;
2728         }
2729
2730         return true;
2731 }
2732
2733
2734 char_type Paragraph::getChar(pos_type pos) const
2735 {
2736         return d->text_[pos];
2737 }
2738
2739
2740 pos_type Paragraph::size() const
2741 {
2742         return d->text_.size();
2743 }
2744
2745
2746 bool Paragraph::empty() const
2747 {
2748         return d->text_.empty();
2749 }
2750
2751
2752 bool Paragraph::isInset(pos_type pos) const
2753 {
2754         return d->text_[pos] == META_INSET;
2755 }
2756
2757
2758 bool Paragraph::isSeparator(pos_type pos) const
2759 {
2760         //FIXME: Are we sure this can be the only separator?
2761         return d->text_[pos] == ' ';
2762 }
2763
2764
2765 void Paragraph::deregisterWords()
2766 {
2767         Private::Words::const_iterator it;
2768         WordList & wl = theWordList();
2769         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2770                 wl.remove(*it);
2771         d->words_.clear();
2772 }
2773
2774
2775 void Paragraph::collectWords(CursorSlice const & sl)
2776 {
2777         // find new words
2778         bool inword = false;
2779
2780         //lyxerr << "Words: ";
2781         pos_type n = size();
2782         for (pos_type pos = 0; pos != n; ++pos) {
2783                 if (isDeleted(pos))
2784                         continue;
2785
2786                 if (!isLetter(pos)) {
2787                         inword = false;
2788                         continue;
2789                 }
2790
2791                 if (inword)
2792                         continue;
2793
2794                 inword = true;
2795                 CursorSlice from = sl;
2796                 CursorSlice to = sl;
2797                 from.pos() = pos;
2798                 to.pos() = pos;
2799                 from.text()->getWord(from, to, WHOLE_WORD);
2800                 if (to.pos() - from.pos() < 6)
2801                         continue;
2802                 docstring word = asString(from.pos(), to.pos(), false);
2803                 d->words_.insert(word);
2804                 //lyxerr << word << " ";
2805         }
2806         //lyxerr << std::endl;
2807 }
2808
2809
2810 void Paragraph::registerWords()
2811 {
2812         Private::Words::const_iterator it;
2813         WordList & wl = theWordList();
2814         for (it = d->words_.begin(); it != d->words_.end(); ++it)
2815                 wl.insert(*it);
2816 }
2817
2818
2819 void Paragraph::updateWords(CursorSlice const & sl)
2820 {
2821         LASSERT(&sl.paragraph() == this, /**/);
2822         deregisterWords();
2823         collectWords(sl);
2824         registerWords();
2825 }
2826
2827 } // namespace lyx