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 "paragraph_funcs.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
76 /////////////////////////////////////////////////////////////////////
80 /////////////////////////////////////////////////////////////////////
82 class Paragraph::Private
86 Private(Paragraph * owner, Layout const & layout);
87 /// "Copy constructor"
88 Private(Private const &, Paragraph * owner);
89 /// Copy constructor from \p beg to \p end
90 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
93 void insertChar(pos_type pos, char_type c, Change const & change);
95 /// Output the surrogate pair formed by \p c and \p next to \p os.
96 /// \return the number of characters written.
97 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98 OutputParams const &);
100 /// Output a space in appropriate formatting (or a surrogate pair
101 /// if the next character is a combining character).
102 /// \return whether a surrogate pair was output.
103 bool simpleTeXBlanks(OutputParams const &,
104 odocstream &, TexRow & texrow,
106 unsigned int & column,
108 Layout const & style);
110 /// Output consecutive unicode chars, belonging to the same script as
111 /// specified by the latex macro \p ltx, to \p os starting from \p i.
112 /// \return the number of characters written.
113 int writeScriptChars(odocstream & os, docstring const & ltx,
114 Change const &, Encoding const &, pos_type & i);
116 /// This could go to ParagraphParameters if we want to.
117 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 OutputParams const &) const;
120 /// This could go to ParagraphParameters if we want to.
121 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122 OutputParams const &) const;
125 void latexInset(BufferParams const &,
127 TexRow & texrow, OutputParams &,
130 Font const & outerfont,
132 Change & running_change,
133 Layout const & style,
135 unsigned int & column);
138 void latexSpecialChar(
140 OutputParams const & runparams,
141 Font const & running_font,
142 Change const & running_change,
143 Layout const & style,
145 unsigned int & column);
152 unsigned int & column);
154 bool latexSpecialTypewriter(
158 unsigned int & column);
160 bool latexSpecialPhrase(
163 unsigned int & column,
164 OutputParams const & runparams);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(string const & str, pos_type pos) const;
178 InsetCode Private::ownerCode() const
180 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
183 /// Which Paragraph owns us?
187 Inset const * inset_owner_;
195 static unsigned int paragraph_id;
197 ParagraphParameters params_;
199 /// for recording and looking up changes
203 InsetList insetlist_;
206 pos_type begin_of_body_;
208 typedef docstring TextContainer;
212 typedef std::set<docstring> Words;
216 Layout const * layout_;
220 // Initialization of the counter for the paragraph id's,
221 unsigned int Paragraph::Private::paragraph_id = 0;
225 struct special_phrase {
231 special_phrase const special_phrases[] = {
232 { "LyX", from_ascii("\\LyX{}"), false },
233 { "TeX", from_ascii("\\TeX{}"), true },
234 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
235 { "LaTeX", from_ascii("\\LaTeX{}"), true },
238 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
243 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
244 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
246 id_ = paragraph_id++;
251 Paragraph::Private::Private(Private const & p, Paragraph * owner)
252 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
253 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
254 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
257 id_ = paragraph_id++;
261 Paragraph::Private::Private(Private const & p, Paragraph * owner,
262 pos_type beg, pos_type end)
263 : owner_(owner), inset_owner_(p.inset_owner_),
264 params_(p.params_), changes_(p.changes_),
265 insetlist_(p.insetlist_, beg, end),
266 begin_of_body_(p.begin_of_body_), words_(p.words_),
269 id_ = paragraph_id++;
270 if (beg >= pos_type(p.text_.size()))
272 text_ = p.text_.substr(beg, end - beg);
274 FontList::const_iterator fcit = fontlist_.begin();
275 FontList::const_iterator fend = fontlist_.end();
276 for (; fcit != fend; ++fcit) {
277 if (fcit->pos() < beg)
279 if (fcit->pos() >= end) {
280 // Add last entry in the fontlist_.
281 fontlist_.set(text_.size() - 1, fcit->font());
284 // Add a new entry in the fontlist_.
285 fontlist_.set(fcit->pos() - beg, fcit->font());
290 void Paragraph::addChangesToToc(DocIterator const & cdit,
291 Buffer const & buf) const
293 d->changes_.addToToc(cdit, buf);
297 bool Paragraph::isDeleted(pos_type start, pos_type end) const
299 LASSERT(start >= 0 && start <= size(), /**/);
300 LASSERT(end > start && end <= size() + 1, /**/);
302 return d->changes_.isDeleted(start, end);
306 bool Paragraph::isChanged(pos_type start, pos_type end) const
308 LASSERT(start >= 0 && start <= size(), /**/);
309 LASSERT(end > start && end <= size() + 1, /**/);
311 return d->changes_.isChanged(start, end);
315 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
317 // keep the logic here in sync with the logic of eraseChars()
321 Change const change = d->changes_.lookup(size());
322 return change.inserted() && change.currentAuthor();
326 void Paragraph::setChange(Change const & change)
328 // beware of the imaginary end-of-par character!
329 d->changes_.set(change, 0, size() + 1);
332 * Propagate the change recursively - but not in case of DELETED!
334 * Imagine that your co-author makes changes in an existing inset. He
335 * sends your document to you and you come to the conclusion that the
336 * inset should go completely. If you erase it, LyX must not delete all
337 * text within the inset. Otherwise, the change tracked insertions of
338 * your co-author get lost and there is no way to restore them later.
340 * Conclusion: An inset's content should remain untouched if you delete it
343 if (!change.deleted()) {
344 for (pos_type pos = 0; pos < size(); ++pos) {
345 if (Inset * inset = getInset(pos))
346 inset->setChange(change);
352 void Paragraph::setChange(pos_type pos, Change const & change)
354 LASSERT(pos >= 0 && pos <= size(), /**/);
355 d->changes_.set(change, pos);
357 // see comment in setChange(Change const &) above
358 if (!change.deleted() && pos < size())
359 if (Inset * inset = getInset(pos))
360 inset->setChange(change);
364 Change const & Paragraph::lookupChange(pos_type pos) const
366 LASSERT(pos >= 0 && pos <= size(), /**/);
367 return d->changes_.lookup(pos);
371 void Paragraph::acceptChanges(pos_type start, pos_type end)
373 LASSERT(start >= 0 && start <= size(), /**/);
374 LASSERT(end > start && end <= size() + 1, /**/);
376 for (pos_type pos = start; pos < end; ++pos) {
377 switch (lookupChange(pos).type) {
378 case Change::UNCHANGED:
379 // accept changes in nested inset
380 if (Inset * inset = getInset(pos))
381 inset->acceptChanges();
384 case Change::INSERTED:
385 d->changes_.set(Change(Change::UNCHANGED), pos);
386 // also accept changes in nested inset
387 if (Inset * inset = getInset(pos))
388 inset->acceptChanges();
391 case Change::DELETED:
392 // Suppress access to non-existent
393 // "end-of-paragraph char"
395 eraseChar(pos, false);
406 void Paragraph::rejectChanges(pos_type start, pos_type end)
408 LASSERT(start >= 0 && start <= size(), /**/);
409 LASSERT(end > start && end <= size() + 1, /**/);
411 for (pos_type pos = start; pos < end; ++pos) {
412 switch (lookupChange(pos).type) {
413 case Change::UNCHANGED:
414 // reject changes in nested inset
415 if (Inset * inset = getInset(pos))
416 inset->rejectChanges();
419 case Change::INSERTED:
420 // Suppress access to non-existent
421 // "end-of-paragraph char"
423 eraseChar(pos, false);
429 case Change::DELETED:
430 d->changes_.set(Change(Change::UNCHANGED), pos);
432 // Do NOT reject changes within a deleted inset!
433 // There may be insertions of a co-author inside of it!
441 void Paragraph::Private::insertChar(pos_type pos, char_type c,
442 Change const & change)
444 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
447 changes_.insert(change, pos);
449 // This is actually very common when parsing buffers (and
450 // maybe inserting ascii text)
451 if (pos == pos_type(text_.size())) {
452 // when appending characters, no need to update tables
457 text_.insert(text_.begin() + pos, c);
459 // Update the font table.
460 fontlist_.increasePosAfterPos(pos);
463 insetlist_.increasePosAfterPos(pos);
467 bool Paragraph::insertInset(pos_type pos, Inset * inset,
468 Change const & change)
470 LASSERT(inset, /**/);
471 LASSERT(pos >= 0 && pos <= size(), /**/);
473 // Paragraph::insertInset() can be used in cut/copy/paste operation where
474 // d->inset_owner_ is not set yet.
475 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
478 d->insertChar(pos, META_INSET, change);
479 LASSERT(d->text_[pos] == META_INSET, /**/);
481 // Add a new entry in the insetlist_.
482 d->insetlist_.insert(inset, pos);
487 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
489 LASSERT(pos >= 0 && pos <= size(), return false);
491 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
494 Change change = d->changes_.lookup(pos);
496 // set the character to DELETED if
497 // a) it was previously unchanged or
498 // b) it was inserted by a co-author
500 if (!change.changed() ||
501 (change.inserted() && !change.currentAuthor())) {
502 setChange(pos, Change(Change::DELETED));
506 if (change.deleted())
510 // Don't physically access the imaginary end-of-paragraph character.
511 // eraseChar() can only mark it as DELETED. A physical deletion of
512 // end-of-par must be handled externally.
518 d->changes_.erase(pos);
520 // if it is an inset, delete the inset entry
521 if (d->text_[pos] == META_INSET)
522 d->insetlist_.erase(pos);
524 d->text_.erase(d->text_.begin() + pos);
526 // Update the fontlist_
527 d->fontlist_.erase(pos);
529 // Update the insetlist_
530 d->insetlist_.decreasePosAfterPos(pos);
536 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
538 LASSERT(start >= 0 && start <= size(), /**/);
539 LASSERT(end >= start && end <= size() + 1, /**/);
542 for (pos_type count = end - start; count; --count) {
543 if (!eraseChar(i, trackChanges))
550 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
551 char_type next, OutputParams const & runparams)
553 // Writing next here may circumvent a possible font change between
554 // c and next. Since next is only output if it forms a surrogate pair
555 // with c we can ignore this:
556 // A font change inside a surrogate pair does not make sense and is
557 // hopefully impossible to input.
558 // FIXME: change tracking
559 // Is this correct WRT change tracking?
560 Encoding const & encoding = *(runparams.encoding);
561 docstring const latex1 = encoding.latexChar(next);
562 docstring const latex2 = encoding.latexChar(c);
563 if (docstring(1, next) == latex1) {
564 // the encoding supports the combination
565 os << latex2 << latex1;
566 return latex1.length() + latex2.length();
567 } else if (runparams.local_font &&
568 runparams.local_font->language()->lang() == "polutonikogreek") {
569 // polutonikogreek only works without the brackets
570 os << latex1 << latex2;
571 return latex1.length() + latex2.length();
573 os << latex1 << '{' << latex2 << '}';
574 return latex1.length() + latex2.length() + 2;
578 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
579 odocstream & os, TexRow & texrow,
581 unsigned int & column,
583 Layout const & style)
585 if (style.pass_thru || runparams.verbatim)
588 if (i + 1 < int(text_.size())) {
589 char_type next = text_[i + 1];
590 if (Encodings::isCombiningChar(next)) {
591 // This space has an accent, so we must always output it.
592 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
597 if (lyxrc.plaintext_linelen > 0
598 && column > lyxrc.plaintext_linelen
600 && text_[i - 1] != ' '
601 && (i + 1 < int(text_.size()))
602 // same in FreeSpacing mode
603 && !owner_->isFreeSpacing()
604 // In typewriter mode, we want to avoid
605 // ! . ? : at the end of a line
606 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
607 && (text_[i - 1] == '.'
608 || text_[i - 1] == '?'
609 || text_[i - 1] == ':'
610 || text_[i - 1] == '!'))) {
613 texrow.start(owner_->id(), i + 1);
615 } else if (style.free_spacing) {
624 int Paragraph::Private::writeScriptChars(odocstream & os,
625 docstring const & ltx,
626 Change const & runningChange,
627 Encoding const & encoding,
630 // FIXME: modifying i here is not very nice...
632 // We only arrive here when a proper language for character text_[i] has
633 // not been specified (i.e., it could not be translated in the current
634 // latex encoding) or its latex translation has been forced, and it
635 // belongs to a known script.
636 // Parameter ltx contains the latex translation of text_[i] as specified
637 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
638 // The latex macro name "textXXX" specifies the script to which text_[i]
639 // belongs and we use it in order to check whether characters from the
640 // same script immediately follow, such that we can collect them in a
641 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
642 // for the first char but only "<spec>" for all subsequent chars.
643 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
644 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
645 string script = to_ascii(ltx.substr(1, brace1 - 1));
648 bool closing_brace = true;
649 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
650 // Correct encoding is being used, so we can avoid \textgreek.
653 closing_brace = false;
655 os << ltx.substr(pos, length);
656 int size = text_.size();
657 while (i + 1 < size) {
658 char_type const next = text_[i + 1];
659 // Stop here if next character belongs to another script
660 // or there is a change in change tracking status.
661 if (!Encodings::isKnownScriptChar(next, script) ||
662 runningChange != owner_->lookupChange(i + 1))
666 FontList::const_iterator cit = fontlist_.begin();
667 FontList::const_iterator end = fontlist_.end();
668 for (; cit != end; ++cit) {
669 if (cit->pos() >= i && !found) {
670 prev_font = cit->font();
673 if (cit->pos() >= i + 1)
676 // Stop here if there is a font attribute or encoding change.
677 if (found && cit != end && prev_font != cit->font())
679 docstring const latex = encoding.latexChar(next);
680 docstring::size_type const b1 =
681 latex.find_first_of(from_ascii("{"));
682 docstring::size_type const b2 =
683 latex.find_last_of(from_ascii("}"));
684 int const len = b2 - b1 - 1;
685 os << latex.substr(b1 + 1, len);
697 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
699 pos_type const len = str.length();
701 // is the paragraph large enough?
702 if (pos + len > int(text_.size()))
705 // does the wanted text start at point?
706 for (string::size_type i = 0; i < str.length(); ++i) {
707 // Caution: direct comparison of characters works only
708 // because str is pure ASCII.
709 if (str[i] != text_[pos + i])
713 return fontlist_.hasChangeInRange(pos, len);
717 void Paragraph::Private::latexInset(
718 BufferParams const & bparams,
721 OutputParams & runparams,
724 Font const & outerfont,
726 Change & running_change,
727 Layout const & style,
729 unsigned int & column)
731 Inset * inset = owner_->getInset(i);
732 LASSERT(inset, /**/);
734 if (style.pass_thru) {
735 inset->plaintext(os, runparams);
739 // FIXME: move this to InsetNewline::latex
740 if (inset->lyxCode() == NEWLINE_CODE) {
741 // newlines are handled differently here than
742 // the default in simpleTeXSpecialChars().
743 if (!style.newline_allowed) {
747 column += running_font.latexWriteEndChanges(
748 os, bparams, runparams,
753 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
756 basefont = owner_->getLayoutFont(bparams, outerfont);
757 running_font = basefont;
759 if (runparams.moving_arg)
764 texrow.start(owner_->id(), i + 1);
768 if (owner_->isDeleted(i)) {
769 if( ++runparams.inDeletedInset == 1)
770 runparams.changeOfDeletedInset = owner_->lookupChange(i);
773 if (inset->canTrackChanges()) {
774 column += Changes::latexMarkChange(os, bparams, running_change,
775 Change(Change::UNCHANGED));
776 running_change = Change(Change::UNCHANGED);
780 odocstream::pos_type const len = os.tellp();
782 if (inset->forceLTR()
783 && running_font.isRightToLeft()
784 // ERT is an exception, it should be output with no
785 // decorations at all
786 && inset->lyxCode() != ERT_CODE) {
787 if (running_font.language()->lang() == "farsi")
794 // FIXME: Bug: we can have an empty font change here!
795 // if there has just been a font change, we are going to close it
796 // right now, which means stupid latex code like \textsf{}. AFAIK,
797 // this does not harm dvi output. A minor bug, thus (JMarc)
799 // Some insets cannot be inside a font change command.
800 // However, even such insets *can* be placed in \L or \R
801 // or their equivalents (for RTL language switches), so we don't
802 // close the language in those cases.
803 // ArabTeX, though, cannot handle this special behavior, it seems.
804 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
805 || running_font.language()->lang() == "arabic_arabtex";
806 if (open_font && inset->noFontChange()) {
807 bool closeLanguage = arabtex
808 || basefont.isRightToLeft() == running_font.isRightToLeft();
809 unsigned int count = running_font.latexWriteEndChanges(os,
810 bparams, runparams, basefont, basefont, closeLanguage);
812 // if any font properties were closed, update the running_font,
813 // making sure, however, to leave the language as it was
815 // FIXME: probably a better way to keep track of the old
816 // language, than copying the entire font?
817 Font const copy_font(running_font);
818 basefont = owner_->getLayoutFont(bparams, outerfont);
819 running_font = basefont;
821 running_font.setLanguage(copy_font.language());
822 // leave font open if language is still open
823 open_font = (running_font.language() == basefont.language());
825 runparams.local_font = &basefont;
832 tmp = inset->latex(os, runparams);
833 } catch (EncodingException & e) {
834 // add location information and throw again.
841 if (running_font.language()->lang() == "farsi")
848 for (int j = 0; j < tmp; ++j)
851 texrow.start(owner_->id(), i + 1);
854 column += os.tellp() - len;
857 if (owner_->isDeleted(i))
858 --runparams.inDeletedInset;
862 void Paragraph::Private::latexSpecialChar(
864 OutputParams const & runparams,
865 Font const & running_font,
866 Change const & running_change,
867 Layout const & style,
869 unsigned int & column)
871 char_type const c = text_[i];
873 if (style.pass_thru) {
875 // FIXME UNICODE: This can fail if c cannot
876 // be encoded in the current encoding.
881 if (runparams.verbatim) {
882 // FIXME UNICODE: This can fail if c cannot
883 // be encoded in the current encoding.
888 // If T1 font encoding is used, use the special
889 // characters it provides.
890 // NOTE: some languages reset the font encoding
892 if (!running_font.language()->internalFontEncoding()
893 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
896 // \tt font needs special treatment
897 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
898 && latexSpecialTypewriter(c, os, i, column))
901 // Otherwise, we use what LaTeX provides us.
904 os << "\\textbackslash{}";
908 os << "\\textless{}";
912 os << "\\textgreater{}";
923 os << "\\char`\\\"{}";
928 case '%': case '#': case '{':
936 os << "\\textasciitilde{}";
941 os << "\\textasciicircum{}";
948 // avoid being mistaken for optional arguments
956 // Blanks are printed before font switching.
957 // Sure? I am not! (try nice-latex)
958 // I am sure it's correct. LyX might be smarter
959 // in the future, but for now, nothing wrong is
965 if (latexSpecialPhrase(os, i, column, runparams))
971 Encoding const & encoding = *(runparams.encoding);
972 if (i + 1 < int(text_.size())) {
973 char_type next = text_[i + 1];
974 if (Encodings::isCombiningChar(next)) {
975 column += latexSurrogatePair(os, c, next, runparams) - 1;
981 docstring const latex = encoding.latexChar(c);
982 if (Encodings::isKnownScriptChar(c, script)
983 && prefixIs(latex, from_ascii("\\" + script)))
984 column += writeScriptChars(os, latex,
985 running_change, encoding, i) - 1;
986 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
987 // Prevent eating of a following
988 // space or command corruption by
989 // following characters
990 column += latex.length() + 1;
993 column += latex.length() - 1;
1001 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1002 pos_type i, unsigned int & column)
1008 // In T1 encoding, these characters exist
1009 // but we should avoid ligatures
1010 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1012 os << "\\textcompwordmark{}";
1019 // soul.sty breaks with \char`\"
1020 os << "\\textquotedbl{}";
1029 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1030 pos_type i, unsigned int & column)
1034 // within \ttfamily, "--" is merged to "-" (no endash)
1035 // so we avoid this rather irritating ligature
1036 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1043 // everything else has to be checked separately
1044 // (depending on the encoding)
1051 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1052 unsigned int & column, OutputParams const & runparams)
1054 // FIXME: if we have "LaTeX" with a font
1055 // change in the middle (before the 'T', then
1056 // the "TeX" part is still special cased.
1057 // Really we should only operate this on
1058 // "words" for some definition of word
1060 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1061 if (!isTextAt(special_phrases[pnr].phrase, i))
1063 if (runparams.moving_arg)
1065 os << special_phrases[pnr].macro;
1066 i += special_phrases[pnr].phrase.length() - 1;
1067 column += special_phrases[pnr].macro.length() - 1;
1074 void Paragraph::Private::validate(LaTeXFeatures & features,
1075 Layout const & layout) const
1077 // check the params.
1078 if (!params_.spacing().isDefault())
1079 features.require("setspace");
1082 features.useLayout(layout.name());
1085 fontlist_.validate(features);
1087 // then the indentation
1088 if (!params_.leftIndent().zero())
1089 features.require("ParagraphLeftIndent");
1092 InsetList::const_iterator icit = insetlist_.begin();
1093 InsetList::const_iterator iend = insetlist_.end();
1094 for (; icit != iend; ++icit) {
1096 icit->inset->validate(features);
1097 if (layout.needprotect &&
1098 icit->inset->lyxCode() == FOOT_CODE)
1099 features.require("NeedLyXFootnoteCode");
1103 // then the contents
1104 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1105 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1106 if (!special_phrases[pnr].builtin
1107 && isTextAt(special_phrases[pnr].phrase, i)) {
1108 features.require(special_phrases[pnr].phrase);
1112 Encodings::validate(text_[i], features);
1116 /////////////////////////////////////////////////////////////////////
1120 /////////////////////////////////////////////////////////////////////
1123 Layout const emptyParagraphLayout;
1126 Paragraph::Paragraph()
1127 : d(new Paragraph::Private(this, emptyParagraphLayout))
1134 Paragraph::Paragraph(Paragraph const & par)
1135 : itemdepth(par.itemdepth),
1136 d(new Paragraph::Private(*par.d, this))
1142 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1143 : itemdepth(par.itemdepth),
1144 d(new Paragraph::Private(*par.d, this, beg, end))
1150 Paragraph & Paragraph::operator=(Paragraph const & par)
1152 // needed as we will destroy the private part before copying it
1154 itemdepth = par.itemdepth;
1158 d = new Private(*par.d, this);
1165 Paragraph::~Paragraph()
1172 void Paragraph::write(ostream & os, BufferParams const & bparams,
1173 depth_type & dth) const
1175 // The beginning or end of a deeper (i.e. nested) area?
1176 if (dth != d->params_.depth()) {
1177 if (d->params_.depth() > dth) {
1178 while (d->params_.depth() > dth) {
1179 os << "\n\\begin_deeper";
1183 while (d->params_.depth() < dth) {
1184 os << "\n\\end_deeper";
1190 // First write the layout
1191 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1193 d->params_.write(os);
1195 Font font1(inherit_font, bparams.language);
1197 Change running_change = Change(Change::UNCHANGED);
1200 for (pos_type i = 0; i <= size(); ++i) {
1202 Change const change = lookupChange(i);
1203 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1204 running_change = change;
1209 // Write font changes (ignore spelling markers)
1210 Font font2 = getFontSettings(bparams, i);
1211 font2.setMisspelled(false);
1212 if (font2 != font1) {
1213 font2.lyxWriteChanges(font1, os);
1218 char_type const c = d->text_[i];
1221 if (Inset const * inset = getInset(i)) {
1222 if (inset->directWrite()) {
1223 // international char, let it write
1224 // code directly so it's shorter in
1230 os << "\\begin_inset ";
1232 os << "\n\\end_inset\n\n";
1238 os << "\n\\backslash\n";
1242 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1249 if ((column > 70 && c == ' ')
1254 // this check is to amend a bug. LyX sometimes
1255 // inserts '\0' this could cause problems.
1257 os << to_utf8(docstring(1, c));
1259 LYXERR0("NUL char in structure.");
1265 os << "\n\\end_layout\n";
1269 void Paragraph::validate(LaTeXFeatures & features) const
1271 d->validate(features, *d->layout_);
1275 void Paragraph::insert(pos_type start, docstring const & str,
1276 Font const & font, Change const & change)
1278 for (size_t i = 0, n = str.size(); i != n ; ++i)
1279 insertChar(start + i, str[i], font, change);
1283 void Paragraph::appendChar(char_type c, Font const & font,
1284 Change const & change)
1287 d->changes_.insert(change, d->text_.size());
1288 // when appending characters, no need to update tables
1289 d->text_.push_back(c);
1290 setFont(d->text_.size() - 1, font);
1294 void Paragraph::appendString(docstring const & s, Font const & font,
1295 Change const & change)
1297 pos_type end = s.size();
1298 size_t oldsize = d->text_.size();
1299 size_t newsize = oldsize + end;
1300 size_t capacity = d->text_.capacity();
1301 if (newsize >= capacity)
1302 d->text_.reserve(max(capacity + 100, newsize));
1304 // when appending characters, no need to update tables
1307 // FIXME: Optimize this!
1308 for (size_t i = oldsize; i != newsize; ++i) {
1310 d->changes_.insert(change, i);
1312 d->fontlist_.set(oldsize, font);
1313 d->fontlist_.set(newsize - 1, font);
1317 void Paragraph::insertChar(pos_type pos, char_type c,
1320 d->insertChar(pos, c, Change(trackChanges ?
1321 Change::INSERTED : Change::UNCHANGED));
1325 void Paragraph::insertChar(pos_type pos, char_type c,
1326 Font const & font, bool trackChanges)
1328 d->insertChar(pos, c, Change(trackChanges ?
1329 Change::INSERTED : Change::UNCHANGED));
1334 void Paragraph::insertChar(pos_type pos, char_type c,
1335 Font const & font, Change const & change)
1337 d->insertChar(pos, c, change);
1342 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1343 Font const & font, Change const & change)
1345 bool const success = insertInset(pos, inset, change);
1346 // Set the font/language of the inset...
1352 void Paragraph::resetFonts(Font const & font)
1354 d->fontlist_.clear();
1355 d->fontlist_.set(0, font);
1356 d->fontlist_.set(d->text_.size() - 1, font);
1359 // Gets uninstantiated font setting at position.
1360 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1364 LYXERR0("pos: " << pos << " size: " << size());
1365 LASSERT(pos <= size(), /**/);
1368 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1369 if (cit != d->fontlist_.end())
1372 if (pos == size() && !empty())
1373 return getFontSettings(bparams, pos - 1);
1375 // Optimisation: avoid a full font instantiation if there is no
1376 // language change from previous call.
1377 static Font previous_font;
1378 static Language const * previous_lang = 0;
1379 Language const * lang = getParLanguage(bparams);
1380 if (lang != previous_lang) {
1381 previous_lang = lang;
1382 previous_font = Font(inherit_font, lang);
1384 return previous_font;
1388 FontSpan Paragraph::fontSpan(pos_type pos) const
1390 LASSERT(pos <= size(), /**/);
1393 FontList::const_iterator cit = d->fontlist_.begin();
1394 FontList::const_iterator end = d->fontlist_.end();
1395 for (; cit != end; ++cit) {
1396 if (cit->pos() >= pos) {
1397 if (pos >= beginOfBody())
1398 return FontSpan(max(start, beginOfBody()),
1401 return FontSpan(start,
1402 min(beginOfBody() - 1,
1405 start = cit->pos() + 1;
1408 // This should not happen, but if so, we take no chances.
1409 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1410 return FontSpan(pos, pos);
1414 // Gets uninstantiated font setting at position 0
1415 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1417 if (!empty() && !d->fontlist_.empty())
1418 return d->fontlist_.begin()->font();
1420 // Optimisation: avoid a full font instantiation if there is no
1421 // language change from previous call.
1422 static Font previous_font;
1423 static Language const * previous_lang = 0;
1424 if (bparams.language != previous_lang) {
1425 previous_lang = bparams.language;
1426 previous_font = Font(inherit_font, bparams.language);
1429 return previous_font;
1433 // Gets the fully instantiated font at a given position in a paragraph
1434 // This is basically the same function as Text::GetFont() in text2.cpp.
1435 // The difference is that this one is used for generating the LaTeX file,
1436 // and thus cosmetic "improvements" are disallowed: This has to deliver
1437 // the true picture of the buffer. (Asger)
1438 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1439 Font const & outerfont) const
1441 LASSERT(pos >= 0, /**/);
1443 Font font = getFontSettings(bparams, pos);
1445 pos_type const body_pos = beginOfBody();
1446 FontInfo & fi = font.fontInfo();
1448 fi.realize(d->layout_->labelfont);
1450 fi.realize(d->layout_->font);
1452 fi.realize(outerfont.fontInfo());
1453 fi.realize(bparams.getFont().fontInfo());
1459 Font const Paragraph::getLabelFont
1460 (BufferParams const & bparams, Font const & outerfont) const
1462 FontInfo tmpfont = d->layout_->labelfont;
1463 tmpfont.realize(outerfont.fontInfo());
1464 tmpfont.realize(bparams.getFont().fontInfo());
1465 return Font(tmpfont, getParLanguage(bparams));
1469 Font const Paragraph::getLayoutFont
1470 (BufferParams const & bparams, Font const & outerfont) const
1472 FontInfo tmpfont = d->layout_->font;
1473 tmpfont.realize(outerfont.fontInfo());
1474 tmpfont.realize(bparams.getFont().fontInfo());
1475 return Font(tmpfont, getParLanguage(bparams));
1479 /// Returns the height of the highest font in range
1480 FontSize Paragraph::highestFontInRange
1481 (pos_type startpos, pos_type endpos, FontSize def_size) const
1483 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1487 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1489 char_type c = d->text_[pos];
1490 if (!lyxrc.rtl_support)
1520 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1526 void Paragraph::setFont(pos_type pos, Font const & font)
1528 LASSERT(pos <= size(), /**/);
1530 // First, reduce font against layout/label font
1531 // Update: The setCharFont() routine in text2.cpp already
1532 // reduces font, so we don't need to do that here. (Asger)
1534 d->fontlist_.set(pos, font);
1538 void Paragraph::makeSameLayout(Paragraph const & par)
1540 d->layout_ = par.d->layout_;
1541 d->params_ = par.d->params_;
1545 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1547 if (isFreeSpacing())
1553 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1554 if (eraseChar(pos, trackChanges))
1560 return count > 0 || pos > 0;
1564 bool Paragraph::hasSameLayout(Paragraph const & par) const
1566 return par.d->layout_ == d->layout_
1567 && d->params_.sameLayout(par.d->params_);
1571 depth_type Paragraph::getDepth() const
1573 return d->params_.depth();
1577 depth_type Paragraph::getMaxDepthAfter() const
1579 if (d->layout_->isEnvironment())
1580 return d->params_.depth() + 1;
1582 return d->params_.depth();
1586 char Paragraph::getAlign() const
1588 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1589 return d->layout_->align;
1591 return d->params_.align();
1595 docstring const & Paragraph::labelString() const
1597 return d->params_.labelString();
1601 // the next two functions are for the manual labels
1602 docstring const Paragraph::getLabelWidthString() const
1604 if (d->layout_->margintype == MARGIN_MANUAL
1605 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1606 return d->params_.labelWidthString();
1608 return _("Senseless with this layout!");
1612 void Paragraph::setLabelWidthString(docstring const & s)
1614 d->params_.labelWidthString(s);
1618 docstring Paragraph::expandLabel(Layout const & layout,
1619 BufferParams const & bparams, bool process_appendix) const
1621 DocumentClass const & tclass = bparams.documentClass();
1622 string const & lang = getParLanguage(bparams)->code();
1623 bool const in_appendix = process_appendix && d->params_.appendix();
1624 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1626 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1627 && !layout.counter.empty())
1628 return tclass.counters().theCounter(layout.counter, lang);
1630 // handle 'inherited level parts' in 'fmt',
1631 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1632 size_t const i = fmt.find('@', 0);
1633 if (i != docstring::npos) {
1634 size_t const j = fmt.find('@', i + 1);
1635 if (j != docstring::npos) {
1636 docstring parent(fmt, i + 1, j - i - 1);
1637 docstring label = from_ascii("??");
1638 if (tclass.hasLayout(parent))
1639 docstring label = expandLabel(tclass[parent], bparams,
1641 fmt = docstring(fmt, 0, i) + label
1642 + docstring(fmt, j + 1, docstring::npos);
1646 return tclass.counters().counterLabel(fmt, lang);
1650 void Paragraph::applyLayout(Layout const & new_layout)
1652 d->layout_ = &new_layout;
1653 LyXAlignment const oldAlign = d->params_.align();
1655 if (!(oldAlign & d->layout_->alignpossible)) {
1656 frontend::Alert::warning(_("Alignment not permitted"),
1657 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1658 d->params_.align(LYX_ALIGN_LAYOUT);
1663 pos_type Paragraph::beginOfBody() const
1665 return d->begin_of_body_;
1669 void Paragraph::setBeginOfBody()
1671 if (d->layout_->labeltype != LABEL_MANUAL) {
1672 d->begin_of_body_ = 0;
1676 // Unroll the first two cycles of the loop
1677 // and remember the previous character to
1678 // remove unnecessary getChar() calls
1680 pos_type end = size();
1681 if (i < end && !isNewline(i)) {
1683 char_type previous_char = 0;
1686 previous_char = d->text_[i];
1687 if (!isNewline(i)) {
1689 while (i < end && previous_char != ' ') {
1694 previous_char = temp;
1700 d->begin_of_body_ = i;
1704 bool Paragraph::forcePlainLayout() const
1706 return inInset().forcePlainLayout();
1710 bool Paragraph::allowParagraphCustomization() const
1712 return inInset().allowParagraphCustomization();
1716 bool Paragraph::usePlainLayout() const
1718 return inInset().usePlainLayout();
1724 // paragraphs inside floats need different alignment tags to avoid
1727 bool noTrivlistCentering(InsetCode code)
1729 return code == FLOAT_CODE
1730 || code == WRAP_CODE
1731 || code == CELL_CODE;
1735 string correction(string const & orig)
1737 if (orig == "flushleft")
1738 return "raggedright";
1739 if (orig == "flushright")
1740 return "raggedleft";
1741 if (orig == "center")
1747 string const corrected_env(string const & suffix, string const & env,
1748 InsetCode code, bool const lastpar)
1750 string output = suffix + "{";
1751 if (noTrivlistCentering(code)) {
1753 // the last paragraph in non-trivlist-aligned
1754 // context is special (to avoid unwanted whitespace)
1755 if (suffix == "\\begin")
1756 return "\\" + correction(env) + "{}";
1759 output += correction(env);
1763 if (suffix == "\\begin")
1769 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1771 if (!contains(str, "\n"))
1772 column += str.size();
1776 column = rsplit(str, tmp, '\n').size();
1783 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1784 odocstream & os, TexRow & texrow,
1785 OutputParams const & runparams) const
1789 if (params_.noindent()) {
1790 os << "\\noindent ";
1794 LyXAlignment const curAlign = params_.align();
1796 if (curAlign == layout_->align)
1800 case LYX_ALIGN_NONE:
1801 case LYX_ALIGN_BLOCK:
1802 case LYX_ALIGN_LAYOUT:
1803 case LYX_ALIGN_SPECIAL:
1805 case LYX_ALIGN_LEFT:
1806 case LYX_ALIGN_RIGHT:
1807 case LYX_ALIGN_CENTER:
1808 if (runparams.moving_arg) {
1815 string const begin_tag = "\\begin";
1816 InsetCode code = ownerCode();
1817 bool const lastpar = runparams.isLastPar;
1820 case LYX_ALIGN_NONE:
1821 case LYX_ALIGN_BLOCK:
1822 case LYX_ALIGN_LAYOUT:
1823 case LYX_ALIGN_SPECIAL:
1825 case LYX_ALIGN_LEFT: {
1827 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1828 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1830 output = corrected_env(begin_tag, "flushright", code, lastpar);
1831 os << from_ascii(output);
1832 adjust_row_column(output, texrow, column);
1834 } case LYX_ALIGN_RIGHT: {
1836 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837 output = corrected_env(begin_tag, "flushright", code, lastpar);
1839 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1840 os << from_ascii(output);
1841 adjust_row_column(output, texrow, column);
1843 } case LYX_ALIGN_CENTER: {
1845 output = corrected_env(begin_tag, "center", code, lastpar);
1846 os << from_ascii(output);
1847 adjust_row_column(output, texrow, column);
1856 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1857 odocstream & os, TexRow & texrow,
1858 OutputParams const & runparams) const
1862 LyXAlignment const curAlign = params_.align();
1864 if (curAlign == layout_->align)
1868 case LYX_ALIGN_NONE:
1869 case LYX_ALIGN_BLOCK:
1870 case LYX_ALIGN_LAYOUT:
1871 case LYX_ALIGN_SPECIAL:
1873 case LYX_ALIGN_LEFT:
1874 case LYX_ALIGN_RIGHT:
1875 case LYX_ALIGN_CENTER:
1876 if (runparams.moving_arg) {
1883 string const end_tag = "\n\\par\\end";
1884 InsetCode code = ownerCode();
1885 bool const lastpar = runparams.isLastPar;
1888 case LYX_ALIGN_NONE:
1889 case LYX_ALIGN_BLOCK:
1890 case LYX_ALIGN_LAYOUT:
1891 case LYX_ALIGN_SPECIAL:
1893 case LYX_ALIGN_LEFT: {
1895 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1896 output = corrected_env(end_tag, "flushleft", code, lastpar);
1898 output = corrected_env(end_tag, "flushright", code, lastpar);
1899 os << from_ascii(output);
1900 adjust_row_column(output, texrow, column);
1902 } case LYX_ALIGN_RIGHT: {
1904 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1905 output = corrected_env(end_tag, "flushright", code, lastpar);
1907 output = corrected_env(end_tag, "flushleft", code, lastpar);
1908 os << from_ascii(output);
1909 adjust_row_column(output, texrow, column);
1911 } case LYX_ALIGN_CENTER: {
1913 output = corrected_env(end_tag, "center", code, lastpar);
1914 os << from_ascii(output);
1915 adjust_row_column(output, texrow, column);
1924 // This one spits out the text of the paragraph
1925 bool Paragraph::latex(BufferParams const & bparams,
1926 Font const & outerfont,
1927 odocstream & os, TexRow & texrow,
1928 OutputParams const & runparams,
1929 int start_pos, int end_pos) const
1931 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1933 bool return_value = false;
1935 bool const allowcust = allowParagraphCustomization();
1937 // FIXME This check should not be needed. Perhaps issue an
1938 // error if it triggers.
1939 Layout const & style = forcePlainLayout() ?
1940 bparams.documentClass().plainLayout() : *d->layout_;
1942 // Current base font for all inherited font changes, without any
1943 // change caused by an individual character, except for the language:
1944 // It is set to the language of the first character.
1945 // As long as we are in the label, this font is the base font of the
1946 // label. Before the first body character it is set to the base font
1950 // Maybe we have to create a optional argument.
1951 pos_type body_pos = beginOfBody();
1952 unsigned int column = 0;
1957 basefont = getLabelFont(bparams, outerfont);
1959 basefont = getLayoutFont(bparams, outerfont);
1962 // Which font is currently active?
1963 Font running_font(basefont);
1964 // Do we have an open font change?
1965 bool open_font = false;
1967 Change runningChange = Change(Change::UNCHANGED);
1969 Encoding const * const prev_encoding = runparams.encoding;
1971 texrow.start(id(), 0);
1973 // if the paragraph is empty, the loop will not be entered at all
1975 if (style.isCommand()) {
1980 column += d->startTeXParParams(bparams, os, texrow,
1984 for (pos_type i = 0; i < size(); ++i) {
1985 // First char in paragraph or after label?
1986 if (i == body_pos) {
1989 column += running_font.latexWriteEndChanges(
1990 os, bparams, runparams,
1991 basefont, basefont);
1994 basefont = getLayoutFont(bparams, outerfont);
1995 running_font = basefont;
1997 column += Changes::latexMarkChange(os, bparams,
1998 runningChange, Change(Change::UNCHANGED));
1999 runningChange = Change(Change::UNCHANGED);
2004 if (style.isCommand()) {
2010 column += d->startTeXParParams(bparams, os,
2015 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2018 if (bparams.outputChanges && runningChange != change) {
2020 column += running_font.latexWriteEndChanges(
2021 os, bparams, runparams, basefont, basefont);
2024 basefont = getLayoutFont(bparams, outerfont);
2025 running_font = basefont;
2027 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2028 runningChange = change;
2031 // do not output text which is marked deleted
2032 // if change tracking output is disabled
2033 if (!bparams.outputChanges && change.deleted()) {
2039 // Fully instantiated font
2040 Font const font = getFont(bparams, i, outerfont);
2042 Font const last_font = running_font;
2044 // Do we need to close the previous font?
2046 (font != running_font ||
2047 font.language() != running_font.language()))
2049 column += running_font.latexWriteEndChanges(
2050 os, bparams, runparams, basefont,
2051 (i == body_pos-1) ? basefont : font);
2052 running_font = basefont;
2056 // close babel's font environment before opening CJK.
2057 if (!running_font.language()->babel().empty() &&
2058 font.language()->encoding()->package() == Encoding::CJK) {
2059 string end_tag = subst(lyxrc.language_command_end,
2061 running_font.language()->babel());
2062 os << from_ascii(end_tag);
2063 column += end_tag.length();
2066 // Switch file encoding if necessary (and allowed)
2067 if (!runparams.verbatim &&
2068 runparams.encoding->package() != Encoding::none &&
2069 font.language()->encoding()->package() != Encoding::none) {
2070 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2071 runparams, *(font.language()->encoding()));
2072 if (enc_switch.first) {
2073 column += enc_switch.second;
2074 runparams.encoding = font.language()->encoding();
2078 char_type const c = d->text_[i];
2080 // Do we need to change font?
2081 if ((font != running_font ||
2082 font.language() != running_font.language()) &&
2085 odocstringstream ods;
2086 column += font.latexWriteStartChanges(ods, bparams,
2087 runparams, basefont,
2089 running_font = font;
2091 docstring fontchange = ods.str();
2092 // check whether the fontchange ends with a \\textcolor
2093 // modifier and the text starts with a space (bug 4473)
2094 docstring const last_modifier = rsplit(fontchange, '\\');
2095 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2096 os << fontchange << from_ascii("{}");
2097 // check if the fontchange ends with a trailing blank
2098 // (like "\small " (see bug 3382)
2099 else if (suffixIs(fontchange, ' ') && c == ' ')
2100 os << fontchange.substr(0, fontchange.size() - 1)
2101 << from_ascii("{}");
2106 // FIXME: think about end_pos implementation...
2107 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2108 // FIXME: integrate this case in latexSpecialChar
2109 // Do not print the separation of the optional argument
2110 // if style.pass_thru is false. This works because
2111 // latexSpecialChar ignores spaces if
2112 // style.pass_thru is false.
2113 if (i != body_pos - 1) {
2114 if (d->simpleTeXBlanks(
2115 runparams, os, texrow,
2116 i, column, font, style)) {
2117 // A surrogate pair was output. We
2118 // must not call latexSpecialChar
2119 // in this iteration, since it would output
2120 // the combining character again.
2127 OutputParams rp = runparams;
2128 rp.free_spacing = style.free_spacing;
2129 rp.local_font = &font;
2130 rp.intitle = style.intitle;
2132 // Two major modes: LaTeX or plain
2133 // Handle here those cases common to both modes
2134 // and then split to handle the two modes separately.
2135 if (c == META_INSET) {
2136 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2137 d->latexInset(bparams, os,
2138 texrow, rp, running_font,
2139 basefont, outerfont, open_font,
2140 runningChange, style, i, column);
2143 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2145 d->latexSpecialChar(os, rp, running_font, runningChange,
2147 } catch (EncodingException & e) {
2148 if (runparams.dryrun) {
2149 os << "<" << _("LyX Warning: ")
2150 << _("uncodable character") << " '";
2154 // add location information and throw again.
2163 // Set the encoding to that returned from latexSpecialChar (see
2164 // comment for encoding member in OutputParams.h)
2165 runparams.encoding = rp.encoding;
2168 // If we have an open font definition, we have to close it
2170 #ifdef FIXED_LANGUAGE_END_DETECTION
2173 .latexWriteEndChanges(os, bparams, runparams,
2175 next_->getFont(bparams, 0, outerfont));
2177 running_font.latexWriteEndChanges(os, bparams,
2178 runparams, basefont, basefont);
2181 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2182 //FIXME: there as we start another \selectlanguage with the next paragraph if
2183 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2184 running_font.latexWriteEndChanges(os, bparams, runparams,
2185 basefont, basefont);
2189 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2191 // Needed if there is an optional argument but no contents.
2192 if (body_pos > 0 && body_pos == size()) {
2194 return_value = false;
2197 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams))
2198 runparams.encoding = prev_encoding;
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();
3026 docstring_list suggestions;
3027 for (pos_type pos = 0; pos < n; ++pos) {
3028 if (isWordSeparator(pos))
3030 pos_type from = pos;
3031 locateWord(from, pos, WHOLE_WORD);
3032 if (pos - from >= 6) {
3033 docstring word = asString(from, pos, AS_STR_NONE);
3034 d->words_.insert(word);
3036 if (lyxrc.spellcheck_continuously
3037 && spellCheck(from, pos, wl, suggestions)) {
3038 for (size_t i = 0; i != suggestions.size(); ++i)
3039 d->words_.insert(suggestions[i]);
3045 void Paragraph::registerWords()
3047 Private::Words::const_iterator it;
3048 WordList & wl = theWordList();
3049 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3054 void Paragraph::updateWords()
3062 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3063 docstring_list & suggestions, bool do_suggestion) const
3065 SpellChecker * speller = theSpellChecker();
3069 locateWord(from, to, WHOLE_WORD);
3070 if (from == to || from >= pos_type(d->text_.size()))
3073 docstring word = asString(from, to, AS_STR_INSETS);
3074 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3075 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3076 : lyxrc.spellchecker_alt_lang;
3077 wl = WordLangTuple(word, lang_code);
3078 SpellChecker::Result res = speller->check(wl);
3079 // Just ignore any error that the spellchecker reports.
3080 // FIXME: we should through out an exception and catch it in the GUI to
3081 // display the error.
3082 if (!speller->error().empty())
3085 bool const misspelled = res != SpellChecker::OK
3086 && res != SpellChecker::IGNORED_WORD;
3088 if (lyxrc.spellcheck_continuously)
3089 d->fontlist_.setMisspelled(from, to, misspelled);
3091 if (misspelled && do_suggestion)
3092 speller->suggest(wl, suggestions);
3094 suggestions.clear();
3100 bool Paragraph::isMisspelled(pos_type pos) const
3102 pos_type from = pos;
3105 docstring_list suggestions;
3106 return spellCheck(from, to, wl, suggestions, false);