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 decorations at all
778 && inset->lyxCode() != ERT_CODE) {
779 if (running_font.language()->lang() == "farsi")
786 // FIXME: Bug: we can have an empty font change here!
787 // if there has just been a font change, we are going to close it
788 // right now, which means stupid latex code like \textsf{}. AFAIK,
789 // this does not harm dvi output. A minor bug, thus (JMarc)
791 // Some insets cannot be inside a font change command.
792 // However, even such insets *can* be placed in \L or \R
793 // or their equivalents (for RTL language switches), so we don't
794 // close the language in those cases.
795 // ArabTeX, though, cannot handle this special behavior, it seems.
796 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
797 || running_font.language()->lang() == "arabic_arabtex";
798 if (open_font && inset->noFontChange()) {
799 bool closeLanguage = arabtex
800 || basefont.isRightToLeft() == running_font.isRightToLeft();
801 unsigned int count = running_font.latexWriteEndChanges(os,
802 bparams, runparams, basefont, basefont, closeLanguage);
804 // if any font properties were closed, update the running_font,
805 // making sure, however, to leave the language as it was
807 // FIXME: probably a better way to keep track of the old
808 // language, than copying the entire font?
809 Font const copy_font(running_font);
810 basefont = owner_->getLayoutFont(bparams, outerfont);
811 running_font = basefont;
813 running_font.setLanguage(copy_font.language());
814 // leave font open if language is still open
815 open_font = (running_font.language() == basefont.language());
817 runparams.local_font = &basefont;
824 tmp = inset->latex(os, runparams);
825 } catch (EncodingException & e) {
826 // add location information and throw again.
833 if (running_font.language()->lang() == "farsi")
840 for (int j = 0; j < tmp; ++j)
843 texrow.start(owner_->id(), i + 1);
846 column += os.tellp() - len;
849 if (owner_->lookupChange(i).type == Change::DELETED)
850 --runparams.inDeletedInset;
854 void Paragraph::Private::latexSpecialChar(
856 OutputParams const & runparams,
857 Font const & running_font,
858 Change const & running_change,
859 Layout const & style,
861 unsigned int & column)
863 char_type const c = text_[i];
865 if (style.pass_thru) {
867 // FIXME UNICODE: This can fail if c cannot
868 // be encoded in the current encoding.
873 if (runparams.verbatim) {
874 // FIXME UNICODE: This can fail if c cannot
875 // be encoded in the current encoding.
880 // If T1 font encoding is used, use the special
881 // characters it provides.
882 // NOTE: some languages reset the font encoding
884 if (!running_font.language()->internalFontEncoding()
885 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
888 // \tt font needs special treatment
889 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
890 && latexSpecialTypewriter(c, os, i, column))
893 // Otherwise, we use what LaTeX provides us.
896 os << "\\textbackslash{}";
900 os << "\\textless{}";
904 os << "\\textgreater{}";
915 os << "\\char`\\\"{}";
920 case '%': case '#': case '{':
928 os << "\\textasciitilde{}";
933 os << "\\textasciicircum{}";
940 // avoid being mistaken for optional arguments
948 // Blanks are printed before font switching.
949 // Sure? I am not! (try nice-latex)
950 // I am sure it's correct. LyX might be smarter
951 // in the future, but for now, nothing wrong is
957 if (latexSpecialPhrase(os, i, column, runparams))
963 Encoding const & encoding = *(runparams.encoding);
964 if (i + 1 < int(text_.size())) {
965 char_type next = text_[i + 1];
966 if (Encodings::isCombiningChar(next)) {
967 column += latexSurrogatePair(os, c, next, runparams) - 1;
973 docstring const latex = encoding.latexChar(c);
974 if (Encodings::isKnownScriptChar(c, script)
975 && prefixIs(latex, from_ascii("\\" + script)))
976 column += writeScriptChars(os, latex,
977 running_change, encoding, i) - 1;
978 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
979 // Prevent eating of a following
980 // space or command corruption by
981 // following characters
982 column += latex.length() + 1;
985 column += latex.length() - 1;
993 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
994 pos_type i, unsigned int & column)
1000 // In T1 encoding, these characters exist
1001 // but we should avoid ligatures
1002 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1004 os << "\\textcompwordmark{}";
1011 // soul.sty breaks with \char`\"
1012 os << "\\textquotedbl{}";
1021 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1022 pos_type i, unsigned int & column)
1026 // within \ttfamily, "--" is merged to "-" (no endash)
1027 // so we avoid this rather irritating ligature
1028 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1035 // everything else has to be checked separately
1036 // (depending on the encoding)
1043 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1044 unsigned int & column, OutputParams const & runparams)
1046 // FIXME: if we have "LaTeX" with a font
1047 // change in the middle (before the 'T', then
1048 // the "TeX" part is still special cased.
1049 // Really we should only operate this on
1050 // "words" for some definition of word
1052 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1053 if (!isTextAt(special_phrases[pnr].phrase, i))
1055 if (runparams.moving_arg)
1057 os << special_phrases[pnr].macro;
1058 i += special_phrases[pnr].phrase.length() - 1;
1059 column += special_phrases[pnr].macro.length() - 1;
1066 void Paragraph::Private::validate(LaTeXFeatures & features,
1067 Layout const & layout) const
1069 // check the params.
1070 if (!params_.spacing().isDefault())
1071 features.require("setspace");
1074 features.useLayout(layout.name());
1077 fontlist_.validate(features);
1079 // then the indentation
1080 if (!params_.leftIndent().zero())
1081 features.require("ParagraphLeftIndent");
1084 InsetList::const_iterator icit = insetlist_.begin();
1085 InsetList::const_iterator iend = insetlist_.end();
1086 for (; icit != iend; ++icit) {
1088 icit->inset->validate(features);
1089 if (layout.needprotect &&
1090 icit->inset->lyxCode() == FOOT_CODE)
1091 features.require("NeedLyXFootnoteCode");
1095 // then the contents
1096 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1097 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1098 if (!special_phrases[pnr].builtin
1099 && isTextAt(special_phrases[pnr].phrase, i)) {
1100 features.require(special_phrases[pnr].phrase);
1104 Encodings::validate(text_[i], features);
1108 /////////////////////////////////////////////////////////////////////
1112 /////////////////////////////////////////////////////////////////////
1115 Layout const emptyParagraphLayout;
1118 Paragraph::Paragraph()
1119 : d(new Paragraph::Private(this, emptyParagraphLayout))
1126 Paragraph::Paragraph(Paragraph const & par)
1127 : itemdepth(par.itemdepth),
1128 d(new Paragraph::Private(*par.d, this))
1134 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1135 : itemdepth(par.itemdepth),
1136 d(new Paragraph::Private(*par.d, this, beg, end))
1142 Paragraph & Paragraph::operator=(Paragraph const & par)
1144 // needed as we will destroy the private part before copying it
1146 itemdepth = par.itemdepth;
1150 d = new Private(*par.d, this);
1157 Paragraph::~Paragraph()
1164 void Paragraph::write(ostream & os, BufferParams const & bparams,
1165 depth_type & dth) const
1167 // The beginning or end of a deeper (i.e. nested) area?
1168 if (dth != d->params_.depth()) {
1169 if (d->params_.depth() > dth) {
1170 while (d->params_.depth() > dth) {
1171 os << "\n\\begin_deeper";
1175 while (d->params_.depth() < dth) {
1176 os << "\n\\end_deeper";
1182 // First write the layout
1183 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1185 d->params_.write(os);
1187 Font font1(inherit_font, bparams.language);
1189 Change running_change = Change(Change::UNCHANGED);
1192 for (pos_type i = 0; i <= size(); ++i) {
1194 Change const change = lookupChange(i);
1195 Changes::lyxMarkChange(os, column, running_change, change);
1196 running_change = change;
1201 // Write font changes (ignore spelling markers)
1202 Font font2 = getFontSettings(bparams, i);
1203 font2.setMisspelled(false);
1204 if (font2 != font1) {
1205 font2.lyxWriteChanges(font1, os);
1210 char_type const c = d->text_[i];
1213 if (Inset const * inset = getInset(i)) {
1214 if (inset->directWrite()) {
1215 // international char, let it write
1216 // code directly so it's shorter in
1222 os << "\\begin_inset ";
1224 os << "\n\\end_inset\n\n";
1230 os << "\n\\backslash\n";
1234 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1241 if ((column > 70 && c == ' ')
1246 // this check is to amend a bug. LyX sometimes
1247 // inserts '\0' this could cause problems.
1249 os << to_utf8(docstring(1, c));
1251 LYXERR0("NUL char in structure.");
1257 os << "\n\\end_layout\n";
1261 void Paragraph::validate(LaTeXFeatures & features) const
1263 d->validate(features, *d->layout_);
1267 void Paragraph::insert(pos_type start, docstring const & str,
1268 Font const & font, Change const & change)
1270 for (size_t i = 0, n = str.size(); i != n ; ++i)
1271 insertChar(start + i, str[i], font, change);
1275 void Paragraph::appendChar(char_type c, Font const & font,
1276 Change const & change)
1279 d->changes_.insert(change, d->text_.size());
1280 // when appending characters, no need to update tables
1281 d->text_.push_back(c);
1282 setFont(d->text_.size() - 1, font);
1286 void Paragraph::appendString(docstring const & s, Font const & font,
1287 Change const & change)
1289 pos_type end = s.size();
1290 size_t oldsize = d->text_.size();
1291 size_t newsize = oldsize + end;
1292 size_t capacity = d->text_.capacity();
1293 if (newsize >= capacity)
1294 d->text_.reserve(max(capacity + 100, newsize));
1296 // when appending characters, no need to update tables
1299 // FIXME: Optimize this!
1300 for (size_t i = oldsize; i != newsize; ++i) {
1302 d->changes_.insert(change, i);
1304 d->fontlist_.set(oldsize, font);
1305 d->fontlist_.set(newsize - 1, font);
1309 void Paragraph::insertChar(pos_type pos, char_type c,
1312 d->insertChar(pos, c, Change(trackChanges ?
1313 Change::INSERTED : Change::UNCHANGED));
1317 void Paragraph::insertChar(pos_type pos, char_type c,
1318 Font const & font, bool trackChanges)
1320 d->insertChar(pos, c, Change(trackChanges ?
1321 Change::INSERTED : Change::UNCHANGED));
1326 void Paragraph::insertChar(pos_type pos, char_type c,
1327 Font const & font, Change const & change)
1329 d->insertChar(pos, c, change);
1334 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1335 Font const & font, Change const & change)
1337 bool const success = insertInset(pos, inset, change);
1338 // Set the font/language of the inset...
1344 void Paragraph::resetFonts(Font const & font)
1346 d->fontlist_.clear();
1347 d->fontlist_.set(0, font);
1348 d->fontlist_.set(d->text_.size() - 1, font);
1351 // Gets uninstantiated font setting at position.
1352 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1356 LYXERR0("pos: " << pos << " size: " << size());
1357 LASSERT(pos <= size(), /**/);
1360 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1361 if (cit != d->fontlist_.end())
1364 if (pos == size() && !empty())
1365 return getFontSettings(bparams, pos - 1);
1367 // Optimisation: avoid a full font instantiation if there is no
1368 // language change from previous call.
1369 static Font previous_font;
1370 static Language const * previous_lang = 0;
1371 Language const * lang = getParLanguage(bparams);
1372 if (lang != previous_lang) {
1373 previous_lang = lang;
1374 previous_font = Font(inherit_font, lang);
1376 return previous_font;
1380 FontSpan Paragraph::fontSpan(pos_type pos) const
1382 LASSERT(pos <= size(), /**/);
1385 FontList::const_iterator cit = d->fontlist_.begin();
1386 FontList::const_iterator end = d->fontlist_.end();
1387 for (; cit != end; ++cit) {
1388 if (cit->pos() >= pos) {
1389 if (pos >= beginOfBody())
1390 return FontSpan(max(start, beginOfBody()),
1393 return FontSpan(start,
1394 min(beginOfBody() - 1,
1397 start = cit->pos() + 1;
1400 // This should not happen, but if so, we take no chances.
1401 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1402 return FontSpan(pos, pos);
1406 // Gets uninstantiated font setting at position 0
1407 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1409 if (!empty() && !d->fontlist_.empty())
1410 return d->fontlist_.begin()->font();
1412 // Optimisation: avoid a full font instantiation if there is no
1413 // language change from previous call.
1414 static Font previous_font;
1415 static Language const * previous_lang = 0;
1416 if (bparams.language != previous_lang) {
1417 previous_lang = bparams.language;
1418 previous_font = Font(inherit_font, bparams.language);
1421 return previous_font;
1425 // Gets the fully instantiated font at a given position in a paragraph
1426 // This is basically the same function as Text::GetFont() in text2.cpp.
1427 // The difference is that this one is used for generating the LaTeX file,
1428 // and thus cosmetic "improvements" are disallowed: This has to deliver
1429 // the true picture of the buffer. (Asger)
1430 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1431 Font const & outerfont) const
1433 LASSERT(pos >= 0, /**/);
1435 Font font = getFontSettings(bparams, pos);
1437 pos_type const body_pos = beginOfBody();
1438 FontInfo & fi = font.fontInfo();
1440 fi.realize(d->layout_->labelfont);
1442 fi.realize(d->layout_->font);
1444 fi.realize(outerfont.fontInfo());
1445 fi.realize(bparams.getFont().fontInfo());
1451 Font const Paragraph::getLabelFont
1452 (BufferParams const & bparams, Font const & outerfont) const
1454 FontInfo tmpfont = d->layout_->labelfont;
1455 tmpfont.realize(outerfont.fontInfo());
1456 tmpfont.realize(bparams.getFont().fontInfo());
1457 return Font(tmpfont, getParLanguage(bparams));
1461 Font const Paragraph::getLayoutFont
1462 (BufferParams const & bparams, Font const & outerfont) const
1464 FontInfo tmpfont = d->layout_->font;
1465 tmpfont.realize(outerfont.fontInfo());
1466 tmpfont.realize(bparams.getFont().fontInfo());
1467 return Font(tmpfont, getParLanguage(bparams));
1471 /// Returns the height of the highest font in range
1472 FontSize Paragraph::highestFontInRange
1473 (pos_type startpos, pos_type endpos, FontSize def_size) const
1475 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1479 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1481 char_type c = d->text_[pos];
1482 if (!lyxrc.rtl_support)
1512 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1518 void Paragraph::setFont(pos_type pos, Font const & font)
1520 LASSERT(pos <= size(), /**/);
1522 // First, reduce font against layout/label font
1523 // Update: The setCharFont() routine in text2.cpp already
1524 // reduces font, so we don't need to do that here. (Asger)
1526 d->fontlist_.set(pos, font);
1530 void Paragraph::makeSameLayout(Paragraph const & par)
1532 d->layout_ = par.d->layout_;
1533 d->params_ = par.d->params_;
1537 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1539 if (isFreeSpacing())
1545 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1546 if (eraseChar(pos, trackChanges))
1552 return count > 0 || pos > 0;
1556 bool Paragraph::hasSameLayout(Paragraph const & par) const
1558 return par.d->layout_ == d->layout_
1559 && d->params_.sameLayout(par.d->params_);
1563 depth_type Paragraph::getDepth() const
1565 return d->params_.depth();
1569 depth_type Paragraph::getMaxDepthAfter() const
1571 if (d->layout_->isEnvironment())
1572 return d->params_.depth() + 1;
1574 return d->params_.depth();
1578 char Paragraph::getAlign() const
1580 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1581 return d->layout_->align;
1583 return d->params_.align();
1587 docstring const & Paragraph::labelString() const
1589 return d->params_.labelString();
1593 // the next two functions are for the manual labels
1594 docstring const Paragraph::getLabelWidthString() const
1596 if (d->layout_->margintype == MARGIN_MANUAL
1597 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1598 return d->params_.labelWidthString();
1600 return _("Senseless with this layout!");
1604 void Paragraph::setLabelWidthString(docstring const & s)
1606 d->params_.labelWidthString(s);
1610 docstring Paragraph::expandLabel(Layout const & layout,
1611 BufferParams const & bparams, bool process_appendix) const
1613 DocumentClass const & tclass = bparams.documentClass();
1614 string const & lang = getParLanguage(bparams)->code();
1615 bool const in_appendix = process_appendix && d->params_.appendix();
1616 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1618 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1619 && !layout.counter.empty())
1620 return tclass.counters().theCounter(layout.counter, lang);
1622 // handle 'inherited level parts' in 'fmt',
1623 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1624 size_t const i = fmt.find('@', 0);
1625 if (i != docstring::npos) {
1626 size_t const j = fmt.find('@', i + 1);
1627 if (j != docstring::npos) {
1628 docstring parent(fmt, i + 1, j - i - 1);
1629 docstring label = from_ascii("??");
1630 if (tclass.hasLayout(parent))
1631 docstring label = expandLabel(tclass[parent], bparams,
1633 fmt = docstring(fmt, 0, i) + label
1634 + docstring(fmt, j + 1, docstring::npos);
1638 return tclass.counters().counterLabel(fmt, lang);
1642 void Paragraph::applyLayout(Layout const & new_layout)
1644 d->layout_ = &new_layout;
1645 LyXAlignment const oldAlign = d->params_.align();
1647 if (!(oldAlign & d->layout_->alignpossible)) {
1648 frontend::Alert::warning(_("Alignment not permitted"),
1649 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1650 d->params_.align(LYX_ALIGN_LAYOUT);
1655 pos_type Paragraph::beginOfBody() const
1657 return d->begin_of_body_;
1661 void Paragraph::setBeginOfBody()
1663 if (d->layout_->labeltype != LABEL_MANUAL) {
1664 d->begin_of_body_ = 0;
1668 // Unroll the first two cycles of the loop
1669 // and remember the previous character to
1670 // remove unnecessary getChar() calls
1672 pos_type end = size();
1673 if (i < end && !isNewline(i)) {
1675 char_type previous_char = 0;
1678 previous_char = d->text_[i];
1679 if (!isNewline(i)) {
1681 while (i < end && previous_char != ' ') {
1686 previous_char = temp;
1692 d->begin_of_body_ = i;
1696 bool Paragraph::forcePlainLayout() const
1698 return inInset().forcePlainLayout();
1702 bool Paragraph::allowParagraphCustomization() const
1704 return inInset().allowParagraphCustomization();
1708 bool Paragraph::usePlainLayout() const
1710 return inInset().usePlainLayout();
1716 // paragraphs inside floats need different alignment tags to avoid
1719 bool noTrivlistCentering(InsetCode code)
1721 return code == FLOAT_CODE
1722 || code == WRAP_CODE
1723 || code == CELL_CODE;
1727 string correction(string const & orig)
1729 if (orig == "flushleft")
1730 return "raggedright";
1731 if (orig == "flushright")
1732 return "raggedleft";
1733 if (orig == "center")
1739 string const corrected_env(string const & suffix, string const & env,
1740 InsetCode code, bool const lastpar)
1742 string output = suffix + "{";
1743 if (noTrivlistCentering(code)) {
1745 // the last paragraph in non-trivlist-aligned
1746 // context is special (to avoid unwanted whitespace)
1747 if (suffix == "\\begin")
1748 return "\\" + correction(env) + "{}";
1751 output += correction(env);
1755 if (suffix == "\\begin")
1761 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1763 if (!contains(str, "\n"))
1764 column += str.size();
1768 column = rsplit(str, tmp, '\n').size();
1775 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1776 odocstream & os, TexRow & texrow,
1777 OutputParams const & runparams) const
1781 if (params_.noindent()) {
1782 os << "\\noindent ";
1786 LyXAlignment const curAlign = params_.align();
1788 if (curAlign == layout_->align)
1792 case LYX_ALIGN_NONE:
1793 case LYX_ALIGN_BLOCK:
1794 case LYX_ALIGN_LAYOUT:
1795 case LYX_ALIGN_SPECIAL:
1797 case LYX_ALIGN_LEFT:
1798 case LYX_ALIGN_RIGHT:
1799 case LYX_ALIGN_CENTER:
1800 if (runparams.moving_arg) {
1807 string const begin_tag = "\\begin";
1808 InsetCode code = owner_->ownerCode();
1809 bool const lastpar = runparams.isLastPar;
1812 case LYX_ALIGN_NONE:
1813 case LYX_ALIGN_BLOCK:
1814 case LYX_ALIGN_LAYOUT:
1815 case LYX_ALIGN_SPECIAL:
1817 case LYX_ALIGN_LEFT: {
1819 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1820 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1822 output = corrected_env(begin_tag, "flushright", code, lastpar);
1823 os << from_ascii(output);
1824 adjust_row_column(output, texrow, column);
1826 } case LYX_ALIGN_RIGHT: {
1828 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1829 output = corrected_env(begin_tag, "flushright", code, lastpar);
1831 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1832 os << from_ascii(output);
1833 adjust_row_column(output, texrow, column);
1835 } case LYX_ALIGN_CENTER: {
1837 output = corrected_env(begin_tag, "center", code, lastpar);
1838 os << from_ascii(output);
1839 adjust_row_column(output, texrow, column);
1848 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1849 odocstream & os, TexRow & texrow,
1850 OutputParams const & runparams) const
1854 LyXAlignment const curAlign = params_.align();
1856 if (curAlign == layout_->align)
1860 case LYX_ALIGN_NONE:
1861 case LYX_ALIGN_BLOCK:
1862 case LYX_ALIGN_LAYOUT:
1863 case LYX_ALIGN_SPECIAL:
1865 case LYX_ALIGN_LEFT:
1866 case LYX_ALIGN_RIGHT:
1867 case LYX_ALIGN_CENTER:
1868 if (runparams.moving_arg) {
1875 string const end_tag = "\n\\par\\end";
1876 InsetCode code = owner_->ownerCode();
1877 bool const lastpar = runparams.isLastPar;
1880 case LYX_ALIGN_NONE:
1881 case LYX_ALIGN_BLOCK:
1882 case LYX_ALIGN_LAYOUT:
1883 case LYX_ALIGN_SPECIAL:
1885 case LYX_ALIGN_LEFT: {
1887 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1888 output = corrected_env(end_tag, "flushleft", code, lastpar);
1890 output = corrected_env(end_tag, "flushright", code, lastpar);
1891 os << from_ascii(output);
1892 adjust_row_column(output, texrow, column);
1894 } case LYX_ALIGN_RIGHT: {
1896 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1897 output = corrected_env(end_tag, "flushright", code, lastpar);
1899 output = corrected_env(end_tag, "flushleft", code, lastpar);
1900 os << from_ascii(output);
1901 adjust_row_column(output, texrow, column);
1903 } case LYX_ALIGN_CENTER: {
1905 output = corrected_env(end_tag, "center", code, lastpar);
1906 os << from_ascii(output);
1907 adjust_row_column(output, texrow, column);
1916 // This one spits out the text of the paragraph
1917 bool Paragraph::latex(BufferParams const & bparams,
1918 Font const & outerfont,
1919 odocstream & os, TexRow & texrow,
1920 OutputParams const & runparams,
1921 int start_pos, int end_pos) const
1923 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1925 bool return_value = false;
1927 bool const allowcust = allowParagraphCustomization();
1929 // FIXME This check should not be needed. Perhaps issue an
1930 // error if it triggers.
1931 Layout const & style = forcePlainLayout() ?
1932 bparams.documentClass().plainLayout() : *d->layout_;
1934 // Current base font for all inherited font changes, without any
1935 // change caused by an individual character, except for the language:
1936 // It is set to the language of the first character.
1937 // As long as we are in the label, this font is the base font of the
1938 // label. Before the first body character it is set to the base font
1942 // Maybe we have to create a optional argument.
1943 pos_type body_pos = beginOfBody();
1944 unsigned int column = 0;
1949 basefont = getLabelFont(bparams, outerfont);
1951 basefont = getLayoutFont(bparams, outerfont);
1954 // Which font is currently active?
1955 Font running_font(basefont);
1956 // Do we have an open font change?
1957 bool open_font = false;
1959 Change runningChange = Change(Change::UNCHANGED);
1961 texrow.start(id(), 0);
1963 // if the paragraph is empty, the loop will not be entered at all
1965 if (style.isCommand()) {
1970 column += d->startTeXParParams(bparams, os, texrow,
1974 for (pos_type i = 0; i < size(); ++i) {
1975 // First char in paragraph or after label?
1976 if (i == body_pos) {
1979 column += running_font.latexWriteEndChanges(
1980 os, bparams, runparams,
1981 basefont, basefont);
1984 basefont = getLayoutFont(bparams, outerfont);
1985 running_font = basefont;
1987 column += Changes::latexMarkChange(os, bparams,
1988 runningChange, Change(Change::UNCHANGED));
1989 runningChange = Change(Change::UNCHANGED);
1994 if (style.isCommand()) {
2000 column += d->startTeXParParams(bparams, os,
2005 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2008 if (bparams.outputChanges && runningChange != change) {
2010 column += running_font.latexWriteEndChanges(
2011 os, bparams, runparams, basefont, basefont);
2014 basefont = getLayoutFont(bparams, outerfont);
2015 running_font = basefont;
2017 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2018 runningChange = change;
2021 // do not output text which is marked deleted
2022 // if change tracking output is disabled
2023 if (!bparams.outputChanges && change.type == Change::DELETED) {
2029 // Fully instantiated font
2030 Font const font = getFont(bparams, i, outerfont);
2032 Font const last_font = running_font;
2034 // Do we need to close the previous font?
2036 (font != running_font ||
2037 font.language() != running_font.language()))
2039 column += running_font.latexWriteEndChanges(
2040 os, bparams, runparams, basefont,
2041 (i == body_pos-1) ? basefont : font);
2042 running_font = basefont;
2046 // close babel's font environment before opening CJK.
2047 if (!running_font.language()->babel().empty() &&
2048 font.language()->encoding()->package() == Encoding::CJK) {
2049 string end_tag = subst(lyxrc.language_command_end,
2051 running_font.language()->babel());
2052 os << from_ascii(end_tag);
2053 column += end_tag.length();
2056 // Switch file encoding if necessary (and allowed)
2057 if (!runparams.verbatim &&
2058 runparams.encoding->package() != Encoding::none &&
2059 font.language()->encoding()->package() != Encoding::none) {
2060 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2061 runparams, *(font.language()->encoding()));
2062 if (enc_switch.first) {
2063 column += enc_switch.second;
2064 runparams.encoding = font.language()->encoding();
2068 char_type const c = d->text_[i];
2070 // Do we need to change font?
2071 if ((font != running_font ||
2072 font.language() != running_font.language()) &&
2075 odocstringstream ods;
2076 column += font.latexWriteStartChanges(ods, bparams,
2077 runparams, basefont,
2079 running_font = font;
2081 docstring fontchange = ods.str();
2082 // check if the fontchange ends with a trailing blank
2083 // (like "\small " (see bug 3382)
2084 if (suffixIs(fontchange, ' ') && c == ' ')
2085 os << fontchange.substr(0, fontchange.size() - 1)
2086 << from_ascii("{}");
2091 // FIXME: think about end_pos implementation...
2092 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2093 // FIXME: integrate this case in latexSpecialChar
2094 // Do not print the separation of the optional argument
2095 // if style.pass_thru is false. This works because
2096 // latexSpecialChar ignores spaces if
2097 // style.pass_thru is false.
2098 if (i != body_pos - 1) {
2099 if (d->simpleTeXBlanks(
2100 runparams, os, texrow,
2101 i, column, font, style)) {
2102 // A surrogate pair was output. We
2103 // must not call latexSpecialChar
2104 // in this iteration, since it would output
2105 // the combining character again.
2112 OutputParams rp = runparams;
2113 rp.free_spacing = style.free_spacing;
2114 rp.local_font = &font;
2115 rp.intitle = style.intitle;
2117 // Two major modes: LaTeX or plain
2118 // Handle here those cases common to both modes
2119 // and then split to handle the two modes separately.
2120 if (c == META_INSET) {
2121 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2122 d->latexInset(bparams, os,
2123 texrow, rp, running_font,
2124 basefont, outerfont, open_font,
2125 runningChange, style, i, column);
2128 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2130 d->latexSpecialChar(os, rp, running_font, runningChange,
2132 } catch (EncodingException & e) {
2133 if (runparams.dryrun) {
2134 os << "<" << _("LyX Warning: ")
2135 << _("uncodable character") << " '";
2139 // add location information and throw again.
2148 // Set the encoding to that returned from latexSpecialChar (see
2149 // comment for encoding member in OutputParams.h)
2150 runparams.encoding = rp.encoding;
2153 // If we have an open font definition, we have to close it
2155 #ifdef FIXED_LANGUAGE_END_DETECTION
2158 .latexWriteEndChanges(os, bparams, runparams,
2160 next_->getFont(bparams, 0, outerfont));
2162 running_font.latexWriteEndChanges(os, bparams,
2163 runparams, basefont, basefont);
2166 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2167 //FIXME: there as we start another \selectlanguage with the next paragraph if
2168 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2169 running_font.latexWriteEndChanges(os, bparams, runparams,
2170 basefont, basefont);
2174 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2176 // Needed if there is an optional argument but no contents.
2177 if (body_pos > 0 && body_pos == size()) {
2179 return_value = false;
2183 column += d->endTeXParParams(bparams, os, texrow,
2187 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2188 return return_value;
2192 bool Paragraph::emptyTag() const
2194 for (pos_type i = 0; i < size(); ++i) {
2195 if (Inset const * inset = getInset(i)) {
2196 InsetCode lyx_code = inset->lyxCode();
2197 if (lyx_code != TOC_CODE &&
2198 lyx_code != INCLUDE_CODE &&
2199 lyx_code != GRAPHICS_CODE &&
2200 lyx_code != ERT_CODE &&
2201 lyx_code != LISTINGS_CODE &&
2202 lyx_code != FLOAT_CODE &&
2203 lyx_code != TABULAR_CODE) {
2207 char_type c = d->text_[i];
2208 if (c != ' ' && c != '\t')
2216 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2219 for (pos_type i = 0; i < size(); ++i) {
2220 if (Inset const * inset = getInset(i)) {
2221 InsetCode lyx_code = inset->lyxCode();
2222 if (lyx_code == LABEL_CODE) {
2223 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2224 docstring const & id = il->getParam("name");
2225 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2233 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2237 for (i = 0; i < size(); ++i) {
2238 if (Inset const * inset = getInset(i)) {
2239 inset->docbook(os, runparams);
2241 char_type c = d->text_[i];
2244 os << sgml::escapeChar(c);
2251 pos_type Paragraph::firstWordLyXHTML(odocstream & os, OutputParams const & runparams)
2255 for (i = 0; i < size(); ++i) {
2256 if (Inset const * inset = getInset(i)) {
2257 inset->xhtml(os, runparams);
2259 char_type c = d->text_[i];
2262 os << html::escapeChar(c);
2269 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2272 pos_type size = text_.size();
2273 for (pos_type i = initial; i < size; ++i) {
2274 Font font = owner_->getFont(buf.params(), i, outerfont);
2275 if (text_[i] == META_INSET)
2277 if (i != initial && font != font_old)
2286 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2288 OutputParams const & runparams,
2289 Font const & outerfont,
2290 pos_type initial) const
2292 bool emph_flag = false;
2294 Layout const & style = *d->layout_;
2296 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2298 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2301 // parsing main loop
2302 for (pos_type i = initial; i < size(); ++i) {
2303 Font font = getFont(buf.params(), i, outerfont);
2305 // handle <emphasis> tag
2306 if (font_old.emph() != font.fontInfo().emph()) {
2307 if (font.fontInfo().emph() == FONT_ON) {
2310 } else if (i != initial) {
2311 os << "</emphasis>";
2316 if (Inset const * inset = getInset(i)) {
2317 inset->docbook(os, runparams);
2319 char_type c = d->text_[i];
2321 if (style.pass_thru)
2324 os << sgml::escapeChar(c);
2326 font_old = font.fontInfo();
2330 os << "</emphasis>";
2333 if (style.free_spacing)
2335 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2340 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2342 OutputParams const & runparams,
2343 Font const & outerfont,
2344 pos_type initial) const
2348 // FIXME We really need to manage the tag nesting here.
2349 // Probably in the same sort of way as in output_xhtml.
2350 bool emph_flag = false;
2351 bool bold_flag = false;
2352 std::string closing_tag;
2354 Layout const & style = *d->layout_;
2356 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2358 //if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2361 // parsing main loop
2362 for (pos_type i = initial; i < size(); ++i) {
2363 Font font = getFont(buf.params(), i, outerfont);
2366 if (font_old.emph() != font.fontInfo().emph()) {
2367 if (font.fontInfo().emph() == FONT_ON) {
2370 } else if (emph_flag && i != initial) {
2376 if (font_old.series() != font.fontInfo().series()) {
2377 if (font.fontInfo().series() == BOLD_SERIES) {
2380 } else if (bold_flag && i != initial) {
2385 // FIXME Other such tags?
2387 if (Inset const * inset = getInset(i)) {
2388 retval += inset->xhtml(os, runparams);
2390 char_type c = d->text_[i];
2392 if (style.pass_thru)
2394 else if (c == '-') {
2397 if (j < size() && d->text_[j] == '-') {
2399 if (j < size() && d->text_[j] == '-') {
2400 str += from_ascii("—");
2403 str += from_ascii("–");
2411 os << html::escapeChar(c);
2413 font_old = font.fontInfo();
2416 // FIXME This could be out of order. See above.
2426 bool Paragraph::isHfill(pos_type pos) const
2428 Inset const * inset = getInset(pos);
2429 return inset && (inset->lyxCode() == SPACE_CODE &&
2430 inset->isStretchableSpace());
2434 bool Paragraph::isNewline(pos_type pos) const
2436 Inset const * inset = getInset(pos);
2437 return inset && inset->lyxCode() == NEWLINE_CODE;
2441 bool Paragraph::isLineSeparator(pos_type pos) const
2443 char_type const c = d->text_[pos];
2444 if (isLineSeparatorChar(c))
2446 Inset const * inset = getInset(pos);
2447 return inset && inset->isLineSeparator();
2451 bool Paragraph::isWordSeparator(pos_type pos) const
2453 if (Inset const * inset = getInset(pos))
2454 return !inset->isLetter();
2455 char_type const c = d->text_[pos];
2456 // We want to pass the ' and escape chars to the spellchecker
2457 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2458 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2463 bool Paragraph::isChar(pos_type pos) const
2465 if (Inset const * inset = getInset(pos))
2466 return inset->isChar();
2467 char_type const c = d->text_[pos];
2468 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2472 bool Paragraph::isSpace(pos_type pos) const
2474 if (Inset const * inset = getInset(pos))
2475 return inset->isSpace();
2476 char_type const c = d->text_[pos];
2477 return lyx::isSpace(c);
2482 Paragraph::getParLanguage(BufferParams const & bparams) const
2485 return getFirstFontSettings(bparams).language();
2486 // FIXME: we should check the prev par as well (Lgb)
2487 return bparams.language;
2491 bool Paragraph::isRTL(BufferParams const & bparams) const
2493 return lyxrc.rtl_support
2494 && getParLanguage(bparams)->rightToLeft()
2495 && ownerCode() != ERT_CODE
2496 && ownerCode() != LISTINGS_CODE;
2500 void Paragraph::changeLanguage(BufferParams const & bparams,
2501 Language const * from, Language const * to)
2503 // change language including dummy font change at the end
2504 for (pos_type i = 0; i <= size(); ++i) {
2505 Font font = getFontSettings(bparams, i);
2506 if (font.language() == from) {
2507 font.setLanguage(to);
2514 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2516 Language const * doc_language = bparams.language;
2517 FontList::const_iterator cit = d->fontlist_.begin();
2518 FontList::const_iterator end = d->fontlist_.end();
2520 for (; cit != end; ++cit)
2521 if (cit->font().language() != ignore_language &&
2522 cit->font().language() != latex_language &&
2523 cit->font().language() != doc_language)
2529 docstring Paragraph::asString(int options) const
2531 return asString(0, size(), options);
2535 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2537 odocstringstream os;
2540 && options & AS_STR_LABEL
2541 && !d->params_.labelString().empty())
2542 os << d->params_.labelString() << ' ';
2544 for (pos_type i = beg; i < end; ++i) {
2545 char_type const c = d->text_[i];
2546 if (isPrintable(c) || c == '\t'
2547 || (c == '\n' && options & AS_STR_NEWLINES))
2549 else if (c == META_INSET && options & AS_STR_INSETS)
2550 getInset(i)->tocString(os);
2557 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2559 odocstringstream os;
2562 && options & AS_STR_LABEL
2563 && !d->params_.labelString().empty())
2564 os << d->params_.labelString() << ' ';
2566 for (pos_type i = beg; i < end; ++i) {
2567 char_type const c = d->text_[i];
2568 if (isPrintable(c) || c == '\t'
2569 || (c == '\n' && options & AS_STR_NEWLINES))
2571 else if (c == META_INSET && options & AS_STR_INSETS) {
2572 getInset(i)->plaintext(os, runparams);
2580 void Paragraph::setInsetOwner(Inset const * inset)
2582 d->inset_owner_ = inset;
2586 int Paragraph::id() const
2592 Layout const & Paragraph::layout() const
2598 void Paragraph::setLayout(Layout const & layout)
2600 d->layout_ = &layout;
2604 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2606 setLayout(tc.defaultLayout());
2610 void Paragraph::setPlainLayout(DocumentClass const & tc)
2612 setLayout(tc.plainLayout());
2616 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2618 if (usePlainLayout())
2619 setPlainLayout(tclass);
2621 setDefaultLayout(tclass);
2625 Inset const & Paragraph::inInset() const
2627 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2628 _("Memory problem"), _("Paragraph not properly initialized")));
2629 return *d->inset_owner_;
2633 InsetCode Paragraph::ownerCode() const
2635 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2639 ParagraphParameters & Paragraph::params()
2645 ParagraphParameters const & Paragraph::params() const
2651 bool Paragraph::isFreeSpacing() const
2653 if (d->layout_->free_spacing)
2655 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2659 bool Paragraph::allowEmpty() const
2661 if (d->layout_->keepempty)
2663 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2667 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2669 if (!Encodings::isArabicChar(c))
2672 char_type prev_char = ' ';
2673 char_type next_char = ' ';
2675 for (pos_type i = pos - 1; i >= 0; --i) {
2676 char_type const par_char = d->text_[i];
2677 if (!Encodings::isArabicComposeChar(par_char)) {
2678 prev_char = par_char;
2683 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2684 char_type const par_char = d->text_[i];
2685 if (!Encodings::isArabicComposeChar(par_char)) {
2686 next_char = par_char;
2691 if (Encodings::isArabicChar(next_char)) {
2692 if (Encodings::isArabicChar(prev_char) &&
2693 !Encodings::isArabicSpecialChar(prev_char))
2694 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2696 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2698 if (Encodings::isArabicChar(prev_char) &&
2699 !Encodings::isArabicSpecialChar(prev_char))
2700 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2702 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2707 int Paragraph::checkBiblio(Buffer const & buffer)
2710 // This is getting more and more a mess. ...We really should clean
2711 // up this bibitem issue for 1.6. See also bug 2743.
2713 // Add bibitem insets if necessary
2714 if (d->layout_->labeltype != LABEL_BIBLIO)
2717 bool hasbibitem = !d->insetlist_.empty()
2718 // Insist on it being in pos 0
2719 && d->text_[0] == META_INSET
2720 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2722 bool track_changes = buffer.params().trackChanges;
2727 // remove a bibitem in pos != 0
2728 // restore it later in pos 0 if necessary
2729 // (e.g. if a user inserts contents _before_ the item)
2730 // we're assuming there's only one of these, which there
2732 int erasedInsetPosition = -1;
2733 InsetList::iterator it = d->insetlist_.begin();
2734 InsetList::iterator end = d->insetlist_.end();
2735 for (; it != end; ++it)
2736 if (it->inset->lyxCode() == BIBITEM_CODE
2738 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2739 oldkey = olditem->getParam("key");
2740 oldlabel = olditem->getParam("label");
2741 erasedInsetPosition = it->pos;
2742 eraseChar(erasedInsetPosition, track_changes);
2746 // There was an InsetBibitem at the beginning, and we didn't
2747 // have to erase one.
2748 if (hasbibitem && erasedInsetPosition < 0)
2751 // There was an InsetBibitem at the beginning and we did have to
2752 // erase one. So we give its properties to the beginning inset.
2754 InsetBibitem * inset =
2755 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2756 if (!oldkey.empty())
2757 inset->setParam("key", oldkey);
2758 inset->setParam("label", oldlabel);
2759 return -erasedInsetPosition;
2762 // There was no inset at the beginning, so we need to create one with
2763 // the key and label of the one we erased.
2764 InsetBibitem * inset =
2765 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2766 // restore values of previously deleted item in this par.
2767 if (!oldkey.empty())
2768 inset->setParam("key", oldkey);
2769 inset->setParam("label", oldlabel);
2770 insertInset(0, static_cast<Inset *>(inset),
2771 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2777 void Paragraph::checkAuthors(AuthorList const & authorList)
2779 d->changes_.checkAuthors(authorList);
2783 bool Paragraph::isUnchanged(pos_type pos) const
2785 return lookupChange(pos).type == Change::UNCHANGED;
2789 bool Paragraph::isInserted(pos_type pos) const
2791 return lookupChange(pos).type == Change::INSERTED;
2795 bool Paragraph::isDeleted(pos_type pos) const
2797 return lookupChange(pos).type == Change::DELETED;
2801 InsetList const & Paragraph::insetList() const
2803 return d->insetlist_;
2807 void Paragraph::setBuffer(Buffer & b)
2809 d->insetlist_.setBuffer(b);
2813 Inset * Paragraph::releaseInset(pos_type pos)
2815 Inset * inset = d->insetlist_.release(pos);
2816 /// does not honour change tracking!
2817 eraseChar(pos, false);
2822 Inset * Paragraph::getInset(pos_type pos)
2824 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2825 ? d->insetlist_.get(pos) : 0;
2829 Inset const * Paragraph::getInset(pos_type pos) const
2831 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2832 ? d->insetlist_.get(pos) : 0;
2836 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2837 pos_type & right, TextCase action)
2839 // process sequences of modified characters; in change
2840 // tracking mode, this approach results in much better
2841 // usability than changing case on a char-by-char basis
2844 bool const trackChanges = bparams.trackChanges;
2846 bool capitalize = true;
2848 for (; pos < right; ++pos) {
2849 char_type oldChar = d->text_[pos];
2850 char_type newChar = oldChar;
2852 // ignore insets and don't play with deleted text!
2853 if (oldChar != META_INSET && !isDeleted(pos)) {
2855 case text_lowercase:
2856 newChar = lowercase(oldChar);
2858 case text_capitalization:
2860 newChar = uppercase(oldChar);
2864 case text_uppercase:
2865 newChar = uppercase(oldChar);
2870 if (isWordSeparator(pos) || isDeleted(pos)) {
2871 // permit capitalization again
2875 if (oldChar != newChar) {
2877 if (pos != right - 1)
2879 // step behind the changing area
2883 int erasePos = pos - changes.size();
2884 for (size_t i = 0; i < changes.size(); i++) {
2885 insertChar(pos, changes[i],
2886 getFontSettings(bparams,
2889 if (!eraseChar(erasePos, trackChanges)) {
2892 ++right; // expand selection
2900 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2901 pos_type pos, bool del) const
2903 int const strsize = str.length();
2905 pos_type const parsize = d->text_.size();
2906 for (i = 0; pos + i < parsize; ++i) {
2909 if (cs && str[i] != d->text_[pos + i])
2911 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2913 if (!del && isDeleted(pos + i))
2920 // if necessary, check whether string matches word
2922 if (pos > 0 && !isWordSeparator(pos - 1))
2924 if (pos + strsize < parsize
2925 && !isWordSeparator(pos + strsize))
2933 char_type Paragraph::getChar(pos_type pos) const
2935 return d->text_[pos];
2939 pos_type Paragraph::size() const
2941 return d->text_.size();
2945 bool Paragraph::empty() const
2947 return d->text_.empty();
2951 bool Paragraph::isInset(pos_type pos) const
2953 return d->text_[pos] == META_INSET;
2957 bool Paragraph::isSeparator(pos_type pos) const
2959 //FIXME: Are we sure this can be the only separator?
2960 return d->text_[pos] == ' ';
2964 void Paragraph::deregisterWords()
2966 Private::Words::const_iterator it;
2967 WordList & wl = theWordList();
2968 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2974 void Paragraph::locateWord(pos_type & from, pos_type & to,
2975 word_location const loc) const
2978 case WHOLE_WORD_STRICT:
2979 if (from == 0 || from == size()
2980 || isWordSeparator(from)
2981 || isWordSeparator(from - 1)) {
2985 // no break here, we go to the next
2988 // If we are already at the beginning of a word, do nothing
2989 if (!from || isWordSeparator(from - 1))
2991 // no break here, we go to the next
2994 // always move the cursor to the beginning of previous word
2995 while (from && !isWordSeparator(from - 1))
2999 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3002 // no need to move the 'from' cursor
3006 while (to < size() && !isWordSeparator(to))
3011 void Paragraph::collectWords()
3013 pos_type n = size();
3015 docstring_list suggestions;
3016 for (pos_type pos = 0; pos < n; ++pos) {
3017 if (isWordSeparator(pos))
3019 pos_type from = pos;
3020 locateWord(from, pos, WHOLE_WORD);
3021 if (pos - from >= 6) {
3022 docstring word = asString(from, pos, AS_STR_NONE);
3023 d->words_.insert(word);
3025 if (lyxrc.spellcheck_continuously
3026 && spellCheck(from, pos, wl, suggestions)) {
3027 for (size_t i = 0; i != suggestions.size(); ++i)
3028 d->words_.insert(suggestions[i]);
3034 void Paragraph::registerWords()
3036 Private::Words::const_iterator it;
3037 WordList & wl = theWordList();
3038 for (it = d->words_.begin(); it != d->words_.end(); ++it)
3043 void Paragraph::updateWords()
3051 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3052 docstring_list & suggestions) const
3054 SpellChecker * speller = theSpellChecker();
3058 locateWord(from, to, WHOLE_WORD);
3059 if (from == to || from >= pos_type(d->text_.size()))
3062 docstring word = asString(from, to, AS_STR_INSETS);
3063 string const lang_code = lyxrc.spellchecker_alt_lang.empty()
3064 ? getFontSettings(d->inset_owner_->buffer().params(), from).language()->code()
3065 : lyxrc.spellchecker_alt_lang;
3066 wl = WordLangTuple(word, lang_code);
3067 SpellChecker::Result res = speller->check(wl);
3068 // Just ignore any error that the spellchecker reports.
3069 // FIXME: we should through out an exception and catch it in the GUI to
3070 // display the error.
3071 if (!speller->error().empty())
3074 bool const misspelled = res != SpellChecker::OK
3075 && res != SpellChecker::IGNORED_WORD;
3077 if (lyxrc.spellcheck_continuously)
3078 d->fontlist_.setMisspelled(from, to, misspelled);
3081 while (!(word = speller->nextMiss()).empty())
3082 suggestions.push_back(word);
3088 bool Paragraph::isMisspelled(pos_type pos) const
3090 pos_type from = pos;
3093 docstring_list suggestions;
3094 return spellCheck(from, to, wl, suggestions);