3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
22 #include "LayoutFile.h"
24 #include "BufferParams.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "paragraph_funcs.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
76 /////////////////////////////////////////////////////////////////////
80 /////////////////////////////////////////////////////////////////////
82 class Paragraph::Private
86 Private(Paragraph * owner, Layout const & layout);
87 /// "Copy constructor"
88 Private(Private const &, Paragraph * owner);
89 /// Copy constructor from \p beg to \p end
90 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
93 void insertChar(pos_type pos, char_type c, Change const & change);
95 /// Output the surrogate pair formed by \p c and \p next to \p os.
96 /// \return the number of characters written.
97 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98 OutputParams const &);
100 /// Output a space in appropriate formatting (or a surrogate pair
101 /// if the next character is a combining character).
102 /// \return whether a surrogate pair was output.
103 bool simpleTeXBlanks(OutputParams const &,
104 odocstream &, TexRow & texrow,
106 unsigned int & column,
108 Layout const & style);
110 /// Output consecutive unicode chars, belonging to the same script as
111 /// specified by the latex macro \p ltx, to \p os starting from \p i.
112 /// \return the number of characters written.
113 int writeScriptChars(odocstream & os, docstring const & ltx,
114 Change const &, Encoding const &, pos_type & i);
116 /// This could go to ParagraphParameters if we want to.
117 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 OutputParams const &) const;
120 /// This could go to ParagraphParameters if we want to.
121 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122 OutputParams const &) const;
125 void latexInset(BufferParams const &,
127 TexRow & texrow, OutputParams &,
130 Font const & outerfont,
132 Change & running_change,
133 Layout const & style,
135 unsigned int & column);
138 void latexSpecialChar(
140 OutputParams const & runparams,
141 Font const & running_font,
142 Change const & running_change,
143 Layout const & style,
145 unsigned int & column);
152 unsigned int & column);
154 bool latexSpecialTypewriter(
158 unsigned int & column);
160 bool latexSpecialPhrase(
163 unsigned int & column,
164 OutputParams const & runparams);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(string const & str, pos_type pos) const;
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, OutputParams const & runparams)
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 Encoding const & encoding = *(runparams.encoding);
555 docstring const latex1 = encoding.latexChar(next);
556 docstring const latex2 = encoding.latexChar(c);
557 if (docstring(1, next) == latex1) {
558 // the encoding supports the combination
559 os << latex2 << latex1;
560 return latex1.length() + latex2.length();
561 } else if (runparams.local_font->language()->lang() == "polutonikogreek") {
562 // polutonikogreek only works without the brackets
563 os << latex1 << latex2;
564 return latex1.length() + latex2.length();
566 os << latex1 << '{' << latex2 << '}';
567 return latex1.length() + latex2.length() + 2;
571 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
572 odocstream & os, TexRow & texrow,
574 unsigned int & column,
576 Layout const & style)
578 if (style.pass_thru || runparams.verbatim)
581 if (i + 1 < int(text_.size())) {
582 char_type next = text_[i + 1];
583 if (Encodings::isCombiningChar(next)) {
584 // This space has an accent, so we must always output it.
585 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
590 if (lyxrc.plaintext_linelen > 0
591 && column > lyxrc.plaintext_linelen
593 && text_[i - 1] != ' '
594 && (i + 1 < int(text_.size()))
595 // same in FreeSpacing mode
596 && !owner_->isFreeSpacing()
597 // In typewriter mode, we want to avoid
598 // ! . ? : at the end of a line
599 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
600 && (text_[i - 1] == '.'
601 || text_[i - 1] == '?'
602 || text_[i - 1] == ':'
603 || text_[i - 1] == '!'))) {
606 texrow.start(owner_->id(), i + 1);
608 } else if (style.free_spacing) {
617 int Paragraph::Private::writeScriptChars(odocstream & os,
618 docstring const & ltx,
619 Change const & runningChange,
620 Encoding const & encoding,
623 // FIXME: modifying i here is not very nice...
625 // We only arrive here when a proper language for character text_[i] has
626 // not been specified (i.e., it could not be translated in the current
627 // latex encoding) or its latex translation has been forced, and it
628 // belongs to a known script.
629 // Parameter ltx contains the latex translation of text_[i] as specified
630 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
631 // The latex macro name "textXXX" specifies the script to which text_[i]
632 // belongs and we use it in order to check whether characters from the
633 // same script immediately follow, such that we can collect them in a
634 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
635 // for the first char but only "<spec>" for all subsequent chars.
636 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
637 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
638 string script = to_ascii(ltx.substr(1, brace1 - 1));
641 bool closing_brace = true;
642 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
643 // Correct encoding is being used, so we can avoid \textgreek.
646 closing_brace = false;
648 os << ltx.substr(pos, length);
649 int size = text_.size();
650 while (i + 1 < size) {
651 char_type const next = text_[i + 1];
652 // Stop here if next character belongs to another script
653 // or there is a change in change tracking status.
654 if (!Encodings::isKnownScriptChar(next, script) ||
655 runningChange != owner_->lookupChange(i + 1))
659 FontList::const_iterator cit = fontlist_.begin();
660 FontList::const_iterator end = fontlist_.end();
661 for (; cit != end; ++cit) {
662 if (cit->pos() >= i && !found) {
663 prev_font = cit->font();
666 if (cit->pos() >= i + 1)
669 // Stop here if there is a font attribute or encoding change.
670 if (found && cit != end && prev_font != cit->font())
672 docstring const latex = encoding.latexChar(next);
673 docstring::size_type const b1 =
674 latex.find_first_of(from_ascii("{"));
675 docstring::size_type const b2 =
676 latex.find_last_of(from_ascii("}"));
677 int const len = b2 - b1 - 1;
678 os << latex.substr(b1 + 1, len);
690 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
692 pos_type const len = str.length();
694 // is the paragraph large enough?
695 if (pos + len > int(text_.size()))
698 // does the wanted text start at point?
699 for (string::size_type i = 0; i < str.length(); ++i) {
700 // Caution: direct comparison of characters works only
701 // because str is pure ASCII.
702 if (str[i] != text_[pos + i])
706 return fontlist_.hasChangeInRange(pos, len);
710 void Paragraph::Private::latexInset(
711 BufferParams const & bparams,
714 OutputParams & runparams,
717 Font const & outerfont,
719 Change & running_change,
720 Layout const & style,
722 unsigned int & column)
724 Inset * inset = owner_->getInset(i);
725 LASSERT(inset, /**/);
727 if (style.pass_thru) {
728 inset->plaintext(os, runparams);
732 // FIXME: move this to InsetNewline::latex
733 if (inset->lyxCode() == NEWLINE_CODE) {
734 // newlines are handled differently here than
735 // the default in simpleTeXSpecialChars().
736 if (!style.newline_allowed) {
740 column += running_font.latexWriteEndChanges(
741 os, bparams, runparams,
746 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
749 basefont = owner_->getLayoutFont(bparams, outerfont);
750 running_font = basefont;
752 if (runparams.moving_arg)
757 texrow.start(owner_->id(), i + 1);
761 if (owner_->lookupChange(i).type == Change::DELETED) {
762 if( ++runparams.inDeletedInset == 1)
763 runparams.changeOfDeletedInset = owner_->lookupChange(i);
766 if (inset->canTrackChanges()) {
767 column += Changes::latexMarkChange(os, bparams, running_change,
768 Change(Change::UNCHANGED));
769 running_change = Change(Change::UNCHANGED);
773 odocstream::pos_type const len = os.tellp();
775 if (inset->forceLTR()
776 && running_font.isRightToLeft()
777 // ERT is an exception, it should be output with no
778 // decorations at all
779 && inset->lyxCode() != ERT_CODE) {
780 if (running_font.language()->lang() == "farsi")
787 // FIXME: Bug: we can have an empty font change here!
788 // if there has just been a font change, we are going to close it
789 // right now, which means stupid latex code like \textsf{}. AFAIK,
790 // this does not harm dvi output. A minor bug, thus (JMarc)
792 // Some insets cannot be inside a font change command.
793 // However, even such insets *can* be placed in \L or \R
794 // or their equivalents (for RTL language switches), so we don't
795 // close the language in those cases.
796 // ArabTeX, though, cannot handle this special behavior, it seems.
797 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
798 || running_font.language()->lang() == "arabic_arabtex";
799 if (open_font && inset->noFontChange()) {
800 bool closeLanguage = arabtex
801 || basefont.isRightToLeft() == running_font.isRightToLeft();
802 unsigned int count = running_font.latexWriteEndChanges(os,
803 bparams, runparams, basefont, basefont, closeLanguage);
805 // if any font properties were closed, update the running_font,
806 // making sure, however, to leave the language as it was
808 // FIXME: probably a better way to keep track of the old
809 // language, than copying the entire font?
810 Font const copy_font(running_font);
811 basefont = owner_->getLayoutFont(bparams, outerfont);
812 running_font = basefont;
814 running_font.setLanguage(copy_font.language());
815 // leave font open if language is still open
816 open_font = (running_font.language() == basefont.language());
818 runparams.local_font = &basefont;
825 tmp = inset->latex(os, runparams);
826 } catch (EncodingException & e) {
827 // add location information and throw again.
834 if (running_font.language()->lang() == "farsi")
841 for (int j = 0; j < tmp; ++j)
844 texrow.start(owner_->id(), i + 1);
847 column += os.tellp() - len;
850 if (owner_->lookupChange(i).type == Change::DELETED)
851 --runparams.inDeletedInset;
855 void Paragraph::Private::latexSpecialChar(
857 OutputParams const & runparams,
858 Font const & running_font,
859 Change const & running_change,
860 Layout const & style,
862 unsigned int & column)
864 char_type const c = text_[i];
866 if (style.pass_thru) {
868 // FIXME UNICODE: This can fail if c cannot
869 // be encoded in the current encoding.
874 if (runparams.verbatim) {
875 // FIXME UNICODE: This can fail if c cannot
876 // be encoded in the current encoding.
881 // If T1 font encoding is used, use the special
882 // characters it provides.
883 // NOTE: some languages reset the font encoding
885 if (!running_font.language()->internalFontEncoding()
886 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
889 // \tt font needs special treatment
890 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
891 && latexSpecialTypewriter(c, os, i, column))
894 // Otherwise, we use what LaTeX provides us.
897 os << "\\textbackslash{}";
901 os << "\\textless{}";
905 os << "\\textgreater{}";
916 os << "\\char`\\\"{}";
921 case '%': case '#': case '{':
929 os << "\\textasciitilde{}";
934 os << "\\textasciicircum{}";
941 // avoid being mistaken for optional arguments
949 // Blanks are printed before font switching.
950 // Sure? I am not! (try nice-latex)
951 // I am sure it's correct. LyX might be smarter
952 // in the future, but for now, nothing wrong is
958 if (latexSpecialPhrase(os, i, column, runparams))
964 Encoding const & encoding = *(runparams.encoding);
965 if (i + 1 < int(text_.size())) {
966 char_type next = text_[i + 1];
967 if (Encodings::isCombiningChar(next)) {
968 column += latexSurrogatePair(os, c, next, runparams) - 1;
974 docstring const latex = encoding.latexChar(c);
975 if (Encodings::isKnownScriptChar(c, script)
976 && prefixIs(latex, from_ascii("\\" + script)))
977 column += writeScriptChars(os, latex,
978 running_change, encoding, i) - 1;
979 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
980 // Prevent eating of a following
981 // space or command corruption by
982 // following characters
983 column += latex.length() + 1;
986 column += latex.length() - 1;
994 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
995 pos_type i, unsigned int & column)
1001 // In T1 encoding, these characters exist
1002 // but we should avoid ligatures
1003 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1005 os << "\\textcompwordmark{}";
1012 // soul.sty breaks with \char`\"
1013 os << "\\textquotedbl{}";
1022 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1023 pos_type i, unsigned int & column)
1027 // within \ttfamily, "--" is merged to "-" (no endash)
1028 // so we avoid this rather irritating ligature
1029 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1036 // everything else has to be checked separately
1037 // (depending on the encoding)
1044 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1045 unsigned int & column, OutputParams const & runparams)
1047 // FIXME: if we have "LaTeX" with a font
1048 // change in the middle (before the 'T', then
1049 // the "TeX" part is still special cased.
1050 // Really we should only operate this on
1051 // "words" for some definition of word
1053 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1054 if (!isTextAt(special_phrases[pnr].phrase, i))
1056 if (runparams.moving_arg)
1058 os << special_phrases[pnr].macro;
1059 i += special_phrases[pnr].phrase.length() - 1;
1060 column += special_phrases[pnr].macro.length() - 1;
1067 void Paragraph::Private::validate(LaTeXFeatures & features,
1068 Layout const & layout) const
1070 // check the params.
1071 if (!params_.spacing().isDefault())
1072 features.require("setspace");
1075 features.useLayout(layout.name());
1078 fontlist_.validate(features);
1080 // then the indentation
1081 if (!params_.leftIndent().zero())
1082 features.require("ParagraphLeftIndent");
1085 InsetList::const_iterator icit = insetlist_.begin();
1086 InsetList::const_iterator iend = insetlist_.end();
1087 for (; icit != iend; ++icit) {
1089 icit->inset->validate(features);
1090 if (layout.needprotect &&
1091 icit->inset->lyxCode() == FOOT_CODE)
1092 features.require("NeedLyXFootnoteCode");
1096 // then the contents
1097 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1098 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1099 if (!special_phrases[pnr].builtin
1100 && isTextAt(special_phrases[pnr].phrase, i)) {
1101 features.require(special_phrases[pnr].phrase);
1105 Encodings::validate(text_[i], features);
1109 /////////////////////////////////////////////////////////////////////
1113 /////////////////////////////////////////////////////////////////////
1116 Layout const emptyParagraphLayout;
1119 Paragraph::Paragraph()
1120 : d(new Paragraph::Private(this, emptyParagraphLayout))
1127 Paragraph::Paragraph(Paragraph const & par)
1128 : itemdepth(par.itemdepth),
1129 d(new Paragraph::Private(*par.d, this))
1135 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1136 : itemdepth(par.itemdepth),
1137 d(new Paragraph::Private(*par.d, this, beg, end))
1143 Paragraph & Paragraph::operator=(Paragraph const & par)
1145 // needed as we will destroy the private part before copying it
1147 itemdepth = par.itemdepth;
1151 d = new Private(*par.d, this);
1158 Paragraph::~Paragraph()
1165 void Paragraph::write(ostream & os, BufferParams const & bparams,
1166 depth_type & dth) const
1168 // The beginning or end of a deeper (i.e. nested) area?
1169 if (dth != d->params_.depth()) {
1170 if (d->params_.depth() > dth) {
1171 while (d->params_.depth() > dth) {
1172 os << "\n\\begin_deeper";
1176 while (d->params_.depth() < dth) {
1177 os << "\n\\end_deeper";
1183 // First write the layout
1184 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1186 d->params_.write(os);
1188 Font font1(inherit_font, bparams.language);
1190 Change running_change = Change(Change::UNCHANGED);
1193 for (pos_type i = 0; i <= size(); ++i) {
1195 Change const change = lookupChange(i);
1196 Changes::lyxMarkChange(os, column, running_change, change);
1197 running_change = change;
1202 // Write font changes (ignore spelling markers)
1203 Font font2 = getFontSettings(bparams, i);
1204 font2.setMisspelled(false);
1205 if (font2 != font1) {
1206 font2.lyxWriteChanges(font1, os);
1211 char_type const c = d->text_[i];
1214 if (Inset const * inset = getInset(i)) {
1215 if (inset->directWrite()) {
1216 // international char, let it write
1217 // code directly so it's shorter in
1223 os << "\\begin_inset ";
1225 os << "\n\\end_inset\n\n";
1231 os << "\n\\backslash\n";
1235 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1242 if ((column > 70 && c == ' ')
1247 // this check is to amend a bug. LyX sometimes
1248 // inserts '\0' this could cause problems.
1250 os << to_utf8(docstring(1, c));
1252 LYXERR0("NUL char in structure.");
1258 os << "\n\\end_layout\n";
1262 void Paragraph::validate(LaTeXFeatures & features) const
1264 d->validate(features, *d->layout_);
1268 void Paragraph::insert(pos_type start, docstring const & str,
1269 Font const & font, Change const & change)
1271 for (size_t i = 0, n = str.size(); i != n ; ++i)
1272 insertChar(start + i, str[i], font, change);
1276 void Paragraph::appendChar(char_type c, Font const & font,
1277 Change const & change)
1280 d->changes_.insert(change, d->text_.size());
1281 // when appending characters, no need to update tables
1282 d->text_.push_back(c);
1283 setFont(d->text_.size() - 1, font);
1287 void Paragraph::appendString(docstring const & s, Font const & font,
1288 Change const & change)
1290 pos_type end = s.size();
1291 size_t oldsize = d->text_.size();
1292 size_t newsize = oldsize + end;
1293 size_t capacity = d->text_.capacity();
1294 if (newsize >= capacity)
1295 d->text_.reserve(max(capacity + 100, newsize));
1297 // when appending characters, no need to update tables
1300 // FIXME: Optimize this!
1301 for (size_t i = oldsize; i != newsize; ++i) {
1303 d->changes_.insert(change, i);
1305 d->fontlist_.set(oldsize, font);
1306 d->fontlist_.set(newsize - 1, font);
1310 void Paragraph::insertChar(pos_type pos, char_type c,
1313 d->insertChar(pos, c, Change(trackChanges ?
1314 Change::INSERTED : Change::UNCHANGED));
1318 void Paragraph::insertChar(pos_type pos, char_type c,
1319 Font const & font, bool trackChanges)
1321 d->insertChar(pos, c, Change(trackChanges ?
1322 Change::INSERTED : Change::UNCHANGED));
1327 void Paragraph::insertChar(pos_type pos, char_type c,
1328 Font const & font, Change const & change)
1330 d->insertChar(pos, c, change);
1335 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1336 Font const & font, Change const & change)
1338 bool const success = insertInset(pos, inset, change);
1339 // Set the font/language of the inset...
1345 void Paragraph::resetFonts(Font const & font)
1347 d->fontlist_.clear();
1348 d->fontlist_.set(0, font);
1349 d->fontlist_.set(d->text_.size() - 1, font);
1352 // Gets uninstantiated font setting at position.
1353 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1357 LYXERR0("pos: " << pos << " size: " << size());
1358 LASSERT(pos <= size(), /**/);
1361 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1362 if (cit != d->fontlist_.end())
1365 if (pos == size() && !empty())
1366 return getFontSettings(bparams, pos - 1);
1368 // Optimisation: avoid a full font instantiation if there is no
1369 // language change from previous call.
1370 static Font previous_font;
1371 static Language const * previous_lang = 0;
1372 Language const * lang = getParLanguage(bparams);
1373 if (lang != previous_lang) {
1374 previous_lang = lang;
1375 previous_font = Font(inherit_font, lang);
1377 return previous_font;
1381 FontSpan Paragraph::fontSpan(pos_type pos) const
1383 LASSERT(pos <= size(), /**/);
1386 FontList::const_iterator cit = d->fontlist_.begin();
1387 FontList::const_iterator end = d->fontlist_.end();
1388 for (; cit != end; ++cit) {
1389 if (cit->pos() >= pos) {
1390 if (pos >= beginOfBody())
1391 return FontSpan(max(start, beginOfBody()),
1394 return FontSpan(start,
1395 min(beginOfBody() - 1,
1398 start = cit->pos() + 1;
1401 // This should not happen, but if so, we take no chances.
1402 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1403 return FontSpan(pos, pos);
1407 // Gets uninstantiated font setting at position 0
1408 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1410 if (!empty() && !d->fontlist_.empty())
1411 return d->fontlist_.begin()->font();
1413 // Optimisation: avoid a full font instantiation if there is no
1414 // language change from previous call.
1415 static Font previous_font;
1416 static Language const * previous_lang = 0;
1417 if (bparams.language != previous_lang) {
1418 previous_lang = bparams.language;
1419 previous_font = Font(inherit_font, bparams.language);
1422 return previous_font;
1426 // Gets the fully instantiated font at a given position in a paragraph
1427 // This is basically the same function as Text::GetFont() in text2.cpp.
1428 // The difference is that this one is used for generating the LaTeX file,
1429 // and thus cosmetic "improvements" are disallowed: This has to deliver
1430 // the true picture of the buffer. (Asger)
1431 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1432 Font const & outerfont) const
1434 LASSERT(pos >= 0, /**/);
1436 Font font = getFontSettings(bparams, pos);
1438 pos_type const body_pos = beginOfBody();
1439 FontInfo & fi = font.fontInfo();
1441 fi.realize(d->layout_->labelfont);
1443 fi.realize(d->layout_->font);
1445 fi.realize(outerfont.fontInfo());
1446 fi.realize(bparams.getFont().fontInfo());
1452 Font const Paragraph::getLabelFont
1453 (BufferParams const & bparams, Font const & outerfont) const
1455 FontInfo tmpfont = d->layout_->labelfont;
1456 tmpfont.realize(outerfont.fontInfo());
1457 tmpfont.realize(bparams.getFont().fontInfo());
1458 return Font(tmpfont, getParLanguage(bparams));
1462 Font const Paragraph::getLayoutFont
1463 (BufferParams const & bparams, Font const & outerfont) const
1465 FontInfo tmpfont = d->layout_->font;
1466 tmpfont.realize(outerfont.fontInfo());
1467 tmpfont.realize(bparams.getFont().fontInfo());
1468 return Font(tmpfont, getParLanguage(bparams));
1472 /// Returns the height of the highest font in range
1473 FontSize Paragraph::highestFontInRange
1474 (pos_type startpos, pos_type endpos, FontSize def_size) const
1476 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1480 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1482 char_type c = d->text_[pos];
1483 if (!lyxrc.rtl_support)
1513 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1519 void Paragraph::setFont(pos_type pos, Font const & font)
1521 LASSERT(pos <= size(), /**/);
1523 // First, reduce font against layout/label font
1524 // Update: The setCharFont() routine in text2.cpp already
1525 // reduces font, so we don't need to do that here. (Asger)
1527 d->fontlist_.set(pos, font);
1531 void Paragraph::makeSameLayout(Paragraph const & par)
1533 d->layout_ = par.d->layout_;
1534 d->params_ = par.d->params_;
1538 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1540 if (isFreeSpacing())
1546 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1547 if (eraseChar(pos, trackChanges))
1553 return count > 0 || pos > 0;
1557 bool Paragraph::hasSameLayout(Paragraph const & par) const
1559 return par.d->layout_ == d->layout_
1560 && d->params_.sameLayout(par.d->params_);
1564 depth_type Paragraph::getDepth() const
1566 return d->params_.depth();
1570 depth_type Paragraph::getMaxDepthAfter() const
1572 if (d->layout_->isEnvironment())
1573 return d->params_.depth() + 1;
1575 return d->params_.depth();
1579 char Paragraph::getAlign() const
1581 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1582 return d->layout_->align;
1584 return d->params_.align();
1588 docstring const & Paragraph::labelString() const
1590 return d->params_.labelString();
1594 // the next two functions are for the manual labels
1595 docstring const Paragraph::getLabelWidthString() const
1597 if (d->layout_->margintype == MARGIN_MANUAL
1598 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1599 return d->params_.labelWidthString();
1601 return _("Senseless with this layout!");
1605 void Paragraph::setLabelWidthString(docstring const & s)
1607 d->params_.labelWidthString(s);
1611 docstring Paragraph::expandLabel(Layout const & layout,
1612 BufferParams const & bparams, bool process_appendix) const
1614 DocumentClass const & tclass = bparams.documentClass();
1615 string const & lang = getParLanguage(bparams)->code();
1616 bool const in_appendix = process_appendix && d->params_.appendix();
1617 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1619 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1620 && !layout.counter.empty())
1621 return tclass.counters().theCounter(layout.counter, lang);
1623 // handle 'inherited level parts' in 'fmt',
1624 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1625 size_t const i = fmt.find('@', 0);
1626 if (i != docstring::npos) {
1627 size_t const j = fmt.find('@', i + 1);
1628 if (j != docstring::npos) {
1629 docstring parent(fmt, i + 1, j - i - 1);
1630 docstring label = from_ascii("??");
1631 if (tclass.hasLayout(parent))
1632 docstring label = expandLabel(tclass[parent], bparams,
1634 fmt = docstring(fmt, 0, i) + label
1635 + docstring(fmt, j + 1, docstring::npos);
1639 return tclass.counters().counterLabel(fmt, lang);
1643 void Paragraph::applyLayout(Layout const & new_layout)
1645 d->layout_ = &new_layout;
1646 LyXAlignment const oldAlign = d->params_.align();
1648 if (!(oldAlign & d->layout_->alignpossible)) {
1649 frontend::Alert::warning(_("Alignment not permitted"),
1650 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1651 d->params_.align(LYX_ALIGN_LAYOUT);
1656 pos_type Paragraph::beginOfBody() const
1658 return d->begin_of_body_;
1662 void Paragraph::setBeginOfBody()
1664 if (d->layout_->labeltype != LABEL_MANUAL) {
1665 d->begin_of_body_ = 0;
1669 // Unroll the first two cycles of the loop
1670 // and remember the previous character to
1671 // remove unnecessary getChar() calls
1673 pos_type end = size();
1674 if (i < end && !isNewline(i)) {
1676 char_type previous_char = 0;
1679 previous_char = d->text_[i];
1680 if (!isNewline(i)) {
1682 while (i < end && previous_char != ' ') {
1687 previous_char = temp;
1693 d->begin_of_body_ = i;
1697 bool Paragraph::forcePlainLayout() const
1699 return inInset().forcePlainLayout();
1703 bool Paragraph::allowParagraphCustomization() const
1705 return inInset().allowParagraphCustomization();
1709 bool Paragraph::usePlainLayout() const
1711 return inInset().usePlainLayout();
1717 // paragraphs inside floats need different alignment tags to avoid
1720 bool noTrivlistCentering(InsetCode code)
1722 return code == FLOAT_CODE
1723 || code == WRAP_CODE
1724 || code == CELL_CODE;
1728 string correction(string const & orig)
1730 if (orig == "flushleft")
1731 return "raggedright";
1732 if (orig == "flushright")
1733 return "raggedleft";
1734 if (orig == "center")
1740 string const corrected_env(string const & suffix, string const & env,
1741 InsetCode code, bool const lastpar)
1743 string output = suffix + "{";
1744 if (noTrivlistCentering(code)) {
1746 // the last paragraph in non-trivlist-aligned
1747 // context is special (to avoid unwanted whitespace)
1748 if (suffix == "\\begin")
1749 return "\\" + correction(env) + "{}";
1752 output += correction(env);
1756 if (suffix == "\\begin")
1762 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1764 if (!contains(str, "\n"))
1765 column += str.size();
1769 column = rsplit(str, tmp, '\n').size();
1776 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1777 odocstream & os, TexRow & texrow,
1778 OutputParams const & runparams) const
1782 if (params_.noindent()) {
1783 os << "\\noindent ";
1787 LyXAlignment const curAlign = params_.align();
1789 if (curAlign == layout_->align)
1793 case LYX_ALIGN_NONE:
1794 case LYX_ALIGN_BLOCK:
1795 case LYX_ALIGN_LAYOUT:
1796 case LYX_ALIGN_SPECIAL:
1798 case LYX_ALIGN_LEFT:
1799 case LYX_ALIGN_RIGHT:
1800 case LYX_ALIGN_CENTER:
1801 if (runparams.moving_arg) {
1808 string const begin_tag = "\\begin";
1809 InsetCode code = owner_->ownerCode();
1810 bool const lastpar = runparams.isLastPar;
1813 case LYX_ALIGN_NONE:
1814 case LYX_ALIGN_BLOCK:
1815 case LYX_ALIGN_LAYOUT:
1816 case LYX_ALIGN_SPECIAL:
1818 case LYX_ALIGN_LEFT: {
1820 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1821 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1823 output = corrected_env(begin_tag, "flushright", code, lastpar);
1824 os << from_ascii(output);
1825 adjust_row_column(output, texrow, column);
1827 } case LYX_ALIGN_RIGHT: {
1829 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1830 output = corrected_env(begin_tag, "flushright", code, lastpar);
1832 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1833 os << from_ascii(output);
1834 adjust_row_column(output, texrow, column);
1836 } case LYX_ALIGN_CENTER: {
1838 output = corrected_env(begin_tag, "center", code, lastpar);
1839 os << from_ascii(output);
1840 adjust_row_column(output, texrow, column);
1849 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1850 odocstream & os, TexRow & texrow,
1851 OutputParams const & runparams) const
1855 LyXAlignment const curAlign = params_.align();
1857 if (curAlign == layout_->align)
1861 case LYX_ALIGN_NONE:
1862 case LYX_ALIGN_BLOCK:
1863 case LYX_ALIGN_LAYOUT:
1864 case LYX_ALIGN_SPECIAL:
1866 case LYX_ALIGN_LEFT:
1867 case LYX_ALIGN_RIGHT:
1868 case LYX_ALIGN_CENTER:
1869 if (runparams.moving_arg) {
1876 string const end_tag = "\n\\par\\end";
1877 InsetCode code = owner_->ownerCode();
1878 bool const lastpar = runparams.isLastPar;
1881 case LYX_ALIGN_NONE:
1882 case LYX_ALIGN_BLOCK:
1883 case LYX_ALIGN_LAYOUT:
1884 case LYX_ALIGN_SPECIAL:
1886 case LYX_ALIGN_LEFT: {
1888 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1889 output = corrected_env(end_tag, "flushleft", code, lastpar);
1891 output = corrected_env(end_tag, "flushright", code, lastpar);
1892 os << from_ascii(output);
1893 adjust_row_column(output, texrow, column);
1895 } case LYX_ALIGN_RIGHT: {
1897 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1898 output = corrected_env(end_tag, "flushright", code, lastpar);
1900 output = corrected_env(end_tag, "flushleft", code, lastpar);
1901 os << from_ascii(output);
1902 adjust_row_column(output, texrow, column);
1904 } case LYX_ALIGN_CENTER: {
1906 output = corrected_env(end_tag, "center", code, lastpar);
1907 os << from_ascii(output);
1908 adjust_row_column(output, texrow, column);
1917 // This one spits out the text of the paragraph
1918 bool Paragraph::latex(BufferParams const & bparams,
1919 Font const & outerfont,
1920 odocstream & os, TexRow & texrow,
1921 OutputParams const & runparams,
1922 int start_pos, int end_pos) const
1924 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1926 bool return_value = false;
1928 bool const allowcust = allowParagraphCustomization();
1930 // FIXME This check should not be needed. Perhaps issue an
1931 // error if it triggers.
1932 Layout const & style = forcePlainLayout() ?
1933 bparams.documentClass().plainLayout() : *d->layout_;
1935 // Current base font for all inherited font changes, without any
1936 // change caused by an individual character, except for the language:
1937 // It is set to the language of the first character.
1938 // As long as we are in the label, this font is the base font of the
1939 // label. Before the first body character it is set to the base font
1943 // Maybe we have to create a optional argument.
1944 pos_type body_pos = beginOfBody();
1945 unsigned int column = 0;
1950 basefont = getLabelFont(bparams, outerfont);
1952 basefont = getLayoutFont(bparams, outerfont);
1955 // Which font is currently active?
1956 Font running_font(basefont);
1957 // Do we have an open font change?
1958 bool open_font = false;
1960 Change runningChange = Change(Change::UNCHANGED);
1962 texrow.start(id(), 0);
1964 // if the paragraph is empty, the loop will not be entered at all
1966 if (style.isCommand()) {
1971 column += d->startTeXParParams(bparams, os, texrow,
1975 for (pos_type i = 0; i < size(); ++i) {
1976 // First char in paragraph or after label?
1977 if (i == body_pos) {
1980 column += running_font.latexWriteEndChanges(
1981 os, bparams, runparams,
1982 basefont, basefont);
1985 basefont = getLayoutFont(bparams, outerfont);
1986 running_font = basefont;
1988 column += Changes::latexMarkChange(os, bparams,
1989 runningChange, Change(Change::UNCHANGED));
1990 runningChange = Change(Change::UNCHANGED);
1995 if (style.isCommand()) {
2001 column += d->startTeXParParams(bparams, os,
2006 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2009 if (bparams.outputChanges && runningChange != change) {
2011 column += running_font.latexWriteEndChanges(
2012 os, bparams, runparams, basefont, basefont);
2015 basefont = getLayoutFont(bparams, outerfont);
2016 running_font = basefont;
2018 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2019 runningChange = change;
2022 // do not output text which is marked deleted
2023 // if change tracking output is disabled
2024 if (!bparams.outputChanges && change.type == Change::DELETED) {
2030 // Fully instantiated font
2031 Font const font = getFont(bparams, i, outerfont);
2033 Font const last_font = running_font;
2035 // Do we need to close the previous font?
2037 (font != running_font ||
2038 font.language() != running_font.language()))
2040 column += running_font.latexWriteEndChanges(
2041 os, bparams, runparams, basefont,
2042 (i == body_pos-1) ? basefont : font);
2043 running_font = basefont;
2047 // close babel's font environment before opening CJK.
2048 if (!running_font.language()->babel().empty() &&
2049 font.language()->encoding()->package() == Encoding::CJK) {
2050 string end_tag = subst(lyxrc.language_command_end,
2052 running_font.language()->babel());
2053 os << from_ascii(end_tag);
2054 column += end_tag.length();
2057 // Switch file encoding if necessary (and allowed)
2058 if (!runparams.verbatim &&
2059 runparams.encoding->package() != Encoding::none &&
2060 font.language()->encoding()->package() != Encoding::none) {
2061 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2062 runparams, *(font.language()->encoding()));
2063 if (enc_switch.first) {
2064 column += enc_switch.second;
2065 runparams.encoding = font.language()->encoding();
2069 char_type const c = d->text_[i];
2071 // Do we need to change font?
2072 if ((font != running_font ||
2073 font.language() != running_font.language()) &&
2076 odocstringstream ods;
2077 column += font.latexWriteStartChanges(ods, bparams,
2078 runparams, basefont,
2080 running_font = font;
2082 docstring fontchange = ods.str();
2083 // check if the fontchange ends with a trailing blank
2084 // (like "\small " (see bug 3382)
2085 if (suffixIs(fontchange, ' ') && c == ' ')
2086 os << fontchange.substr(0, fontchange.size() - 1)
2087 << from_ascii("{}");
2092 // FIXME: think about end_pos implementation...
2093 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2094 // FIXME: integrate this case in latexSpecialChar
2095 // Do not print the separation of the optional argument
2096 // if style.pass_thru is false. This works because
2097 // latexSpecialChar ignores spaces if
2098 // style.pass_thru is false.
2099 if (i != body_pos - 1) {
2100 if (d->simpleTeXBlanks(
2101 runparams, os, texrow,
2102 i, column, font, style)) {
2103 // A surrogate pair was output. We
2104 // must not call latexSpecialChar
2105 // in this iteration, since it would output
2106 // the combining character again.
2113 OutputParams rp = runparams;
2114 rp.free_spacing = style.free_spacing;
2115 rp.local_font = &font;
2116 rp.intitle = style.intitle;
2118 // Two major modes: LaTeX or plain
2119 // Handle here those cases common to both modes
2120 // and then split to handle the two modes separately.
2121 if (c == META_INSET) {
2122 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2123 d->latexInset(bparams, os,
2124 texrow, rp, running_font,
2125 basefont, outerfont, open_font,
2126 runningChange, style, i, column);
2129 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2131 d->latexSpecialChar(os, rp, running_font, runningChange,
2133 } catch (EncodingException & e) {
2134 if (runparams.dryrun) {
2135 os << "<" << _("LyX Warning: ")
2136 << _("uncodable character") << " '";
2140 // add location information and throw again.
2149 // Set the encoding to that returned from latexSpecialChar (see
2150 // comment for encoding member in OutputParams.h)
2151 runparams.encoding = rp.encoding;
2154 // If we have an open font definition, we have to close it
2156 #ifdef FIXED_LANGUAGE_END_DETECTION
2159 .latexWriteEndChanges(os, bparams, runparams,
2161 next_->getFont(bparams, 0, outerfont));
2163 running_font.latexWriteEndChanges(os, bparams,
2164 runparams, basefont, basefont);
2167 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2168 //FIXME: there as we start another \selectlanguage with the next paragraph if
2169 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2170 running_font.latexWriteEndChanges(os, bparams, runparams,
2171 basefont, basefont);
2175 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2177 // Needed if there is an optional argument but no contents.
2178 if (body_pos > 0 && body_pos == size()) {
2180 return_value = false;
2184 column += d->endTeXParParams(bparams, os, texrow,
2188 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2189 return return_value;
2193 bool Paragraph::emptyTag() const
2195 for (pos_type i = 0; i < size(); ++i) {
2196 if (Inset const * inset = getInset(i)) {
2197 InsetCode lyx_code = inset->lyxCode();
2198 // FIXME testing like that is wrong. What is
2200 if (lyx_code != TOC_CODE &&
2201 lyx_code != INCLUDE_CODE &&
2202 lyx_code != GRAPHICS_CODE &&
2203 lyx_code != ERT_CODE &&
2204 lyx_code != LISTINGS_CODE &&
2205 lyx_code != FLOAT_CODE &&
2206 lyx_code != TABULAR_CODE) {
2210 char_type c = d->text_[i];
2211 if (c != ' ' && c != '\t')
2219 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2222 for (pos_type i = 0; i < size(); ++i) {
2223 if (Inset const * inset = getInset(i)) {
2224 InsetCode lyx_code = inset->lyxCode();
2225 if (lyx_code == LABEL_CODE) {
2226 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2227 docstring const & id = il->getParam("name");
2228 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2236 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2240 for (i = 0; i < size(); ++i) {
2241 if (Inset const * inset = getInset(i)) {
2242 inset->docbook(os, runparams);
2244 char_type c = d->text_[i];
2247 os << sgml::escapeChar(c);
2254 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2258 for (i = 0; i < size(); ++i) {
2259 if (Inset const * inset = getInset(i)) {
2260 inset->xhtml(os, runparams);
2262 char_type c = d->text_[i];
2265 os << html::escapeChar(c);
2272 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2275 pos_type size = text_.size();
2276 for (pos_type i = initial; i < size; ++i) {
2277 Font font = owner_->getFont(buf.params(), i, outerfont);
2278 if (text_[i] == META_INSET)
2280 if (i != initial && font != font_old)
2289 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2291 OutputParams const & runparams,
2292 Font const & outerfont,
2293 pos_type initial) const
2295 bool emph_flag = false;
2297 Layout const & style = *d->layout_;
2299 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2301 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2304 // parsing main loop
2305 for (pos_type i = initial; i < size(); ++i) {
2306 Font font = getFont(buf.params(), i, outerfont);
2308 // handle <emphasis> tag
2309 if (font_old.emph() != font.fontInfo().emph()) {
2310 if (font.fontInfo().emph() == FONT_ON) {
2313 } else if (i != initial) {
2314 os << "</emphasis>";
2319 if (Inset const * inset = getInset(i)) {
2320 inset->docbook(os, runparams);
2322 char_type c = d->text_[i];
2324 if (style.pass_thru)
2327 os << sgml::escapeChar(c);
2329 font_old = font.fontInfo();
2333 os << "</emphasis>";
2336 if (style.free_spacing)
2338 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2343 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2345 OutputParams const & runparams,
2346 Font const & outerfont,
2347 pos_type initial) const
2351 // FIXME We really need to manage the tag nesting here.
2352 // Probably in the same sort of way as in output_xhtml.
2353 bool emph_flag = false;
2354 bool bold_flag = false;
2355 std::string closing_tag;
2357 Layout const & style = *d->layout_;
2359 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2361 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2364 // parsing main loop
2365 for (pos_type i = initial; i < size(); ++i) {
2366 Font font = getFont(buf.params(), i, outerfont);
2369 if (font_old.emph() != font.fontInfo().emph()) {
2370 if (font.fontInfo().emph() == FONT_ON) {
2373 } else if (emph_flag && i != initial) {
2379 if (font_old.series() != font.fontInfo().series()) {
2380 if (font.fontInfo().series() == BOLD_SERIES) {
2383 } else if (bold_flag && i != initial) {
2388 // FIXME Other such tags?
2390 if (Inset const * inset = getInset(i)) {
2391 retval += inset->xhtml(os, runparams);
2393 char_type c = d->text_[i];
2395 if (style.pass_thru)
2397 else if (c == '-') {
2400 if (j < size() && d->text_[j] == '-') {
2402 if (j < size() && d->text_[j] == '-') {
2403 str += from_ascii("—");
2406 str += from_ascii("–");
2414 os << html::escapeChar(c);
2416 font_old = font.fontInfo();
2419 // FIXME This could be out of order. See above.
2429 bool Paragraph::isHfill(pos_type pos) const
2431 Inset const * inset = getInset(pos);
2432 return inset && (inset->lyxCode() == SPACE_CODE &&
2433 inset->isStretchableSpace());
2437 bool Paragraph::isNewline(pos_type pos) const
2439 Inset const * inset = getInset(pos);
2440 return inset && inset->lyxCode() == NEWLINE_CODE;
2444 bool Paragraph::isLineSeparator(pos_type pos) const
2446 char_type const c = d->text_[pos];
2447 if (isLineSeparatorChar(c))
2449 Inset const * inset = getInset(pos);
2450 return inset && inset->isLineSeparator();
2454 bool Paragraph::isWordSeparator(pos_type pos) const
2456 if (Inset const * inset = getInset(pos))
2457 return !inset->isLetter();
2458 char_type const c = d->text_[pos];
2459 // We want to pass the ' and escape chars to the spellchecker
2460 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2461 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2466 bool Paragraph::isChar(pos_type pos) const
2468 if (Inset const * inset = getInset(pos))
2469 return inset->isChar();
2470 char_type const c = d->text_[pos];
2471 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2475 bool Paragraph::isSpace(pos_type pos) const
2477 if (Inset const * inset = getInset(pos))
2478 return inset->isSpace();
2479 char_type const c = d->text_[pos];
2480 return lyx::isSpace(c);
2485 Paragraph::getParLanguage(BufferParams const & bparams) const
2488 return getFirstFontSettings(bparams).language();
2489 // FIXME: we should check the prev par as well (Lgb)
2490 return bparams.language;
2494 bool Paragraph::isRTL(BufferParams const & bparams) const
2496 return lyxrc.rtl_support
2497 && getParLanguage(bparams)->rightToLeft()
2498 && !inInset().getLayout().forceLTR();
2502 void Paragraph::changeLanguage(BufferParams const & bparams,
2503 Language const * from, Language const * to)
2505 // change language including dummy font change at the end
2506 for (pos_type i = 0; i <= size(); ++i) {
2507 Font font = getFontSettings(bparams, i);
2508 if (font.language() == from) {
2509 font.setLanguage(to);
2516 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2518 Language const * doc_language = bparams.language;
2519 FontList::const_iterator cit = d->fontlist_.begin();
2520 FontList::const_iterator end = d->fontlist_.end();
2522 for (; cit != end; ++cit)
2523 if (cit->font().language() != ignore_language &&
2524 cit->font().language() != latex_language &&
2525 cit->font().language() != doc_language)
2531 docstring Paragraph::asString(int options) const
2533 return asString(0, size(), options);
2537 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2539 odocstringstream os;
2542 && options & AS_STR_LABEL
2543 && !d->params_.labelString().empty())
2544 os << d->params_.labelString() << ' ';
2546 for (pos_type i = beg; i < end; ++i) {
2547 char_type const c = d->text_[i];
2548 if (isPrintable(c) || c == '\t'
2549 || (c == '\n' && options & AS_STR_NEWLINES))
2551 else if (c == META_INSET && options & AS_STR_INSETS)
2552 getInset(i)->tocString(os);
2559 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2561 odocstringstream os;
2564 && options & AS_STR_LABEL
2565 && !d->params_.labelString().empty())
2566 os << d->params_.labelString() << ' ';
2568 for (pos_type i = beg; i < end; ++i) {
2569 char_type const c = d->text_[i];
2570 if (isPrintable(c) || c == '\t'
2571 || (c == '\n' && options & AS_STR_NEWLINES))
2573 else if (c == META_INSET && options & AS_STR_INSETS) {
2574 getInset(i)->plaintext(os, runparams);
2582 void Paragraph::setInsetOwner(Inset const * inset)
2584 d->inset_owner_ = inset;
2588 int Paragraph::id() const
2594 Layout const & Paragraph::layout() const
2600 void Paragraph::setLayout(Layout const & layout)
2602 d->layout_ = &layout;
2606 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2608 setLayout(tc.defaultLayout());
2612 void Paragraph::setPlainLayout(DocumentClass const & tc)
2614 setLayout(tc.plainLayout());
2618 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2620 if (usePlainLayout())
2621 setPlainLayout(tclass);
2623 setDefaultLayout(tclass);
2627 Inset const & Paragraph::inInset() const
2629 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2630 _("Memory problem"), _("Paragraph not properly initialized")));
2631 return *d->inset_owner_;
2635 InsetCode Paragraph::ownerCode() const
2637 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2641 ParagraphParameters & Paragraph::params()
2647 ParagraphParameters const & Paragraph::params() const
2653 bool Paragraph::isFreeSpacing() const
2655 if (d->layout_->free_spacing)
2657 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2661 bool Paragraph::allowEmpty() const
2663 if (d->layout_->keepempty)
2665 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2669 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2671 if (!Encodings::isArabicChar(c))
2674 char_type prev_char = ' ';
2675 char_type next_char = ' ';
2677 for (pos_type i = pos - 1; i >= 0; --i) {
2678 char_type const par_char = d->text_[i];
2679 if (!Encodings::isArabicComposeChar(par_char)) {
2680 prev_char = par_char;
2685 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2686 char_type const par_char = d->text_[i];
2687 if (!Encodings::isArabicComposeChar(par_char)) {
2688 next_char = par_char;
2693 if (Encodings::isArabicChar(next_char)) {
2694 if (Encodings::isArabicChar(prev_char) &&
2695 !Encodings::isArabicSpecialChar(prev_char))
2696 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2698 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2700 if (Encodings::isArabicChar(prev_char) &&
2701 !Encodings::isArabicSpecialChar(prev_char))
2702 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2704 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2709 int Paragraph::checkBiblio(Buffer const & buffer)
2712 // This is getting more and more a mess. ...We really should clean
2713 // up this bibitem issue for 1.6. See also bug 2743.
2715 // Add bibitem insets if necessary
2716 if (d->layout_->labeltype != LABEL_BIBLIO)
2719 bool hasbibitem = !d->insetlist_.empty()
2720 // Insist on it being in pos 0
2721 && d->text_[0] == META_INSET
2722 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2724 bool track_changes = buffer.params().trackChanges;
2729 // remove a bibitem in pos != 0
2730 // restore it later in pos 0 if necessary
2731 // (e.g. if a user inserts contents _before_ the item)
2732 // we're assuming there's only one of these, which there
2734 int erasedInsetPosition = -1;
2735 InsetList::iterator it = d->insetlist_.begin();
2736 InsetList::iterator end = d->insetlist_.end();
2737 for (; it != end; ++it)
2738 if (it->inset->lyxCode() == BIBITEM_CODE
2740 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2741 oldkey = olditem->getParam("key");
2742 oldlabel = olditem->getParam("label");
2743 erasedInsetPosition = it->pos;
2744 eraseChar(erasedInsetPosition, track_changes);
2748 // There was an InsetBibitem at the beginning, and we didn't
2749 // have to erase one.
2750 if (hasbibitem && erasedInsetPosition < 0)
2753 // There was an InsetBibitem at the beginning and we did have to
2754 // erase one. So we give its properties to the beginning inset.
2756 InsetBibitem * inset =
2757 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2758 if (!oldkey.empty())
2759 inset->setParam("key", oldkey);
2760 inset->setParam("label", oldlabel);
2761 return -erasedInsetPosition;
2764 // There was no inset at the beginning, so we need to create one with
2765 // the key and label of the one we erased.
2766 InsetBibitem * inset =
2767 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2768 // restore values of previously deleted item in this par.
2769 if (!oldkey.empty())
2770 inset->setParam("key", oldkey);
2771 inset->setParam("label", oldlabel);
2772 insertInset(0, static_cast<Inset *>(inset),
2773 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2779 void Paragraph::checkAuthors(AuthorList const & authorList)
2781 d->changes_.checkAuthors(authorList);
2785 bool Paragraph::isUnchanged(pos_type pos) const
2787 return lookupChange(pos).type == Change::UNCHANGED;
2791 bool Paragraph::isInserted(pos_type pos) const
2793 return lookupChange(pos).type == Change::INSERTED;
2797 bool Paragraph::isDeleted(pos_type pos) const
2799 return lookupChange(pos).type == Change::DELETED;
2803 InsetList const & Paragraph::insetList() const
2805 return d->insetlist_;
2809 void Paragraph::setBuffer(Buffer & b)
2811 d->insetlist_.setBuffer(b);
2815 Inset * Paragraph::releaseInset(pos_type pos)
2817 Inset * inset = d->insetlist_.release(pos);
2818 /// does not honour change tracking!
2819 eraseChar(pos, false);
2824 Inset * Paragraph::getInset(pos_type pos)
2826 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2827 ? d->insetlist_.get(pos) : 0;
2831 Inset const * Paragraph::getInset(pos_type pos) const
2833 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2834 ? d->insetlist_.get(pos) : 0;
2838 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2839 pos_type & right, TextCase action)
2841 // process sequences of modified characters; in change
2842 // tracking mode, this approach results in much better
2843 // usability than changing case on a char-by-char basis
2846 bool const trackChanges = bparams.trackChanges;
2848 bool capitalize = true;
2850 for (; pos < right; ++pos) {
2851 char_type oldChar = d->text_[pos];
2852 char_type newChar = oldChar;
2854 // ignore insets and don't play with deleted text!
2855 if (oldChar != META_INSET && !isDeleted(pos)) {
2857 case text_lowercase:
2858 newChar = lowercase(oldChar);
2860 case text_capitalization:
2862 newChar = uppercase(oldChar);
2866 case text_uppercase:
2867 newChar = uppercase(oldChar);
2872 if (isWordSeparator(pos) || isDeleted(pos)) {
2873 // permit capitalization again
2877 if (oldChar != newChar) {
2879 if (pos != right - 1)
2881 // step behind the changing area
2885 int erasePos = pos - changes.size();
2886 for (size_t i = 0; i < changes.size(); i++) {
2887 insertChar(pos, changes[i],
2888 getFontSettings(bparams,
2891 if (!eraseChar(erasePos, trackChanges)) {
2894 ++right; // expand selection
2902 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2903 pos_type pos, bool del) const
2905 int const strsize = str.length();
2907 pos_type const parsize = d->text_.size();
2908 for (i = 0; pos + i < parsize; ++i) {
2911 if (cs && str[i] != d->text_[pos + i])
2913 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2915 if (!del && isDeleted(pos + i))
2922 // if necessary, check whether string matches word
2924 if (pos > 0 && !isWordSeparator(pos - 1))
2926 if (pos + strsize < parsize
2927 && !isWordSeparator(pos + strsize))
2935 char_type Paragraph::getChar(pos_type pos) const
2937 return d->text_[pos];
2941 pos_type Paragraph::size() const
2943 return d->text_.size();
2947 bool Paragraph::empty() const
2949 return d->text_.empty();
2953 bool Paragraph::isInset(pos_type pos) const
2955 return d->text_[pos] == META_INSET;
2959 bool Paragraph::isSeparator(pos_type pos) const
2961 //FIXME: Are we sure this can be the only separator?
2962 return d->text_[pos] == ' ';
2966 void Paragraph::deregisterWords()
2968 Private::Words::const_iterator it;
2969 WordList & wl = theWordList();
2970 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2976 void Paragraph::locateWord(pos_type & from, pos_type & to,
2977 word_location const loc) const
2980 case WHOLE_WORD_STRICT:
2981 if (from == 0 || from == size()
2982 || isWordSeparator(from)
2983 || isWordSeparator(from - 1)) {
2987 // no break here, we go to the next
2990 // If we are already at the beginning of a word, do nothing
2991 if (!from || isWordSeparator(from - 1))
2993 // no break here, we go to the next
2996 // always move the cursor to the beginning of previous word
2997 while (from && !isWordSeparator(from - 1))
3001 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3004 // no need to move the 'from' cursor
3008 while (to < size() && !isWordSeparator(to))
3013 void Paragraph::collectWords()
3015 pos_type n = size();
3017 docstring_list suggestions;
3018 for (pos_type pos = 0; pos < n; ++pos) {
3019 if (isWordSeparator(pos))
3021 pos_type from = pos;
3022 locateWord(from, pos, WHOLE_WORD);
3023 if (pos - from >= 6) {
3024 docstring word = asString(from, pos, AS_STR_NONE);
3025 d->words_.insert(word);
3027 if (lyxrc.spellcheck_continuously
3028 && spellCheck(from, pos, wl, suggestions)) {
3029 for (size_t i = 0; i != suggestions.size(); ++i)
3030 d->words_.insert(suggestions[i]);
3036 void Paragraph::registerWords()
3038 Private::Words::const_iterator it;
3039 WordList & wl = theWordList();
3040 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3045 void Paragraph::updateWords()
3053 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3054 docstring_list & suggestions) const
3056 SpellChecker * speller = theSpellChecker();
3060 locateWord(from, to, WHOLE_WORD);
3061 if (from == to || from >= pos_type(d->text_.size()))
3064 docstring word = asString(from, to, AS_STR_INSETS);
3065 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3066 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3067 : lyxrc.spellchecker_alt_lang;
3068 wl = WordLangTuple(word, lang_code);
3069 SpellChecker::Result res = speller->check(wl);
3070 // Just ignore any error that the spellchecker reports.
3071 // FIXME: we should through out an exception and catch it in the GUI to
3072 // display the error.
3073 if (!speller->error().empty())
3076 bool const misspelled = res != SpellChecker::OK
3077 && res != SpellChecker::IGNORED_WORD;
3079 if (lyxrc.spellcheck_continuously)
3080 d->fontlist_.setMisspelled(from, to, misspelled);
3083 while (!(word = speller->nextMiss()).empty())
3084 suggestions.push_back(word);
3090 bool Paragraph::isMisspelled(pos_type pos) const
3092 pos_type from = pos;
3095 docstring_list suggestions;
3096 return spellCheck(from, to, wl, suggestions);