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"
23 #include "BufferParams.h"
27 #include "InsetList.h"
29 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
40 #include "TextClass.h"
44 #include "frontends/alert.h"
45 #include "frontends/FontMetrics.h"
47 #include "insets/InsetBibitem.h"
48 #include "insets/InsetLabel.h"
50 #include "support/convert.h"
51 #include "support/debug.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54 #include "support/Messages.h"
55 #include "support/textutils.h"
56 #include "support/unicode.h"
65 using support::contains;
66 using support::lowercase;
67 using support::prefixIs;
69 using support::suffixIs;
70 using support::rsplit;
71 using support::uppercase;
74 /// Inset identifier (above 0x10ffff, for ucs-4)
75 char_type const META_INSET = 0x200001;
78 /////////////////////////////////////////////////////////////////////
82 /////////////////////////////////////////////////////////////////////
84 class Paragraph::Private
88 Private(Paragraph * owner);
89 /// "Copy constructor"
90 Private(Private const &, Paragraph * owner);
93 void insertChar(pos_type pos, char_type c, Change const & change);
95 /// Output the surrogate pair formed by \p c and \p next to \p os.
96 /// \return the number of characters written.
97 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
100 /// Output a space in appropriate formatting (or a surrogate pair
101 /// if the next character is a combining character).
102 /// \return whether a surrogate pair was output.
103 bool simpleTeXBlanks(OutputParams const &,
104 odocstream &, TexRow & texrow,
106 unsigned int & column,
108 Layout const & style);
110 /// Output consecutive unicode chars, belonging to the same script as
111 /// specified by the latex macro \p ltx, to \p os starting from \p i.
112 /// \return the number of characters written.
113 int writeScriptChars(odocstream & os, docstring const & ltx,
114 Change &, Encoding const &, pos_type & i);
116 /// This could go to ParagraphParameters if we want to.
117 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
120 /// This could go to ParagraphParameters if we want to.
121 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
125 void latexInset(Buffer const &, BufferParams const &,
127 TexRow & texrow, OutputParams &,
130 Font const & outerfont,
132 Change & running_change,
133 Layout const & style,
135 unsigned int & column);
138 void latexSpecialChar(
140 OutputParams & runparams,
142 Change & running_change,
143 Layout const & style,
145 unsigned int & column);
152 unsigned int & column);
154 bool latexSpecialTypewriter(
158 unsigned int & column);
160 bool latexSpecialPhrase(
163 unsigned int & column,
164 OutputParams & runparams);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(std::string const & str, pos_type pos) const;
177 /// Which Paragraph owns us?
181 Inset * inset_owner_;
189 static unsigned int paragraph_id;
191 ParagraphParameters params_;
193 /// position of the paragraph in the buffer. Only macros from
194 /// paragraphs strictly smaller are visible in this paragraph
195 unsigned int macrocontext_position_;
197 /// for recording and looking up changes
201 InsetList insetlist_;
207 pos_type begin_of_body_;
209 typedef docstring TextContainer;
215 // Initialization of the counter for the paragraph id's,
216 unsigned int Paragraph::Private::paragraph_id = 0;
220 struct special_phrase {
226 special_phrase const special_phrases[] = {
227 { "LyX", from_ascii("\\LyX{}"), false },
228 { "TeX", from_ascii("\\TeX{}"), true },
229 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
230 { "LaTeX", from_ascii("\\LaTeX{}"), true },
233 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
238 Paragraph::Private::Private(Paragraph * owner)
239 : owner_(owner), inset_owner_(0), begin_of_body_(0)
241 id_ = paragraph_id++;
242 macrocontext_position_ = 0;
247 Paragraph::Private::Private(Private const & p, Paragraph * owner)
248 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
249 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
250 layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
252 id_ = paragraph_id++;
256 bool Paragraph::isChanged(pos_type start, pos_type end) const
258 BOOST_ASSERT(start >= 0 && start <= size());
259 BOOST_ASSERT(end > start && end <= size() + 1);
261 return d->changes_.isChanged(start, end);
265 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
266 // keep the logic here in sync with the logic of eraseChars()
272 Change change = d->changes_.lookup(size());
274 return change.type == Change::INSERTED && change.author == 0;
278 void Paragraph::setChange(Change const & change)
280 // beware of the imaginary end-of-par character!
281 d->changes_.set(change, 0, size() + 1);
284 * Propagate the change recursively - but not in case of DELETED!
286 * Imagine that your co-author makes changes in an existing inset. He
287 * sends your document to you and you come to the conclusion that the
288 * inset should go completely. If you erase it, LyX must not delete all
289 * text within the inset. Otherwise, the change tracked insertions of
290 * your co-author get lost and there is no way to restore them later.
292 * Conclusion: An inset's content should remain untouched if you delete it
295 if (change.type != Change::DELETED) {
296 for (pos_type pos = 0; pos < size(); ++pos) {
298 getInset(pos)->setChange(change);
304 void Paragraph::setChange(pos_type pos, Change const & change)
306 BOOST_ASSERT(pos >= 0 && pos <= size());
308 d->changes_.set(change, pos);
310 // see comment in setChange(Change const &) above
312 if (change.type != Change::DELETED &&
313 pos < size() && isInset(pos)) {
314 getInset(pos)->setChange(change);
319 Change const & Paragraph::lookupChange(pos_type pos) const
321 BOOST_ASSERT(pos >= 0 && pos <= size());
323 return d->changes_.lookup(pos);
327 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
330 BOOST_ASSERT(start >= 0 && start <= size());
331 BOOST_ASSERT(end > start && end <= size() + 1);
333 for (pos_type pos = start; pos < end; ++pos) {
334 switch (lookupChange(pos).type) {
335 case Change::UNCHANGED:
336 // accept changes in nested inset
337 if (pos < size() && isInset(pos))
338 getInset(pos)->acceptChanges(bparams);
342 case Change::INSERTED:
343 d->changes_.set(Change(Change::UNCHANGED), pos);
344 // also accept changes in nested inset
345 if (pos < size() && isInset(pos)) {
346 getInset(pos)->acceptChanges(bparams);
350 case Change::DELETED:
351 // Suppress access to non-existent
352 // "end-of-paragraph char"
354 eraseChar(pos, false);
365 void Paragraph::rejectChanges(BufferParams const & bparams,
366 pos_type start, pos_type end)
368 BOOST_ASSERT(start >= 0 && start <= size());
369 BOOST_ASSERT(end > start && end <= size() + 1);
371 for (pos_type pos = start; pos < end; ++pos) {
372 switch (lookupChange(pos).type) {
373 case Change::UNCHANGED:
374 // reject changes in nested inset
375 if (pos < size() && isInset(pos)) {
376 getInset(pos)->rejectChanges(bparams);
380 case Change::INSERTED:
381 // Suppress access to non-existent
382 // "end-of-paragraph char"
384 eraseChar(pos, false);
390 case Change::DELETED:
391 d->changes_.set(Change(Change::UNCHANGED), pos);
393 // Do NOT reject changes within a deleted inset!
394 // There may be insertions of a co-author inside of it!
402 void Paragraph::Private::insertChar(pos_type pos, char_type c,
403 Change const & change)
405 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
408 changes_.insert(change, pos);
410 // This is actually very common when parsing buffers (and
411 // maybe inserting ascii text)
412 if (pos == pos_type(text_.size())) {
413 // when appending characters, no need to update tables
418 text_.insert(text_.begin() + pos, c);
420 // Update the font table.
421 fontlist_.increasePosAfterPos(pos);
424 insetlist_.increasePosAfterPos(pos);
428 void Paragraph::insertInset(pos_type pos, Inset * inset,
429 Change const & change)
432 BOOST_ASSERT(pos >= 0 && pos <= size());
434 d->insertChar(pos, META_INSET, change);
435 BOOST_ASSERT(d->text_[pos] == META_INSET);
437 // Add a new entry in the insetlist_.
438 d->insetlist_.insert(inset, pos);
442 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
444 BOOST_ASSERT(pos >= 0 && pos <= size());
446 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
449 Change change = d->changes_.lookup(pos);
451 // set the character to DELETED if
452 // a) it was previously unchanged or
453 // b) it was inserted by a co-author
455 if (change.type == Change::UNCHANGED ||
456 (change.type == Change::INSERTED && change.author != 0)) {
457 setChange(pos, Change(Change::DELETED));
461 if (change.type == Change::DELETED)
465 // Don't physically access the imaginary end-of-paragraph character.
466 // eraseChar() can only mark it as DELETED. A physical deletion of
467 // end-of-par must be handled externally.
473 d->changes_.erase(pos);
475 // if it is an inset, delete the inset entry
476 if (d->text_[pos] == META_INSET)
477 d->insetlist_.erase(pos);
479 d->text_.erase(d->text_.begin() + pos);
481 // Update the fontlist_
482 d->fontlist_.erase(pos);
484 // Update the insetlist_
485 d->insetlist_.decreasePosAfterPos(pos);
491 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
493 BOOST_ASSERT(start >= 0 && start <= size());
494 BOOST_ASSERT(end >= start && end <= size() + 1);
497 for (pos_type count = end - start; count; --count) {
498 if (!eraseChar(i, trackChanges))
505 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
506 char_type next, Encoding const & encoding)
508 // Writing next here may circumvent a possible font change between
509 // c and next. Since next is only output if it forms a surrogate pair
510 // with c we can ignore this:
511 // A font change inside a surrogate pair does not make sense and is
512 // hopefully impossible to input.
513 // FIXME: change tracking
514 // Is this correct WRT change tracking?
515 docstring const latex1 = encoding.latexChar(next);
516 docstring const latex2 = encoding.latexChar(c);
517 os << latex1 << '{' << latex2 << '}';
518 return latex1.length() + latex2.length() + 2;
522 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
523 odocstream & os, TexRow & texrow,
525 unsigned int & column,
527 Layout const & style)
529 if (style.pass_thru || runparams.verbatim)
532 if (i + 1 < int(text_.size())) {
533 char_type next = text_[i + 1];
534 if (Encodings::isCombiningChar(next)) {
535 Encoding const & encoding = *(runparams.encoding);
536 // This space has an accent, so we must always output it.
537 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
542 if (lyxrc.plaintext_linelen > 0
543 && column > lyxrc.plaintext_linelen
545 && text_[i - 1] != ' '
546 && (i + 1 < int(text_.size()))
547 // same in FreeSpacing mode
548 && !owner_->isFreeSpacing()
549 // In typewriter mode, we want to avoid
550 // ! . ? : at the end of a line
551 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
552 && (text_[i - 1] == '.'
553 || text_[i - 1] == '?'
554 || text_[i - 1] == ':'
555 || text_[i - 1] == '!'))) {
558 texrow.start(owner_->id(), i + 1);
560 } else if (style.free_spacing) {
569 int Paragraph::Private::writeScriptChars(odocstream & os,
570 docstring const & ltx,
571 Change & runningChange,
572 Encoding const & encoding,
575 // FIXME: modifying i here is not very nice...
577 // We only arrive here when a proper language for character text_[i] has
578 // not been specified (i.e., it could not be translated in the current
579 // latex encoding) and it belongs to a known script.
580 // Parameter ltx contains the latex translation of text_[i] as specified in
581 // the unicodesymbols file and is something like "\textXXX{<spec>}".
582 // The latex macro name "textXXX" specifies the script to which text_[i]
583 // belongs and we use it in order to check whether characters from the
584 // same script immediately follow, such that we can collect them in a
585 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
586 // for the first char but only "<spec>" for all subsequent chars.
587 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
588 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
589 string script = to_ascii(ltx.substr(1, brace1 - 1));
590 int length = ltx.substr(0, brace2).length();
591 os << ltx.substr(0, brace2);
592 int size = text_.size();
593 while (i + 1 < size) {
594 char_type const next = text_[i + 1];
595 // Stop here if next character belongs to another script
596 // or there is a change in change tracking status.
597 if (!Encodings::isKnownScriptChar(next, script) ||
598 runningChange != owner_->lookupChange(i + 1))
602 FontList::const_iterator cit = fontlist_.begin();
603 FontList::const_iterator end = fontlist_.end();
604 for (; cit != end; ++cit) {
605 if (cit->pos() >= i && !found) {
606 prev_font = cit->font();
609 if (cit->pos() >= i + 1)
612 // Stop here if there is a font attribute or encoding change.
613 if (found && cit != end && prev_font != cit->font())
615 docstring const latex = encoding.latexChar(next);
616 docstring::size_type const b1 =
617 latex.find_first_of(from_ascii("{"));
618 docstring::size_type const b2 =
619 latex.find_last_of(from_ascii("}"));
620 int const len = b2 - b1 - 1;
621 os << latex.substr(b1 + 1, len);
631 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
633 pos_type const len = str.length();
635 // is the paragraph large enough?
636 if (pos + len > int(text_.size()))
639 // does the wanted text start at point?
640 for (string::size_type i = 0; i < str.length(); ++i) {
641 // Caution: direct comparison of characters works only
642 // because str is pure ASCII.
643 if (str[i] != text_[pos + i])
647 return fontlist_.hasChangeInRange(pos, len);
651 void Paragraph::Private::latexInset(Buffer const & buf,
652 BufferParams const & bparams,
655 OutputParams & runparams,
658 Font const & outerfont,
660 Change & running_change,
661 Layout const & style,
663 unsigned int & column)
665 Inset * inset = owner_->getInset(i);
668 if (style.pass_thru) {
669 inset->plaintext(buf, os, runparams);
673 // FIXME: move this to InsetNewline::latex
674 if (inset->lyxCode() == NEWLINE_CODE) {
675 // newlines are handled differently here than
676 // the default in simpleTeXSpecialChars().
677 if (!style.newline_allowed) {
681 column += running_font.latexWriteEndChanges(
682 os, bparams, runparams,
687 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
690 basefont = owner_->getLayoutFont(bparams, outerfont);
691 running_font = basefont;
693 if (runparams.moving_arg)
698 texrow.start(owner_->id(), i + 1);
702 if (owner_->lookupChange(i).type == Change::DELETED) {
703 if( ++runparams.inDeletedInset == 1)
704 runparams.changeOfDeletedInset = owner_->lookupChange(i);
707 if (inset->canTrackChanges()) {
708 column += Changes::latexMarkChange(os, bparams, running_change,
709 Change(Change::UNCHANGED));
710 running_change = Change(Change::UNCHANGED);
714 odocstream::pos_type const len = os.tellp();
716 if (inset->forceLTR()
717 && running_font.isRightToLeft()
718 // ERT is an exception, it should be output with no decorations at all
719 && inset->lyxCode() != ERT_CODE) {
720 if (running_font.language()->lang() == "farsi")
727 // FIXME: Bug: we can have an empty font change here!
728 // if there has just been a font change, we are going to close it
729 // right now, which means stupid latex code like \textsf{}. AFAIK,
730 // this does not harm dvi output. A minor bug, thus (JMarc)
732 // Some insets cannot be inside a font change command.
733 // However, even such insets *can* be placed in \L or \R
734 // or their equivalents (for RTL language switches), so we don't
735 // close the language in those cases.
736 // ArabTeX, though, cannot handle this special behavior, it seems.
737 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
738 || running_font.language()->lang() == "arabic_arabtex";
739 if (open_font && inset->noFontChange()) {
740 bool closeLanguage = arabtex
741 || basefont.isRightToLeft() == running_font.isRightToLeft();
742 unsigned int count = running_font.latexWriteEndChanges(os,
743 bparams, runparams, basefont, basefont, closeLanguage);
745 // if any font properties were closed, update the running_font,
746 // making sure, however, to leave the language as it was
748 // FIXME: probably a better way to keep track of the old
749 // language, than copying the entire font?
750 Font const copy_font(running_font);
751 basefont = owner_->getLayoutFont(bparams, outerfont);
752 running_font = basefont;
754 running_font.setLanguage(copy_font.language());
755 // leave font open if language is still open
756 open_font = (running_font.language() == basefont.language());
758 runparams.local_font = &basefont;
762 int tmp = inset->latex(buf, os, runparams);
765 if (running_font.language()->lang() == "farsi")
772 for (int j = 0; j < tmp; ++j)
775 texrow.start(owner_->id(), i + 1);
778 column += os.tellp() - len;
781 if (owner_->lookupChange(i).type == Change::DELETED)
782 --runparams.inDeletedInset;
786 void Paragraph::Private::latexSpecialChar(
788 OutputParams & runparams,
790 Change & running_change,
791 Layout const & style,
793 unsigned int & column)
795 char_type const c = text_[i];
797 if (style.pass_thru) {
799 // FIXME UNICODE: This can fail if c cannot
800 // be encoded in the current encoding.
805 if (runparams.verbatim) {
810 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
813 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
814 && latexSpecialTypewriter(c, os, i, column))
817 // Otherwise, we use what LaTeX provides us.
820 os << "\\textbackslash{}";
824 os << "\\textless{}";
828 os << "\\textgreater{}";
839 os << "\\char`\\\"{}";
844 case '%': case '#': case '{':
852 os << "\\textasciitilde{}";
857 os << "\\textasciicircum{}";
862 // avoid being mistaken for optional arguments
870 // Blanks are printed before font switching.
871 // Sure? I am not! (try nice-latex)
872 // I am sure it's correct. LyX might be smarter
873 // in the future, but for now, nothing wrong is
880 if (latexSpecialPhrase(os, i, column, runparams))
886 Encoding const & encoding = *(runparams.encoding);
887 if (i + 1 < int(text_.size())) {
888 char_type next = text_[i + 1];
889 if (Encodings::isCombiningChar(next)) {
890 column += latexSurrogatePair(os, c, next, encoding) - 1;
896 docstring const latex = encoding.latexChar(c);
897 if (Encodings::isKnownScriptChar(c, script)
898 && prefixIs(latex, from_ascii("\\" + script)))
899 column += writeScriptChars(os, latex,
900 running_change, encoding, i) - 1;
901 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
902 // Prevent eating of a following
903 // space or command corruption by
904 // following characters
905 column += latex.length() + 1;
908 column += latex.length() - 1;
916 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
917 pos_type & i, unsigned int & column)
923 // In T1 encoding, these characters exist
924 // but we should avoid ligatures
925 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
930 //os << "\\textcompwordmark{}";
942 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
943 pos_type & i, unsigned int & column)
947 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
948 // "--" in Typewriter mode -> "-{}-"
955 // I assume this is hack treating typewriter as verbatim
956 // FIXME UNICODE: This can fail if c cannot be encoded
957 // in the current encoding.
962 // Those characters are not directly supported.
966 case '%': case '#': case '{':
975 // With Typewriter font, these characters exist.
982 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
983 unsigned int & column, OutputParams & runparams)
985 // FIXME: if we have "LaTeX" with a font
986 // change in the middle (before the 'T', then
987 // the "TeX" part is still special cased.
988 // Really we should only operate this on
989 // "words" for some definition of word
991 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
992 if (!isTextAt(special_phrases[pnr].phrase, i))
994 if (runparams.moving_arg)
996 os << special_phrases[pnr].macro;
997 i += special_phrases[pnr].phrase.length() - 1;
998 column += special_phrases[pnr].macro.length() - 1;
1005 void Paragraph::Private::validate(LaTeXFeatures & features,
1006 Layout const & layout) const
1008 // check the params.
1009 if (!params_.spacing().isDefault())
1010 features.require("setspace");
1013 features.useLayout(layout.name());
1016 fontlist_.validate(features);
1018 // then the indentation
1019 if (!params_.leftIndent().zero())
1020 features.require("ParagraphLeftIndent");
1023 InsetList::const_iterator icit = insetlist_.begin();
1024 InsetList::const_iterator iend = insetlist_.end();
1025 for (; icit != iend; ++icit) {
1027 icit->inset->validate(features);
1028 if (layout.needprotect &&
1029 icit->inset->lyxCode() == FOOT_CODE)
1030 features.require("NeedLyXFootnoteCode");
1034 // then the contents
1035 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1036 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1037 if (!special_phrases[pnr].builtin
1038 && isTextAt(special_phrases[pnr].phrase, i)) {
1039 features.require(special_phrases[pnr].phrase);
1043 Encodings::validate(text_[i], features);
1047 /////////////////////////////////////////////////////////////////////
1051 /////////////////////////////////////////////////////////////////////
1053 Paragraph::Paragraph()
1054 : d(new Paragraph::Private(this))
1061 Paragraph::Paragraph(Paragraph const & par)
1062 : itemdepth(par.itemdepth),
1063 d(new Paragraph::Private(*par.d, this))
1068 Paragraph & Paragraph::operator=(Paragraph const & par)
1070 // needed as we will destroy the private part before copying it
1072 itemdepth = par.itemdepth;
1075 d = new Private(*par.d, this);
1081 Paragraph::~Paragraph()
1087 void Paragraph::write(Buffer const & buf, ostream & os,
1088 BufferParams const & bparams,
1089 depth_type & dth) const
1091 // The beginning or end of a deeper (i.e. nested) area?
1092 if (dth != params().depth()) {
1093 if (params().depth() > dth) {
1094 while (params().depth() > dth) {
1095 os << "\n\\begin_deeper";
1099 while (params().depth() < dth) {
1100 os << "\n\\end_deeper";
1106 // First write the layout
1107 os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1111 Font font1(inherit_font, bparams.language);
1113 Change running_change = Change(Change::UNCHANGED);
1116 for (pos_type i = 0; i <= size(); ++i) {
1118 Change change = lookupChange(i);
1119 Changes::lyxMarkChange(os, column, running_change, change);
1120 running_change = change;
1125 // Write font changes
1126 Font font2 = getFontSettings(bparams, i);
1127 if (font2 != font1) {
1128 font2.lyxWriteChanges(font1, os);
1133 char_type const c = d->text_[i];
1137 Inset const * inset = getInset(i);
1139 if (inset->directWrite()) {
1140 // international char, let it write
1141 // code directly so it's shorter in
1143 inset->write(buf, os);
1147 os << "\\begin_inset ";
1148 inset->write(buf, os);
1149 os << "\n\\end_inset\n\n";
1155 os << "\n\\backslash\n";
1159 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1166 if ((column > 70 && c == ' ')
1171 // this check is to amend a bug. LyX sometimes
1172 // inserts '\0' this could cause problems.
1174 std::vector<char> tmp = ucs4_to_utf8(c);
1175 tmp.push_back('\0');
1178 lyxerr << "ERROR (Paragraph::writeFile):"
1179 " NULL char in structure." << endl;
1185 os << "\n\\end_layout\n";
1189 void Paragraph::validate(LaTeXFeatures & features) const
1191 d->validate(features, *layout());
1195 void Paragraph::insert(pos_type start, docstring const & str,
1196 Font const & font, Change const & change)
1198 for (size_t i = 0, n = str.size(); i != n ; ++i)
1199 insertChar(start + i, str[i], font, change);
1203 void Paragraph::appendChar(char_type c, Font const & font,
1204 Change const & change)
1207 d->changes_.insert(change, d->text_.size());
1208 // when appending characters, no need to update tables
1209 d->text_.push_back(c);
1210 setFont(d->text_.size() - 1, font);
1214 void Paragraph::appendString(docstring const & s, Font const & font,
1215 Change const & change)
1217 pos_type end = s.size();
1218 size_t oldsize = d->text_.size();
1219 size_t newsize = oldsize + end;
1220 size_t capacity = d->text_.capacity();
1221 if (newsize >= capacity)
1222 d->text_.reserve(std::max(capacity + 100, newsize));
1224 // when appending characters, no need to update tables
1227 // FIXME: Optimize this!
1228 for (pos_type i = 0; i != end; ++i) {
1230 d->changes_.insert(change, i);
1232 d->fontlist_.set(oldsize, font);
1233 d->fontlist_.set(newsize - 1, font);
1237 void Paragraph::insertChar(pos_type pos, char_type c,
1240 d->insertChar(pos, c, Change(trackChanges ?
1241 Change::INSERTED : Change::UNCHANGED));
1245 void Paragraph::insertChar(pos_type pos, char_type c,
1246 Font const & font, bool trackChanges)
1248 d->insertChar(pos, c, Change(trackChanges ?
1249 Change::INSERTED : Change::UNCHANGED));
1254 void Paragraph::insertChar(pos_type pos, char_type c,
1255 Font const & font, Change const & change)
1257 d->insertChar(pos, c, change);
1262 void Paragraph::insertInset(pos_type pos, Inset * inset,
1263 Font const & font, Change const & change)
1265 insertInset(pos, inset, change);
1266 // Set the font/language of the inset...
1271 bool Paragraph::insetAllowed(InsetCode code)
1273 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1277 void Paragraph::resetFonts(Font const & font)
1279 d->fontlist_.clear();
1280 d->fontlist_.set(0, font);
1281 d->fontlist_.set(d->text_.size() - 1, font);
1284 // Gets uninstantiated font setting at position.
1285 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1289 lyxerr << " pos: " << pos << " size: " << size() << endl;
1290 BOOST_ASSERT(pos <= size());
1293 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1294 if (cit != d->fontlist_.end())
1297 if (pos == size() && !empty())
1298 return getFontSettings(bparams, pos - 1);
1300 return Font(inherit_font, getParLanguage(bparams));
1304 FontSpan Paragraph::fontSpan(pos_type pos) const
1306 BOOST_ASSERT(pos <= size());
1309 FontList::const_iterator cit = d->fontlist_.begin();
1310 FontList::const_iterator end = d->fontlist_.end();
1311 for (; cit != end; ++cit) {
1312 if (cit->pos() >= pos) {
1313 if (pos >= beginOfBody())
1314 return FontSpan(std::max(start, beginOfBody()),
1317 return FontSpan(start,
1318 std::min(beginOfBody() - 1,
1321 start = cit->pos() + 1;
1324 // This should not happen, but if so, we take no chances.
1325 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1327 return FontSpan(pos, pos);
1331 // Gets uninstantiated font setting at position 0
1332 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1334 if (!empty() && !d->fontlist_.empty())
1335 return d->fontlist_.begin()->font();
1337 return Font(inherit_font, bparams.language);
1341 // Gets the fully instantiated font at a given position in a paragraph
1342 // This is basically the same function as Text::GetFont() in text2.cpp.
1343 // The difference is that this one is used for generating the LaTeX file,
1344 // and thus cosmetic "improvements" are disallowed: This has to deliver
1345 // the true picture of the buffer. (Asger)
1346 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1347 Font const & outerfont) const
1349 BOOST_ASSERT(pos >= 0);
1351 Font font = getFontSettings(bparams, pos);
1353 pos_type const body_pos = beginOfBody();
1355 font.fontInfo().realize(d->layout_->labelfont);
1357 font.fontInfo().realize(d->layout_->font);
1359 font.fontInfo().realize(outerfont.fontInfo());
1360 font.fontInfo().realize(bparams.getFont().fontInfo());
1366 Font const Paragraph::getLabelFont
1367 (BufferParams const & bparams, Font const & outerfont) const
1369 FontInfo tmpfont = layout()->labelfont;
1370 tmpfont.realize(outerfont.fontInfo());
1371 tmpfont.realize(bparams.getFont().fontInfo());
1372 return Font(tmpfont, getParLanguage(bparams));
1376 Font const Paragraph::getLayoutFont
1377 (BufferParams const & bparams, Font const & outerfont) const
1379 FontInfo tmpfont = layout()->font;
1380 tmpfont.realize(outerfont.fontInfo());
1381 tmpfont.realize(bparams.getFont().fontInfo());
1382 return Font(tmpfont, getParLanguage(bparams));
1386 /// Returns the height of the highest font in range
1387 FontSize Paragraph::highestFontInRange
1388 (pos_type startpos, pos_type endpos, FontSize def_size) const
1390 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1395 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1397 char_type c = d->text_[pos];
1398 if (!lyxrc.rtl_support)
1428 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1435 void Paragraph::setFont(pos_type pos, Font const & font)
1437 BOOST_ASSERT(pos <= size());
1439 // First, reduce font against layout/label font
1440 // Update: The setCharFont() routine in text2.cpp already
1441 // reduces font, so we don't need to do that here. (Asger)
1443 d->fontlist_.set(pos, font);
1447 void Paragraph::makeSameLayout(Paragraph const & par)
1449 layout(par.layout());
1451 d->params_ = par.params();
1455 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1457 if (isFreeSpacing())
1463 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1464 if (eraseChar(pos, trackChanges))
1470 return count > 0 || pos > 0;
1474 bool Paragraph::hasSameLayout(Paragraph const & par) const
1476 return par.layout() == layout() && d->params_.sameLayout(par.params());
1480 depth_type Paragraph::getDepth() const
1482 return params().depth();
1486 depth_type Paragraph::getMaxDepthAfter() const
1488 if (layout()->isEnvironment())
1489 return params().depth() + 1;
1491 return params().depth();
1495 char Paragraph::getAlign() const
1497 if (params().align() == LYX_ALIGN_LAYOUT)
1498 return layout()->align;
1500 return params().align();
1504 docstring const & Paragraph::getLabelstring() const
1506 return params().labelString();
1510 // the next two functions are for the manual labels
1511 docstring const Paragraph::getLabelWidthString() const
1513 if (layout()->margintype == MARGIN_MANUAL)
1514 return params().labelWidthString();
1516 return _("Senseless with this layout!");
1520 void Paragraph::setLabelWidthString(docstring const & s)
1522 params().labelWidthString(s);
1526 docstring const Paragraph::translateIfPossible(docstring const & s,
1527 BufferParams const & bparams) const
1529 if (!support::isAscii(s) || s.empty()) {
1530 // This must be a user defined layout. We cannot translate
1531 // this, since gettext accepts only ascii keys.
1534 // Probably standard layout, try to translate
1535 Messages & m = getMessages(getParLanguage(bparams)->code());
1536 return m.get(to_ascii(s));
1540 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1541 BufferParams const & bparams, bool process_appendix) const
1543 TextClass const & tclass = bparams.getTextClass();
1546 if (process_appendix && params().appendix())
1547 fmt = translateIfPossible(layout->labelstring_appendix(),
1550 fmt = translateIfPossible(layout->labelstring(), bparams);
1552 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1553 && !layout->counter.empty())
1554 fmt = "\\the" + layout->counter;
1556 // handle 'inherited level parts' in 'fmt',
1557 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1558 size_t const i = fmt.find('@', 0);
1559 if (i != docstring::npos) {
1560 size_t const j = fmt.find('@', i + 1);
1561 if (j != docstring::npos) {
1562 docstring parent(fmt, i + 1, j - i - 1);
1563 docstring label = from_ascii("??");
1564 if (tclass.hasLayout(parent))
1565 docstring label = expandLabel(tclass[parent], bparams,
1567 fmt = docstring(fmt, 0, i) + label
1568 + docstring(fmt, j + 1, docstring::npos);
1572 return tclass.counters().counterLabel(fmt);
1576 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1579 LyXAlignment const oldAlign = params().align();
1581 if (!(oldAlign & layout()->alignpossible)) {
1582 frontend::Alert::warning(_("Alignment not permitted"),
1583 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1584 params().align(LYX_ALIGN_LAYOUT);
1589 pos_type Paragraph::beginOfBody() const
1591 return d->begin_of_body_;
1595 void Paragraph::setBeginOfBody()
1597 if (layout()->labeltype != LABEL_MANUAL) {
1598 d->begin_of_body_ = 0;
1602 // Unroll the first two cycles of the loop
1603 // and remember the previous character to
1604 // remove unnecessary getChar() calls
1606 pos_type end = size();
1607 if (i < end && !isNewline(i)) {
1609 char_type previous_char = 0;
1612 previous_char = d->text_[i];
1613 if (!isNewline(i)) {
1615 while (i < end && previous_char != ' ') {
1620 previous_char = temp;
1626 d->begin_of_body_ = i;
1630 bool Paragraph::forceDefaultParagraphs() const
1632 return inInset() && inInset()->forceDefaultParagraphs(0);
1638 // paragraphs inside floats need different alignment tags to avoid
1641 bool noTrivlistCentering(InsetCode code)
1643 return code == FLOAT_CODE || code == WRAP_CODE;
1647 string correction(string const & orig)
1649 if (orig == "flushleft")
1650 return "raggedright";
1651 if (orig == "flushright")
1652 return "raggedleft";
1653 if (orig == "center")
1659 string const corrected_env(string const & suffix, string const & env,
1662 string output = suffix + "{";
1663 if (noTrivlistCentering(code))
1664 output += correction(env);
1668 if (suffix == "\\begin")
1674 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1676 if (!contains(str, "\n"))
1677 column += str.size();
1681 column = rsplit(str, tmp, '\n').size();
1688 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1689 odocstream & os, TexRow & texrow,
1690 bool moving_arg) const
1694 if (params_.noindent()) {
1695 os << "\\noindent ";
1699 LyXAlignment const curAlign = params_.align();
1701 if (curAlign == layout_->align)
1705 case LYX_ALIGN_NONE:
1706 case LYX_ALIGN_BLOCK:
1707 case LYX_ALIGN_LAYOUT:
1708 case LYX_ALIGN_SPECIAL:
1710 case LYX_ALIGN_LEFT:
1711 case LYX_ALIGN_RIGHT:
1712 case LYX_ALIGN_CENTER:
1721 case LYX_ALIGN_NONE:
1722 case LYX_ALIGN_BLOCK:
1723 case LYX_ALIGN_LAYOUT:
1724 case LYX_ALIGN_SPECIAL:
1726 case LYX_ALIGN_LEFT: {
1728 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1729 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1731 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1732 os << from_ascii(output);
1733 adjust_row_column(output, texrow, column);
1735 } case LYX_ALIGN_RIGHT: {
1737 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1738 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1740 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1741 os << from_ascii(output);
1742 adjust_row_column(output, texrow, column);
1744 } case LYX_ALIGN_CENTER: {
1746 output = corrected_env("\\begin", "center", owner_->ownerCode());
1747 os << from_ascii(output);
1748 adjust_row_column(output, texrow, column);
1757 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1758 odocstream & os, TexRow & texrow,
1759 bool moving_arg) const
1763 switch (params_.align()) {
1764 case LYX_ALIGN_NONE:
1765 case LYX_ALIGN_BLOCK:
1766 case LYX_ALIGN_LAYOUT:
1767 case LYX_ALIGN_SPECIAL:
1769 case LYX_ALIGN_LEFT:
1770 case LYX_ALIGN_RIGHT:
1771 case LYX_ALIGN_CENTER:
1779 switch (params_.align()) {
1780 case LYX_ALIGN_NONE:
1781 case LYX_ALIGN_BLOCK:
1782 case LYX_ALIGN_LAYOUT:
1783 case LYX_ALIGN_SPECIAL:
1785 case LYX_ALIGN_LEFT: {
1787 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1788 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1790 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1791 os << from_ascii(output);
1792 adjust_row_column(output, texrow, column);
1794 } case LYX_ALIGN_RIGHT: {
1796 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1797 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1799 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1800 os << from_ascii(output);
1801 adjust_row_column(output, texrow, column);
1803 } case LYX_ALIGN_CENTER: {
1805 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1806 os << from_ascii(output);
1807 adjust_row_column(output, texrow, column);
1816 // This one spits out the text of the paragraph
1817 bool Paragraph::latex(Buffer const & buf,
1818 BufferParams const & bparams,
1819 Font const & outerfont,
1820 odocstream & os, TexRow & texrow,
1821 OutputParams const & runparams) const
1823 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1825 bool return_value = false;
1829 // well we have to check if we are in an inset with unlimited
1830 // length (all in one row) if that is true then we don't allow
1831 // any special options in the paragraph and also we don't allow
1832 // any environment other than the default layout of the text class
1834 bool asdefault = forceDefaultParagraphs();
1837 style = bparams.getTextClass().defaultLayout();
1842 // Current base font for all inherited font changes, without any
1843 // change caused by an individual character, except for the language:
1844 // It is set to the language of the first character.
1845 // As long as we are in the label, this font is the base font of the
1846 // label. Before the first body character it is set to the base font
1850 // Maybe we have to create a optional argument.
1851 pos_type body_pos = beginOfBody();
1852 unsigned int column = 0;
1855 // the optional argument is kept in curly brackets in
1856 // case it contains a ']'
1859 basefont = getLabelFont(bparams, outerfont);
1861 basefont = getLayoutFont(bparams, outerfont);
1864 // Which font is currently active?
1865 Font running_font(basefont);
1866 // Do we have an open font change?
1867 bool open_font = false;
1869 Change runningChange = Change(Change::UNCHANGED);
1871 texrow.start(id(), 0);
1873 // if the paragraph is empty, the loop will not be entered at all
1875 if (style->isCommand()) {
1880 column += d->startTeXParParams(bparams, os, texrow,
1881 runparams.moving_arg);
1884 for (pos_type i = 0; i < size(); ++i) {
1885 // First char in paragraph or after label?
1886 if (i == body_pos) {
1889 column += running_font.latexWriteEndChanges(
1890 os, bparams, runparams,
1891 basefont, basefont);
1894 basefont = getLayoutFont(bparams, outerfont);
1895 running_font = basefont;
1897 column += Changes::latexMarkChange(os, bparams,
1898 runningChange, Change(Change::UNCHANGED));
1899 runningChange = Change(Change::UNCHANGED);
1904 if (style->isCommand()) {
1910 column += d->startTeXParParams(bparams, os,
1912 runparams.moving_arg);
1915 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1918 if (bparams.outputChanges && runningChange != change) {
1920 column += running_font.latexWriteEndChanges(
1921 os, bparams, runparams, basefont, basefont);
1924 basefont = getLayoutFont(bparams, outerfont);
1925 running_font = basefont;
1927 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1928 runningChange = change;
1931 // do not output text which is marked deleted
1932 // if change tracking output is disabled
1933 if (!bparams.outputChanges && change.type == Change::DELETED) {
1939 // Fully instantiated font
1940 Font const font = getFont(bparams, i, outerfont);
1942 Font const last_font = running_font;
1944 // Do we need to close the previous font?
1946 (font != running_font ||
1947 font.language() != running_font.language()))
1949 column += running_font.latexWriteEndChanges(
1950 os, bparams, runparams, basefont,
1951 (i == body_pos-1) ? basefont : font);
1952 running_font = basefont;
1956 // close babel's font environment before opening CJK.
1957 if (!running_font.language()->babel().empty() &&
1958 font.language()->encoding()->package() == Encoding::CJK) {
1959 string end_tag = subst(lyxrc.language_command_end,
1961 running_font.language()->babel());
1962 os << from_ascii(end_tag);
1963 column += end_tag.length();
1966 // Switch file encoding if necessary (and allowed)
1967 if (!runparams.verbatim &&
1968 runparams.encoding->package() == Encoding::none &&
1969 font.language()->encoding()->package() == Encoding::none) {
1970 std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1971 runparams, *(runparams.encoding),
1972 *(font.language()->encoding()));
1973 if (enc_switch.first) {
1974 column += enc_switch.second;
1975 runparams.encoding = font.language()->encoding();
1979 char_type const c = d->text_[i];
1981 // Do we need to change font?
1982 if ((font != running_font ||
1983 font.language() != running_font.language()) &&
1986 odocstringstream ods;
1987 column += font.latexWriteStartChanges(ods, bparams,
1988 runparams, basefont,
1990 running_font = font;
1992 docstring fontchange = ods.str();
1993 // check if the fontchange ends with a trailing blank
1994 // (like "\small " (see bug 3382)
1995 if (suffixIs(fontchange, ' ') && c == ' ')
1996 os << fontchange.substr(0, fontchange.size() - 1)
1997 << from_ascii("{}");
2003 // FIXME: integrate this case in latexSpecialChar
2004 // Do not print the separation of the optional argument
2005 // if style->pass_thru is false. This works because
2006 // latexSpecialChar ignores spaces if
2007 // style->pass_thru is false.
2008 if (i != body_pos - 1) {
2009 if (d->simpleTeXBlanks(
2010 runparams, os, texrow,
2011 i, column, font, *style)) {
2012 // A surrogate pair was output. We
2013 // must not call latexSpecialChar
2014 // in this iteration, since it would output
2015 // the combining character again.
2022 OutputParams rp = runparams;
2023 rp.free_spacing = style->free_spacing;
2024 rp.local_font = &font;
2025 rp.intitle = style->intitle;
2027 // Two major modes: LaTeX or plain
2028 // Handle here those cases common to both modes
2029 // and then split to handle the two modes separately.
2030 if (c == META_INSET)
2031 d->latexInset(buf, bparams, os,
2032 texrow, rp, running_font,
2033 basefont, outerfont, open_font,
2034 runningChange, *style, i, column);
2036 d->latexSpecialChar(os, rp, running_font, runningChange,
2039 // Set the encoding to that returned from simpleTeXSpecialChars (see
2040 // comment for encoding member in OutputParams.h)
2041 runparams.encoding = rp.encoding;
2044 // If we have an open font definition, we have to close it
2046 #ifdef FIXED_LANGUAGE_END_DETECTION
2049 .latexWriteEndChanges(os, bparams, runparams,
2051 next_->getFont(bparams, 0, outerfont));
2053 running_font.latexWriteEndChanges(os, bparams,
2054 runparams, basefont, basefont);
2057 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2058 //FIXME: there as we start another \selectlanguage with the next paragraph if
2059 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2060 running_font.latexWriteEndChanges(os, bparams, runparams,
2061 basefont, basefont);
2065 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2067 // Needed if there is an optional argument but no contents.
2068 if (body_pos > 0 && body_pos == size()) {
2070 return_value = false;
2074 column += d->endTeXParParams(bparams, os, texrow,
2075 runparams.moving_arg);
2078 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2079 return return_value;
2083 bool Paragraph::emptyTag() const
2085 for (pos_type i = 0; i < size(); ++i) {
2087 Inset const * inset = getInset(i);
2088 InsetCode lyx_code = inset->lyxCode();
2089 if (lyx_code != TOC_CODE &&
2090 lyx_code != INCLUDE_CODE &&
2091 lyx_code != GRAPHICS_CODE &&
2092 lyx_code != ERT_CODE &&
2093 lyx_code != LISTINGS_CODE &&
2094 lyx_code != FLOAT_CODE &&
2095 lyx_code != TABULAR_CODE) {
2099 char_type c = d->text_[i];
2100 if (c != ' ' && c != '\t')
2108 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2110 for (pos_type i = 0; i < size(); ++i) {
2112 Inset const * inset = getInset(i);
2113 InsetCode lyx_code = inset->lyxCode();
2114 if (lyx_code == LABEL_CODE) {
2115 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2116 docstring const & id = il->getParam("name");
2117 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2126 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2129 for (i = 0; i < size(); ++i) {
2131 Inset const * inset = getInset(i);
2132 inset->docbook(buf, os, runparams);
2134 char_type c = d->text_[i];
2137 os << sgml::escapeChar(c);
2144 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2147 pos_type size = text_.size();
2148 for (pos_type i = initial; i < size; ++i) {
2149 Font font = owner_->getFont(buf.params(), i, outerfont);
2150 if (text_[i] == META_INSET)
2152 if (i != initial && font != font_old)
2161 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2163 OutputParams const & runparams,
2164 Font const & outerfont,
2165 pos_type initial) const
2167 bool emph_flag = false;
2169 LayoutPtr const & style = layout();
2171 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2173 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2176 // parsing main loop
2177 for (pos_type i = initial; i < size(); ++i) {
2178 Font font = getFont(buf.params(), i, outerfont);
2180 // handle <emphasis> tag
2181 if (font_old.emph() != font.fontInfo().emph()) {
2182 if (font.fontInfo().emph() == FONT_ON) {
2185 } else if (i != initial) {
2186 os << "</emphasis>";
2192 Inset const * inset = getInset(i);
2193 inset->docbook(buf, os, runparams);
2195 char_type c = d->text_[i];
2197 if (style->pass_thru)
2200 os << sgml::escapeChar(c);
2202 font_old = font.fontInfo();
2206 os << "</emphasis>";
2209 if (style->free_spacing)
2211 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2216 bool Paragraph::isHfill(pos_type pos) const
2219 && getInset(pos)->lyxCode() == HFILL_CODE;
2223 bool Paragraph::isNewline(pos_type pos) const
2226 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2230 bool Paragraph::isLineSeparator(pos_type pos) const
2232 char_type const c = d->text_[pos];
2233 return isLineSeparatorChar(c)
2234 || (c == META_INSET && getInset(pos) &&
2235 getInset(pos)->isLineSeparator());
2239 /// Used by the spellchecker
2240 bool Paragraph::isLetter(pos_type pos) const
2243 return getInset(pos)->isLetter();
2245 char_type const c = d->text_[pos];
2246 return isLetterChar(c) || isDigit(c);
2252 Paragraph::getParLanguage(BufferParams const & bparams) const
2255 return getFirstFontSettings(bparams).language();
2256 // FIXME: we should check the prev par as well (Lgb)
2257 return bparams.language;
2261 bool Paragraph::isRTL(BufferParams const & bparams) const
2263 return lyxrc.rtl_support
2264 && getParLanguage(bparams)->rightToLeft()
2265 && ownerCode() != ERT_CODE
2266 && ownerCode() != LISTINGS_CODE;
2270 void Paragraph::changeLanguage(BufferParams const & bparams,
2271 Language const * from, Language const * to)
2273 // change language including dummy font change at the end
2274 for (pos_type i = 0; i <= size(); ++i) {
2275 Font font = getFontSettings(bparams, i);
2276 if (font.language() == from) {
2277 font.setLanguage(to);
2284 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2286 Language const * doc_language = bparams.language;
2287 FontList::const_iterator cit = d->fontlist_.begin();
2288 FontList::const_iterator end = d->fontlist_.end();
2290 for (; cit != end; ++cit)
2291 if (cit->font().language() != ignore_language &&
2292 cit->font().language() != latex_language &&
2293 cit->font().language() != doc_language)
2299 // Convert the paragraph to a string.
2300 // Used for building the table of contents
2301 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2303 return asString(buffer, 0, size(), label);
2307 docstring const Paragraph::asString(Buffer const & buffer,
2308 pos_type beg, pos_type end, bool label) const
2311 odocstringstream os;
2313 if (beg == 0 && label && !params().labelString().empty())
2314 os << params().labelString() << ' ';
2316 for (pos_type i = beg; i < end; ++i) {
2317 char_type const c = d->text_[i];
2320 else if (c == META_INSET)
2321 getInset(i)->textString(buffer, os);
2328 void Paragraph::setInsetOwner(Inset * inset)
2330 d->inset_owner_ = inset;
2334 int Paragraph::id() const
2340 LayoutPtr const & Paragraph::layout() const
2346 void Paragraph::layout(LayoutPtr const & new_layout)
2348 d->layout_ = new_layout;
2352 Inset * Paragraph::inInset() const
2354 return d->inset_owner_;
2358 InsetCode Paragraph::ownerCode() const
2360 return d->inset_owner_ ?
2361 d->inset_owner_->lyxCode() : NO_CODE;
2365 ParagraphParameters & Paragraph::params()
2371 ParagraphParameters const & Paragraph::params() const
2377 bool Paragraph::isFreeSpacing() const
2379 if (layout()->free_spacing)
2381 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2385 bool Paragraph::allowEmpty() const
2387 if (layout()->keepempty)
2389 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2393 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2395 if (!Encodings::is_arabic(c))
2398 char_type prev_char = ' ';
2399 char_type next_char = ' ';
2401 for (pos_type i = pos - 1; i >= 0; --i) {
2402 char_type const par_char = d->text_[i];
2403 if (!Encodings::isComposeChar_arabic(par_char)) {
2404 prev_char = par_char;
2409 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2410 char_type const par_char = d->text_[i];
2411 if (!Encodings::isComposeChar_arabic(par_char)) {
2412 next_char = par_char;
2417 if (Encodings::is_arabic(next_char)) {
2418 if (Encodings::is_arabic(prev_char) &&
2419 !Encodings::is_arabic_special(prev_char))
2420 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2422 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2424 if (Encodings::is_arabic(prev_char) &&
2425 !Encodings::is_arabic_special(prev_char))
2426 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2428 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2433 int Paragraph::checkBiblio(bool track_changes)
2436 //This is getting more and more a mess. ...We really should clean
2437 //up this bibitem issue for 1.6. See also bug 2743.
2439 // Add bibitem insets if necessary
2440 if (layout()->labeltype != LABEL_BIBLIO)
2443 bool hasbibitem = !d->insetlist_.empty()
2444 // Insist on it being in pos 0
2445 && d->text_[0] == META_INSET
2446 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2451 // remove a bibitem in pos != 0
2452 // restore it later in pos 0 if necessary
2453 // (e.g. if a user inserts contents _before_ the item)
2454 // we're assuming there's only one of these, which there
2456 int erasedInsetPosition = -1;
2457 InsetList::iterator it = d->insetlist_.begin();
2458 InsetList::iterator end = d->insetlist_.end();
2459 for (; it != end; ++it)
2460 if (it->inset->lyxCode() == BIBITEM_CODE
2462 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2463 oldkey = olditem->getParam("key");
2464 oldlabel = olditem->getParam("label");
2465 erasedInsetPosition = it->pos;
2466 eraseChar(erasedInsetPosition, track_changes);
2470 //There was an InsetBibitem at the beginning, and we didn't
2471 //have to erase one.
2472 if (hasbibitem && erasedInsetPosition < 0)
2475 //There was an InsetBibitem at the beginning and we did have to
2476 //erase one. So we give its properties to the beginning inset.
2478 InsetBibitem * inset =
2479 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2480 if (!oldkey.empty())
2481 inset->setParam("key", oldkey);
2482 inset->setParam("label", oldlabel);
2483 return -erasedInsetPosition;
2486 //There was no inset at the beginning, so we need to create one with
2487 //the key and label of the one we erased.
2488 InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2489 // restore values of previously deleted item in this par.
2490 if (!oldkey.empty())
2491 inset->setParam("key", oldkey);
2492 inset->setParam("label", oldlabel);
2493 insertInset(0, static_cast<Inset *>(inset),
2494 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2500 unsigned int Paragraph::macrocontextPosition() const
2502 return d->macrocontext_position_;
2506 void Paragraph::setMacrocontextPosition(unsigned int pos)
2508 d->macrocontext_position_ = pos;
2512 void Paragraph::checkAuthors(AuthorList const & authorList)
2514 d->changes_.checkAuthors(authorList);
2518 bool Paragraph::isUnchanged(pos_type pos) const
2520 return lookupChange(pos).type == Change::UNCHANGED;
2524 bool Paragraph::isInserted(pos_type pos) const
2526 return lookupChange(pos).type == Change::INSERTED;
2530 bool Paragraph::isDeleted(pos_type pos) const
2532 return lookupChange(pos).type == Change::DELETED;
2536 InsetList const & Paragraph::insetList() const
2538 return d->insetlist_;
2542 Inset * Paragraph::releaseInset(pos_type pos)
2544 Inset * inset = d->insetlist_.release(pos);
2545 /// does not honour change tracking!
2546 eraseChar(pos, false);
2551 Inset * Paragraph::getInset(pos_type pos)
2553 return d->insetlist_.get(pos);
2557 Inset const * Paragraph::getInset(pos_type pos) const
2559 return d->insetlist_.get(pos);
2563 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2564 pos_type right, TextCase action)
2566 // process sequences of modified characters; in change
2567 // tracking mode, this approach results in much better
2568 // usability than changing case on a char-by-char basis
2571 bool const trackChanges = bparams.trackChanges;
2573 bool capitalize = true;
2575 for (; pos < right; ++pos) {
2576 char_type oldChar = d->text_[pos];
2577 char_type newChar = oldChar;
2579 // ignore insets and don't play with deleted text!
2580 if (oldChar != META_INSET && !isDeleted(pos)) {
2582 case text_lowercase:
2583 newChar = lowercase(oldChar);
2585 case text_capitalization:
2587 newChar = uppercase(oldChar);
2591 case text_uppercase:
2592 newChar = uppercase(oldChar);
2597 if (!isLetter(pos) || isDeleted(pos)) {
2598 // permit capitalization again
2602 if (oldChar != newChar)
2605 if (oldChar == newChar || pos == right - 1) {
2606 if (oldChar != newChar) {
2607 // step behind the changing area
2610 int erasePos = pos - changes.size();
2611 for (size_t i = 0; i < changes.size(); i++) {
2612 insertChar(pos, changes[i],
2613 getFontSettings(bparams,
2616 if (!eraseChar(erasePos, trackChanges)) {
2619 ++right; // expand selection
2628 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2629 pos_type pos, bool del) const
2631 int const strsize = str.length();
2633 pos_type const parsize = d->text_.size();
2634 for (i = 0; pos + i < parsize; ++i) {
2637 if (cs && str[i] != d->text_[pos + i])
2639 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2641 if (!del && isDeleted(pos + i))
2648 // if necessary, check whether string matches word
2650 if (pos > 0 && isLetter(pos - 1))
2652 if (pos + strsize < parsize
2653 && isLetter(pos + strsize))
2661 char_type Paragraph::getChar(pos_type pos) const
2663 return d->text_[pos];
2667 pos_type Paragraph::size() const
2669 return d->text_.size();
2673 bool Paragraph::empty() const
2675 return d->text_.empty();
2679 bool Paragraph::isInset(pos_type pos) const
2681 return d->text_[pos] == META_INSET;
2685 bool Paragraph::isSeparator(pos_type pos) const
2687 //FIXME: Are we sure this can be the only separator?
2688 return d->text_[pos] == ' ';