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