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 "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
41 #include "TextClass.h"
47 #include "frontends/alert.h"
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
52 #include "support/lassert.h"
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/ExceptionMessage.h"
56 #include "support/gettext.h"
57 #include "support/lstrings.h"
58 #include "support/Messages.h"
59 #include "support/textutils.h"
65 using namespace lyx::support;
70 /// Inset identifier (above 0x10ffff, for ucs-4)
71 char_type const META_INSET = 0x200001;
74 /////////////////////////////////////////////////////////////////////
78 /////////////////////////////////////////////////////////////////////
80 class Paragraph::Private
84 Private(Paragraph * owner, Layout const & layout);
85 /// "Copy constructor"
86 Private(Private const &, Paragraph * owner);
87 /// Copy constructor from \p beg to \p end
88 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
91 void insertChar(pos_type pos, char_type c, Change const & change);
93 /// Output the surrogate pair formed by \p c and \p next to \p os.
94 /// \return the number of characters written.
95 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98 /// Output a space in appropriate formatting (or a surrogate pair
99 /// if the next character is a combining character).
100 /// \return whether a surrogate pair was output.
101 bool simpleTeXBlanks(OutputParams const &,
102 odocstream &, TexRow & texrow,
104 unsigned int & column,
106 Layout const & style);
108 /// Output consecutive unicode chars, belonging to the same script as
109 /// specified by the latex macro \p ltx, to \p os starting from \p i.
110 /// \return the number of characters written.
111 int writeScriptChars(odocstream & os, docstring const & ltx,
112 Change &, Encoding const &, pos_type & i);
114 /// This could go to ParagraphParameters if we want to.
115 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
116 OutputParams const &) const;
118 /// This could go to ParagraphParameters if we want to.
119 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
120 OutputParams const &) const;
123 void latexInset(BufferParams const &,
125 TexRow & texrow, OutputParams &,
128 Font const & outerfont,
130 Change & running_change,
131 Layout const & style,
133 unsigned int & column);
136 void latexSpecialChar(
138 OutputParams & runparams,
140 Change & running_change,
141 Layout const & style,
143 unsigned int & column);
150 unsigned int & column);
152 bool latexSpecialTypewriter(
156 unsigned int & column);
158 bool latexSpecialPhrase(
161 unsigned int & column,
162 OutputParams & runparams);
165 void validate(LaTeXFeatures & features,
166 Layout const & layout) const;
168 /// Checks if the paragraph contains only text and no inset or font change.
169 bool onlyText(Buffer const & buf, Font const & outerfont,
170 pos_type initial) const;
172 /// match a string against a particular point in the paragraph
173 bool isTextAt(string const & str, pos_type pos) const;
175 /// Which Paragraph owns us?
179 Inset const * inset_owner_;
187 static unsigned int paragraph_id;
189 ParagraphParameters params_;
191 /// for recording and looking up changes
195 InsetList insetlist_;
198 pos_type begin_of_body_;
200 typedef docstring TextContainer;
204 typedef std::set<docstring> Words;
208 Layout const * layout_;
212 // Initialization of the counter for the paragraph id's,
213 unsigned int Paragraph::Private::paragraph_id = 0;
217 struct special_phrase {
223 special_phrase const special_phrases[] = {
224 { "LyX", from_ascii("\\LyX{}"), false },
225 { "TeX", from_ascii("\\TeX{}"), true },
226 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
227 { "LaTeX", from_ascii("\\LaTeX{}"), true },
230 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
235 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
236 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
238 id_ = paragraph_id++;
243 Paragraph::Private::Private(Private const & p, Paragraph * owner)
244 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
245 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
246 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
249 id_ = paragraph_id++;
253 Paragraph::Private::Private(Private const & p, Paragraph * owner,
254 pos_type beg, pos_type end)
255 : owner_(owner), inset_owner_(p.inset_owner_),
256 params_(p.params_), changes_(p.changes_),
257 insetlist_(p.insetlist_, beg, end),
258 begin_of_body_(p.begin_of_body_), words_(p.words_),
261 id_ = paragraph_id++;
262 if (beg >= pos_type(p.text_.size()))
264 text_ = p.text_.substr(beg, end - beg);
266 FontList::const_iterator fcit = fontlist_.begin();
267 FontList::const_iterator fend = fontlist_.end();
268 for (; fcit != fend; ++fcit) {
269 if (fcit->pos() < beg)
271 if (fcit->pos() >= end) {
272 // Add last entry in the fontlist_.
273 fontlist_.set(text_.size() - 1, fcit->font());
276 // Add a new entry in the fontlist_.
277 fontlist_.set(fcit->pos() - beg, fcit->font());
282 void Paragraph::addChangesToToc(DocIterator const & cdit,
283 Buffer const & buf) const
285 d->changes_.addToToc(cdit, buf);
289 bool Paragraph::isChanged(pos_type start, pos_type end) const
291 LASSERT(start >= 0 && start <= size(), /**/);
292 LASSERT(end > start && end <= size() + 1, /**/);
294 return d->changes_.isChanged(start, end);
298 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
300 // keep the logic here in sync with the logic of eraseChars()
304 Change const change = d->changes_.lookup(size());
305 return change.type == Change::INSERTED && change.author == 0;
309 void Paragraph::setChange(Change const & change)
311 // beware of the imaginary end-of-par character!
312 d->changes_.set(change, 0, size() + 1);
315 * Propagate the change recursively - but not in case of DELETED!
317 * Imagine that your co-author makes changes in an existing inset. He
318 * sends your document to you and you come to the conclusion that the
319 * inset should go completely. If you erase it, LyX must not delete all
320 * text within the inset. Otherwise, the change tracked insertions of
321 * your co-author get lost and there is no way to restore them later.
323 * Conclusion: An inset's content should remain untouched if you delete it
326 if (change.type != Change::DELETED) {
327 for (pos_type pos = 0; pos < size(); ++pos) {
328 if (Inset * inset = getInset(pos))
329 inset->setChange(change);
335 void Paragraph::setChange(pos_type pos, Change const & change)
337 LASSERT(pos >= 0 && pos <= size(), /**/);
338 d->changes_.set(change, pos);
340 // see comment in setChange(Change const &) above
341 if (change.type != Change::DELETED && pos < size())
342 if (Inset * inset = getInset(pos))
343 inset->setChange(change);
347 Change const & Paragraph::lookupChange(pos_type pos) const
349 LASSERT(pos >= 0 && pos <= size(), /**/);
350 return d->changes_.lookup(pos);
354 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
357 LASSERT(start >= 0 && start <= size(), /**/);
358 LASSERT(end > start && end <= size() + 1, /**/);
360 for (pos_type pos = start; pos < end; ++pos) {
361 switch (lookupChange(pos).type) {
362 case Change::UNCHANGED:
363 // accept changes in nested inset
364 if (Inset * inset = getInset(pos))
365 inset->acceptChanges(bparams);
368 case Change::INSERTED:
369 d->changes_.set(Change(Change::UNCHANGED), pos);
370 // also accept changes in nested inset
371 if (Inset * inset = getInset(pos))
372 inset->acceptChanges(bparams);
375 case Change::DELETED:
376 // Suppress access to non-existent
377 // "end-of-paragraph char"
379 eraseChar(pos, false);
390 void Paragraph::rejectChanges(BufferParams const & bparams,
391 pos_type start, pos_type end)
393 LASSERT(start >= 0 && start <= size(), /**/);
394 LASSERT(end > start && end <= size() + 1, /**/);
396 for (pos_type pos = start; pos < end; ++pos) {
397 switch (lookupChange(pos).type) {
398 case Change::UNCHANGED:
399 // reject changes in nested inset
400 if (Inset * inset = getInset(pos))
401 inset->rejectChanges(bparams);
404 case Change::INSERTED:
405 // Suppress access to non-existent
406 // "end-of-paragraph char"
408 eraseChar(pos, false);
414 case Change::DELETED:
415 d->changes_.set(Change(Change::UNCHANGED), pos);
417 // Do NOT reject changes within a deleted inset!
418 // There may be insertions of a co-author inside of it!
426 void Paragraph::Private::insertChar(pos_type pos, char_type c,
427 Change const & change)
429 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
432 changes_.insert(change, pos);
434 // This is actually very common when parsing buffers (and
435 // maybe inserting ascii text)
436 if (pos == pos_type(text_.size())) {
437 // when appending characters, no need to update tables
442 text_.insert(text_.begin() + pos, c);
444 // Update the font table.
445 fontlist_.increasePosAfterPos(pos);
448 insetlist_.increasePosAfterPos(pos);
452 void Paragraph::insertInset(pos_type pos, Inset * inset,
453 Change const & change)
455 LASSERT(inset, /**/);
456 LASSERT(pos >= 0 && pos <= size(), /**/);
458 d->insertChar(pos, META_INSET, change);
459 LASSERT(d->text_[pos] == META_INSET, /**/);
461 // Add a new entry in the insetlist_.
462 d->insetlist_.insert(inset, pos);
466 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
468 LASSERT(pos >= 0 && pos <= size(), return false);
470 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
473 Change change = d->changes_.lookup(pos);
475 // set the character to DELETED if
476 // a) it was previously unchanged or
477 // b) it was inserted by a co-author
479 if (change.type == Change::UNCHANGED ||
480 (change.type == Change::INSERTED && change.author != 0)) {
481 setChange(pos, Change(Change::DELETED));
485 if (change.type == Change::DELETED)
489 // Don't physically access the imaginary end-of-paragraph character.
490 // eraseChar() can only mark it as DELETED. A physical deletion of
491 // end-of-par must be handled externally.
497 d->changes_.erase(pos);
499 // if it is an inset, delete the inset entry
500 if (d->text_[pos] == META_INSET)
501 d->insetlist_.erase(pos);
503 d->text_.erase(d->text_.begin() + pos);
505 // Update the fontlist_
506 d->fontlist_.erase(pos);
508 // Update the insetlist_
509 d->insetlist_.decreasePosAfterPos(pos);
515 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
517 LASSERT(start >= 0 && start <= size(), /**/);
518 LASSERT(end >= start && end <= size() + 1, /**/);
521 for (pos_type count = end - start; count; --count) {
522 if (!eraseChar(i, trackChanges))
529 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
530 char_type next, Encoding const & encoding)
532 // Writing next here may circumvent a possible font change between
533 // c and next. Since next is only output if it forms a surrogate pair
534 // with c we can ignore this:
535 // A font change inside a surrogate pair does not make sense and is
536 // hopefully impossible to input.
537 // FIXME: change tracking
538 // Is this correct WRT change tracking?
539 docstring const latex1 = encoding.latexChar(next);
540 docstring const latex2 = encoding.latexChar(c);
541 if (docstring(1, next) == latex1) {
542 // the encoding supports the combination
543 os << latex2 << latex1;
544 return latex1.length() + latex2.length();
546 os << latex1 << '{' << latex2 << '}';
547 return latex1.length() + latex2.length() + 2;
551 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
552 odocstream & os, TexRow & texrow,
554 unsigned int & column,
556 Layout const & style)
558 if (style.pass_thru || runparams.verbatim)
561 if (i + 1 < int(text_.size())) {
562 char_type next = text_[i + 1];
563 if (Encodings::isCombiningChar(next)) {
564 Encoding const & encoding = *(runparams.encoding);
565 // This space has an accent, so we must always output it.
566 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
571 if (lyxrc.plaintext_linelen > 0
572 && column > lyxrc.plaintext_linelen
574 && text_[i - 1] != ' '
575 && (i + 1 < int(text_.size()))
576 // same in FreeSpacing mode
577 && !owner_->isFreeSpacing()
578 // In typewriter mode, we want to avoid
579 // ! . ? : at the end of a line
580 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
581 && (text_[i - 1] == '.'
582 || text_[i - 1] == '?'
583 || text_[i - 1] == ':'
584 || text_[i - 1] == '!'))) {
587 texrow.start(owner_->id(), i + 1);
589 } else if (style.free_spacing) {
598 int Paragraph::Private::writeScriptChars(odocstream & os,
599 docstring const & ltx,
600 Change & runningChange,
601 Encoding const & encoding,
604 // FIXME: modifying i here is not very nice...
606 // We only arrive here when a proper language for character text_[i] has
607 // not been specified (i.e., it could not be translated in the current
608 // latex encoding) or its latex translation has been forced, and it
609 // belongs to a known script.
610 // Parameter ltx contains the latex translation of text_[i] as specified
611 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
612 // The latex macro name "textXXX" specifies the script to which text_[i]
613 // belongs and we use it in order to check whether characters from the
614 // same script immediately follow, such that we can collect them in a
615 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
616 // for the first char but only "<spec>" for all subsequent chars.
617 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
618 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
619 string script = to_ascii(ltx.substr(1, brace1 - 1));
622 bool closing_brace = true;
623 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
624 // Correct encoding is being used, so we can avoid \textgreek.
627 closing_brace = false;
629 os << ltx.substr(pos, length);
630 int size = text_.size();
631 while (i + 1 < size) {
632 char_type const next = text_[i + 1];
633 // Stop here if next character belongs to another script
634 // or there is a change in change tracking status.
635 if (!Encodings::isKnownScriptChar(next, script) ||
636 runningChange != owner_->lookupChange(i + 1))
640 FontList::const_iterator cit = fontlist_.begin();
641 FontList::const_iterator end = fontlist_.end();
642 for (; cit != end; ++cit) {
643 if (cit->pos() >= i && !found) {
644 prev_font = cit->font();
647 if (cit->pos() >= i + 1)
650 // Stop here if there is a font attribute or encoding change.
651 if (found && cit != end && prev_font != cit->font())
653 docstring const latex = encoding.latexChar(next);
654 docstring::size_type const b1 =
655 latex.find_first_of(from_ascii("{"));
656 docstring::size_type const b2 =
657 latex.find_last_of(from_ascii("}"));
658 int const len = b2 - b1 - 1;
659 os << latex.substr(b1 + 1, len);
671 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
673 pos_type const len = str.length();
675 // is the paragraph large enough?
676 if (pos + len > int(text_.size()))
679 // does the wanted text start at point?
680 for (string::size_type i = 0; i < str.length(); ++i) {
681 // Caution: direct comparison of characters works only
682 // because str is pure ASCII.
683 if (str[i] != text_[pos + i])
687 return fontlist_.hasChangeInRange(pos, len);
691 void Paragraph::Private::latexInset(
692 BufferParams const & bparams,
695 OutputParams & runparams,
698 Font const & outerfont,
700 Change & running_change,
701 Layout const & style,
703 unsigned int & column)
705 Inset * inset = owner_->getInset(i);
706 LASSERT(inset, /**/);
708 if (style.pass_thru) {
709 inset->plaintext(os, runparams);
713 // FIXME: move this to InsetNewline::latex
714 if (inset->lyxCode() == NEWLINE_CODE) {
715 // newlines are handled differently here than
716 // the default in simpleTeXSpecialChars().
717 if (!style.newline_allowed) {
721 column += running_font.latexWriteEndChanges(
722 os, bparams, runparams,
727 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
730 basefont = owner_->getLayoutFont(bparams, outerfont);
731 running_font = basefont;
733 if (runparams.moving_arg)
738 texrow.start(owner_->id(), i + 1);
742 if (owner_->lookupChange(i).type == Change::DELETED) {
743 if( ++runparams.inDeletedInset == 1)
744 runparams.changeOfDeletedInset = owner_->lookupChange(i);
747 if (inset->canTrackChanges()) {
748 column += Changes::latexMarkChange(os, bparams, running_change,
749 Change(Change::UNCHANGED));
750 running_change = Change(Change::UNCHANGED);
754 odocstream::pos_type const len = os.tellp();
756 if (inset->forceLTR()
757 && running_font.isRightToLeft()
758 // ERT is an exception, it should be output with no decorations at all
759 && inset->lyxCode() != ERT_CODE) {
760 if (running_font.language()->lang() == "farsi")
767 // FIXME: Bug: we can have an empty font change here!
768 // if there has just been a font change, we are going to close it
769 // right now, which means stupid latex code like \textsf{}. AFAIK,
770 // this does not harm dvi output. A minor bug, thus (JMarc)
772 // Some insets cannot be inside a font change command.
773 // However, even such insets *can* be placed in \L or \R
774 // or their equivalents (for RTL language switches), so we don't
775 // close the language in those cases.
776 // ArabTeX, though, cannot handle this special behavior, it seems.
777 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
778 || running_font.language()->lang() == "arabic_arabtex";
779 if (open_font && inset->noFontChange()) {
780 bool closeLanguage = arabtex
781 || basefont.isRightToLeft() == running_font.isRightToLeft();
782 unsigned int count = running_font.latexWriteEndChanges(os,
783 bparams, runparams, basefont, basefont, closeLanguage);
785 // if any font properties were closed, update the running_font,
786 // making sure, however, to leave the language as it was
788 // FIXME: probably a better way to keep track of the old
789 // language, than copying the entire font?
790 Font const copy_font(running_font);
791 basefont = owner_->getLayoutFont(bparams, outerfont);
792 running_font = basefont;
794 running_font.setLanguage(copy_font.language());
795 // leave font open if language is still open
796 open_font = (running_font.language() == basefont.language());
798 runparams.local_font = &basefont;
805 tmp = inset->latex(os, runparams);
806 } catch (EncodingException & e) {
807 // add location information and throw again.
814 if (running_font.language()->lang() == "farsi")
821 for (int j = 0; j < tmp; ++j)
824 texrow.start(owner_->id(), i + 1);
827 column += os.tellp() - len;
830 if (owner_->lookupChange(i).type == Change::DELETED)
831 --runparams.inDeletedInset;
835 void Paragraph::Private::latexSpecialChar(
837 OutputParams & runparams,
839 Change & running_change,
840 Layout const & style,
842 unsigned int & column)
844 char_type const c = text_[i];
846 if (style.pass_thru) {
848 // FIXME UNICODE: This can fail if c cannot
849 // be encoded in the current encoding.
854 if (runparams.verbatim) {
855 // FIXME UNICODE: This can fail if c cannot
856 // be encoded in the current encoding.
861 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
864 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
865 && latexSpecialTypewriter(c, os, i, column))
868 // Otherwise, we use what LaTeX provides us.
871 os << "\\textbackslash{}";
875 os << "\\textless{}";
879 os << "\\textgreater{}";
890 os << "\\char`\\\"{}";
895 case '%': case '#': case '{':
903 os << "\\textasciitilde{}";
908 os << "\\textasciicircum{}";
913 // avoid being mistaken for optional arguments
921 // Blanks are printed before font switching.
922 // Sure? I am not! (try nice-latex)
923 // I am sure it's correct. LyX might be smarter
924 // in the future, but for now, nothing wrong is
930 if (latexSpecialPhrase(os, i, column, runparams))
936 Encoding const & encoding = *(runparams.encoding);
937 if (i + 1 < int(text_.size())) {
938 char_type next = text_[i + 1];
939 if (Encodings::isCombiningChar(next)) {
940 column += latexSurrogatePair(os, c, next, encoding) - 1;
946 docstring const latex = encoding.latexChar(c);
947 if (Encodings::isKnownScriptChar(c, script)
948 && prefixIs(latex, from_ascii("\\" + script)))
949 column += writeScriptChars(os, latex,
950 running_change, encoding, i) - 1;
951 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
952 // Prevent eating of a following
953 // space or command corruption by
954 // following characters
955 column += latex.length() + 1;
958 column += latex.length() - 1;
966 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
967 pos_type & i, unsigned int & column)
973 // In T1 encoding, these characters exist
974 // but we should avoid ligatures
975 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
977 os << "\\textcompwordmark{}";
984 // soul.sty breaks with \char`\"
985 os << "\\textquotedbl{}";
994 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
995 pos_type & i, unsigned int & column)
999 // within \ttfamily, "--" is merged to "-" (no endash)
1000 // so we avoid this rather irritating ligature
1001 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1008 // everything else has to be checked separately
1009 // (depending on the encoding)
1016 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1017 unsigned int & column, OutputParams & runparams)
1019 // FIXME: if we have "LaTeX" with a font
1020 // change in the middle (before the 'T', then
1021 // the "TeX" part is still special cased.
1022 // Really we should only operate this on
1023 // "words" for some definition of word
1025 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1026 if (!isTextAt(special_phrases[pnr].phrase, i))
1028 if (runparams.moving_arg)
1030 os << special_phrases[pnr].macro;
1031 i += special_phrases[pnr].phrase.length() - 1;
1032 column += special_phrases[pnr].macro.length() - 1;
1039 void Paragraph::Private::validate(LaTeXFeatures & features,
1040 Layout const & layout) const
1042 // check the params.
1043 if (!params_.spacing().isDefault())
1044 features.require("setspace");
1047 features.useLayout(layout.name());
1050 fontlist_.validate(features);
1052 // then the indentation
1053 if (!params_.leftIndent().zero())
1054 features.require("ParagraphLeftIndent");
1057 InsetList::const_iterator icit = insetlist_.begin();
1058 InsetList::const_iterator iend = insetlist_.end();
1059 for (; icit != iend; ++icit) {
1061 icit->inset->validate(features);
1062 if (layout.needprotect &&
1063 icit->inset->lyxCode() == FOOT_CODE)
1064 features.require("NeedLyXFootnoteCode");
1068 // then the contents
1069 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1070 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1071 if (!special_phrases[pnr].builtin
1072 && isTextAt(special_phrases[pnr].phrase, i)) {
1073 features.require(special_phrases[pnr].phrase);
1077 Encodings::validate(text_[i], features);
1081 /////////////////////////////////////////////////////////////////////
1085 /////////////////////////////////////////////////////////////////////
1088 Layout const emptyParagraphLayout;
1091 Paragraph::Paragraph()
1092 : d(new Paragraph::Private(this, emptyParagraphLayout))
1099 Paragraph::Paragraph(Paragraph const & par)
1100 : itemdepth(par.itemdepth),
1101 d(new Paragraph::Private(*par.d, this))
1107 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1108 : itemdepth(par.itemdepth),
1109 d(new Paragraph::Private(*par.d, this, beg, end))
1115 Paragraph & Paragraph::operator=(Paragraph const & par)
1117 // needed as we will destroy the private part before copying it
1119 itemdepth = par.itemdepth;
1123 d = new Private(*par.d, this);
1130 Paragraph::~Paragraph()
1137 void Paragraph::write(ostream & os, BufferParams const & bparams,
1138 depth_type & dth) const
1140 // The beginning or end of a deeper (i.e. nested) area?
1141 if (dth != d->params_.depth()) {
1142 if (d->params_.depth() > dth) {
1143 while (d->params_.depth() > dth) {
1144 os << "\n\\begin_deeper";
1148 while (d->params_.depth() < dth) {
1149 os << "\n\\end_deeper";
1155 // First write the layout
1156 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1158 d->params_.write(os);
1160 Font font1(inherit_font, bparams.language);
1162 Change running_change = Change(Change::UNCHANGED);
1165 for (pos_type i = 0; i <= size(); ++i) {
1167 Change change = lookupChange(i);
1168 Changes::lyxMarkChange(os, column, running_change, change);
1169 running_change = change;
1174 // Write font changes
1175 Font font2 = getFontSettings(bparams, i);
1176 if (font2 != font1) {
1177 font2.lyxWriteChanges(font1, os);
1182 char_type const c = d->text_[i];
1185 if (Inset const * inset = getInset(i)) {
1186 if (inset->directWrite()) {
1187 // international char, let it write
1188 // code directly so it's shorter in
1194 os << "\\begin_inset ";
1196 os << "\n\\end_inset\n\n";
1202 os << "\n\\backslash\n";
1206 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1213 if ((column > 70 && c == ' ')
1218 // this check is to amend a bug. LyX sometimes
1219 // inserts '\0' this could cause problems.
1221 os << to_utf8(docstring(1, c));
1223 LYXERR0("NUL char in structure.");
1229 os << "\n\\end_layout\n";
1233 void Paragraph::validate(LaTeXFeatures & features) const
1235 d->validate(features, *d->layout_);
1239 void Paragraph::insert(pos_type start, docstring const & str,
1240 Font const & font, Change const & change)
1242 for (size_t i = 0, n = str.size(); i != n ; ++i)
1243 insertChar(start + i, str[i], font, change);
1247 void Paragraph::appendChar(char_type c, Font const & font,
1248 Change const & change)
1251 d->changes_.insert(change, d->text_.size());
1252 // when appending characters, no need to update tables
1253 d->text_.push_back(c);
1254 setFont(d->text_.size() - 1, font);
1258 void Paragraph::appendString(docstring const & s, Font const & font,
1259 Change const & change)
1261 pos_type end = s.size();
1262 size_t oldsize = d->text_.size();
1263 size_t newsize = oldsize + end;
1264 size_t capacity = d->text_.capacity();
1265 if (newsize >= capacity)
1266 d->text_.reserve(max(capacity + 100, newsize));
1268 // when appending characters, no need to update tables
1271 // FIXME: Optimize this!
1272 for (pos_type i = oldsize; i != newsize; ++i) {
1274 d->changes_.insert(change, i);
1276 d->fontlist_.set(oldsize, font);
1277 d->fontlist_.set(newsize - 1, font);
1281 void Paragraph::insertChar(pos_type pos, char_type c,
1284 d->insertChar(pos, c, Change(trackChanges ?
1285 Change::INSERTED : Change::UNCHANGED));
1289 void Paragraph::insertChar(pos_type pos, char_type c,
1290 Font const & font, bool trackChanges)
1292 d->insertChar(pos, c, Change(trackChanges ?
1293 Change::INSERTED : Change::UNCHANGED));
1298 void Paragraph::insertChar(pos_type pos, char_type c,
1299 Font const & font, Change const & change)
1301 d->insertChar(pos, c, change);
1306 void Paragraph::insertInset(pos_type pos, Inset * inset,
1307 Font const & font, Change const & change)
1309 insertInset(pos, inset, change);
1310 // Set the font/language of the inset...
1315 void Paragraph::resetFonts(Font const & font)
1317 d->fontlist_.clear();
1318 d->fontlist_.set(0, font);
1319 d->fontlist_.set(d->text_.size() - 1, font);
1322 // Gets uninstantiated font setting at position.
1323 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1327 LYXERR0("pos: " << pos << " size: " << size());
1328 LASSERT(pos <= size(), /**/);
1331 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1332 if (cit != d->fontlist_.end())
1335 if (pos == size() && !empty())
1336 return getFontSettings(bparams, pos - 1);
1338 return Font(inherit_font, getParLanguage(bparams));
1342 FontSpan Paragraph::fontSpan(pos_type pos) const
1344 LASSERT(pos <= size(), /**/);
1347 FontList::const_iterator cit = d->fontlist_.begin();
1348 FontList::const_iterator end = d->fontlist_.end();
1349 for (; cit != end; ++cit) {
1350 if (cit->pos() >= pos) {
1351 if (pos >= beginOfBody())
1352 return FontSpan(max(start, beginOfBody()),
1355 return FontSpan(start,
1356 min(beginOfBody() - 1,
1359 start = cit->pos() + 1;
1362 // This should not happen, but if so, we take no chances.
1363 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1364 return FontSpan(pos, pos);
1368 // Gets uninstantiated font setting at position 0
1369 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1371 if (!empty() && !d->fontlist_.empty())
1372 return d->fontlist_.begin()->font();
1374 return Font(inherit_font, bparams.language);
1378 // Gets the fully instantiated font at a given position in a paragraph
1379 // This is basically the same function as Text::GetFont() in text2.cpp.
1380 // The difference is that this one is used for generating the LaTeX file,
1381 // and thus cosmetic "improvements" are disallowed: This has to deliver
1382 // the true picture of the buffer. (Asger)
1383 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1384 Font const & outerfont) const
1386 LASSERT(pos >= 0, /**/);
1388 Font font = getFontSettings(bparams, pos);
1390 pos_type const body_pos = beginOfBody();
1392 font.fontInfo().realize(d->layout_->labelfont);
1394 font.fontInfo().realize(d->layout_->font);
1396 font.fontInfo().realize(outerfont.fontInfo());
1397 font.fontInfo().realize(bparams.getFont().fontInfo());
1403 Font const Paragraph::getLabelFont
1404 (BufferParams const & bparams, Font const & outerfont) const
1406 FontInfo tmpfont = d->layout_->labelfont;
1407 tmpfont.realize(outerfont.fontInfo());
1408 tmpfont.realize(bparams.getFont().fontInfo());
1409 return Font(tmpfont, getParLanguage(bparams));
1413 Font const Paragraph::getLayoutFont
1414 (BufferParams const & bparams, Font const & outerfont) const
1416 FontInfo tmpfont = d->layout_->font;
1417 tmpfont.realize(outerfont.fontInfo());
1418 tmpfont.realize(bparams.getFont().fontInfo());
1419 return Font(tmpfont, getParLanguage(bparams));
1423 /// Returns the height of the highest font in range
1424 FontSize Paragraph::highestFontInRange
1425 (pos_type startpos, pos_type endpos, FontSize def_size) const
1427 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1431 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1433 char_type c = d->text_[pos];
1434 if (!lyxrc.rtl_support)
1464 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1470 void Paragraph::setFont(pos_type pos, Font const & font)
1472 LASSERT(pos <= size(), /**/);
1474 // First, reduce font against layout/label font
1475 // Update: The setCharFont() routine in text2.cpp already
1476 // reduces font, so we don't need to do that here. (Asger)
1478 d->fontlist_.set(pos, font);
1482 void Paragraph::makeSameLayout(Paragraph const & par)
1484 d->layout_ = par.d->layout_;
1485 d->params_ = par.d->params_;
1489 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1491 if (isFreeSpacing())
1497 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1498 if (eraseChar(pos, trackChanges))
1504 return count > 0 || pos > 0;
1508 bool Paragraph::hasSameLayout(Paragraph const & par) const
1510 return par.d->layout_ == d->layout_
1511 && d->params_.sameLayout(par.d->params_);
1515 depth_type Paragraph::getDepth() const
1517 return d->params_.depth();
1521 depth_type Paragraph::getMaxDepthAfter() const
1523 if (d->layout_->isEnvironment())
1524 return d->params_.depth() + 1;
1526 return d->params_.depth();
1530 char Paragraph::getAlign() const
1532 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1533 return d->layout_->align;
1535 return d->params_.align();
1539 docstring const & Paragraph::labelString() const
1541 return d->params_.labelString();
1545 // the next two functions are for the manual labels
1546 docstring const Paragraph::getLabelWidthString() const
1548 if (d->layout_->margintype == MARGIN_MANUAL)
1549 return d->params_.labelWidthString();
1551 return _("Senseless with this layout!");
1555 void Paragraph::setLabelWidthString(docstring const & s)
1557 d->params_.labelWidthString(s);
1561 docstring const Paragraph::translateIfPossible(docstring const & s,
1562 BufferParams const & bparams) const
1564 if (!isAscii(s) || s.empty()) {
1565 // This must be a user defined layout. We cannot translate
1566 // this, since gettext accepts only ascii keys.
1569 // Probably standard layout, try to translate
1570 Messages & m = getMessages(getParLanguage(bparams)->code());
1571 return m.get(to_ascii(s));
1575 docstring Paragraph::expandLabel(Layout const & layout,
1576 BufferParams const & bparams, bool process_appendix) const
1578 DocumentClass const & tclass = bparams.documentClass();
1581 if (process_appendix && d->params_.appendix())
1582 fmt = translateIfPossible(layout.labelstring_appendix(),
1585 fmt = translateIfPossible(layout.labelstring(), bparams);
1587 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1588 && !layout.counter.empty())
1589 fmt = "\\the" + layout.counter;
1591 // handle 'inherited level parts' in 'fmt',
1592 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1593 size_t const i = fmt.find('@', 0);
1594 if (i != docstring::npos) {
1595 size_t const j = fmt.find('@', i + 1);
1596 if (j != docstring::npos) {
1597 docstring parent(fmt, i + 1, j - i - 1);
1598 docstring label = from_ascii("??");
1599 if (tclass.hasLayout(parent))
1600 docstring label = expandLabel(tclass[parent], bparams,
1602 fmt = docstring(fmt, 0, i) + label
1603 + docstring(fmt, j + 1, docstring::npos);
1607 return tclass.counters().counterLabel(fmt);
1611 void Paragraph::applyLayout(Layout const & new_layout)
1613 d->layout_ = &new_layout;
1614 LyXAlignment const oldAlign = d->params_.align();
1616 if (!(oldAlign & d->layout_->alignpossible)) {
1617 frontend::Alert::warning(_("Alignment not permitted"),
1618 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1619 d->params_.align(LYX_ALIGN_LAYOUT);
1624 pos_type Paragraph::beginOfBody() const
1626 return d->begin_of_body_;
1630 void Paragraph::setBeginOfBody()
1632 if (d->layout_->labeltype != LABEL_MANUAL) {
1633 d->begin_of_body_ = 0;
1637 // Unroll the first two cycles of the loop
1638 // and remember the previous character to
1639 // remove unnecessary getChar() calls
1641 pos_type end = size();
1642 if (i < end && !isNewline(i)) {
1644 char_type previous_char = 0;
1647 previous_char = d->text_[i];
1648 if (!isNewline(i)) {
1650 while (i < end && previous_char != ' ') {
1655 previous_char = temp;
1661 d->begin_of_body_ = i;
1665 bool Paragraph::forcePlainLayout() const
1667 return inInset().forcePlainLayout();
1671 bool Paragraph::allowParagraphCustomization() const
1673 return inInset().allowParagraphCustomization();
1677 bool Paragraph::usePlainLayout() const
1679 return inInset().usePlainLayout();
1685 // paragraphs inside floats need different alignment tags to avoid
1688 bool noTrivlistCentering(InsetCode code)
1690 return code == FLOAT_CODE
1691 || code == WRAP_CODE
1692 || code == CELL_CODE;
1696 string correction(string const & orig)
1698 if (orig == "flushleft")
1699 return "raggedright";
1700 if (orig == "flushright")
1701 return "raggedleft";
1702 if (orig == "center")
1708 string const corrected_env(string const & suffix, string const & env,
1709 InsetCode code, bool const lastpar)
1711 string output = suffix + "{";
1712 if (noTrivlistCentering(code)) {
1714 // the last paragraph in non-trivlist-aligned
1715 // context is special (to avoid unwanted whitespace)
1716 if (suffix == "\\begin")
1717 return "\\" + correction(env) + "{}";
1720 output += correction(env);
1724 if (suffix == "\\begin")
1730 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1732 if (!contains(str, "\n"))
1733 column += str.size();
1737 column = rsplit(str, tmp, '\n').size();
1744 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1745 odocstream & os, TexRow & texrow,
1746 OutputParams const & runparams) const
1750 if (params_.noindent()) {
1751 os << "\\noindent ";
1755 LyXAlignment const curAlign = params_.align();
1757 if (curAlign == layout_->align)
1761 case LYX_ALIGN_NONE:
1762 case LYX_ALIGN_BLOCK:
1763 case LYX_ALIGN_LAYOUT:
1764 case LYX_ALIGN_SPECIAL:
1766 case LYX_ALIGN_LEFT:
1767 case LYX_ALIGN_RIGHT:
1768 case LYX_ALIGN_CENTER:
1769 if (runparams.moving_arg) {
1776 string const begin_tag = "\\begin";
1777 InsetCode code = owner_->ownerCode();
1778 bool const lastpar = runparams.isLastPar;
1781 case LYX_ALIGN_NONE:
1782 case LYX_ALIGN_BLOCK:
1783 case LYX_ALIGN_LAYOUT:
1784 case LYX_ALIGN_SPECIAL:
1786 case LYX_ALIGN_LEFT: {
1788 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1789 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1791 output = corrected_env(begin_tag, "flushright", code, lastpar);
1792 os << from_ascii(output);
1793 adjust_row_column(output, texrow, column);
1795 } case LYX_ALIGN_RIGHT: {
1797 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1798 output = corrected_env(begin_tag, "flushright", code, lastpar);
1800 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1801 os << from_ascii(output);
1802 adjust_row_column(output, texrow, column);
1804 } case LYX_ALIGN_CENTER: {
1806 output = corrected_env(begin_tag, "center", code, lastpar);
1807 os << from_ascii(output);
1808 adjust_row_column(output, texrow, column);
1817 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1818 odocstream & os, TexRow & texrow,
1819 OutputParams const & runparams) const
1823 switch (params_.align()) {
1824 case LYX_ALIGN_NONE:
1825 case LYX_ALIGN_BLOCK:
1826 case LYX_ALIGN_LAYOUT:
1827 case LYX_ALIGN_SPECIAL:
1829 case LYX_ALIGN_LEFT:
1830 case LYX_ALIGN_RIGHT:
1831 case LYX_ALIGN_CENTER:
1832 if (runparams.moving_arg) {
1839 string const end_tag = "\n\\par\\end";
1840 InsetCode code = owner_->ownerCode();
1841 bool const lastpar = runparams.isLastPar;
1843 switch (params_.align()) {
1844 case LYX_ALIGN_NONE:
1845 case LYX_ALIGN_BLOCK:
1846 case LYX_ALIGN_LAYOUT:
1847 case LYX_ALIGN_SPECIAL:
1849 case LYX_ALIGN_LEFT: {
1851 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1852 output = corrected_env(end_tag, "flushleft", code, lastpar);
1854 output = corrected_env(end_tag, "flushright", code, lastpar);
1855 os << from_ascii(output);
1856 adjust_row_column(output, texrow, column);
1858 } case LYX_ALIGN_RIGHT: {
1860 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1861 output = corrected_env(end_tag, "flushright", code, lastpar);
1863 output = corrected_env(end_tag, "flushleft", code, lastpar);
1864 os << from_ascii(output);
1865 adjust_row_column(output, texrow, column);
1867 } case LYX_ALIGN_CENTER: {
1869 output = corrected_env(end_tag, "center", code, lastpar);
1870 os << from_ascii(output);
1871 adjust_row_column(output, texrow, column);
1880 // This one spits out the text of the paragraph
1881 bool Paragraph::latex(BufferParams const & bparams,
1882 Font const & outerfont,
1883 odocstream & os, TexRow & texrow,
1884 OutputParams const & runparams) const
1886 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1888 bool return_value = false;
1890 bool asdefault = forcePlainLayout();
1892 Layout const & style = asdefault ?
1893 bparams.documentClass().plainLayout() :
1896 // Current base font for all inherited font changes, without any
1897 // change caused by an individual character, except for the language:
1898 // It is set to the language of the first character.
1899 // As long as we are in the label, this font is the base font of the
1900 // label. Before the first body character it is set to the base font
1904 // Maybe we have to create a optional argument.
1905 pos_type body_pos = beginOfBody();
1906 unsigned int column = 0;
1909 // the optional argument is kept in curly brackets in
1910 // case it contains a ']'
1913 basefont = getLabelFont(bparams, outerfont);
1915 basefont = getLayoutFont(bparams, outerfont);
1918 // Which font is currently active?
1919 Font running_font(basefont);
1920 // Do we have an open font change?
1921 bool open_font = false;
1923 Change runningChange = Change(Change::UNCHANGED);
1925 texrow.start(id(), 0);
1927 // if the paragraph is empty, the loop will not be entered at all
1929 if (style.isCommand()) {
1934 column += d->startTeXParParams(bparams, os, texrow,
1938 for (pos_type i = 0; i < size(); ++i) {
1939 // First char in paragraph or after label?
1940 if (i == body_pos) {
1943 column += running_font.latexWriteEndChanges(
1944 os, bparams, runparams,
1945 basefont, basefont);
1948 basefont = getLayoutFont(bparams, outerfont);
1949 running_font = basefont;
1951 column += Changes::latexMarkChange(os, bparams,
1952 runningChange, Change(Change::UNCHANGED));
1953 runningChange = Change(Change::UNCHANGED);
1958 if (style.isCommand()) {
1964 column += d->startTeXParParams(bparams, os,
1969 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1972 if (bparams.outputChanges && runningChange != change) {
1974 column += running_font.latexWriteEndChanges(
1975 os, bparams, runparams, basefont, basefont);
1978 basefont = getLayoutFont(bparams, outerfont);
1979 running_font = basefont;
1981 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1982 runningChange = change;
1985 // do not output text which is marked deleted
1986 // if change tracking output is disabled
1987 if (!bparams.outputChanges && change.type == Change::DELETED) {
1993 // Fully instantiated font
1994 Font const font = getFont(bparams, i, outerfont);
1996 Font const last_font = running_font;
1998 // Do we need to close the previous font?
2000 (font != running_font ||
2001 font.language() != running_font.language()))
2003 column += running_font.latexWriteEndChanges(
2004 os, bparams, runparams, basefont,
2005 (i == body_pos-1) ? basefont : font);
2006 running_font = basefont;
2010 // close babel's font environment before opening CJK.
2011 if (!running_font.language()->babel().empty() &&
2012 font.language()->encoding()->package() == Encoding::CJK) {
2013 string end_tag = subst(lyxrc.language_command_end,
2015 running_font.language()->babel());
2016 os << from_ascii(end_tag);
2017 column += end_tag.length();
2020 // Switch file encoding if necessary (and allowed)
2021 if (!runparams.verbatim &&
2022 runparams.encoding->package() != Encoding::none &&
2023 font.language()->encoding()->package() != Encoding::none) {
2024 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2025 runparams, *(font.language()->encoding()));
2026 if (enc_switch.first) {
2027 column += enc_switch.second;
2028 runparams.encoding = font.language()->encoding();
2032 char_type const c = d->text_[i];
2034 // Do we need to change font?
2035 if ((font != running_font ||
2036 font.language() != running_font.language()) &&
2039 odocstringstream ods;
2040 column += font.latexWriteStartChanges(ods, bparams,
2041 runparams, basefont,
2043 running_font = font;
2045 docstring fontchange = ods.str();
2046 // check if the fontchange ends with a trailing blank
2047 // (like "\small " (see bug 3382)
2048 if (suffixIs(fontchange, ' ') && c == ' ')
2049 os << fontchange.substr(0, fontchange.size() - 1)
2050 << from_ascii("{}");
2056 // FIXME: integrate this case in latexSpecialChar
2057 // Do not print the separation of the optional argument
2058 // if style.pass_thru is false. This works because
2059 // latexSpecialChar ignores spaces if
2060 // style.pass_thru is false.
2061 if (i != body_pos - 1) {
2062 if (d->simpleTeXBlanks(
2063 runparams, os, texrow,
2064 i, column, font, style)) {
2065 // A surrogate pair was output. We
2066 // must not call latexSpecialChar
2067 // in this iteration, since it would output
2068 // the combining character again.
2075 OutputParams rp = runparams;
2076 rp.free_spacing = style.free_spacing;
2077 rp.local_font = &font;
2078 rp.intitle = style.intitle;
2080 // Two major modes: LaTeX or plain
2081 // Handle here those cases common to both modes
2082 // and then split to handle the two modes separately.
2083 if (c == META_INSET)
2084 d->latexInset(bparams, os,
2085 texrow, rp, running_font,
2086 basefont, outerfont, open_font,
2087 runningChange, style, i, column);
2090 d->latexSpecialChar(os, rp, running_font, runningChange,
2092 } catch (EncodingException & e) {
2093 if (runparams.dryrun) {
2094 os << "<" << _("LyX Warning: ")
2095 << _("uncodable character") << " '";
2099 // add location information and throw again.
2107 // Set the encoding to that returned from latexSpecialChar (see
2108 // comment for encoding member in OutputParams.h)
2109 runparams.encoding = rp.encoding;
2112 // If we have an open font definition, we have to close it
2114 #ifdef FIXED_LANGUAGE_END_DETECTION
2117 .latexWriteEndChanges(os, bparams, runparams,
2119 next_->getFont(bparams, 0, outerfont));
2121 running_font.latexWriteEndChanges(os, bparams,
2122 runparams, basefont, basefont);
2125 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2126 //FIXME: there as we start another \selectlanguage with the next paragraph if
2127 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2128 running_font.latexWriteEndChanges(os, bparams, runparams,
2129 basefont, basefont);
2133 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2135 // Needed if there is an optional argument but no contents.
2136 if (body_pos > 0 && body_pos == size()) {
2138 return_value = false;
2142 column += d->endTeXParParams(bparams, os, texrow,
2146 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2147 return return_value;
2151 bool Paragraph::emptyTag() const
2153 for (pos_type i = 0; i < size(); ++i) {
2154 if (Inset const * inset = getInset(i)) {
2155 InsetCode lyx_code = inset->lyxCode();
2156 if (lyx_code != TOC_CODE &&
2157 lyx_code != INCLUDE_CODE &&
2158 lyx_code != GRAPHICS_CODE &&
2159 lyx_code != ERT_CODE &&
2160 lyx_code != LISTINGS_CODE &&
2161 lyx_code != FLOAT_CODE &&
2162 lyx_code != TABULAR_CODE) {
2166 char_type c = d->text_[i];
2167 if (c != ' ' && c != '\t')
2175 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2178 for (pos_type i = 0; i < size(); ++i) {
2179 if (Inset const * inset = getInset(i)) {
2180 InsetCode lyx_code = inset->lyxCode();
2181 if (lyx_code == LABEL_CODE) {
2182 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2183 docstring const & id = il->getParam("name");
2184 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2192 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2196 for (i = 0; i < size(); ++i) {
2197 if (Inset const * inset = getInset(i)) {
2198 inset->docbook(os, runparams);
2200 char_type c = d->text_[i];
2203 os << sgml::escapeChar(c);
2210 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2213 pos_type size = text_.size();
2214 for (pos_type i = initial; i < size; ++i) {
2215 Font font = owner_->getFont(buf.params(), i, outerfont);
2216 if (text_[i] == META_INSET)
2218 if (i != initial && font != font_old)
2227 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2229 OutputParams const & runparams,
2230 Font const & outerfont,
2231 pos_type initial) const
2233 bool emph_flag = false;
2235 Layout const & style = *d->layout_;
2237 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2239 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2242 // parsing main loop
2243 for (pos_type i = initial; i < size(); ++i) {
2244 Font font = getFont(buf.params(), i, outerfont);
2246 // handle <emphasis> tag
2247 if (font_old.emph() != font.fontInfo().emph()) {
2248 if (font.fontInfo().emph() == FONT_ON) {
2251 } else if (i != initial) {
2252 os << "</emphasis>";
2257 if (Inset const * inset = getInset(i)) {
2258 inset->docbook(os, runparams);
2260 char_type c = d->text_[i];
2262 if (style.pass_thru)
2265 os << sgml::escapeChar(c);
2267 font_old = font.fontInfo();
2271 os << "</emphasis>";
2274 if (style.free_spacing)
2276 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2281 bool Paragraph::isHfill(pos_type pos) const
2283 Inset const * inset = getInset(pos);
2284 return inset && (inset->lyxCode() == SPACE_CODE &&
2285 inset->isStretchableSpace());
2289 bool Paragraph::isNewline(pos_type pos) const
2291 Inset const * inset = getInset(pos);
2292 return inset && inset->lyxCode() == NEWLINE_CODE;
2296 bool Paragraph::isLineSeparator(pos_type pos) const
2298 char_type const c = d->text_[pos];
2299 if (isLineSeparatorChar(c))
2301 Inset const * inset = getInset(pos);
2302 return inset && inset->isLineSeparator();
2306 /// Used by the spellchecker
2307 bool Paragraph::isLetter(pos_type pos) const
2309 if (Inset const * inset = getInset(pos))
2310 return inset->isLetter();
2311 char_type const c = d->text_[pos];
2312 return isLetterChar(c) || isDigit(c);
2316 bool Paragraph::isChar(pos_type pos) const
2318 if (Inset const * inset = getInset(pos))
2319 return inset->isChar();
2320 char_type const c = d->text_[pos];
2321 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2325 bool Paragraph::isSpace(pos_type pos) const
2327 if (Inset const * inset = getInset(pos))
2328 return inset->isSpace();
2329 char_type const c = d->text_[pos];
2330 return lyx::isSpace(c);
2335 Paragraph::getParLanguage(BufferParams const & bparams) const
2338 return getFirstFontSettings(bparams).language();
2339 // FIXME: we should check the prev par as well (Lgb)
2340 return bparams.language;
2344 bool Paragraph::isRTL(BufferParams const & bparams) const
2346 return lyxrc.rtl_support
2347 && getParLanguage(bparams)->rightToLeft()
2348 && ownerCode() != ERT_CODE
2349 && ownerCode() != LISTINGS_CODE;
2353 void Paragraph::changeLanguage(BufferParams const & bparams,
2354 Language const * from, Language const * to)
2356 // change language including dummy font change at the end
2357 for (pos_type i = 0; i <= size(); ++i) {
2358 Font font = getFontSettings(bparams, i);
2359 if (font.language() == from) {
2360 font.setLanguage(to);
2367 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2369 Language const * doc_language = bparams.language;
2370 FontList::const_iterator cit = d->fontlist_.begin();
2371 FontList::const_iterator end = d->fontlist_.end();
2373 for (; cit != end; ++cit)
2374 if (cit->font().language() != ignore_language &&
2375 cit->font().language() != latex_language &&
2376 cit->font().language() != doc_language)
2382 docstring Paragraph::asString(int options) const
2384 return asString(0, size(), options);
2388 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2390 odocstringstream os;
2393 && options & AS_STR_LABEL
2394 && !d->params_.labelString().empty())
2395 os << d->params_.labelString() << ' ';
2397 for (pos_type i = beg; i < end; ++i) {
2398 char_type const c = d->text_[i];
2399 if (isPrintable(c) || c == '\t')
2401 else if (c == META_INSET && options & AS_STR_INSETS)
2402 getInset(i)->textString(os);
2409 void Paragraph::setInsetOwner(Inset const * inset)
2411 d->inset_owner_ = inset;
2415 int Paragraph::id() const
2421 Layout const & Paragraph::layout() const
2427 void Paragraph::setLayout(Layout const & layout)
2429 d->layout_ = &layout;
2433 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2435 if (usePlainLayout())
2436 setLayout(tclass.plainLayout());
2438 setLayout(tclass.defaultLayout());
2442 Inset const & Paragraph::inInset() const
2444 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2445 _("Memory problem"), _("Paragraph not properly initiliazed")));
2446 return *d->inset_owner_;
2450 InsetCode Paragraph::ownerCode() const
2452 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2456 ParagraphParameters & Paragraph::params()
2462 ParagraphParameters const & Paragraph::params() const
2468 bool Paragraph::isFreeSpacing() const
2470 if (d->layout_->free_spacing)
2472 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2476 bool Paragraph::allowEmpty() const
2478 if (d->layout_->keepempty)
2480 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2484 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2486 if (!Encodings::isArabicChar(c))
2489 char_type prev_char = ' ';
2490 char_type next_char = ' ';
2492 for (pos_type i = pos - 1; i >= 0; --i) {
2493 char_type const par_char = d->text_[i];
2494 if (!Encodings::isArabicComposeChar(par_char)) {
2495 prev_char = par_char;
2500 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2501 char_type const par_char = d->text_[i];
2502 if (!Encodings::isArabicComposeChar(par_char)) {
2503 next_char = par_char;
2508 if (Encodings::isArabicChar(next_char)) {
2509 if (Encodings::isArabicChar(prev_char) &&
2510 !Encodings::isArabicSpecialChar(prev_char))
2511 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2513 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2515 if (Encodings::isArabicChar(prev_char) &&
2516 !Encodings::isArabicSpecialChar(prev_char))
2517 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2519 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2524 int Paragraph::checkBiblio(Buffer const & buffer)
2527 // This is getting more and more a mess. ...We really should clean
2528 // up this bibitem issue for 1.6. See also bug 2743.
2530 // Add bibitem insets if necessary
2531 if (d->layout_->labeltype != LABEL_BIBLIO)
2534 bool hasbibitem = !d->insetlist_.empty()
2535 // Insist on it being in pos 0
2536 && d->text_[0] == META_INSET
2537 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2539 bool track_changes = buffer.params().trackChanges;
2544 // remove a bibitem in pos != 0
2545 // restore it later in pos 0 if necessary
2546 // (e.g. if a user inserts contents _before_ the item)
2547 // we're assuming there's only one of these, which there
2549 int erasedInsetPosition = -1;
2550 InsetList::iterator it = d->insetlist_.begin();
2551 InsetList::iterator end = d->insetlist_.end();
2552 for (; it != end; ++it)
2553 if (it->inset->lyxCode() == BIBITEM_CODE
2555 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2556 oldkey = olditem->getParam("key");
2557 oldlabel = olditem->getParam("label");
2558 erasedInsetPosition = it->pos;
2559 eraseChar(erasedInsetPosition, track_changes);
2563 // There was an InsetBibitem at the beginning, and we didn't
2564 // have to erase one.
2565 if (hasbibitem && erasedInsetPosition < 0)
2568 // There was an InsetBibitem at the beginning and we did have to
2569 // erase one. So we give its properties to the beginning inset.
2571 InsetBibitem * inset =
2572 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2573 if (!oldkey.empty())
2574 inset->setParam("key", oldkey);
2575 inset->setParam("label", oldlabel);
2576 return -erasedInsetPosition;
2579 // There was no inset at the beginning, so we need to create one with
2580 // the key and label of the one we erased.
2581 InsetBibitem * inset =
2582 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2583 // restore values of previously deleted item in this par.
2584 if (!oldkey.empty())
2585 inset->setParam("key", oldkey);
2586 inset->setParam("label", oldlabel);
2587 insertInset(0, static_cast<Inset *>(inset),
2588 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2594 void Paragraph::checkAuthors(AuthorList const & authorList)
2596 d->changes_.checkAuthors(authorList);
2600 bool Paragraph::isUnchanged(pos_type pos) const
2602 return lookupChange(pos).type == Change::UNCHANGED;
2606 bool Paragraph::isInserted(pos_type pos) const
2608 return lookupChange(pos).type == Change::INSERTED;
2612 bool Paragraph::isDeleted(pos_type pos) const
2614 return lookupChange(pos).type == Change::DELETED;
2618 InsetList const & Paragraph::insetList() const
2620 return d->insetlist_;
2624 void Paragraph::setBuffer(Buffer & b)
2626 d->insetlist_.setBuffer(b);
2630 Inset * Paragraph::releaseInset(pos_type pos)
2632 Inset * inset = d->insetlist_.release(pos);
2633 /// does not honour change tracking!
2634 eraseChar(pos, false);
2639 Inset * Paragraph::getInset(pos_type pos)
2641 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2642 ? d->insetlist_.get(pos) : 0;
2646 Inset const * Paragraph::getInset(pos_type pos) const
2648 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2649 ? d->insetlist_.get(pos) : 0;
2653 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2654 pos_type & right, TextCase action)
2656 // process sequences of modified characters; in change
2657 // tracking mode, this approach results in much better
2658 // usability than changing case on a char-by-char basis
2661 bool const trackChanges = bparams.trackChanges;
2663 bool capitalize = true;
2665 for (; pos < right; ++pos) {
2666 char_type oldChar = d->text_[pos];
2667 char_type newChar = oldChar;
2669 // ignore insets and don't play with deleted text!
2670 if (oldChar != META_INSET && !isDeleted(pos)) {
2672 case text_lowercase:
2673 newChar = lowercase(oldChar);
2675 case text_capitalization:
2677 newChar = uppercase(oldChar);
2681 case text_uppercase:
2682 newChar = uppercase(oldChar);
2687 if (!isLetter(pos) || isDeleted(pos)) {
2688 // permit capitalization again
2692 if (oldChar != newChar)
2695 if (oldChar == newChar || pos == right - 1) {
2696 if (oldChar != newChar) {
2697 // step behind the changing area
2700 int erasePos = pos - changes.size();
2701 for (size_t i = 0; i < changes.size(); i++) {
2702 insertChar(pos, changes[i],
2703 getFontSettings(bparams,
2706 if (!eraseChar(erasePos, trackChanges)) {
2709 ++right; // expand selection
2718 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2719 pos_type pos, bool del) const
2721 int const strsize = str.length();
2723 pos_type const parsize = d->text_.size();
2724 for (i = 0; pos + i < parsize; ++i) {
2727 if (cs && str[i] != d->text_[pos + i])
2729 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2731 if (!del && isDeleted(pos + i))
2738 // if necessary, check whether string matches word
2740 if (pos > 0 && isLetter(pos - 1))
2742 if (pos + strsize < parsize
2743 && isLetter(pos + strsize))
2751 char_type Paragraph::getChar(pos_type pos) const
2753 return d->text_[pos];
2757 pos_type Paragraph::size() const
2759 return d->text_.size();
2763 bool Paragraph::empty() const
2765 return d->text_.empty();
2769 bool Paragraph::isInset(pos_type pos) const
2771 return d->text_[pos] == META_INSET;
2775 bool Paragraph::isSeparator(pos_type pos) const
2777 //FIXME: Are we sure this can be the only separator?
2778 return d->text_[pos] == ' ';
2782 void Paragraph::deregisterWords()
2784 Private::Words::const_iterator it;
2785 WordList & wl = theWordList();
2786 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2792 void Paragraph::collectWords(CursorSlice const & sl)
2795 bool inword = false;
2797 //lyxerr << "Words: ";
2798 pos_type n = size();
2799 for (pos_type pos = 0; pos != n; ++pos) {
2803 if (!isLetter(pos)) {
2812 CursorSlice from = sl;
2813 CursorSlice to = sl;
2816 from.text()->getWord(from, to, WHOLE_WORD);
2817 if (to.pos() - from.pos() < 6)
2819 docstring word = asString(from.pos(), to.pos(), false);
2820 d->words_.insert(word);
2821 //lyxerr << word << " ";
2823 //lyxerr << std::endl;
2827 void Paragraph::registerWords()
2829 Private::Words::const_iterator it;
2830 WordList & wl = theWordList();
2831 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2836 void Paragraph::updateWords(CursorSlice const & sl)
2838 LASSERT(&sl.paragraph() == this, /**/);