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(BufferParams const & bparams, pos_type start,
368 LASSERT(start >= 0 && start <= size(), /**/);
369 LASSERT(end > start && end <= size() + 1, /**/);
371 for (pos_type pos = start; pos < end; ++pos) {
372 switch (lookupChange(pos).type) {
373 case Change::UNCHANGED:
374 // accept changes in nested inset
375 if (Inset * inset = getInset(pos))
376 inset->acceptChanges(bparams);
379 case Change::INSERTED:
380 d->changes_.set(Change(Change::UNCHANGED), pos);
381 // also accept changes in nested inset
382 if (Inset * inset = getInset(pos))
383 inset->acceptChanges(bparams);
386 case Change::DELETED:
387 // Suppress access to non-existent
388 // "end-of-paragraph char"
390 eraseChar(pos, false);
401 void Paragraph::rejectChanges(BufferParams const & bparams,
402 pos_type start, pos_type end)
404 LASSERT(start >= 0 && start <= size(), /**/);
405 LASSERT(end > start && end <= size() + 1, /**/);
407 for (pos_type pos = start; pos < end; ++pos) {
408 switch (lookupChange(pos).type) {
409 case Change::UNCHANGED:
410 // reject changes in nested inset
411 if (Inset * inset = getInset(pos))
412 inset->rejectChanges(bparams);
415 case Change::INSERTED:
416 // Suppress access to non-existent
417 // "end-of-paragraph char"
419 eraseChar(pos, false);
425 case Change::DELETED:
426 d->changes_.set(Change(Change::UNCHANGED), pos);
428 // Do NOT reject changes within a deleted inset!
429 // There may be insertions of a co-author inside of it!
437 void Paragraph::Private::insertChar(pos_type pos, char_type c,
438 Change const & change)
440 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
443 changes_.insert(change, pos);
445 // This is actually very common when parsing buffers (and
446 // maybe inserting ascii text)
447 if (pos == pos_type(text_.size())) {
448 // when appending characters, no need to update tables
453 text_.insert(text_.begin() + pos, c);
455 // Update the font table.
456 fontlist_.increasePosAfterPos(pos);
459 insetlist_.increasePosAfterPos(pos);
463 bool Paragraph::insertInset(pos_type pos, Inset * inset,
464 Change const & change)
466 LASSERT(inset, /**/);
467 LASSERT(pos >= 0 && pos <= size(), /**/);
469 // Paragraph::insertInset() can be used in cut/copy/paste operation where
470 // d->inset_owner_ is not set yet.
471 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
474 d->insertChar(pos, META_INSET, change);
475 LASSERT(d->text_[pos] == META_INSET, /**/);
477 // Add a new entry in the insetlist_.
478 d->insetlist_.insert(inset, pos);
483 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
485 LASSERT(pos >= 0 && pos <= size(), return false);
487 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
490 Change change = d->changes_.lookup(pos);
492 // set the character to DELETED if
493 // a) it was previously unchanged or
494 // b) it was inserted by a co-author
496 if (change.type == Change::UNCHANGED ||
497 (change.type == Change::INSERTED && change.author != 0)) {
498 setChange(pos, Change(Change::DELETED));
502 if (change.type == Change::DELETED)
506 // Don't physically access the imaginary end-of-paragraph character.
507 // eraseChar() can only mark it as DELETED. A physical deletion of
508 // end-of-par must be handled externally.
514 d->changes_.erase(pos);
516 // if it is an inset, delete the inset entry
517 if (d->text_[pos] == META_INSET)
518 d->insetlist_.erase(pos);
520 d->text_.erase(d->text_.begin() + pos);
522 // Update the fontlist_
523 d->fontlist_.erase(pos);
525 // Update the insetlist_
526 d->insetlist_.decreasePosAfterPos(pos);
532 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
534 LASSERT(start >= 0 && start <= size(), /**/);
535 LASSERT(end >= start && end <= size() + 1, /**/);
538 for (pos_type count = end - start; count; --count) {
539 if (!eraseChar(i, trackChanges))
546 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
547 char_type next, Encoding const & encoding)
549 // Writing next here may circumvent a possible font change between
550 // c and next. Since next is only output if it forms a surrogate pair
551 // with c we can ignore this:
552 // A font change inside a surrogate pair does not make sense and is
553 // hopefully impossible to input.
554 // FIXME: change tracking
555 // Is this correct WRT change tracking?
556 docstring const latex1 = encoding.latexChar(next);
557 docstring const latex2 = encoding.latexChar(c);
558 if (docstring(1, next) == latex1) {
559 // the encoding supports the combination
560 os << latex2 << latex1;
561 return latex1.length() + latex2.length();
563 os << latex1 << '{' << latex2 << '}';
564 return latex1.length() + latex2.length() + 2;
568 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
569 odocstream & os, TexRow & texrow,
571 unsigned int & column,
573 Layout const & style)
575 if (style.pass_thru || runparams.verbatim)
578 if (i + 1 < int(text_.size())) {
579 char_type next = text_[i + 1];
580 if (Encodings::isCombiningChar(next)) {
581 Encoding const & encoding = *(runparams.encoding);
582 // This space has an accent, so we must always output it.
583 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
588 if (lyxrc.plaintext_linelen > 0
589 && column > lyxrc.plaintext_linelen
591 && text_[i - 1] != ' '
592 && (i + 1 < int(text_.size()))
593 // same in FreeSpacing mode
594 && !owner_->isFreeSpacing()
595 // In typewriter mode, we want to avoid
596 // ! . ? : at the end of a line
597 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
598 && (text_[i - 1] == '.'
599 || text_[i - 1] == '?'
600 || text_[i - 1] == ':'
601 || text_[i - 1] == '!'))) {
604 texrow.start(owner_->id(), i + 1);
606 } else if (style.free_spacing) {
615 int Paragraph::Private::writeScriptChars(odocstream & os,
616 docstring const & ltx,
617 Change const & runningChange,
618 Encoding const & encoding,
621 // FIXME: modifying i here is not very nice...
623 // We only arrive here when a proper language for character text_[i] has
624 // not been specified (i.e., it could not be translated in the current
625 // latex encoding) or its latex translation has been forced, and it
626 // belongs to a known script.
627 // Parameter ltx contains the latex translation of text_[i] as specified
628 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
629 // The latex macro name "textXXX" specifies the script to which text_[i]
630 // belongs and we use it in order to check whether characters from the
631 // same script immediately follow, such that we can collect them in a
632 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
633 // for the first char but only "<spec>" for all subsequent chars.
634 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
635 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
636 string script = to_ascii(ltx.substr(1, brace1 - 1));
639 bool closing_brace = true;
640 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
641 // Correct encoding is being used, so we can avoid \textgreek.
644 closing_brace = false;
646 os << ltx.substr(pos, length);
647 int size = text_.size();
648 while (i + 1 < size) {
649 char_type const next = text_[i + 1];
650 // Stop here if next character belongs to another script
651 // or there is a change in change tracking status.
652 if (!Encodings::isKnownScriptChar(next, script) ||
653 runningChange != owner_->lookupChange(i + 1))
657 FontList::const_iterator cit = fontlist_.begin();
658 FontList::const_iterator end = fontlist_.end();
659 for (; cit != end; ++cit) {
660 if (cit->pos() >= i && !found) {
661 prev_font = cit->font();
664 if (cit->pos() >= i + 1)
667 // Stop here if there is a font attribute or encoding change.
668 if (found && cit != end && prev_font != cit->font())
670 docstring const latex = encoding.latexChar(next);
671 docstring::size_type const b1 =
672 latex.find_first_of(from_ascii("{"));
673 docstring::size_type const b2 =
674 latex.find_last_of(from_ascii("}"));
675 int const len = b2 - b1 - 1;
676 os << latex.substr(b1 + 1, len);
688 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
690 pos_type const len = str.length();
692 // is the paragraph large enough?
693 if (pos + len > int(text_.size()))
696 // does the wanted text start at point?
697 for (string::size_type i = 0; i < str.length(); ++i) {
698 // Caution: direct comparison of characters works only
699 // because str is pure ASCII.
700 if (str[i] != text_[pos + i])
704 return fontlist_.hasChangeInRange(pos, len);
708 void Paragraph::Private::latexInset(
709 BufferParams const & bparams,
712 OutputParams & runparams,
715 Font const & outerfont,
717 Change & running_change,
718 Layout const & style,
720 unsigned int & column)
722 Inset * inset = owner_->getInset(i);
723 LASSERT(inset, /**/);
725 if (style.pass_thru) {
726 inset->plaintext(os, runparams);
730 // FIXME: move this to InsetNewline::latex
731 if (inset->lyxCode() == NEWLINE_CODE) {
732 // newlines are handled differently here than
733 // the default in simpleTeXSpecialChars().
734 if (!style.newline_allowed) {
738 column += running_font.latexWriteEndChanges(
739 os, bparams, runparams,
744 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
747 basefont = owner_->getLayoutFont(bparams, outerfont);
748 running_font = basefont;
750 if (runparams.moving_arg)
755 texrow.start(owner_->id(), i + 1);
759 if (owner_->lookupChange(i).type == Change::DELETED) {
760 if( ++runparams.inDeletedInset == 1)
761 runparams.changeOfDeletedInset = owner_->lookupChange(i);
764 if (inset->canTrackChanges()) {
765 column += Changes::latexMarkChange(os, bparams, running_change,
766 Change(Change::UNCHANGED));
767 running_change = Change(Change::UNCHANGED);
771 odocstream::pos_type const len = os.tellp();
773 if (inset->forceLTR()
774 && running_font.isRightToLeft()
775 // ERT is an exception, it should be output with no decorations at all
776 && inset->lyxCode() != ERT_CODE) {
777 if (running_font.language()->lang() == "farsi")
784 // FIXME: Bug: we can have an empty font change here!
785 // if there has just been a font change, we are going to close it
786 // right now, which means stupid latex code like \textsf{}. AFAIK,
787 // this does not harm dvi output. A minor bug, thus (JMarc)
789 // Some insets cannot be inside a font change command.
790 // However, even such insets *can* be placed in \L or \R
791 // or their equivalents (for RTL language switches), so we don't
792 // close the language in those cases.
793 // ArabTeX, though, cannot handle this special behavior, it seems.
794 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
795 || running_font.language()->lang() == "arabic_arabtex";
796 if (open_font && inset->noFontChange()) {
797 bool closeLanguage = arabtex
798 || basefont.isRightToLeft() == running_font.isRightToLeft();
799 unsigned int count = running_font.latexWriteEndChanges(os,
800 bparams, runparams, basefont, basefont, closeLanguage);
802 // if any font properties were closed, update the running_font,
803 // making sure, however, to leave the language as it was
805 // FIXME: probably a better way to keep track of the old
806 // language, than copying the entire font?
807 Font const copy_font(running_font);
808 basefont = owner_->getLayoutFont(bparams, outerfont);
809 running_font = basefont;
811 running_font.setLanguage(copy_font.language());
812 // leave font open if language is still open
813 open_font = (running_font.language() == basefont.language());
815 runparams.local_font = &basefont;
822 tmp = inset->latex(os, runparams);
823 } catch (EncodingException & e) {
824 // add location information and throw again.
831 if (running_font.language()->lang() == "farsi")
838 for (int j = 0; j < tmp; ++j)
841 texrow.start(owner_->id(), i + 1);
844 column += os.tellp() - len;
847 if (owner_->lookupChange(i).type == Change::DELETED)
848 --runparams.inDeletedInset;
852 void Paragraph::Private::latexSpecialChar(
854 OutputParams const & runparams,
855 Font const & running_font,
856 Change const & running_change,
857 Layout const & style,
859 unsigned int & column)
861 char_type const c = text_[i];
863 if (style.pass_thru) {
865 // FIXME UNICODE: This can fail if c cannot
866 // be encoded in the current encoding.
871 if (runparams.verbatim) {
872 // FIXME UNICODE: This can fail if c cannot
873 // be encoded in the current encoding.
878 // If T1 font encoding is used, use the special
879 // characters it provides.
880 // NOTE: some languages reset the font encoding
882 if (!running_font.language()->internalFontEncoding()
883 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
886 // \tt font needs special treatment
887 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
888 && latexSpecialTypewriter(c, os, i, column))
891 // Otherwise, we use what LaTeX provides us.
894 os << "\\textbackslash{}";
898 os << "\\textless{}";
902 os << "\\textgreater{}";
913 os << "\\char`\\\"{}";
918 case '%': case '#': case '{':
926 os << "\\textasciitilde{}";
931 os << "\\textasciicircum{}";
938 // avoid being mistaken for optional arguments
946 // Blanks are printed before font switching.
947 // Sure? I am not! (try nice-latex)
948 // I am sure it's correct. LyX might be smarter
949 // in the future, but for now, nothing wrong is
955 if (latexSpecialPhrase(os, i, column, runparams))
961 Encoding const & encoding = *(runparams.encoding);
962 if (i + 1 < int(text_.size())) {
963 char_type next = text_[i + 1];
964 if (Encodings::isCombiningChar(next)) {
965 column += latexSurrogatePair(os, c, next, encoding) - 1;
971 docstring const latex = encoding.latexChar(c);
972 if (Encodings::isKnownScriptChar(c, script)
973 && prefixIs(latex, from_ascii("\\" + script)))
974 column += writeScriptChars(os, latex,
975 running_change, encoding, i) - 1;
976 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
977 // Prevent eating of a following
978 // space or command corruption by
979 // following characters
980 column += latex.length() + 1;
983 column += latex.length() - 1;
991 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
992 pos_type i, unsigned int & column)
998 // In T1 encoding, these characters exist
999 // but we should avoid ligatures
1000 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1002 os << "\\textcompwordmark{}";
1009 // soul.sty breaks with \char`\"
1010 os << "\\textquotedbl{}";
1019 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1020 pos_type i, unsigned int & column)
1024 // within \ttfamily, "--" is merged to "-" (no endash)
1025 // so we avoid this rather irritating ligature
1026 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1033 // everything else has to be checked separately
1034 // (depending on the encoding)
1041 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1042 unsigned int & column, OutputParams const & runparams)
1044 // FIXME: if we have "LaTeX" with a font
1045 // change in the middle (before the 'T', then
1046 // the "TeX" part is still special cased.
1047 // Really we should only operate this on
1048 // "words" for some definition of word
1050 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1051 if (!isTextAt(special_phrases[pnr].phrase, i))
1053 if (runparams.moving_arg)
1055 os << special_phrases[pnr].macro;
1056 i += special_phrases[pnr].phrase.length() - 1;
1057 column += special_phrases[pnr].macro.length() - 1;
1064 void Paragraph::Private::validate(LaTeXFeatures & features,
1065 Layout const & layout) const
1067 // check the params.
1068 if (!params_.spacing().isDefault())
1069 features.require("setspace");
1072 features.useLayout(layout.name());
1075 fontlist_.validate(features);
1077 // then the indentation
1078 if (!params_.leftIndent().zero())
1079 features.require("ParagraphLeftIndent");
1082 InsetList::const_iterator icit = insetlist_.begin();
1083 InsetList::const_iterator iend = insetlist_.end();
1084 for (; icit != iend; ++icit) {
1086 icit->inset->validate(features);
1087 if (layout.needprotect &&
1088 icit->inset->lyxCode() == FOOT_CODE)
1089 features.require("NeedLyXFootnoteCode");
1093 // then the contents
1094 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1095 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1096 if (!special_phrases[pnr].builtin
1097 && isTextAt(special_phrases[pnr].phrase, i)) {
1098 features.require(special_phrases[pnr].phrase);
1102 Encodings::validate(text_[i], features);
1106 /////////////////////////////////////////////////////////////////////
1110 /////////////////////////////////////////////////////////////////////
1113 Layout const emptyParagraphLayout;
1116 Paragraph::Paragraph()
1117 : d(new Paragraph::Private(this, emptyParagraphLayout))
1124 Paragraph::Paragraph(Paragraph const & par)
1125 : itemdepth(par.itemdepth),
1126 d(new Paragraph::Private(*par.d, this))
1132 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1133 : itemdepth(par.itemdepth),
1134 d(new Paragraph::Private(*par.d, this, beg, end))
1140 Paragraph & Paragraph::operator=(Paragraph const & par)
1142 // needed as we will destroy the private part before copying it
1144 itemdepth = par.itemdepth;
1148 d = new Private(*par.d, this);
1155 Paragraph::~Paragraph()
1162 void Paragraph::write(ostream & os, BufferParams const & bparams,
1163 depth_type & dth) const
1165 // The beginning or end of a deeper (i.e. nested) area?
1166 if (dth != d->params_.depth()) {
1167 if (d->params_.depth() > dth) {
1168 while (d->params_.depth() > dth) {
1169 os << "\n\\begin_deeper";
1173 while (d->params_.depth() < dth) {
1174 os << "\n\\end_deeper";
1180 // First write the layout
1181 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1183 d->params_.write(os);
1185 Font font1(inherit_font, bparams.language);
1187 Change running_change = Change(Change::UNCHANGED);
1190 for (pos_type i = 0; i <= size(); ++i) {
1192 Change const change = lookupChange(i);
1193 Changes::lyxMarkChange(os, column, running_change, change);
1194 running_change = change;
1199 // Write font changes (ignore spelling markers)
1200 Font font2 = getFontSettings(bparams, i);
1201 font2.setMisspelled(false);
1202 if (font2 != font1) {
1203 font2.lyxWriteChanges(font1, os);
1208 char_type const c = d->text_[i];
1211 if (Inset const * inset = getInset(i)) {
1212 if (inset->directWrite()) {
1213 // international char, let it write
1214 // code directly so it's shorter in
1220 os << "\\begin_inset ";
1222 os << "\n\\end_inset\n\n";
1228 os << "\n\\backslash\n";
1232 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1239 if ((column > 70 && c == ' ')
1244 // this check is to amend a bug. LyX sometimes
1245 // inserts '\0' this could cause problems.
1247 os << to_utf8(docstring(1, c));
1249 LYXERR0("NUL char in structure.");
1255 os << "\n\\end_layout\n";
1259 void Paragraph::validate(LaTeXFeatures & features) const
1261 d->validate(features, *d->layout_);
1265 void Paragraph::insert(pos_type start, docstring const & str,
1266 Font const & font, Change const & change)
1268 for (size_t i = 0, n = str.size(); i != n ; ++i)
1269 insertChar(start + i, str[i], font, change);
1273 void Paragraph::appendChar(char_type c, Font const & font,
1274 Change const & change)
1277 d->changes_.insert(change, d->text_.size());
1278 // when appending characters, no need to update tables
1279 d->text_.push_back(c);
1280 setFont(d->text_.size() - 1, font);
1284 void Paragraph::appendString(docstring const & s, Font const & font,
1285 Change const & change)
1287 pos_type end = s.size();
1288 size_t oldsize = d->text_.size();
1289 size_t newsize = oldsize + end;
1290 size_t capacity = d->text_.capacity();
1291 if (newsize >= capacity)
1292 d->text_.reserve(max(capacity + 100, newsize));
1294 // when appending characters, no need to update tables
1297 // FIXME: Optimize this!
1298 for (size_t i = oldsize; i != newsize; ++i) {
1300 d->changes_.insert(change, i);
1302 d->fontlist_.set(oldsize, font);
1303 d->fontlist_.set(newsize - 1, font);
1307 void Paragraph::insertChar(pos_type pos, char_type c,
1310 d->insertChar(pos, c, Change(trackChanges ?
1311 Change::INSERTED : Change::UNCHANGED));
1315 void Paragraph::insertChar(pos_type pos, char_type c,
1316 Font const & font, bool trackChanges)
1318 d->insertChar(pos, c, Change(trackChanges ?
1319 Change::INSERTED : Change::UNCHANGED));
1324 void Paragraph::insertChar(pos_type pos, char_type c,
1325 Font const & font, Change const & change)
1327 d->insertChar(pos, c, change);
1332 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1333 Font const & font, Change const & change)
1335 bool const success = insertInset(pos, inset, change);
1336 // Set the font/language of the inset...
1342 void Paragraph::resetFonts(Font const & font)
1344 d->fontlist_.clear();
1345 d->fontlist_.set(0, font);
1346 d->fontlist_.set(d->text_.size() - 1, font);
1349 // Gets uninstantiated font setting at position.
1350 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1354 LYXERR0("pos: " << pos << " size: " << size());
1355 LASSERT(pos <= size(), /**/);
1358 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1359 if (cit != d->fontlist_.end())
1362 if (pos == size() && !empty())
1363 return getFontSettings(bparams, pos - 1);
1365 // Optimisation: avoid a full font instantiation if there is no
1366 // language change from previous call.
1367 static Font previous_font;
1368 static Language const * previous_lang = 0;
1369 Language const * lang = getParLanguage(bparams);
1370 if (lang != previous_lang) {
1371 previous_lang = lang;
1372 previous_font = Font(inherit_font, lang);
1374 return previous_font;
1378 FontSpan Paragraph::fontSpan(pos_type pos) const
1380 LASSERT(pos <= size(), /**/);
1383 FontList::const_iterator cit = d->fontlist_.begin();
1384 FontList::const_iterator end = d->fontlist_.end();
1385 for (; cit != end; ++cit) {
1386 if (cit->pos() >= pos) {
1387 if (pos >= beginOfBody())
1388 return FontSpan(max(start, beginOfBody()),
1391 return FontSpan(start,
1392 min(beginOfBody() - 1,
1395 start = cit->pos() + 1;
1398 // This should not happen, but if so, we take no chances.
1399 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1400 return FontSpan(pos, pos);
1404 // Gets uninstantiated font setting at position 0
1405 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1407 if (!empty() && !d->fontlist_.empty())
1408 return d->fontlist_.begin()->font();
1410 // Optimisation: avoid a full font instantiation if there is no
1411 // language change from previous call.
1412 static Font previous_font;
1413 static Language const * previous_lang = 0;
1414 if (bparams.language != previous_lang) {
1415 previous_lang = bparams.language;
1416 previous_font = Font(inherit_font, bparams.language);
1419 return previous_font;
1423 // Gets the fully instantiated font at a given position in a paragraph
1424 // This is basically the same function as Text::GetFont() in text2.cpp.
1425 // The difference is that this one is used for generating the LaTeX file,
1426 // and thus cosmetic "improvements" are disallowed: This has to deliver
1427 // the true picture of the buffer. (Asger)
1428 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1429 Font const & outerfont) const
1431 LASSERT(pos >= 0, /**/);
1433 Font font = getFontSettings(bparams, pos);
1435 pos_type const body_pos = beginOfBody();
1436 FontInfo & fi = font.fontInfo();
1438 fi.realize(d->layout_->labelfont);
1440 fi.realize(d->layout_->font);
1442 fi.realize(outerfont.fontInfo());
1443 fi.realize(bparams.getFont().fontInfo());
1449 Font const Paragraph::getLabelFont
1450 (BufferParams const & bparams, Font const & outerfont) const
1452 FontInfo tmpfont = d->layout_->labelfont;
1453 tmpfont.realize(outerfont.fontInfo());
1454 tmpfont.realize(bparams.getFont().fontInfo());
1455 return Font(tmpfont, getParLanguage(bparams));
1459 Font const Paragraph::getLayoutFont
1460 (BufferParams const & bparams, Font const & outerfont) const
1462 FontInfo tmpfont = d->layout_->font;
1463 tmpfont.realize(outerfont.fontInfo());
1464 tmpfont.realize(bparams.getFont().fontInfo());
1465 return Font(tmpfont, getParLanguage(bparams));
1469 /// Returns the height of the highest font in range
1470 FontSize Paragraph::highestFontInRange
1471 (pos_type startpos, pos_type endpos, FontSize def_size) const
1473 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1477 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1479 char_type c = d->text_[pos];
1480 if (!lyxrc.rtl_support)
1510 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1516 void Paragraph::setFont(pos_type pos, Font const & font)
1518 LASSERT(pos <= size(), /**/);
1520 // First, reduce font against layout/label font
1521 // Update: The setCharFont() routine in text2.cpp already
1522 // reduces font, so we don't need to do that here. (Asger)
1524 d->fontlist_.set(pos, font);
1528 void Paragraph::makeSameLayout(Paragraph const & par)
1530 d->layout_ = par.d->layout_;
1531 d->params_ = par.d->params_;
1535 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1537 if (isFreeSpacing())
1543 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1544 if (eraseChar(pos, trackChanges))
1550 return count > 0 || pos > 0;
1554 bool Paragraph::hasSameLayout(Paragraph const & par) const
1556 return par.d->layout_ == d->layout_
1557 && d->params_.sameLayout(par.d->params_);
1561 depth_type Paragraph::getDepth() const
1563 return d->params_.depth();
1567 depth_type Paragraph::getMaxDepthAfter() const
1569 if (d->layout_->isEnvironment())
1570 return d->params_.depth() + 1;
1572 return d->params_.depth();
1576 char Paragraph::getAlign() const
1578 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1579 return d->layout_->align;
1581 return d->params_.align();
1585 docstring const & Paragraph::labelString() const
1587 return d->params_.labelString();
1591 // the next two functions are for the manual labels
1592 docstring const Paragraph::getLabelWidthString() const
1594 if (d->layout_->margintype == MARGIN_MANUAL
1595 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1596 return d->params_.labelWidthString();
1598 return _("Senseless with this layout!");
1602 void Paragraph::setLabelWidthString(docstring const & s)
1604 d->params_.labelWidthString(s);
1608 docstring Paragraph::expandLabel(Layout const & layout,
1609 BufferParams const & bparams, bool process_appendix) const
1611 DocumentClass const & tclass = bparams.documentClass();
1612 string const & lang = getParLanguage(bparams)->code();
1613 bool const in_appendix = process_appendix && d->params_.appendix();
1614 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1616 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1617 && !layout.counter.empty())
1618 return tclass.counters().theCounter(layout.counter, lang);
1620 // handle 'inherited level parts' in 'fmt',
1621 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1622 size_t const i = fmt.find('@', 0);
1623 if (i != docstring::npos) {
1624 size_t const j = fmt.find('@', i + 1);
1625 if (j != docstring::npos) {
1626 docstring parent(fmt, i + 1, j - i - 1);
1627 docstring label = from_ascii("??");
1628 if (tclass.hasLayout(parent))
1629 docstring label = expandLabel(tclass[parent], bparams,
1631 fmt = docstring(fmt, 0, i) + label
1632 + docstring(fmt, j + 1, docstring::npos);
1636 return tclass.counters().counterLabel(fmt, lang);
1640 void Paragraph::applyLayout(Layout const & new_layout)
1642 d->layout_ = &new_layout;
1643 LyXAlignment const oldAlign = d->params_.align();
1645 if (!(oldAlign & d->layout_->alignpossible)) {
1646 frontend::Alert::warning(_("Alignment not permitted"),
1647 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1648 d->params_.align(LYX_ALIGN_LAYOUT);
1653 pos_type Paragraph::beginOfBody() const
1655 return d->begin_of_body_;
1659 void Paragraph::setBeginOfBody()
1661 if (d->layout_->labeltype != LABEL_MANUAL) {
1662 d->begin_of_body_ = 0;
1666 // Unroll the first two cycles of the loop
1667 // and remember the previous character to
1668 // remove unnecessary getChar() calls
1670 pos_type end = size();
1671 if (i < end && !isNewline(i)) {
1673 char_type previous_char = 0;
1676 previous_char = d->text_[i];
1677 if (!isNewline(i)) {
1679 while (i < end && previous_char != ' ') {
1684 previous_char = temp;
1690 d->begin_of_body_ = i;
1694 bool Paragraph::forcePlainLayout() const
1696 return inInset().forcePlainLayout();
1700 bool Paragraph::allowParagraphCustomization() const
1702 return inInset().allowParagraphCustomization();
1706 bool Paragraph::usePlainLayout() const
1708 return inInset().usePlainLayout();
1714 // paragraphs inside floats need different alignment tags to avoid
1717 bool noTrivlistCentering(InsetCode code)
1719 return code == FLOAT_CODE
1720 || code == WRAP_CODE
1721 || code == CELL_CODE;
1725 string correction(string const & orig)
1727 if (orig == "flushleft")
1728 return "raggedright";
1729 if (orig == "flushright")
1730 return "raggedleft";
1731 if (orig == "center")
1737 string const corrected_env(string const & suffix, string const & env,
1738 InsetCode code, bool const lastpar)
1740 string output = suffix + "{";
1741 if (noTrivlistCentering(code)) {
1743 // the last paragraph in non-trivlist-aligned
1744 // context is special (to avoid unwanted whitespace)
1745 if (suffix == "\\begin")
1746 return "\\" + correction(env) + "{}";
1749 output += correction(env);
1753 if (suffix == "\\begin")
1759 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1761 if (!contains(str, "\n"))
1762 column += str.size();
1766 column = rsplit(str, tmp, '\n').size();
1773 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1774 odocstream & os, TexRow & texrow,
1775 OutputParams const & runparams) const
1779 if (params_.noindent()) {
1780 os << "\\noindent ";
1784 LyXAlignment const curAlign = params_.align();
1786 if (curAlign == layout_->align)
1790 case LYX_ALIGN_NONE:
1791 case LYX_ALIGN_BLOCK:
1792 case LYX_ALIGN_LAYOUT:
1793 case LYX_ALIGN_SPECIAL:
1795 case LYX_ALIGN_LEFT:
1796 case LYX_ALIGN_RIGHT:
1797 case LYX_ALIGN_CENTER:
1798 if (runparams.moving_arg) {
1805 string const begin_tag = "\\begin";
1806 InsetCode code = owner_->ownerCode();
1807 bool const lastpar = runparams.isLastPar;
1810 case LYX_ALIGN_NONE:
1811 case LYX_ALIGN_BLOCK:
1812 case LYX_ALIGN_LAYOUT:
1813 case LYX_ALIGN_SPECIAL:
1815 case LYX_ALIGN_LEFT: {
1817 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1818 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1820 output = corrected_env(begin_tag, "flushright", code, lastpar);
1821 os << from_ascii(output);
1822 adjust_row_column(output, texrow, column);
1824 } case LYX_ALIGN_RIGHT: {
1826 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1827 output = corrected_env(begin_tag, "flushright", code, lastpar);
1829 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1830 os << from_ascii(output);
1831 adjust_row_column(output, texrow, column);
1833 } case LYX_ALIGN_CENTER: {
1835 output = corrected_env(begin_tag, "center", code, lastpar);
1836 os << from_ascii(output);
1837 adjust_row_column(output, texrow, column);
1846 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1847 odocstream & os, TexRow & texrow,
1848 OutputParams const & runparams) const
1852 LyXAlignment const curAlign = params_.align();
1854 if (curAlign == layout_->align)
1858 case LYX_ALIGN_NONE:
1859 case LYX_ALIGN_BLOCK:
1860 case LYX_ALIGN_LAYOUT:
1861 case LYX_ALIGN_SPECIAL:
1863 case LYX_ALIGN_LEFT:
1864 case LYX_ALIGN_RIGHT:
1865 case LYX_ALIGN_CENTER:
1866 if (runparams.moving_arg) {
1873 string const end_tag = "\n\\par\\end";
1874 InsetCode code = owner_->ownerCode();
1875 bool const lastpar = runparams.isLastPar;
1878 case LYX_ALIGN_NONE:
1879 case LYX_ALIGN_BLOCK:
1880 case LYX_ALIGN_LAYOUT:
1881 case LYX_ALIGN_SPECIAL:
1883 case LYX_ALIGN_LEFT: {
1885 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1886 output = corrected_env(end_tag, "flushleft", code, lastpar);
1888 output = corrected_env(end_tag, "flushright", code, lastpar);
1889 os << from_ascii(output);
1890 adjust_row_column(output, texrow, column);
1892 } case LYX_ALIGN_RIGHT: {
1894 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1895 output = corrected_env(end_tag, "flushright", code, lastpar);
1897 output = corrected_env(end_tag, "flushleft", code, lastpar);
1898 os << from_ascii(output);
1899 adjust_row_column(output, texrow, column);
1901 } case LYX_ALIGN_CENTER: {
1903 output = corrected_env(end_tag, "center", code, lastpar);
1904 os << from_ascii(output);
1905 adjust_row_column(output, texrow, column);
1914 // This one spits out the text of the paragraph
1915 bool Paragraph::latex(BufferParams const & bparams,
1916 Font const & outerfont,
1917 odocstream & os, TexRow & texrow,
1918 OutputParams const & runparams,
1919 int start_pos, int end_pos) const
1921 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1923 bool return_value = false;
1925 bool const allowcust = allowParagraphCustomization();
1927 // FIXME This check should not be needed. Perhaps issue an
1928 // error if it triggers.
1929 Layout const & style = forcePlainLayout() ?
1930 bparams.documentClass().plainLayout() : *d->layout_;
1932 // Current base font for all inherited font changes, without any
1933 // change caused by an individual character, except for the language:
1934 // It is set to the language of the first character.
1935 // As long as we are in the label, this font is the base font of the
1936 // label. Before the first body character it is set to the base font
1940 // Maybe we have to create a optional argument.
1941 pos_type body_pos = beginOfBody();
1942 unsigned int column = 0;
1947 basefont = getLabelFont(bparams, outerfont);
1949 basefont = getLayoutFont(bparams, outerfont);
1952 // Which font is currently active?
1953 Font running_font(basefont);
1954 // Do we have an open font change?
1955 bool open_font = false;
1957 Change runningChange = Change(Change::UNCHANGED);
1959 texrow.start(id(), 0);
1961 // if the paragraph is empty, the loop will not be entered at all
1963 if (style.isCommand()) {
1968 column += d->startTeXParParams(bparams, os, texrow,
1972 for (pos_type i = 0; i < size(); ++i) {
1973 // First char in paragraph or after label?
1974 if (i == body_pos) {
1977 column += running_font.latexWriteEndChanges(
1978 os, bparams, runparams,
1979 basefont, basefont);
1982 basefont = getLayoutFont(bparams, outerfont);
1983 running_font = basefont;
1985 column += Changes::latexMarkChange(os, bparams,
1986 runningChange, Change(Change::UNCHANGED));
1987 runningChange = Change(Change::UNCHANGED);
1992 if (style.isCommand()) {
1998 column += d->startTeXParParams(bparams, os,
2003 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2006 if (bparams.outputChanges && runningChange != change) {
2008 column += running_font.latexWriteEndChanges(
2009 os, bparams, runparams, basefont, basefont);
2012 basefont = getLayoutFont(bparams, outerfont);
2013 running_font = basefont;
2015 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2016 runningChange = change;
2019 // do not output text which is marked deleted
2020 // if change tracking output is disabled
2021 if (!bparams.outputChanges && change.type == Change::DELETED) {
2027 // Fully instantiated font
2028 Font const font = getFont(bparams, i, outerfont);
2030 Font const last_font = running_font;
2032 // Do we need to close the previous font?
2034 (font != running_font ||
2035 font.language() != running_font.language()))
2037 column += running_font.latexWriteEndChanges(
2038 os, bparams, runparams, basefont,
2039 (i == body_pos-1) ? basefont : font);
2040 running_font = basefont;
2044 // close babel's font environment before opening CJK.
2045 if (!running_font.language()->babel().empty() &&
2046 font.language()->encoding()->package() == Encoding::CJK) {
2047 string end_tag = subst(lyxrc.language_command_end,
2049 running_font.language()->babel());
2050 os << from_ascii(end_tag);
2051 column += end_tag.length();
2054 // Switch file encoding if necessary (and allowed)
2055 if (!runparams.verbatim &&
2056 runparams.encoding->package() != Encoding::none &&
2057 font.language()->encoding()->package() != Encoding::none) {
2058 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2059 runparams, *(font.language()->encoding()));
2060 if (enc_switch.first) {
2061 column += enc_switch.second;
2062 runparams.encoding = font.language()->encoding();
2066 char_type const c = d->text_[i];
2068 // Do we need to change font?
2069 if ((font != running_font ||
2070 font.language() != running_font.language()) &&
2073 odocstringstream ods;
2074 column += font.latexWriteStartChanges(ods, bparams,
2075 runparams, basefont,
2077 running_font = font;
2079 docstring fontchange = ods.str();
2080 // check if the fontchange ends with a trailing blank
2081 // (like "\small " (see bug 3382)
2082 if (suffixIs(fontchange, ' ') && c == ' ')
2083 os << fontchange.substr(0, fontchange.size() - 1)
2084 << from_ascii("{}");
2089 // FIXME: think about end_pos implementation...
2090 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2091 // FIXME: integrate this case in latexSpecialChar
2092 // Do not print the separation of the optional argument
2093 // if style.pass_thru is false. This works because
2094 // latexSpecialChar ignores spaces if
2095 // style.pass_thru is false.
2096 if (i != body_pos - 1) {
2097 if (d->simpleTeXBlanks(
2098 runparams, os, texrow,
2099 i, column, font, style)) {
2100 // A surrogate pair was output. We
2101 // must not call latexSpecialChar
2102 // in this iteration, since it would output
2103 // the combining character again.
2110 OutputParams rp = runparams;
2111 rp.free_spacing = style.free_spacing;
2112 rp.local_font = &font;
2113 rp.intitle = style.intitle;
2115 // Two major modes: LaTeX or plain
2116 // Handle here those cases common to both modes
2117 // and then split to handle the two modes separately.
2118 if (c == META_INSET) {
2119 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2120 d->latexInset(bparams, os,
2121 texrow, rp, running_font,
2122 basefont, outerfont, open_font,
2123 runningChange, style, i, column);
2126 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2128 d->latexSpecialChar(os, rp, running_font, runningChange,
2130 } catch (EncodingException & e) {
2131 if (runparams.dryrun) {
2132 os << "<" << _("LyX Warning: ")
2133 << _("uncodable character") << " '";
2137 // add location information and throw again.
2146 // Set the encoding to that returned from latexSpecialChar (see
2147 // comment for encoding member in OutputParams.h)
2148 runparams.encoding = rp.encoding;
2151 // If we have an open font definition, we have to close it
2153 #ifdef FIXED_LANGUAGE_END_DETECTION
2156 .latexWriteEndChanges(os, bparams, runparams,
2158 next_->getFont(bparams, 0, outerfont));
2160 running_font.latexWriteEndChanges(os, bparams,
2161 runparams, basefont, basefont);
2164 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2165 //FIXME: there as we start another \selectlanguage with the next paragraph if
2166 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2167 running_font.latexWriteEndChanges(os, bparams, runparams,
2168 basefont, basefont);
2172 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2174 // Needed if there is an optional argument but no contents.
2175 if (body_pos > 0 && body_pos == size()) {
2177 return_value = false;
2181 column += d->endTeXParParams(bparams, os, texrow,
2185 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2186 return return_value;
2190 bool Paragraph::emptyTag() const
2192 for (pos_type i = 0; i < size(); ++i) {
2193 if (Inset const * inset = getInset(i)) {
2194 InsetCode lyx_code = inset->lyxCode();
2195 if (lyx_code != TOC_CODE &&
2196 lyx_code != INCLUDE_CODE &&
2197 lyx_code != GRAPHICS_CODE &&
2198 lyx_code != ERT_CODE &&
2199 lyx_code != LISTINGS_CODE &&
2200 lyx_code != FLOAT_CODE &&
2201 lyx_code != TABULAR_CODE) {
2205 char_type c = d->text_[i];
2206 if (c != ' ' && c != '\t')
2214 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2217 for (pos_type i = 0; i < size(); ++i) {
2218 if (Inset const * inset = getInset(i)) {
2219 InsetCode lyx_code = inset->lyxCode();
2220 if (lyx_code == LABEL_CODE) {
2221 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2222 docstring const & id = il->getParam("name");
2223 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2231 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2235 for (i = 0; i < size(); ++i) {
2236 if (Inset const * inset = getInset(i)) {
2237 inset->docbook(os, runparams);
2239 char_type c = d->text_[i];
2242 os << sgml::escapeChar(c);
2249 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2253 for (i = 0; i < size(); ++i) {
2254 if (Inset const * inset = getInset(i)) {
2255 inset->xhtml(os, runparams);
2257 char_type c = d->text_[i];
2260 os << html::escapeChar(c);
2267 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2270 pos_type size = text_.size();
2271 for (pos_type i = initial; i < size; ++i) {
2272 Font font = owner_->getFont(buf.params(), i, outerfont);
2273 if (text_[i] == META_INSET)
2275 if (i != initial && font != font_old)
2284 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2286 OutputParams const & runparams,
2287 Font const & outerfont,
2288 pos_type initial) const
2290 bool emph_flag = false;
2292 Layout const & style = *d->layout_;
2294 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2296 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2299 // parsing main loop
2300 for (pos_type i = initial; i < size(); ++i) {
2301 Font font = getFont(buf.params(), i, outerfont);
2303 // handle <emphasis> tag
2304 if (font_old.emph() != font.fontInfo().emph()) {
2305 if (font.fontInfo().emph() == FONT_ON) {
2308 } else if (i != initial) {
2309 os << "</emphasis>";
2314 if (Inset const * inset = getInset(i)) {
2315 inset->docbook(os, runparams);
2317 char_type c = d->text_[i];
2319 if (style.pass_thru)
2322 os << sgml::escapeChar(c);
2324 font_old = font.fontInfo();
2328 os << "</emphasis>";
2331 if (style.free_spacing)
2333 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2338 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2340 OutputParams const & runparams,
2341 Font const & outerfont,
2342 pos_type initial) const
2346 // FIXME We really need to manage the tag nesting here.
2347 // Probably in the same sort of way as in output_xhtml.
2348 bool emph_flag = false;
2349 bool bold_flag = false;
2350 std::string closing_tag;
2352 Layout const & style = *d->layout_;
2354 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2356 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2359 // parsing main loop
2360 for (pos_type i = initial; i < size(); ++i) {
2361 Font font = getFont(buf.params(), i, outerfont);
2364 if (font_old.emph() != font.fontInfo().emph()) {
2365 if (font.fontInfo().emph() == FONT_ON) {
2368 } else if (emph_flag && i != initial) {
2374 if (font_old.series() != font.fontInfo().series()) {
2375 if (font.fontInfo().series() == BOLD_SERIES) {
2378 } else if (bold_flag && i != initial) {
2383 // FIXME Other such tags?
2385 if (Inset const * inset = getInset(i)) {
2386 retval += inset->xhtml(os, runparams);
2388 char_type c = d->text_[i];
2390 if (style.pass_thru)
2392 else if (c == '-') {
2395 if (j < size() && d->text_[j] == '-') {
2397 if (j < size() && d->text_[j] == '-') {
2398 str += from_ascii("—");
2401 str += from_ascii("–");
2409 os << html::escapeChar(c);
2411 font_old = font.fontInfo();
2414 // FIXME This could be out of order. See above.
2424 bool Paragraph::isHfill(pos_type pos) const
2426 Inset const * inset = getInset(pos);
2427 return inset && (inset->lyxCode() == SPACE_CODE &&
2428 inset->isStretchableSpace());
2432 bool Paragraph::isNewline(pos_type pos) const
2434 Inset const * inset = getInset(pos);
2435 return inset && inset->lyxCode() == NEWLINE_CODE;
2439 bool Paragraph::isLineSeparator(pos_type pos) const
2441 char_type const c = d->text_[pos];
2442 if (isLineSeparatorChar(c))
2444 Inset const * inset = getInset(pos);
2445 return inset && inset->isLineSeparator();
2449 bool Paragraph::isWordSeparator(pos_type pos) const
2451 if (Inset const * inset = getInset(pos))
2452 return !inset->isLetter();
2453 char_type const c = d->text_[pos];
2454 // We want to pass the ' and escape chars to the spellchecker
2455 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2456 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2461 bool Paragraph::isChar(pos_type pos) const
2463 if (Inset const * inset = getInset(pos))
2464 return inset->isChar();
2465 char_type const c = d->text_[pos];
2466 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2470 bool Paragraph::isSpace(pos_type pos) const
2472 if (Inset const * inset = getInset(pos))
2473 return inset->isSpace();
2474 char_type const c = d->text_[pos];
2475 return lyx::isSpace(c);
2480 Paragraph::getParLanguage(BufferParams const & bparams) const
2483 return getFirstFontSettings(bparams).language();
2484 // FIXME: we should check the prev par as well (Lgb)
2485 return bparams.language;
2489 bool Paragraph::isRTL(BufferParams const & bparams) const
2491 return lyxrc.rtl_support
2492 && getParLanguage(bparams)->rightToLeft()
2493 && ownerCode() != ERT_CODE
2494 && ownerCode() != LISTINGS_CODE;
2498 void Paragraph::changeLanguage(BufferParams const & bparams,
2499 Language const * from, Language const * to)
2501 // change language including dummy font change at the end
2502 for (pos_type i = 0; i <= size(); ++i) {
2503 Font font = getFontSettings(bparams, i);
2504 if (font.language() == from) {
2505 font.setLanguage(to);
2512 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2514 Language const * doc_language = bparams.language;
2515 FontList::const_iterator cit = d->fontlist_.begin();
2516 FontList::const_iterator end = d->fontlist_.end();
2518 for (; cit != end; ++cit)
2519 if (cit->font().language() != ignore_language &&
2520 cit->font().language() != latex_language &&
2521 cit->font().language() != doc_language)
2527 docstring Paragraph::asString(int options) const
2529 return asString(0, size(), options);
2533 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2535 odocstringstream os;
2538 && options & AS_STR_LABEL
2539 && !d->params_.labelString().empty())
2540 os << d->params_.labelString() << ' ';
2542 for (pos_type i = beg; i < end; ++i) {
2543 char_type const c = d->text_[i];
2544 if (isPrintable(c) || c == '\t'
2545 || (c == '\n' && options & AS_STR_NEWLINES))
2547 else if (c == META_INSET && options & AS_STR_INSETS)
2548 getInset(i)->tocString(os);
2555 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2557 odocstringstream os;
2560 && options & AS_STR_LABEL
2561 && !d->params_.labelString().empty())
2562 os << d->params_.labelString() << ' ';
2564 for (pos_type i = beg; i < end; ++i) {
2565 char_type const c = d->text_[i];
2566 if (isPrintable(c) || c == '\t'
2567 || (c == '\n' && options & AS_STR_NEWLINES))
2569 else if (c == META_INSET && options & AS_STR_INSETS) {
2570 getInset(i)->plaintext(os, runparams);
2578 void Paragraph::setInsetOwner(Inset const * inset)
2580 d->inset_owner_ = inset;
2584 int Paragraph::id() const
2590 Layout const & Paragraph::layout() const
2596 void Paragraph::setLayout(Layout const & layout)
2598 d->layout_ = &layout;
2602 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2604 setLayout(tc.defaultLayout());
2608 void Paragraph::setPlainLayout(DocumentClass const & tc)
2610 setLayout(tc.plainLayout());
2614 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2616 if (usePlainLayout())
2617 setPlainLayout(tclass);
2619 setDefaultLayout(tclass);
2623 Inset const & Paragraph::inInset() const
2625 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2626 _("Memory problem"), _("Paragraph not properly initialized")));
2627 return *d->inset_owner_;
2631 InsetCode Paragraph::ownerCode() const
2633 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2637 ParagraphParameters & Paragraph::params()
2643 ParagraphParameters const & Paragraph::params() const
2649 bool Paragraph::isFreeSpacing() const
2651 if (d->layout_->free_spacing)
2653 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2657 bool Paragraph::allowEmpty() const
2659 if (d->layout_->keepempty)
2661 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2665 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2667 if (!Encodings::isArabicChar(c))
2670 char_type prev_char = ' ';
2671 char_type next_char = ' ';
2673 for (pos_type i = pos - 1; i >= 0; --i) {
2674 char_type const par_char = d->text_[i];
2675 if (!Encodings::isArabicComposeChar(par_char)) {
2676 prev_char = par_char;
2681 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2682 char_type const par_char = d->text_[i];
2683 if (!Encodings::isArabicComposeChar(par_char)) {
2684 next_char = par_char;
2689 if (Encodings::isArabicChar(next_char)) {
2690 if (Encodings::isArabicChar(prev_char) &&
2691 !Encodings::isArabicSpecialChar(prev_char))
2692 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2694 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2696 if (Encodings::isArabicChar(prev_char) &&
2697 !Encodings::isArabicSpecialChar(prev_char))
2698 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2700 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2705 int Paragraph::checkBiblio(Buffer const & buffer)
2708 // This is getting more and more a mess. ...We really should clean
2709 // up this bibitem issue for 1.6. See also bug 2743.
2711 // Add bibitem insets if necessary
2712 if (d->layout_->labeltype != LABEL_BIBLIO)
2715 bool hasbibitem = !d->insetlist_.empty()
2716 // Insist on it being in pos 0
2717 && d->text_[0] == META_INSET
2718 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2720 bool track_changes = buffer.params().trackChanges;
2725 // remove a bibitem in pos != 0
2726 // restore it later in pos 0 if necessary
2727 // (e.g. if a user inserts contents _before_ the item)
2728 // we're assuming there's only one of these, which there
2730 int erasedInsetPosition = -1;
2731 InsetList::iterator it = d->insetlist_.begin();
2732 InsetList::iterator end = d->insetlist_.end();
2733 for (; it != end; ++it)
2734 if (it->inset->lyxCode() == BIBITEM_CODE
2736 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2737 oldkey = olditem->getParam("key");
2738 oldlabel = olditem->getParam("label");
2739 erasedInsetPosition = it->pos;
2740 eraseChar(erasedInsetPosition, track_changes);
2744 // There was an InsetBibitem at the beginning, and we didn't
2745 // have to erase one.
2746 if (hasbibitem && erasedInsetPosition < 0)
2749 // There was an InsetBibitem at the beginning and we did have to
2750 // erase one. So we give its properties to the beginning inset.
2752 InsetBibitem * inset =
2753 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2754 if (!oldkey.empty())
2755 inset->setParam("key", oldkey);
2756 inset->setParam("label", oldlabel);
2757 return -erasedInsetPosition;
2760 // There was no inset at the beginning, so we need to create one with
2761 // the key and label of the one we erased.
2762 InsetBibitem * inset =
2763 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2764 // restore values of previously deleted item in this par.
2765 if (!oldkey.empty())
2766 inset->setParam("key", oldkey);
2767 inset->setParam("label", oldlabel);
2768 insertInset(0, static_cast<Inset *>(inset),
2769 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2775 void Paragraph::checkAuthors(AuthorList const & authorList)
2777 d->changes_.checkAuthors(authorList);
2781 bool Paragraph::isUnchanged(pos_type pos) const
2783 return lookupChange(pos).type == Change::UNCHANGED;
2787 bool Paragraph::isInserted(pos_type pos) const
2789 return lookupChange(pos).type == Change::INSERTED;
2793 bool Paragraph::isDeleted(pos_type pos) const
2795 return lookupChange(pos).type == Change::DELETED;
2799 InsetList const & Paragraph::insetList() const
2801 return d->insetlist_;
2805 void Paragraph::setBuffer(Buffer & b)
2807 d->insetlist_.setBuffer(b);
2811 Inset * Paragraph::releaseInset(pos_type pos)
2813 Inset * inset = d->insetlist_.release(pos);
2814 /// does not honour change tracking!
2815 eraseChar(pos, false);
2820 Inset * Paragraph::getInset(pos_type pos)
2822 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2823 ? d->insetlist_.get(pos) : 0;
2827 Inset const * Paragraph::getInset(pos_type pos) const
2829 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2830 ? d->insetlist_.get(pos) : 0;
2834 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2835 pos_type & right, TextCase action)
2837 // process sequences of modified characters; in change
2838 // tracking mode, this approach results in much better
2839 // usability than changing case on a char-by-char basis
2842 bool const trackChanges = bparams.trackChanges;
2844 bool capitalize = true;
2846 for (; pos < right; ++pos) {
2847 char_type oldChar = d->text_[pos];
2848 char_type newChar = oldChar;
2850 // ignore insets and don't play with deleted text!
2851 if (oldChar != META_INSET && !isDeleted(pos)) {
2853 case text_lowercase:
2854 newChar = lowercase(oldChar);
2856 case text_capitalization:
2858 newChar = uppercase(oldChar);
2862 case text_uppercase:
2863 newChar = uppercase(oldChar);
2868 if (isWordSeparator(pos) || isDeleted(pos)) {
2869 // permit capitalization again
2873 if (oldChar != newChar) {
2875 if (pos != right - 1)
2877 // step behind the changing area
2881 int erasePos = pos - changes.size();
2882 for (size_t i = 0; i < changes.size(); i++) {
2883 insertChar(pos, changes[i],
2884 getFontSettings(bparams,
2887 if (!eraseChar(erasePos, trackChanges)) {
2890 ++right; // expand selection
2898 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2899 pos_type pos, bool del) const
2901 int const strsize = str.length();
2903 pos_type const parsize = d->text_.size();
2904 for (i = 0; pos + i < parsize; ++i) {
2907 if (cs && str[i] != d->text_[pos + i])
2909 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2911 if (!del && isDeleted(pos + i))
2918 // if necessary, check whether string matches word
2920 if (pos > 0 && !isWordSeparator(pos - 1))
2922 if (pos + strsize < parsize
2923 && !isWordSeparator(pos + strsize))
2931 char_type Paragraph::getChar(pos_type pos) const
2933 return d->text_[pos];
2937 pos_type Paragraph::size() const
2939 return d->text_.size();
2943 bool Paragraph::empty() const
2945 return d->text_.empty();
2949 bool Paragraph::isInset(pos_type pos) const
2951 return d->text_[pos] == META_INSET;
2955 bool Paragraph::isSeparator(pos_type pos) const
2957 //FIXME: Are we sure this can be the only separator?
2958 return d->text_[pos] == ' ';
2962 void Paragraph::deregisterWords()
2964 Private::Words::const_iterator it;
2965 WordList & wl = theWordList();
2966 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2972 void Paragraph::locateWord(pos_type & from, pos_type & to,
2973 word_location const loc) const
2976 case WHOLE_WORD_STRICT:
2977 if (from == 0 || from == size()
2978 || isWordSeparator(from)
2979 || isWordSeparator(from - 1)) {
2983 // no break here, we go to the next
2986 // If we are already at the beginning of a word, do nothing
2987 if (!from || isWordSeparator(from - 1))
2989 // no break here, we go to the next
2992 // always move the cursor to the beginning of previous word
2993 while (from && !isWordSeparator(from - 1))
2997 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3000 // no need to move the 'from' cursor
3004 while (to < size() && !isWordSeparator(to))
3009 void Paragraph::collectWords()
3011 pos_type n = size();
3013 docstring_list suggestions;
3014 for (pos_type pos = 0; pos < n; ++pos) {
3015 if (isWordSeparator(pos))
3017 pos_type from = pos;
3018 locateWord(from, pos, WHOLE_WORD);
3019 if (pos - from >= 6) {
3020 docstring word = asString(from, pos, AS_STR_NONE);
3021 d->words_.insert(word);
3023 if (lyxrc.spellcheck_continuously
3024 && spellCheck(from, pos, wl, suggestions)) {
3025 for (size_t i = 0; i != suggestions.size(); ++i)
3026 d->words_.insert(suggestions[i]);
3032 void Paragraph::registerWords()
3034 Private::Words::const_iterator it;
3035 WordList & wl = theWordList();
3036 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3041 void Paragraph::updateWords()
3049 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3050 docstring_list & suggestions) const
3052 SpellChecker * speller = theSpellChecker();
3056 locateWord(from, to, WHOLE_WORD);
3057 if (from == to || from >= pos_type(d->text_.size()))
3060 docstring word = asString(from, to, AS_STR_INSETS);
3061 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3062 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3063 : lyxrc.spellchecker_alt_lang;
3064 wl = WordLangTuple(word, lang_code);
3065 SpellChecker::Result res = speller->check(wl);
3066 // Just ignore any error that the spellchecker reports.
3067 // FIXME: we should through out an exception and catch it in the GUI to
3068 // display the error.
3069 if (!speller->error().empty())
3072 bool const misspelled = res != SpellChecker::OK
3073 && res != SpellChecker::IGNORED_WORD;
3075 if (lyxrc.spellcheck_continuously)
3076 d->fontlist_.setMisspelled(from, to, misspelled);
3079 while (!(word = speller->nextMiss()).empty())
3080 suggestions.push_back(word);
3086 bool Paragraph::isMisspelled(pos_type pos) const
3088 pos_type from = pos;
3091 docstring_list suggestions;
3092 return spellCheck(from, to, wl, suggestions);