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 const &, 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 const & runparams,
139 Font const & running_font,
140 Change const & 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 const & 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 bool Paragraph::insertInset(pos_type pos, Inset * inset,
453 Change const & change)
455 LASSERT(inset, /**/);
456 LASSERT(pos >= 0 && pos <= size(), /**/);
458 // Paragraph::insertInset() can be used in cut/copy/paste operation where
459 // d->inset_owner_ is not set yet.
460 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
463 d->insertChar(pos, META_INSET, change);
464 LASSERT(d->text_[pos] == META_INSET, /**/);
466 // Add a new entry in the insetlist_.
467 d->insetlist_.insert(inset, pos);
472 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
474 LASSERT(pos >= 0 && pos <= size(), return false);
476 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
479 Change change = d->changes_.lookup(pos);
481 // set the character to DELETED if
482 // a) it was previously unchanged or
483 // b) it was inserted by a co-author
485 if (change.type == Change::UNCHANGED ||
486 (change.type == Change::INSERTED && change.author != 0)) {
487 setChange(pos, Change(Change::DELETED));
491 if (change.type == Change::DELETED)
495 // Don't physically access the imaginary end-of-paragraph character.
496 // eraseChar() can only mark it as DELETED. A physical deletion of
497 // end-of-par must be handled externally.
503 d->changes_.erase(pos);
505 // if it is an inset, delete the inset entry
506 if (d->text_[pos] == META_INSET)
507 d->insetlist_.erase(pos);
509 d->text_.erase(d->text_.begin() + pos);
511 // Update the fontlist_
512 d->fontlist_.erase(pos);
514 // Update the insetlist_
515 d->insetlist_.decreasePosAfterPos(pos);
521 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
523 LASSERT(start >= 0 && start <= size(), /**/);
524 LASSERT(end >= start && end <= size() + 1, /**/);
527 for (pos_type count = end - start; count; --count) {
528 if (!eraseChar(i, trackChanges))
535 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
536 char_type next, Encoding const & encoding)
538 // Writing next here may circumvent a possible font change between
539 // c and next. Since next is only output if it forms a surrogate pair
540 // with c we can ignore this:
541 // A font change inside a surrogate pair does not make sense and is
542 // hopefully impossible to input.
543 // FIXME: change tracking
544 // Is this correct WRT change tracking?
545 docstring const latex1 = encoding.latexChar(next);
546 docstring const latex2 = encoding.latexChar(c);
547 if (docstring(1, next) == latex1) {
548 // the encoding supports the combination
549 os << latex2 << latex1;
550 return latex1.length() + latex2.length();
552 os << latex1 << '{' << latex2 << '}';
553 return latex1.length() + latex2.length() + 2;
557 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
558 odocstream & os, TexRow & texrow,
560 unsigned int & column,
562 Layout const & style)
564 if (style.pass_thru || runparams.verbatim)
567 if (i + 1 < int(text_.size())) {
568 char_type next = text_[i + 1];
569 if (Encodings::isCombiningChar(next)) {
570 Encoding const & encoding = *(runparams.encoding);
571 // This space has an accent, so we must always output it.
572 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
577 if (lyxrc.plaintext_linelen > 0
578 && column > lyxrc.plaintext_linelen
580 && text_[i - 1] != ' '
581 && (i + 1 < int(text_.size()))
582 // same in FreeSpacing mode
583 && !owner_->isFreeSpacing()
584 // In typewriter mode, we want to avoid
585 // ! . ? : at the end of a line
586 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
587 && (text_[i - 1] == '.'
588 || text_[i - 1] == '?'
589 || text_[i - 1] == ':'
590 || text_[i - 1] == '!'))) {
593 texrow.start(owner_->id(), i + 1);
595 } else if (style.free_spacing) {
604 int Paragraph::Private::writeScriptChars(odocstream & os,
605 docstring const & ltx,
606 Change const & runningChange,
607 Encoding const & encoding,
610 // FIXME: modifying i here is not very nice...
612 // We only arrive here when a proper language for character text_[i] has
613 // not been specified (i.e., it could not be translated in the current
614 // latex encoding) or its latex translation has been forced, and it
615 // belongs to a known script.
616 // Parameter ltx contains the latex translation of text_[i] as specified
617 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
618 // The latex macro name "textXXX" specifies the script to which text_[i]
619 // belongs and we use it in order to check whether characters from the
620 // same script immediately follow, such that we can collect them in a
621 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
622 // for the first char but only "<spec>" for all subsequent chars.
623 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
624 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
625 string script = to_ascii(ltx.substr(1, brace1 - 1));
628 bool closing_brace = true;
629 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
630 // Correct encoding is being used, so we can avoid \textgreek.
633 closing_brace = false;
635 os << ltx.substr(pos, length);
636 int size = text_.size();
637 while (i + 1 < size) {
638 char_type const next = text_[i + 1];
639 // Stop here if next character belongs to another script
640 // or there is a change in change tracking status.
641 if (!Encodings::isKnownScriptChar(next, script) ||
642 runningChange != owner_->lookupChange(i + 1))
646 FontList::const_iterator cit = fontlist_.begin();
647 FontList::const_iterator end = fontlist_.end();
648 for (; cit != end; ++cit) {
649 if (cit->pos() >= i && !found) {
650 prev_font = cit->font();
653 if (cit->pos() >= i + 1)
656 // Stop here if there is a font attribute or encoding change.
657 if (found && cit != end && prev_font != cit->font())
659 docstring const latex = encoding.latexChar(next);
660 docstring::size_type const b1 =
661 latex.find_first_of(from_ascii("{"));
662 docstring::size_type const b2 =
663 latex.find_last_of(from_ascii("}"));
664 int const len = b2 - b1 - 1;
665 os << latex.substr(b1 + 1, len);
677 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
679 pos_type const len = str.length();
681 // is the paragraph large enough?
682 if (pos + len > int(text_.size()))
685 // does the wanted text start at point?
686 for (string::size_type i = 0; i < str.length(); ++i) {
687 // Caution: direct comparison of characters works only
688 // because str is pure ASCII.
689 if (str[i] != text_[pos + i])
693 return fontlist_.hasChangeInRange(pos, len);
697 void Paragraph::Private::latexInset(
698 BufferParams const & bparams,
701 OutputParams & runparams,
704 Font const & outerfont,
706 Change & running_change,
707 Layout const & style,
709 unsigned int & column)
711 Inset * inset = owner_->getInset(i);
712 LASSERT(inset, /**/);
714 if (style.pass_thru) {
715 inset->plaintext(os, runparams);
719 // FIXME: move this to InsetNewline::latex
720 if (inset->lyxCode() == NEWLINE_CODE) {
721 // newlines are handled differently here than
722 // the default in simpleTeXSpecialChars().
723 if (!style.newline_allowed) {
727 column += running_font.latexWriteEndChanges(
728 os, bparams, runparams,
733 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
736 basefont = owner_->getLayoutFont(bparams, outerfont);
737 running_font = basefont;
739 if (runparams.moving_arg)
744 texrow.start(owner_->id(), i + 1);
748 if (owner_->lookupChange(i).type == Change::DELETED) {
749 if( ++runparams.inDeletedInset == 1)
750 runparams.changeOfDeletedInset = owner_->lookupChange(i);
753 if (inset->canTrackChanges()) {
754 column += Changes::latexMarkChange(os, bparams, running_change,
755 Change(Change::UNCHANGED));
756 running_change = Change(Change::UNCHANGED);
760 odocstream::pos_type const len = os.tellp();
762 if (inset->forceLTR()
763 && running_font.isRightToLeft()
764 // ERT is an exception, it should be output with no decorations at all
765 && inset->lyxCode() != ERT_CODE) {
766 if (running_font.language()->lang() == "farsi")
773 // FIXME: Bug: we can have an empty font change here!
774 // if there has just been a font change, we are going to close it
775 // right now, which means stupid latex code like \textsf{}. AFAIK,
776 // this does not harm dvi output. A minor bug, thus (JMarc)
778 // Some insets cannot be inside a font change command.
779 // However, even such insets *can* be placed in \L or \R
780 // or their equivalents (for RTL language switches), so we don't
781 // close the language in those cases.
782 // ArabTeX, though, cannot handle this special behavior, it seems.
783 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
784 || running_font.language()->lang() == "arabic_arabtex";
785 if (open_font && inset->noFontChange()) {
786 bool closeLanguage = arabtex
787 || basefont.isRightToLeft() == running_font.isRightToLeft();
788 unsigned int count = running_font.latexWriteEndChanges(os,
789 bparams, runparams, basefont, basefont, closeLanguage);
791 // if any font properties were closed, update the running_font,
792 // making sure, however, to leave the language as it was
794 // FIXME: probably a better way to keep track of the old
795 // language, than copying the entire font?
796 Font const copy_font(running_font);
797 basefont = owner_->getLayoutFont(bparams, outerfont);
798 running_font = basefont;
800 running_font.setLanguage(copy_font.language());
801 // leave font open if language is still open
802 open_font = (running_font.language() == basefont.language());
804 runparams.local_font = &basefont;
811 tmp = inset->latex(os, runparams);
812 } catch (EncodingException & e) {
813 // add location information and throw again.
820 if (running_font.language()->lang() == "farsi")
827 for (int j = 0; j < tmp; ++j)
830 texrow.start(owner_->id(), i + 1);
833 column += os.tellp() - len;
836 if (owner_->lookupChange(i).type == Change::DELETED)
837 --runparams.inDeletedInset;
841 void Paragraph::Private::latexSpecialChar(
843 OutputParams const & runparams,
844 Font const & running_font,
845 Change const & running_change,
846 Layout const & style,
848 unsigned int & column)
850 char_type const c = text_[i];
852 if (style.pass_thru) {
854 // FIXME UNICODE: This can fail if c cannot
855 // be encoded in the current encoding.
860 if (runparams.verbatim) {
861 // FIXME UNICODE: This can fail if c cannot
862 // be encoded in the current encoding.
867 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
870 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
871 && latexSpecialTypewriter(c, os, i, column))
874 // Otherwise, we use what LaTeX provides us.
877 os << "\\textbackslash{}";
881 os << "\\textless{}";
885 os << "\\textgreater{}";
896 os << "\\char`\\\"{}";
901 case '%': case '#': case '{':
909 os << "\\textasciitilde{}";
914 os << "\\textasciicircum{}";
919 // avoid being mistaken for optional arguments
927 // Blanks are printed before font switching.
928 // Sure? I am not! (try nice-latex)
929 // I am sure it's correct. LyX might be smarter
930 // in the future, but for now, nothing wrong is
936 if (latexSpecialPhrase(os, i, column, runparams))
942 Encoding const & encoding = *(runparams.encoding);
943 if (i + 1 < int(text_.size())) {
944 char_type next = text_[i + 1];
945 if (Encodings::isCombiningChar(next)) {
946 column += latexSurrogatePair(os, c, next, encoding) - 1;
952 docstring const latex = encoding.latexChar(c);
953 if (Encodings::isKnownScriptChar(c, script)
954 && prefixIs(latex, from_ascii("\\" + script)))
955 column += writeScriptChars(os, latex,
956 running_change, encoding, i) - 1;
957 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
958 // Prevent eating of a following
959 // space or command corruption by
960 // following characters
961 column += latex.length() + 1;
964 column += latex.length() - 1;
972 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
973 pos_type i, unsigned int & column)
979 // In T1 encoding, these characters exist
980 // but we should avoid ligatures
981 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
983 os << "\\textcompwordmark{}";
990 // soul.sty breaks with \char`\"
991 os << "\\textquotedbl{}";
1000 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1001 pos_type i, unsigned int & column)
1005 // within \ttfamily, "--" is merged to "-" (no endash)
1006 // so we avoid this rather irritating ligature
1007 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1014 // everything else has to be checked separately
1015 // (depending on the encoding)
1022 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1023 unsigned int & column, OutputParams const & runparams)
1025 // FIXME: if we have "LaTeX" with a font
1026 // change in the middle (before the 'T', then
1027 // the "TeX" part is still special cased.
1028 // Really we should only operate this on
1029 // "words" for some definition of word
1031 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1032 if (!isTextAt(special_phrases[pnr].phrase, i))
1034 if (runparams.moving_arg)
1036 os << special_phrases[pnr].macro;
1037 i += special_phrases[pnr].phrase.length() - 1;
1038 column += special_phrases[pnr].macro.length() - 1;
1045 void Paragraph::Private::validate(LaTeXFeatures & features,
1046 Layout const & layout) const
1048 // check the params.
1049 if (!params_.spacing().isDefault())
1050 features.require("setspace");
1053 features.useLayout(layout.name());
1056 fontlist_.validate(features);
1058 // then the indentation
1059 if (!params_.leftIndent().zero())
1060 features.require("ParagraphLeftIndent");
1063 InsetList::const_iterator icit = insetlist_.begin();
1064 InsetList::const_iterator iend = insetlist_.end();
1065 for (; icit != iend; ++icit) {
1067 icit->inset->validate(features);
1068 if (layout.needprotect &&
1069 icit->inset->lyxCode() == FOOT_CODE)
1070 features.require("NeedLyXFootnoteCode");
1074 // then the contents
1075 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1076 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1077 if (!special_phrases[pnr].builtin
1078 && isTextAt(special_phrases[pnr].phrase, i)) {
1079 features.require(special_phrases[pnr].phrase);
1083 Encodings::validate(text_[i], features);
1087 /////////////////////////////////////////////////////////////////////
1091 /////////////////////////////////////////////////////////////////////
1094 Layout const emptyParagraphLayout;
1097 Paragraph::Paragraph()
1098 : d(new Paragraph::Private(this, emptyParagraphLayout))
1105 Paragraph::Paragraph(Paragraph const & par)
1106 : itemdepth(par.itemdepth),
1107 d(new Paragraph::Private(*par.d, this))
1113 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1114 : itemdepth(par.itemdepth),
1115 d(new Paragraph::Private(*par.d, this, beg, end))
1121 Paragraph & Paragraph::operator=(Paragraph const & par)
1123 // needed as we will destroy the private part before copying it
1125 itemdepth = par.itemdepth;
1129 d = new Private(*par.d, this);
1136 Paragraph::~Paragraph()
1143 void Paragraph::write(ostream & os, BufferParams const & bparams,
1144 depth_type & dth) const
1146 // The beginning or end of a deeper (i.e. nested) area?
1147 if (dth != d->params_.depth()) {
1148 if (d->params_.depth() > dth) {
1149 while (d->params_.depth() > dth) {
1150 os << "\n\\begin_deeper";
1154 while (d->params_.depth() < dth) {
1155 os << "\n\\end_deeper";
1161 // First write the layout
1162 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1164 d->params_.write(os);
1166 Font font1(inherit_font, bparams.language);
1168 Change running_change = Change(Change::UNCHANGED);
1171 for (pos_type i = 0; i <= size(); ++i) {
1173 Change change = lookupChange(i);
1174 Changes::lyxMarkChange(os, column, running_change, change);
1175 running_change = change;
1180 // Write font changes
1181 Font const & font2 = getFontSettings(bparams, i);
1182 if (font2 != font1) {
1183 font2.lyxWriteChanges(font1, os);
1188 char_type const c = d->text_[i];
1191 if (Inset const * inset = getInset(i)) {
1192 if (inset->directWrite()) {
1193 // international char, let it write
1194 // code directly so it's shorter in
1200 os << "\\begin_inset ";
1202 os << "\n\\end_inset\n\n";
1208 os << "\n\\backslash\n";
1212 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1219 if ((column > 70 && c == ' ')
1224 // this check is to amend a bug. LyX sometimes
1225 // inserts '\0' this could cause problems.
1227 os << to_utf8(docstring(1, c));
1229 LYXERR0("NUL char in structure.");
1235 os << "\n\\end_layout\n";
1239 void Paragraph::validate(LaTeXFeatures & features) const
1241 d->validate(features, *d->layout_);
1245 void Paragraph::insert(pos_type start, docstring const & str,
1246 Font const & font, Change const & change)
1248 for (size_t i = 0, n = str.size(); i != n ; ++i)
1249 insertChar(start + i, str[i], font, change);
1253 void Paragraph::appendChar(char_type c, Font const & font,
1254 Change const & change)
1257 d->changes_.insert(change, d->text_.size());
1258 // when appending characters, no need to update tables
1259 d->text_.push_back(c);
1260 setFont(d->text_.size() - 1, font);
1264 void Paragraph::appendString(docstring const & s, Font const & font,
1265 Change const & change)
1267 pos_type end = s.size();
1268 size_t oldsize = d->text_.size();
1269 size_t newsize = oldsize + end;
1270 size_t capacity = d->text_.capacity();
1271 if (newsize >= capacity)
1272 d->text_.reserve(max(capacity + 100, newsize));
1274 // when appending characters, no need to update tables
1277 // FIXME: Optimize this!
1278 for (pos_type i = oldsize; i != newsize; ++i) {
1280 d->changes_.insert(change, i);
1282 d->fontlist_.set(oldsize, font);
1283 d->fontlist_.set(newsize - 1, font);
1287 void Paragraph::insertChar(pos_type pos, char_type c,
1290 d->insertChar(pos, c, Change(trackChanges ?
1291 Change::INSERTED : Change::UNCHANGED));
1295 void Paragraph::insertChar(pos_type pos, char_type c,
1296 Font const & font, bool trackChanges)
1298 d->insertChar(pos, c, Change(trackChanges ?
1299 Change::INSERTED : Change::UNCHANGED));
1304 void Paragraph::insertChar(pos_type pos, char_type c,
1305 Font const & font, Change const & change)
1307 d->insertChar(pos, c, change);
1312 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1313 Font const & font, Change const & change)
1315 bool const success = insertInset(pos, inset, change);
1316 // Set the font/language of the inset...
1322 void Paragraph::resetFonts(Font const & font)
1324 d->fontlist_.clear();
1325 d->fontlist_.set(0, font);
1326 d->fontlist_.set(d->text_.size() - 1, font);
1329 // Gets uninstantiated font setting at position.
1330 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1334 LYXERR0("pos: " << pos << " size: " << size());
1335 LASSERT(pos <= size(), /**/);
1338 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1339 if (cit != d->fontlist_.end())
1342 if (pos == size() && !empty())
1343 return getFontSettings(bparams, pos - 1);
1345 // Optimisation: avoid a full font instantiation if there is no
1346 // language change from previous call.
1347 static Font previous_font;
1348 static Language const * previous_lang = 0;
1349 Language const * lang = getParLanguage(bparams);
1350 if (lang != previous_lang) {
1351 previous_lang = lang;
1352 previous_font = Font(inherit_font, lang);
1354 return previous_font;
1358 FontSpan Paragraph::fontSpan(pos_type pos) const
1360 LASSERT(pos <= size(), /**/);
1363 FontList::const_iterator cit = d->fontlist_.begin();
1364 FontList::const_iterator end = d->fontlist_.end();
1365 for (; cit != end; ++cit) {
1366 if (cit->pos() >= pos) {
1367 if (pos >= beginOfBody())
1368 return FontSpan(max(start, beginOfBody()),
1371 return FontSpan(start,
1372 min(beginOfBody() - 1,
1375 start = cit->pos() + 1;
1378 // This should not happen, but if so, we take no chances.
1379 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1380 return FontSpan(pos, pos);
1384 // Gets uninstantiated font setting at position 0
1385 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1387 if (!empty() && !d->fontlist_.empty())
1388 return d->fontlist_.begin()->font();
1390 // Optimisation: avoid a full font instantiation if there is no
1391 // language change from previous call.
1392 static Font previous_font;
1393 static Language const * previous_lang = 0;
1394 if (bparams.language != previous_lang) {
1395 previous_lang = bparams.language;
1396 previous_font = Font(inherit_font, bparams.language);
1399 return previous_font;
1403 // Gets the fully instantiated font at a given position in a paragraph
1404 // This is basically the same function as Text::GetFont() in text2.cpp.
1405 // The difference is that this one is used for generating the LaTeX file,
1406 // and thus cosmetic "improvements" are disallowed: This has to deliver
1407 // the true picture of the buffer. (Asger)
1408 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1409 Font const & outerfont) const
1411 LASSERT(pos >= 0, /**/);
1413 Font font = getFontSettings(bparams, pos);
1415 pos_type const body_pos = beginOfBody();
1416 FontInfo & fi = font.fontInfo();
1418 fi.realize(d->layout_->labelfont);
1420 fi.realize(d->layout_->font);
1422 fi.realize(outerfont.fontInfo());
1423 fi.realize(bparams.getFont().fontInfo());
1429 Font const Paragraph::getLabelFont
1430 (BufferParams const & bparams, Font const & outerfont) const
1432 FontInfo tmpfont = d->layout_->labelfont;
1433 tmpfont.realize(outerfont.fontInfo());
1434 tmpfont.realize(bparams.getFont().fontInfo());
1435 return Font(tmpfont, getParLanguage(bparams));
1439 Font const Paragraph::getLayoutFont
1440 (BufferParams const & bparams, Font const & outerfont) const
1442 FontInfo tmpfont = d->layout_->font;
1443 tmpfont.realize(outerfont.fontInfo());
1444 tmpfont.realize(bparams.getFont().fontInfo());
1445 return Font(tmpfont, getParLanguage(bparams));
1449 /// Returns the height of the highest font in range
1450 FontSize Paragraph::highestFontInRange
1451 (pos_type startpos, pos_type endpos, FontSize def_size) const
1453 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1457 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1459 char_type c = d->text_[pos];
1460 if (!lyxrc.rtl_support)
1490 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1496 void Paragraph::setFont(pos_type pos, Font const & font)
1498 LASSERT(pos <= size(), /**/);
1500 // First, reduce font against layout/label font
1501 // Update: The setCharFont() routine in text2.cpp already
1502 // reduces font, so we don't need to do that here. (Asger)
1504 d->fontlist_.set(pos, font);
1508 void Paragraph::makeSameLayout(Paragraph const & par)
1510 d->layout_ = par.d->layout_;
1511 d->params_ = par.d->params_;
1515 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1517 if (isFreeSpacing())
1523 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1524 if (eraseChar(pos, trackChanges))
1530 return count > 0 || pos > 0;
1534 bool Paragraph::hasSameLayout(Paragraph const & par) const
1536 return par.d->layout_ == d->layout_
1537 && d->params_.sameLayout(par.d->params_);
1541 depth_type Paragraph::getDepth() const
1543 return d->params_.depth();
1547 depth_type Paragraph::getMaxDepthAfter() const
1549 if (d->layout_->isEnvironment())
1550 return d->params_.depth() + 1;
1552 return d->params_.depth();
1556 char Paragraph::getAlign() const
1558 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1559 return d->layout_->align;
1561 return d->params_.align();
1565 docstring const & Paragraph::labelString() const
1567 return d->params_.labelString();
1571 // the next two functions are for the manual labels
1572 docstring const Paragraph::getLabelWidthString() const
1574 if (d->layout_->margintype == MARGIN_MANUAL)
1575 return d->params_.labelWidthString();
1577 return _("Senseless with this layout!");
1581 void Paragraph::setLabelWidthString(docstring const & s)
1583 d->params_.labelWidthString(s);
1587 docstring const Paragraph::translateIfPossible(docstring const & s,
1588 BufferParams const & bparams) const
1590 if (!isAscii(s) || s.empty()) {
1591 // This must be a user defined layout. We cannot translate
1592 // this, since gettext accepts only ascii keys.
1595 // Probably standard layout, try to translate
1596 Messages & m = getMessages(getParLanguage(bparams)->code());
1597 return m.get(to_ascii(s));
1601 docstring Paragraph::expandLabel(Layout const & layout,
1602 BufferParams const & bparams, bool process_appendix) const
1604 DocumentClass const & tclass = bparams.documentClass();
1607 if (process_appendix && d->params_.appendix())
1608 fmt = translateIfPossible(layout.labelstring_appendix(),
1611 fmt = translateIfPossible(layout.labelstring(), bparams);
1613 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1614 && !layout.counter.empty())
1615 fmt = "\\the" + layout.counter;
1617 // handle 'inherited level parts' in 'fmt',
1618 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1619 size_t const i = fmt.find('@', 0);
1620 if (i != docstring::npos) {
1621 size_t const j = fmt.find('@', i + 1);
1622 if (j != docstring::npos) {
1623 docstring parent(fmt, i + 1, j - i - 1);
1624 docstring label = from_ascii("??");
1625 if (tclass.hasLayout(parent))
1626 docstring label = expandLabel(tclass[parent], bparams,
1628 fmt = docstring(fmt, 0, i) + label
1629 + docstring(fmt, j + 1, docstring::npos);
1633 return tclass.counters().counterLabel(fmt);
1637 void Paragraph::applyLayout(Layout const & new_layout)
1639 d->layout_ = &new_layout;
1640 LyXAlignment const oldAlign = d->params_.align();
1642 if (!(oldAlign & d->layout_->alignpossible)) {
1643 frontend::Alert::warning(_("Alignment not permitted"),
1644 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1645 d->params_.align(LYX_ALIGN_LAYOUT);
1650 pos_type Paragraph::beginOfBody() const
1652 return d->begin_of_body_;
1656 void Paragraph::setBeginOfBody()
1658 if (d->layout_->labeltype != LABEL_MANUAL) {
1659 d->begin_of_body_ = 0;
1663 // Unroll the first two cycles of the loop
1664 // and remember the previous character to
1665 // remove unnecessary getChar() calls
1667 pos_type end = size();
1668 if (i < end && !isNewline(i)) {
1670 char_type previous_char = 0;
1673 previous_char = d->text_[i];
1674 if (!isNewline(i)) {
1676 while (i < end && previous_char != ' ') {
1681 previous_char = temp;
1687 d->begin_of_body_ = i;
1691 bool Paragraph::forcePlainLayout() const
1693 return inInset().forcePlainLayout();
1697 bool Paragraph::allowParagraphCustomization() const
1699 return inInset().allowParagraphCustomization();
1703 bool Paragraph::usePlainLayout() const
1705 return inInset().usePlainLayout();
1711 // paragraphs inside floats need different alignment tags to avoid
1714 bool noTrivlistCentering(InsetCode code)
1716 return code == FLOAT_CODE
1717 || code == WRAP_CODE
1718 || code == CELL_CODE;
1722 string correction(string const & orig)
1724 if (orig == "flushleft")
1725 return "raggedright";
1726 if (orig == "flushright")
1727 return "raggedleft";
1728 if (orig == "center")
1734 string const corrected_env(string const & suffix, string const & env,
1735 InsetCode code, bool const lastpar)
1737 string output = suffix + "{";
1738 if (noTrivlistCentering(code)) {
1740 // the last paragraph in non-trivlist-aligned
1741 // context is special (to avoid unwanted whitespace)
1742 if (suffix == "\\begin")
1743 return "\\" + correction(env) + "{}";
1746 output += correction(env);
1750 if (suffix == "\\begin")
1756 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1758 if (!contains(str, "\n"))
1759 column += str.size();
1763 column = rsplit(str, tmp, '\n').size();
1770 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1771 odocstream & os, TexRow & texrow,
1772 OutputParams const & runparams) const
1776 if (params_.noindent()) {
1777 os << "\\noindent ";
1781 LyXAlignment const curAlign = params_.align();
1783 if (curAlign == layout_->align)
1787 case LYX_ALIGN_NONE:
1788 case LYX_ALIGN_BLOCK:
1789 case LYX_ALIGN_LAYOUT:
1790 case LYX_ALIGN_SPECIAL:
1792 case LYX_ALIGN_LEFT:
1793 case LYX_ALIGN_RIGHT:
1794 case LYX_ALIGN_CENTER:
1795 if (runparams.moving_arg) {
1802 string const begin_tag = "\\begin";
1803 InsetCode code = owner_->ownerCode();
1804 bool const lastpar = runparams.isLastPar;
1807 case LYX_ALIGN_NONE:
1808 case LYX_ALIGN_BLOCK:
1809 case LYX_ALIGN_LAYOUT:
1810 case LYX_ALIGN_SPECIAL:
1812 case LYX_ALIGN_LEFT: {
1814 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1815 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1817 output = corrected_env(begin_tag, "flushright", code, lastpar);
1818 os << from_ascii(output);
1819 adjust_row_column(output, texrow, column);
1821 } case LYX_ALIGN_RIGHT: {
1823 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1824 output = corrected_env(begin_tag, "flushright", code, lastpar);
1826 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1827 os << from_ascii(output);
1828 adjust_row_column(output, texrow, column);
1830 } case LYX_ALIGN_CENTER: {
1832 output = corrected_env(begin_tag, "center", code, lastpar);
1833 os << from_ascii(output);
1834 adjust_row_column(output, texrow, column);
1843 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1844 odocstream & os, TexRow & texrow,
1845 OutputParams const & runparams) const
1849 switch (params_.align()) {
1850 case LYX_ALIGN_NONE:
1851 case LYX_ALIGN_BLOCK:
1852 case LYX_ALIGN_LAYOUT:
1853 case LYX_ALIGN_SPECIAL:
1855 case LYX_ALIGN_LEFT:
1856 case LYX_ALIGN_RIGHT:
1857 case LYX_ALIGN_CENTER:
1858 if (runparams.moving_arg) {
1865 string const end_tag = "\n\\par\\end";
1866 InsetCode code = owner_->ownerCode();
1867 bool const lastpar = runparams.isLastPar;
1869 switch (params_.align()) {
1870 case LYX_ALIGN_NONE:
1871 case LYX_ALIGN_BLOCK:
1872 case LYX_ALIGN_LAYOUT:
1873 case LYX_ALIGN_SPECIAL:
1875 case LYX_ALIGN_LEFT: {
1877 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1878 output = corrected_env(end_tag, "flushleft", code, lastpar);
1880 output = corrected_env(end_tag, "flushright", code, lastpar);
1881 os << from_ascii(output);
1882 adjust_row_column(output, texrow, column);
1884 } case LYX_ALIGN_RIGHT: {
1886 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1887 output = corrected_env(end_tag, "flushright", code, lastpar);
1889 output = corrected_env(end_tag, "flushleft", code, lastpar);
1890 os << from_ascii(output);
1891 adjust_row_column(output, texrow, column);
1893 } case LYX_ALIGN_CENTER: {
1895 output = corrected_env(end_tag, "center", code, lastpar);
1896 os << from_ascii(output);
1897 adjust_row_column(output, texrow, column);
1906 // This one spits out the text of the paragraph
1907 bool Paragraph::latex(BufferParams const & bparams,
1908 Font const & outerfont,
1909 odocstream & os, TexRow & texrow,
1910 OutputParams const & runparams) const
1912 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1914 bool return_value = false;
1916 bool const allowcust = allowParagraphCustomization();
1918 // FIXME This check should not be needed. Perhaps issue an
1919 // error if it triggers.
1920 Layout const & style = forcePlainLayout() ?
1921 bparams.documentClass().plainLayout() : *d->layout_;
1923 // Current base font for all inherited font changes, without any
1924 // change caused by an individual character, except for the language:
1925 // It is set to the language of the first character.
1926 // As long as we are in the label, this font is the base font of the
1927 // label. Before the first body character it is set to the base font
1931 // Maybe we have to create a optional argument.
1932 pos_type body_pos = beginOfBody();
1933 unsigned int column = 0;
1936 // the optional argument is kept in curly brackets in
1937 // case it contains a ']'
1940 basefont = getLabelFont(bparams, outerfont);
1942 basefont = getLayoutFont(bparams, outerfont);
1945 // Which font is currently active?
1946 Font running_font(basefont);
1947 // Do we have an open font change?
1948 bool open_font = false;
1950 Change runningChange = Change(Change::UNCHANGED);
1952 texrow.start(id(), 0);
1954 // if the paragraph is empty, the loop will not be entered at all
1956 if (style.isCommand()) {
1961 column += d->startTeXParParams(bparams, os, texrow,
1965 for (pos_type i = 0; i < size(); ++i) {
1966 // First char in paragraph or after label?
1967 if (i == body_pos) {
1970 column += running_font.latexWriteEndChanges(
1971 os, bparams, runparams,
1972 basefont, basefont);
1975 basefont = getLayoutFont(bparams, outerfont);
1976 running_font = basefont;
1978 column += Changes::latexMarkChange(os, bparams,
1979 runningChange, Change(Change::UNCHANGED));
1980 runningChange = Change(Change::UNCHANGED);
1985 if (style.isCommand()) {
1991 column += d->startTeXParParams(bparams, os,
1996 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1999 if (bparams.outputChanges && runningChange != change) {
2001 column += running_font.latexWriteEndChanges(
2002 os, bparams, runparams, basefont, basefont);
2005 basefont = getLayoutFont(bparams, outerfont);
2006 running_font = basefont;
2008 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2009 runningChange = change;
2012 // do not output text which is marked deleted
2013 // if change tracking output is disabled
2014 if (!bparams.outputChanges && change.type == Change::DELETED) {
2020 // Fully instantiated font
2021 Font const font = getFont(bparams, i, outerfont);
2023 Font const last_font = running_font;
2025 // Do we need to close the previous font?
2027 (font != running_font ||
2028 font.language() != running_font.language()))
2030 column += running_font.latexWriteEndChanges(
2031 os, bparams, runparams, basefont,
2032 (i == body_pos-1) ? basefont : font);
2033 running_font = basefont;
2037 // close babel's font environment before opening CJK.
2038 if (!running_font.language()->babel().empty() &&
2039 font.language()->encoding()->package() == Encoding::CJK) {
2040 string end_tag = subst(lyxrc.language_command_end,
2042 running_font.language()->babel());
2043 os << from_ascii(end_tag);
2044 column += end_tag.length();
2047 // Switch file encoding if necessary (and allowed)
2048 if (!runparams.verbatim &&
2049 runparams.encoding->package() != Encoding::none &&
2050 font.language()->encoding()->package() != Encoding::none) {
2051 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2052 runparams, *(font.language()->encoding()));
2053 if (enc_switch.first) {
2054 column += enc_switch.second;
2055 runparams.encoding = font.language()->encoding();
2059 char_type const c = d->text_[i];
2061 // Do we need to change font?
2062 if ((font != running_font ||
2063 font.language() != running_font.language()) &&
2066 odocstringstream ods;
2067 column += font.latexWriteStartChanges(ods, bparams,
2068 runparams, basefont,
2070 running_font = font;
2072 docstring fontchange = ods.str();
2073 // check if the fontchange ends with a trailing blank
2074 // (like "\small " (see bug 3382)
2075 if (suffixIs(fontchange, ' ') && c == ' ')
2076 os << fontchange.substr(0, fontchange.size() - 1)
2077 << from_ascii("{}");
2083 // FIXME: integrate this case in latexSpecialChar
2084 // Do not print the separation of the optional argument
2085 // if style.pass_thru is false. This works because
2086 // latexSpecialChar ignores spaces if
2087 // style.pass_thru is false.
2088 if (i != body_pos - 1) {
2089 if (d->simpleTeXBlanks(
2090 runparams, os, texrow,
2091 i, column, font, style)) {
2092 // A surrogate pair was output. We
2093 // must not call latexSpecialChar
2094 // in this iteration, since it would output
2095 // the combining character again.
2102 OutputParams rp = runparams;
2103 rp.free_spacing = style.free_spacing;
2104 rp.local_font = &font;
2105 rp.intitle = style.intitle;
2107 // Two major modes: LaTeX or plain
2108 // Handle here those cases common to both modes
2109 // and then split to handle the two modes separately.
2110 if (c == META_INSET)
2111 d->latexInset(bparams, os,
2112 texrow, rp, running_font,
2113 basefont, outerfont, open_font,
2114 runningChange, style, i, column);
2117 d->latexSpecialChar(os, rp, running_font, runningChange,
2119 } catch (EncodingException & e) {
2120 if (runparams.dryrun) {
2121 os << "<" << _("LyX Warning: ")
2122 << _("uncodable character") << " '";
2126 // add location information and throw again.
2134 // Set the encoding to that returned from latexSpecialChar (see
2135 // comment for encoding member in OutputParams.h)
2136 runparams.encoding = rp.encoding;
2139 // If we have an open font definition, we have to close it
2141 #ifdef FIXED_LANGUAGE_END_DETECTION
2144 .latexWriteEndChanges(os, bparams, runparams,
2146 next_->getFont(bparams, 0, outerfont));
2148 running_font.latexWriteEndChanges(os, bparams,
2149 runparams, basefont, basefont);
2152 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2153 //FIXME: there as we start another \selectlanguage with the next paragraph if
2154 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2155 running_font.latexWriteEndChanges(os, bparams, runparams,
2156 basefont, basefont);
2160 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2162 // Needed if there is an optional argument but no contents.
2163 if (body_pos > 0 && body_pos == size()) {
2165 return_value = false;
2169 column += d->endTeXParParams(bparams, os, texrow,
2173 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2174 return return_value;
2178 bool Paragraph::emptyTag() const
2180 for (pos_type i = 0; i < size(); ++i) {
2181 if (Inset const * inset = getInset(i)) {
2182 InsetCode lyx_code = inset->lyxCode();
2183 if (lyx_code != TOC_CODE &&
2184 lyx_code != INCLUDE_CODE &&
2185 lyx_code != GRAPHICS_CODE &&
2186 lyx_code != ERT_CODE &&
2187 lyx_code != LISTINGS_CODE &&
2188 lyx_code != FLOAT_CODE &&
2189 lyx_code != TABULAR_CODE) {
2193 char_type c = d->text_[i];
2194 if (c != ' ' && c != '\t')
2202 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2205 for (pos_type i = 0; i < size(); ++i) {
2206 if (Inset const * inset = getInset(i)) {
2207 InsetCode lyx_code = inset->lyxCode();
2208 if (lyx_code == LABEL_CODE) {
2209 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2210 docstring const & id = il->getParam("name");
2211 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2219 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2223 for (i = 0; i < size(); ++i) {
2224 if (Inset const * inset = getInset(i)) {
2225 inset->docbook(os, runparams);
2227 char_type c = d->text_[i];
2230 os << sgml::escapeChar(c);
2237 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2240 pos_type size = text_.size();
2241 for (pos_type i = initial; i < size; ++i) {
2242 Font font = owner_->getFont(buf.params(), i, outerfont);
2243 if (text_[i] == META_INSET)
2245 if (i != initial && font != font_old)
2254 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2256 OutputParams const & runparams,
2257 Font const & outerfont,
2258 pos_type initial) const
2260 bool emph_flag = false;
2262 Layout const & style = *d->layout_;
2264 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2266 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2269 // parsing main loop
2270 for (pos_type i = initial; i < size(); ++i) {
2271 Font font = getFont(buf.params(), i, outerfont);
2273 // handle <emphasis> tag
2274 if (font_old.emph() != font.fontInfo().emph()) {
2275 if (font.fontInfo().emph() == FONT_ON) {
2278 } else if (i != initial) {
2279 os << "</emphasis>";
2284 if (Inset const * inset = getInset(i)) {
2285 inset->docbook(os, runparams);
2287 char_type c = d->text_[i];
2289 if (style.pass_thru)
2292 os << sgml::escapeChar(c);
2294 font_old = font.fontInfo();
2298 os << "</emphasis>";
2301 if (style.free_spacing)
2303 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2308 bool Paragraph::isHfill(pos_type pos) const
2310 Inset const * inset = getInset(pos);
2311 return inset && (inset->lyxCode() == SPACE_CODE &&
2312 inset->isStretchableSpace());
2316 bool Paragraph::isNewline(pos_type pos) const
2318 Inset const * inset = getInset(pos);
2319 return inset && inset->lyxCode() == NEWLINE_CODE;
2323 bool Paragraph::isLineSeparator(pos_type pos) const
2325 char_type const c = d->text_[pos];
2326 if (isLineSeparatorChar(c))
2328 Inset const * inset = getInset(pos);
2329 return inset && inset->isLineSeparator();
2333 /// Used by the spellchecker
2334 bool Paragraph::isLetter(pos_type pos) const
2336 if (Inset const * inset = getInset(pos))
2337 return inset->isLetter();
2338 char_type const c = d->text_[pos];
2339 return isLetterChar(c) || isDigit(c);
2343 bool Paragraph::isChar(pos_type pos) const
2345 if (Inset const * inset = getInset(pos))
2346 return inset->isChar();
2347 char_type const c = d->text_[pos];
2348 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2352 bool Paragraph::isSpace(pos_type pos) const
2354 if (Inset const * inset = getInset(pos))
2355 return inset->isSpace();
2356 char_type const c = d->text_[pos];
2357 return lyx::isSpace(c);
2362 Paragraph::getParLanguage(BufferParams const & bparams) const
2365 return getFirstFontSettings(bparams).language();
2366 // FIXME: we should check the prev par as well (Lgb)
2367 return bparams.language;
2371 bool Paragraph::isRTL(BufferParams const & bparams) const
2373 return lyxrc.rtl_support
2374 && getParLanguage(bparams)->rightToLeft()
2375 && ownerCode() != ERT_CODE
2376 && ownerCode() != LISTINGS_CODE;
2380 void Paragraph::changeLanguage(BufferParams const & bparams,
2381 Language const * from, Language const * to)
2383 // change language including dummy font change at the end
2384 for (pos_type i = 0; i <= size(); ++i) {
2385 Font font = getFontSettings(bparams, i);
2386 if (font.language() == from) {
2387 font.setLanguage(to);
2394 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2396 Language const * doc_language = bparams.language;
2397 FontList::const_iterator cit = d->fontlist_.begin();
2398 FontList::const_iterator end = d->fontlist_.end();
2400 for (; cit != end; ++cit)
2401 if (cit->font().language() != ignore_language &&
2402 cit->font().language() != latex_language &&
2403 cit->font().language() != doc_language)
2409 docstring Paragraph::asString(int options) const
2411 return asString(0, size(), options);
2415 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2417 odocstringstream os;
2420 && options & AS_STR_LABEL
2421 && !d->params_.labelString().empty())
2422 os << d->params_.labelString() << ' ';
2424 for (pos_type i = beg; i < end; ++i) {
2425 char_type const c = d->text_[i];
2426 if (isPrintable(c) || c == '\t'
2427 || (c == '\n' && options & AS_STR_NEWLINES))
2429 else if (c == META_INSET && options & AS_STR_INSETS)
2430 getInset(i)->textString(os);
2437 void Paragraph::setInsetOwner(Inset const * inset)
2439 d->inset_owner_ = inset;
2443 int Paragraph::id() const
2449 Layout const & Paragraph::layout() const
2455 void Paragraph::setLayout(Layout const & layout)
2457 d->layout_ = &layout;
2461 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2463 setLayout(tc.defaultLayout());
2467 void Paragraph::setPlainLayout(DocumentClass const & tc)
2469 setLayout(tc.plainLayout());
2473 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2475 if (usePlainLayout())
2476 setPlainLayout(tclass);
2478 setDefaultLayout(tclass);
2482 Inset const & Paragraph::inInset() const
2484 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2485 _("Memory problem"), _("Paragraph not properly initiliazed")));
2486 return *d->inset_owner_;
2490 InsetCode Paragraph::ownerCode() const
2492 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2496 ParagraphParameters & Paragraph::params()
2502 ParagraphParameters const & Paragraph::params() const
2508 bool Paragraph::isFreeSpacing() const
2510 if (d->layout_->free_spacing)
2512 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2516 bool Paragraph::allowEmpty() const
2518 if (d->layout_->keepempty)
2520 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2524 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2526 if (!Encodings::isArabicChar(c))
2529 char_type prev_char = ' ';
2530 char_type next_char = ' ';
2532 for (pos_type i = pos - 1; i >= 0; --i) {
2533 char_type const par_char = d->text_[i];
2534 if (!Encodings::isArabicComposeChar(par_char)) {
2535 prev_char = par_char;
2540 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2541 char_type const par_char = d->text_[i];
2542 if (!Encodings::isArabicComposeChar(par_char)) {
2543 next_char = par_char;
2548 if (Encodings::isArabicChar(next_char)) {
2549 if (Encodings::isArabicChar(prev_char) &&
2550 !Encodings::isArabicSpecialChar(prev_char))
2551 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2553 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2555 if (Encodings::isArabicChar(prev_char) &&
2556 !Encodings::isArabicSpecialChar(prev_char))
2557 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2559 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2564 int Paragraph::checkBiblio(Buffer const & buffer)
2567 // This is getting more and more a mess. ...We really should clean
2568 // up this bibitem issue for 1.6. See also bug 2743.
2570 // Add bibitem insets if necessary
2571 if (d->layout_->labeltype != LABEL_BIBLIO)
2574 bool hasbibitem = !d->insetlist_.empty()
2575 // Insist on it being in pos 0
2576 && d->text_[0] == META_INSET
2577 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2579 bool track_changes = buffer.params().trackChanges;
2584 // remove a bibitem in pos != 0
2585 // restore it later in pos 0 if necessary
2586 // (e.g. if a user inserts contents _before_ the item)
2587 // we're assuming there's only one of these, which there
2589 int erasedInsetPosition = -1;
2590 InsetList::iterator it = d->insetlist_.begin();
2591 InsetList::iterator end = d->insetlist_.end();
2592 for (; it != end; ++it)
2593 if (it->inset->lyxCode() == BIBITEM_CODE
2595 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2596 oldkey = olditem->getParam("key");
2597 oldlabel = olditem->getParam("label");
2598 erasedInsetPosition = it->pos;
2599 eraseChar(erasedInsetPosition, track_changes);
2603 // There was an InsetBibitem at the beginning, and we didn't
2604 // have to erase one.
2605 if (hasbibitem && erasedInsetPosition < 0)
2608 // There was an InsetBibitem at the beginning and we did have to
2609 // erase one. So we give its properties to the beginning inset.
2611 InsetBibitem * inset =
2612 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2613 if (!oldkey.empty())
2614 inset->setParam("key", oldkey);
2615 inset->setParam("label", oldlabel);
2616 return -erasedInsetPosition;
2619 // There was no inset at the beginning, so we need to create one with
2620 // the key and label of the one we erased.
2621 InsetBibitem * inset =
2622 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2623 // restore values of previously deleted item in this par.
2624 if (!oldkey.empty())
2625 inset->setParam("key", oldkey);
2626 inset->setParam("label", oldlabel);
2627 insertInset(0, static_cast<Inset *>(inset),
2628 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2634 void Paragraph::checkAuthors(AuthorList const & authorList)
2636 d->changes_.checkAuthors(authorList);
2640 bool Paragraph::isUnchanged(pos_type pos) const
2642 return lookupChange(pos).type == Change::UNCHANGED;
2646 bool Paragraph::isInserted(pos_type pos) const
2648 return lookupChange(pos).type == Change::INSERTED;
2652 bool Paragraph::isDeleted(pos_type pos) const
2654 return lookupChange(pos).type == Change::DELETED;
2658 InsetList const & Paragraph::insetList() const
2660 return d->insetlist_;
2664 void Paragraph::setBuffer(Buffer & b)
2666 d->insetlist_.setBuffer(b);
2670 Inset * Paragraph::releaseInset(pos_type pos)
2672 Inset * inset = d->insetlist_.release(pos);
2673 /// does not honour change tracking!
2674 eraseChar(pos, false);
2679 Inset * Paragraph::getInset(pos_type pos)
2681 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2682 ? d->insetlist_.get(pos) : 0;
2686 Inset const * Paragraph::getInset(pos_type pos) const
2688 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2689 ? d->insetlist_.get(pos) : 0;
2693 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2694 pos_type & right, TextCase action)
2696 // process sequences of modified characters; in change
2697 // tracking mode, this approach results in much better
2698 // usability than changing case on a char-by-char basis
2701 bool const trackChanges = bparams.trackChanges;
2703 bool capitalize = true;
2705 for (; pos < right; ++pos) {
2706 char_type oldChar = d->text_[pos];
2707 char_type newChar = oldChar;
2709 // ignore insets and don't play with deleted text!
2710 if (oldChar != META_INSET && !isDeleted(pos)) {
2712 case text_lowercase:
2713 newChar = lowercase(oldChar);
2715 case text_capitalization:
2717 newChar = uppercase(oldChar);
2721 case text_uppercase:
2722 newChar = uppercase(oldChar);
2727 if (!isLetter(pos) || isDeleted(pos)) {
2728 // permit capitalization again
2732 if (oldChar != newChar)
2735 if (oldChar == newChar || pos == right - 1) {
2736 if (oldChar != newChar) {
2737 // step behind the changing area
2740 int erasePos = pos - changes.size();
2741 for (size_t i = 0; i < changes.size(); i++) {
2742 insertChar(pos, changes[i],
2743 getFontSettings(bparams,
2746 if (!eraseChar(erasePos, trackChanges)) {
2749 ++right; // expand selection
2758 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2759 pos_type pos, bool del) const
2761 int const strsize = str.length();
2763 pos_type const parsize = d->text_.size();
2764 for (i = 0; pos + i < parsize; ++i) {
2767 if (cs && str[i] != d->text_[pos + i])
2769 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2771 if (!del && isDeleted(pos + i))
2778 // if necessary, check whether string matches word
2780 if (pos > 0 && isLetter(pos - 1))
2782 if (pos + strsize < parsize
2783 && isLetter(pos + strsize))
2791 char_type Paragraph::getChar(pos_type pos) const
2793 return d->text_[pos];
2797 pos_type Paragraph::size() const
2799 return d->text_.size();
2803 bool Paragraph::empty() const
2805 return d->text_.empty();
2809 bool Paragraph::isInset(pos_type pos) const
2811 return d->text_[pos] == META_INSET;
2815 bool Paragraph::isSeparator(pos_type pos) const
2817 //FIXME: Are we sure this can be the only separator?
2818 return d->text_[pos] == ' ';
2822 void Paragraph::deregisterWords()
2824 Private::Words::const_iterator it;
2825 WordList & wl = theWordList();
2826 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2832 void Paragraph::collectWords(CursorSlice const & sl)
2835 bool inword = false;
2837 //lyxerr << "Words: ";
2838 pos_type n = size();
2839 for (pos_type pos = 0; pos != n; ++pos) {
2843 if (!isLetter(pos)) {
2852 CursorSlice from = sl;
2853 CursorSlice to = sl;
2856 from.text()->getWord(from, to, WHOLE_WORD);
2857 if (to.pos() - from.pos() < 6)
2859 docstring word = asString(from.pos(), to.pos(), false);
2860 d->words_.insert(word);
2861 //lyxerr << word << " ";
2863 //lyxerr << std::endl;
2867 void Paragraph::registerWords()
2869 Private::Words::const_iterator it;
2870 WordList & wl = theWordList();
2871 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2876 void Paragraph::updateWords(CursorSlice const & sl)
2878 LASSERT(&sl.paragraph() == this, /**/);