3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
22 #include "LayoutFile.h"
24 #include "BufferParams.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "ParagraphParameters.h"
40 #include "SpellChecker.h"
42 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
54 #include "support/debug.h"
55 #include "support/docstring_list.h"
56 #include "support/ExceptionMessage.h"
57 #include "support/gettext.h"
58 #include "support/lassert.h"
59 #include "support/lstrings.h"
60 #include "support/textutils.h"
66 using namespace lyx::support;
71 /// Inset identifier (above 0x10ffff, for ucs-4)
72 char_type const META_INSET = 0x200001;
75 /////////////////////////////////////////////////////////////////////
79 /////////////////////////////////////////////////////////////////////
81 class Paragraph::Private
85 Private(Paragraph * owner, Layout const & layout);
86 /// "Copy constructor"
87 Private(Private const &, Paragraph * owner);
88 /// Copy constructor from \p beg to \p end
89 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
92 void insertChar(pos_type pos, char_type c, Change const & change);
94 /// Output the surrogate pair formed by \p c and \p next to \p os.
95 /// \return the number of characters written.
96 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
97 OutputParams const &);
99 /// Output a space in appropriate formatting (or a surrogate pair
100 /// if the next character is a combining character).
101 /// \return whether a surrogate pair was output.
102 bool simpleTeXBlanks(OutputParams const &,
103 odocstream &, TexRow & texrow,
105 unsigned int & column,
107 Layout const & style);
109 /// Output consecutive unicode chars, belonging to the same script as
110 /// specified by the latex macro \p ltx, to \p os starting from \p i.
111 /// \return the number of characters written.
112 int writeScriptChars(odocstream & os, docstring const & ltx,
113 Change const &, Encoding const &, pos_type & i);
115 /// This could go to ParagraphParameters if we want to.
116 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
117 OutputParams const &) const;
119 /// This could go to ParagraphParameters if we want to.
120 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
121 OutputParams const &) const;
124 void latexInset(BufferParams const &,
126 TexRow & texrow, OutputParams &,
129 Font const & outerfont,
131 Change & running_change,
132 Layout const & style,
134 unsigned int & column);
137 void latexSpecialChar(
139 OutputParams const & runparams,
140 Font const & running_font,
141 Change const & running_change,
142 Layout const & style,
144 unsigned int & column);
151 unsigned int & column);
153 bool latexSpecialTypewriter(
157 unsigned int & column);
159 bool latexSpecialPhrase(
162 unsigned int & column,
163 OutputParams const & runparams);
166 void validate(LaTeXFeatures & features) const;
168 /// Checks if the paragraph contains only text and no inset or font change.
169 bool onlyText(Buffer const & buf, Font const & outerfont,
170 pos_type initial) const;
172 /// match a string against a particular point in the paragraph
173 bool isTextAt(string const & str, pos_type pos) const;
176 InsetCode ownerCode() const
178 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
181 /// Which Paragraph owns us?
185 Inset const * inset_owner_;
193 static unsigned int paragraph_id;
195 ParagraphParameters params_;
197 /// for recording and looking up changes
201 InsetList insetlist_;
204 pos_type begin_of_body_;
206 typedef docstring TextContainer;
210 typedef std::set<docstring> Words;
214 Layout const * layout_;
218 // Initialization of the counter for the paragraph id's,
219 unsigned int Paragraph::Private::paragraph_id = 0;
223 struct special_phrase {
229 special_phrase const special_phrases[] = {
230 { "LyX", from_ascii("\\LyX{}"), false },
231 { "TeX", from_ascii("\\TeX{}"), true },
232 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
233 { "LaTeX", from_ascii("\\LaTeX{}"), true },
236 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
241 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
242 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
244 id_ = paragraph_id++;
249 Paragraph::Private::Private(Private const & p, Paragraph * owner)
250 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
251 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
252 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
255 id_ = paragraph_id++;
259 Paragraph::Private::Private(Private const & p, Paragraph * owner,
260 pos_type beg, pos_type end)
261 : owner_(owner), inset_owner_(p.inset_owner_),
262 params_(p.params_), changes_(p.changes_),
263 insetlist_(p.insetlist_, beg, end),
264 begin_of_body_(p.begin_of_body_), words_(p.words_),
267 id_ = paragraph_id++;
268 if (beg >= pos_type(p.text_.size()))
270 text_ = p.text_.substr(beg, end - beg);
272 FontList::const_iterator fcit = fontlist_.begin();
273 FontList::const_iterator fend = fontlist_.end();
274 for (; fcit != fend; ++fcit) {
275 if (fcit->pos() < beg)
277 if (fcit->pos() >= end) {
278 // Add last entry in the fontlist_.
279 fontlist_.set(text_.size() - 1, fcit->font());
282 // Add a new entry in the fontlist_.
283 fontlist_.set(fcit->pos() - beg, fcit->font());
288 void Paragraph::addChangesToToc(DocIterator const & cdit,
289 Buffer const & buf) const
291 d->changes_.addToToc(cdit, buf);
295 bool Paragraph::isDeleted(pos_type start, pos_type end) const
297 LASSERT(start >= 0 && start <= size(), /**/);
298 LASSERT(end > start && end <= size() + 1, /**/);
300 return d->changes_.isDeleted(start, end);
304 bool Paragraph::isChanged(pos_type start, pos_type end) const
306 LASSERT(start >= 0 && start <= size(), /**/);
307 LASSERT(end > start && end <= size() + 1, /**/);
309 return d->changes_.isChanged(start, end);
313 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
315 // keep the logic here in sync with the logic of eraseChars()
319 Change const change = d->changes_.lookup(size());
320 return change.inserted() && change.currentAuthor();
324 void Paragraph::setChange(Change const & change)
326 // beware of the imaginary end-of-par character!
327 d->changes_.set(change, 0, size() + 1);
330 * Propagate the change recursively - but not in case of DELETED!
332 * Imagine that your co-author makes changes in an existing inset. He
333 * sends your document to you and you come to the conclusion that the
334 * inset should go completely. If you erase it, LyX must not delete all
335 * text within the inset. Otherwise, the change tracked insertions of
336 * your co-author get lost and there is no way to restore them later.
338 * Conclusion: An inset's content should remain untouched if you delete it
341 if (!change.deleted()) {
342 for (pos_type pos = 0; pos < size(); ++pos) {
343 if (Inset * inset = getInset(pos))
344 inset->setChange(change);
350 void Paragraph::setChange(pos_type pos, Change const & change)
352 LASSERT(pos >= 0 && pos <= size(), /**/);
353 d->changes_.set(change, pos);
355 // see comment in setChange(Change const &) above
356 if (!change.deleted() && pos < size())
357 if (Inset * inset = getInset(pos))
358 inset->setChange(change);
362 Change const & Paragraph::lookupChange(pos_type pos) const
364 LASSERT(pos >= 0 && pos <= size(), /**/);
365 return d->changes_.lookup(pos);
369 void Paragraph::acceptChanges(pos_type start, pos_type end)
371 LASSERT(start >= 0 && start <= size(), /**/);
372 LASSERT(end > start && end <= size() + 1, /**/);
374 for (pos_type pos = start; pos < end; ++pos) {
375 switch (lookupChange(pos).type) {
376 case Change::UNCHANGED:
377 // accept changes in nested inset
378 if (Inset * inset = getInset(pos))
379 inset->acceptChanges();
382 case Change::INSERTED:
383 d->changes_.set(Change(Change::UNCHANGED), pos);
384 // also accept changes in nested inset
385 if (Inset * inset = getInset(pos))
386 inset->acceptChanges();
389 case Change::DELETED:
390 // Suppress access to non-existent
391 // "end-of-paragraph char"
393 eraseChar(pos, false);
404 void Paragraph::rejectChanges(pos_type start, pos_type end)
406 LASSERT(start >= 0 && start <= size(), /**/);
407 LASSERT(end > start && end <= size() + 1, /**/);
409 for (pos_type pos = start; pos < end; ++pos) {
410 switch (lookupChange(pos).type) {
411 case Change::UNCHANGED:
412 // reject changes in nested inset
413 if (Inset * inset = getInset(pos))
414 inset->rejectChanges();
417 case Change::INSERTED:
418 // Suppress access to non-existent
419 // "end-of-paragraph char"
421 eraseChar(pos, false);
427 case Change::DELETED:
428 d->changes_.set(Change(Change::UNCHANGED), pos);
430 // Do NOT reject changes within a deleted inset!
431 // There may be insertions of a co-author inside of it!
439 void Paragraph::Private::insertChar(pos_type pos, char_type c,
440 Change const & change)
442 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
445 changes_.insert(change, pos);
447 // This is actually very common when parsing buffers (and
448 // maybe inserting ascii text)
449 if (pos == pos_type(text_.size())) {
450 // when appending characters, no need to update tables
455 text_.insert(text_.begin() + pos, c);
457 // Update the font table.
458 fontlist_.increasePosAfterPos(pos);
461 insetlist_.increasePosAfterPos(pos);
465 bool Paragraph::insertInset(pos_type pos, Inset * inset,
466 Change const & change)
468 LASSERT(inset, /**/);
469 LASSERT(pos >= 0 && pos <= size(), /**/);
471 // Paragraph::insertInset() can be used in cut/copy/paste operation where
472 // d->inset_owner_ is not set yet.
473 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
476 d->insertChar(pos, META_INSET, change);
477 LASSERT(d->text_[pos] == META_INSET, /**/);
479 // Add a new entry in the insetlist_.
480 d->insetlist_.insert(inset, pos);
485 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
487 LASSERT(pos >= 0 && pos <= size(), return false);
489 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
492 Change change = d->changes_.lookup(pos);
494 // set the character to DELETED if
495 // a) it was previously unchanged or
496 // b) it was inserted by a co-author
498 if (!change.changed() ||
499 (change.inserted() && !change.currentAuthor())) {
500 setChange(pos, Change(Change::DELETED));
504 if (change.deleted())
508 // Don't physically access the imaginary end-of-paragraph character.
509 // eraseChar() can only mark it as DELETED. A physical deletion of
510 // end-of-par must be handled externally.
516 d->changes_.erase(pos);
518 // if it is an inset, delete the inset entry
519 if (d->text_[pos] == META_INSET)
520 d->insetlist_.erase(pos);
522 d->text_.erase(d->text_.begin() + pos);
524 // Update the fontlist_
525 d->fontlist_.erase(pos);
527 // Update the insetlist_
528 d->insetlist_.decreasePosAfterPos(pos);
534 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
536 LASSERT(start >= 0 && start <= size(), /**/);
537 LASSERT(end >= start && end <= size() + 1, /**/);
540 for (pos_type count = end - start; count; --count) {
541 if (!eraseChar(i, trackChanges))
548 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
549 char_type next, OutputParams const & runparams)
551 // Writing next here may circumvent a possible font change between
552 // c and next. Since next is only output if it forms a surrogate pair
553 // with c we can ignore this:
554 // A font change inside a surrogate pair does not make sense and is
555 // hopefully impossible to input.
556 // FIXME: change tracking
557 // Is this correct WRT change tracking?
558 Encoding const & encoding = *(runparams.encoding);
559 docstring const latex1 = encoding.latexChar(next);
560 docstring const latex2 = encoding.latexChar(c);
561 if (docstring(1, next) == latex1) {
562 // the encoding supports the combination
563 os << latex2 << latex1;
564 return latex1.length() + latex2.length();
565 } else if (runparams.local_font &&
566 runparams.local_font->language()->lang() == "polutonikogreek") {
567 // polutonikogreek only works without the brackets
568 os << latex1 << latex2;
569 return latex1.length() + latex2.length();
571 os << latex1 << '{' << latex2 << '}';
572 return latex1.length() + latex2.length() + 2;
576 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
577 odocstream & os, TexRow & texrow,
579 unsigned int & column,
581 Layout const & style)
583 if (style.pass_thru || runparams.verbatim)
586 if (i + 1 < int(text_.size())) {
587 char_type next = text_[i + 1];
588 if (Encodings::isCombiningChar(next)) {
589 // This space has an accent, so we must always output it.
590 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
595 if (runparams.linelen > 0
596 && column > runparams.linelen
598 && text_[i - 1] != ' '
599 && (i + 1 < int(text_.size()))
600 // same in FreeSpacing mode
601 && !owner_->isFreeSpacing()
602 // In typewriter mode, we want to avoid
603 // ! . ? : at the end of a line
604 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
605 && (text_[i - 1] == '.'
606 || text_[i - 1] == '?'
607 || text_[i - 1] == ':'
608 || text_[i - 1] == '!'))) {
611 texrow.start(owner_->id(), i + 1);
613 } else if (style.free_spacing) {
622 int Paragraph::Private::writeScriptChars(odocstream & os,
623 docstring const & ltx,
624 Change const & runningChange,
625 Encoding const & encoding,
628 // FIXME: modifying i here is not very nice...
630 // We only arrive here when a proper language for character text_[i] has
631 // not been specified (i.e., it could not be translated in the current
632 // latex encoding) or its latex translation has been forced, and it
633 // belongs to a known script.
634 // Parameter ltx contains the latex translation of text_[i] as specified
635 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
636 // The latex macro name "textXXX" specifies the script to which text_[i]
637 // belongs and we use it in order to check whether characters from the
638 // same script immediately follow, such that we can collect them in a
639 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
640 // for the first char but only "<spec>" for all subsequent chars.
641 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
642 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
643 string script = to_ascii(ltx.substr(1, brace1 - 1));
646 bool closing_brace = true;
647 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
648 // Correct encoding is being used, so we can avoid \textgreek.
651 closing_brace = false;
653 os << ltx.substr(pos, length);
654 int size = text_.size();
655 while (i + 1 < size) {
656 char_type const next = text_[i + 1];
657 // Stop here if next character belongs to another script
658 // or there is a change in change tracking status.
659 if (!Encodings::isKnownScriptChar(next, script) ||
660 runningChange != owner_->lookupChange(i + 1))
664 FontList::const_iterator cit = fontlist_.begin();
665 FontList::const_iterator end = fontlist_.end();
666 for (; cit != end; ++cit) {
667 if (cit->pos() >= i && !found) {
668 prev_font = cit->font();
671 if (cit->pos() >= i + 1)
674 // Stop here if there is a font attribute or encoding change.
675 if (found && cit != end && prev_font != cit->font())
677 docstring const latex = encoding.latexChar(next);
678 docstring::size_type const b1 =
679 latex.find_first_of(from_ascii("{"));
680 docstring::size_type const b2 =
681 latex.find_last_of(from_ascii("}"));
682 int const len = b2 - b1 - 1;
683 os << latex.substr(b1 + 1, len);
695 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
697 pos_type const len = str.length();
699 // is the paragraph large enough?
700 if (pos + len > int(text_.size()))
703 // does the wanted text start at point?
704 for (string::size_type i = 0; i < str.length(); ++i) {
705 // Caution: direct comparison of characters works only
706 // because str is pure ASCII.
707 if (str[i] != text_[pos + i])
711 return fontlist_.hasChangeInRange(pos, len);
715 void Paragraph::Private::latexInset(
716 BufferParams const & bparams,
719 OutputParams & runparams,
722 Font const & outerfont,
724 Change & running_change,
725 Layout const & style,
727 unsigned int & column)
729 Inset * inset = owner_->getInset(i);
730 LASSERT(inset, /**/);
732 if (style.pass_thru) {
733 inset->plaintext(os, runparams);
737 // FIXME: move this to InsetNewline::latex
738 if (inset->lyxCode() == NEWLINE_CODE) {
739 // newlines are handled differently here than
740 // the default in simpleTeXSpecialChars().
741 if (!style.newline_allowed) {
745 column += running_font.latexWriteEndChanges(
746 os, bparams, runparams,
751 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
754 basefont = owner_->getLayoutFont(bparams, outerfont);
755 running_font = basefont;
757 if (runparams.moving_arg)
762 texrow.start(owner_->id(), i + 1);
766 if (owner_->isDeleted(i)) {
767 if( ++runparams.inDeletedInset == 1)
768 runparams.changeOfDeletedInset = owner_->lookupChange(i);
771 if (inset->canTrackChanges()) {
772 column += Changes::latexMarkChange(os, bparams, running_change,
773 Change(Change::UNCHANGED), runparams);
774 running_change = Change(Change::UNCHANGED);
778 odocstream::pos_type const len = os.tellp();
780 if (inset->forceLTR()
781 && running_font.isRightToLeft()
782 // ERT is an exception, it should be output with no
783 // decorations at all
784 && inset->lyxCode() != ERT_CODE) {
785 if (running_font.language()->lang() == "farsi")
792 // FIXME: Bug: we can have an empty font change here!
793 // if there has just been a font change, we are going to close it
794 // right now, which means stupid latex code like \textsf{}. AFAIK,
795 // this does not harm dvi output. A minor bug, thus (JMarc)
797 // Some insets cannot be inside a font change command.
798 // However, even such insets *can* be placed in \L or \R
799 // or their equivalents (for RTL language switches), so we don't
800 // close the language in those cases.
801 // ArabTeX, though, cannot handle this special behavior, it seems.
802 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
803 || running_font.language()->lang() == "arabic_arabtex";
804 if (open_font && inset->noFontChange()) {
805 bool closeLanguage = arabtex
806 || basefont.isRightToLeft() == running_font.isRightToLeft();
807 unsigned int count = running_font.latexWriteEndChanges(os,
808 bparams, runparams, basefont, basefont, closeLanguage);
810 // if any font properties were closed, update the running_font,
811 // making sure, however, to leave the language as it was
813 // FIXME: probably a better way to keep track of the old
814 // language, than copying the entire font?
815 Font const copy_font(running_font);
816 basefont = owner_->getLayoutFont(bparams, outerfont);
817 running_font = basefont;
819 running_font.setLanguage(copy_font.language());
820 // leave font open if language is still open
821 open_font = (running_font.language() == basefont.language());
823 runparams.local_font = &basefont;
830 tmp = inset->latex(os, runparams);
831 } catch (EncodingException & e) {
832 // add location information and throw again.
839 if (running_font.language()->lang() == "farsi")
846 for (int j = 0; j < tmp; ++j)
849 texrow.start(owner_->id(), i + 1);
852 column += os.tellp() - len;
855 if (owner_->isDeleted(i))
856 --runparams.inDeletedInset;
860 void Paragraph::Private::latexSpecialChar(
862 OutputParams const & runparams,
863 Font const & running_font,
864 Change const & running_change,
865 Layout const & style,
867 unsigned int & column)
869 char_type const c = text_[i];
871 if (style.pass_thru) {
873 // FIXME UNICODE: This can fail if c cannot
874 // be encoded in the current encoding.
879 if (runparams.verbatim) {
880 // FIXME UNICODE: This can fail if c cannot
881 // be encoded in the current encoding.
886 // If T1 font encoding is used, use the special
887 // characters it provides.
888 // NOTE: some languages reset the font encoding
890 if (!running_font.language()->internalFontEncoding()
891 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
894 // \tt font needs special treatment
895 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
896 && latexSpecialTypewriter(c, os, i, column))
899 // Otherwise, we use what LaTeX provides us.
902 os << "\\textbackslash{}";
906 os << "\\textless{}";
910 os << "\\textgreater{}";
921 os << "\\char`\\\"{}";
926 case '%': case '#': case '{':
934 os << "\\textasciitilde{}";
939 os << "\\textasciicircum{}";
946 // avoid being mistaken for optional arguments
954 // Blanks are printed before font switching.
955 // Sure? I am not! (try nice-latex)
956 // I am sure it's correct. LyX might be smarter
957 // in the future, but for now, nothing wrong is
963 if (latexSpecialPhrase(os, i, column, runparams))
969 Encoding const & encoding = *(runparams.encoding);
970 if (i + 1 < int(text_.size())) {
971 char_type next = text_[i + 1];
972 if (Encodings::isCombiningChar(next)) {
973 column += latexSurrogatePair(os, c, next, runparams) - 1;
979 docstring const latex = encoding.latexChar(c);
980 if (Encodings::isKnownScriptChar(c, script)
981 && prefixIs(latex, from_ascii("\\" + script)))
982 column += writeScriptChars(os, latex,
983 running_change, encoding, i) - 1;
984 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
985 // Prevent eating of a following
986 // space or command corruption by
987 // following characters
988 column += latex.length() + 1;
991 column += latex.length() - 1;
999 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1000 pos_type i, unsigned int & column)
1006 // In T1 encoding, these characters exist
1007 // but we should avoid ligatures
1008 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1010 os << "\\textcompwordmark{}";
1017 // soul.sty breaks with \char`\"
1018 os << "\\textquotedbl{}";
1027 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1028 pos_type i, unsigned int & column)
1032 // within \ttfamily, "--" is merged to "-" (no endash)
1033 // so we avoid this rather irritating ligature
1034 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1041 // everything else has to be checked separately
1042 // (depending on the encoding)
1049 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1050 unsigned int & column, OutputParams const & runparams)
1052 // FIXME: if we have "LaTeX" with a font
1053 // change in the middle (before the 'T', then
1054 // the "TeX" part is still special cased.
1055 // Really we should only operate this on
1056 // "words" for some definition of word
1058 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1059 if (!isTextAt(special_phrases[pnr].phrase, i))
1061 if (runparams.moving_arg)
1063 os << special_phrases[pnr].macro;
1064 i += special_phrases[pnr].phrase.length() - 1;
1065 column += special_phrases[pnr].macro.length() - 1;
1072 void Paragraph::Private::validate(LaTeXFeatures & features) const
1074 // check the params.
1075 if (!params_.spacing().isDefault())
1076 features.require("setspace");
1079 features.useLayout(layout_->name());
1082 fontlist_.validate(features);
1084 // then the indentation
1085 if (!params_.leftIndent().zero())
1086 features.require("ParagraphLeftIndent");
1089 InsetList::const_iterator icit = insetlist_.begin();
1090 InsetList::const_iterator iend = insetlist_.end();
1091 for (; icit != iend; ++icit) {
1093 icit->inset->validate(features);
1094 if (layout_->needprotect &&
1095 icit->inset->lyxCode() == FOOT_CODE)
1096 features.require("NeedLyXFootnoteCode");
1100 // then the contents
1101 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1102 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1103 if (!special_phrases[pnr].builtin
1104 && isTextAt(special_phrases[pnr].phrase, i)) {
1105 features.require(special_phrases[pnr].phrase);
1109 Encodings::validate(text_[i], features);
1113 /////////////////////////////////////////////////////////////////////
1117 /////////////////////////////////////////////////////////////////////
1120 Layout const emptyParagraphLayout;
1123 Paragraph::Paragraph()
1124 : d(new Paragraph::Private(this, emptyParagraphLayout))
1131 Paragraph::Paragraph(Paragraph const & par)
1132 : itemdepth(par.itemdepth),
1133 d(new Paragraph::Private(*par.d, this))
1139 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1140 : itemdepth(par.itemdepth),
1141 d(new Paragraph::Private(*par.d, this, beg, end))
1147 Paragraph & Paragraph::operator=(Paragraph const & par)
1149 // needed as we will destroy the private part before copying it
1151 itemdepth = par.itemdepth;
1155 d = new Private(*par.d, this);
1162 Paragraph::~Paragraph()
1171 // this shall be called just before every "os << ..." action.
1172 void flushString(ostream & os, docstring & s)
1181 void Paragraph::write(ostream & os, BufferParams const & bparams,
1182 depth_type & dth) const
1184 // The beginning or end of a deeper (i.e. nested) area?
1185 if (dth != d->params_.depth()) {
1186 if (d->params_.depth() > dth) {
1187 while (d->params_.depth() > dth) {
1188 os << "\n\\begin_deeper";
1192 while (d->params_.depth() < dth) {
1193 os << "\n\\end_deeper";
1199 // First write the layout
1200 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1202 d->params_.write(os);
1204 Font font1(inherit_font, bparams.language);
1206 Change running_change = Change(Change::UNCHANGED);
1208 // this string is used as a buffer to avoid repetitive calls
1209 // to to_utf8(), which turn out to be expensive (JMarc)
1210 docstring write_buffer;
1213 for (pos_type i = 0; i <= size(); ++i) {
1215 Change const change = lookupChange(i);
1216 if (change != running_change)
1217 flushString(os, write_buffer);
1218 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1219 running_change = change;
1224 // Write font changes (ignore spelling markers)
1225 Font font2 = getFontSettings(bparams, i);
1226 font2.setMisspelled(false);
1227 if (font2 != font1) {
1228 flushString(os, write_buffer);
1229 font2.lyxWriteChanges(font1, os);
1234 char_type const c = d->text_[i];
1237 if (Inset const * inset = getInset(i)) {
1238 flushString(os, write_buffer);
1239 if (inset->directWrite()) {
1240 // international char, let it write
1241 // code directly so it's shorter in
1247 os << "\\begin_inset ";
1249 os << "\n\\end_inset\n\n";
1255 flushString(os, write_buffer);
1256 os << "\n\\backslash\n";
1260 flushString(os, write_buffer);
1261 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1268 if ((column > 70 && c == ' ')
1270 flushString(os, write_buffer);
1274 // this check is to amend a bug. LyX sometimes
1275 // inserts '\0' this could cause problems.
1277 write_buffer.push_back(c);
1279 LYXERR0("NUL char in structure.");
1285 flushString(os, write_buffer);
1286 os << "\n\\end_layout\n";
1290 void Paragraph::validate(LaTeXFeatures & features) const
1292 d->validate(features);
1296 void Paragraph::insert(pos_type start, docstring const & str,
1297 Font const & font, Change const & change)
1299 for (size_t i = 0, n = str.size(); i != n ; ++i)
1300 insertChar(start + i, str[i], font, change);
1304 void Paragraph::appendChar(char_type c, Font const & font,
1305 Change const & change)
1308 d->changes_.insert(change, d->text_.size());
1309 // when appending characters, no need to update tables
1310 d->text_.push_back(c);
1311 setFont(d->text_.size() - 1, font);
1315 void Paragraph::appendString(docstring const & s, Font const & font,
1316 Change const & change)
1318 pos_type end = s.size();
1319 size_t oldsize = d->text_.size();
1320 size_t newsize = oldsize + end;
1321 size_t capacity = d->text_.capacity();
1322 if (newsize >= capacity)
1323 d->text_.reserve(max(capacity + 100, newsize));
1325 // when appending characters, no need to update tables
1328 // FIXME: Optimize this!
1329 for (size_t i = oldsize; i != newsize; ++i) {
1331 d->changes_.insert(change, i);
1333 d->fontlist_.set(oldsize, font);
1334 d->fontlist_.set(newsize - 1, font);
1338 void Paragraph::insertChar(pos_type pos, char_type c,
1341 d->insertChar(pos, c, Change(trackChanges ?
1342 Change::INSERTED : Change::UNCHANGED));
1346 void Paragraph::insertChar(pos_type pos, char_type c,
1347 Font const & font, bool trackChanges)
1349 d->insertChar(pos, c, Change(trackChanges ?
1350 Change::INSERTED : Change::UNCHANGED));
1355 void Paragraph::insertChar(pos_type pos, char_type c,
1356 Font const & font, Change const & change)
1358 d->insertChar(pos, c, change);
1363 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1364 Font const & font, Change const & change)
1366 bool const success = insertInset(pos, inset, change);
1367 // Set the font/language of the inset...
1373 void Paragraph::resetFonts(Font const & font)
1375 d->fontlist_.clear();
1376 d->fontlist_.set(0, font);
1377 d->fontlist_.set(d->text_.size() - 1, font);
1380 // Gets uninstantiated font setting at position.
1381 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1385 LYXERR0("pos: " << pos << " size: " << size());
1386 LASSERT(pos <= size(), /**/);
1389 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1390 if (cit != d->fontlist_.end())
1393 if (pos == size() && !empty())
1394 return getFontSettings(bparams, pos - 1);
1396 // Optimisation: avoid a full font instantiation if there is no
1397 // language change from previous call.
1398 static Font previous_font;
1399 static Language const * previous_lang = 0;
1400 Language const * lang = getParLanguage(bparams);
1401 if (lang != previous_lang) {
1402 previous_lang = lang;
1403 previous_font = Font(inherit_font, lang);
1405 return previous_font;
1409 FontSpan Paragraph::fontSpan(pos_type pos) const
1411 LASSERT(pos <= size(), /**/);
1414 FontList::const_iterator cit = d->fontlist_.begin();
1415 FontList::const_iterator end = d->fontlist_.end();
1416 for (; cit != end; ++cit) {
1417 if (cit->pos() >= pos) {
1418 if (pos >= beginOfBody())
1419 return FontSpan(max(start, beginOfBody()),
1422 return FontSpan(start,
1423 min(beginOfBody() - 1,
1426 start = cit->pos() + 1;
1429 // This should not happen, but if so, we take no chances.
1430 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1431 return FontSpan(pos, pos);
1435 // Gets uninstantiated font setting at position 0
1436 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1438 if (!empty() && !d->fontlist_.empty())
1439 return d->fontlist_.begin()->font();
1441 // Optimisation: avoid a full font instantiation if there is no
1442 // language change from previous call.
1443 static Font previous_font;
1444 static Language const * previous_lang = 0;
1445 if (bparams.language != previous_lang) {
1446 previous_lang = bparams.language;
1447 previous_font = Font(inherit_font, bparams.language);
1450 return previous_font;
1454 // Gets the fully instantiated font at a given position in a paragraph
1455 // This is basically the same function as Text::GetFont() in text2.cpp.
1456 // The difference is that this one is used for generating the LaTeX file,
1457 // and thus cosmetic "improvements" are disallowed: This has to deliver
1458 // the true picture of the buffer. (Asger)
1459 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1460 Font const & outerfont) const
1462 LASSERT(pos >= 0, /**/);
1464 Font font = getFontSettings(bparams, pos);
1466 pos_type const body_pos = beginOfBody();
1467 FontInfo & fi = font.fontInfo();
1469 fi.realize(d->layout_->labelfont);
1471 fi.realize(d->layout_->font);
1473 fi.realize(outerfont.fontInfo());
1474 fi.realize(bparams.getFont().fontInfo());
1480 Font const Paragraph::getLabelFont
1481 (BufferParams const & bparams, Font const & outerfont) const
1483 FontInfo tmpfont = d->layout_->labelfont;
1484 tmpfont.realize(outerfont.fontInfo());
1485 tmpfont.realize(bparams.getFont().fontInfo());
1486 return Font(tmpfont, getParLanguage(bparams));
1490 Font const Paragraph::getLayoutFont
1491 (BufferParams const & bparams, Font const & outerfont) const
1493 FontInfo tmpfont = d->layout_->font;
1494 tmpfont.realize(outerfont.fontInfo());
1495 tmpfont.realize(bparams.getFont().fontInfo());
1496 return Font(tmpfont, getParLanguage(bparams));
1500 /// Returns the height of the highest font in range
1501 FontSize Paragraph::highestFontInRange
1502 (pos_type startpos, pos_type endpos, FontSize def_size) const
1504 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1508 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1510 char_type c = d->text_[pos];
1511 if (!lyxrc.rtl_support)
1541 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1547 void Paragraph::setFont(pos_type pos, Font const & font)
1549 LASSERT(pos <= size(), /**/);
1551 // First, reduce font against layout/label font
1552 // Update: The setCharFont() routine in text2.cpp already
1553 // reduces font, so we don't need to do that here. (Asger)
1555 d->fontlist_.set(pos, font);
1559 void Paragraph::makeSameLayout(Paragraph const & par)
1561 d->layout_ = par.d->layout_;
1562 d->params_ = par.d->params_;
1566 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1568 if (isFreeSpacing())
1574 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1575 if (eraseChar(pos, trackChanges))
1581 return count > 0 || pos > 0;
1585 bool Paragraph::hasSameLayout(Paragraph const & par) const
1587 return par.d->layout_ == d->layout_
1588 && d->params_.sameLayout(par.d->params_);
1592 depth_type Paragraph::getDepth() const
1594 return d->params_.depth();
1598 depth_type Paragraph::getMaxDepthAfter() const
1600 if (d->layout_->isEnvironment())
1601 return d->params_.depth() + 1;
1603 return d->params_.depth();
1607 char Paragraph::getAlign() const
1609 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1610 return d->layout_->align;
1612 return d->params_.align();
1616 docstring const & Paragraph::labelString() const
1618 return d->params_.labelString();
1622 // the next two functions are for the manual labels
1623 docstring const Paragraph::getLabelWidthString() const
1625 if (d->layout_->margintype == MARGIN_MANUAL
1626 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1627 return d->params_.labelWidthString();
1629 return _("Senseless with this layout!");
1633 void Paragraph::setLabelWidthString(docstring const & s)
1635 d->params_.labelWidthString(s);
1639 docstring Paragraph::expandLabel(Layout const & layout,
1640 BufferParams const & bparams, bool process_appendix) const
1642 DocumentClass const & tclass = bparams.documentClass();
1643 string const & lang = getParLanguage(bparams)->code();
1644 bool const in_appendix = process_appendix && d->params_.appendix();
1645 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1647 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1648 && !layout.counter.empty())
1649 return tclass.counters().theCounter(layout.counter, lang);
1651 // handle 'inherited level parts' in 'fmt',
1652 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1653 size_t const i = fmt.find('@', 0);
1654 if (i != docstring::npos) {
1655 size_t const j = fmt.find('@', i + 1);
1656 if (j != docstring::npos) {
1657 docstring parent(fmt, i + 1, j - i - 1);
1658 docstring label = from_ascii("??");
1659 if (tclass.hasLayout(parent))
1660 docstring label = expandLabel(tclass[parent], bparams,
1662 fmt = docstring(fmt, 0, i) + label
1663 + docstring(fmt, j + 1, docstring::npos);
1667 return tclass.counters().counterLabel(fmt, lang);
1671 void Paragraph::applyLayout(Layout const & new_layout)
1673 d->layout_ = &new_layout;
1674 LyXAlignment const oldAlign = d->params_.align();
1676 if (!(oldAlign & d->layout_->alignpossible)) {
1677 frontend::Alert::warning(_("Alignment not permitted"),
1678 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1679 d->params_.align(LYX_ALIGN_LAYOUT);
1684 pos_type Paragraph::beginOfBody() const
1686 return d->begin_of_body_;
1690 void Paragraph::setBeginOfBody()
1692 if (d->layout_->labeltype != LABEL_MANUAL) {
1693 d->begin_of_body_ = 0;
1697 // Unroll the first two cycles of the loop
1698 // and remember the previous character to
1699 // remove unnecessary getChar() calls
1701 pos_type end = size();
1702 if (i < end && !isNewline(i)) {
1704 char_type previous_char = 0;
1707 previous_char = d->text_[i];
1708 if (!isNewline(i)) {
1710 while (i < end && previous_char != ' ') {
1715 previous_char = temp;
1721 d->begin_of_body_ = i;
1725 bool Paragraph::allowParagraphCustomization() const
1727 return inInset().allowParagraphCustomization();
1731 bool Paragraph::usePlainLayout() const
1733 return inInset().usePlainLayout();
1739 // paragraphs inside floats need different alignment tags to avoid
1742 bool noTrivlistCentering(InsetCode code)
1744 return code == FLOAT_CODE
1745 || code == WRAP_CODE
1746 || code == CELL_CODE;
1750 string correction(string const & orig)
1752 if (orig == "flushleft")
1753 return "raggedright";
1754 if (orig == "flushright")
1755 return "raggedleft";
1756 if (orig == "center")
1762 string const corrected_env(string const & suffix, string const & env,
1763 InsetCode code, bool const lastpar)
1765 string output = suffix + "{";
1766 if (noTrivlistCentering(code)) {
1768 // the last paragraph in non-trivlist-aligned
1769 // context is special (to avoid unwanted whitespace)
1770 if (suffix == "\\begin")
1771 return "\\" + correction(env) + "{}";
1774 output += correction(env);
1778 if (suffix == "\\begin")
1784 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1786 if (!contains(str, "\n"))
1787 column += str.size();
1791 column = rsplit(str, tmp, '\n').size();
1798 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1799 odocstream & os, TexRow & texrow,
1800 OutputParams const & runparams) const
1804 if (params_.noindent()) {
1805 os << "\\noindent ";
1809 LyXAlignment const curAlign = params_.align();
1811 if (curAlign == layout_->align)
1815 case LYX_ALIGN_NONE:
1816 case LYX_ALIGN_BLOCK:
1817 case LYX_ALIGN_LAYOUT:
1818 case LYX_ALIGN_SPECIAL:
1820 case LYX_ALIGN_LEFT:
1821 case LYX_ALIGN_RIGHT:
1822 case LYX_ALIGN_CENTER:
1823 if (runparams.moving_arg) {
1830 string const begin_tag = "\\begin";
1831 InsetCode code = ownerCode();
1832 bool const lastpar = runparams.isLastPar;
1835 case LYX_ALIGN_NONE:
1836 case LYX_ALIGN_BLOCK:
1837 case LYX_ALIGN_LAYOUT:
1838 case LYX_ALIGN_SPECIAL:
1840 case LYX_ALIGN_LEFT: {
1842 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1843 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1845 output = corrected_env(begin_tag, "flushright", code, lastpar);
1846 os << from_ascii(output);
1847 adjust_row_column(output, texrow, column);
1849 } case LYX_ALIGN_RIGHT: {
1851 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1852 output = corrected_env(begin_tag, "flushright", code, lastpar);
1854 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1855 os << from_ascii(output);
1856 adjust_row_column(output, texrow, column);
1858 } case LYX_ALIGN_CENTER: {
1860 output = corrected_env(begin_tag, "center", code, lastpar);
1861 os << from_ascii(output);
1862 adjust_row_column(output, texrow, column);
1871 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1872 odocstream & os, TexRow & texrow,
1873 OutputParams const & runparams) const
1877 LyXAlignment const curAlign = params_.align();
1879 if (curAlign == layout_->align)
1883 case LYX_ALIGN_NONE:
1884 case LYX_ALIGN_BLOCK:
1885 case LYX_ALIGN_LAYOUT:
1886 case LYX_ALIGN_SPECIAL:
1888 case LYX_ALIGN_LEFT:
1889 case LYX_ALIGN_RIGHT:
1890 case LYX_ALIGN_CENTER:
1891 if (runparams.moving_arg) {
1898 string const end_tag = "\n\\par\\end";
1899 InsetCode code = ownerCode();
1900 bool const lastpar = runparams.isLastPar;
1903 case LYX_ALIGN_NONE:
1904 case LYX_ALIGN_BLOCK:
1905 case LYX_ALIGN_LAYOUT:
1906 case LYX_ALIGN_SPECIAL:
1908 case LYX_ALIGN_LEFT: {
1910 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1911 output = corrected_env(end_tag, "flushleft", code, lastpar);
1913 output = corrected_env(end_tag, "flushright", code, lastpar);
1914 os << from_ascii(output);
1915 adjust_row_column(output, texrow, column);
1917 } case LYX_ALIGN_RIGHT: {
1919 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1920 output = corrected_env(end_tag, "flushright", code, lastpar);
1922 output = corrected_env(end_tag, "flushleft", code, lastpar);
1923 os << from_ascii(output);
1924 adjust_row_column(output, texrow, column);
1926 } case LYX_ALIGN_CENTER: {
1928 output = corrected_env(end_tag, "center", code, lastpar);
1929 os << from_ascii(output);
1930 adjust_row_column(output, texrow, column);
1939 // This one spits out the text of the paragraph
1940 bool Paragraph::latex(BufferParams const & bparams,
1941 Font const & outerfont,
1942 odocstream & os, TexRow & texrow,
1943 OutputParams const & runparams,
1944 int start_pos, int end_pos) const
1946 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1948 bool return_value = false;
1950 bool const allowcust = allowParagraphCustomization();
1952 // FIXME This check should not be needed. Perhaps issue an
1953 // error if it triggers.
1954 Layout const & style = inInset().forcePlainLayout() ?
1955 bparams.documentClass().plainLayout() : *d->layout_;
1957 // Current base font for all inherited font changes, without any
1958 // change caused by an individual character, except for the language:
1959 // It is set to the language of the first character.
1960 // As long as we are in the label, this font is the base font of the
1961 // label. Before the first body character it is set to the base font
1965 // Maybe we have to create a optional argument.
1966 pos_type body_pos = beginOfBody();
1967 unsigned int column = 0;
1972 basefont = getLabelFont(bparams, outerfont);
1974 basefont = getLayoutFont(bparams, outerfont);
1977 // Which font is currently active?
1978 Font running_font(basefont);
1979 // Do we have an open font change?
1980 bool open_font = false;
1982 Change runningChange = Change(Change::UNCHANGED);
1984 Encoding const * const prev_encoding = runparams.encoding;
1986 texrow.start(id(), 0);
1988 // if the paragraph is empty, the loop will not be entered at all
1990 if (style.isCommand()) {
1995 column += d->startTeXParParams(bparams, os, texrow,
1999 for (pos_type i = 0; i < size(); ++i) {
2000 // First char in paragraph or after label?
2001 if (i == body_pos) {
2004 column += running_font.latexWriteEndChanges(
2005 os, bparams, runparams,
2006 basefont, basefont);
2009 basefont = getLayoutFont(bparams, outerfont);
2010 running_font = basefont;
2012 column += Changes::latexMarkChange(os, bparams,
2013 runningChange, Change(Change::UNCHANGED),
2015 runningChange = Change(Change::UNCHANGED);
2020 if (style.isCommand()) {
2026 column += d->startTeXParParams(bparams, os,
2031 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2034 if (bparams.outputChanges && runningChange != change) {
2036 column += running_font.latexWriteEndChanges(
2037 os, bparams, runparams, basefont, basefont);
2040 basefont = getLayoutFont(bparams, outerfont);
2041 running_font = basefont;
2043 column += Changes::latexMarkChange(os, bparams, runningChange,
2045 runningChange = change;
2048 // do not output text which is marked deleted
2049 // if change tracking output is disabled
2050 if (!bparams.outputChanges && change.deleted()) {
2056 // Fully instantiated font
2057 Font const font = getFont(bparams, i, outerfont);
2059 Font const last_font = running_font;
2061 // Do we need to close the previous font?
2063 (font != running_font ||
2064 font.language() != running_font.language()))
2066 column += running_font.latexWriteEndChanges(
2067 os, bparams, runparams, basefont,
2068 (i == body_pos-1) ? basefont : font);
2069 running_font = basefont;
2073 // close babel's font environment before opening CJK.
2074 if (!running_font.language()->babel().empty() &&
2075 font.language()->encoding()->package() == Encoding::CJK) {
2076 string end_tag = subst(lyxrc.language_command_end,
2078 running_font.language()->babel());
2079 os << from_ascii(end_tag);
2080 column += end_tag.length();
2083 // Switch file encoding if necessary (and allowed)
2084 if (!runparams.verbatim &&
2085 runparams.encoding->package() != Encoding::none &&
2086 font.language()->encoding()->package() != Encoding::none) {
2087 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2088 runparams, *(font.language()->encoding()));
2089 if (enc_switch.first) {
2090 column += enc_switch.second;
2091 runparams.encoding = font.language()->encoding();
2095 char_type const c = d->text_[i];
2097 // Do we need to change font?
2098 if ((font != running_font ||
2099 font.language() != running_font.language()) &&
2102 odocstringstream ods;
2103 column += font.latexWriteStartChanges(ods, bparams,
2104 runparams, basefont,
2106 running_font = font;
2108 docstring fontchange = ods.str();
2109 // check whether the fontchange ends with a \\textcolor
2110 // modifier and the text starts with a space (bug 4473)
2111 docstring const last_modifier = rsplit(fontchange, '\\');
2112 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2113 os << fontchange << from_ascii("{}");
2114 // check if the fontchange ends with a trailing blank
2115 // (like "\small " (see bug 3382)
2116 else if (suffixIs(fontchange, ' ') && c == ' ')
2117 os << fontchange.substr(0, fontchange.size() - 1)
2118 << from_ascii("{}");
2123 // FIXME: think about end_pos implementation...
2124 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2125 // FIXME: integrate this case in latexSpecialChar
2126 // Do not print the separation of the optional argument
2127 // if style.pass_thru is false. This works because
2128 // latexSpecialChar ignores spaces if
2129 // style.pass_thru is false.
2130 if (i != body_pos - 1) {
2131 if (d->simpleTeXBlanks(
2132 runparams, os, texrow,
2133 i, column, font, style)) {
2134 // A surrogate pair was output. We
2135 // must not call latexSpecialChar
2136 // in this iteration, since it would output
2137 // the combining character again.
2144 OutputParams rp = runparams;
2145 rp.free_spacing = style.free_spacing;
2146 rp.local_font = &font;
2147 rp.intitle = style.intitle;
2149 // Two major modes: LaTeX or plain
2150 // Handle here those cases common to both modes
2151 // and then split to handle the two modes separately.
2152 if (c == META_INSET) {
2153 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2154 d->latexInset(bparams, os,
2155 texrow, rp, running_font,
2156 basefont, outerfont, open_font,
2157 runningChange, style, i, column);
2160 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2162 d->latexSpecialChar(os, rp, running_font, runningChange,
2164 } catch (EncodingException & e) {
2165 if (runparams.dryrun) {
2166 os << "<" << _("LyX Warning: ")
2167 << _("uncodable character") << " '";
2171 // add location information and throw again.
2180 // Set the encoding to that returned from latexSpecialChar (see
2181 // comment for encoding member in OutputParams.h)
2182 runparams.encoding = rp.encoding;
2185 // If we have an open font definition, we have to close it
2187 #ifdef FIXED_LANGUAGE_END_DETECTION
2190 .latexWriteEndChanges(os, bparams, runparams,
2192 next_->getFont(bparams, 0, outerfont));
2194 running_font.latexWriteEndChanges(os, bparams,
2195 runparams, basefont, basefont);
2198 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2199 //FIXME: there as we start another \selectlanguage with the next paragraph if
2200 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2201 running_font.latexWriteEndChanges(os, bparams, runparams,
2202 basefont, basefont);
2206 column += Changes::latexMarkChange(os, bparams, runningChange,
2207 Change(Change::UNCHANGED), runparams);
2209 // Needed if there is an optional argument but no contents.
2210 if (body_pos > 0 && body_pos == size()) {
2212 return_value = false;
2215 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2216 && runparams.encoding != prev_encoding) {
2217 runparams.encoding = prev_encoding;
2218 if (!bparams.useXetex)
2219 os << setEncoding(prev_encoding->iconvName());
2222 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2223 return return_value;
2227 bool Paragraph::emptyTag() const
2229 for (pos_type i = 0; i < size(); ++i) {
2230 if (Inset const * inset = getInset(i)) {
2231 InsetCode lyx_code = inset->lyxCode();
2232 // FIXME testing like that is wrong. What is
2234 if (lyx_code != TOC_CODE &&
2235 lyx_code != INCLUDE_CODE &&
2236 lyx_code != GRAPHICS_CODE &&
2237 lyx_code != ERT_CODE &&
2238 lyx_code != LISTINGS_CODE &&
2239 lyx_code != FLOAT_CODE &&
2240 lyx_code != TABULAR_CODE) {
2244 char_type c = d->text_[i];
2245 if (c != ' ' && c != '\t')
2253 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2256 for (pos_type i = 0; i < size(); ++i) {
2257 if (Inset const * inset = getInset(i)) {
2258 InsetCode lyx_code = inset->lyxCode();
2259 if (lyx_code == LABEL_CODE) {
2260 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2261 docstring const & id = il->getParam("name");
2262 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2270 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2274 for (i = 0; i < size(); ++i) {
2275 if (Inset const * inset = getInset(i)) {
2276 inset->docbook(os, runparams);
2278 char_type c = d->text_[i];
2281 os << sgml::escapeChar(c);
2288 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2292 for (i = 0; i < size(); ++i) {
2293 if (Inset const * inset = getInset(i)) {
2294 // FIXME XHTMLStream
2295 // inset->xhtml(xs, runparams);
2297 char_type c = d->text_[i];
2300 xs << html::escapeChar(c);
2307 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2310 pos_type size = text_.size();
2311 for (pos_type i = initial; i < size; ++i) {
2312 Font font = owner_->getFont(buf.params(), i, outerfont);
2313 if (text_[i] == META_INSET)
2315 if (i != initial && font != font_old)
2324 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2326 OutputParams const & runparams,
2327 Font const & outerfont,
2328 pos_type initial) const
2330 bool emph_flag = false;
2332 Layout const & style = *d->layout_;
2334 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2336 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2339 // parsing main loop
2340 for (pos_type i = initial; i < size(); ++i) {
2341 Font font = getFont(buf.params(), i, outerfont);
2343 // handle <emphasis> tag
2344 if (font_old.emph() != font.fontInfo().emph()) {
2345 if (font.fontInfo().emph() == FONT_ON) {
2348 } else if (i != initial) {
2349 os << "</emphasis>";
2354 if (Inset const * inset = getInset(i)) {
2355 inset->docbook(os, runparams);
2357 char_type c = d->text_[i];
2359 if (style.pass_thru)
2362 os << sgml::escapeChar(c);
2364 font_old = font.fontInfo();
2368 os << "</emphasis>";
2371 if (style.free_spacing)
2373 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2378 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2380 OutputParams const & runparams,
2381 Font const & outerfont,
2382 pos_type initial) const
2386 // FIXME We really need to manage the tag nesting here.
2387 // Probably in the same sort of way as in output_xhtml.
2388 bool emph_flag = false;
2389 bool bold_flag = false;
2390 std::string closing_tag;
2392 Layout const & style = *d->layout_;
2394 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2396 // parsing main loop
2397 for (pos_type i = initial; i < size(); ++i) {
2398 Font font = getFont(buf.params(), i, outerfont);
2401 if (font_old.emph() != font.fontInfo().emph()) {
2402 if (font.fontInfo().emph() == FONT_ON) {
2403 xs << StartTag("em");
2405 } else if (emph_flag && i != initial) {
2411 if (font_old.series() != font.fontInfo().series()) {
2412 if (font.fontInfo().series() == BOLD_SERIES) {
2413 xs << StartTag("strong");
2415 } else if (bold_flag && i != initial) {
2416 xs << EndTag("strong");
2420 // FIXME Other such tags?
2422 Inset const * inset = getInset(i);
2424 InsetLayout const & il = inset->getLayout();
2425 OutputParams np = runparams;
2426 if (!il.htmlisblock())
2427 np.html_in_par = true;
2428 // FIXME XHTMLStream
2429 // retval += inset->xhtml(xs, np);
2431 char_type c = d->text_[i];
2433 if (style.pass_thru)
2435 else if (c == '-') {
2438 if (j < size() && d->text_[j] == '-') {
2440 if (j < size() && d->text_[j] == '-') {
2441 str += from_ascii("—");
2444 str += from_ascii("–");
2454 font_old = font.fontInfo();
2462 bool Paragraph::isHfill(pos_type pos) const
2464 Inset const * inset = getInset(pos);
2465 return inset && (inset->lyxCode() == SPACE_CODE &&
2466 inset->isStretchableSpace());
2470 bool Paragraph::isNewline(pos_type pos) const
2472 Inset const * inset = getInset(pos);
2473 return inset && inset->lyxCode() == NEWLINE_CODE;
2477 bool Paragraph::isLineSeparator(pos_type pos) const
2479 char_type const c = d->text_[pos];
2480 if (isLineSeparatorChar(c))
2482 Inset const * inset = getInset(pos);
2483 return inset && inset->isLineSeparator();
2487 bool Paragraph::isWordSeparator(pos_type pos) const
2489 if (Inset const * inset = getInset(pos))
2490 return !inset->isLetter();
2491 char_type const c = d->text_[pos];
2492 // We want to pass the ' and escape chars to the spellchecker
2493 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2494 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2499 bool Paragraph::isChar(pos_type pos) const
2501 if (Inset const * inset = getInset(pos))
2502 return inset->isChar();
2503 char_type const c = d->text_[pos];
2504 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2508 bool Paragraph::isSpace(pos_type pos) const
2510 if (Inset const * inset = getInset(pos))
2511 return inset->isSpace();
2512 char_type const c = d->text_[pos];
2513 return lyx::isSpace(c);
2518 Paragraph::getParLanguage(BufferParams const & bparams) const
2521 return getFirstFontSettings(bparams).language();
2522 // FIXME: we should check the prev par as well (Lgb)
2523 return bparams.language;
2527 bool Paragraph::isRTL(BufferParams const & bparams) const
2529 return lyxrc.rtl_support
2530 && getParLanguage(bparams)->rightToLeft()
2531 && !inInset().getLayout().forceLTR();
2535 void Paragraph::changeLanguage(BufferParams const & bparams,
2536 Language const * from, Language const * to)
2538 // change language including dummy font change at the end
2539 for (pos_type i = 0; i <= size(); ++i) {
2540 Font font = getFontSettings(bparams, i);
2541 if (font.language() == from) {
2542 font.setLanguage(to);
2549 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2551 Language const * doc_language = bparams.language;
2552 FontList::const_iterator cit = d->fontlist_.begin();
2553 FontList::const_iterator end = d->fontlist_.end();
2555 for (; cit != end; ++cit)
2556 if (cit->font().language() != ignore_language &&
2557 cit->font().language() != latex_language &&
2558 cit->font().language() != doc_language)
2564 docstring Paragraph::asString(int options) const
2566 return asString(0, size(), options);
2570 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2572 odocstringstream os;
2575 && options & AS_STR_LABEL
2576 && !d->params_.labelString().empty())
2577 os << d->params_.labelString() << ' ';
2579 for (pos_type i = beg; i < end; ++i) {
2580 char_type const c = d->text_[i];
2581 if (isPrintable(c) || c == '\t'
2582 || (c == '\n' && (options & AS_STR_NEWLINES)))
2584 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2585 getInset(i)->tocString(os);
2586 if (getInset(i)->asInsetMath())
2595 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2597 odocstringstream os;
2600 && options & AS_STR_LABEL
2601 && !d->params_.labelString().empty())
2602 os << d->params_.labelString() << ' ';
2604 for (pos_type i = beg; i < end; ++i) {
2605 char_type const c = d->text_[i];
2606 if (isPrintable(c) || c == '\t'
2607 || (c == '\n' && (options & AS_STR_NEWLINES)))
2609 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2610 getInset(i)->plaintext(os, runparams);
2618 void Paragraph::setInsetOwner(Inset const * inset)
2620 d->inset_owner_ = inset;
2624 int Paragraph::id() const
2630 Layout const & Paragraph::layout() const
2636 void Paragraph::setLayout(Layout const & layout)
2638 d->layout_ = &layout;
2642 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2644 setLayout(tc.defaultLayout());
2648 void Paragraph::setPlainLayout(DocumentClass const & tc)
2650 setLayout(tc.plainLayout());
2654 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2656 if (usePlainLayout())
2657 setPlainLayout(tclass);
2659 setDefaultLayout(tclass);
2663 Inset const & Paragraph::inInset() const
2665 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2666 _("Memory problem"), _("Paragraph not properly initialized")));
2667 return *d->inset_owner_;
2671 ParagraphParameters & Paragraph::params()
2677 ParagraphParameters const & Paragraph::params() const
2683 bool Paragraph::isFreeSpacing() const
2685 if (d->layout_->free_spacing)
2687 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2691 bool Paragraph::allowEmpty() const
2693 if (d->layout_->keepempty)
2695 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2699 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2701 if (!Encodings::isArabicChar(c))
2704 char_type prev_char = ' ';
2705 char_type next_char = ' ';
2707 for (pos_type i = pos - 1; i >= 0; --i) {
2708 char_type const par_char = d->text_[i];
2709 if (!Encodings::isArabicComposeChar(par_char)) {
2710 prev_char = par_char;
2715 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2716 char_type const par_char = d->text_[i];
2717 if (!Encodings::isArabicComposeChar(par_char)) {
2718 next_char = par_char;
2723 if (Encodings::isArabicChar(next_char)) {
2724 if (Encodings::isArabicChar(prev_char) &&
2725 !Encodings::isArabicSpecialChar(prev_char))
2726 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2728 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2730 if (Encodings::isArabicChar(prev_char) &&
2731 !Encodings::isArabicSpecialChar(prev_char))
2732 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2734 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2739 int Paragraph::checkBiblio(Buffer const & buffer)
2742 // This is getting more and more a mess. ...We really should clean
2743 // up this bibitem issue for 1.6. See also bug 2743.
2745 // Add bibitem insets if necessary
2746 if (d->layout_->labeltype != LABEL_BIBLIO)
2749 bool hasbibitem = !d->insetlist_.empty()
2750 // Insist on it being in pos 0
2751 && d->text_[0] == META_INSET
2752 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2754 bool track_changes = buffer.params().trackChanges;
2759 // remove a bibitem in pos != 0
2760 // restore it later in pos 0 if necessary
2761 // (e.g. if a user inserts contents _before_ the item)
2762 // we're assuming there's only one of these, which there
2764 int erasedInsetPosition = -1;
2765 InsetList::iterator it = d->insetlist_.begin();
2766 InsetList::iterator end = d->insetlist_.end();
2767 for (; it != end; ++it)
2768 if (it->inset->lyxCode() == BIBITEM_CODE
2770 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2771 oldkey = olditem->getParam("key");
2772 oldlabel = olditem->getParam("label");
2773 erasedInsetPosition = it->pos;
2774 eraseChar(erasedInsetPosition, track_changes);
2778 // There was an InsetBibitem at the beginning, and we didn't
2779 // have to erase one.
2780 if (hasbibitem && erasedInsetPosition < 0)
2783 // There was an InsetBibitem at the beginning and we did have to
2784 // erase one. So we give its properties to the beginning inset.
2786 InsetBibitem * inset =
2787 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2788 if (!oldkey.empty())
2789 inset->setParam("key", oldkey);
2790 inset->setParam("label", oldlabel);
2791 return -erasedInsetPosition;
2794 // There was no inset at the beginning, so we need to create one with
2795 // the key and label of the one we erased.
2796 InsetBibitem * inset =
2797 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
2798 // restore values of previously deleted item in this par.
2799 if (!oldkey.empty())
2800 inset->setParam("key", oldkey);
2801 inset->setParam("label", oldlabel);
2802 insertInset(0, static_cast<Inset *>(inset),
2803 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2809 void Paragraph::checkAuthors(AuthorList const & authorList)
2811 d->changes_.checkAuthors(authorList);
2815 bool Paragraph::isChanged(pos_type pos) const
2817 return lookupChange(pos).changed();
2821 bool Paragraph::isInserted(pos_type pos) const
2823 return lookupChange(pos).inserted();
2827 bool Paragraph::isDeleted(pos_type pos) const
2829 return lookupChange(pos).deleted();
2833 InsetList const & Paragraph::insetList() const
2835 return d->insetlist_;
2839 void Paragraph::setBuffer(Buffer & b)
2841 d->insetlist_.setBuffer(b);
2845 Inset * Paragraph::releaseInset(pos_type pos)
2847 Inset * inset = d->insetlist_.release(pos);
2848 /// does not honour change tracking!
2849 eraseChar(pos, false);
2854 Inset * Paragraph::getInset(pos_type pos)
2856 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2857 ? d->insetlist_.get(pos) : 0;
2861 Inset const * Paragraph::getInset(pos_type pos) const
2863 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2864 ? d->insetlist_.get(pos) : 0;
2868 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2869 pos_type & right, TextCase action)
2871 // process sequences of modified characters; in change
2872 // tracking mode, this approach results in much better
2873 // usability than changing case on a char-by-char basis
2876 bool const trackChanges = bparams.trackChanges;
2878 bool capitalize = true;
2880 for (; pos < right; ++pos) {
2881 char_type oldChar = d->text_[pos];
2882 char_type newChar = oldChar;
2884 // ignore insets and don't play with deleted text!
2885 if (oldChar != META_INSET && !isDeleted(pos)) {
2887 case text_lowercase:
2888 newChar = lowercase(oldChar);
2890 case text_capitalization:
2892 newChar = uppercase(oldChar);
2896 case text_uppercase:
2897 newChar = uppercase(oldChar);
2902 if (isWordSeparator(pos) || isDeleted(pos)) {
2903 // permit capitalization again
2907 if (oldChar != newChar) {
2909 if (pos != right - 1)
2911 // step behind the changing area
2915 int erasePos = pos - changes.size();
2916 for (size_t i = 0; i < changes.size(); i++) {
2917 insertChar(pos, changes[i],
2918 getFontSettings(bparams,
2921 if (!eraseChar(erasePos, trackChanges)) {
2924 ++right; // expand selection
2932 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2933 pos_type pos, bool del) const
2935 int const strsize = str.length();
2937 pos_type const parsize = d->text_.size();
2938 for (i = 0; pos + i < parsize; ++i) {
2941 if (cs && str[i] != d->text_[pos + i])
2943 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2945 if (!del && isDeleted(pos + i))
2952 // if necessary, check whether string matches word
2954 if (pos > 0 && !isWordSeparator(pos - 1))
2956 if (pos + strsize < parsize
2957 && !isWordSeparator(pos + strsize))
2965 char_type Paragraph::getChar(pos_type pos) const
2967 return d->text_[pos];
2971 pos_type Paragraph::size() const
2973 return d->text_.size();
2977 bool Paragraph::empty() const
2979 return d->text_.empty();
2983 bool Paragraph::isInset(pos_type pos) const
2985 return d->text_[pos] == META_INSET;
2989 bool Paragraph::isSeparator(pos_type pos) const
2991 //FIXME: Are we sure this can be the only separator?
2992 return d->text_[pos] == ' ';
2996 void Paragraph::deregisterWords()
2998 Private::Words::const_iterator it;
2999 WordList & wl = theWordList();
3000 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3006 void Paragraph::locateWord(pos_type & from, pos_type & to,
3007 word_location const loc) const
3010 case WHOLE_WORD_STRICT:
3011 if (from == 0 || from == size()
3012 || isWordSeparator(from)
3013 || isWordSeparator(from - 1)) {
3017 // no break here, we go to the next
3020 // If we are already at the beginning of a word, do nothing
3021 if (!from || isWordSeparator(from - 1))
3023 // no break here, we go to the next
3026 // always move the cursor to the beginning of previous word
3027 while (from && !isWordSeparator(from - 1))
3031 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3034 // no need to move the 'from' cursor
3038 while (to < size() && !isWordSeparator(to))
3043 void Paragraph::collectWords()
3045 pos_type n = size();
3046 for (pos_type pos = 0; pos < n; ++pos) {
3047 if (isWordSeparator(pos))
3049 pos_type from = pos;
3050 locateWord(from, pos, WHOLE_WORD);
3051 if (pos - from >= 6) {
3052 docstring word = asString(from, pos, AS_STR_NONE);
3053 d->words_.insert(word);
3059 void Paragraph::registerWords()
3061 Private::Words::const_iterator it;
3062 WordList & wl = theWordList();
3063 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3068 void Paragraph::updateWords()
3076 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3077 docstring_list & suggestions, bool do_suggestion) const
3079 SpellChecker * speller = theSpellChecker();
3083 locateWord(from, to, WHOLE_WORD);
3084 if (from == to || from >= pos_type(d->text_.size()))
3087 docstring word = asString(from, to, AS_STR_INSETS);
3088 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3089 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3090 : lyxrc.spellchecker_alt_lang;
3091 wl = WordLangTuple(word, lang_code);
3092 SpellChecker::Result res = speller->check(wl);
3093 // Just ignore any error that the spellchecker reports.
3094 // FIXME: we should through out an exception and catch it in the GUI to
3095 // display the error.
3096 if (!speller->error().empty())
3099 bool const misspelled = res != SpellChecker::OK
3100 && res != SpellChecker::IGNORED_WORD;
3102 if (lyxrc.spellcheck_continuously)
3103 d->fontlist_.setMisspelled(from, to, misspelled);
3105 if (misspelled && do_suggestion)
3106 speller->suggest(wl, suggestions);
3108 suggestions.clear();
3114 bool Paragraph::isMisspelled(pos_type pos) const
3116 pos_type from = pos;
3119 docstring_list suggestions;
3120 return spellCheck(from, to, wl, suggestions, false);