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,
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;
177 /// Which Paragraph owns us?
181 Inset const * inset_owner_;
189 static unsigned int paragraph_id;
191 ParagraphParameters params_;
193 /// for recording and looking up changes
197 InsetList insetlist_;
200 pos_type begin_of_body_;
202 typedef docstring TextContainer;
206 typedef std::set<docstring> Words;
210 Layout const * layout_;
214 // Initialization of the counter for the paragraph id's,
215 unsigned int Paragraph::Private::paragraph_id = 0;
219 struct special_phrase {
225 special_phrase const special_phrases[] = {
226 { "LyX", from_ascii("\\LyX{}"), false },
227 { "TeX", from_ascii("\\TeX{}"), true },
228 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
229 { "LaTeX", from_ascii("\\LaTeX{}"), true },
232 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
237 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
238 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
240 id_ = paragraph_id++;
245 Paragraph::Private::Private(Private const & p, Paragraph * owner)
246 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
247 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
248 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
251 id_ = paragraph_id++;
255 Paragraph::Private::Private(Private const & p, Paragraph * owner,
256 pos_type beg, pos_type end)
257 : owner_(owner), inset_owner_(p.inset_owner_),
258 params_(p.params_), changes_(p.changes_),
259 insetlist_(p.insetlist_, beg, end),
260 begin_of_body_(p.begin_of_body_), words_(p.words_),
263 id_ = paragraph_id++;
264 if (beg >= pos_type(p.text_.size()))
266 text_ = p.text_.substr(beg, end - beg);
268 FontList::const_iterator fcit = fontlist_.begin();
269 FontList::const_iterator fend = fontlist_.end();
270 for (; fcit != fend; ++fcit) {
271 if (fcit->pos() < beg)
273 if (fcit->pos() >= end) {
274 // Add last entry in the fontlist_.
275 fontlist_.set(text_.size() - 1, fcit->font());
278 // Add a new entry in the fontlist_.
279 fontlist_.set(fcit->pos() - beg, fcit->font());
284 void Paragraph::addChangesToToc(DocIterator const & cdit,
285 Buffer const & buf) const
287 d->changes_.addToToc(cdit, buf);
291 bool Paragraph::isFullyDeleted(pos_type start, pos_type end) const
293 LASSERT(start >= 0 && start <= size(), /**/);
294 LASSERT(end > start && end <= size() + 1, /**/);
296 return d->changes_.isFullyDeleted(start, end);
300 bool Paragraph::isChanged(pos_type start, pos_type end) const
302 LASSERT(start >= 0 && start <= size(), /**/);
303 LASSERT(end > start && end <= size() + 1, /**/);
305 return d->changes_.isChanged(start, end);
309 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
311 // keep the logic here in sync with the logic of eraseChars()
315 Change const change = d->changes_.lookup(size());
316 return change.type == Change::INSERTED && change.author == 0;
320 void Paragraph::setChange(Change const & change)
322 // beware of the imaginary end-of-par character!
323 d->changes_.set(change, 0, size() + 1);
326 * Propagate the change recursively - but not in case of DELETED!
328 * Imagine that your co-author makes changes in an existing inset. He
329 * sends your document to you and you come to the conclusion that the
330 * inset should go completely. If you erase it, LyX must not delete all
331 * text within the inset. Otherwise, the change tracked insertions of
332 * your co-author get lost and there is no way to restore them later.
334 * Conclusion: An inset's content should remain untouched if you delete it
337 if (change.type != Change::DELETED) {
338 for (pos_type pos = 0; pos < size(); ++pos) {
339 if (Inset * inset = getInset(pos))
340 inset->setChange(change);
346 void Paragraph::setChange(pos_type pos, Change const & change)
348 LASSERT(pos >= 0 && pos <= size(), /**/);
349 d->changes_.set(change, pos);
351 // see comment in setChange(Change const &) above
352 if (change.type != Change::DELETED && pos < size())
353 if (Inset * inset = getInset(pos))
354 inset->setChange(change);
358 Change const & Paragraph::lookupChange(pos_type pos) const
360 LASSERT(pos >= 0 && pos <= size(), /**/);
361 return d->changes_.lookup(pos);
365 void Paragraph::acceptChanges(pos_type start, pos_type end)
367 LASSERT(start >= 0 && start <= size(), /**/);
368 LASSERT(end > start && end <= size() + 1, /**/);
370 for (pos_type pos = start; pos < end; ++pos) {
371 switch (lookupChange(pos).type) {
372 case Change::UNCHANGED:
373 // accept changes in nested inset
374 if (Inset * inset = getInset(pos))
375 inset->acceptChanges();
378 case Change::INSERTED:
379 d->changes_.set(Change(Change::UNCHANGED), pos);
380 // also accept changes in nested inset
381 if (Inset * inset = getInset(pos))
382 inset->acceptChanges();
385 case Change::DELETED:
386 // Suppress access to non-existent
387 // "end-of-paragraph char"
389 eraseChar(pos, false);
400 void Paragraph::rejectChanges(pos_type start, pos_type end)
402 LASSERT(start >= 0 && start <= size(), /**/);
403 LASSERT(end > start && end <= size() + 1, /**/);
405 for (pos_type pos = start; pos < end; ++pos) {
406 switch (lookupChange(pos).type) {
407 case Change::UNCHANGED:
408 // reject changes in nested inset
409 if (Inset * inset = getInset(pos))
410 inset->rejectChanges();
413 case Change::INSERTED:
414 // Suppress access to non-existent
415 // "end-of-paragraph char"
417 eraseChar(pos, false);
423 case Change::DELETED:
424 d->changes_.set(Change(Change::UNCHANGED), pos);
426 // Do NOT reject changes within a deleted inset!
427 // There may be insertions of a co-author inside of it!
435 void Paragraph::Private::insertChar(pos_type pos, char_type c,
436 Change const & change)
438 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
441 changes_.insert(change, pos);
443 // This is actually very common when parsing buffers (and
444 // maybe inserting ascii text)
445 if (pos == pos_type(text_.size())) {
446 // when appending characters, no need to update tables
451 text_.insert(text_.begin() + pos, c);
453 // Update the font table.
454 fontlist_.increasePosAfterPos(pos);
457 insetlist_.increasePosAfterPos(pos);
461 bool Paragraph::insertInset(pos_type pos, Inset * inset,
462 Change const & change)
464 LASSERT(inset, /**/);
465 LASSERT(pos >= 0 && pos <= size(), /**/);
467 // Paragraph::insertInset() can be used in cut/copy/paste operation where
468 // d->inset_owner_ is not set yet.
469 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
472 d->insertChar(pos, META_INSET, change);
473 LASSERT(d->text_[pos] == META_INSET, /**/);
475 // Add a new entry in the insetlist_.
476 d->insetlist_.insert(inset, pos);
481 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
483 LASSERT(pos >= 0 && pos <= size(), return false);
485 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
488 Change change = d->changes_.lookup(pos);
490 // set the character to DELETED if
491 // a) it was previously unchanged or
492 // b) it was inserted by a co-author
494 if (change.type == Change::UNCHANGED ||
495 (change.type == Change::INSERTED && change.author != 0)) {
496 setChange(pos, Change(Change::DELETED));
500 if (change.type == Change::DELETED)
504 // Don't physically access the imaginary end-of-paragraph character.
505 // eraseChar() can only mark it as DELETED. A physical deletion of
506 // end-of-par must be handled externally.
512 d->changes_.erase(pos);
514 // if it is an inset, delete the inset entry
515 if (d->text_[pos] == META_INSET)
516 d->insetlist_.erase(pos);
518 d->text_.erase(d->text_.begin() + pos);
520 // Update the fontlist_
521 d->fontlist_.erase(pos);
523 // Update the insetlist_
524 d->insetlist_.decreasePosAfterPos(pos);
530 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
532 LASSERT(start >= 0 && start <= size(), /**/);
533 LASSERT(end >= start && end <= size() + 1, /**/);
536 for (pos_type count = end - start; count; --count) {
537 if (!eraseChar(i, trackChanges))
544 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
545 char_type next, Encoding const & encoding)
547 // Writing next here may circumvent a possible font change between
548 // c and next. Since next is only output if it forms a surrogate pair
549 // with c we can ignore this:
550 // A font change inside a surrogate pair does not make sense and is
551 // hopefully impossible to input.
552 // FIXME: change tracking
553 // Is this correct WRT change tracking?
554 docstring const latex1 = encoding.latexChar(next);
555 docstring const latex2 = encoding.latexChar(c);
556 if (docstring(1, next) == latex1) {
557 // the encoding supports the combination
558 os << latex2 << latex1;
559 return latex1.length() + latex2.length();
561 os << latex1 << '{' << latex2 << '}';
562 return latex1.length() + latex2.length() + 2;
566 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
567 odocstream & os, TexRow & texrow,
569 unsigned int & column,
571 Layout const & style)
573 if (style.pass_thru || runparams.verbatim)
576 if (i + 1 < int(text_.size())) {
577 char_type next = text_[i + 1];
578 if (Encodings::isCombiningChar(next)) {
579 Encoding const & encoding = *(runparams.encoding);
580 // This space has an accent, so we must always output it.
581 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
586 if (lyxrc.plaintext_linelen > 0
587 && column > lyxrc.plaintext_linelen
589 && text_[i - 1] != ' '
590 && (i + 1 < int(text_.size()))
591 // same in FreeSpacing mode
592 && !owner_->isFreeSpacing()
593 // In typewriter mode, we want to avoid
594 // ! . ? : at the end of a line
595 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
596 && (text_[i - 1] == '.'
597 || text_[i - 1] == '?'
598 || text_[i - 1] == ':'
599 || text_[i - 1] == '!'))) {
602 texrow.start(owner_->id(), i + 1);
604 } else if (style.free_spacing) {
613 int Paragraph::Private::writeScriptChars(odocstream & os,
614 docstring const & ltx,
615 Change const & runningChange,
616 Encoding const & encoding,
619 // FIXME: modifying i here is not very nice...
621 // We only arrive here when a proper language for character text_[i] has
622 // not been specified (i.e., it could not be translated in the current
623 // latex encoding) or its latex translation has been forced, and it
624 // belongs to a known script.
625 // Parameter ltx contains the latex translation of text_[i] as specified
626 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
627 // The latex macro name "textXXX" specifies the script to which text_[i]
628 // belongs and we use it in order to check whether characters from the
629 // same script immediately follow, such that we can collect them in a
630 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
631 // for the first char but only "<spec>" for all subsequent chars.
632 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
633 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
634 string script = to_ascii(ltx.substr(1, brace1 - 1));
637 bool closing_brace = true;
638 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
639 // Correct encoding is being used, so we can avoid \textgreek.
642 closing_brace = false;
644 os << ltx.substr(pos, length);
645 int size = text_.size();
646 while (i + 1 < size) {
647 char_type const next = text_[i + 1];
648 // Stop here if next character belongs to another script
649 // or there is a change in change tracking status.
650 if (!Encodings::isKnownScriptChar(next, script) ||
651 runningChange != owner_->lookupChange(i + 1))
655 FontList::const_iterator cit = fontlist_.begin();
656 FontList::const_iterator end = fontlist_.end();
657 for (; cit != end; ++cit) {
658 if (cit->pos() >= i && !found) {
659 prev_font = cit->font();
662 if (cit->pos() >= i + 1)
665 // Stop here if there is a font attribute or encoding change.
666 if (found && cit != end && prev_font != cit->font())
668 docstring const latex = encoding.latexChar(next);
669 docstring::size_type const b1 =
670 latex.find_first_of(from_ascii("{"));
671 docstring::size_type const b2 =
672 latex.find_last_of(from_ascii("}"));
673 int const len = b2 - b1 - 1;
674 os << latex.substr(b1 + 1, len);
686 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
688 pos_type const len = str.length();
690 // is the paragraph large enough?
691 if (pos + len > int(text_.size()))
694 // does the wanted text start at point?
695 for (string::size_type i = 0; i < str.length(); ++i) {
696 // Caution: direct comparison of characters works only
697 // because str is pure ASCII.
698 if (str[i] != text_[pos + i])
702 return fontlist_.hasChangeInRange(pos, len);
706 void Paragraph::Private::latexInset(
707 BufferParams const & bparams,
710 OutputParams & runparams,
713 Font const & outerfont,
715 Change & running_change,
716 Layout const & style,
718 unsigned int & column)
720 Inset * inset = owner_->getInset(i);
721 LASSERT(inset, /**/);
723 if (style.pass_thru) {
724 inset->plaintext(os, runparams);
728 // FIXME: move this to InsetNewline::latex
729 if (inset->lyxCode() == NEWLINE_CODE) {
730 // newlines are handled differently here than
731 // the default in simpleTeXSpecialChars().
732 if (!style.newline_allowed) {
736 column += running_font.latexWriteEndChanges(
737 os, bparams, runparams,
742 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
745 basefont = owner_->getLayoutFont(bparams, outerfont);
746 running_font = basefont;
748 if (runparams.moving_arg)
753 texrow.start(owner_->id(), i + 1);
757 if (owner_->lookupChange(i).type == Change::DELETED) {
758 if( ++runparams.inDeletedInset == 1)
759 runparams.changeOfDeletedInset = owner_->lookupChange(i);
762 if (inset->canTrackChanges()) {
763 column += Changes::latexMarkChange(os, bparams, running_change,
764 Change(Change::UNCHANGED));
765 running_change = Change(Change::UNCHANGED);
769 odocstream::pos_type const len = os.tellp();
771 if (inset->forceLTR()
772 && running_font.isRightToLeft()
773 // ERT is an exception, it should be output with no decorations at all
774 && inset->lyxCode() != ERT_CODE) {
775 if (running_font.language()->lang() == "farsi")
782 // FIXME: Bug: we can have an empty font change here!
783 // if there has just been a font change, we are going to close it
784 // right now, which means stupid latex code like \textsf{}. AFAIK,
785 // this does not harm dvi output. A minor bug, thus (JMarc)
787 // Some insets cannot be inside a font change command.
788 // However, even such insets *can* be placed in \L or \R
789 // or their equivalents (for RTL language switches), so we don't
790 // close the language in those cases.
791 // ArabTeX, though, cannot handle this special behavior, it seems.
792 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
793 || running_font.language()->lang() == "arabic_arabtex";
794 if (open_font && inset->noFontChange()) {
795 bool closeLanguage = arabtex
796 || basefont.isRightToLeft() == running_font.isRightToLeft();
797 unsigned int count = running_font.latexWriteEndChanges(os,
798 bparams, runparams, basefont, basefont, closeLanguage);
800 // if any font properties were closed, update the running_font,
801 // making sure, however, to leave the language as it was
803 // FIXME: probably a better way to keep track of the old
804 // language, than copying the entire font?
805 Font const copy_font(running_font);
806 basefont = owner_->getLayoutFont(bparams, outerfont);
807 running_font = basefont;
809 running_font.setLanguage(copy_font.language());
810 // leave font open if language is still open
811 open_font = (running_font.language() == basefont.language());
813 runparams.local_font = &basefont;
820 tmp = inset->latex(os, runparams);
821 } catch (EncodingException & e) {
822 // add location information and throw again.
829 if (running_font.language()->lang() == "farsi")
836 for (int j = 0; j < tmp; ++j)
839 texrow.start(owner_->id(), i + 1);
842 column += os.tellp() - len;
845 if (owner_->lookupChange(i).type == Change::DELETED)
846 --runparams.inDeletedInset;
850 void Paragraph::Private::latexSpecialChar(
852 OutputParams const & runparams,
853 Font const & running_font,
854 Change const & running_change,
855 Layout const & style,
857 unsigned int & column)
859 char_type const c = text_[i];
861 if (style.pass_thru) {
863 // FIXME UNICODE: This can fail if c cannot
864 // be encoded in the current encoding.
869 if (runparams.verbatim) {
870 // FIXME UNICODE: This can fail if c cannot
871 // be encoded in the current encoding.
876 // If T1 font encoding is used, use the special
877 // characters it provides.
878 // NOTE: some languages reset the font encoding
880 if (!running_font.language()->internalFontEncoding()
881 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
884 // \tt font needs special treatment
885 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
886 && latexSpecialTypewriter(c, os, i, column))
889 // Otherwise, we use what LaTeX provides us.
892 os << "\\textbackslash{}";
896 os << "\\textless{}";
900 os << "\\textgreater{}";
911 os << "\\char`\\\"{}";
916 case '%': case '#': case '{':
924 os << "\\textasciitilde{}";
929 os << "\\textasciicircum{}";
936 // avoid being mistaken for optional arguments
944 // Blanks are printed before font switching.
945 // Sure? I am not! (try nice-latex)
946 // I am sure it's correct. LyX might be smarter
947 // in the future, but for now, nothing wrong is
953 if (latexSpecialPhrase(os, i, column, runparams))
959 Encoding const & encoding = *(runparams.encoding);
960 if (i + 1 < int(text_.size())) {
961 char_type next = text_[i + 1];
962 if (Encodings::isCombiningChar(next)) {
963 column += latexSurrogatePair(os, c, next, encoding) - 1;
969 docstring const latex = encoding.latexChar(c);
970 if (Encodings::isKnownScriptChar(c, script)
971 && prefixIs(latex, from_ascii("\\" + script)))
972 column += writeScriptChars(os, latex,
973 running_change, encoding, i) - 1;
974 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
975 // Prevent eating of a following
976 // space or command corruption by
977 // following characters
978 column += latex.length() + 1;
981 column += latex.length() - 1;
989 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
990 pos_type i, unsigned int & column)
996 // In T1 encoding, these characters exist
997 // but we should avoid ligatures
998 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1000 os << "\\textcompwordmark{}";
1007 // soul.sty breaks with \char`\"
1008 os << "\\textquotedbl{}";
1017 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1018 pos_type i, unsigned int & column)
1022 // within \ttfamily, "--" is merged to "-" (no endash)
1023 // so we avoid this rather irritating ligature
1024 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1031 // everything else has to be checked separately
1032 // (depending on the encoding)
1039 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1040 unsigned int & column, OutputParams const & runparams)
1042 // FIXME: if we have "LaTeX" with a font
1043 // change in the middle (before the 'T', then
1044 // the "TeX" part is still special cased.
1045 // Really we should only operate this on
1046 // "words" for some definition of word
1048 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1049 if (!isTextAt(special_phrases[pnr].phrase, i))
1051 if (runparams.moving_arg)
1053 os << special_phrases[pnr].macro;
1054 i += special_phrases[pnr].phrase.length() - 1;
1055 column += special_phrases[pnr].macro.length() - 1;
1062 void Paragraph::Private::validate(LaTeXFeatures & features,
1063 Layout const & layout) const
1065 // check the params.
1066 if (!params_.spacing().isDefault())
1067 features.require("setspace");
1070 features.useLayout(layout.name());
1073 fontlist_.validate(features);
1075 // then the indentation
1076 if (!params_.leftIndent().zero())
1077 features.require("ParagraphLeftIndent");
1080 InsetList::const_iterator icit = insetlist_.begin();
1081 InsetList::const_iterator iend = insetlist_.end();
1082 for (; icit != iend; ++icit) {
1084 icit->inset->validate(features);
1085 if (layout.needprotect &&
1086 icit->inset->lyxCode() == FOOT_CODE)
1087 features.require("NeedLyXFootnoteCode");
1091 // then the contents
1092 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1093 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1094 if (!special_phrases[pnr].builtin
1095 && isTextAt(special_phrases[pnr].phrase, i)) {
1096 features.require(special_phrases[pnr].phrase);
1100 Encodings::validate(text_[i], features);
1104 /////////////////////////////////////////////////////////////////////
1108 /////////////////////////////////////////////////////////////////////
1111 Layout const emptyParagraphLayout;
1114 Paragraph::Paragraph()
1115 : d(new Paragraph::Private(this, emptyParagraphLayout))
1122 Paragraph::Paragraph(Paragraph const & par)
1123 : itemdepth(par.itemdepth),
1124 d(new Paragraph::Private(*par.d, this))
1130 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1131 : itemdepth(par.itemdepth),
1132 d(new Paragraph::Private(*par.d, this, beg, end))
1138 Paragraph & Paragraph::operator=(Paragraph const & par)
1140 // needed as we will destroy the private part before copying it
1142 itemdepth = par.itemdepth;
1146 d = new Private(*par.d, this);
1153 Paragraph::~Paragraph()
1160 void Paragraph::write(ostream & os, BufferParams const & bparams,
1161 depth_type & dth) const
1163 // The beginning or end of a deeper (i.e. nested) area?
1164 if (dth != d->params_.depth()) {
1165 if (d->params_.depth() > dth) {
1166 while (d->params_.depth() > dth) {
1167 os << "\n\\begin_deeper";
1171 while (d->params_.depth() < dth) {
1172 os << "\n\\end_deeper";
1178 // First write the layout
1179 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1181 d->params_.write(os);
1183 Font font1(inherit_font, bparams.language);
1185 Change running_change = Change(Change::UNCHANGED);
1188 for (pos_type i = 0; i <= size(); ++i) {
1190 Change const change = lookupChange(i);
1191 Changes::lyxMarkChange(os, column, running_change, change);
1192 running_change = change;
1197 // Write font changes (ignore spelling markers)
1198 Font font2 = getFontSettings(bparams, i);
1199 font2.setMisspelled(false);
1200 if (font2 != font1) {
1201 font2.lyxWriteChanges(font1, os);
1206 char_type const c = d->text_[i];
1209 if (Inset const * inset = getInset(i)) {
1210 if (inset->directWrite()) {
1211 // international char, let it write
1212 // code directly so it's shorter in
1218 os << "\\begin_inset ";
1220 os << "\n\\end_inset\n\n";
1226 os << "\n\\backslash\n";
1230 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1237 if ((column > 70 && c == ' ')
1242 // this check is to amend a bug. LyX sometimes
1243 // inserts '\0' this could cause problems.
1245 os << to_utf8(docstring(1, c));
1247 LYXERR0("NUL char in structure.");
1253 os << "\n\\end_layout\n";
1257 void Paragraph::validate(LaTeXFeatures & features) const
1259 d->validate(features, *d->layout_);
1263 void Paragraph::insert(pos_type start, docstring const & str,
1264 Font const & font, Change const & change)
1266 for (size_t i = 0, n = str.size(); i != n ; ++i)
1267 insertChar(start + i, str[i], font, change);
1271 void Paragraph::appendChar(char_type c, Font const & font,
1272 Change const & change)
1275 d->changes_.insert(change, d->text_.size());
1276 // when appending characters, no need to update tables
1277 d->text_.push_back(c);
1278 setFont(d->text_.size() - 1, font);
1282 void Paragraph::appendString(docstring const & s, Font const & font,
1283 Change const & change)
1285 pos_type end = s.size();
1286 size_t oldsize = d->text_.size();
1287 size_t newsize = oldsize + end;
1288 size_t capacity = d->text_.capacity();
1289 if (newsize >= capacity)
1290 d->text_.reserve(max(capacity + 100, newsize));
1292 // when appending characters, no need to update tables
1295 // FIXME: Optimize this!
1296 for (size_t i = oldsize; i != newsize; ++i) {
1298 d->changes_.insert(change, i);
1300 d->fontlist_.set(oldsize, font);
1301 d->fontlist_.set(newsize - 1, font);
1305 void Paragraph::insertChar(pos_type pos, char_type c,
1308 d->insertChar(pos, c, Change(trackChanges ?
1309 Change::INSERTED : Change::UNCHANGED));
1313 void Paragraph::insertChar(pos_type pos, char_type c,
1314 Font const & font, bool trackChanges)
1316 d->insertChar(pos, c, Change(trackChanges ?
1317 Change::INSERTED : Change::UNCHANGED));
1322 void Paragraph::insertChar(pos_type pos, char_type c,
1323 Font const & font, Change const & change)
1325 d->insertChar(pos, c, change);
1330 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1331 Font const & font, Change const & change)
1333 bool const success = insertInset(pos, inset, change);
1334 // Set the font/language of the inset...
1340 void Paragraph::resetFonts(Font const & font)
1342 d->fontlist_.clear();
1343 d->fontlist_.set(0, font);
1344 d->fontlist_.set(d->text_.size() - 1, font);
1347 // Gets uninstantiated font setting at position.
1348 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1352 LYXERR0("pos: " << pos << " size: " << size());
1353 LASSERT(pos <= size(), /**/);
1356 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1357 if (cit != d->fontlist_.end())
1360 if (pos == size() && !empty())
1361 return getFontSettings(bparams, pos - 1);
1363 // Optimisation: avoid a full font instantiation if there is no
1364 // language change from previous call.
1365 static Font previous_font;
1366 static Language const * previous_lang = 0;
1367 Language const * lang = getParLanguage(bparams);
1368 if (lang != previous_lang) {
1369 previous_lang = lang;
1370 previous_font = Font(inherit_font, lang);
1372 return previous_font;
1376 FontSpan Paragraph::fontSpan(pos_type pos) const
1378 LASSERT(pos <= size(), /**/);
1381 FontList::const_iterator cit = d->fontlist_.begin();
1382 FontList::const_iterator end = d->fontlist_.end();
1383 for (; cit != end; ++cit) {
1384 if (cit->pos() >= pos) {
1385 if (pos >= beginOfBody())
1386 return FontSpan(max(start, beginOfBody()),
1389 return FontSpan(start,
1390 min(beginOfBody() - 1,
1393 start = cit->pos() + 1;
1396 // This should not happen, but if so, we take no chances.
1397 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1398 return FontSpan(pos, pos);
1402 // Gets uninstantiated font setting at position 0
1403 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1405 if (!empty() && !d->fontlist_.empty())
1406 return d->fontlist_.begin()->font();
1408 // Optimisation: avoid a full font instantiation if there is no
1409 // language change from previous call.
1410 static Font previous_font;
1411 static Language const * previous_lang = 0;
1412 if (bparams.language != previous_lang) {
1413 previous_lang = bparams.language;
1414 previous_font = Font(inherit_font, bparams.language);
1417 return previous_font;
1421 // Gets the fully instantiated font at a given position in a paragraph
1422 // This is basically the same function as Text::GetFont() in text2.cpp.
1423 // The difference is that this one is used for generating the LaTeX file,
1424 // and thus cosmetic "improvements" are disallowed: This has to deliver
1425 // the true picture of the buffer. (Asger)
1426 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1427 Font const & outerfont) const
1429 LASSERT(pos >= 0, /**/);
1431 Font font = getFontSettings(bparams, pos);
1433 pos_type const body_pos = beginOfBody();
1434 FontInfo & fi = font.fontInfo();
1436 fi.realize(d->layout_->labelfont);
1438 fi.realize(d->layout_->font);
1440 fi.realize(outerfont.fontInfo());
1441 fi.realize(bparams.getFont().fontInfo());
1447 Font const Paragraph::getLabelFont
1448 (BufferParams const & bparams, Font const & outerfont) const
1450 FontInfo tmpfont = d->layout_->labelfont;
1451 tmpfont.realize(outerfont.fontInfo());
1452 tmpfont.realize(bparams.getFont().fontInfo());
1453 return Font(tmpfont, getParLanguage(bparams));
1457 Font const Paragraph::getLayoutFont
1458 (BufferParams const & bparams, Font const & outerfont) const
1460 FontInfo tmpfont = d->layout_->font;
1461 tmpfont.realize(outerfont.fontInfo());
1462 tmpfont.realize(bparams.getFont().fontInfo());
1463 return Font(tmpfont, getParLanguage(bparams));
1467 /// Returns the height of the highest font in range
1468 FontSize Paragraph::highestFontInRange
1469 (pos_type startpos, pos_type endpos, FontSize def_size) const
1471 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1475 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1477 char_type c = d->text_[pos];
1478 if (!lyxrc.rtl_support)
1508 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1514 void Paragraph::setFont(pos_type pos, Font const & font)
1516 LASSERT(pos <= size(), /**/);
1518 // First, reduce font against layout/label font
1519 // Update: The setCharFont() routine in text2.cpp already
1520 // reduces font, so we don't need to do that here. (Asger)
1522 d->fontlist_.set(pos, font);
1526 void Paragraph::makeSameLayout(Paragraph const & par)
1528 d->layout_ = par.d->layout_;
1529 d->params_ = par.d->params_;
1533 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1535 if (isFreeSpacing())
1541 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1542 if (eraseChar(pos, trackChanges))
1548 return count > 0 || pos > 0;
1552 bool Paragraph::hasSameLayout(Paragraph const & par) const
1554 return par.d->layout_ == d->layout_
1555 && d->params_.sameLayout(par.d->params_);
1559 depth_type Paragraph::getDepth() const
1561 return d->params_.depth();
1565 depth_type Paragraph::getMaxDepthAfter() const
1567 if (d->layout_->isEnvironment())
1568 return d->params_.depth() + 1;
1570 return d->params_.depth();
1574 char Paragraph::getAlign() const
1576 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1577 return d->layout_->align;
1579 return d->params_.align();
1583 docstring const & Paragraph::labelString() const
1585 return d->params_.labelString();
1589 // the next two functions are for the manual labels
1590 docstring const Paragraph::getLabelWidthString() const
1592 if (d->layout_->margintype == MARGIN_MANUAL
1593 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1594 return d->params_.labelWidthString();
1596 return _("Senseless with this layout!");
1600 void Paragraph::setLabelWidthString(docstring const & s)
1602 d->params_.labelWidthString(s);
1606 docstring Paragraph::expandLabel(Layout const & layout,
1607 BufferParams const & bparams, bool process_appendix) const
1609 DocumentClass const & tclass = bparams.documentClass();
1610 string const & lang = getParLanguage(bparams)->code();
1611 bool const in_appendix = process_appendix && d->params_.appendix();
1612 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1614 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1615 && !layout.counter.empty())
1616 return tclass.counters().theCounter(layout.counter, lang);
1618 // handle 'inherited level parts' in 'fmt',
1619 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1620 size_t const i = fmt.find('@', 0);
1621 if (i != docstring::npos) {
1622 size_t const j = fmt.find('@', i + 1);
1623 if (j != docstring::npos) {
1624 docstring parent(fmt, i + 1, j - i - 1);
1625 docstring label = from_ascii("??");
1626 if (tclass.hasLayout(parent))
1627 docstring label = expandLabel(tclass[parent], bparams,
1629 fmt = docstring(fmt, 0, i) + label
1630 + docstring(fmt, j + 1, docstring::npos);
1634 return tclass.counters().counterLabel(fmt, lang);
1638 void Paragraph::applyLayout(Layout const & new_layout)
1640 d->layout_ = &new_layout;
1641 LyXAlignment const oldAlign = d->params_.align();
1643 if (!(oldAlign & d->layout_->alignpossible)) {
1644 frontend::Alert::warning(_("Alignment not permitted"),
1645 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1646 d->params_.align(LYX_ALIGN_LAYOUT);
1651 pos_type Paragraph::beginOfBody() const
1653 return d->begin_of_body_;
1657 void Paragraph::setBeginOfBody()
1659 if (d->layout_->labeltype != LABEL_MANUAL) {
1660 d->begin_of_body_ = 0;
1664 // Unroll the first two cycles of the loop
1665 // and remember the previous character to
1666 // remove unnecessary getChar() calls
1668 pos_type end = size();
1669 if (i < end && !isNewline(i)) {
1671 char_type previous_char = 0;
1674 previous_char = d->text_[i];
1675 if (!isNewline(i)) {
1677 while (i < end && previous_char != ' ') {
1682 previous_char = temp;
1688 d->begin_of_body_ = i;
1692 bool Paragraph::forcePlainLayout() const
1694 return inInset().forcePlainLayout();
1698 bool Paragraph::allowParagraphCustomization() const
1700 return inInset().allowParagraphCustomization();
1704 bool Paragraph::usePlainLayout() const
1706 return inInset().usePlainLayout();
1712 // paragraphs inside floats need different alignment tags to avoid
1715 bool noTrivlistCentering(InsetCode code)
1717 return code == FLOAT_CODE
1718 || code == WRAP_CODE
1719 || code == CELL_CODE;
1723 string correction(string const & orig)
1725 if (orig == "flushleft")
1726 return "raggedright";
1727 if (orig == "flushright")
1728 return "raggedleft";
1729 if (orig == "center")
1735 string const corrected_env(string const & suffix, string const & env,
1736 InsetCode code, bool const lastpar)
1738 string output = suffix + "{";
1739 if (noTrivlistCentering(code)) {
1741 // the last paragraph in non-trivlist-aligned
1742 // context is special (to avoid unwanted whitespace)
1743 if (suffix == "\\begin")
1744 return "\\" + correction(env) + "{}";
1747 output += correction(env);
1751 if (suffix == "\\begin")
1757 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1759 if (!contains(str, "\n"))
1760 column += str.size();
1764 column = rsplit(str, tmp, '\n').size();
1771 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1772 odocstream & os, TexRow & texrow,
1773 OutputParams const & runparams) const
1777 if (params_.noindent()) {
1778 os << "\\noindent ";
1782 LyXAlignment const curAlign = params_.align();
1784 if (curAlign == layout_->align)
1788 case LYX_ALIGN_NONE:
1789 case LYX_ALIGN_BLOCK:
1790 case LYX_ALIGN_LAYOUT:
1791 case LYX_ALIGN_SPECIAL:
1793 case LYX_ALIGN_LEFT:
1794 case LYX_ALIGN_RIGHT:
1795 case LYX_ALIGN_CENTER:
1796 if (runparams.moving_arg) {
1803 string const begin_tag = "\\begin";
1804 InsetCode code = owner_->ownerCode();
1805 bool const lastpar = runparams.isLastPar;
1808 case LYX_ALIGN_NONE:
1809 case LYX_ALIGN_BLOCK:
1810 case LYX_ALIGN_LAYOUT:
1811 case LYX_ALIGN_SPECIAL:
1813 case LYX_ALIGN_LEFT: {
1815 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1816 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1818 output = corrected_env(begin_tag, "flushright", code, lastpar);
1819 os << from_ascii(output);
1820 adjust_row_column(output, texrow, column);
1822 } case LYX_ALIGN_RIGHT: {
1824 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1825 output = corrected_env(begin_tag, "flushright", code, lastpar);
1827 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1828 os << from_ascii(output);
1829 adjust_row_column(output, texrow, column);
1831 } case LYX_ALIGN_CENTER: {
1833 output = corrected_env(begin_tag, "center", code, lastpar);
1834 os << from_ascii(output);
1835 adjust_row_column(output, texrow, column);
1844 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1845 odocstream & os, TexRow & texrow,
1846 OutputParams const & runparams) const
1850 LyXAlignment const curAlign = params_.align();
1852 if (curAlign == layout_->align)
1856 case LYX_ALIGN_NONE:
1857 case LYX_ALIGN_BLOCK:
1858 case LYX_ALIGN_LAYOUT:
1859 case LYX_ALIGN_SPECIAL:
1861 case LYX_ALIGN_LEFT:
1862 case LYX_ALIGN_RIGHT:
1863 case LYX_ALIGN_CENTER:
1864 if (runparams.moving_arg) {
1871 string const end_tag = "\n\\par\\end";
1872 InsetCode code = owner_->ownerCode();
1873 bool const lastpar = runparams.isLastPar;
1876 case LYX_ALIGN_NONE:
1877 case LYX_ALIGN_BLOCK:
1878 case LYX_ALIGN_LAYOUT:
1879 case LYX_ALIGN_SPECIAL:
1881 case LYX_ALIGN_LEFT: {
1883 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1884 output = corrected_env(end_tag, "flushleft", code, lastpar);
1886 output = corrected_env(end_tag, "flushright", code, lastpar);
1887 os << from_ascii(output);
1888 adjust_row_column(output, texrow, column);
1890 } case LYX_ALIGN_RIGHT: {
1892 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1893 output = corrected_env(end_tag, "flushright", code, lastpar);
1895 output = corrected_env(end_tag, "flushleft", code, lastpar);
1896 os << from_ascii(output);
1897 adjust_row_column(output, texrow, column);
1899 } case LYX_ALIGN_CENTER: {
1901 output = corrected_env(end_tag, "center", code, lastpar);
1902 os << from_ascii(output);
1903 adjust_row_column(output, texrow, column);
1912 // This one spits out the text of the paragraph
1913 bool Paragraph::latex(BufferParams const & bparams,
1914 Font const & outerfont,
1915 odocstream & os, TexRow & texrow,
1916 OutputParams const & runparams,
1917 int start_pos, int end_pos) const
1919 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1921 bool return_value = false;
1923 bool const allowcust = allowParagraphCustomization();
1925 // FIXME This check should not be needed. Perhaps issue an
1926 // error if it triggers.
1927 Layout const & style = forcePlainLayout() ?
1928 bparams.documentClass().plainLayout() : *d->layout_;
1930 // Current base font for all inherited font changes, without any
1931 // change caused by an individual character, except for the language:
1932 // It is set to the language of the first character.
1933 // As long as we are in the label, this font is the base font of the
1934 // label. Before the first body character it is set to the base font
1938 // Maybe we have to create a optional argument.
1939 pos_type body_pos = beginOfBody();
1940 unsigned int column = 0;
1945 basefont = getLabelFont(bparams, outerfont);
1947 basefont = getLayoutFont(bparams, outerfont);
1950 // Which font is currently active?
1951 Font running_font(basefont);
1952 // Do we have an open font change?
1953 bool open_font = false;
1955 Change runningChange = Change(Change::UNCHANGED);
1957 texrow.start(id(), 0);
1959 // if the paragraph is empty, the loop will not be entered at all
1961 if (style.isCommand()) {
1966 column += d->startTeXParParams(bparams, os, texrow,
1970 for (pos_type i = 0; i < size(); ++i) {
1971 // First char in paragraph or after label?
1972 if (i == body_pos) {
1975 column += running_font.latexWriteEndChanges(
1976 os, bparams, runparams,
1977 basefont, basefont);
1980 basefont = getLayoutFont(bparams, outerfont);
1981 running_font = basefont;
1983 column += Changes::latexMarkChange(os, bparams,
1984 runningChange, Change(Change::UNCHANGED));
1985 runningChange = Change(Change::UNCHANGED);
1990 if (style.isCommand()) {
1996 column += d->startTeXParParams(bparams, os,
2001 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2004 if (bparams.outputChanges && runningChange != change) {
2006 column += running_font.latexWriteEndChanges(
2007 os, bparams, runparams, basefont, basefont);
2010 basefont = getLayoutFont(bparams, outerfont);
2011 running_font = basefont;
2013 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2014 runningChange = change;
2017 // do not output text which is marked deleted
2018 // if change tracking output is disabled
2019 if (!bparams.outputChanges && change.type == Change::DELETED) {
2025 // Fully instantiated font
2026 Font const font = getFont(bparams, i, outerfont);
2028 Font const last_font = running_font;
2030 // Do we need to close the previous font?
2032 (font != running_font ||
2033 font.language() != running_font.language()))
2035 column += running_font.latexWriteEndChanges(
2036 os, bparams, runparams, basefont,
2037 (i == body_pos-1) ? basefont : font);
2038 running_font = basefont;
2042 // close babel's font environment before opening CJK.
2043 if (!running_font.language()->babel().empty() &&
2044 font.language()->encoding()->package() == Encoding::CJK) {
2045 string end_tag = subst(lyxrc.language_command_end,
2047 running_font.language()->babel());
2048 os << from_ascii(end_tag);
2049 column += end_tag.length();
2052 // Switch file encoding if necessary (and allowed)
2053 if (!runparams.verbatim &&
2054 runparams.encoding->package() != Encoding::none &&
2055 font.language()->encoding()->package() != Encoding::none) {
2056 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2057 runparams, *(font.language()->encoding()));
2058 if (enc_switch.first) {
2059 column += enc_switch.second;
2060 runparams.encoding = font.language()->encoding();
2064 char_type const c = d->text_[i];
2066 // Do we need to change font?
2067 if ((font != running_font ||
2068 font.language() != running_font.language()) &&
2071 odocstringstream ods;
2072 column += font.latexWriteStartChanges(ods, bparams,
2073 runparams, basefont,
2075 running_font = font;
2077 docstring fontchange = ods.str();
2078 // check if the fontchange ends with a trailing blank
2079 // (like "\small " (see bug 3382)
2080 if (suffixIs(fontchange, ' ') && c == ' ')
2081 os << fontchange.substr(0, fontchange.size() - 1)
2082 << from_ascii("{}");
2087 // FIXME: think about end_pos implementation...
2088 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2089 // FIXME: integrate this case in latexSpecialChar
2090 // Do not print the separation of the optional argument
2091 // if style.pass_thru is false. This works because
2092 // latexSpecialChar ignores spaces if
2093 // style.pass_thru is false.
2094 if (i != body_pos - 1) {
2095 if (d->simpleTeXBlanks(
2096 runparams, os, texrow,
2097 i, column, font, style)) {
2098 // A surrogate pair was output. We
2099 // must not call latexSpecialChar
2100 // in this iteration, since it would output
2101 // the combining character again.
2108 OutputParams rp = runparams;
2109 rp.free_spacing = style.free_spacing;
2110 rp.local_font = &font;
2111 rp.intitle = style.intitle;
2113 // Two major modes: LaTeX or plain
2114 // Handle here those cases common to both modes
2115 // and then split to handle the two modes separately.
2116 if (c == META_INSET) {
2117 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2118 d->latexInset(bparams, os,
2119 texrow, rp, running_font,
2120 basefont, outerfont, open_font,
2121 runningChange, style, i, column);
2124 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2126 d->latexSpecialChar(os, rp, running_font, runningChange,
2128 } catch (EncodingException & e) {
2129 if (runparams.dryrun) {
2130 os << "<" << _("LyX Warning: ")
2131 << _("uncodable character") << " '";
2135 // add location information and throw again.
2144 // Set the encoding to that returned from latexSpecialChar (see
2145 // comment for encoding member in OutputParams.h)
2146 runparams.encoding = rp.encoding;
2149 // If we have an open font definition, we have to close it
2151 #ifdef FIXED_LANGUAGE_END_DETECTION
2154 .latexWriteEndChanges(os, bparams, runparams,
2156 next_->getFont(bparams, 0, outerfont));
2158 running_font.latexWriteEndChanges(os, bparams,
2159 runparams, basefont, basefont);
2162 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2163 //FIXME: there as we start another \selectlanguage with the next paragraph if
2164 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2165 running_font.latexWriteEndChanges(os, bparams, runparams,
2166 basefont, basefont);
2170 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2172 // Needed if there is an optional argument but no contents.
2173 if (body_pos > 0 && body_pos == size()) {
2175 return_value = false;
2179 column += d->endTeXParParams(bparams, os, texrow,
2183 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2184 return return_value;
2188 bool Paragraph::emptyTag() const
2190 for (pos_type i = 0; i < size(); ++i) {
2191 if (Inset const * inset = getInset(i)) {
2192 InsetCode lyx_code = inset->lyxCode();
2193 if (lyx_code != TOC_CODE &&
2194 lyx_code != INCLUDE_CODE &&
2195 lyx_code != GRAPHICS_CODE &&
2196 lyx_code != ERT_CODE &&
2197 lyx_code != LISTINGS_CODE &&
2198 lyx_code != FLOAT_CODE &&
2199 lyx_code != TABULAR_CODE) {
2203 char_type c = d->text_[i];
2204 if (c != ' ' && c != '\t')
2212 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2215 for (pos_type i = 0; i < size(); ++i) {
2216 if (Inset const * inset = getInset(i)) {
2217 InsetCode lyx_code = inset->lyxCode();
2218 if (lyx_code == LABEL_CODE) {
2219 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2220 docstring const & id = il->getParam("name");
2221 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2229 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2233 for (i = 0; i < size(); ++i) {
2234 if (Inset const * inset = getInset(i)) {
2235 inset->docbook(os, runparams);
2237 char_type c = d->text_[i];
2240 os << sgml::escapeChar(c);
2247 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2251 for (i = 0; i < size(); ++i) {
2252 if (Inset const * inset = getInset(i)) {
2253 inset->xhtml(os, runparams);
2255 char_type c = d->text_[i];
2258 os << html::escapeChar(c);
2265 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2268 pos_type size = text_.size();
2269 for (pos_type i = initial; i < size; ++i) {
2270 Font font = owner_->getFont(buf.params(), i, outerfont);
2271 if (text_[i] == META_INSET)
2273 if (i != initial && font != font_old)
2282 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2284 OutputParams const & runparams,
2285 Font const & outerfont,
2286 pos_type initial) const
2288 bool emph_flag = false;
2290 Layout const & style = *d->layout_;
2292 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2294 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2297 // parsing main loop
2298 for (pos_type i = initial; i < size(); ++i) {
2299 Font font = getFont(buf.params(), i, outerfont);
2301 // handle <emphasis> tag
2302 if (font_old.emph() != font.fontInfo().emph()) {
2303 if (font.fontInfo().emph() == FONT_ON) {
2306 } else if (i != initial) {
2307 os << "</emphasis>";
2312 if (Inset const * inset = getInset(i)) {
2313 inset->docbook(os, runparams);
2315 char_type c = d->text_[i];
2317 if (style.pass_thru)
2320 os << sgml::escapeChar(c);
2322 font_old = font.fontInfo();
2326 os << "</emphasis>";
2329 if (style.free_spacing)
2331 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2336 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2338 OutputParams const & runparams,
2339 Font const & outerfont,
2340 pos_type initial) const
2344 // FIXME We really need to manage the tag nesting here.
2345 // Probably in the same sort of way as in output_xhtml.
2346 bool emph_flag = false;
2347 bool bold_flag = false;
2348 std::string closing_tag;
2350 Layout const & style = *d->layout_;
2352 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2354 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2357 // parsing main loop
2358 for (pos_type i = initial; i < size(); ++i) {
2359 Font font = getFont(buf.params(), i, outerfont);
2362 if (font_old.emph() != font.fontInfo().emph()) {
2363 if (font.fontInfo().emph() == FONT_ON) {
2366 } else if (emph_flag && i != initial) {
2372 if (font_old.series() != font.fontInfo().series()) {
2373 if (font.fontInfo().series() == BOLD_SERIES) {
2376 } else if (bold_flag && i != initial) {
2381 // FIXME Other such tags?
2383 if (Inset const * inset = getInset(i)) {
2384 retval += inset->xhtml(os, runparams);
2386 char_type c = d->text_[i];
2388 if (style.pass_thru)
2390 else if (c == '-') {
2393 if (j < size() && d->text_[j] == '-') {
2395 if (j < size() && d->text_[j] == '-') {
2396 str += from_ascii("—");
2399 str += from_ascii("–");
2407 os << html::escapeChar(c);
2409 font_old = font.fontInfo();
2412 // FIXME This could be out of order. See above.
2422 bool Paragraph::isHfill(pos_type pos) const
2424 Inset const * inset = getInset(pos);
2425 return inset && (inset->lyxCode() == SPACE_CODE &&
2426 inset->isStretchableSpace());
2430 bool Paragraph::isNewline(pos_type pos) const
2432 Inset const * inset = getInset(pos);
2433 return inset && inset->lyxCode() == NEWLINE_CODE;
2437 bool Paragraph::isLineSeparator(pos_type pos) const
2439 char_type const c = d->text_[pos];
2440 if (isLineSeparatorChar(c))
2442 Inset const * inset = getInset(pos);
2443 return inset && inset->isLineSeparator();
2447 bool Paragraph::isWordSeparator(pos_type pos) const
2449 if (Inset const * inset = getInset(pos))
2450 return !inset->isLetter();
2451 char_type const c = d->text_[pos];
2452 // We want to pass the ' and escape chars to the spellchecker
2453 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2454 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2459 bool Paragraph::isChar(pos_type pos) const
2461 if (Inset const * inset = getInset(pos))
2462 return inset->isChar();
2463 char_type const c = d->text_[pos];
2464 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2468 bool Paragraph::isSpace(pos_type pos) const
2470 if (Inset const * inset = getInset(pos))
2471 return inset->isSpace();
2472 char_type const c = d->text_[pos];
2473 return lyx::isSpace(c);
2478 Paragraph::getParLanguage(BufferParams const & bparams) const
2481 return getFirstFontSettings(bparams).language();
2482 // FIXME: we should check the prev par as well (Lgb)
2483 return bparams.language;
2487 bool Paragraph::isRTL(BufferParams const & bparams) const
2489 return lyxrc.rtl_support
2490 && getParLanguage(bparams)->rightToLeft()
2491 && ownerCode() != ERT_CODE
2492 && ownerCode() != LISTINGS_CODE;
2496 void Paragraph::changeLanguage(BufferParams const & bparams,
2497 Language const * from, Language const * to)
2499 // change language including dummy font change at the end
2500 for (pos_type i = 0; i <= size(); ++i) {
2501 Font font = getFontSettings(bparams, i);
2502 if (font.language() == from) {
2503 font.setLanguage(to);
2510 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2512 Language const * doc_language = bparams.language;
2513 FontList::const_iterator cit = d->fontlist_.begin();
2514 FontList::const_iterator end = d->fontlist_.end();
2516 for (; cit != end; ++cit)
2517 if (cit->font().language() != ignore_language &&
2518 cit->font().language() != latex_language &&
2519 cit->font().language() != doc_language)
2525 docstring Paragraph::asString(int options) const
2527 return asString(0, size(), options);
2531 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2533 odocstringstream os;
2536 && options & AS_STR_LABEL
2537 && !d->params_.labelString().empty())
2538 os << d->params_.labelString() << ' ';
2540 for (pos_type i = beg; i < end; ++i) {
2541 char_type const c = d->text_[i];
2542 if (isPrintable(c) || c == '\t'
2543 || (c == '\n' && options & AS_STR_NEWLINES))
2545 else if (c == META_INSET && options & AS_STR_INSETS)
2546 getInset(i)->tocString(os);
2553 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2555 odocstringstream os;
2558 && options & AS_STR_LABEL
2559 && !d->params_.labelString().empty())
2560 os << d->params_.labelString() << ' ';
2562 for (pos_type i = beg; i < end; ++i) {
2563 char_type const c = d->text_[i];
2564 if (isPrintable(c) || c == '\t'
2565 || (c == '\n' && options & AS_STR_NEWLINES))
2567 else if (c == META_INSET && options & AS_STR_INSETS) {
2568 getInset(i)->plaintext(os, runparams);
2576 void Paragraph::setInsetOwner(Inset const * inset)
2578 d->inset_owner_ = inset;
2582 int Paragraph::id() const
2588 Layout const & Paragraph::layout() const
2594 void Paragraph::setLayout(Layout const & layout)
2596 d->layout_ = &layout;
2600 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2602 setLayout(tc.defaultLayout());
2606 void Paragraph::setPlainLayout(DocumentClass const & tc)
2608 setLayout(tc.plainLayout());
2612 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2614 if (usePlainLayout())
2615 setPlainLayout(tclass);
2617 setDefaultLayout(tclass);
2621 Inset const & Paragraph::inInset() const
2623 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2624 _("Memory problem"), _("Paragraph not properly initialized")));
2625 return *d->inset_owner_;
2629 InsetCode Paragraph::ownerCode() const
2631 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2635 ParagraphParameters & Paragraph::params()
2641 ParagraphParameters const & Paragraph::params() const
2647 bool Paragraph::isFreeSpacing() const
2649 if (d->layout_->free_spacing)
2651 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2655 bool Paragraph::allowEmpty() const
2657 if (d->layout_->keepempty)
2659 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2663 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2665 if (!Encodings::isArabicChar(c))
2668 char_type prev_char = ' ';
2669 char_type next_char = ' ';
2671 for (pos_type i = pos - 1; i >= 0; --i) {
2672 char_type const par_char = d->text_[i];
2673 if (!Encodings::isArabicComposeChar(par_char)) {
2674 prev_char = par_char;
2679 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2680 char_type const par_char = d->text_[i];
2681 if (!Encodings::isArabicComposeChar(par_char)) {
2682 next_char = par_char;
2687 if (Encodings::isArabicChar(next_char)) {
2688 if (Encodings::isArabicChar(prev_char) &&
2689 !Encodings::isArabicSpecialChar(prev_char))
2690 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2692 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2694 if (Encodings::isArabicChar(prev_char) &&
2695 !Encodings::isArabicSpecialChar(prev_char))
2696 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2698 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2703 int Paragraph::checkBiblio(Buffer const & buffer)
2706 // This is getting more and more a mess. ...We really should clean
2707 // up this bibitem issue for 1.6. See also bug 2743.
2709 // Add bibitem insets if necessary
2710 if (d->layout_->labeltype != LABEL_BIBLIO)
2713 bool hasbibitem = !d->insetlist_.empty()
2714 // Insist on it being in pos 0
2715 && d->text_[0] == META_INSET
2716 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2718 bool track_changes = buffer.params().trackChanges;
2723 // remove a bibitem in pos != 0
2724 // restore it later in pos 0 if necessary
2725 // (e.g. if a user inserts contents _before_ the item)
2726 // we're assuming there's only one of these, which there
2728 int erasedInsetPosition = -1;
2729 InsetList::iterator it = d->insetlist_.begin();
2730 InsetList::iterator end = d->insetlist_.end();
2731 for (; it != end; ++it)
2732 if (it->inset->lyxCode() == BIBITEM_CODE
2734 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2735 oldkey = olditem->getParam("key");
2736 oldlabel = olditem->getParam("label");
2737 erasedInsetPosition = it->pos;
2738 eraseChar(erasedInsetPosition, track_changes);
2742 // There was an InsetBibitem at the beginning, and we didn't
2743 // have to erase one.
2744 if (hasbibitem && erasedInsetPosition < 0)
2747 // There was an InsetBibitem at the beginning and we did have to
2748 // erase one. So we give its properties to the beginning inset.
2750 InsetBibitem * inset =
2751 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2752 if (!oldkey.empty())
2753 inset->setParam("key", oldkey);
2754 inset->setParam("label", oldlabel);
2755 return -erasedInsetPosition;
2758 // There was no inset at the beginning, so we need to create one with
2759 // the key and label of the one we erased.
2760 InsetBibitem * inset =
2761 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2762 // restore values of previously deleted item in this par.
2763 if (!oldkey.empty())
2764 inset->setParam("key", oldkey);
2765 inset->setParam("label", oldlabel);
2766 insertInset(0, static_cast<Inset *>(inset),
2767 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2773 void Paragraph::checkAuthors(AuthorList const & authorList)
2775 d->changes_.checkAuthors(authorList);
2779 bool Paragraph::isUnchanged(pos_type pos) const
2781 return lookupChange(pos).type == Change::UNCHANGED;
2785 bool Paragraph::isInserted(pos_type pos) const
2787 return lookupChange(pos).type == Change::INSERTED;
2791 bool Paragraph::isDeleted(pos_type pos) const
2793 return lookupChange(pos).type == Change::DELETED;
2797 InsetList const & Paragraph::insetList() const
2799 return d->insetlist_;
2803 void Paragraph::setBuffer(Buffer & b)
2805 d->insetlist_.setBuffer(b);
2809 Inset * Paragraph::releaseInset(pos_type pos)
2811 Inset * inset = d->insetlist_.release(pos);
2812 /// does not honour change tracking!
2813 eraseChar(pos, false);
2818 Inset * Paragraph::getInset(pos_type pos)
2820 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2821 ? d->insetlist_.get(pos) : 0;
2825 Inset const * Paragraph::getInset(pos_type pos) const
2827 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2828 ? d->insetlist_.get(pos) : 0;
2832 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2833 pos_type & right, TextCase action)
2835 // process sequences of modified characters; in change
2836 // tracking mode, this approach results in much better
2837 // usability than changing case on a char-by-char basis
2840 bool const trackChanges = bparams.trackChanges;
2842 bool capitalize = true;
2844 for (; pos < right; ++pos) {
2845 char_type oldChar = d->text_[pos];
2846 char_type newChar = oldChar;
2848 // ignore insets and don't play with deleted text!
2849 if (oldChar != META_INSET && !isDeleted(pos)) {
2851 case text_lowercase:
2852 newChar = lowercase(oldChar);
2854 case text_capitalization:
2856 newChar = uppercase(oldChar);
2860 case text_uppercase:
2861 newChar = uppercase(oldChar);
2866 if (isWordSeparator(pos) || isDeleted(pos)) {
2867 // permit capitalization again
2871 if (oldChar != newChar) {
2873 if (pos != right - 1)
2875 // step behind the changing area
2879 int erasePos = pos - changes.size();
2880 for (size_t i = 0; i < changes.size(); i++) {
2881 insertChar(pos, changes[i],
2882 getFontSettings(bparams,
2885 if (!eraseChar(erasePos, trackChanges)) {
2888 ++right; // expand selection
2896 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2897 pos_type pos, bool del) const
2899 int const strsize = str.length();
2901 pos_type const parsize = d->text_.size();
2902 for (i = 0; pos + i < parsize; ++i) {
2905 if (cs && str[i] != d->text_[pos + i])
2907 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2909 if (!del && isDeleted(pos + i))
2916 // if necessary, check whether string matches word
2918 if (pos > 0 && !isWordSeparator(pos - 1))
2920 if (pos + strsize < parsize
2921 && !isWordSeparator(pos + strsize))
2929 char_type Paragraph::getChar(pos_type pos) const
2931 return d->text_[pos];
2935 pos_type Paragraph::size() const
2937 return d->text_.size();
2941 bool Paragraph::empty() const
2943 return d->text_.empty();
2947 bool Paragraph::isInset(pos_type pos) const
2949 return d->text_[pos] == META_INSET;
2953 bool Paragraph::isSeparator(pos_type pos) const
2955 //FIXME: Are we sure this can be the only separator?
2956 return d->text_[pos] == ' ';
2960 void Paragraph::deregisterWords()
2962 Private::Words::const_iterator it;
2963 WordList & wl = theWordList();
2964 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2970 void Paragraph::locateWord(pos_type & from, pos_type & to,
2971 word_location const loc) const
2974 case WHOLE_WORD_STRICT:
2975 if (from == 0 || from == size()
2976 || isWordSeparator(from)
2977 || isWordSeparator(from - 1)) {
2981 // no break here, we go to the next
2984 // If we are already at the beginning of a word, do nothing
2985 if (!from || isWordSeparator(from - 1))
2987 // no break here, we go to the next
2990 // always move the cursor to the beginning of previous word
2991 while (from && !isWordSeparator(from - 1))
2995 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
2998 // no need to move the 'from' cursor
3002 while (to < size() && !isWordSeparator(to))
3007 void Paragraph::collectWords()
3009 pos_type n = size();
3011 docstring_list suggestions;
3012 for (pos_type pos = 0; pos < n; ++pos) {
3013 if (isWordSeparator(pos))
3015 pos_type from = pos;
3016 locateWord(from, pos, WHOLE_WORD);
3017 if (pos - from >= 6) {
3018 docstring word = asString(from, pos, AS_STR_NONE);
3019 d->words_.insert(word);
3021 if (lyxrc.spellcheck_continuously
3022 && spellCheck(from, pos, wl, suggestions)) {
3023 for (size_t i = 0; i != suggestions.size(); ++i)
3024 d->words_.insert(suggestions[i]);
3030 void Paragraph::registerWords()
3032 Private::Words::const_iterator it;
3033 WordList & wl = theWordList();
3034 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3039 void Paragraph::updateWords()
3047 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3048 docstring_list & suggestions) const
3050 SpellChecker * speller = theSpellChecker();
3054 locateWord(from, to, WHOLE_WORD);
3055 if (from == to || from >= pos_type(d->text_.size()))
3058 docstring word = asString(from, to, AS_STR_INSETS);
3059 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3060 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3061 : lyxrc.spellchecker_alt_lang;
3062 wl = WordLangTuple(word, lang_code);
3063 SpellChecker::Result res = speller->check(wl);
3064 // Just ignore any error that the spellchecker reports.
3065 // FIXME: we should through out an exception and catch it in the GUI to
3066 // display the error.
3067 if (!speller->error().empty())
3070 bool const misspelled = res != SpellChecker::OK
3071 && res != SpellChecker::IGNORED_WORD;
3073 if (lyxrc.spellcheck_continuously)
3074 d->fontlist_.setMisspelled(from, to, misspelled);
3077 while (!(word = speller->nextMiss()).empty())
3078 suggestions.push_back(word);
3084 bool Paragraph::isMisspelled(pos_type pos) const
3086 pos_type from = pos;
3089 docstring_list suggestions;
3090 return spellCheck(from, to, wl, suggestions);