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/Messages.h"
62 #include "support/textutils.h"
68 using namespace lyx::support;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 class Paragraph::Private
87 Private(Paragraph * owner, Layout const & layout);
88 /// "Copy constructor"
89 Private(Private const &, Paragraph * owner);
90 /// Copy constructor from \p beg to \p end
91 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
94 void insertChar(pos_type pos, char_type c, Change const & change);
96 /// Output the surrogate pair formed by \p c and \p next to \p os.
97 /// \return the number of characters written.
98 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
101 /// Output a space in appropriate formatting (or a surrogate pair
102 /// if the next character is a combining character).
103 /// \return whether a surrogate pair was output.
104 bool simpleTeXBlanks(OutputParams const &,
105 odocstream &, TexRow & texrow,
107 unsigned int & column,
109 Layout const & style);
111 /// Output consecutive unicode chars, belonging to the same script as
112 /// specified by the latex macro \p ltx, to \p os starting from \p i.
113 /// \return the number of characters written.
114 int writeScriptChars(odocstream & os, docstring const & ltx,
115 Change const &, Encoding const &, pos_type & i);
117 /// This could go to ParagraphParameters if we want to.
118 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
119 OutputParams const &) const;
121 /// This could go to ParagraphParameters if we want to.
122 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
123 OutputParams const &) const;
126 void latexInset(BufferParams const &,
128 TexRow & texrow, OutputParams &,
131 Font const & outerfont,
133 Change & running_change,
134 Layout const & style,
136 unsigned int & column);
139 void latexSpecialChar(
141 OutputParams const & runparams,
142 Font const & running_font,
143 Change const & running_change,
144 Layout const & style,
146 unsigned int & column);
153 unsigned int & column);
155 bool latexSpecialTypewriter(
159 unsigned int & column);
161 bool latexSpecialPhrase(
164 unsigned int & column,
165 OutputParams const & runparams);
168 void validate(LaTeXFeatures & features,
169 Layout const & layout) const;
171 /// Checks if the paragraph contains only text and no inset or font change.
172 bool onlyText(Buffer const & buf, Font const & outerfont,
173 pos_type initial) const;
175 /// match a string against a particular point in the paragraph
176 bool isTextAt(string const & str, pos_type pos) const;
178 /// Which Paragraph owns us?
182 Inset const * inset_owner_;
190 static unsigned int paragraph_id;
192 ParagraphParameters params_;
194 /// for recording and looking up changes
198 InsetList insetlist_;
201 pos_type begin_of_body_;
203 typedef docstring TextContainer;
207 typedef std::set<docstring> Words;
211 Layout const * layout_;
215 // Initialization of the counter for the paragraph id's,
216 unsigned int Paragraph::Private::paragraph_id = 0;
220 struct special_phrase {
226 special_phrase const special_phrases[] = {
227 { "LyX", from_ascii("\\LyX{}"), false },
228 { "TeX", from_ascii("\\TeX{}"), true },
229 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
230 { "LaTeX", from_ascii("\\LaTeX{}"), true },
233 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
238 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
239 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
241 id_ = paragraph_id++;
246 Paragraph::Private::Private(Private const & p, Paragraph * owner)
247 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
248 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
249 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
252 id_ = paragraph_id++;
256 Paragraph::Private::Private(Private const & p, Paragraph * owner,
257 pos_type beg, pos_type end)
258 : owner_(owner), inset_owner_(p.inset_owner_),
259 params_(p.params_), changes_(p.changes_),
260 insetlist_(p.insetlist_, beg, end),
261 begin_of_body_(p.begin_of_body_), words_(p.words_),
264 id_ = paragraph_id++;
265 if (beg >= pos_type(p.text_.size()))
267 text_ = p.text_.substr(beg, end - beg);
269 FontList::const_iterator fcit = fontlist_.begin();
270 FontList::const_iterator fend = fontlist_.end();
271 for (; fcit != fend; ++fcit) {
272 if (fcit->pos() < beg)
274 if (fcit->pos() >= end) {
275 // Add last entry in the fontlist_.
276 fontlist_.set(text_.size() - 1, fcit->font());
279 // Add a new entry in the fontlist_.
280 fontlist_.set(fcit->pos() - beg, fcit->font());
285 void Paragraph::addChangesToToc(DocIterator const & cdit,
286 Buffer const & buf) const
288 d->changes_.addToToc(cdit, buf);
292 bool Paragraph::isFullyDeleted(pos_type start, pos_type end) const
294 LASSERT(start >= 0 && start <= size(), /**/);
295 LASSERT(end > start && end <= size() + 1, /**/);
297 return d->changes_.isFullyDeleted(start, end);
301 bool Paragraph::isChanged(pos_type start, pos_type end) const
303 LASSERT(start >= 0 && start <= size(), /**/);
304 LASSERT(end > start && end <= size() + 1, /**/);
306 return d->changes_.isChanged(start, end);
310 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
312 // keep the logic here in sync with the logic of eraseChars()
316 Change const change = d->changes_.lookup(size());
317 return change.type == Change::INSERTED && change.author == 0;
321 void Paragraph::setChange(Change const & change)
323 // beware of the imaginary end-of-par character!
324 d->changes_.set(change, 0, size() + 1);
327 * Propagate the change recursively - but not in case of DELETED!
329 * Imagine that your co-author makes changes in an existing inset. He
330 * sends your document to you and you come to the conclusion that the
331 * inset should go completely. If you erase it, LyX must not delete all
332 * text within the inset. Otherwise, the change tracked insertions of
333 * your co-author get lost and there is no way to restore them later.
335 * Conclusion: An inset's content should remain untouched if you delete it
338 if (change.type != Change::DELETED) {
339 for (pos_type pos = 0; pos < size(); ++pos) {
340 if (Inset * inset = getInset(pos))
341 inset->setChange(change);
347 void Paragraph::setChange(pos_type pos, Change const & change)
349 LASSERT(pos >= 0 && pos <= size(), /**/);
350 d->changes_.set(change, pos);
352 // see comment in setChange(Change const &) above
353 if (change.type != Change::DELETED && pos < size())
354 if (Inset * inset = getInset(pos))
355 inset->setChange(change);
359 Change const & Paragraph::lookupChange(pos_type pos) const
361 LASSERT(pos >= 0 && pos <= size(), /**/);
362 return d->changes_.lookup(pos);
366 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
369 LASSERT(start >= 0 && start <= size(), /**/);
370 LASSERT(end > start && end <= size() + 1, /**/);
372 for (pos_type pos = start; pos < end; ++pos) {
373 switch (lookupChange(pos).type) {
374 case Change::UNCHANGED:
375 // accept changes in nested inset
376 if (Inset * inset = getInset(pos))
377 inset->acceptChanges(bparams);
380 case Change::INSERTED:
381 d->changes_.set(Change(Change::UNCHANGED), pos);
382 // also accept changes in nested inset
383 if (Inset * inset = getInset(pos))
384 inset->acceptChanges(bparams);
387 case Change::DELETED:
388 // Suppress access to non-existent
389 // "end-of-paragraph char"
391 eraseChar(pos, false);
402 void Paragraph::rejectChanges(BufferParams const & bparams,
403 pos_type start, pos_type end)
405 LASSERT(start >= 0 && start <= size(), /**/);
406 LASSERT(end > start && end <= size() + 1, /**/);
408 for (pos_type pos = start; pos < end; ++pos) {
409 switch (lookupChange(pos).type) {
410 case Change::UNCHANGED:
411 // reject changes in nested inset
412 if (Inset * inset = getInset(pos))
413 inset->rejectChanges(bparams);
416 case Change::INSERTED:
417 // Suppress access to non-existent
418 // "end-of-paragraph char"
420 eraseChar(pos, false);
426 case Change::DELETED:
427 d->changes_.set(Change(Change::UNCHANGED), pos);
429 // Do NOT reject changes within a deleted inset!
430 // There may be insertions of a co-author inside of it!
438 void Paragraph::Private::insertChar(pos_type pos, char_type c,
439 Change const & change)
441 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
444 changes_.insert(change, pos);
446 // This is actually very common when parsing buffers (and
447 // maybe inserting ascii text)
448 if (pos == pos_type(text_.size())) {
449 // when appending characters, no need to update tables
454 text_.insert(text_.begin() + pos, c);
456 // Update the font table.
457 fontlist_.increasePosAfterPos(pos);
460 insetlist_.increasePosAfterPos(pos);
464 bool Paragraph::insertInset(pos_type pos, Inset * inset,
465 Change const & change)
467 LASSERT(inset, /**/);
468 LASSERT(pos >= 0 && pos <= size(), /**/);
470 // Paragraph::insertInset() can be used in cut/copy/paste operation where
471 // d->inset_owner_ is not set yet.
472 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
475 d->insertChar(pos, META_INSET, change);
476 LASSERT(d->text_[pos] == META_INSET, /**/);
478 // Add a new entry in the insetlist_.
479 d->insetlist_.insert(inset, pos);
484 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
486 LASSERT(pos >= 0 && pos <= size(), return false);
488 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
491 Change change = d->changes_.lookup(pos);
493 // set the character to DELETED if
494 // a) it was previously unchanged or
495 // b) it was inserted by a co-author
497 if (change.type == Change::UNCHANGED ||
498 (change.type == Change::INSERTED && change.author != 0)) {
499 setChange(pos, Change(Change::DELETED));
503 if (change.type == Change::DELETED)
507 // Don't physically access the imaginary end-of-paragraph character.
508 // eraseChar() can only mark it as DELETED. A physical deletion of
509 // end-of-par must be handled externally.
515 d->changes_.erase(pos);
517 // if it is an inset, delete the inset entry
518 if (d->text_[pos] == META_INSET)
519 d->insetlist_.erase(pos);
521 d->text_.erase(d->text_.begin() + pos);
523 // Update the fontlist_
524 d->fontlist_.erase(pos);
526 // Update the insetlist_
527 d->insetlist_.decreasePosAfterPos(pos);
533 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
535 LASSERT(start >= 0 && start <= size(), /**/);
536 LASSERT(end >= start && end <= size() + 1, /**/);
539 for (pos_type count = end - start; count; --count) {
540 if (!eraseChar(i, trackChanges))
547 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
548 char_type next, Encoding const & encoding)
550 // Writing next here may circumvent a possible font change between
551 // c and next. Since next is only output if it forms a surrogate pair
552 // with c we can ignore this:
553 // A font change inside a surrogate pair does not make sense and is
554 // hopefully impossible to input.
555 // FIXME: change tracking
556 // Is this correct WRT change tracking?
557 docstring const latex1 = encoding.latexChar(next);
558 docstring const latex2 = encoding.latexChar(c);
559 if (docstring(1, next) == latex1) {
560 // the encoding supports the combination
561 os << latex2 << latex1;
562 return latex1.length() + latex2.length();
564 os << latex1 << '{' << latex2 << '}';
565 return latex1.length() + latex2.length() + 2;
569 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
570 odocstream & os, TexRow & texrow,
572 unsigned int & column,
574 Layout const & style)
576 if (style.pass_thru || runparams.verbatim)
579 if (i + 1 < int(text_.size())) {
580 char_type next = text_[i + 1];
581 if (Encodings::isCombiningChar(next)) {
582 Encoding const & encoding = *(runparams.encoding);
583 // This space has an accent, so we must always output it.
584 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
589 if (lyxrc.plaintext_linelen > 0
590 && column > lyxrc.plaintext_linelen
592 && text_[i - 1] != ' '
593 && (i + 1 < int(text_.size()))
594 // same in FreeSpacing mode
595 && !owner_->isFreeSpacing()
596 // In typewriter mode, we want to avoid
597 // ! . ? : at the end of a line
598 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
599 && (text_[i - 1] == '.'
600 || text_[i - 1] == '?'
601 || text_[i - 1] == ':'
602 || text_[i - 1] == '!'))) {
605 texrow.start(owner_->id(), i + 1);
607 } else if (style.free_spacing) {
616 int Paragraph::Private::writeScriptChars(odocstream & os,
617 docstring const & ltx,
618 Change const & runningChange,
619 Encoding const & encoding,
622 // FIXME: modifying i here is not very nice...
624 // We only arrive here when a proper language for character text_[i] has
625 // not been specified (i.e., it could not be translated in the current
626 // latex encoding) or its latex translation has been forced, and it
627 // belongs to a known script.
628 // Parameter ltx contains the latex translation of text_[i] as specified
629 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
630 // The latex macro name "textXXX" specifies the script to which text_[i]
631 // belongs and we use it in order to check whether characters from the
632 // same script immediately follow, such that we can collect them in a
633 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
634 // for the first char but only "<spec>" for all subsequent chars.
635 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
636 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
637 string script = to_ascii(ltx.substr(1, brace1 - 1));
640 bool closing_brace = true;
641 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
642 // Correct encoding is being used, so we can avoid \textgreek.
645 closing_brace = false;
647 os << ltx.substr(pos, length);
648 int size = text_.size();
649 while (i + 1 < size) {
650 char_type const next = text_[i + 1];
651 // Stop here if next character belongs to another script
652 // or there is a change in change tracking status.
653 if (!Encodings::isKnownScriptChar(next, script) ||
654 runningChange != owner_->lookupChange(i + 1))
658 FontList::const_iterator cit = fontlist_.begin();
659 FontList::const_iterator end = fontlist_.end();
660 for (; cit != end; ++cit) {
661 if (cit->pos() >= i && !found) {
662 prev_font = cit->font();
665 if (cit->pos() >= i + 1)
668 // Stop here if there is a font attribute or encoding change.
669 if (found && cit != end && prev_font != cit->font())
671 docstring const latex = encoding.latexChar(next);
672 docstring::size_type const b1 =
673 latex.find_first_of(from_ascii("{"));
674 docstring::size_type const b2 =
675 latex.find_last_of(from_ascii("}"));
676 int const len = b2 - b1 - 1;
677 os << latex.substr(b1 + 1, len);
689 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
691 pos_type const len = str.length();
693 // is the paragraph large enough?
694 if (pos + len > int(text_.size()))
697 // does the wanted text start at point?
698 for (string::size_type i = 0; i < str.length(); ++i) {
699 // Caution: direct comparison of characters works only
700 // because str is pure ASCII.
701 if (str[i] != text_[pos + i])
705 return fontlist_.hasChangeInRange(pos, len);
709 void Paragraph::Private::latexInset(
710 BufferParams const & bparams,
713 OutputParams & runparams,
716 Font const & outerfont,
718 Change & running_change,
719 Layout const & style,
721 unsigned int & column)
723 Inset * inset = owner_->getInset(i);
724 LASSERT(inset, /**/);
726 if (style.pass_thru) {
727 inset->plaintext(os, runparams);
731 // FIXME: move this to InsetNewline::latex
732 if (inset->lyxCode() == NEWLINE_CODE) {
733 // newlines are handled differently here than
734 // the default in simpleTeXSpecialChars().
735 if (!style.newline_allowed) {
739 column += running_font.latexWriteEndChanges(
740 os, bparams, runparams,
745 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
748 basefont = owner_->getLayoutFont(bparams, outerfont);
749 running_font = basefont;
751 if (runparams.moving_arg)
756 texrow.start(owner_->id(), i + 1);
760 if (owner_->lookupChange(i).type == Change::DELETED) {
761 if( ++runparams.inDeletedInset == 1)
762 runparams.changeOfDeletedInset = owner_->lookupChange(i);
765 if (inset->canTrackChanges()) {
766 column += Changes::latexMarkChange(os, bparams, running_change,
767 Change(Change::UNCHANGED));
768 running_change = Change(Change::UNCHANGED);
772 odocstream::pos_type const len = os.tellp();
774 if (inset->forceLTR()
775 && running_font.isRightToLeft()
776 // ERT is an exception, it should be output with no decorations at all
777 && inset->lyxCode() != ERT_CODE) {
778 if (running_font.language()->lang() == "farsi")
785 // FIXME: Bug: we can have an empty font change here!
786 // if there has just been a font change, we are going to close it
787 // right now, which means stupid latex code like \textsf{}. AFAIK,
788 // this does not harm dvi output. A minor bug, thus (JMarc)
790 // Some insets cannot be inside a font change command.
791 // However, even such insets *can* be placed in \L or \R
792 // or their equivalents (for RTL language switches), so we don't
793 // close the language in those cases.
794 // ArabTeX, though, cannot handle this special behavior, it seems.
795 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
796 || running_font.language()->lang() == "arabic_arabtex";
797 if (open_font && inset->noFontChange()) {
798 bool closeLanguage = arabtex
799 || basefont.isRightToLeft() == running_font.isRightToLeft();
800 unsigned int count = running_font.latexWriteEndChanges(os,
801 bparams, runparams, basefont, basefont, closeLanguage);
803 // if any font properties were closed, update the running_font,
804 // making sure, however, to leave the language as it was
806 // FIXME: probably a better way to keep track of the old
807 // language, than copying the entire font?
808 Font const copy_font(running_font);
809 basefont = owner_->getLayoutFont(bparams, outerfont);
810 running_font = basefont;
812 running_font.setLanguage(copy_font.language());
813 // leave font open if language is still open
814 open_font = (running_font.language() == basefont.language());
816 runparams.local_font = &basefont;
823 tmp = inset->latex(os, runparams);
824 } catch (EncodingException & e) {
825 // add location information and throw again.
832 if (running_font.language()->lang() == "farsi")
839 for (int j = 0; j < tmp; ++j)
842 texrow.start(owner_->id(), i + 1);
845 column += os.tellp() - len;
848 if (owner_->lookupChange(i).type == Change::DELETED)
849 --runparams.inDeletedInset;
853 void Paragraph::Private::latexSpecialChar(
855 OutputParams const & runparams,
856 Font const & running_font,
857 Change const & running_change,
858 Layout const & style,
860 unsigned int & column)
862 char_type const c = text_[i];
864 if (style.pass_thru) {
866 // FIXME UNICODE: This can fail if c cannot
867 // be encoded in the current encoding.
872 if (runparams.verbatim) {
873 // FIXME UNICODE: This can fail if c cannot
874 // be encoded in the current encoding.
879 // If T1 font encoding is used, use the special
880 // characters it provides.
881 // NOTE: some languages reset the font encoding
883 if (!running_font.language()->internalFontEncoding()
884 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
887 // \tt font needs special treatment
888 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
889 && latexSpecialTypewriter(c, os, i, column))
892 // Otherwise, we use what LaTeX provides us.
895 os << "\\textbackslash{}";
899 os << "\\textless{}";
903 os << "\\textgreater{}";
914 os << "\\char`\\\"{}";
919 case '%': case '#': case '{':
927 os << "\\textasciitilde{}";
932 os << "\\textasciicircum{}";
939 // avoid being mistaken for optional arguments
947 // Blanks are printed before font switching.
948 // Sure? I am not! (try nice-latex)
949 // I am sure it's correct. LyX might be smarter
950 // in the future, but for now, nothing wrong is
956 if (latexSpecialPhrase(os, i, column, runparams))
962 Encoding const & encoding = *(runparams.encoding);
963 if (i + 1 < int(text_.size())) {
964 char_type next = text_[i + 1];
965 if (Encodings::isCombiningChar(next)) {
966 column += latexSurrogatePair(os, c, next, encoding) - 1;
972 docstring const latex = encoding.latexChar(c);
973 if (Encodings::isKnownScriptChar(c, script)
974 && prefixIs(latex, from_ascii("\\" + script)))
975 column += writeScriptChars(os, latex,
976 running_change, encoding, i) - 1;
977 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
978 // Prevent eating of a following
979 // space or command corruption by
980 // following characters
981 column += latex.length() + 1;
984 column += latex.length() - 1;
992 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
993 pos_type i, unsigned int & column)
999 // In T1 encoding, these characters exist
1000 // but we should avoid ligatures
1001 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1003 os << "\\textcompwordmark{}";
1010 // soul.sty breaks with \char`\"
1011 os << "\\textquotedbl{}";
1020 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1021 pos_type i, unsigned int & column)
1025 // within \ttfamily, "--" is merged to "-" (no endash)
1026 // so we avoid this rather irritating ligature
1027 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1034 // everything else has to be checked separately
1035 // (depending on the encoding)
1042 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1043 unsigned int & column, OutputParams const & runparams)
1045 // FIXME: if we have "LaTeX" with a font
1046 // change in the middle (before the 'T', then
1047 // the "TeX" part is still special cased.
1048 // Really we should only operate this on
1049 // "words" for some definition of word
1051 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1052 if (!isTextAt(special_phrases[pnr].phrase, i))
1054 if (runparams.moving_arg)
1056 os << special_phrases[pnr].macro;
1057 i += special_phrases[pnr].phrase.length() - 1;
1058 column += special_phrases[pnr].macro.length() - 1;
1065 void Paragraph::Private::validate(LaTeXFeatures & features,
1066 Layout const & layout) const
1068 // check the params.
1069 if (!params_.spacing().isDefault())
1070 features.require("setspace");
1073 features.useLayout(layout.name());
1076 fontlist_.validate(features);
1078 // then the indentation
1079 if (!params_.leftIndent().zero())
1080 features.require("ParagraphLeftIndent");
1083 InsetList::const_iterator icit = insetlist_.begin();
1084 InsetList::const_iterator iend = insetlist_.end();
1085 for (; icit != iend; ++icit) {
1087 icit->inset->validate(features);
1088 if (layout.needprotect &&
1089 icit->inset->lyxCode() == FOOT_CODE)
1090 features.require("NeedLyXFootnoteCode");
1094 // then the contents
1095 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1096 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1097 if (!special_phrases[pnr].builtin
1098 && isTextAt(special_phrases[pnr].phrase, i)) {
1099 features.require(special_phrases[pnr].phrase);
1103 Encodings::validate(text_[i], features);
1107 /////////////////////////////////////////////////////////////////////
1111 /////////////////////////////////////////////////////////////////////
1114 Layout const emptyParagraphLayout;
1117 Paragraph::Paragraph()
1118 : d(new Paragraph::Private(this, emptyParagraphLayout))
1125 Paragraph::Paragraph(Paragraph const & par)
1126 : itemdepth(par.itemdepth),
1127 d(new Paragraph::Private(*par.d, this))
1133 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1134 : itemdepth(par.itemdepth),
1135 d(new Paragraph::Private(*par.d, this, beg, end))
1141 Paragraph & Paragraph::operator=(Paragraph const & par)
1143 // needed as we will destroy the private part before copying it
1145 itemdepth = par.itemdepth;
1149 d = new Private(*par.d, this);
1156 Paragraph::~Paragraph()
1163 void Paragraph::write(ostream & os, BufferParams const & bparams,
1164 depth_type & dth) const
1166 // The beginning or end of a deeper (i.e. nested) area?
1167 if (dth != d->params_.depth()) {
1168 if (d->params_.depth() > dth) {
1169 while (d->params_.depth() > dth) {
1170 os << "\n\\begin_deeper";
1174 while (d->params_.depth() < dth) {
1175 os << "\n\\end_deeper";
1181 // First write the layout
1182 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1184 d->params_.write(os);
1186 Font font1(inherit_font, bparams.language);
1188 Change running_change = Change(Change::UNCHANGED);
1191 for (pos_type i = 0; i <= size(); ++i) {
1193 Change const change = lookupChange(i);
1194 Changes::lyxMarkChange(os, column, running_change, change);
1195 running_change = change;
1200 // Write font changes (ignore spelling markers)
1201 Font font2 = getFontSettings(bparams, i);
1202 font2.setMisspelled(false);
1203 if (font2 != font1) {
1204 font2.lyxWriteChanges(font1, os);
1209 char_type const c = d->text_[i];
1212 if (Inset const * inset = getInset(i)) {
1213 if (inset->directWrite()) {
1214 // international char, let it write
1215 // code directly so it's shorter in
1221 os << "\\begin_inset ";
1223 os << "\n\\end_inset\n\n";
1229 os << "\n\\backslash\n";
1233 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1240 if ((column > 70 && c == ' ')
1245 // this check is to amend a bug. LyX sometimes
1246 // inserts '\0' this could cause problems.
1248 os << to_utf8(docstring(1, c));
1250 LYXERR0("NUL char in structure.");
1256 os << "\n\\end_layout\n";
1260 void Paragraph::validate(LaTeXFeatures & features) const
1262 d->validate(features, *d->layout_);
1266 void Paragraph::insert(pos_type start, docstring const & str,
1267 Font const & font, Change const & change)
1269 for (size_t i = 0, n = str.size(); i != n ; ++i)
1270 insertChar(start + i, str[i], font, change);
1274 void Paragraph::appendChar(char_type c, Font const & font,
1275 Change const & change)
1278 d->changes_.insert(change, d->text_.size());
1279 // when appending characters, no need to update tables
1280 d->text_.push_back(c);
1281 setFont(d->text_.size() - 1, font);
1285 void Paragraph::appendString(docstring const & s, Font const & font,
1286 Change const & change)
1288 pos_type end = s.size();
1289 size_t oldsize = d->text_.size();
1290 size_t newsize = oldsize + end;
1291 size_t capacity = d->text_.capacity();
1292 if (newsize >= capacity)
1293 d->text_.reserve(max(capacity + 100, newsize));
1295 // when appending characters, no need to update tables
1298 // FIXME: Optimize this!
1299 for (size_t i = oldsize; i != newsize; ++i) {
1301 d->changes_.insert(change, i);
1303 d->fontlist_.set(oldsize, font);
1304 d->fontlist_.set(newsize - 1, font);
1308 void Paragraph::insertChar(pos_type pos, char_type c,
1311 d->insertChar(pos, c, Change(trackChanges ?
1312 Change::INSERTED : Change::UNCHANGED));
1316 void Paragraph::insertChar(pos_type pos, char_type c,
1317 Font const & font, bool trackChanges)
1319 d->insertChar(pos, c, Change(trackChanges ?
1320 Change::INSERTED : Change::UNCHANGED));
1325 void Paragraph::insertChar(pos_type pos, char_type c,
1326 Font const & font, Change const & change)
1328 d->insertChar(pos, c, change);
1333 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1334 Font const & font, Change const & change)
1336 bool const success = insertInset(pos, inset, change);
1337 // Set the font/language of the inset...
1343 void Paragraph::resetFonts(Font const & font)
1345 d->fontlist_.clear();
1346 d->fontlist_.set(0, font);
1347 d->fontlist_.set(d->text_.size() - 1, font);
1350 // Gets uninstantiated font setting at position.
1351 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1355 LYXERR0("pos: " << pos << " size: " << size());
1356 LASSERT(pos <= size(), /**/);
1359 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1360 if (cit != d->fontlist_.end())
1363 if (pos == size() && !empty())
1364 return getFontSettings(bparams, pos - 1);
1366 // Optimisation: avoid a full font instantiation if there is no
1367 // language change from previous call.
1368 static Font previous_font;
1369 static Language const * previous_lang = 0;
1370 Language const * lang = getParLanguage(bparams);
1371 if (lang != previous_lang) {
1372 previous_lang = lang;
1373 previous_font = Font(inherit_font, lang);
1375 return previous_font;
1379 FontSpan Paragraph::fontSpan(pos_type pos) const
1381 LASSERT(pos <= size(), /**/);
1384 FontList::const_iterator cit = d->fontlist_.begin();
1385 FontList::const_iterator end = d->fontlist_.end();
1386 for (; cit != end; ++cit) {
1387 if (cit->pos() >= pos) {
1388 if (pos >= beginOfBody())
1389 return FontSpan(max(start, beginOfBody()),
1392 return FontSpan(start,
1393 min(beginOfBody() - 1,
1396 start = cit->pos() + 1;
1399 // This should not happen, but if so, we take no chances.
1400 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1401 return FontSpan(pos, pos);
1405 // Gets uninstantiated font setting at position 0
1406 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1408 if (!empty() && !d->fontlist_.empty())
1409 return d->fontlist_.begin()->font();
1411 // Optimisation: avoid a full font instantiation if there is no
1412 // language change from previous call.
1413 static Font previous_font;
1414 static Language const * previous_lang = 0;
1415 if (bparams.language != previous_lang) {
1416 previous_lang = bparams.language;
1417 previous_font = Font(inherit_font, bparams.language);
1420 return previous_font;
1424 // Gets the fully instantiated font at a given position in a paragraph
1425 // This is basically the same function as Text::GetFont() in text2.cpp.
1426 // The difference is that this one is used for generating the LaTeX file,
1427 // and thus cosmetic "improvements" are disallowed: This has to deliver
1428 // the true picture of the buffer. (Asger)
1429 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1430 Font const & outerfont) const
1432 LASSERT(pos >= 0, /**/);
1434 Font font = getFontSettings(bparams, pos);
1436 pos_type const body_pos = beginOfBody();
1437 FontInfo & fi = font.fontInfo();
1439 fi.realize(d->layout_->labelfont);
1441 fi.realize(d->layout_->font);
1443 fi.realize(outerfont.fontInfo());
1444 fi.realize(bparams.getFont().fontInfo());
1450 Font const Paragraph::getLabelFont
1451 (BufferParams const & bparams, Font const & outerfont) const
1453 FontInfo tmpfont = d->layout_->labelfont;
1454 tmpfont.realize(outerfont.fontInfo());
1455 tmpfont.realize(bparams.getFont().fontInfo());
1456 return Font(tmpfont, getParLanguage(bparams));
1460 Font const Paragraph::getLayoutFont
1461 (BufferParams const & bparams, Font const & outerfont) const
1463 FontInfo tmpfont = d->layout_->font;
1464 tmpfont.realize(outerfont.fontInfo());
1465 tmpfont.realize(bparams.getFont().fontInfo());
1466 return Font(tmpfont, getParLanguage(bparams));
1470 /// Returns the height of the highest font in range
1471 FontSize Paragraph::highestFontInRange
1472 (pos_type startpos, pos_type endpos, FontSize def_size) const
1474 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1478 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1480 char_type c = d->text_[pos];
1481 if (!lyxrc.rtl_support)
1511 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1517 void Paragraph::setFont(pos_type pos, Font const & font)
1519 LASSERT(pos <= size(), /**/);
1521 // First, reduce font against layout/label font
1522 // Update: The setCharFont() routine in text2.cpp already
1523 // reduces font, so we don't need to do that here. (Asger)
1525 d->fontlist_.set(pos, font);
1529 void Paragraph::makeSameLayout(Paragraph const & par)
1531 d->layout_ = par.d->layout_;
1532 d->params_ = par.d->params_;
1536 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1538 if (isFreeSpacing())
1544 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1545 if (eraseChar(pos, trackChanges))
1551 return count > 0 || pos > 0;
1555 bool Paragraph::hasSameLayout(Paragraph const & par) const
1557 return par.d->layout_ == d->layout_
1558 && d->params_.sameLayout(par.d->params_);
1562 depth_type Paragraph::getDepth() const
1564 return d->params_.depth();
1568 depth_type Paragraph::getMaxDepthAfter() const
1570 if (d->layout_->isEnvironment())
1571 return d->params_.depth() + 1;
1573 return d->params_.depth();
1577 char Paragraph::getAlign() const
1579 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1580 return d->layout_->align;
1582 return d->params_.align();
1586 docstring const & Paragraph::labelString() const
1588 return d->params_.labelString();
1592 // the next two functions are for the manual labels
1593 docstring const Paragraph::getLabelWidthString() const
1595 if (d->layout_->margintype == MARGIN_MANUAL
1596 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1597 return d->params_.labelWidthString();
1599 return _("Senseless with this layout!");
1603 void Paragraph::setLabelWidthString(docstring const & s)
1605 d->params_.labelWidthString(s);
1609 docstring const Paragraph::translateIfPossible(docstring const & s,
1610 BufferParams const & bparams) const
1612 if (!isAscii(s) || s.empty()) {
1613 // This must be a user defined layout. We cannot translate
1614 // this, since gettext accepts only ascii keys.
1617 // Probably standard layout, try to translate
1618 Messages & m = getMessages(getParLanguage(bparams)->code());
1619 return m.get(to_ascii(s));
1623 docstring Paragraph::expandLabel(Layout const & layout,
1624 BufferParams const & bparams, bool process_appendix) const
1626 DocumentClass const & tclass = bparams.documentClass();
1629 if (process_appendix && d->params_.appendix())
1630 fmt = translateIfPossible(layout.labelstring_appendix(),
1633 fmt = translateIfPossible(layout.labelstring(), bparams);
1635 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1636 && !layout.counter.empty())
1637 return tclass.counters().theCounter(layout.counter);
1639 // handle 'inherited level parts' in 'fmt',
1640 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1641 size_t const i = fmt.find('@', 0);
1642 if (i != docstring::npos) {
1643 size_t const j = fmt.find('@', i + 1);
1644 if (j != docstring::npos) {
1645 docstring parent(fmt, i + 1, j - i - 1);
1646 docstring label = from_ascii("??");
1647 if (tclass.hasLayout(parent))
1648 docstring label = expandLabel(tclass[parent], bparams,
1650 fmt = docstring(fmt, 0, i) + label
1651 + docstring(fmt, j + 1, docstring::npos);
1655 return tclass.counters().counterLabel(fmt);
1659 void Paragraph::applyLayout(Layout const & new_layout)
1661 d->layout_ = &new_layout;
1662 LyXAlignment const oldAlign = d->params_.align();
1664 if (!(oldAlign & d->layout_->alignpossible)) {
1665 frontend::Alert::warning(_("Alignment not permitted"),
1666 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1667 d->params_.align(LYX_ALIGN_LAYOUT);
1672 pos_type Paragraph::beginOfBody() const
1674 return d->begin_of_body_;
1678 void Paragraph::setBeginOfBody()
1680 if (d->layout_->labeltype != LABEL_MANUAL) {
1681 d->begin_of_body_ = 0;
1685 // Unroll the first two cycles of the loop
1686 // and remember the previous character to
1687 // remove unnecessary getChar() calls
1689 pos_type end = size();
1690 if (i < end && !isNewline(i)) {
1692 char_type previous_char = 0;
1695 previous_char = d->text_[i];
1696 if (!isNewline(i)) {
1698 while (i < end && previous_char != ' ') {
1703 previous_char = temp;
1709 d->begin_of_body_ = i;
1713 bool Paragraph::forcePlainLayout() const
1715 return inInset().forcePlainLayout();
1719 bool Paragraph::allowParagraphCustomization() const
1721 return inInset().allowParagraphCustomization();
1725 bool Paragraph::usePlainLayout() const
1727 return inInset().usePlainLayout();
1733 // paragraphs inside floats need different alignment tags to avoid
1736 bool noTrivlistCentering(InsetCode code)
1738 return code == FLOAT_CODE
1739 || code == WRAP_CODE
1740 || code == CELL_CODE;
1744 string correction(string const & orig)
1746 if (orig == "flushleft")
1747 return "raggedright";
1748 if (orig == "flushright")
1749 return "raggedleft";
1750 if (orig == "center")
1756 string const corrected_env(string const & suffix, string const & env,
1757 InsetCode code, bool const lastpar)
1759 string output = suffix + "{";
1760 if (noTrivlistCentering(code)) {
1762 // the last paragraph in non-trivlist-aligned
1763 // context is special (to avoid unwanted whitespace)
1764 if (suffix == "\\begin")
1765 return "\\" + correction(env) + "{}";
1768 output += correction(env);
1772 if (suffix == "\\begin")
1778 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1780 if (!contains(str, "\n"))
1781 column += str.size();
1785 column = rsplit(str, tmp, '\n').size();
1792 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1793 odocstream & os, TexRow & texrow,
1794 OutputParams const & runparams) const
1798 if (params_.noindent()) {
1799 os << "\\noindent ";
1803 LyXAlignment const curAlign = params_.align();
1805 if (curAlign == layout_->align)
1809 case LYX_ALIGN_NONE:
1810 case LYX_ALIGN_BLOCK:
1811 case LYX_ALIGN_LAYOUT:
1812 case LYX_ALIGN_SPECIAL:
1814 case LYX_ALIGN_LEFT:
1815 case LYX_ALIGN_RIGHT:
1816 case LYX_ALIGN_CENTER:
1817 if (runparams.moving_arg) {
1824 string const begin_tag = "\\begin";
1825 InsetCode code = owner_->ownerCode();
1826 bool const lastpar = runparams.isLastPar;
1829 case LYX_ALIGN_NONE:
1830 case LYX_ALIGN_BLOCK:
1831 case LYX_ALIGN_LAYOUT:
1832 case LYX_ALIGN_SPECIAL:
1834 case LYX_ALIGN_LEFT: {
1836 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1839 output = corrected_env(begin_tag, "flushright", code, lastpar);
1840 os << from_ascii(output);
1841 adjust_row_column(output, texrow, column);
1843 } case LYX_ALIGN_RIGHT: {
1845 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1846 output = corrected_env(begin_tag, "flushright", code, lastpar);
1848 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1849 os << from_ascii(output);
1850 adjust_row_column(output, texrow, column);
1852 } case LYX_ALIGN_CENTER: {
1854 output = corrected_env(begin_tag, "center", code, lastpar);
1855 os << from_ascii(output);
1856 adjust_row_column(output, texrow, column);
1865 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1866 odocstream & os, TexRow & texrow,
1867 OutputParams const & runparams) const
1871 LyXAlignment const curAlign = params_.align();
1873 if (curAlign == layout_->align)
1877 case LYX_ALIGN_NONE:
1878 case LYX_ALIGN_BLOCK:
1879 case LYX_ALIGN_LAYOUT:
1880 case LYX_ALIGN_SPECIAL:
1882 case LYX_ALIGN_LEFT:
1883 case LYX_ALIGN_RIGHT:
1884 case LYX_ALIGN_CENTER:
1885 if (runparams.moving_arg) {
1892 string const end_tag = "\n\\par\\end";
1893 InsetCode code = owner_->ownerCode();
1894 bool const lastpar = runparams.isLastPar;
1897 case LYX_ALIGN_NONE:
1898 case LYX_ALIGN_BLOCK:
1899 case LYX_ALIGN_LAYOUT:
1900 case LYX_ALIGN_SPECIAL:
1902 case LYX_ALIGN_LEFT: {
1904 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1905 output = corrected_env(end_tag, "flushleft", code, lastpar);
1907 output = corrected_env(end_tag, "flushright", code, lastpar);
1908 os << from_ascii(output);
1909 adjust_row_column(output, texrow, column);
1911 } case LYX_ALIGN_RIGHT: {
1913 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1914 output = corrected_env(end_tag, "flushright", code, lastpar);
1916 output = corrected_env(end_tag, "flushleft", code, lastpar);
1917 os << from_ascii(output);
1918 adjust_row_column(output, texrow, column);
1920 } case LYX_ALIGN_CENTER: {
1922 output = corrected_env(end_tag, "center", code, lastpar);
1923 os << from_ascii(output);
1924 adjust_row_column(output, texrow, column);
1933 // This one spits out the text of the paragraph
1934 bool Paragraph::latex(BufferParams const & bparams,
1935 Font const & outerfont,
1936 odocstream & os, TexRow & texrow,
1937 OutputParams const & runparams,
1938 int start_pos, int end_pos) const
1940 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1942 bool return_value = false;
1944 bool const allowcust = allowParagraphCustomization();
1946 // FIXME This check should not be needed. Perhaps issue an
1947 // error if it triggers.
1948 Layout const & style = forcePlainLayout() ?
1949 bparams.documentClass().plainLayout() : *d->layout_;
1951 // Current base font for all inherited font changes, without any
1952 // change caused by an individual character, except for the language:
1953 // It is set to the language of the first character.
1954 // As long as we are in the label, this font is the base font of the
1955 // label. Before the first body character it is set to the base font
1959 // Maybe we have to create a optional argument.
1960 pos_type body_pos = beginOfBody();
1961 unsigned int column = 0;
1966 basefont = getLabelFont(bparams, outerfont);
1968 basefont = getLayoutFont(bparams, outerfont);
1971 // Which font is currently active?
1972 Font running_font(basefont);
1973 // Do we have an open font change?
1974 bool open_font = false;
1976 Change runningChange = Change(Change::UNCHANGED);
1978 texrow.start(id(), 0);
1980 // if the paragraph is empty, the loop will not be entered at all
1982 if (style.isCommand()) {
1987 column += d->startTeXParParams(bparams, os, texrow,
1991 for (pos_type i = 0; i < size(); ++i) {
1992 // First char in paragraph or after label?
1993 if (i == body_pos) {
1996 column += running_font.latexWriteEndChanges(
1997 os, bparams, runparams,
1998 basefont, basefont);
2001 basefont = getLayoutFont(bparams, outerfont);
2002 running_font = basefont;
2004 column += Changes::latexMarkChange(os, bparams,
2005 runningChange, Change(Change::UNCHANGED));
2006 runningChange = Change(Change::UNCHANGED);
2011 if (style.isCommand()) {
2017 column += d->startTeXParParams(bparams, os,
2022 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2025 if (bparams.outputChanges && runningChange != change) {
2027 column += running_font.latexWriteEndChanges(
2028 os, bparams, runparams, basefont, basefont);
2031 basefont = getLayoutFont(bparams, outerfont);
2032 running_font = basefont;
2034 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2035 runningChange = change;
2038 // do not output text which is marked deleted
2039 // if change tracking output is disabled
2040 if (!bparams.outputChanges && change.type == Change::DELETED) {
2046 // Fully instantiated font
2047 Font const font = getFont(bparams, i, outerfont);
2049 Font const last_font = running_font;
2051 // Do we need to close the previous font?
2053 (font != running_font ||
2054 font.language() != running_font.language()))
2056 column += running_font.latexWriteEndChanges(
2057 os, bparams, runparams, basefont,
2058 (i == body_pos-1) ? basefont : font);
2059 running_font = basefont;
2063 // close babel's font environment before opening CJK.
2064 if (!running_font.language()->babel().empty() &&
2065 font.language()->encoding()->package() == Encoding::CJK) {
2066 string end_tag = subst(lyxrc.language_command_end,
2068 running_font.language()->babel());
2069 os << from_ascii(end_tag);
2070 column += end_tag.length();
2073 // Switch file encoding if necessary (and allowed)
2074 if (!runparams.verbatim &&
2075 runparams.encoding->package() != Encoding::none &&
2076 font.language()->encoding()->package() != Encoding::none) {
2077 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2078 runparams, *(font.language()->encoding()));
2079 if (enc_switch.first) {
2080 column += enc_switch.second;
2081 runparams.encoding = font.language()->encoding();
2085 char_type const c = d->text_[i];
2087 // Do we need to change font?
2088 if ((font != running_font ||
2089 font.language() != running_font.language()) &&
2092 odocstringstream ods;
2093 column += font.latexWriteStartChanges(ods, bparams,
2094 runparams, basefont,
2096 running_font = font;
2098 docstring fontchange = ods.str();
2099 // check if the fontchange ends with a trailing blank
2100 // (like "\small " (see bug 3382)
2101 if (suffixIs(fontchange, ' ') && c == ' ')
2102 os << fontchange.substr(0, fontchange.size() - 1)
2103 << from_ascii("{}");
2108 // FIXME: think about end_pos implementation...
2109 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2110 // FIXME: integrate this case in latexSpecialChar
2111 // Do not print the separation of the optional argument
2112 // if style.pass_thru is false. This works because
2113 // latexSpecialChar ignores spaces if
2114 // style.pass_thru is false.
2115 if (i != body_pos - 1) {
2116 if (d->simpleTeXBlanks(
2117 runparams, os, texrow,
2118 i, column, font, style)) {
2119 // A surrogate pair was output. We
2120 // must not call latexSpecialChar
2121 // in this iteration, since it would output
2122 // the combining character again.
2129 OutputParams rp = runparams;
2130 rp.free_spacing = style.free_spacing;
2131 rp.local_font = &font;
2132 rp.intitle = style.intitle;
2134 // Two major modes: LaTeX or plain
2135 // Handle here those cases common to both modes
2136 // and then split to handle the two modes separately.
2137 if (c == META_INSET) {
2138 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2139 d->latexInset(bparams, os,
2140 texrow, rp, running_font,
2141 basefont, outerfont, open_font,
2142 runningChange, style, i, column);
2145 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2147 d->latexSpecialChar(os, rp, running_font, runningChange,
2149 } catch (EncodingException & e) {
2150 if (runparams.dryrun) {
2151 os << "<" << _("LyX Warning: ")
2152 << _("uncodable character") << " '";
2156 // add location information and throw again.
2165 // Set the encoding to that returned from latexSpecialChar (see
2166 // comment for encoding member in OutputParams.h)
2167 runparams.encoding = rp.encoding;
2170 // If we have an open font definition, we have to close it
2172 #ifdef FIXED_LANGUAGE_END_DETECTION
2175 .latexWriteEndChanges(os, bparams, runparams,
2177 next_->getFont(bparams, 0, outerfont));
2179 running_font.latexWriteEndChanges(os, bparams,
2180 runparams, basefont, basefont);
2183 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2184 //FIXME: there as we start another \selectlanguage with the next paragraph if
2185 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2186 running_font.latexWriteEndChanges(os, bparams, runparams,
2187 basefont, basefont);
2191 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2193 // Needed if there is an optional argument but no contents.
2194 if (body_pos > 0 && body_pos == size()) {
2196 return_value = false;
2200 column += d->endTeXParParams(bparams, os, texrow,
2204 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2205 return return_value;
2209 bool Paragraph::emptyTag() const
2211 for (pos_type i = 0; i < size(); ++i) {
2212 if (Inset const * inset = getInset(i)) {
2213 InsetCode lyx_code = inset->lyxCode();
2214 if (lyx_code != TOC_CODE &&
2215 lyx_code != INCLUDE_CODE &&
2216 lyx_code != GRAPHICS_CODE &&
2217 lyx_code != ERT_CODE &&
2218 lyx_code != LISTINGS_CODE &&
2219 lyx_code != FLOAT_CODE &&
2220 lyx_code != TABULAR_CODE) {
2224 char_type c = d->text_[i];
2225 if (c != ' ' && c != '\t')
2233 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2236 for (pos_type i = 0; i < size(); ++i) {
2237 if (Inset const * inset = getInset(i)) {
2238 InsetCode lyx_code = inset->lyxCode();
2239 if (lyx_code == LABEL_CODE) {
2240 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2241 docstring const & id = il->getParam("name");
2242 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2250 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2254 for (i = 0; i < size(); ++i) {
2255 if (Inset const * inset = getInset(i)) {
2256 inset->docbook(os, runparams);
2258 char_type c = d->text_[i];
2261 os << sgml::escapeChar(c);
2268 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2272 for (i = 0; i < size(); ++i) {
2273 if (Inset const * inset = getInset(i)) {
2274 inset->xhtml(os, runparams);
2276 char_type c = d->text_[i];
2279 os << html::escapeChar(c);
2286 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2289 pos_type size = text_.size();
2290 for (pos_type i = initial; i < size; ++i) {
2291 Font font = owner_->getFont(buf.params(), i, outerfont);
2292 if (text_[i] == META_INSET)
2294 if (i != initial && font != font_old)
2303 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2305 OutputParams const & runparams,
2306 Font const & outerfont,
2307 pos_type initial) const
2309 bool emph_flag = false;
2311 Layout const & style = *d->layout_;
2313 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2315 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2318 // parsing main loop
2319 for (pos_type i = initial; i < size(); ++i) {
2320 Font font = getFont(buf.params(), i, outerfont);
2322 // handle <emphasis> tag
2323 if (font_old.emph() != font.fontInfo().emph()) {
2324 if (font.fontInfo().emph() == FONT_ON) {
2327 } else if (i != initial) {
2328 os << "</emphasis>";
2333 if (Inset const * inset = getInset(i)) {
2334 inset->docbook(os, runparams);
2336 char_type c = d->text_[i];
2338 if (style.pass_thru)
2341 os << sgml::escapeChar(c);
2343 font_old = font.fontInfo();
2347 os << "</emphasis>";
2350 if (style.free_spacing)
2352 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2357 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2359 OutputParams const & runparams,
2360 Font const & outerfont,
2361 pos_type initial) const
2365 // FIXME We really need to manage the tag nesting here.
2366 // Probably in the same sort of way as in output_xhtml.
2367 bool emph_flag = false;
2368 bool bold_flag = false;
2369 std::string closing_tag;
2371 Layout const & style = *d->layout_;
2373 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2375 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2378 // parsing main loop
2379 for (pos_type i = initial; i < size(); ++i) {
2380 Font font = getFont(buf.params(), i, outerfont);
2383 if (font_old.emph() != font.fontInfo().emph()) {
2384 if (font.fontInfo().emph() == FONT_ON) {
2387 } else if (emph_flag && i != initial) {
2393 if (font_old.series() != font.fontInfo().series()) {
2394 if (font.fontInfo().series() == BOLD_SERIES) {
2397 } else if (bold_flag && i != initial) {
2402 // FIXME Other such tags?
2404 if (Inset const * inset = getInset(i)) {
2405 retval += inset->xhtml(os, runparams);
2407 char_type c = d->text_[i];
2409 if (style.pass_thru)
2411 else if (c == '-') {
2414 if (j < size() && d->text_[j] == '-') {
2416 if (j < size() && d->text_[j] == '-') {
2417 str += from_ascii("—");
2420 str += from_ascii("–");
2428 os << html::escapeChar(c);
2430 font_old = font.fontInfo();
2433 // FIXME This could be out of order. See above.
2443 bool Paragraph::isHfill(pos_type pos) const
2445 Inset const * inset = getInset(pos);
2446 return inset && (inset->lyxCode() == SPACE_CODE &&
2447 inset->isStretchableSpace());
2451 bool Paragraph::isNewline(pos_type pos) const
2453 Inset const * inset = getInset(pos);
2454 return inset && inset->lyxCode() == NEWLINE_CODE;
2458 bool Paragraph::isLineSeparator(pos_type pos) const
2460 char_type const c = d->text_[pos];
2461 if (isLineSeparatorChar(c))
2463 Inset const * inset = getInset(pos);
2464 return inset && inset->isLineSeparator();
2468 bool Paragraph::isWordSeparator(pos_type pos) const
2470 if (Inset const * inset = getInset(pos))
2471 return !inset->isLetter();
2472 char_type const c = d->text_[pos];
2473 // We want to pass the ' and escape chars to the spellchecker
2474 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2475 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2480 bool Paragraph::isChar(pos_type pos) const
2482 if (Inset const * inset = getInset(pos))
2483 return inset->isChar();
2484 char_type const c = d->text_[pos];
2485 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2489 bool Paragraph::isSpace(pos_type pos) const
2491 if (Inset const * inset = getInset(pos))
2492 return inset->isSpace();
2493 char_type const c = d->text_[pos];
2494 return lyx::isSpace(c);
2499 Paragraph::getParLanguage(BufferParams const & bparams) const
2502 return getFirstFontSettings(bparams).language();
2503 // FIXME: we should check the prev par as well (Lgb)
2504 return bparams.language;
2508 bool Paragraph::isRTL(BufferParams const & bparams) const
2510 return lyxrc.rtl_support
2511 && getParLanguage(bparams)->rightToLeft()
2512 && ownerCode() != ERT_CODE
2513 && ownerCode() != LISTINGS_CODE;
2517 void Paragraph::changeLanguage(BufferParams const & bparams,
2518 Language const * from, Language const * to)
2520 // change language including dummy font change at the end
2521 for (pos_type i = 0; i <= size(); ++i) {
2522 Font font = getFontSettings(bparams, i);
2523 if (font.language() == from) {
2524 font.setLanguage(to);
2531 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2533 Language const * doc_language = bparams.language;
2534 FontList::const_iterator cit = d->fontlist_.begin();
2535 FontList::const_iterator end = d->fontlist_.end();
2537 for (; cit != end; ++cit)
2538 if (cit->font().language() != ignore_language &&
2539 cit->font().language() != latex_language &&
2540 cit->font().language() != doc_language)
2546 docstring Paragraph::asString(int options) const
2548 return asString(0, size(), options);
2552 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2554 odocstringstream os;
2557 && options & AS_STR_LABEL
2558 && !d->params_.labelString().empty())
2559 os << d->params_.labelString() << ' ';
2561 for (pos_type i = beg; i < end; ++i) {
2562 char_type const c = d->text_[i];
2563 if (isPrintable(c) || c == '\t'
2564 || (c == '\n' && options & AS_STR_NEWLINES))
2566 else if (c == META_INSET && options & AS_STR_INSETS)
2567 getInset(i)->tocString(os);
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 InsetCode Paragraph::ownerCode() const
2652 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2656 ParagraphParameters & Paragraph::params()
2662 ParagraphParameters const & Paragraph::params() const
2668 bool Paragraph::isFreeSpacing() const
2670 if (d->layout_->free_spacing)
2672 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2676 bool Paragraph::allowEmpty() const
2678 if (d->layout_->keepempty)
2680 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2684 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2686 if (!Encodings::isArabicChar(c))
2689 char_type prev_char = ' ';
2690 char_type next_char = ' ';
2692 for (pos_type i = pos - 1; i >= 0; --i) {
2693 char_type const par_char = d->text_[i];
2694 if (!Encodings::isArabicComposeChar(par_char)) {
2695 prev_char = par_char;
2700 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2701 char_type const par_char = d->text_[i];
2702 if (!Encodings::isArabicComposeChar(par_char)) {
2703 next_char = par_char;
2708 if (Encodings::isArabicChar(next_char)) {
2709 if (Encodings::isArabicChar(prev_char) &&
2710 !Encodings::isArabicSpecialChar(prev_char))
2711 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2713 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2715 if (Encodings::isArabicChar(prev_char) &&
2716 !Encodings::isArabicSpecialChar(prev_char))
2717 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2719 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2724 int Paragraph::checkBiblio(Buffer const & buffer)
2727 // This is getting more and more a mess. ...We really should clean
2728 // up this bibitem issue for 1.6. See also bug 2743.
2730 // Add bibitem insets if necessary
2731 if (d->layout_->labeltype != LABEL_BIBLIO)
2734 bool hasbibitem = !d->insetlist_.empty()
2735 // Insist on it being in pos 0
2736 && d->text_[0] == META_INSET
2737 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2739 bool track_changes = buffer.params().trackChanges;
2744 // remove a bibitem in pos != 0
2745 // restore it later in pos 0 if necessary
2746 // (e.g. if a user inserts contents _before_ the item)
2747 // we're assuming there's only one of these, which there
2749 int erasedInsetPosition = -1;
2750 InsetList::iterator it = d->insetlist_.begin();
2751 InsetList::iterator end = d->insetlist_.end();
2752 for (; it != end; ++it)
2753 if (it->inset->lyxCode() == BIBITEM_CODE
2755 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2756 oldkey = olditem->getParam("key");
2757 oldlabel = olditem->getParam("label");
2758 erasedInsetPosition = it->pos;
2759 eraseChar(erasedInsetPosition, track_changes);
2763 // There was an InsetBibitem at the beginning, and we didn't
2764 // have to erase one.
2765 if (hasbibitem && erasedInsetPosition < 0)
2768 // There was an InsetBibitem at the beginning and we did have to
2769 // erase one. So we give its properties to the beginning inset.
2771 InsetBibitem * inset =
2772 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2773 if (!oldkey.empty())
2774 inset->setParam("key", oldkey);
2775 inset->setParam("label", oldlabel);
2776 return -erasedInsetPosition;
2779 // There was no inset at the beginning, so we need to create one with
2780 // the key and label of the one we erased.
2781 InsetBibitem * inset =
2782 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2783 // restore values of previously deleted item in this par.
2784 if (!oldkey.empty())
2785 inset->setParam("key", oldkey);
2786 inset->setParam("label", oldlabel);
2787 insertInset(0, static_cast<Inset *>(inset),
2788 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2794 void Paragraph::checkAuthors(AuthorList const & authorList)
2796 d->changes_.checkAuthors(authorList);
2800 bool Paragraph::isUnchanged(pos_type pos) const
2802 return lookupChange(pos).type == Change::UNCHANGED;
2806 bool Paragraph::isInserted(pos_type pos) const
2808 return lookupChange(pos).type == Change::INSERTED;
2812 bool Paragraph::isDeleted(pos_type pos) const
2814 return lookupChange(pos).type == Change::DELETED;
2818 InsetList const & Paragraph::insetList() const
2820 return d->insetlist_;
2824 void Paragraph::setBuffer(Buffer & b)
2826 d->insetlist_.setBuffer(b);
2830 Inset * Paragraph::releaseInset(pos_type pos)
2832 Inset * inset = d->insetlist_.release(pos);
2833 /// does not honour change tracking!
2834 eraseChar(pos, false);
2839 Inset * Paragraph::getInset(pos_type pos)
2841 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2842 ? d->insetlist_.get(pos) : 0;
2846 Inset const * Paragraph::getInset(pos_type pos) const
2848 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2849 ? d->insetlist_.get(pos) : 0;
2853 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2854 pos_type & right, TextCase action)
2856 // process sequences of modified characters; in change
2857 // tracking mode, this approach results in much better
2858 // usability than changing case on a char-by-char basis
2861 bool const trackChanges = bparams.trackChanges;
2863 bool capitalize = true;
2865 for (; pos < right; ++pos) {
2866 char_type oldChar = d->text_[pos];
2867 char_type newChar = oldChar;
2869 // ignore insets and don't play with deleted text!
2870 if (oldChar != META_INSET && !isDeleted(pos)) {
2872 case text_lowercase:
2873 newChar = lowercase(oldChar);
2875 case text_capitalization:
2877 newChar = uppercase(oldChar);
2881 case text_uppercase:
2882 newChar = uppercase(oldChar);
2887 if (isWordSeparator(pos) || isDeleted(pos)) {
2888 // permit capitalization again
2892 if (oldChar != newChar) {
2894 if (pos != right - 1)
2896 // step behind the changing area
2900 int erasePos = pos - changes.size();
2901 for (size_t i = 0; i < changes.size(); i++) {
2902 insertChar(pos, changes[i],
2903 getFontSettings(bparams,
2906 if (!eraseChar(erasePos, trackChanges)) {
2909 ++right; // expand selection
2917 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2918 pos_type pos, bool del) const
2920 int const strsize = str.length();
2922 pos_type const parsize = d->text_.size();
2923 for (i = 0; pos + i < parsize; ++i) {
2926 if (cs && str[i] != d->text_[pos + i])
2928 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2930 if (!del && isDeleted(pos + i))
2937 // if necessary, check whether string matches word
2939 if (pos > 0 && !isWordSeparator(pos - 1))
2941 if (pos + strsize < parsize
2942 && !isWordSeparator(pos + strsize))
2950 char_type Paragraph::getChar(pos_type pos) const
2952 return d->text_[pos];
2956 pos_type Paragraph::size() const
2958 return d->text_.size();
2962 bool Paragraph::empty() const
2964 return d->text_.empty();
2968 bool Paragraph::isInset(pos_type pos) const
2970 return d->text_[pos] == META_INSET;
2974 bool Paragraph::isSeparator(pos_type pos) const
2976 //FIXME: Are we sure this can be the only separator?
2977 return d->text_[pos] == ' ';
2981 void Paragraph::deregisterWords()
2983 Private::Words::const_iterator it;
2984 WordList & wl = theWordList();
2985 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2991 void Paragraph::locateWord(pos_type & from, pos_type & to,
2992 word_location const loc) const
2995 case WHOLE_WORD_STRICT:
2996 if (from == 0 || from == size()
2997 || isWordSeparator(from)
2998 || isWordSeparator(from - 1)) {
3002 // no break here, we go to the next
3005 // If we are already at the beginning of a word, do nothing
3006 if (!from || isWordSeparator(from - 1))
3008 // no break here, we go to the next
3011 // always move the cursor to the beginning of previous word
3012 while (from && !isWordSeparator(from - 1))
3016 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3019 // no need to move the 'from' cursor
3023 while (to < size() && !isWordSeparator(to))
3028 void Paragraph::collectWords()
3030 SpellChecker * speller = theSpellChecker();
3032 //lyxerr << "Words: ";
3033 pos_type n = size();
3034 for (pos_type pos = 0; pos < n; ++pos) {
3035 if (isWordSeparator(pos))
3037 pos_type from = pos;
3038 locateWord(from, pos, WHOLE_WORD);
3039 if (!lyxrc.spellcheck_continuously && pos - from < 6)
3042 docstring word = asString(from, pos, false);
3043 if (pos - from >= 6)
3044 d->words_.insert(word);
3046 if (!lyxrc.spellcheck_continuously || !speller)
3049 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3050 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3051 : lyxrc.spellchecker_alt_lang;
3052 WordLangTuple wl(word, lang_code);
3053 SpellChecker::Result res = speller->check(wl);
3054 // ... just ignore any error that the spellchecker reports.
3055 if (!speller->error().empty())
3057 bool const misspelled = res != SpellChecker::OK
3058 && res != SpellChecker::IGNORED_WORD;
3059 d->fontlist_.setMisspelled(from, pos, misspelled);
3061 //lyxerr << word << " ";
3063 //lyxerr << std::endl;
3067 void Paragraph::registerWords()
3069 Private::Words::const_iterator it;
3070 WordList & wl = theWordList();
3071 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3076 void Paragraph::updateWords()
3084 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3085 docstring_list & suggestions) const
3087 SpellChecker * speller = theSpellChecker();
3091 locateWord(from, to, WHOLE_WORD);
3092 if (from == to || from >= pos_type(d->text_.size()))
3095 docstring word = asString(from, to, AS_STR_INSETS);
3096 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3097 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3098 : lyxrc.spellchecker_alt_lang;
3099 wl = WordLangTuple(word, lang_code);
3100 SpellChecker::Result res = speller->check(wl);
3101 // Just ignore any error that the spellchecker reports.
3102 // FIXME: we should through out an exception and catch it in the GUI to
3103 // display the error.
3104 if (!speller->error().empty())
3107 bool const misspelled = res != SpellChecker::OK
3108 && res != SpellChecker::IGNORED_WORD;
3110 if (lyxrc.spellcheck_continuously)
3111 d->fontlist_.setMisspelled(from, to, misspelled);
3114 while (!(word = speller->nextMiss()).empty())
3115 suggestions.push_back(word);
3121 bool Paragraph::isMisspelled(pos_type pos) const
3123 pos_type from = pos;
3126 docstring_list suggestions;
3127 return spellCheck(from, to, wl, suggestions);