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