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