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