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,
167 Layout const & layout) const;
169 /// Checks if the paragraph contains only text and no inset or font change.
170 bool onlyText(Buffer const & buf, Font const & outerfont,
171 pos_type initial) const;
173 /// match a string against a particular point in the paragraph
174 bool isTextAt(string const & str, pos_type pos) const;
177 InsetCode ownerCode() const
179 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
182 /// Which Paragraph owns us?
186 Inset const * inset_owner_;
194 static unsigned int paragraph_id;
196 ParagraphParameters params_;
198 /// for recording and looking up changes
202 InsetList insetlist_;
205 pos_type begin_of_body_;
207 typedef docstring TextContainer;
211 typedef std::set<docstring> Words;
215 Layout const * layout_;
219 // Initialization of the counter for the paragraph id's,
220 unsigned int Paragraph::Private::paragraph_id = 0;
224 struct special_phrase {
230 special_phrase const special_phrases[] = {
231 { "LyX", from_ascii("\\LyX{}"), false },
232 { "TeX", from_ascii("\\TeX{}"), true },
233 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
234 { "LaTeX", from_ascii("\\LaTeX{}"), true },
237 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
242 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
243 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
245 id_ = paragraph_id++;
250 Paragraph::Private::Private(Private const & p, Paragraph * owner)
251 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
252 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
253 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
256 id_ = paragraph_id++;
260 Paragraph::Private::Private(Private const & p, Paragraph * owner,
261 pos_type beg, pos_type end)
262 : owner_(owner), inset_owner_(p.inset_owner_),
263 params_(p.params_), changes_(p.changes_),
264 insetlist_(p.insetlist_, beg, end),
265 begin_of_body_(p.begin_of_body_), words_(p.words_),
268 id_ = paragraph_id++;
269 if (beg >= pos_type(p.text_.size()))
271 text_ = p.text_.substr(beg, end - beg);
273 FontList::const_iterator fcit = fontlist_.begin();
274 FontList::const_iterator fend = fontlist_.end();
275 for (; fcit != fend; ++fcit) {
276 if (fcit->pos() < beg)
278 if (fcit->pos() >= end) {
279 // Add last entry in the fontlist_.
280 fontlist_.set(text_.size() - 1, fcit->font());
283 // Add a new entry in the fontlist_.
284 fontlist_.set(fcit->pos() - beg, fcit->font());
289 void Paragraph::addChangesToToc(DocIterator const & cdit,
290 Buffer const & buf) const
292 d->changes_.addToToc(cdit, buf);
296 bool Paragraph::isDeleted(pos_type start, pos_type end) const
298 LASSERT(start >= 0 && start <= size(), /**/);
299 LASSERT(end > start && end <= size() + 1, /**/);
301 return d->changes_.isDeleted(start, end);
305 bool Paragraph::isChanged(pos_type start, pos_type end) const
307 LASSERT(start >= 0 && start <= size(), /**/);
308 LASSERT(end > start && end <= size() + 1, /**/);
310 return d->changes_.isChanged(start, end);
314 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
316 // keep the logic here in sync with the logic of eraseChars()
320 Change const change = d->changes_.lookup(size());
321 return change.inserted() && change.currentAuthor();
325 void Paragraph::setChange(Change const & change)
327 // beware of the imaginary end-of-par character!
328 d->changes_.set(change, 0, size() + 1);
331 * Propagate the change recursively - but not in case of DELETED!
333 * Imagine that your co-author makes changes in an existing inset. He
334 * sends your document to you and you come to the conclusion that the
335 * inset should go completely. If you erase it, LyX must not delete all
336 * text within the inset. Otherwise, the change tracked insertions of
337 * your co-author get lost and there is no way to restore them later.
339 * Conclusion: An inset's content should remain untouched if you delete it
342 if (!change.deleted()) {
343 for (pos_type pos = 0; pos < size(); ++pos) {
344 if (Inset * inset = getInset(pos))
345 inset->setChange(change);
351 void Paragraph::setChange(pos_type pos, Change const & change)
353 LASSERT(pos >= 0 && pos <= size(), /**/);
354 d->changes_.set(change, pos);
356 // see comment in setChange(Change const &) above
357 if (!change.deleted() && pos < size())
358 if (Inset * inset = getInset(pos))
359 inset->setChange(change);
363 Change const & Paragraph::lookupChange(pos_type pos) const
365 LASSERT(pos >= 0 && pos <= size(), /**/);
366 return d->changes_.lookup(pos);
370 void Paragraph::acceptChanges(pos_type start, pos_type end)
372 LASSERT(start >= 0 && start <= size(), /**/);
373 LASSERT(end > start && end <= size() + 1, /**/);
375 for (pos_type pos = start; pos < end; ++pos) {
376 switch (lookupChange(pos).type) {
377 case Change::UNCHANGED:
378 // accept changes in nested inset
379 if (Inset * inset = getInset(pos))
380 inset->acceptChanges();
383 case Change::INSERTED:
384 d->changes_.set(Change(Change::UNCHANGED), pos);
385 // also accept changes in nested inset
386 if (Inset * inset = getInset(pos))
387 inset->acceptChanges();
390 case Change::DELETED:
391 // Suppress access to non-existent
392 // "end-of-paragraph char"
394 eraseChar(pos, false);
405 void Paragraph::rejectChanges(pos_type start, pos_type end)
407 LASSERT(start >= 0 && start <= size(), /**/);
408 LASSERT(end > start && end <= size() + 1, /**/);
410 for (pos_type pos = start; pos < end; ++pos) {
411 switch (lookupChange(pos).type) {
412 case Change::UNCHANGED:
413 // reject changes in nested inset
414 if (Inset * inset = getInset(pos))
415 inset->rejectChanges();
418 case Change::INSERTED:
419 // Suppress access to non-existent
420 // "end-of-paragraph char"
422 eraseChar(pos, false);
428 case Change::DELETED:
429 d->changes_.set(Change(Change::UNCHANGED), pos);
431 // Do NOT reject changes within a deleted inset!
432 // There may be insertions of a co-author inside of it!
440 void Paragraph::Private::insertChar(pos_type pos, char_type c,
441 Change const & change)
443 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
446 changes_.insert(change, pos);
448 // This is actually very common when parsing buffers (and
449 // maybe inserting ascii text)
450 if (pos == pos_type(text_.size())) {
451 // when appending characters, no need to update tables
456 text_.insert(text_.begin() + pos, c);
458 // Update the font table.
459 fontlist_.increasePosAfterPos(pos);
462 insetlist_.increasePosAfterPos(pos);
466 bool Paragraph::insertInset(pos_type pos, Inset * inset,
467 Change const & change)
469 LASSERT(inset, /**/);
470 LASSERT(pos >= 0 && pos <= size(), /**/);
472 // Paragraph::insertInset() can be used in cut/copy/paste operation where
473 // d->inset_owner_ is not set yet.
474 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
477 d->insertChar(pos, META_INSET, change);
478 LASSERT(d->text_[pos] == META_INSET, /**/);
480 // Add a new entry in the insetlist_.
481 d->insetlist_.insert(inset, pos);
486 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
488 LASSERT(pos >= 0 && pos <= size(), return false);
490 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
493 Change change = d->changes_.lookup(pos);
495 // set the character to DELETED if
496 // a) it was previously unchanged or
497 // b) it was inserted by a co-author
499 if (!change.changed() ||
500 (change.inserted() && !change.currentAuthor())) {
501 setChange(pos, Change(Change::DELETED));
505 if (change.deleted())
509 // Don't physically access the imaginary end-of-paragraph character.
510 // eraseChar() can only mark it as DELETED. A physical deletion of
511 // end-of-par must be handled externally.
517 d->changes_.erase(pos);
519 // if it is an inset, delete the inset entry
520 if (d->text_[pos] == META_INSET)
521 d->insetlist_.erase(pos);
523 d->text_.erase(d->text_.begin() + pos);
525 // Update the fontlist_
526 d->fontlist_.erase(pos);
528 // Update the insetlist_
529 d->insetlist_.decreasePosAfterPos(pos);
535 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
537 LASSERT(start >= 0 && start <= size(), /**/);
538 LASSERT(end >= start && end <= size() + 1, /**/);
541 for (pos_type count = end - start; count; --count) {
542 if (!eraseChar(i, trackChanges))
549 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
550 char_type next, OutputParams const & runparams)
552 // Writing next here may circumvent a possible font change between
553 // c and next. Since next is only output if it forms a surrogate pair
554 // with c we can ignore this:
555 // A font change inside a surrogate pair does not make sense and is
556 // hopefully impossible to input.
557 // FIXME: change tracking
558 // Is this correct WRT change tracking?
559 Encoding const & encoding = *(runparams.encoding);
560 docstring const latex1 = encoding.latexChar(next);
561 docstring const latex2 = encoding.latexChar(c);
562 if (docstring(1, next) == latex1) {
563 // the encoding supports the combination
564 os << latex2 << latex1;
565 return latex1.length() + latex2.length();
566 } else if (runparams.local_font &&
567 runparams.local_font->language()->lang() == "polutonikogreek") {
568 // polutonikogreek only works without the brackets
569 os << latex1 << latex2;
570 return latex1.length() + latex2.length();
572 os << latex1 << '{' << latex2 << '}';
573 return latex1.length() + latex2.length() + 2;
577 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
578 odocstream & os, TexRow & texrow,
580 unsigned int & column,
582 Layout const & style)
584 if (style.pass_thru || runparams.verbatim)
587 if (i + 1 < int(text_.size())) {
588 char_type next = text_[i + 1];
589 if (Encodings::isCombiningChar(next)) {
590 // This space has an accent, so we must always output it.
591 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
596 if (runparams.linelen > 0
597 && column > runparams.linelen
599 && text_[i - 1] != ' '
600 && (i + 1 < int(text_.size()))
601 // same in FreeSpacing mode
602 && !owner_->isFreeSpacing()
603 // In typewriter mode, we want to avoid
604 // ! . ? : at the end of a line
605 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
606 && (text_[i - 1] == '.'
607 || text_[i - 1] == '?'
608 || text_[i - 1] == ':'
609 || text_[i - 1] == '!'))) {
612 texrow.start(owner_->id(), i + 1);
614 } else if (style.free_spacing) {
623 int Paragraph::Private::writeScriptChars(odocstream & os,
624 docstring const & ltx,
625 Change const & runningChange,
626 Encoding const & encoding,
629 // FIXME: modifying i here is not very nice...
631 // We only arrive here when a proper language for character text_[i] has
632 // not been specified (i.e., it could not be translated in the current
633 // latex encoding) or its latex translation has been forced, and it
634 // belongs to a known script.
635 // Parameter ltx contains the latex translation of text_[i] as specified
636 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
637 // The latex macro name "textXXX" specifies the script to which text_[i]
638 // belongs and we use it in order to check whether characters from the
639 // same script immediately follow, such that we can collect them in a
640 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
641 // for the first char but only "<spec>" for all subsequent chars.
642 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
643 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
644 string script = to_ascii(ltx.substr(1, brace1 - 1));
647 bool closing_brace = true;
648 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
649 // Correct encoding is being used, so we can avoid \textgreek.
652 closing_brace = false;
654 os << ltx.substr(pos, length);
655 int size = text_.size();
656 while (i + 1 < size) {
657 char_type const next = text_[i + 1];
658 // Stop here if next character belongs to another script
659 // or there is a change in change tracking status.
660 if (!Encodings::isKnownScriptChar(next, script) ||
661 runningChange != owner_->lookupChange(i + 1))
665 FontList::const_iterator cit = fontlist_.begin();
666 FontList::const_iterator end = fontlist_.end();
667 for (; cit != end; ++cit) {
668 if (cit->pos() >= i && !found) {
669 prev_font = cit->font();
672 if (cit->pos() >= i + 1)
675 // Stop here if there is a font attribute or encoding change.
676 if (found && cit != end && prev_font != cit->font())
678 docstring const latex = encoding.latexChar(next);
679 docstring::size_type const b1 =
680 latex.find_first_of(from_ascii("{"));
681 docstring::size_type const b2 =
682 latex.find_last_of(from_ascii("}"));
683 int const len = b2 - b1 - 1;
684 os << latex.substr(b1 + 1, len);
696 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
698 pos_type const len = str.length();
700 // is the paragraph large enough?
701 if (pos + len > int(text_.size()))
704 // does the wanted text start at point?
705 for (string::size_type i = 0; i < str.length(); ++i) {
706 // Caution: direct comparison of characters works only
707 // because str is pure ASCII.
708 if (str[i] != text_[pos + i])
712 return fontlist_.hasChangeInRange(pos, len);
716 void Paragraph::Private::latexInset(
717 BufferParams const & bparams,
720 OutputParams & runparams,
723 Font const & outerfont,
725 Change & running_change,
726 Layout const & style,
728 unsigned int & column)
730 Inset * inset = owner_->getInset(i);
731 LASSERT(inset, /**/);
733 if (style.pass_thru) {
734 inset->plaintext(os, runparams);
738 // FIXME: move this to InsetNewline::latex
739 if (inset->lyxCode() == NEWLINE_CODE) {
740 // newlines are handled differently here than
741 // the default in simpleTeXSpecialChars().
742 if (!style.newline_allowed) {
746 column += running_font.latexWriteEndChanges(
747 os, bparams, runparams,
752 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
755 basefont = owner_->getLayoutFont(bparams, outerfont);
756 running_font = basefont;
758 if (runparams.moving_arg)
763 texrow.start(owner_->id(), i + 1);
767 if (owner_->isDeleted(i)) {
768 if( ++runparams.inDeletedInset == 1)
769 runparams.changeOfDeletedInset = owner_->lookupChange(i);
772 if (inset->canTrackChanges()) {
773 column += Changes::latexMarkChange(os, bparams, running_change,
774 Change(Change::UNCHANGED), runparams);
775 running_change = Change(Change::UNCHANGED);
779 odocstream::pos_type const len = os.tellp();
781 if (inset->forceLTR()
782 && running_font.isRightToLeft()
783 // ERT is an exception, it should be output with no
784 // decorations at all
785 && inset->lyxCode() != ERT_CODE) {
786 if (running_font.language()->lang() == "farsi")
793 // FIXME: Bug: we can have an empty font change here!
794 // if there has just been a font change, we are going to close it
795 // right now, which means stupid latex code like \textsf{}. AFAIK,
796 // this does not harm dvi output. A minor bug, thus (JMarc)
798 // Some insets cannot be inside a font change command.
799 // However, even such insets *can* be placed in \L or \R
800 // or their equivalents (for RTL language switches), so we don't
801 // close the language in those cases.
802 // ArabTeX, though, cannot handle this special behavior, it seems.
803 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
804 || running_font.language()->lang() == "arabic_arabtex";
805 if (open_font && inset->noFontChange()) {
806 bool closeLanguage = arabtex
807 || basefont.isRightToLeft() == running_font.isRightToLeft();
808 unsigned int count = running_font.latexWriteEndChanges(os,
809 bparams, runparams, basefont, basefont, closeLanguage);
811 // if any font properties were closed, update the running_font,
812 // making sure, however, to leave the language as it was
814 // FIXME: probably a better way to keep track of the old
815 // language, than copying the entire font?
816 Font const copy_font(running_font);
817 basefont = owner_->getLayoutFont(bparams, outerfont);
818 running_font = basefont;
820 running_font.setLanguage(copy_font.language());
821 // leave font open if language is still open
822 open_font = (running_font.language() == basefont.language());
824 runparams.local_font = &basefont;
831 tmp = inset->latex(os, runparams);
832 } catch (EncodingException & e) {
833 // add location information and throw again.
840 if (running_font.language()->lang() == "farsi")
847 for (int j = 0; j < tmp; ++j)
850 texrow.start(owner_->id(), i + 1);
853 column += os.tellp() - len;
856 if (owner_->isDeleted(i))
857 --runparams.inDeletedInset;
861 void Paragraph::Private::latexSpecialChar(
863 OutputParams const & runparams,
864 Font const & running_font,
865 Change const & running_change,
866 Layout const & style,
868 unsigned int & column)
870 char_type const c = text_[i];
872 if (style.pass_thru) {
874 // FIXME UNICODE: This can fail if c cannot
875 // be encoded in the current encoding.
880 if (runparams.verbatim) {
881 // FIXME UNICODE: This can fail if c cannot
882 // be encoded in the current encoding.
887 // If T1 font encoding is used, use the special
888 // characters it provides.
889 // NOTE: some languages reset the font encoding
891 if (!running_font.language()->internalFontEncoding()
892 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
895 // \tt font needs special treatment
896 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
897 && latexSpecialTypewriter(c, os, i, column))
900 // Otherwise, we use what LaTeX provides us.
903 os << "\\textbackslash{}";
907 os << "\\textless{}";
911 os << "\\textgreater{}";
922 os << "\\char`\\\"{}";
927 case '%': case '#': case '{':
935 os << "\\textasciitilde{}";
940 os << "\\textasciicircum{}";
947 // avoid being mistaken for optional arguments
955 // Blanks are printed before font switching.
956 // Sure? I am not! (try nice-latex)
957 // I am sure it's correct. LyX might be smarter
958 // in the future, but for now, nothing wrong is
964 if (latexSpecialPhrase(os, i, column, runparams))
970 Encoding const & encoding = *(runparams.encoding);
971 if (i + 1 < int(text_.size())) {
972 char_type next = text_[i + 1];
973 if (Encodings::isCombiningChar(next)) {
974 column += latexSurrogatePair(os, c, next, runparams) - 1;
980 docstring const latex = encoding.latexChar(c);
981 if (Encodings::isKnownScriptChar(c, script)
982 && prefixIs(latex, from_ascii("\\" + script)))
983 column += writeScriptChars(os, latex,
984 running_change, encoding, i) - 1;
985 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
986 // Prevent eating of a following
987 // space or command corruption by
988 // following characters
989 column += latex.length() + 1;
992 column += latex.length() - 1;
1000 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1001 pos_type i, unsigned int & column)
1007 // In T1 encoding, these characters exist
1008 // but we should avoid ligatures
1009 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1011 os << "\\textcompwordmark{}";
1018 // soul.sty breaks with \char`\"
1019 os << "\\textquotedbl{}";
1028 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1029 pos_type i, unsigned int & column)
1033 // within \ttfamily, "--" is merged to "-" (no endash)
1034 // so we avoid this rather irritating ligature
1035 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1042 // everything else has to be checked separately
1043 // (depending on the encoding)
1050 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1051 unsigned int & column, OutputParams const & runparams)
1053 // FIXME: if we have "LaTeX" with a font
1054 // change in the middle (before the 'T', then
1055 // the "TeX" part is still special cased.
1056 // Really we should only operate this on
1057 // "words" for some definition of word
1059 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1060 if (!isTextAt(special_phrases[pnr].phrase, i))
1062 if (runparams.moving_arg)
1064 os << special_phrases[pnr].macro;
1065 i += special_phrases[pnr].phrase.length() - 1;
1066 column += special_phrases[pnr].macro.length() - 1;
1073 void Paragraph::Private::validate(LaTeXFeatures & features,
1074 Layout const & layout) const
1076 // check the params.
1077 if (!params_.spacing().isDefault())
1078 features.require("setspace");
1081 features.useLayout(layout.name());
1084 fontlist_.validate(features);
1086 // then the indentation
1087 if (!params_.leftIndent().zero())
1088 features.require("ParagraphLeftIndent");
1091 InsetList::const_iterator icit = insetlist_.begin();
1092 InsetList::const_iterator iend = insetlist_.end();
1093 for (; icit != iend; ++icit) {
1095 icit->inset->validate(features);
1096 if (layout.needprotect &&
1097 icit->inset->lyxCode() == FOOT_CODE)
1098 features.require("NeedLyXFootnoteCode");
1102 // then the contents
1103 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1104 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1105 if (!special_phrases[pnr].builtin
1106 && isTextAt(special_phrases[pnr].phrase, i)) {
1107 features.require(special_phrases[pnr].phrase);
1111 Encodings::validate(text_[i], features);
1115 /////////////////////////////////////////////////////////////////////
1119 /////////////////////////////////////////////////////////////////////
1122 Layout const emptyParagraphLayout;
1125 Paragraph::Paragraph()
1126 : d(new Paragraph::Private(this, emptyParagraphLayout))
1133 Paragraph::Paragraph(Paragraph const & par)
1134 : itemdepth(par.itemdepth),
1135 d(new Paragraph::Private(*par.d, this))
1141 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1142 : itemdepth(par.itemdepth),
1143 d(new Paragraph::Private(*par.d, this, beg, end))
1149 Paragraph & Paragraph::operator=(Paragraph const & par)
1151 // needed as we will destroy the private part before copying it
1153 itemdepth = par.itemdepth;
1157 d = new Private(*par.d, this);
1164 Paragraph::~Paragraph()
1171 void Paragraph::write(ostream & os, BufferParams const & bparams,
1172 depth_type & dth) const
1174 // The beginning or end of a deeper (i.e. nested) area?
1175 if (dth != d->params_.depth()) {
1176 if (d->params_.depth() > dth) {
1177 while (d->params_.depth() > dth) {
1178 os << "\n\\begin_deeper";
1182 while (d->params_.depth() < dth) {
1183 os << "\n\\end_deeper";
1189 // First write the layout
1190 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1192 d->params_.write(os);
1194 Font font1(inherit_font, bparams.language);
1196 Change running_change = Change(Change::UNCHANGED);
1199 for (pos_type i = 0; i <= size(); ++i) {
1201 Change const change = lookupChange(i);
1202 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1203 running_change = change;
1208 // Write font changes (ignore spelling markers)
1209 Font font2 = getFontSettings(bparams, i);
1210 font2.setMisspelled(false);
1211 if (font2 != font1) {
1212 font2.lyxWriteChanges(font1, os);
1217 char_type const c = d->text_[i];
1220 if (Inset const * inset = getInset(i)) {
1221 if (inset->directWrite()) {
1222 // international char, let it write
1223 // code directly so it's shorter in
1229 os << "\\begin_inset ";
1231 os << "\n\\end_inset\n\n";
1237 os << "\n\\backslash\n";
1241 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1248 if ((column > 70 && c == ' ')
1253 // this check is to amend a bug. LyX sometimes
1254 // inserts '\0' this could cause problems.
1256 os << to_utf8(docstring(1, c));
1258 LYXERR0("NUL char in structure.");
1264 os << "\n\\end_layout\n";
1268 void Paragraph::validate(LaTeXFeatures & features) const
1270 d->validate(features, *d->layout_);
1274 void Paragraph::insert(pos_type start, docstring const & str,
1275 Font const & font, Change const & change)
1277 for (size_t i = 0, n = str.size(); i != n ; ++i)
1278 insertChar(start + i, str[i], font, change);
1282 void Paragraph::appendChar(char_type c, Font const & font,
1283 Change const & change)
1286 d->changes_.insert(change, d->text_.size());
1287 // when appending characters, no need to update tables
1288 d->text_.push_back(c);
1289 setFont(d->text_.size() - 1, font);
1293 void Paragraph::appendString(docstring const & s, Font const & font,
1294 Change const & change)
1296 pos_type end = s.size();
1297 size_t oldsize = d->text_.size();
1298 size_t newsize = oldsize + end;
1299 size_t capacity = d->text_.capacity();
1300 if (newsize >= capacity)
1301 d->text_.reserve(max(capacity + 100, newsize));
1303 // when appending characters, no need to update tables
1306 // FIXME: Optimize this!
1307 for (size_t i = oldsize; i != newsize; ++i) {
1309 d->changes_.insert(change, i);
1311 d->fontlist_.set(oldsize, font);
1312 d->fontlist_.set(newsize - 1, font);
1316 void Paragraph::insertChar(pos_type pos, char_type c,
1319 d->insertChar(pos, c, Change(trackChanges ?
1320 Change::INSERTED : Change::UNCHANGED));
1324 void Paragraph::insertChar(pos_type pos, char_type c,
1325 Font const & font, bool trackChanges)
1327 d->insertChar(pos, c, Change(trackChanges ?
1328 Change::INSERTED : Change::UNCHANGED));
1333 void Paragraph::insertChar(pos_type pos, char_type c,
1334 Font const & font, Change const & change)
1336 d->insertChar(pos, c, change);
1341 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1342 Font const & font, Change const & change)
1344 bool const success = insertInset(pos, inset, change);
1345 // Set the font/language of the inset...
1351 void Paragraph::resetFonts(Font const & font)
1353 d->fontlist_.clear();
1354 d->fontlist_.set(0, font);
1355 d->fontlist_.set(d->text_.size() - 1, font);
1358 // Gets uninstantiated font setting at position.
1359 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1363 LYXERR0("pos: " << pos << " size: " << size());
1364 LASSERT(pos <= size(), /**/);
1367 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1368 if (cit != d->fontlist_.end())
1371 if (pos == size() && !empty())
1372 return getFontSettings(bparams, pos - 1);
1374 // Optimisation: avoid a full font instantiation if there is no
1375 // language change from previous call.
1376 static Font previous_font;
1377 static Language const * previous_lang = 0;
1378 Language const * lang = getParLanguage(bparams);
1379 if (lang != previous_lang) {
1380 previous_lang = lang;
1381 previous_font = Font(inherit_font, lang);
1383 return previous_font;
1387 FontSpan Paragraph::fontSpan(pos_type pos) const
1389 LASSERT(pos <= size(), /**/);
1392 FontList::const_iterator cit = d->fontlist_.begin();
1393 FontList::const_iterator end = d->fontlist_.end();
1394 for (; cit != end; ++cit) {
1395 if (cit->pos() >= pos) {
1396 if (pos >= beginOfBody())
1397 return FontSpan(max(start, beginOfBody()),
1400 return FontSpan(start,
1401 min(beginOfBody() - 1,
1404 start = cit->pos() + 1;
1407 // This should not happen, but if so, we take no chances.
1408 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1409 return FontSpan(pos, pos);
1413 // Gets uninstantiated font setting at position 0
1414 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1416 if (!empty() && !d->fontlist_.empty())
1417 return d->fontlist_.begin()->font();
1419 // Optimisation: avoid a full font instantiation if there is no
1420 // language change from previous call.
1421 static Font previous_font;
1422 static Language const * previous_lang = 0;
1423 if (bparams.language != previous_lang) {
1424 previous_lang = bparams.language;
1425 previous_font = Font(inherit_font, bparams.language);
1428 return previous_font;
1432 // Gets the fully instantiated font at a given position in a paragraph
1433 // This is basically the same function as Text::GetFont() in text2.cpp.
1434 // The difference is that this one is used for generating the LaTeX file,
1435 // and thus cosmetic "improvements" are disallowed: This has to deliver
1436 // the true picture of the buffer. (Asger)
1437 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1438 Font const & outerfont) const
1440 LASSERT(pos >= 0, /**/);
1442 Font font = getFontSettings(bparams, pos);
1444 pos_type const body_pos = beginOfBody();
1445 FontInfo & fi = font.fontInfo();
1447 fi.realize(d->layout_->labelfont);
1449 fi.realize(d->layout_->font);
1451 fi.realize(outerfont.fontInfo());
1452 fi.realize(bparams.getFont().fontInfo());
1458 Font const Paragraph::getLabelFont
1459 (BufferParams const & bparams, Font const & outerfont) const
1461 FontInfo tmpfont = d->layout_->labelfont;
1462 tmpfont.realize(outerfont.fontInfo());
1463 tmpfont.realize(bparams.getFont().fontInfo());
1464 return Font(tmpfont, getParLanguage(bparams));
1468 Font const Paragraph::getLayoutFont
1469 (BufferParams const & bparams, Font const & outerfont) const
1471 FontInfo tmpfont = d->layout_->font;
1472 tmpfont.realize(outerfont.fontInfo());
1473 tmpfont.realize(bparams.getFont().fontInfo());
1474 return Font(tmpfont, getParLanguage(bparams));
1478 /// Returns the height of the highest font in range
1479 FontSize Paragraph::highestFontInRange
1480 (pos_type startpos, pos_type endpos, FontSize def_size) const
1482 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1486 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1488 char_type c = d->text_[pos];
1489 if (!lyxrc.rtl_support)
1519 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1525 void Paragraph::setFont(pos_type pos, Font const & font)
1527 LASSERT(pos <= size(), /**/);
1529 // First, reduce font against layout/label font
1530 // Update: The setCharFont() routine in text2.cpp already
1531 // reduces font, so we don't need to do that here. (Asger)
1533 d->fontlist_.set(pos, font);
1537 void Paragraph::makeSameLayout(Paragraph const & par)
1539 d->layout_ = par.d->layout_;
1540 d->params_ = par.d->params_;
1544 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1546 if (isFreeSpacing())
1552 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1553 if (eraseChar(pos, trackChanges))
1559 return count > 0 || pos > 0;
1563 bool Paragraph::hasSameLayout(Paragraph const & par) const
1565 return par.d->layout_ == d->layout_
1566 && d->params_.sameLayout(par.d->params_);
1570 depth_type Paragraph::getDepth() const
1572 return d->params_.depth();
1576 depth_type Paragraph::getMaxDepthAfter() const
1578 if (d->layout_->isEnvironment())
1579 return d->params_.depth() + 1;
1581 return d->params_.depth();
1585 char Paragraph::getAlign() const
1587 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1588 return d->layout_->align;
1590 return d->params_.align();
1594 docstring const & Paragraph::labelString() const
1596 return d->params_.labelString();
1600 // the next two functions are for the manual labels
1601 docstring const Paragraph::getLabelWidthString() const
1603 if (d->layout_->margintype == MARGIN_MANUAL
1604 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1605 return d->params_.labelWidthString();
1607 return _("Senseless with this layout!");
1611 void Paragraph::setLabelWidthString(docstring const & s)
1613 d->params_.labelWidthString(s);
1617 docstring Paragraph::expandLabel(Layout const & layout,
1618 BufferParams const & bparams, bool process_appendix) const
1620 DocumentClass const & tclass = bparams.documentClass();
1621 string const & lang = getParLanguage(bparams)->code();
1622 bool const in_appendix = process_appendix && d->params_.appendix();
1623 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1625 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1626 && !layout.counter.empty())
1627 return tclass.counters().theCounter(layout.counter, lang);
1629 // handle 'inherited level parts' in 'fmt',
1630 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1631 size_t const i = fmt.find('@', 0);
1632 if (i != docstring::npos) {
1633 size_t const j = fmt.find('@', i + 1);
1634 if (j != docstring::npos) {
1635 docstring parent(fmt, i + 1, j - i - 1);
1636 docstring label = from_ascii("??");
1637 if (tclass.hasLayout(parent))
1638 docstring label = expandLabel(tclass[parent], bparams,
1640 fmt = docstring(fmt, 0, i) + label
1641 + docstring(fmt, j + 1, docstring::npos);
1645 return tclass.counters().counterLabel(fmt, lang);
1649 void Paragraph::applyLayout(Layout const & new_layout)
1651 d->layout_ = &new_layout;
1652 LyXAlignment const oldAlign = d->params_.align();
1654 if (!(oldAlign & d->layout_->alignpossible)) {
1655 frontend::Alert::warning(_("Alignment not permitted"),
1656 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1657 d->params_.align(LYX_ALIGN_LAYOUT);
1662 pos_type Paragraph::beginOfBody() const
1664 return d->begin_of_body_;
1668 void Paragraph::setBeginOfBody()
1670 if (d->layout_->labeltype != LABEL_MANUAL) {
1671 d->begin_of_body_ = 0;
1675 // Unroll the first two cycles of the loop
1676 // and remember the previous character to
1677 // remove unnecessary getChar() calls
1679 pos_type end = size();
1680 if (i < end && !isNewline(i)) {
1682 char_type previous_char = 0;
1685 previous_char = d->text_[i];
1686 if (!isNewline(i)) {
1688 while (i < end && previous_char != ' ') {
1693 previous_char = temp;
1699 d->begin_of_body_ = i;
1703 bool Paragraph::allowParagraphCustomization() const
1705 return inInset().allowParagraphCustomization();
1709 bool Paragraph::usePlainLayout() const
1711 return inInset().usePlainLayout();
1717 // paragraphs inside floats need different alignment tags to avoid
1720 bool noTrivlistCentering(InsetCode code)
1722 return code == FLOAT_CODE
1723 || code == WRAP_CODE
1724 || code == CELL_CODE;
1728 string correction(string const & orig)
1730 if (orig == "flushleft")
1731 return "raggedright";
1732 if (orig == "flushright")
1733 return "raggedleft";
1734 if (orig == "center")
1740 string const corrected_env(string const & suffix, string const & env,
1741 InsetCode code, bool const lastpar)
1743 string output = suffix + "{";
1744 if (noTrivlistCentering(code)) {
1746 // the last paragraph in non-trivlist-aligned
1747 // context is special (to avoid unwanted whitespace)
1748 if (suffix == "\\begin")
1749 return "\\" + correction(env) + "{}";
1752 output += correction(env);
1756 if (suffix == "\\begin")
1762 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1764 if (!contains(str, "\n"))
1765 column += str.size();
1769 column = rsplit(str, tmp, '\n').size();
1776 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1777 odocstream & os, TexRow & texrow,
1778 OutputParams const & runparams) const
1782 if (params_.noindent()) {
1783 os << "\\noindent ";
1787 LyXAlignment const curAlign = params_.align();
1789 if (curAlign == layout_->align)
1793 case LYX_ALIGN_NONE:
1794 case LYX_ALIGN_BLOCK:
1795 case LYX_ALIGN_LAYOUT:
1796 case LYX_ALIGN_SPECIAL:
1798 case LYX_ALIGN_LEFT:
1799 case LYX_ALIGN_RIGHT:
1800 case LYX_ALIGN_CENTER:
1801 if (runparams.moving_arg) {
1808 string const begin_tag = "\\begin";
1809 InsetCode code = ownerCode();
1810 bool const lastpar = runparams.isLastPar;
1813 case LYX_ALIGN_NONE:
1814 case LYX_ALIGN_BLOCK:
1815 case LYX_ALIGN_LAYOUT:
1816 case LYX_ALIGN_SPECIAL:
1818 case LYX_ALIGN_LEFT: {
1820 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1821 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1823 output = corrected_env(begin_tag, "flushright", code, lastpar);
1824 os << from_ascii(output);
1825 adjust_row_column(output, texrow, column);
1827 } case LYX_ALIGN_RIGHT: {
1829 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1830 output = corrected_env(begin_tag, "flushright", code, lastpar);
1832 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1833 os << from_ascii(output);
1834 adjust_row_column(output, texrow, column);
1836 } case LYX_ALIGN_CENTER: {
1838 output = corrected_env(begin_tag, "center", code, lastpar);
1839 os << from_ascii(output);
1840 adjust_row_column(output, texrow, column);
1849 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1850 odocstream & os, TexRow & texrow,
1851 OutputParams const & runparams) const
1855 LyXAlignment const curAlign = params_.align();
1857 if (curAlign == layout_->align)
1861 case LYX_ALIGN_NONE:
1862 case LYX_ALIGN_BLOCK:
1863 case LYX_ALIGN_LAYOUT:
1864 case LYX_ALIGN_SPECIAL:
1866 case LYX_ALIGN_LEFT:
1867 case LYX_ALIGN_RIGHT:
1868 case LYX_ALIGN_CENTER:
1869 if (runparams.moving_arg) {
1876 string const end_tag = "\n\\par\\end";
1877 InsetCode code = ownerCode();
1878 bool const lastpar = runparams.isLastPar;
1881 case LYX_ALIGN_NONE:
1882 case LYX_ALIGN_BLOCK:
1883 case LYX_ALIGN_LAYOUT:
1884 case LYX_ALIGN_SPECIAL:
1886 case LYX_ALIGN_LEFT: {
1888 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1889 output = corrected_env(end_tag, "flushleft", code, lastpar);
1891 output = corrected_env(end_tag, "flushright", code, lastpar);
1892 os << from_ascii(output);
1893 adjust_row_column(output, texrow, column);
1895 } case LYX_ALIGN_RIGHT: {
1897 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1898 output = corrected_env(end_tag, "flushright", code, lastpar);
1900 output = corrected_env(end_tag, "flushleft", code, lastpar);
1901 os << from_ascii(output);
1902 adjust_row_column(output, texrow, column);
1904 } case LYX_ALIGN_CENTER: {
1906 output = corrected_env(end_tag, "center", code, lastpar);
1907 os << from_ascii(output);
1908 adjust_row_column(output, texrow, column);
1917 // This one spits out the text of the paragraph
1918 bool Paragraph::latex(BufferParams const & bparams,
1919 Font const & outerfont,
1920 odocstream & os, TexRow & texrow,
1921 OutputParams const & runparams,
1922 int start_pos, int end_pos) const
1924 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1926 bool return_value = false;
1928 bool const allowcust = allowParagraphCustomization();
1930 // FIXME This check should not be needed. Perhaps issue an
1931 // error if it triggers.
1932 Layout const & style = inInset().forcePlainLayout() ?
1933 bparams.documentClass().plainLayout() : *d->layout_;
1935 // Current base font for all inherited font changes, without any
1936 // change caused by an individual character, except for the language:
1937 // It is set to the language of the first character.
1938 // As long as we are in the label, this font is the base font of the
1939 // label. Before the first body character it is set to the base font
1943 // Maybe we have to create a optional argument.
1944 pos_type body_pos = beginOfBody();
1945 unsigned int column = 0;
1950 basefont = getLabelFont(bparams, outerfont);
1952 basefont = getLayoutFont(bparams, outerfont);
1955 // Which font is currently active?
1956 Font running_font(basefont);
1957 // Do we have an open font change?
1958 bool open_font = false;
1960 Change runningChange = Change(Change::UNCHANGED);
1962 Encoding const * const prev_encoding = runparams.encoding;
1964 texrow.start(id(), 0);
1966 // if the paragraph is empty, the loop will not be entered at all
1968 if (style.isCommand()) {
1973 column += d->startTeXParParams(bparams, os, texrow,
1977 for (pos_type i = 0; i < size(); ++i) {
1978 // First char in paragraph or after label?
1979 if (i == body_pos) {
1982 column += running_font.latexWriteEndChanges(
1983 os, bparams, runparams,
1984 basefont, basefont);
1987 basefont = getLayoutFont(bparams, outerfont);
1988 running_font = basefont;
1990 column += Changes::latexMarkChange(os, bparams,
1991 runningChange, Change(Change::UNCHANGED),
1993 runningChange = Change(Change::UNCHANGED);
1998 if (style.isCommand()) {
2004 column += d->startTeXParParams(bparams, os,
2009 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2012 if (bparams.outputChanges && runningChange != change) {
2014 column += running_font.latexWriteEndChanges(
2015 os, bparams, runparams, basefont, basefont);
2018 basefont = getLayoutFont(bparams, outerfont);
2019 running_font = basefont;
2021 column += Changes::latexMarkChange(os, bparams, runningChange,
2023 runningChange = change;
2026 // do not output text which is marked deleted
2027 // if change tracking output is disabled
2028 if (!bparams.outputChanges && change.deleted()) {
2034 // Fully instantiated font
2035 Font const font = getFont(bparams, i, outerfont);
2037 Font const last_font = running_font;
2039 // Do we need to close the previous font?
2041 (font != running_font ||
2042 font.language() != running_font.language()))
2044 column += running_font.latexWriteEndChanges(
2045 os, bparams, runparams, basefont,
2046 (i == body_pos-1) ? basefont : font);
2047 running_font = basefont;
2051 // close babel's font environment before opening CJK.
2052 if (!running_font.language()->babel().empty() &&
2053 font.language()->encoding()->package() == Encoding::CJK) {
2054 string end_tag = subst(lyxrc.language_command_end,
2056 running_font.language()->babel());
2057 os << from_ascii(end_tag);
2058 column += end_tag.length();
2061 // Switch file encoding if necessary (and allowed)
2062 if (!runparams.verbatim &&
2063 runparams.encoding->package() != Encoding::none &&
2064 font.language()->encoding()->package() != Encoding::none) {
2065 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2066 runparams, *(font.language()->encoding()));
2067 if (enc_switch.first) {
2068 column += enc_switch.second;
2069 runparams.encoding = font.language()->encoding();
2073 char_type const c = d->text_[i];
2075 // Do we need to change font?
2076 if ((font != running_font ||
2077 font.language() != running_font.language()) &&
2080 odocstringstream ods;
2081 column += font.latexWriteStartChanges(ods, bparams,
2082 runparams, basefont,
2084 running_font = font;
2086 docstring fontchange = ods.str();
2087 // check whether the fontchange ends with a \\textcolor
2088 // modifier and the text starts with a space (bug 4473)
2089 docstring const last_modifier = rsplit(fontchange, '\\');
2090 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2091 os << fontchange << from_ascii("{}");
2092 // check if the fontchange ends with a trailing blank
2093 // (like "\small " (see bug 3382)
2094 else if (suffixIs(fontchange, ' ') && c == ' ')
2095 os << fontchange.substr(0, fontchange.size() - 1)
2096 << from_ascii("{}");
2101 // FIXME: think about end_pos implementation...
2102 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2103 // FIXME: integrate this case in latexSpecialChar
2104 // Do not print the separation of the optional argument
2105 // if style.pass_thru is false. This works because
2106 // latexSpecialChar ignores spaces if
2107 // style.pass_thru is false.
2108 if (i != body_pos - 1) {
2109 if (d->simpleTeXBlanks(
2110 runparams, os, texrow,
2111 i, column, font, style)) {
2112 // A surrogate pair was output. We
2113 // must not call latexSpecialChar
2114 // in this iteration, since it would output
2115 // the combining character again.
2122 OutputParams rp = runparams;
2123 rp.free_spacing = style.free_spacing;
2124 rp.local_font = &font;
2125 rp.intitle = style.intitle;
2127 // Two major modes: LaTeX or plain
2128 // Handle here those cases common to both modes
2129 // and then split to handle the two modes separately.
2130 if (c == META_INSET) {
2131 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2132 d->latexInset(bparams, os,
2133 texrow, rp, running_font,
2134 basefont, outerfont, open_font,
2135 runningChange, style, i, column);
2138 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2140 d->latexSpecialChar(os, rp, running_font, runningChange,
2142 } catch (EncodingException & e) {
2143 if (runparams.dryrun) {
2144 os << "<" << _("LyX Warning: ")
2145 << _("uncodable character") << " '";
2149 // add location information and throw again.
2158 // Set the encoding to that returned from latexSpecialChar (see
2159 // comment for encoding member in OutputParams.h)
2160 runparams.encoding = rp.encoding;
2163 // If we have an open font definition, we have to close it
2165 #ifdef FIXED_LANGUAGE_END_DETECTION
2168 .latexWriteEndChanges(os, bparams, runparams,
2170 next_->getFont(bparams, 0, outerfont));
2172 running_font.latexWriteEndChanges(os, bparams,
2173 runparams, basefont, basefont);
2176 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2177 //FIXME: there as we start another \selectlanguage with the next paragraph if
2178 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2179 running_font.latexWriteEndChanges(os, bparams, runparams,
2180 basefont, basefont);
2184 column += Changes::latexMarkChange(os, bparams, runningChange,
2185 Change(Change::UNCHANGED), runparams);
2187 // Needed if there is an optional argument but no contents.
2188 if (body_pos > 0 && body_pos == size()) {
2190 return_value = false;
2193 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2194 && runparams.encoding != prev_encoding) {
2195 runparams.encoding = prev_encoding;
2196 if (!bparams.useXetex)
2197 os << setEncoding(prev_encoding->iconvName());
2200 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2201 return return_value;
2205 bool Paragraph::emptyTag() const
2207 for (pos_type i = 0; i < size(); ++i) {
2208 if (Inset const * inset = getInset(i)) {
2209 InsetCode lyx_code = inset->lyxCode();
2210 // FIXME testing like that is wrong. What is
2212 if (lyx_code != TOC_CODE &&
2213 lyx_code != INCLUDE_CODE &&
2214 lyx_code != GRAPHICS_CODE &&
2215 lyx_code != ERT_CODE &&
2216 lyx_code != LISTINGS_CODE &&
2217 lyx_code != FLOAT_CODE &&
2218 lyx_code != TABULAR_CODE) {
2222 char_type c = d->text_[i];
2223 if (c != ' ' && c != '\t')
2231 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2234 for (pos_type i = 0; i < size(); ++i) {
2235 if (Inset const * inset = getInset(i)) {
2236 InsetCode lyx_code = inset->lyxCode();
2237 if (lyx_code == LABEL_CODE) {
2238 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2239 docstring const & id = il->getParam("name");
2240 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2248 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2252 for (i = 0; i < size(); ++i) {
2253 if (Inset const * inset = getInset(i)) {
2254 inset->docbook(os, runparams);
2256 char_type c = d->text_[i];
2259 os << sgml::escapeChar(c);
2266 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2270 for (i = 0; i < size(); ++i) {
2271 if (Inset const * inset = getInset(i)) {
2272 inset->xhtml(os, runparams);
2274 char_type c = d->text_[i];
2277 os << html::escapeChar(c);
2284 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2287 pos_type size = text_.size();
2288 for (pos_type i = initial; i < size; ++i) {
2289 Font font = owner_->getFont(buf.params(), i, outerfont);
2290 if (text_[i] == META_INSET)
2292 if (i != initial && font != font_old)
2301 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2303 OutputParams const & runparams,
2304 Font const & outerfont,
2305 pos_type initial) const
2307 bool emph_flag = false;
2309 Layout const & style = *d->layout_;
2311 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2313 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2316 // parsing main loop
2317 for (pos_type i = initial; i < size(); ++i) {
2318 Font font = getFont(buf.params(), i, outerfont);
2320 // handle <emphasis> tag
2321 if (font_old.emph() != font.fontInfo().emph()) {
2322 if (font.fontInfo().emph() == FONT_ON) {
2325 } else if (i != initial) {
2326 os << "</emphasis>";
2331 if (Inset const * inset = getInset(i)) {
2332 inset->docbook(os, runparams);
2334 char_type c = d->text_[i];
2336 if (style.pass_thru)
2339 os << sgml::escapeChar(c);
2341 font_old = font.fontInfo();
2345 os << "</emphasis>";
2348 if (style.free_spacing)
2350 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2355 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2357 OutputParams const & runparams,
2358 Font const & outerfont,
2359 pos_type initial) const
2363 // FIXME We really need to manage the tag nesting here.
2364 // Probably in the same sort of way as in output_xhtml.
2365 bool emph_flag = false;
2366 bool bold_flag = false;
2367 std::string closing_tag;
2369 Layout const & style = *d->layout_;
2371 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2373 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2376 // parsing main loop
2377 for (pos_type i = initial; i < size(); ++i) {
2378 Font font = getFont(buf.params(), i, outerfont);
2381 if (font_old.emph() != font.fontInfo().emph()) {
2382 if (font.fontInfo().emph() == FONT_ON) {
2385 } else if (emph_flag && i != initial) {
2391 if (font_old.series() != font.fontInfo().series()) {
2392 if (font.fontInfo().series() == BOLD_SERIES) {
2395 } else if (bold_flag && i != initial) {
2400 // FIXME Other such tags?
2402 if (Inset const * inset = getInset(i)) {
2403 retval += inset->xhtml(os, runparams);
2405 char_type c = d->text_[i];
2407 if (style.pass_thru)
2409 else if (c == '-') {
2412 if (j < size() && d->text_[j] == '-') {
2414 if (j < size() && d->text_[j] == '-') {
2415 str += from_ascii("—");
2418 str += from_ascii("–");
2426 os << html::escapeChar(c);
2428 font_old = font.fontInfo();
2431 // FIXME This could be out of order. See above.
2441 bool Paragraph::isHfill(pos_type pos) const
2443 Inset const * inset = getInset(pos);
2444 return inset && (inset->lyxCode() == SPACE_CODE &&
2445 inset->isStretchableSpace());
2449 bool Paragraph::isNewline(pos_type pos) const
2451 Inset const * inset = getInset(pos);
2452 return inset && inset->lyxCode() == NEWLINE_CODE;
2456 bool Paragraph::isLineSeparator(pos_type pos) const
2458 char_type const c = d->text_[pos];
2459 if (isLineSeparatorChar(c))
2461 Inset const * inset = getInset(pos);
2462 return inset && inset->isLineSeparator();
2466 bool Paragraph::isWordSeparator(pos_type pos) const
2468 if (Inset const * inset = getInset(pos))
2469 return !inset->isLetter();
2470 char_type const c = d->text_[pos];
2471 // We want to pass the ' and escape chars to the spellchecker
2472 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2473 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2478 bool Paragraph::isChar(pos_type pos) const
2480 if (Inset const * inset = getInset(pos))
2481 return inset->isChar();
2482 char_type const c = d->text_[pos];
2483 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2487 bool Paragraph::isSpace(pos_type pos) const
2489 if (Inset const * inset = getInset(pos))
2490 return inset->isSpace();
2491 char_type const c = d->text_[pos];
2492 return lyx::isSpace(c);
2497 Paragraph::getParLanguage(BufferParams const & bparams) const
2500 return getFirstFontSettings(bparams).language();
2501 // FIXME: we should check the prev par as well (Lgb)
2502 return bparams.language;
2506 bool Paragraph::isRTL(BufferParams const & bparams) const
2508 return lyxrc.rtl_support
2509 && getParLanguage(bparams)->rightToLeft()
2510 && !inInset().getLayout().forceLTR();
2514 void Paragraph::changeLanguage(BufferParams const & bparams,
2515 Language const * from, Language const * to)
2517 // change language including dummy font change at the end
2518 for (pos_type i = 0; i <= size(); ++i) {
2519 Font font = getFontSettings(bparams, i);
2520 if (font.language() == from) {
2521 font.setLanguage(to);
2528 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2530 Language const * doc_language = bparams.language;
2531 FontList::const_iterator cit = d->fontlist_.begin();
2532 FontList::const_iterator end = d->fontlist_.end();
2534 for (; cit != end; ++cit)
2535 if (cit->font().language() != ignore_language &&
2536 cit->font().language() != latex_language &&
2537 cit->font().language() != doc_language)
2543 docstring Paragraph::asString(int options) const
2545 return asString(0, size(), options);
2549 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2551 odocstringstream os;
2554 && options & AS_STR_LABEL
2555 && !d->params_.labelString().empty())
2556 os << d->params_.labelString() << ' ';
2558 for (pos_type i = beg; i < end; ++i) {
2559 char_type const c = d->text_[i];
2560 if (isPrintable(c) || c == '\t'
2561 || (c == '\n' && (options & AS_STR_NEWLINES)))
2563 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2564 getInset(i)->tocString(os);
2565 if (getInset(i)->asInsetMath())
2574 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2576 odocstringstream os;
2579 && options & AS_STR_LABEL
2580 && !d->params_.labelString().empty())
2581 os << d->params_.labelString() << ' ';
2583 for (pos_type i = beg; i < end; ++i) {
2584 char_type const c = d->text_[i];
2585 if (isPrintable(c) || c == '\t'
2586 || (c == '\n' && (options & AS_STR_NEWLINES)))
2588 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2589 getInset(i)->plaintext(os, runparams);
2597 void Paragraph::setInsetOwner(Inset const * inset)
2599 d->inset_owner_ = inset;
2603 int Paragraph::id() const
2609 Layout const & Paragraph::layout() const
2615 void Paragraph::setLayout(Layout const & layout)
2617 d->layout_ = &layout;
2621 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2623 setLayout(tc.defaultLayout());
2627 void Paragraph::setPlainLayout(DocumentClass const & tc)
2629 setLayout(tc.plainLayout());
2633 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2635 if (usePlainLayout())
2636 setPlainLayout(tclass);
2638 setDefaultLayout(tclass);
2642 Inset const & Paragraph::inInset() const
2644 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2645 _("Memory problem"), _("Paragraph not properly initialized")));
2646 return *d->inset_owner_;
2650 ParagraphParameters & Paragraph::params()
2656 ParagraphParameters const & Paragraph::params() const
2662 bool Paragraph::isFreeSpacing() const
2664 if (d->layout_->free_spacing)
2666 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2670 bool Paragraph::allowEmpty() const
2672 if (d->layout_->keepempty)
2674 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2678 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2680 if (!Encodings::isArabicChar(c))
2683 char_type prev_char = ' ';
2684 char_type next_char = ' ';
2686 for (pos_type i = pos - 1; i >= 0; --i) {
2687 char_type const par_char = d->text_[i];
2688 if (!Encodings::isArabicComposeChar(par_char)) {
2689 prev_char = par_char;
2694 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2695 char_type const par_char = d->text_[i];
2696 if (!Encodings::isArabicComposeChar(par_char)) {
2697 next_char = par_char;
2702 if (Encodings::isArabicChar(next_char)) {
2703 if (Encodings::isArabicChar(prev_char) &&
2704 !Encodings::isArabicSpecialChar(prev_char))
2705 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2707 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2709 if (Encodings::isArabicChar(prev_char) &&
2710 !Encodings::isArabicSpecialChar(prev_char))
2711 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2713 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2718 int Paragraph::checkBiblio(Buffer const & buffer)
2721 // This is getting more and more a mess. ...We really should clean
2722 // up this bibitem issue for 1.6. See also bug 2743.
2724 // Add bibitem insets if necessary
2725 if (d->layout_->labeltype != LABEL_BIBLIO)
2728 bool hasbibitem = !d->insetlist_.empty()
2729 // Insist on it being in pos 0
2730 && d->text_[0] == META_INSET
2731 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2733 bool track_changes = buffer.params().trackChanges;
2738 // remove a bibitem in pos != 0
2739 // restore it later in pos 0 if necessary
2740 // (e.g. if a user inserts contents _before_ the item)
2741 // we're assuming there's only one of these, which there
2743 int erasedInsetPosition = -1;
2744 InsetList::iterator it = d->insetlist_.begin();
2745 InsetList::iterator end = d->insetlist_.end();
2746 for (; it != end; ++it)
2747 if (it->inset->lyxCode() == BIBITEM_CODE
2749 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2750 oldkey = olditem->getParam("key");
2751 oldlabel = olditem->getParam("label");
2752 erasedInsetPosition = it->pos;
2753 eraseChar(erasedInsetPosition, track_changes);
2757 // There was an InsetBibitem at the beginning, and we didn't
2758 // have to erase one.
2759 if (hasbibitem && erasedInsetPosition < 0)
2762 // There was an InsetBibitem at the beginning and we did have to
2763 // erase one. So we give its properties to the beginning inset.
2765 InsetBibitem * inset =
2766 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2767 if (!oldkey.empty())
2768 inset->setParam("key", oldkey);
2769 inset->setParam("label", oldlabel);
2770 return -erasedInsetPosition;
2773 // There was no inset at the beginning, so we need to create one with
2774 // the key and label of the one we erased.
2775 InsetBibitem * inset =
2776 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2777 // restore values of previously deleted item in this par.
2778 if (!oldkey.empty())
2779 inset->setParam("key", oldkey);
2780 inset->setParam("label", oldlabel);
2781 insertInset(0, static_cast<Inset *>(inset),
2782 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2788 void Paragraph::checkAuthors(AuthorList const & authorList)
2790 d->changes_.checkAuthors(authorList);
2794 bool Paragraph::isChanged(pos_type pos) const
2796 return lookupChange(pos).changed();
2800 bool Paragraph::isInserted(pos_type pos) const
2802 return lookupChange(pos).inserted();
2806 bool Paragraph::isDeleted(pos_type pos) const
2808 return lookupChange(pos).deleted();
2812 InsetList const & Paragraph::insetList() const
2814 return d->insetlist_;
2818 void Paragraph::setBuffer(Buffer & b)
2820 d->insetlist_.setBuffer(b);
2824 Inset * Paragraph::releaseInset(pos_type pos)
2826 Inset * inset = d->insetlist_.release(pos);
2827 /// does not honour change tracking!
2828 eraseChar(pos, false);
2833 Inset * Paragraph::getInset(pos_type pos)
2835 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2836 ? d->insetlist_.get(pos) : 0;
2840 Inset const * Paragraph::getInset(pos_type pos) const
2842 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2843 ? d->insetlist_.get(pos) : 0;
2847 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2848 pos_type & right, TextCase action)
2850 // process sequences of modified characters; in change
2851 // tracking mode, this approach results in much better
2852 // usability than changing case on a char-by-char basis
2855 bool const trackChanges = bparams.trackChanges;
2857 bool capitalize = true;
2859 for (; pos < right; ++pos) {
2860 char_type oldChar = d->text_[pos];
2861 char_type newChar = oldChar;
2863 // ignore insets and don't play with deleted text!
2864 if (oldChar != META_INSET && !isDeleted(pos)) {
2866 case text_lowercase:
2867 newChar = lowercase(oldChar);
2869 case text_capitalization:
2871 newChar = uppercase(oldChar);
2875 case text_uppercase:
2876 newChar = uppercase(oldChar);
2881 if (isWordSeparator(pos) || isDeleted(pos)) {
2882 // permit capitalization again
2886 if (oldChar != newChar) {
2888 if (pos != right - 1)
2890 // step behind the changing area
2894 int erasePos = pos - changes.size();
2895 for (size_t i = 0; i < changes.size(); i++) {
2896 insertChar(pos, changes[i],
2897 getFontSettings(bparams,
2900 if (!eraseChar(erasePos, trackChanges)) {
2903 ++right; // expand selection
2911 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2912 pos_type pos, bool del) const
2914 int const strsize = str.length();
2916 pos_type const parsize = d->text_.size();
2917 for (i = 0; pos + i < parsize; ++i) {
2920 if (cs && str[i] != d->text_[pos + i])
2922 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2924 if (!del && isDeleted(pos + i))
2931 // if necessary, check whether string matches word
2933 if (pos > 0 && !isWordSeparator(pos - 1))
2935 if (pos + strsize < parsize
2936 && !isWordSeparator(pos + strsize))
2944 char_type Paragraph::getChar(pos_type pos) const
2946 return d->text_[pos];
2950 pos_type Paragraph::size() const
2952 return d->text_.size();
2956 bool Paragraph::empty() const
2958 return d->text_.empty();
2962 bool Paragraph::isInset(pos_type pos) const
2964 return d->text_[pos] == META_INSET;
2968 bool Paragraph::isSeparator(pos_type pos) const
2970 //FIXME: Are we sure this can be the only separator?
2971 return d->text_[pos] == ' ';
2975 void Paragraph::deregisterWords()
2977 Private::Words::const_iterator it;
2978 WordList & wl = theWordList();
2979 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2985 void Paragraph::locateWord(pos_type & from, pos_type & to,
2986 word_location const loc) const
2989 case WHOLE_WORD_STRICT:
2990 if (from == 0 || from == size()
2991 || isWordSeparator(from)
2992 || isWordSeparator(from - 1)) {
2996 // no break here, we go to the next
2999 // If we are already at the beginning of a word, do nothing
3000 if (!from || isWordSeparator(from - 1))
3002 // no break here, we go to the next
3005 // always move the cursor to the beginning of previous word
3006 while (from && !isWordSeparator(from - 1))
3010 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3013 // no need to move the 'from' cursor
3017 while (to < size() && !isWordSeparator(to))
3022 void Paragraph::collectWords()
3024 pos_type n = size();
3025 for (pos_type pos = 0; pos < n; ++pos) {
3026 if (isWordSeparator(pos))
3028 pos_type from = pos;
3029 locateWord(from, pos, WHOLE_WORD);
3030 if (pos - from >= 6) {
3031 docstring word = asString(from, pos, AS_STR_NONE);
3032 d->words_.insert(word);
3038 void Paragraph::registerWords()
3040 Private::Words::const_iterator it;
3041 WordList & wl = theWordList();
3042 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3047 void Paragraph::updateWords()
3055 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3056 docstring_list & suggestions, bool do_suggestion) const
3058 SpellChecker * speller = theSpellChecker();
3062 locateWord(from, to, WHOLE_WORD);
3063 if (from == to || from >= pos_type(d->text_.size()))
3066 docstring word = asString(from, to, AS_STR_INSETS);
3067 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3068 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3069 : lyxrc.spellchecker_alt_lang;
3070 wl = WordLangTuple(word, lang_code);
3071 SpellChecker::Result res = speller->check(wl);
3072 // Just ignore any error that the spellchecker reports.
3073 // FIXME: we should through out an exception and catch it in the GUI to
3074 // display the error.
3075 if (!speller->error().empty())
3078 bool const misspelled = res != SpellChecker::OK
3079 && res != SpellChecker::IGNORED_WORD;
3081 if (lyxrc.spellcheck_continuously)
3082 d->fontlist_.setMisspelled(from, to, misspelled);
3084 if (misspelled && do_suggestion)
3085 speller->suggest(wl, suggestions);
3087 suggestions.clear();
3093 bool Paragraph::isMisspelled(pos_type pos) const
3095 pos_type from = pos;
3098 docstring_list suggestions;
3099 return spellCheck(from, to, wl, suggestions, false);