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 bool Paragraph::isChanged(pos_type start, pos_type end) const
284 LASSERT(start >= 0 && start <= size(), /**/);
285 LASSERT(end > start && end <= size() + 1, /**/);
287 return d->changes_.isChanged(start, end);
291 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
293 // keep the logic here in sync with the logic of eraseChars()
297 Change const change = d->changes_.lookup(size());
298 return change.type == Change::INSERTED && change.author == 0;
302 void Paragraph::setChange(Change const & change)
304 // beware of the imaginary end-of-par character!
305 d->changes_.set(change, 0, size() + 1);
308 * Propagate the change recursively - but not in case of DELETED!
310 * Imagine that your co-author makes changes in an existing inset. He
311 * sends your document to you and you come to the conclusion that the
312 * inset should go completely. If you erase it, LyX must not delete all
313 * text within the inset. Otherwise, the change tracked insertions of
314 * your co-author get lost and there is no way to restore them later.
316 * Conclusion: An inset's content should remain untouched if you delete it
319 if (change.type != Change::DELETED) {
320 for (pos_type pos = 0; pos < size(); ++pos) {
321 if (Inset * inset = getInset(pos))
322 inset->setChange(change);
328 void Paragraph::setChange(pos_type pos, Change const & change)
330 LASSERT(pos >= 0 && pos <= size(), /**/);
331 d->changes_.set(change, pos);
333 // see comment in setChange(Change const &) above
334 if (change.type != Change::DELETED && pos < size())
335 if (Inset * inset = getInset(pos))
336 inset->setChange(change);
340 Change const & Paragraph::lookupChange(pos_type pos) const
342 LASSERT(pos >= 0 && pos <= size(), /**/);
343 return d->changes_.lookup(pos);
347 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
350 LASSERT(start >= 0 && start <= size(), /**/);
351 LASSERT(end > start && end <= size() + 1, /**/);
353 for (pos_type pos = start; pos < end; ++pos) {
354 switch (lookupChange(pos).type) {
355 case Change::UNCHANGED:
356 // accept changes in nested inset
357 if (Inset * inset = getInset(pos))
358 inset->acceptChanges(bparams);
361 case Change::INSERTED:
362 d->changes_.set(Change(Change::UNCHANGED), pos);
363 // also accept changes in nested inset
364 if (Inset * inset = getInset(pos))
365 inset->acceptChanges(bparams);
368 case Change::DELETED:
369 // Suppress access to non-existent
370 // "end-of-paragraph char"
372 eraseChar(pos, false);
383 void Paragraph::rejectChanges(BufferParams const & bparams,
384 pos_type start, pos_type end)
386 LASSERT(start >= 0 && start <= size(), /**/);
387 LASSERT(end > start && end <= size() + 1, /**/);
389 for (pos_type pos = start; pos < end; ++pos) {
390 switch (lookupChange(pos).type) {
391 case Change::UNCHANGED:
392 // reject changes in nested inset
393 if (Inset * inset = getInset(pos))
394 inset->rejectChanges(bparams);
397 case Change::INSERTED:
398 // Suppress access to non-existent
399 // "end-of-paragraph char"
401 eraseChar(pos, false);
407 case Change::DELETED:
408 d->changes_.set(Change(Change::UNCHANGED), pos);
410 // Do NOT reject changes within a deleted inset!
411 // There may be insertions of a co-author inside of it!
419 void Paragraph::Private::insertChar(pos_type pos, char_type c,
420 Change const & change)
422 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
425 changes_.insert(change, pos);
427 // This is actually very common when parsing buffers (and
428 // maybe inserting ascii text)
429 if (pos == pos_type(text_.size())) {
430 // when appending characters, no need to update tables
435 text_.insert(text_.begin() + pos, c);
437 // Update the font table.
438 fontlist_.increasePosAfterPos(pos);
441 insetlist_.increasePosAfterPos(pos);
445 void Paragraph::insertInset(pos_type pos, Inset * inset,
446 Change const & change)
448 LASSERT(inset, /**/);
449 LASSERT(pos >= 0 && pos <= size(), /**/);
451 d->insertChar(pos, META_INSET, change);
452 LASSERT(d->text_[pos] == META_INSET, /**/);
454 // Add a new entry in the insetlist_.
455 d->insetlist_.insert(inset, pos);
459 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
461 LASSERT(pos >= 0 && pos <= size(), return false);
463 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
466 Change change = d->changes_.lookup(pos);
468 // set the character to DELETED if
469 // a) it was previously unchanged or
470 // b) it was inserted by a co-author
472 if (change.type == Change::UNCHANGED ||
473 (change.type == Change::INSERTED && change.author != 0)) {
474 setChange(pos, Change(Change::DELETED));
478 if (change.type == Change::DELETED)
482 // Don't physically access the imaginary end-of-paragraph character.
483 // eraseChar() can only mark it as DELETED. A physical deletion of
484 // end-of-par must be handled externally.
490 d->changes_.erase(pos);
492 // if it is an inset, delete the inset entry
493 if (d->text_[pos] == META_INSET)
494 d->insetlist_.erase(pos);
496 d->text_.erase(d->text_.begin() + pos);
498 // Update the fontlist_
499 d->fontlist_.erase(pos);
501 // Update the insetlist_
502 d->insetlist_.decreasePosAfterPos(pos);
508 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
510 LASSERT(start >= 0 && start <= size(), /**/);
511 LASSERT(end >= start && end <= size() + 1, /**/);
514 for (pos_type count = end - start; count; --count) {
515 if (!eraseChar(i, trackChanges))
522 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
523 char_type next, Encoding const & encoding)
525 // Writing next here may circumvent a possible font change between
526 // c and next. Since next is only output if it forms a surrogate pair
527 // with c we can ignore this:
528 // A font change inside a surrogate pair does not make sense and is
529 // hopefully impossible to input.
530 // FIXME: change tracking
531 // Is this correct WRT change tracking?
532 docstring const latex1 = encoding.latexChar(next);
533 docstring const latex2 = encoding.latexChar(c);
534 if (docstring(1, next) == latex1) {
535 // the encoding supports the combination
536 os << latex2 << latex1;
537 return latex1.length() + latex2.length();
539 os << latex1 << '{' << latex2 << '}';
540 return latex1.length() + latex2.length() + 2;
544 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
545 odocstream & os, TexRow & texrow,
547 unsigned int & column,
549 Layout const & style)
551 if (style.pass_thru || runparams.verbatim)
554 if (i + 1 < int(text_.size())) {
555 char_type next = text_[i + 1];
556 if (Encodings::isCombiningChar(next)) {
557 Encoding const & encoding = *(runparams.encoding);
558 // This space has an accent, so we must always output it.
559 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
564 if (lyxrc.plaintext_linelen > 0
565 && column > lyxrc.plaintext_linelen
567 && text_[i - 1] != ' '
568 && (i + 1 < int(text_.size()))
569 // same in FreeSpacing mode
570 && !owner_->isFreeSpacing()
571 // In typewriter mode, we want to avoid
572 // ! . ? : at the end of a line
573 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
574 && (text_[i - 1] == '.'
575 || text_[i - 1] == '?'
576 || text_[i - 1] == ':'
577 || text_[i - 1] == '!'))) {
580 texrow.start(owner_->id(), i + 1);
582 } else if (style.free_spacing) {
591 int Paragraph::Private::writeScriptChars(odocstream & os,
592 docstring const & ltx,
593 Change & runningChange,
594 Encoding const & encoding,
597 // FIXME: modifying i here is not very nice...
599 // We only arrive here when a proper language for character text_[i] has
600 // not been specified (i.e., it could not be translated in the current
601 // latex encoding) or its latex translation has been forced, and it
602 // belongs to a known script.
603 // Parameter ltx contains the latex translation of text_[i] as specified
604 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
605 // The latex macro name "textXXX" specifies the script to which text_[i]
606 // belongs and we use it in order to check whether characters from the
607 // same script immediately follow, such that we can collect them in a
608 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
609 // for the first char but only "<spec>" for all subsequent chars.
610 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
611 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
612 string script = to_ascii(ltx.substr(1, brace1 - 1));
615 bool closing_brace = true;
616 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
617 // Correct encoding is being used, so we can avoid \textgreek.
620 closing_brace = false;
622 os << ltx.substr(pos, length);
623 int size = text_.size();
624 while (i + 1 < size) {
625 char_type const next = text_[i + 1];
626 // Stop here if next character belongs to another script
627 // or there is a change in change tracking status.
628 if (!Encodings::isKnownScriptChar(next, script) ||
629 runningChange != owner_->lookupChange(i + 1))
633 FontList::const_iterator cit = fontlist_.begin();
634 FontList::const_iterator end = fontlist_.end();
635 for (; cit != end; ++cit) {
636 if (cit->pos() >= i && !found) {
637 prev_font = cit->font();
640 if (cit->pos() >= i + 1)
643 // Stop here if there is a font attribute or encoding change.
644 if (found && cit != end && prev_font != cit->font())
646 docstring const latex = encoding.latexChar(next);
647 docstring::size_type const b1 =
648 latex.find_first_of(from_ascii("{"));
649 docstring::size_type const b2 =
650 latex.find_last_of(from_ascii("}"));
651 int const len = b2 - b1 - 1;
652 os << latex.substr(b1 + 1, len);
664 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
666 pos_type const len = str.length();
668 // is the paragraph large enough?
669 if (pos + len > int(text_.size()))
672 // does the wanted text start at point?
673 for (string::size_type i = 0; i < str.length(); ++i) {
674 // Caution: direct comparison of characters works only
675 // because str is pure ASCII.
676 if (str[i] != text_[pos + i])
680 return fontlist_.hasChangeInRange(pos, len);
684 void Paragraph::Private::latexInset(
685 BufferParams const & bparams,
688 OutputParams & runparams,
691 Font const & outerfont,
693 Change & running_change,
694 Layout const & style,
696 unsigned int & column)
698 Inset * inset = owner_->getInset(i);
699 LASSERT(inset, /**/);
701 if (style.pass_thru) {
702 inset->plaintext(os, runparams);
706 // FIXME: move this to InsetNewline::latex
707 if (inset->lyxCode() == NEWLINE_CODE) {
708 // newlines are handled differently here than
709 // the default in simpleTeXSpecialChars().
710 if (!style.newline_allowed) {
714 column += running_font.latexWriteEndChanges(
715 os, bparams, runparams,
720 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
723 basefont = owner_->getLayoutFont(bparams, outerfont);
724 running_font = basefont;
726 if (runparams.moving_arg)
731 texrow.start(owner_->id(), i + 1);
735 if (owner_->lookupChange(i).type == Change::DELETED) {
736 if( ++runparams.inDeletedInset == 1)
737 runparams.changeOfDeletedInset = owner_->lookupChange(i);
740 if (inset->canTrackChanges()) {
741 column += Changes::latexMarkChange(os, bparams, running_change,
742 Change(Change::UNCHANGED));
743 running_change = Change(Change::UNCHANGED);
747 odocstream::pos_type const len = os.tellp();
749 if (inset->forceLTR()
750 && running_font.isRightToLeft()
751 // ERT is an exception, it should be output with no decorations at all
752 && inset->lyxCode() != ERT_CODE) {
753 if (running_font.language()->lang() == "farsi")
760 // FIXME: Bug: we can have an empty font change here!
761 // if there has just been a font change, we are going to close it
762 // right now, which means stupid latex code like \textsf{}. AFAIK,
763 // this does not harm dvi output. A minor bug, thus (JMarc)
765 // Some insets cannot be inside a font change command.
766 // However, even such insets *can* be placed in \L or \R
767 // or their equivalents (for RTL language switches), so we don't
768 // close the language in those cases.
769 // ArabTeX, though, cannot handle this special behavior, it seems.
770 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
771 || running_font.language()->lang() == "arabic_arabtex";
772 if (open_font && inset->noFontChange()) {
773 bool closeLanguage = arabtex
774 || basefont.isRightToLeft() == running_font.isRightToLeft();
775 unsigned int count = running_font.latexWriteEndChanges(os,
776 bparams, runparams, basefont, basefont, closeLanguage);
778 // if any font properties were closed, update the running_font,
779 // making sure, however, to leave the language as it was
781 // FIXME: probably a better way to keep track of the old
782 // language, than copying the entire font?
783 Font const copy_font(running_font);
784 basefont = owner_->getLayoutFont(bparams, outerfont);
785 running_font = basefont;
787 running_font.setLanguage(copy_font.language());
788 // leave font open if language is still open
789 open_font = (running_font.language() == basefont.language());
791 runparams.local_font = &basefont;
798 tmp = inset->latex(os, runparams);
799 } catch (EncodingException & e) {
800 // add location information and throw again.
807 if (running_font.language()->lang() == "farsi")
814 for (int j = 0; j < tmp; ++j)
817 texrow.start(owner_->id(), i + 1);
820 column += os.tellp() - len;
823 if (owner_->lookupChange(i).type == Change::DELETED)
824 --runparams.inDeletedInset;
828 void Paragraph::Private::latexSpecialChar(
830 OutputParams & runparams,
832 Change & running_change,
833 Layout const & style,
835 unsigned int & column)
837 char_type const c = text_[i];
839 if (style.pass_thru) {
841 // FIXME UNICODE: This can fail if c cannot
842 // be encoded in the current encoding.
847 if (runparams.verbatim) {
848 // FIXME UNICODE: This can fail if c cannot
849 // be encoded in the current encoding.
854 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
857 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
858 && latexSpecialTypewriter(c, os, i, column))
861 // Otherwise, we use what LaTeX provides us.
864 os << "\\textbackslash{}";
868 os << "\\textless{}";
872 os << "\\textgreater{}";
883 os << "\\char`\\\"{}";
888 case '%': case '#': case '{':
896 os << "\\textasciitilde{}";
901 os << "\\textasciicircum{}";
906 // avoid being mistaken for optional arguments
914 // Blanks are printed before font switching.
915 // Sure? I am not! (try nice-latex)
916 // I am sure it's correct. LyX might be smarter
917 // in the future, but for now, nothing wrong is
923 if (latexSpecialPhrase(os, i, column, runparams))
929 Encoding const & encoding = *(runparams.encoding);
930 if (i + 1 < int(text_.size())) {
931 char_type next = text_[i + 1];
932 if (Encodings::isCombiningChar(next)) {
933 column += latexSurrogatePair(os, c, next, encoding) - 1;
939 docstring const latex = encoding.latexChar(c);
940 if (Encodings::isKnownScriptChar(c, script)
941 && prefixIs(latex, from_ascii("\\" + script)))
942 column += writeScriptChars(os, latex,
943 running_change, encoding, i) - 1;
944 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
945 // Prevent eating of a following
946 // space or command corruption by
947 // following characters
948 column += latex.length() + 1;
951 column += latex.length() - 1;
959 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
960 pos_type & i, unsigned int & column)
966 // In T1 encoding, these characters exist
967 // but we should avoid ligatures
968 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
970 os << "\\textcompwordmark{}";
977 // soul.sty breaks with \char`\"
978 os << "\\textquotedbl{}";
987 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
988 pos_type & i, unsigned int & column)
992 // within \ttfamily, "--" is merged to "-" (no endash)
993 // so we avoid this rather irritating ligature
994 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1001 // everything else has to be checked separately
1002 // (depending on the encoding)
1009 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1010 unsigned int & column, OutputParams & runparams)
1012 // FIXME: if we have "LaTeX" with a font
1013 // change in the middle (before the 'T', then
1014 // the "TeX" part is still special cased.
1015 // Really we should only operate this on
1016 // "words" for some definition of word
1018 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1019 if (!isTextAt(special_phrases[pnr].phrase, i))
1021 if (runparams.moving_arg)
1023 os << special_phrases[pnr].macro;
1024 i += special_phrases[pnr].phrase.length() - 1;
1025 column += special_phrases[pnr].macro.length() - 1;
1032 void Paragraph::Private::validate(LaTeXFeatures & features,
1033 Layout const & layout) const
1035 // check the params.
1036 if (!params_.spacing().isDefault())
1037 features.require("setspace");
1040 features.useLayout(layout.name());
1043 fontlist_.validate(features);
1045 // then the indentation
1046 if (!params_.leftIndent().zero())
1047 features.require("ParagraphLeftIndent");
1050 InsetList::const_iterator icit = insetlist_.begin();
1051 InsetList::const_iterator iend = insetlist_.end();
1052 for (; icit != iend; ++icit) {
1054 icit->inset->validate(features);
1055 if (layout.needprotect &&
1056 icit->inset->lyxCode() == FOOT_CODE)
1057 features.require("NeedLyXFootnoteCode");
1061 // then the contents
1062 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1063 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1064 if (!special_phrases[pnr].builtin
1065 && isTextAt(special_phrases[pnr].phrase, i)) {
1066 features.require(special_phrases[pnr].phrase);
1070 Encodings::validate(text_[i], features);
1074 /////////////////////////////////////////////////////////////////////
1078 /////////////////////////////////////////////////////////////////////
1081 Layout const emptyParagraphLayout;
1084 Paragraph::Paragraph()
1085 : d(new Paragraph::Private(this, emptyParagraphLayout))
1092 Paragraph::Paragraph(Paragraph const & par)
1093 : itemdepth(par.itemdepth),
1094 d(new Paragraph::Private(*par.d, this))
1100 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1101 : itemdepth(par.itemdepth),
1102 d(new Paragraph::Private(*par.d, this, beg, end))
1108 Paragraph & Paragraph::operator=(Paragraph const & par)
1110 // needed as we will destroy the private part before copying it
1112 itemdepth = par.itemdepth;
1116 d = new Private(*par.d, this);
1123 Paragraph::~Paragraph()
1130 void Paragraph::write(ostream & os, BufferParams const & bparams,
1131 depth_type & dth) const
1133 // The beginning or end of a deeper (i.e. nested) area?
1134 if (dth != d->params_.depth()) {
1135 if (d->params_.depth() > dth) {
1136 while (d->params_.depth() > dth) {
1137 os << "\n\\begin_deeper";
1141 while (d->params_.depth() < dth) {
1142 os << "\n\\end_deeper";
1148 // First write the layout
1149 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1151 d->params_.write(os);
1153 Font font1(inherit_font, bparams.language);
1155 Change running_change = Change(Change::UNCHANGED);
1158 for (pos_type i = 0; i <= size(); ++i) {
1160 Change change = lookupChange(i);
1161 Changes::lyxMarkChange(os, column, running_change, change);
1162 running_change = change;
1167 // Write font changes
1168 Font font2 = getFontSettings(bparams, i);
1169 if (font2 != font1) {
1170 font2.lyxWriteChanges(font1, os);
1175 char_type const c = d->text_[i];
1178 if (Inset const * inset = getInset(i)) {
1179 if (inset->directWrite()) {
1180 // international char, let it write
1181 // code directly so it's shorter in
1187 os << "\\begin_inset ";
1189 os << "\n\\end_inset\n\n";
1195 os << "\n\\backslash\n";
1199 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1206 if ((column > 70 && c == ' ')
1211 // this check is to amend a bug. LyX sometimes
1212 // inserts '\0' this could cause problems.
1214 os << to_utf8(docstring(1, c));
1216 LYXERR0("NUL char in structure.");
1222 os << "\n\\end_layout\n";
1226 void Paragraph::validate(LaTeXFeatures & features) const
1228 d->validate(features, *d->layout_);
1232 void Paragraph::insert(pos_type start, docstring const & str,
1233 Font const & font, Change const & change)
1235 for (size_t i = 0, n = str.size(); i != n ; ++i)
1236 insertChar(start + i, str[i], font, change);
1240 void Paragraph::appendChar(char_type c, Font const & font,
1241 Change const & change)
1244 d->changes_.insert(change, d->text_.size());
1245 // when appending characters, no need to update tables
1246 d->text_.push_back(c);
1247 setFont(d->text_.size() - 1, font);
1251 void Paragraph::appendString(docstring const & s, Font const & font,
1252 Change const & change)
1254 pos_type end = s.size();
1255 size_t oldsize = d->text_.size();
1256 size_t newsize = oldsize + end;
1257 size_t capacity = d->text_.capacity();
1258 if (newsize >= capacity)
1259 d->text_.reserve(max(capacity + 100, newsize));
1261 // when appending characters, no need to update tables
1264 // FIXME: Optimize this!
1265 for (pos_type i = oldsize; i != newsize; ++i) {
1267 d->changes_.insert(change, i);
1269 d->fontlist_.set(oldsize, font);
1270 d->fontlist_.set(newsize - 1, font);
1274 void Paragraph::insertChar(pos_type pos, char_type c,
1277 d->insertChar(pos, c, Change(trackChanges ?
1278 Change::INSERTED : Change::UNCHANGED));
1282 void Paragraph::insertChar(pos_type pos, char_type c,
1283 Font const & font, bool trackChanges)
1285 d->insertChar(pos, c, Change(trackChanges ?
1286 Change::INSERTED : Change::UNCHANGED));
1291 void Paragraph::insertChar(pos_type pos, char_type c,
1292 Font const & font, Change const & change)
1294 d->insertChar(pos, c, change);
1299 void Paragraph::insertInset(pos_type pos, Inset * inset,
1300 Font const & font, Change const & change)
1302 insertInset(pos, inset, change);
1303 // Set the font/language of the inset...
1308 void Paragraph::resetFonts(Font const & font)
1310 d->fontlist_.clear();
1311 d->fontlist_.set(0, font);
1312 d->fontlist_.set(d->text_.size() - 1, font);
1315 // Gets uninstantiated font setting at position.
1316 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1320 LYXERR0("pos: " << pos << " size: " << size());
1321 LASSERT(pos <= size(), /**/);
1324 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1325 if (cit != d->fontlist_.end())
1328 if (pos == size() && !empty())
1329 return getFontSettings(bparams, pos - 1);
1331 return Font(inherit_font, getParLanguage(bparams));
1335 FontSpan Paragraph::fontSpan(pos_type pos) const
1337 LASSERT(pos <= size(), /**/);
1340 FontList::const_iterator cit = d->fontlist_.begin();
1341 FontList::const_iterator end = d->fontlist_.end();
1342 for (; cit != end; ++cit) {
1343 if (cit->pos() >= pos) {
1344 if (pos >= beginOfBody())
1345 return FontSpan(max(start, beginOfBody()),
1348 return FontSpan(start,
1349 min(beginOfBody() - 1,
1352 start = cit->pos() + 1;
1355 // This should not happen, but if so, we take no chances.
1356 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1357 return FontSpan(pos, pos);
1361 // Gets uninstantiated font setting at position 0
1362 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1364 if (!empty() && !d->fontlist_.empty())
1365 return d->fontlist_.begin()->font();
1367 return Font(inherit_font, bparams.language);
1371 // Gets the fully instantiated font at a given position in a paragraph
1372 // This is basically the same function as Text::GetFont() in text2.cpp.
1373 // The difference is that this one is used for generating the LaTeX file,
1374 // and thus cosmetic "improvements" are disallowed: This has to deliver
1375 // the true picture of the buffer. (Asger)
1376 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1377 Font const & outerfont) const
1379 LASSERT(pos >= 0, /**/);
1381 Font font = getFontSettings(bparams, pos);
1383 pos_type const body_pos = beginOfBody();
1385 font.fontInfo().realize(d->layout_->labelfont);
1387 font.fontInfo().realize(d->layout_->font);
1389 font.fontInfo().realize(outerfont.fontInfo());
1390 font.fontInfo().realize(bparams.getFont().fontInfo());
1396 Font const Paragraph::getLabelFont
1397 (BufferParams const & bparams, Font const & outerfont) const
1399 FontInfo tmpfont = d->layout_->labelfont;
1400 tmpfont.realize(outerfont.fontInfo());
1401 tmpfont.realize(bparams.getFont().fontInfo());
1402 return Font(tmpfont, getParLanguage(bparams));
1406 Font const Paragraph::getLayoutFont
1407 (BufferParams const & bparams, Font const & outerfont) const
1409 FontInfo tmpfont = d->layout_->font;
1410 tmpfont.realize(outerfont.fontInfo());
1411 tmpfont.realize(bparams.getFont().fontInfo());
1412 return Font(tmpfont, getParLanguage(bparams));
1416 /// Returns the height of the highest font in range
1417 FontSize Paragraph::highestFontInRange
1418 (pos_type startpos, pos_type endpos, FontSize def_size) const
1420 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1424 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1426 char_type c = d->text_[pos];
1427 if (!lyxrc.rtl_support)
1457 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1463 void Paragraph::setFont(pos_type pos, Font const & font)
1465 LASSERT(pos <= size(), /**/);
1467 // First, reduce font against layout/label font
1468 // Update: The setCharFont() routine in text2.cpp already
1469 // reduces font, so we don't need to do that here. (Asger)
1471 d->fontlist_.set(pos, font);
1475 void Paragraph::makeSameLayout(Paragraph const & par)
1477 d->layout_ = par.d->layout_;
1478 d->params_ = par.d->params_;
1482 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1484 if (isFreeSpacing())
1490 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1491 if (eraseChar(pos, trackChanges))
1497 return count > 0 || pos > 0;
1501 bool Paragraph::hasSameLayout(Paragraph const & par) const
1503 return par.d->layout_ == d->layout_
1504 && d->params_.sameLayout(par.d->params_);
1508 depth_type Paragraph::getDepth() const
1510 return d->params_.depth();
1514 depth_type Paragraph::getMaxDepthAfter() const
1516 if (d->layout_->isEnvironment())
1517 return d->params_.depth() + 1;
1519 return d->params_.depth();
1523 char Paragraph::getAlign() const
1525 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1526 return d->layout_->align;
1528 return d->params_.align();
1532 docstring const & Paragraph::labelString() const
1534 return d->params_.labelString();
1538 // the next two functions are for the manual labels
1539 docstring const Paragraph::getLabelWidthString() const
1541 if (d->layout_->margintype == MARGIN_MANUAL)
1542 return d->params_.labelWidthString();
1544 return _("Senseless with this layout!");
1548 void Paragraph::setLabelWidthString(docstring const & s)
1550 d->params_.labelWidthString(s);
1554 docstring const Paragraph::translateIfPossible(docstring const & s,
1555 BufferParams const & bparams) const
1557 if (!isAscii(s) || s.empty()) {
1558 // This must be a user defined layout. We cannot translate
1559 // this, since gettext accepts only ascii keys.
1562 // Probably standard layout, try to translate
1563 Messages & m = getMessages(getParLanguage(bparams)->code());
1564 return m.get(to_ascii(s));
1568 docstring Paragraph::expandLabel(Layout const & layout,
1569 BufferParams const & bparams, bool process_appendix) const
1571 DocumentClass const & tclass = bparams.documentClass();
1574 if (process_appendix && d->params_.appendix())
1575 fmt = translateIfPossible(layout.labelstring_appendix(),
1578 fmt = translateIfPossible(layout.labelstring(), bparams);
1580 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1581 && !layout.counter.empty())
1582 fmt = "\\the" + layout.counter;
1584 // handle 'inherited level parts' in 'fmt',
1585 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1586 size_t const i = fmt.find('@', 0);
1587 if (i != docstring::npos) {
1588 size_t const j = fmt.find('@', i + 1);
1589 if (j != docstring::npos) {
1590 docstring parent(fmt, i + 1, j - i - 1);
1591 docstring label = from_ascii("??");
1592 if (tclass.hasLayout(parent))
1593 docstring label = expandLabel(tclass[parent], bparams,
1595 fmt = docstring(fmt, 0, i) + label
1596 + docstring(fmt, j + 1, docstring::npos);
1600 return tclass.counters().counterLabel(fmt);
1604 void Paragraph::applyLayout(Layout const & new_layout)
1606 d->layout_ = &new_layout;
1607 LyXAlignment const oldAlign = d->params_.align();
1609 if (!(oldAlign & d->layout_->alignpossible)) {
1610 frontend::Alert::warning(_("Alignment not permitted"),
1611 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1612 d->params_.align(LYX_ALIGN_LAYOUT);
1617 pos_type Paragraph::beginOfBody() const
1619 return d->begin_of_body_;
1623 void Paragraph::setBeginOfBody()
1625 if (d->layout_->labeltype != LABEL_MANUAL) {
1626 d->begin_of_body_ = 0;
1630 // Unroll the first two cycles of the loop
1631 // and remember the previous character to
1632 // remove unnecessary getChar() calls
1634 pos_type end = size();
1635 if (i < end && !isNewline(i)) {
1637 char_type previous_char = 0;
1640 previous_char = d->text_[i];
1641 if (!isNewline(i)) {
1643 while (i < end && previous_char != ' ') {
1648 previous_char = temp;
1654 d->begin_of_body_ = i;
1658 bool Paragraph::forcePlainLayout() const
1660 return inInset().forcePlainLayout();
1664 bool Paragraph::allowParagraphCustomization() const
1666 return inInset().allowParagraphCustomization();
1670 bool Paragraph::usePlainLayout() const
1672 return inInset().usePlainLayout();
1678 // paragraphs inside floats need different alignment tags to avoid
1681 bool noTrivlistCentering(InsetCode code)
1683 return code == FLOAT_CODE
1684 || code == WRAP_CODE
1685 || code == CELL_CODE;
1689 string correction(string const & orig)
1691 if (orig == "flushleft")
1692 return "raggedright";
1693 if (orig == "flushright")
1694 return "raggedleft";
1695 if (orig == "center")
1701 string const corrected_env(string const & suffix, string const & env,
1702 InsetCode code, bool const lastpar)
1704 string output = suffix + "{";
1705 if (noTrivlistCentering(code)) {
1707 // the last paragraph in non-trivlist-aligned
1708 // context is special (to avoid unwanted whitespace)
1709 if (suffix == "\\begin")
1710 return "\\" + correction(env) + "{}";
1713 output += correction(env);
1717 if (suffix == "\\begin")
1723 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1725 if (!contains(str, "\n"))
1726 column += str.size();
1730 column = rsplit(str, tmp, '\n').size();
1737 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1738 odocstream & os, TexRow & texrow,
1739 OutputParams const & runparams) const
1743 if (params_.noindent()) {
1744 os << "\\noindent ";
1748 LyXAlignment const curAlign = params_.align();
1750 if (curAlign == layout_->align)
1754 case LYX_ALIGN_NONE:
1755 case LYX_ALIGN_BLOCK:
1756 case LYX_ALIGN_LAYOUT:
1757 case LYX_ALIGN_SPECIAL:
1759 case LYX_ALIGN_LEFT:
1760 case LYX_ALIGN_RIGHT:
1761 case LYX_ALIGN_CENTER:
1762 if (runparams.moving_arg) {
1769 string const begin_tag = "\\begin";
1770 InsetCode code = owner_->ownerCode();
1771 bool const lastpar = runparams.isLastPar;
1774 case LYX_ALIGN_NONE:
1775 case LYX_ALIGN_BLOCK:
1776 case LYX_ALIGN_LAYOUT:
1777 case LYX_ALIGN_SPECIAL:
1779 case LYX_ALIGN_LEFT: {
1781 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1782 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1784 output = corrected_env(begin_tag, "flushright", code, lastpar);
1785 os << from_ascii(output);
1786 adjust_row_column(output, texrow, column);
1788 } case LYX_ALIGN_RIGHT: {
1790 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1791 output = corrected_env(begin_tag, "flushright", code, lastpar);
1793 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1794 os << from_ascii(output);
1795 adjust_row_column(output, texrow, column);
1797 } case LYX_ALIGN_CENTER: {
1799 output = corrected_env(begin_tag, "center", code, lastpar);
1800 os << from_ascii(output);
1801 adjust_row_column(output, texrow, column);
1810 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1811 odocstream & os, TexRow & texrow,
1812 OutputParams const & runparams) const
1816 switch (params_.align()) {
1817 case LYX_ALIGN_NONE:
1818 case LYX_ALIGN_BLOCK:
1819 case LYX_ALIGN_LAYOUT:
1820 case LYX_ALIGN_SPECIAL:
1822 case LYX_ALIGN_LEFT:
1823 case LYX_ALIGN_RIGHT:
1824 case LYX_ALIGN_CENTER:
1825 if (runparams.moving_arg) {
1832 string const end_tag = "\n\\par\\end";
1833 InsetCode code = owner_->ownerCode();
1834 bool const lastpar = runparams.isLastPar;
1836 switch (params_.align()) {
1837 case LYX_ALIGN_NONE:
1838 case LYX_ALIGN_BLOCK:
1839 case LYX_ALIGN_LAYOUT:
1840 case LYX_ALIGN_SPECIAL:
1842 case LYX_ALIGN_LEFT: {
1844 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1845 output = corrected_env(end_tag, "flushleft", code, lastpar);
1847 output = corrected_env(end_tag, "flushright", code, lastpar);
1848 os << from_ascii(output);
1849 adjust_row_column(output, texrow, column);
1851 } case LYX_ALIGN_RIGHT: {
1853 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1854 output = corrected_env(end_tag, "flushright", code, lastpar);
1856 output = corrected_env(end_tag, "flushleft", code, lastpar);
1857 os << from_ascii(output);
1858 adjust_row_column(output, texrow, column);
1860 } case LYX_ALIGN_CENTER: {
1862 output = corrected_env(end_tag, "center", code, lastpar);
1863 os << from_ascii(output);
1864 adjust_row_column(output, texrow, column);
1873 // This one spits out the text of the paragraph
1874 bool Paragraph::latex(BufferParams const & bparams,
1875 Font const & outerfont,
1876 odocstream & os, TexRow & texrow,
1877 OutputParams const & runparams) const
1879 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1881 bool return_value = false;
1883 bool asdefault = forcePlainLayout();
1885 Layout const & style = asdefault ?
1886 bparams.documentClass().plainLayout() :
1889 // Current base font for all inherited font changes, without any
1890 // change caused by an individual character, except for the language:
1891 // It is set to the language of the first character.
1892 // As long as we are in the label, this font is the base font of the
1893 // label. Before the first body character it is set to the base font
1897 // Maybe we have to create a optional argument.
1898 pos_type body_pos = beginOfBody();
1899 unsigned int column = 0;
1902 // the optional argument is kept in curly brackets in
1903 // case it contains a ']'
1906 basefont = getLabelFont(bparams, outerfont);
1908 basefont = getLayoutFont(bparams, outerfont);
1911 // Which font is currently active?
1912 Font running_font(basefont);
1913 // Do we have an open font change?
1914 bool open_font = false;
1916 Change runningChange = Change(Change::UNCHANGED);
1918 texrow.start(id(), 0);
1920 // if the paragraph is empty, the loop will not be entered at all
1922 if (style.isCommand()) {
1927 column += d->startTeXParParams(bparams, os, texrow,
1931 for (pos_type i = 0; i < size(); ++i) {
1932 // First char in paragraph or after label?
1933 if (i == body_pos) {
1936 column += running_font.latexWriteEndChanges(
1937 os, bparams, runparams,
1938 basefont, basefont);
1941 basefont = getLayoutFont(bparams, outerfont);
1942 running_font = basefont;
1944 column += Changes::latexMarkChange(os, bparams,
1945 runningChange, Change(Change::UNCHANGED));
1946 runningChange = Change(Change::UNCHANGED);
1951 if (style.isCommand()) {
1957 column += d->startTeXParParams(bparams, os,
1962 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1965 if (bparams.outputChanges && runningChange != change) {
1967 column += running_font.latexWriteEndChanges(
1968 os, bparams, runparams, basefont, basefont);
1971 basefont = getLayoutFont(bparams, outerfont);
1972 running_font = basefont;
1974 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1975 runningChange = change;
1978 // do not output text which is marked deleted
1979 // if change tracking output is disabled
1980 if (!bparams.outputChanges && change.type == Change::DELETED) {
1986 // Fully instantiated font
1987 Font const font = getFont(bparams, i, outerfont);
1989 Font const last_font = running_font;
1991 // Do we need to close the previous font?
1993 (font != running_font ||
1994 font.language() != running_font.language()))
1996 column += running_font.latexWriteEndChanges(
1997 os, bparams, runparams, basefont,
1998 (i == body_pos-1) ? basefont : font);
1999 running_font = basefont;
2003 // close babel's font environment before opening CJK.
2004 if (!running_font.language()->babel().empty() &&
2005 font.language()->encoding()->package() == Encoding::CJK) {
2006 string end_tag = subst(lyxrc.language_command_end,
2008 running_font.language()->babel());
2009 os << from_ascii(end_tag);
2010 column += end_tag.length();
2013 // Switch file encoding if necessary (and allowed)
2014 if (!runparams.verbatim &&
2015 runparams.encoding->package() != Encoding::none &&
2016 font.language()->encoding()->package() != Encoding::none) {
2017 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2018 runparams, *(font.language()->encoding()));
2019 if (enc_switch.first) {
2020 column += enc_switch.second;
2021 runparams.encoding = font.language()->encoding();
2025 char_type const c = d->text_[i];
2027 // Do we need to change font?
2028 if ((font != running_font ||
2029 font.language() != running_font.language()) &&
2032 odocstringstream ods;
2033 column += font.latexWriteStartChanges(ods, bparams,
2034 runparams, basefont,
2036 running_font = font;
2038 docstring fontchange = ods.str();
2039 // check if the fontchange ends with a trailing blank
2040 // (like "\small " (see bug 3382)
2041 if (suffixIs(fontchange, ' ') && c == ' ')
2042 os << fontchange.substr(0, fontchange.size() - 1)
2043 << from_ascii("{}");
2049 // FIXME: integrate this case in latexSpecialChar
2050 // Do not print the separation of the optional argument
2051 // if style.pass_thru is false. This works because
2052 // latexSpecialChar ignores spaces if
2053 // style.pass_thru is false.
2054 if (i != body_pos - 1) {
2055 if (d->simpleTeXBlanks(
2056 runparams, os, texrow,
2057 i, column, font, style)) {
2058 // A surrogate pair was output. We
2059 // must not call latexSpecialChar
2060 // in this iteration, since it would output
2061 // the combining character again.
2068 OutputParams rp = runparams;
2069 rp.free_spacing = style.free_spacing;
2070 rp.local_font = &font;
2071 rp.intitle = style.intitle;
2073 // Two major modes: LaTeX or plain
2074 // Handle here those cases common to both modes
2075 // and then split to handle the two modes separately.
2076 if (c == META_INSET)
2077 d->latexInset(bparams, os,
2078 texrow, rp, running_font,
2079 basefont, outerfont, open_font,
2080 runningChange, style, i, column);
2083 d->latexSpecialChar(os, rp, running_font, runningChange,
2085 } catch (EncodingException & e) {
2086 if (runparams.dryrun) {
2087 os << "<" << _("LyX Warning: ")
2088 << _("uncodable character") << " '";
2092 // add location information and throw again.
2100 // Set the encoding to that returned from latexSpecialChar (see
2101 // comment for encoding member in OutputParams.h)
2102 runparams.encoding = rp.encoding;
2105 // If we have an open font definition, we have to close it
2107 #ifdef FIXED_LANGUAGE_END_DETECTION
2110 .latexWriteEndChanges(os, bparams, runparams,
2112 next_->getFont(bparams, 0, outerfont));
2114 running_font.latexWriteEndChanges(os, bparams,
2115 runparams, basefont, basefont);
2118 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2119 //FIXME: there as we start another \selectlanguage with the next paragraph if
2120 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2121 running_font.latexWriteEndChanges(os, bparams, runparams,
2122 basefont, basefont);
2126 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2128 // Needed if there is an optional argument but no contents.
2129 if (body_pos > 0 && body_pos == size()) {
2131 return_value = false;
2135 column += d->endTeXParParams(bparams, os, texrow,
2139 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2140 return return_value;
2144 bool Paragraph::emptyTag() const
2146 for (pos_type i = 0; i < size(); ++i) {
2147 if (Inset const * inset = getInset(i)) {
2148 InsetCode lyx_code = inset->lyxCode();
2149 if (lyx_code != TOC_CODE &&
2150 lyx_code != INCLUDE_CODE &&
2151 lyx_code != GRAPHICS_CODE &&
2152 lyx_code != ERT_CODE &&
2153 lyx_code != LISTINGS_CODE &&
2154 lyx_code != FLOAT_CODE &&
2155 lyx_code != TABULAR_CODE) {
2159 char_type c = d->text_[i];
2160 if (c != ' ' && c != '\t')
2168 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2171 for (pos_type i = 0; i < size(); ++i) {
2172 if (Inset const * inset = getInset(i)) {
2173 InsetCode lyx_code = inset->lyxCode();
2174 if (lyx_code == LABEL_CODE) {
2175 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2176 docstring const & id = il->getParam("name");
2177 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2185 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2189 for (i = 0; i < size(); ++i) {
2190 if (Inset const * inset = getInset(i)) {
2191 inset->docbook(os, runparams);
2193 char_type c = d->text_[i];
2196 os << sgml::escapeChar(c);
2203 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2206 pos_type size = text_.size();
2207 for (pos_type i = initial; i < size; ++i) {
2208 Font font = owner_->getFont(buf.params(), i, outerfont);
2209 if (text_[i] == META_INSET)
2211 if (i != initial && font != font_old)
2220 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2222 OutputParams const & runparams,
2223 Font const & outerfont,
2224 pos_type initial) const
2226 bool emph_flag = false;
2228 Layout const & style = *d->layout_;
2230 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2232 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2235 // parsing main loop
2236 for (pos_type i = initial; i < size(); ++i) {
2237 Font font = getFont(buf.params(), i, outerfont);
2239 // handle <emphasis> tag
2240 if (font_old.emph() != font.fontInfo().emph()) {
2241 if (font.fontInfo().emph() == FONT_ON) {
2244 } else if (i != initial) {
2245 os << "</emphasis>";
2250 if (Inset const * inset = getInset(i)) {
2251 inset->docbook(os, runparams);
2253 char_type c = d->text_[i];
2255 if (style.pass_thru)
2258 os << sgml::escapeChar(c);
2260 font_old = font.fontInfo();
2264 os << "</emphasis>";
2267 if (style.free_spacing)
2269 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2274 bool Paragraph::isHfill(pos_type pos) const
2276 Inset const * inset = getInset(pos);
2277 return inset && (inset->lyxCode() == SPACE_CODE &&
2278 inset->isStretchableSpace());
2282 bool Paragraph::isNewline(pos_type pos) const
2284 Inset const * inset = getInset(pos);
2285 return inset && inset->lyxCode() == NEWLINE_CODE;
2289 bool Paragraph::isLineSeparator(pos_type pos) const
2291 char_type const c = d->text_[pos];
2292 if (isLineSeparatorChar(c))
2294 Inset const * inset = getInset(pos);
2295 return inset && inset->isLineSeparator();
2299 /// Used by the spellchecker
2300 bool Paragraph::isLetter(pos_type pos) const
2302 if (Inset const * inset = getInset(pos))
2303 return inset->isLetter();
2304 char_type const c = d->text_[pos];
2305 return isLetterChar(c) || isDigit(c);
2309 bool Paragraph::isChar(pos_type pos) const
2311 if (Inset const * inset = getInset(pos))
2312 return inset->isChar();
2313 char_type const c = d->text_[pos];
2314 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2318 bool Paragraph::isSpace(pos_type pos) const
2320 if (Inset const * inset = getInset(pos))
2321 return inset->isSpace();
2322 char_type const c = d->text_[pos];
2323 return lyx::isSpace(c);
2328 Paragraph::getParLanguage(BufferParams const & bparams) const
2331 return getFirstFontSettings(bparams).language();
2332 // FIXME: we should check the prev par as well (Lgb)
2333 return bparams.language;
2337 bool Paragraph::isRTL(BufferParams const & bparams) const
2339 return lyxrc.rtl_support
2340 && getParLanguage(bparams)->rightToLeft()
2341 && ownerCode() != ERT_CODE
2342 && ownerCode() != LISTINGS_CODE;
2346 void Paragraph::changeLanguage(BufferParams const & bparams,
2347 Language const * from, Language const * to)
2349 // change language including dummy font change at the end
2350 for (pos_type i = 0; i <= size(); ++i) {
2351 Font font = getFontSettings(bparams, i);
2352 if (font.language() == from) {
2353 font.setLanguage(to);
2360 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2362 Language const * doc_language = bparams.language;
2363 FontList::const_iterator cit = d->fontlist_.begin();
2364 FontList::const_iterator end = d->fontlist_.end();
2366 for (; cit != end; ++cit)
2367 if (cit->font().language() != ignore_language &&
2368 cit->font().language() != latex_language &&
2369 cit->font().language() != doc_language)
2375 docstring Paragraph::asString(int options) const
2377 return asString(0, size(), options);
2381 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2383 odocstringstream os;
2386 && options & AS_STR_LABEL
2387 && !d->params_.labelString().empty())
2388 os << d->params_.labelString() << ' ';
2390 for (pos_type i = beg; i < end; ++i) {
2391 char_type const c = d->text_[i];
2394 else if (c == META_INSET && options & AS_STR_INSETS)
2395 getInset(i)->textString(os);
2402 void Paragraph::setInsetOwner(Inset const * inset)
2404 d->inset_owner_ = inset;
2408 int Paragraph::id() const
2414 Layout const & Paragraph::layout() const
2420 void Paragraph::setLayout(Layout const & layout)
2422 d->layout_ = &layout;
2426 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2428 if (usePlainLayout())
2429 setLayout(tclass.plainLayout());
2431 setLayout(tclass.defaultLayout());
2435 Inset const & Paragraph::inInset() const
2437 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2438 _("Memory problem"), _("Paragraph not properly initiliazed")));
2439 return *d->inset_owner_;
2443 InsetCode Paragraph::ownerCode() const
2445 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2449 ParagraphParameters & Paragraph::params()
2455 ParagraphParameters const & Paragraph::params() const
2461 bool Paragraph::isFreeSpacing() const
2463 if (d->layout_->free_spacing)
2465 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2469 bool Paragraph::allowEmpty() const
2471 if (d->layout_->keepempty)
2473 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2477 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2479 if (!Encodings::isArabicChar(c))
2482 char_type prev_char = ' ';
2483 char_type next_char = ' ';
2485 for (pos_type i = pos - 1; i >= 0; --i) {
2486 char_type const par_char = d->text_[i];
2487 if (!Encodings::isArabicComposeChar(par_char)) {
2488 prev_char = par_char;
2493 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2494 char_type const par_char = d->text_[i];
2495 if (!Encodings::isArabicComposeChar(par_char)) {
2496 next_char = par_char;
2501 if (Encodings::isArabicChar(next_char)) {
2502 if (Encodings::isArabicChar(prev_char) &&
2503 !Encodings::isArabicSpecialChar(prev_char))
2504 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2506 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2508 if (Encodings::isArabicChar(prev_char) &&
2509 !Encodings::isArabicSpecialChar(prev_char))
2510 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2512 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2517 int Paragraph::checkBiblio(Buffer const & buffer)
2520 // This is getting more and more a mess. ...We really should clean
2521 // up this bibitem issue for 1.6. See also bug 2743.
2523 // Add bibitem insets if necessary
2524 if (d->layout_->labeltype != LABEL_BIBLIO)
2527 bool hasbibitem = !d->insetlist_.empty()
2528 // Insist on it being in pos 0
2529 && d->text_[0] == META_INSET
2530 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2532 bool track_changes = buffer.params().trackChanges;
2537 // remove a bibitem in pos != 0
2538 // restore it later in pos 0 if necessary
2539 // (e.g. if a user inserts contents _before_ the item)
2540 // we're assuming there's only one of these, which there
2542 int erasedInsetPosition = -1;
2543 InsetList::iterator it = d->insetlist_.begin();
2544 InsetList::iterator end = d->insetlist_.end();
2545 for (; it != end; ++it)
2546 if (it->inset->lyxCode() == BIBITEM_CODE
2548 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2549 oldkey = olditem->getParam("key");
2550 oldlabel = olditem->getParam("label");
2551 erasedInsetPosition = it->pos;
2552 eraseChar(erasedInsetPosition, track_changes);
2556 // There was an InsetBibitem at the beginning, and we didn't
2557 // have to erase one.
2558 if (hasbibitem && erasedInsetPosition < 0)
2561 // There was an InsetBibitem at the beginning and we did have to
2562 // erase one. So we give its properties to the beginning inset.
2564 InsetBibitem * inset =
2565 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2566 if (!oldkey.empty())
2567 inset->setParam("key", oldkey);
2568 inset->setParam("label", oldlabel);
2569 return -erasedInsetPosition;
2572 // There was no inset at the beginning, so we need to create one with
2573 // the key and label of the one we erased.
2574 InsetBibitem * inset =
2575 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2576 // restore values of previously deleted item in this par.
2577 if (!oldkey.empty())
2578 inset->setParam("key", oldkey);
2579 inset->setParam("label", oldlabel);
2580 insertInset(0, static_cast<Inset *>(inset),
2581 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2587 void Paragraph::checkAuthors(AuthorList const & authorList)
2589 d->changes_.checkAuthors(authorList);
2593 bool Paragraph::isUnchanged(pos_type pos) const
2595 return lookupChange(pos).type == Change::UNCHANGED;
2599 bool Paragraph::isInserted(pos_type pos) const
2601 return lookupChange(pos).type == Change::INSERTED;
2605 bool Paragraph::isDeleted(pos_type pos) const
2607 return lookupChange(pos).type == Change::DELETED;
2611 InsetList const & Paragraph::insetList() const
2613 return d->insetlist_;
2617 void Paragraph::setBuffer(Buffer & b)
2619 d->insetlist_.setBuffer(b);
2623 Inset * Paragraph::releaseInset(pos_type pos)
2625 Inset * inset = d->insetlist_.release(pos);
2626 /// does not honour change tracking!
2627 eraseChar(pos, false);
2632 Inset * Paragraph::getInset(pos_type pos)
2634 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2635 ? d->insetlist_.get(pos) : 0;
2639 Inset const * Paragraph::getInset(pos_type pos) const
2641 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2642 ? d->insetlist_.get(pos) : 0;
2646 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2647 pos_type & right, TextCase action)
2649 // process sequences of modified characters; in change
2650 // tracking mode, this approach results in much better
2651 // usability than changing case on a char-by-char basis
2654 bool const trackChanges = bparams.trackChanges;
2656 bool capitalize = true;
2658 for (; pos < right; ++pos) {
2659 char_type oldChar = d->text_[pos];
2660 char_type newChar = oldChar;
2662 // ignore insets and don't play with deleted text!
2663 if (oldChar != META_INSET && !isDeleted(pos)) {
2665 case text_lowercase:
2666 newChar = lowercase(oldChar);
2668 case text_capitalization:
2670 newChar = uppercase(oldChar);
2674 case text_uppercase:
2675 newChar = uppercase(oldChar);
2680 if (!isLetter(pos) || isDeleted(pos)) {
2681 // permit capitalization again
2685 if (oldChar != newChar)
2688 if (oldChar == newChar || pos == right - 1) {
2689 if (oldChar != newChar) {
2690 // step behind the changing area
2693 int erasePos = pos - changes.size();
2694 for (size_t i = 0; i < changes.size(); i++) {
2695 insertChar(pos, changes[i],
2696 getFontSettings(bparams,
2699 if (!eraseChar(erasePos, trackChanges)) {
2702 ++right; // expand selection
2711 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2712 pos_type pos, bool del) const
2714 int const strsize = str.length();
2716 pos_type const parsize = d->text_.size();
2717 for (i = 0; pos + i < parsize; ++i) {
2720 if (cs && str[i] != d->text_[pos + i])
2722 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2724 if (!del && isDeleted(pos + i))
2731 // if necessary, check whether string matches word
2733 if (pos > 0 && isLetter(pos - 1))
2735 if (pos + strsize < parsize
2736 && isLetter(pos + strsize))
2744 char_type Paragraph::getChar(pos_type pos) const
2746 return d->text_[pos];
2750 pos_type Paragraph::size() const
2752 return d->text_.size();
2756 bool Paragraph::empty() const
2758 return d->text_.empty();
2762 bool Paragraph::isInset(pos_type pos) const
2764 return d->text_[pos] == META_INSET;
2768 bool Paragraph::isSeparator(pos_type pos) const
2770 //FIXME: Are we sure this can be the only separator?
2771 return d->text_[pos] == ' ';
2775 void Paragraph::deregisterWords()
2777 Private::Words::const_iterator it;
2778 WordList & wl = theWordList();
2779 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2785 void Paragraph::collectWords(CursorSlice const & sl)
2788 bool inword = false;
2790 //lyxerr << "Words: ";
2791 pos_type n = size();
2792 for (pos_type pos = 0; pos != n; ++pos) {
2796 if (!isLetter(pos)) {
2805 CursorSlice from = sl;
2806 CursorSlice to = sl;
2809 from.text()->getWord(from, to, WHOLE_WORD);
2810 if (to.pos() - from.pos() < 6)
2812 docstring word = asString(from.pos(), to.pos(), false);
2813 d->words_.insert(word);
2814 //lyxerr << word << " ";
2816 //lyxerr << std::endl;
2820 void Paragraph::registerWords()
2822 Private::Words::const_iterator it;
2823 WordList & wl = theWordList();
2824 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2829 void Paragraph::updateWords(CursorSlice const & sl)
2831 LASSERT(&sl.paragraph() == this, /**/);