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 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::allowParagraphCustomization() const
1706 return inInset().allowParagraphCustomization();
1710 bool Paragraph::usePlainLayout() const
1712 return inInset().usePlainLayout();
1718 // paragraphs inside floats need different alignment tags to avoid
1721 bool noTrivlistCentering(InsetCode code)
1723 return code == FLOAT_CODE
1724 || code == WRAP_CODE
1725 || code == CELL_CODE;
1729 string correction(string const & orig)
1731 if (orig == "flushleft")
1732 return "raggedright";
1733 if (orig == "flushright")
1734 return "raggedleft";
1735 if (orig == "center")
1741 string const corrected_env(string const & suffix, string const & env,
1742 InsetCode code, bool const lastpar)
1744 string output = suffix + "{";
1745 if (noTrivlistCentering(code)) {
1747 // the last paragraph in non-trivlist-aligned
1748 // context is special (to avoid unwanted whitespace)
1749 if (suffix == "\\begin")
1750 return "\\" + correction(env) + "{}";
1753 output += correction(env);
1757 if (suffix == "\\begin")
1763 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1765 if (!contains(str, "\n"))
1766 column += str.size();
1770 column = rsplit(str, tmp, '\n').size();
1777 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1778 odocstream & os, TexRow & texrow,
1779 OutputParams const & runparams) const
1783 if (params_.noindent()) {
1784 os << "\\noindent ";
1788 LyXAlignment const curAlign = params_.align();
1790 if (curAlign == layout_->align)
1794 case LYX_ALIGN_NONE:
1795 case LYX_ALIGN_BLOCK:
1796 case LYX_ALIGN_LAYOUT:
1797 case LYX_ALIGN_SPECIAL:
1799 case LYX_ALIGN_LEFT:
1800 case LYX_ALIGN_RIGHT:
1801 case LYX_ALIGN_CENTER:
1802 if (runparams.moving_arg) {
1809 string const begin_tag = "\\begin";
1810 InsetCode code = ownerCode();
1811 bool const lastpar = runparams.isLastPar;
1814 case LYX_ALIGN_NONE:
1815 case LYX_ALIGN_BLOCK:
1816 case LYX_ALIGN_LAYOUT:
1817 case LYX_ALIGN_SPECIAL:
1819 case LYX_ALIGN_LEFT: {
1821 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1822 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1824 output = corrected_env(begin_tag, "flushright", code, lastpar);
1825 os << from_ascii(output);
1826 adjust_row_column(output, texrow, column);
1828 } case LYX_ALIGN_RIGHT: {
1830 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1831 output = corrected_env(begin_tag, "flushright", code, lastpar);
1833 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1834 os << from_ascii(output);
1835 adjust_row_column(output, texrow, column);
1837 } case LYX_ALIGN_CENTER: {
1839 output = corrected_env(begin_tag, "center", code, lastpar);
1840 os << from_ascii(output);
1841 adjust_row_column(output, texrow, column);
1850 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1851 odocstream & os, TexRow & texrow,
1852 OutputParams const & runparams) const
1856 LyXAlignment const curAlign = params_.align();
1858 if (curAlign == layout_->align)
1862 case LYX_ALIGN_NONE:
1863 case LYX_ALIGN_BLOCK:
1864 case LYX_ALIGN_LAYOUT:
1865 case LYX_ALIGN_SPECIAL:
1867 case LYX_ALIGN_LEFT:
1868 case LYX_ALIGN_RIGHT:
1869 case LYX_ALIGN_CENTER:
1870 if (runparams.moving_arg) {
1877 string const end_tag = "\n\\par\\end";
1878 InsetCode code = ownerCode();
1879 bool const lastpar = runparams.isLastPar;
1882 case LYX_ALIGN_NONE:
1883 case LYX_ALIGN_BLOCK:
1884 case LYX_ALIGN_LAYOUT:
1885 case LYX_ALIGN_SPECIAL:
1887 case LYX_ALIGN_LEFT: {
1889 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1890 output = corrected_env(end_tag, "flushleft", code, lastpar);
1892 output = corrected_env(end_tag, "flushright", code, lastpar);
1893 os << from_ascii(output);
1894 adjust_row_column(output, texrow, column);
1896 } case LYX_ALIGN_RIGHT: {
1898 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1899 output = corrected_env(end_tag, "flushright", code, lastpar);
1901 output = corrected_env(end_tag, "flushleft", code, lastpar);
1902 os << from_ascii(output);
1903 adjust_row_column(output, texrow, column);
1905 } case LYX_ALIGN_CENTER: {
1907 output = corrected_env(end_tag, "center", code, lastpar);
1908 os << from_ascii(output);
1909 adjust_row_column(output, texrow, column);
1918 // This one spits out the text of the paragraph
1919 bool Paragraph::latex(BufferParams const & bparams,
1920 Font const & outerfont,
1921 odocstream & os, TexRow & texrow,
1922 OutputParams const & runparams,
1923 int start_pos, int end_pos) const
1925 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1927 bool return_value = false;
1929 bool const allowcust = allowParagraphCustomization();
1931 // FIXME This check should not be needed. Perhaps issue an
1932 // error if it triggers.
1933 Layout const & style = inInset().forcePlainLayout() ?
1934 bparams.documentClass().plainLayout() : *d->layout_;
1936 // Current base font for all inherited font changes, without any
1937 // change caused by an individual character, except for the language:
1938 // It is set to the language of the first character.
1939 // As long as we are in the label, this font is the base font of the
1940 // label. Before the first body character it is set to the base font
1944 // Maybe we have to create a optional argument.
1945 pos_type body_pos = beginOfBody();
1946 unsigned int column = 0;
1951 basefont = getLabelFont(bparams, outerfont);
1953 basefont = getLayoutFont(bparams, outerfont);
1956 // Which font is currently active?
1957 Font running_font(basefont);
1958 // Do we have an open font change?
1959 bool open_font = false;
1961 Change runningChange = Change(Change::UNCHANGED);
1963 Encoding const * const prev_encoding = runparams.encoding;
1965 texrow.start(id(), 0);
1967 // if the paragraph is empty, the loop will not be entered at all
1969 if (style.isCommand()) {
1974 column += d->startTeXParParams(bparams, os, texrow,
1978 for (pos_type i = 0; i < size(); ++i) {
1979 // First char in paragraph or after label?
1980 if (i == body_pos) {
1983 column += running_font.latexWriteEndChanges(
1984 os, bparams, runparams,
1985 basefont, basefont);
1988 basefont = getLayoutFont(bparams, outerfont);
1989 running_font = basefont;
1991 column += Changes::latexMarkChange(os, bparams,
1992 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, change);
2022 runningChange = change;
2025 // do not output text which is marked deleted
2026 // if change tracking output is disabled
2027 if (!bparams.outputChanges && change.deleted()) {
2033 // Fully instantiated font
2034 Font const font = getFont(bparams, i, outerfont);
2036 Font const last_font = running_font;
2038 // Do we need to close the previous font?
2040 (font != running_font ||
2041 font.language() != running_font.language()))
2043 column += running_font.latexWriteEndChanges(
2044 os, bparams, runparams, basefont,
2045 (i == body_pos-1) ? basefont : font);
2046 running_font = basefont;
2050 // close babel's font environment before opening CJK.
2051 if (!running_font.language()->babel().empty() &&
2052 font.language()->encoding()->package() == Encoding::CJK) {
2053 string end_tag = subst(lyxrc.language_command_end,
2055 running_font.language()->babel());
2056 os << from_ascii(end_tag);
2057 column += end_tag.length();
2060 // Switch file encoding if necessary (and allowed)
2061 if (!runparams.verbatim &&
2062 runparams.encoding->package() != Encoding::none &&
2063 font.language()->encoding()->package() != Encoding::none) {
2064 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2065 runparams, *(font.language()->encoding()));
2066 if (enc_switch.first) {
2067 column += enc_switch.second;
2068 runparams.encoding = font.language()->encoding();
2072 char_type const c = d->text_[i];
2074 // Do we need to change font?
2075 if ((font != running_font ||
2076 font.language() != running_font.language()) &&
2079 odocstringstream ods;
2080 column += font.latexWriteStartChanges(ods, bparams,
2081 runparams, basefont,
2083 running_font = font;
2085 docstring fontchange = ods.str();
2086 // check whether the fontchange ends with a \\textcolor
2087 // modifier and the text starts with a space (bug 4473)
2088 docstring const last_modifier = rsplit(fontchange, '\\');
2089 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2090 os << fontchange << from_ascii("{}");
2091 // check if the fontchange ends with a trailing blank
2092 // (like "\small " (see bug 3382)
2093 else if (suffixIs(fontchange, ' ') && c == ' ')
2094 os << fontchange.substr(0, fontchange.size() - 1)
2095 << from_ascii("{}");
2100 // FIXME: think about end_pos implementation...
2101 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2102 // FIXME: integrate this case in latexSpecialChar
2103 // Do not print the separation of the optional argument
2104 // if style.pass_thru is false. This works because
2105 // latexSpecialChar ignores spaces if
2106 // style.pass_thru is false.
2107 if (i != body_pos - 1) {
2108 if (d->simpleTeXBlanks(
2109 runparams, os, texrow,
2110 i, column, font, style)) {
2111 // A surrogate pair was output. We
2112 // must not call latexSpecialChar
2113 // in this iteration, since it would output
2114 // the combining character again.
2121 OutputParams rp = runparams;
2122 rp.free_spacing = style.free_spacing;
2123 rp.local_font = &font;
2124 rp.intitle = style.intitle;
2126 // Two major modes: LaTeX or plain
2127 // Handle here those cases common to both modes
2128 // and then split to handle the two modes separately.
2129 if (c == META_INSET) {
2130 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2131 d->latexInset(bparams, os,
2132 texrow, rp, running_font,
2133 basefont, outerfont, open_font,
2134 runningChange, style, i, column);
2137 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2139 d->latexSpecialChar(os, rp, running_font, runningChange,
2141 } catch (EncodingException & e) {
2142 if (runparams.dryrun) {
2143 os << "<" << _("LyX Warning: ")
2144 << _("uncodable character") << " '";
2148 // add location information and throw again.
2157 // Set the encoding to that returned from latexSpecialChar (see
2158 // comment for encoding member in OutputParams.h)
2159 runparams.encoding = rp.encoding;
2162 // If we have an open font definition, we have to close it
2164 #ifdef FIXED_LANGUAGE_END_DETECTION
2167 .latexWriteEndChanges(os, bparams, runparams,
2169 next_->getFont(bparams, 0, outerfont));
2171 running_font.latexWriteEndChanges(os, bparams,
2172 runparams, basefont, basefont);
2175 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2176 //FIXME: there as we start another \selectlanguage with the next paragraph if
2177 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2178 running_font.latexWriteEndChanges(os, bparams, runparams,
2179 basefont, basefont);
2183 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2185 // Needed if there is an optional argument but no contents.
2186 if (body_pos > 0 && body_pos == size()) {
2188 return_value = false;
2191 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams))
2192 runparams.encoding = prev_encoding;
2194 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2195 return return_value;
2199 bool Paragraph::emptyTag() const
2201 for (pos_type i = 0; i < size(); ++i) {
2202 if (Inset const * inset = getInset(i)) {
2203 InsetCode lyx_code = inset->lyxCode();
2204 // FIXME testing like that is wrong. What is
2206 if (lyx_code != TOC_CODE &&
2207 lyx_code != INCLUDE_CODE &&
2208 lyx_code != GRAPHICS_CODE &&
2209 lyx_code != ERT_CODE &&
2210 lyx_code != LISTINGS_CODE &&
2211 lyx_code != FLOAT_CODE &&
2212 lyx_code != TABULAR_CODE) {
2216 char_type c = d->text_[i];
2217 if (c != ' ' && c != '\t')
2225 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2228 for (pos_type i = 0; i < size(); ++i) {
2229 if (Inset const * inset = getInset(i)) {
2230 InsetCode lyx_code = inset->lyxCode();
2231 if (lyx_code == LABEL_CODE) {
2232 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2233 docstring const & id = il->getParam("name");
2234 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2242 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2246 for (i = 0; i < size(); ++i) {
2247 if (Inset const * inset = getInset(i)) {
2248 inset->docbook(os, runparams);
2250 char_type c = d->text_[i];
2253 os << sgml::escapeChar(c);
2260 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2264 for (i = 0; i < size(); ++i) {
2265 if (Inset const * inset = getInset(i)) {
2266 inset->xhtml(os, runparams);
2268 char_type c = d->text_[i];
2271 os << html::escapeChar(c);
2278 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2281 pos_type size = text_.size();
2282 for (pos_type i = initial; i < size; ++i) {
2283 Font font = owner_->getFont(buf.params(), i, outerfont);
2284 if (text_[i] == META_INSET)
2286 if (i != initial && font != font_old)
2295 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2297 OutputParams const & runparams,
2298 Font const & outerfont,
2299 pos_type initial) const
2301 bool emph_flag = false;
2303 Layout const & style = *d->layout_;
2305 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2307 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2310 // parsing main loop
2311 for (pos_type i = initial; i < size(); ++i) {
2312 Font font = getFont(buf.params(), i, outerfont);
2314 // handle <emphasis> tag
2315 if (font_old.emph() != font.fontInfo().emph()) {
2316 if (font.fontInfo().emph() == FONT_ON) {
2319 } else if (i != initial) {
2320 os << "</emphasis>";
2325 if (Inset const * inset = getInset(i)) {
2326 inset->docbook(os, runparams);
2328 char_type c = d->text_[i];
2330 if (style.pass_thru)
2333 os << sgml::escapeChar(c);
2335 font_old = font.fontInfo();
2339 os << "</emphasis>";
2342 if (style.free_spacing)
2344 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2349 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2351 OutputParams const & runparams,
2352 Font const & outerfont,
2353 pos_type initial) const
2357 // FIXME We really need to manage the tag nesting here.
2358 // Probably in the same sort of way as in output_xhtml.
2359 bool emph_flag = false;
2360 bool bold_flag = false;
2361 std::string closing_tag;
2363 Layout const & style = *d->layout_;
2365 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2367 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2370 // parsing main loop
2371 for (pos_type i = initial; i < size(); ++i) {
2372 Font font = getFont(buf.params(), i, outerfont);
2375 if (font_old.emph() != font.fontInfo().emph()) {
2376 if (font.fontInfo().emph() == FONT_ON) {
2379 } else if (emph_flag && i != initial) {
2385 if (font_old.series() != font.fontInfo().series()) {
2386 if (font.fontInfo().series() == BOLD_SERIES) {
2389 } else if (bold_flag && i != initial) {
2394 // FIXME Other such tags?
2396 if (Inset const * inset = getInset(i)) {
2397 retval += inset->xhtml(os, runparams);
2399 char_type c = d->text_[i];
2401 if (style.pass_thru)
2403 else if (c == '-') {
2406 if (j < size() && d->text_[j] == '-') {
2408 if (j < size() && d->text_[j] == '-') {
2409 str += from_ascii("—");
2412 str += from_ascii("–");
2420 os << html::escapeChar(c);
2422 font_old = font.fontInfo();
2425 // FIXME This could be out of order. See above.
2435 bool Paragraph::isHfill(pos_type pos) const
2437 Inset const * inset = getInset(pos);
2438 return inset && (inset->lyxCode() == SPACE_CODE &&
2439 inset->isStretchableSpace());
2443 bool Paragraph::isNewline(pos_type pos) const
2445 Inset const * inset = getInset(pos);
2446 return inset && inset->lyxCode() == NEWLINE_CODE;
2450 bool Paragraph::isLineSeparator(pos_type pos) const
2452 char_type const c = d->text_[pos];
2453 if (isLineSeparatorChar(c))
2455 Inset const * inset = getInset(pos);
2456 return inset && inset->isLineSeparator();
2460 bool Paragraph::isWordSeparator(pos_type pos) const
2462 if (Inset const * inset = getInset(pos))
2463 return !inset->isLetter();
2464 char_type const c = d->text_[pos];
2465 // We want to pass the ' and escape chars to the spellchecker
2466 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2467 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2472 bool Paragraph::isChar(pos_type pos) const
2474 if (Inset const * inset = getInset(pos))
2475 return inset->isChar();
2476 char_type const c = d->text_[pos];
2477 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2481 bool Paragraph::isSpace(pos_type pos) const
2483 if (Inset const * inset = getInset(pos))
2484 return inset->isSpace();
2485 char_type const c = d->text_[pos];
2486 return lyx::isSpace(c);
2491 Paragraph::getParLanguage(BufferParams const & bparams) const
2494 return getFirstFontSettings(bparams).language();
2495 // FIXME: we should check the prev par as well (Lgb)
2496 return bparams.language;
2500 bool Paragraph::isRTL(BufferParams const & bparams) const
2502 return lyxrc.rtl_support
2503 && getParLanguage(bparams)->rightToLeft()
2504 && !inInset().getLayout().forceLTR();
2508 void Paragraph::changeLanguage(BufferParams const & bparams,
2509 Language const * from, Language const * to)
2511 // change language including dummy font change at the end
2512 for (pos_type i = 0; i <= size(); ++i) {
2513 Font font = getFontSettings(bparams, i);
2514 if (font.language() == from) {
2515 font.setLanguage(to);
2522 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2524 Language const * doc_language = bparams.language;
2525 FontList::const_iterator cit = d->fontlist_.begin();
2526 FontList::const_iterator end = d->fontlist_.end();
2528 for (; cit != end; ++cit)
2529 if (cit->font().language() != ignore_language &&
2530 cit->font().language() != latex_language &&
2531 cit->font().language() != doc_language)
2537 docstring Paragraph::asString(int options) const
2539 return asString(0, size(), options);
2543 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2545 odocstringstream os;
2548 && options & AS_STR_LABEL
2549 && !d->params_.labelString().empty())
2550 os << d->params_.labelString() << ' ';
2552 for (pos_type i = beg; i < end; ++i) {
2553 char_type const c = d->text_[i];
2554 if (isPrintable(c) || c == '\t'
2555 || (c == '\n' && (options & AS_STR_NEWLINES)))
2557 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2558 getInset(i)->tocString(os);
2559 if (getInset(i)->asInsetMath())
2568 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2570 odocstringstream os;
2573 && options & AS_STR_LABEL
2574 && !d->params_.labelString().empty())
2575 os << d->params_.labelString() << ' ';
2577 for (pos_type i = beg; i < end; ++i) {
2578 char_type const c = d->text_[i];
2579 if (isPrintable(c) || c == '\t'
2580 || (c == '\n' && (options & AS_STR_NEWLINES)))
2582 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2583 getInset(i)->plaintext(os, runparams);
2591 void Paragraph::setInsetOwner(Inset const * inset)
2593 d->inset_owner_ = inset;
2597 int Paragraph::id() const
2603 Layout const & Paragraph::layout() const
2609 void Paragraph::setLayout(Layout const & layout)
2611 d->layout_ = &layout;
2615 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2617 setLayout(tc.defaultLayout());
2621 void Paragraph::setPlainLayout(DocumentClass const & tc)
2623 setLayout(tc.plainLayout());
2627 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2629 if (usePlainLayout())
2630 setPlainLayout(tclass);
2632 setDefaultLayout(tclass);
2636 Inset const & Paragraph::inInset() const
2638 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2639 _("Memory problem"), _("Paragraph not properly initialized")));
2640 return *d->inset_owner_;
2644 ParagraphParameters & Paragraph::params()
2650 ParagraphParameters const & Paragraph::params() const
2656 bool Paragraph::isFreeSpacing() const
2658 if (d->layout_->free_spacing)
2660 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2664 bool Paragraph::allowEmpty() const
2666 if (d->layout_->keepempty)
2668 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2672 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2674 if (!Encodings::isArabicChar(c))
2677 char_type prev_char = ' ';
2678 char_type next_char = ' ';
2680 for (pos_type i = pos - 1; i >= 0; --i) {
2681 char_type const par_char = d->text_[i];
2682 if (!Encodings::isArabicComposeChar(par_char)) {
2683 prev_char = par_char;
2688 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2689 char_type const par_char = d->text_[i];
2690 if (!Encodings::isArabicComposeChar(par_char)) {
2691 next_char = par_char;
2696 if (Encodings::isArabicChar(next_char)) {
2697 if (Encodings::isArabicChar(prev_char) &&
2698 !Encodings::isArabicSpecialChar(prev_char))
2699 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2701 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2703 if (Encodings::isArabicChar(prev_char) &&
2704 !Encodings::isArabicSpecialChar(prev_char))
2705 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2707 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2712 int Paragraph::checkBiblio(Buffer const & buffer)
2715 // This is getting more and more a mess. ...We really should clean
2716 // up this bibitem issue for 1.6. See also bug 2743.
2718 // Add bibitem insets if necessary
2719 if (d->layout_->labeltype != LABEL_BIBLIO)
2722 bool hasbibitem = !d->insetlist_.empty()
2723 // Insist on it being in pos 0
2724 && d->text_[0] == META_INSET
2725 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2727 bool track_changes = buffer.params().trackChanges;
2732 // remove a bibitem in pos != 0
2733 // restore it later in pos 0 if necessary
2734 // (e.g. if a user inserts contents _before_ the item)
2735 // we're assuming there's only one of these, which there
2737 int erasedInsetPosition = -1;
2738 InsetList::iterator it = d->insetlist_.begin();
2739 InsetList::iterator end = d->insetlist_.end();
2740 for (; it != end; ++it)
2741 if (it->inset->lyxCode() == BIBITEM_CODE
2743 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2744 oldkey = olditem->getParam("key");
2745 oldlabel = olditem->getParam("label");
2746 erasedInsetPosition = it->pos;
2747 eraseChar(erasedInsetPosition, track_changes);
2751 // There was an InsetBibitem at the beginning, and we didn't
2752 // have to erase one.
2753 if (hasbibitem && erasedInsetPosition < 0)
2756 // There was an InsetBibitem at the beginning and we did have to
2757 // erase one. So we give its properties to the beginning inset.
2759 InsetBibitem * inset =
2760 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2761 if (!oldkey.empty())
2762 inset->setParam("key", oldkey);
2763 inset->setParam("label", oldlabel);
2764 return -erasedInsetPosition;
2767 // There was no inset at the beginning, so we need to create one with
2768 // the key and label of the one we erased.
2769 InsetBibitem * inset =
2770 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2771 // restore values of previously deleted item in this par.
2772 if (!oldkey.empty())
2773 inset->setParam("key", oldkey);
2774 inset->setParam("label", oldlabel);
2775 insertInset(0, static_cast<Inset *>(inset),
2776 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2782 void Paragraph::checkAuthors(AuthorList const & authorList)
2784 d->changes_.checkAuthors(authorList);
2788 bool Paragraph::isChanged(pos_type pos) const
2790 return lookupChange(pos).changed();
2794 bool Paragraph::isInserted(pos_type pos) const
2796 return lookupChange(pos).inserted();
2800 bool Paragraph::isDeleted(pos_type pos) const
2802 return lookupChange(pos).deleted();
2806 InsetList const & Paragraph::insetList() const
2808 return d->insetlist_;
2812 void Paragraph::setBuffer(Buffer & b)
2814 d->insetlist_.setBuffer(b);
2818 Inset * Paragraph::releaseInset(pos_type pos)
2820 Inset * inset = d->insetlist_.release(pos);
2821 /// does not honour change tracking!
2822 eraseChar(pos, false);
2827 Inset * Paragraph::getInset(pos_type pos)
2829 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2830 ? d->insetlist_.get(pos) : 0;
2834 Inset const * Paragraph::getInset(pos_type pos) const
2836 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2837 ? d->insetlist_.get(pos) : 0;
2841 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2842 pos_type & right, TextCase action)
2844 // process sequences of modified characters; in change
2845 // tracking mode, this approach results in much better
2846 // usability than changing case on a char-by-char basis
2849 bool const trackChanges = bparams.trackChanges;
2851 bool capitalize = true;
2853 for (; pos < right; ++pos) {
2854 char_type oldChar = d->text_[pos];
2855 char_type newChar = oldChar;
2857 // ignore insets and don't play with deleted text!
2858 if (oldChar != META_INSET && !isDeleted(pos)) {
2860 case text_lowercase:
2861 newChar = lowercase(oldChar);
2863 case text_capitalization:
2865 newChar = uppercase(oldChar);
2869 case text_uppercase:
2870 newChar = uppercase(oldChar);
2875 if (isWordSeparator(pos) || isDeleted(pos)) {
2876 // permit capitalization again
2880 if (oldChar != newChar) {
2882 if (pos != right - 1)
2884 // step behind the changing area
2888 int erasePos = pos - changes.size();
2889 for (size_t i = 0; i < changes.size(); i++) {
2890 insertChar(pos, changes[i],
2891 getFontSettings(bparams,
2894 if (!eraseChar(erasePos, trackChanges)) {
2897 ++right; // expand selection
2905 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2906 pos_type pos, bool del) const
2908 int const strsize = str.length();
2910 pos_type const parsize = d->text_.size();
2911 for (i = 0; pos + i < parsize; ++i) {
2914 if (cs && str[i] != d->text_[pos + i])
2916 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2918 if (!del && isDeleted(pos + i))
2925 // if necessary, check whether string matches word
2927 if (pos > 0 && !isWordSeparator(pos - 1))
2929 if (pos + strsize < parsize
2930 && !isWordSeparator(pos + strsize))
2938 char_type Paragraph::getChar(pos_type pos) const
2940 return d->text_[pos];
2944 pos_type Paragraph::size() const
2946 return d->text_.size();
2950 bool Paragraph::empty() const
2952 return d->text_.empty();
2956 bool Paragraph::isInset(pos_type pos) const
2958 return d->text_[pos] == META_INSET;
2962 bool Paragraph::isSeparator(pos_type pos) const
2964 //FIXME: Are we sure this can be the only separator?
2965 return d->text_[pos] == ' ';
2969 void Paragraph::deregisterWords()
2971 Private::Words::const_iterator it;
2972 WordList & wl = theWordList();
2973 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2979 void Paragraph::locateWord(pos_type & from, pos_type & to,
2980 word_location const loc) const
2983 case WHOLE_WORD_STRICT:
2984 if (from == 0 || from == size()
2985 || isWordSeparator(from)
2986 || isWordSeparator(from - 1)) {
2990 // no break here, we go to the next
2993 // If we are already at the beginning of a word, do nothing
2994 if (!from || isWordSeparator(from - 1))
2996 // no break here, we go to the next
2999 // always move the cursor to the beginning of previous word
3000 while (from && !isWordSeparator(from - 1))
3004 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3007 // no need to move the 'from' cursor
3011 while (to < size() && !isWordSeparator(to))
3016 void Paragraph::collectWords()
3018 pos_type n = size();
3020 docstring_list suggestions;
3021 for (pos_type pos = 0; pos < n; ++pos) {
3022 if (isWordSeparator(pos))
3024 pos_type from = pos;
3025 locateWord(from, pos, WHOLE_WORD);
3026 if (pos - from >= 6) {
3027 docstring word = asString(from, pos, AS_STR_NONE);
3028 d->words_.insert(word);
3030 if (lyxrc.spellcheck_continuously
3031 && spellCheck(from, pos, wl, suggestions)) {
3032 for (size_t i = 0; i != suggestions.size(); ++i)
3033 d->words_.insert(suggestions[i]);
3039 void Paragraph::registerWords()
3041 Private::Words::const_iterator it;
3042 WordList & wl = theWordList();
3043 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3048 void Paragraph::updateWords()
3056 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3057 docstring_list & suggestions, bool do_suggestion) const
3059 SpellChecker * speller = theSpellChecker();
3063 locateWord(from, to, WHOLE_WORD);
3064 if (from == to || from >= pos_type(d->text_.size()))
3067 docstring word = asString(from, to, AS_STR_INSETS);
3068 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3069 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3070 : lyxrc.spellchecker_alt_lang;
3071 wl = WordLangTuple(word, lang_code);
3072 SpellChecker::Result res = speller->check(wl);
3073 // Just ignore any error that the spellchecker reports.
3074 // FIXME: we should through out an exception and catch it in the GUI to
3075 // display the error.
3076 if (!speller->error().empty())
3079 bool const misspelled = res != SpellChecker::OK
3080 && res != SpellChecker::IGNORED_WORD;
3082 if (lyxrc.spellcheck_continuously)
3083 d->fontlist_.setMisspelled(from, to, misspelled);
3085 if (misspelled && do_suggestion)
3086 speller->suggest(wl, suggestions);
3088 suggestions.clear();
3094 bool Paragraph::isMisspelled(pos_type pos) const
3096 pos_type from = pos;
3099 docstring_list suggestions;
3100 return spellCheck(from, to, wl, suggestions, false);