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