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"
51 // needed only for inTableCell()
52 #include "insets/InsetText.h"
54 #include "support/convert.h"
55 #include "support/debug.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);
89 void insertChar(pos_type pos, char_type c, Change const & change);
91 /// Output the surrogate pair formed by \p c and \p next to \p os.
92 /// \return the number of characters written.
93 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
96 /// Output a space in appropriate formatting (or a surrogate pair
97 /// if the next character is a combining character).
98 /// \return whether a surrogate pair was output.
99 bool simpleTeXBlanks(OutputParams const &,
100 odocstream &, TexRow & texrow,
102 unsigned int & column,
104 Layout const & style);
106 /// Output consecutive unicode chars, belonging to the same script as
107 /// specified by the latex macro \p ltx, to \p os starting from \p i.
108 /// \return the number of characters written.
109 int writeScriptChars(odocstream & os, docstring const & ltx,
110 Change &, Encoding const &, pos_type & i);
112 /// This could go to ParagraphParameters if we want to.
113 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
116 /// This could go to ParagraphParameters if we want to.
117 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
121 void latexInset(BufferParams const &,
123 TexRow & texrow, OutputParams &,
126 Font const & outerfont,
128 Change & running_change,
129 Layout const & style,
131 unsigned int & column);
134 void latexSpecialChar(
136 OutputParams & runparams,
138 Change & running_change,
139 Layout const & style,
141 unsigned int & column);
148 unsigned int & column);
150 bool latexSpecialTypewriter(
154 unsigned int & column);
156 bool latexSpecialPhrase(
159 unsigned int & column,
160 OutputParams & runparams);
163 void validate(LaTeXFeatures & features,
164 Layout const & layout) const;
166 /// Checks if the paragraph contains only text and no inset or font change.
167 bool onlyText(Buffer const & buf, Font const & outerfont,
168 pos_type initial) const;
170 /// match a string against a particular point in the paragraph
171 bool isTextAt(string const & str, pos_type pos) const;
173 /// Which Paragraph owns us?
177 Inset * inset_owner_;
185 static unsigned int paragraph_id;
187 ParagraphParameters params_;
189 /// for recording and looking up changes
193 InsetList insetlist_;
196 pos_type begin_of_body_;
198 typedef docstring TextContainer;
202 typedef std::set<docstring> Words;
206 Layout const * layout_;
210 // Initialization of the counter for the paragraph id's,
211 unsigned int Paragraph::Private::paragraph_id = 0;
215 struct special_phrase {
221 special_phrase const special_phrases[] = {
222 { "LyX", from_ascii("\\LyX{}"), false },
223 { "TeX", from_ascii("\\TeX{}"), true },
224 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
225 { "LaTeX", from_ascii("\\LaTeX{}"), true },
228 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
233 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
234 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
236 id_ = paragraph_id++;
241 Paragraph::Private::Private(Private const & p, Paragraph * owner)
242 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
243 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
244 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
247 id_ = paragraph_id++;
251 bool Paragraph::isChanged(pos_type start, pos_type end) const
253 BOOST_ASSERT(start >= 0 && start <= size());
254 BOOST_ASSERT(end > start && end <= size() + 1);
256 return d->changes_.isChanged(start, end);
260 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
262 // keep the logic here in sync with the logic of eraseChars()
266 Change const change = d->changes_.lookup(size());
267 return change.type == Change::INSERTED && change.author == 0;
271 void Paragraph::setChange(Change const & change)
273 // beware of the imaginary end-of-par character!
274 d->changes_.set(change, 0, size() + 1);
277 * Propagate the change recursively - but not in case of DELETED!
279 * Imagine that your co-author makes changes in an existing inset. He
280 * sends your document to you and you come to the conclusion that the
281 * inset should go completely. If you erase it, LyX must not delete all
282 * text within the inset. Otherwise, the change tracked insertions of
283 * your co-author get lost and there is no way to restore them later.
285 * Conclusion: An inset's content should remain untouched if you delete it
288 if (change.type != Change::DELETED) {
289 for (pos_type pos = 0; pos < size(); ++pos) {
290 if (Inset * inset = getInset(pos))
291 inset->setChange(change);
297 void Paragraph::setChange(pos_type pos, Change const & change)
299 BOOST_ASSERT(pos >= 0 && pos <= size());
300 d->changes_.set(change, pos);
302 // see comment in setChange(Change const &) above
303 if (change.type != Change::DELETED && pos < size())
304 if (Inset * inset = getInset(pos))
305 inset->setChange(change);
309 Change const & Paragraph::lookupChange(pos_type pos) const
311 BOOST_ASSERT(pos >= 0 && pos <= size());
312 return d->changes_.lookup(pos);
316 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
319 BOOST_ASSERT(start >= 0 && start <= size());
320 BOOST_ASSERT(end > start && end <= size() + 1);
322 for (pos_type pos = start; pos < end; ++pos) {
323 switch (lookupChange(pos).type) {
324 case Change::UNCHANGED:
325 // accept changes in nested inset
326 if (Inset * inset = getInset(pos))
327 inset->acceptChanges(bparams);
330 case Change::INSERTED:
331 d->changes_.set(Change(Change::UNCHANGED), pos);
332 // also accept changes in nested inset
333 if (Inset * inset = getInset(pos))
334 inset->acceptChanges(bparams);
337 case Change::DELETED:
338 // Suppress access to non-existent
339 // "end-of-paragraph char"
341 eraseChar(pos, false);
352 void Paragraph::rejectChanges(BufferParams const & bparams,
353 pos_type start, pos_type end)
355 BOOST_ASSERT(start >= 0 && start <= size());
356 BOOST_ASSERT(end > start && end <= size() + 1);
358 for (pos_type pos = start; pos < end; ++pos) {
359 switch (lookupChange(pos).type) {
360 case Change::UNCHANGED:
361 // reject changes in nested inset
362 if (Inset * inset = getInset(pos))
363 inset->rejectChanges(bparams);
366 case Change::INSERTED:
367 // Suppress access to non-existent
368 // "end-of-paragraph char"
370 eraseChar(pos, false);
376 case Change::DELETED:
377 d->changes_.set(Change(Change::UNCHANGED), pos);
379 // Do NOT reject changes within a deleted inset!
380 // There may be insertions of a co-author inside of it!
388 void Paragraph::Private::insertChar(pos_type pos, char_type c,
389 Change const & change)
391 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
394 changes_.insert(change, pos);
396 // This is actually very common when parsing buffers (and
397 // maybe inserting ascii text)
398 if (pos == pos_type(text_.size())) {
399 // when appending characters, no need to update tables
404 text_.insert(text_.begin() + pos, c);
406 // Update the font table.
407 fontlist_.increasePosAfterPos(pos);
410 insetlist_.increasePosAfterPos(pos);
414 void Paragraph::insertInset(pos_type pos, Inset * inset,
415 Change const & change)
418 BOOST_ASSERT(pos >= 0 && pos <= size());
420 d->insertChar(pos, META_INSET, change);
421 BOOST_ASSERT(d->text_[pos] == META_INSET);
423 // Add a new entry in the insetlist_.
424 d->insetlist_.insert(inset, pos);
428 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
430 BOOST_ASSERT(pos >= 0 && pos <= size());
432 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
435 Change change = d->changes_.lookup(pos);
437 // set the character to DELETED if
438 // a) it was previously unchanged or
439 // b) it was inserted by a co-author
441 if (change.type == Change::UNCHANGED ||
442 (change.type == Change::INSERTED && change.author != 0)) {
443 setChange(pos, Change(Change::DELETED));
447 if (change.type == Change::DELETED)
451 // Don't physically access the imaginary end-of-paragraph character.
452 // eraseChar() can only mark it as DELETED. A physical deletion of
453 // end-of-par must be handled externally.
459 d->changes_.erase(pos);
461 // if it is an inset, delete the inset entry
462 if (d->text_[pos] == META_INSET)
463 d->insetlist_.erase(pos);
465 d->text_.erase(d->text_.begin() + pos);
467 // Update the fontlist_
468 d->fontlist_.erase(pos);
470 // Update the insetlist_
471 d->insetlist_.decreasePosAfterPos(pos);
477 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
479 BOOST_ASSERT(start >= 0 && start <= size());
480 BOOST_ASSERT(end >= start && end <= size() + 1);
483 for (pos_type count = end - start; count; --count) {
484 if (!eraseChar(i, trackChanges))
491 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
492 char_type next, Encoding const & encoding)
494 // Writing next here may circumvent a possible font change between
495 // c and next. Since next is only output if it forms a surrogate pair
496 // with c we can ignore this:
497 // A font change inside a surrogate pair does not make sense and is
498 // hopefully impossible to input.
499 // FIXME: change tracking
500 // Is this correct WRT change tracking?
501 docstring const latex1 = encoding.latexChar(next);
502 docstring const latex2 = encoding.latexChar(c);
503 os << latex1 << '{' << latex2 << '}';
504 return latex1.length() + latex2.length() + 2;
508 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
509 odocstream & os, TexRow & texrow,
511 unsigned int & column,
513 Layout const & style)
515 if (style.pass_thru || runparams.verbatim)
518 if (i + 1 < int(text_.size())) {
519 char_type next = text_[i + 1];
520 if (Encodings::isCombiningChar(next)) {
521 Encoding const & encoding = *(runparams.encoding);
522 // This space has an accent, so we must always output it.
523 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
528 if (lyxrc.plaintext_linelen > 0
529 && column > lyxrc.plaintext_linelen
531 && text_[i - 1] != ' '
532 && (i + 1 < int(text_.size()))
533 // same in FreeSpacing mode
534 && !owner_->isFreeSpacing()
535 // In typewriter mode, we want to avoid
536 // ! . ? : at the end of a line
537 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
538 && (text_[i - 1] == '.'
539 || text_[i - 1] == '?'
540 || text_[i - 1] == ':'
541 || text_[i - 1] == '!'))) {
544 texrow.start(owner_->id(), i + 1);
546 } else if (style.free_spacing) {
555 int Paragraph::Private::writeScriptChars(odocstream & os,
556 docstring const & ltx,
557 Change & runningChange,
558 Encoding const & encoding,
561 // FIXME: modifying i here is not very nice...
563 // We only arrive here when a proper language for character text_[i] has
564 // not been specified (i.e., it could not be translated in the current
565 // latex encoding) and it belongs to a known script.
566 // Parameter ltx contains the latex translation of text_[i] as specified in
567 // the unicodesymbols file and is something like "\textXXX{<spec>}".
568 // The latex macro name "textXXX" specifies the script to which text_[i]
569 // belongs and we use it in order to check whether characters from the
570 // same script immediately follow, such that we can collect them in a
571 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
572 // for the first char but only "<spec>" for all subsequent chars.
573 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
574 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
575 string script = to_ascii(ltx.substr(1, brace1 - 1));
576 int length = ltx.substr(0, brace2).length();
577 os << ltx.substr(0, brace2);
578 int size = text_.size();
579 while (i + 1 < size) {
580 char_type const next = text_[i + 1];
581 // Stop here if next character belongs to another script
582 // or there is a change in change tracking status.
583 if (!Encodings::isKnownScriptChar(next, script) ||
584 runningChange != owner_->lookupChange(i + 1))
588 FontList::const_iterator cit = fontlist_.begin();
589 FontList::const_iterator end = fontlist_.end();
590 for (; cit != end; ++cit) {
591 if (cit->pos() >= i && !found) {
592 prev_font = cit->font();
595 if (cit->pos() >= i + 1)
598 // Stop here if there is a font attribute or encoding change.
599 if (found && cit != end && prev_font != cit->font())
601 docstring const latex = encoding.latexChar(next);
602 docstring::size_type const b1 =
603 latex.find_first_of(from_ascii("{"));
604 docstring::size_type const b2 =
605 latex.find_last_of(from_ascii("}"));
606 int const len = b2 - b1 - 1;
607 os << latex.substr(b1 + 1, len);
617 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
619 pos_type const len = str.length();
621 // is the paragraph large enough?
622 if (pos + len > int(text_.size()))
625 // does the wanted text start at point?
626 for (string::size_type i = 0; i < str.length(); ++i) {
627 // Caution: direct comparison of characters works only
628 // because str is pure ASCII.
629 if (str[i] != text_[pos + i])
633 return fontlist_.hasChangeInRange(pos, len);
637 void Paragraph::Private::latexInset(
638 BufferParams const & bparams,
641 OutputParams & runparams,
644 Font const & outerfont,
646 Change & running_change,
647 Layout const & style,
649 unsigned int & column)
651 Inset * inset = owner_->getInset(i);
654 if (style.pass_thru) {
655 inset->plaintext(os, runparams);
659 // FIXME: move this to InsetNewline::latex
660 if (inset->lyxCode() == NEWLINE_CODE) {
661 // newlines are handled differently here than
662 // the default in simpleTeXSpecialChars().
663 if (!style.newline_allowed) {
667 column += running_font.latexWriteEndChanges(
668 os, bparams, runparams,
673 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
676 basefont = owner_->getLayoutFont(bparams, outerfont);
677 running_font = basefont;
679 if (runparams.moving_arg)
684 texrow.start(owner_->id(), i + 1);
688 if (owner_->lookupChange(i).type == Change::DELETED) {
689 if( ++runparams.inDeletedInset == 1)
690 runparams.changeOfDeletedInset = owner_->lookupChange(i);
693 if (inset->canTrackChanges()) {
694 column += Changes::latexMarkChange(os, bparams, running_change,
695 Change(Change::UNCHANGED));
696 running_change = Change(Change::UNCHANGED);
700 odocstream::pos_type const len = os.tellp();
702 if (inset->forceLTR()
703 && running_font.isRightToLeft()
704 // ERT is an exception, it should be output with no decorations at all
705 && inset->lyxCode() != ERT_CODE) {
706 if (running_font.language()->lang() == "farsi")
713 // FIXME: Bug: we can have an empty font change here!
714 // if there has just been a font change, we are going to close it
715 // right now, which means stupid latex code like \textsf{}. AFAIK,
716 // this does not harm dvi output. A minor bug, thus (JMarc)
718 // Some insets cannot be inside a font change command.
719 // However, even such insets *can* be placed in \L or \R
720 // or their equivalents (for RTL language switches), so we don't
721 // close the language in those cases.
722 // ArabTeX, though, cannot handle this special behavior, it seems.
723 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
724 || running_font.language()->lang() == "arabic_arabtex";
725 if (open_font && inset->noFontChange()) {
726 bool closeLanguage = arabtex
727 || basefont.isRightToLeft() == running_font.isRightToLeft();
728 unsigned int count = running_font.latexWriteEndChanges(os,
729 bparams, runparams, basefont, basefont, closeLanguage);
731 // if any font properties were closed, update the running_font,
732 // making sure, however, to leave the language as it was
734 // FIXME: probably a better way to keep track of the old
735 // language, than copying the entire font?
736 Font const copy_font(running_font);
737 basefont = owner_->getLayoutFont(bparams, outerfont);
738 running_font = basefont;
740 running_font.setLanguage(copy_font.language());
741 // leave font open if language is still open
742 open_font = (running_font.language() == basefont.language());
744 runparams.local_font = &basefont;
748 int tmp = inset->latex(os, runparams);
751 if (running_font.language()->lang() == "farsi")
758 for (int j = 0; j < tmp; ++j)
761 texrow.start(owner_->id(), i + 1);
764 column += os.tellp() - len;
767 if (owner_->lookupChange(i).type == Change::DELETED)
768 --runparams.inDeletedInset;
772 void Paragraph::Private::latexSpecialChar(
774 OutputParams & runparams,
776 Change & running_change,
777 Layout const & style,
779 unsigned int & column)
781 char_type const c = text_[i];
783 if (style.pass_thru) {
785 // FIXME UNICODE: This can fail if c cannot
786 // be encoded in the current encoding.
791 if (runparams.verbatim) {
796 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
799 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
800 && latexSpecialTypewriter(c, os, i, column))
803 // Otherwise, we use what LaTeX provides us.
806 os << "\\textbackslash{}";
810 os << "\\textless{}";
814 os << "\\textgreater{}";
825 os << "\\char`\\\"{}";
830 case '%': case '#': case '{':
838 os << "\\textasciitilde{}";
843 os << "\\textasciicircum{}";
848 // avoid being mistaken for optional arguments
856 // Blanks are printed before font switching.
857 // Sure? I am not! (try nice-latex)
858 // I am sure it's correct. LyX might be smarter
859 // in the future, but for now, nothing wrong is
866 if (latexSpecialPhrase(os, i, column, runparams))
872 Encoding const & encoding = *(runparams.encoding);
873 if (i + 1 < int(text_.size())) {
874 char_type next = text_[i + 1];
875 if (Encodings::isCombiningChar(next)) {
876 column += latexSurrogatePair(os, c, next, encoding) - 1;
882 docstring const latex = encoding.latexChar(c);
883 if (Encodings::isKnownScriptChar(c, script)
884 && prefixIs(latex, from_ascii("\\" + script)))
885 column += writeScriptChars(os, latex,
886 running_change, encoding, i) - 1;
887 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
888 // Prevent eating of a following
889 // space or command corruption by
890 // following characters
891 column += latex.length() + 1;
894 column += latex.length() - 1;
902 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
903 pos_type & i, unsigned int & column)
909 // In T1 encoding, these characters exist
910 // but we should avoid ligatures
911 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
916 //os << "\\textcompwordmark{}";
928 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
929 pos_type & i, unsigned int & column)
933 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
934 // "--" in Typewriter mode -> "-{}-"
941 // I assume this is hack treating typewriter as verbatim
942 // FIXME UNICODE: This can fail if c cannot be encoded
943 // in the current encoding.
948 // Those characters are not directly supported.
952 case '%': case '#': case '{':
961 // With Typewriter font, these characters exist.
968 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
969 unsigned int & column, OutputParams & runparams)
971 // FIXME: if we have "LaTeX" with a font
972 // change in the middle (before the 'T', then
973 // the "TeX" part is still special cased.
974 // Really we should only operate this on
975 // "words" for some definition of word
977 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
978 if (!isTextAt(special_phrases[pnr].phrase, i))
980 if (runparams.moving_arg)
982 os << special_phrases[pnr].macro;
983 i += special_phrases[pnr].phrase.length() - 1;
984 column += special_phrases[pnr].macro.length() - 1;
991 void Paragraph::Private::validate(LaTeXFeatures & features,
992 Layout const & layout) const
995 if (!params_.spacing().isDefault())
996 features.require("setspace");
999 features.useLayout(layout.name());
1002 fontlist_.validate(features);
1004 // then the indentation
1005 if (!params_.leftIndent().zero())
1006 features.require("ParagraphLeftIndent");
1009 InsetList::const_iterator icit = insetlist_.begin();
1010 InsetList::const_iterator iend = insetlist_.end();
1011 for (; icit != iend; ++icit) {
1013 icit->inset->validate(features);
1014 if (layout.needprotect &&
1015 icit->inset->lyxCode() == FOOT_CODE)
1016 features.require("NeedLyXFootnoteCode");
1020 // then the contents
1021 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1022 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1023 if (!special_phrases[pnr].builtin
1024 && isTextAt(special_phrases[pnr].phrase, i)) {
1025 features.require(special_phrases[pnr].phrase);
1029 Encodings::validate(text_[i], features);
1033 /////////////////////////////////////////////////////////////////////
1037 /////////////////////////////////////////////////////////////////////
1040 Layout const emptyParagraphLayout;
1043 Paragraph::Paragraph()
1044 : d(new Paragraph::Private(this, emptyParagraphLayout))
1051 Paragraph::Paragraph(Paragraph const & par)
1052 : itemdepth(par.itemdepth),
1053 d(new Paragraph::Private(*par.d, this))
1059 Paragraph & Paragraph::operator=(Paragraph const & par)
1061 // needed as we will destroy the private part before copying it
1063 itemdepth = par.itemdepth;
1067 d = new Private(*par.d, this);
1074 Paragraph::~Paragraph()
1081 void Paragraph::write(ostream & os, BufferParams const & bparams,
1082 depth_type & dth) const
1084 // The beginning or end of a deeper (i.e. nested) area?
1085 if (dth != d->params_.depth()) {
1086 if (d->params_.depth() > dth) {
1087 while (d->params_.depth() > dth) {
1088 os << "\n\\begin_deeper";
1092 while (d->params_.depth() < dth) {
1093 os << "\n\\end_deeper";
1099 // First write the layout
1100 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1102 d->params_.write(os);
1104 Font font1(inherit_font, bparams.language);
1106 Change running_change = Change(Change::UNCHANGED);
1109 for (pos_type i = 0; i <= size(); ++i) {
1111 Change change = lookupChange(i);
1112 Changes::lyxMarkChange(os, column, running_change, change);
1113 running_change = change;
1118 // Write font changes
1119 Font font2 = getFontSettings(bparams, i);
1120 if (font2 != font1) {
1121 font2.lyxWriteChanges(font1, os);
1126 char_type const c = d->text_[i];
1129 if (Inset const * inset = getInset(i)) {
1130 if (inset->directWrite()) {
1131 // international char, let it write
1132 // code directly so it's shorter in
1138 os << "\\begin_inset ";
1140 os << "\n\\end_inset\n\n";
1146 os << "\n\\backslash\n";
1150 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1157 if ((column > 70 && c == ' ')
1162 // this check is to amend a bug. LyX sometimes
1163 // inserts '\0' this could cause problems.
1165 os << to_utf8(docstring(1, c));
1167 lyxerr << "ERROR (Paragraph::writeFile):"
1168 " NULL char in structure." << endl;
1174 os << "\n\\end_layout\n";
1178 void Paragraph::validate(LaTeXFeatures & features) const
1180 d->validate(features, *d->layout_);
1184 void Paragraph::insert(pos_type start, docstring const & str,
1185 Font const & font, Change const & change)
1187 for (size_t i = 0, n = str.size(); i != n ; ++i)
1188 insertChar(start + i, str[i], font, change);
1192 void Paragraph::appendChar(char_type c, Font const & font,
1193 Change const & change)
1196 d->changes_.insert(change, d->text_.size());
1197 // when appending characters, no need to update tables
1198 d->text_.push_back(c);
1199 setFont(d->text_.size() - 1, font);
1203 void Paragraph::appendString(docstring const & s, Font const & font,
1204 Change const & change)
1206 pos_type end = s.size();
1207 size_t oldsize = d->text_.size();
1208 size_t newsize = oldsize + end;
1209 size_t capacity = d->text_.capacity();
1210 if (newsize >= capacity)
1211 d->text_.reserve(max(capacity + 100, newsize));
1213 // when appending characters, no need to update tables
1216 // FIXME: Optimize this!
1217 for (pos_type i = 0; i != end; ++i) {
1219 d->changes_.insert(change, i);
1221 d->fontlist_.set(oldsize, font);
1222 d->fontlist_.set(newsize - 1, font);
1226 void Paragraph::insertChar(pos_type pos, char_type c,
1229 d->insertChar(pos, c, Change(trackChanges ?
1230 Change::INSERTED : Change::UNCHANGED));
1234 void Paragraph::insertChar(pos_type pos, char_type c,
1235 Font const & font, bool trackChanges)
1237 d->insertChar(pos, c, Change(trackChanges ?
1238 Change::INSERTED : Change::UNCHANGED));
1243 void Paragraph::insertChar(pos_type pos, char_type c,
1244 Font const & font, Change const & change)
1246 d->insertChar(pos, c, change);
1251 void Paragraph::insertInset(pos_type pos, Inset * inset,
1252 Font const & font, Change const & change)
1254 insertInset(pos, inset, change);
1255 // Set the font/language of the inset...
1260 bool Paragraph::insetAllowed(InsetCode code)
1262 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1266 void Paragraph::resetFonts(Font const & font)
1268 d->fontlist_.clear();
1269 d->fontlist_.set(0, font);
1270 d->fontlist_.set(d->text_.size() - 1, font);
1273 // Gets uninstantiated font setting at position.
1274 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1278 lyxerr << " pos: " << pos << " size: " << size() << endl;
1279 BOOST_ASSERT(pos <= size());
1282 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1283 if (cit != d->fontlist_.end())
1286 if (pos == size() && !empty())
1287 return getFontSettings(bparams, pos - 1);
1289 return Font(inherit_font, getParLanguage(bparams));
1293 FontSpan Paragraph::fontSpan(pos_type pos) const
1295 BOOST_ASSERT(pos <= size());
1298 FontList::const_iterator cit = d->fontlist_.begin();
1299 FontList::const_iterator end = d->fontlist_.end();
1300 for (; cit != end; ++cit) {
1301 if (cit->pos() >= pos) {
1302 if (pos >= beginOfBody())
1303 return FontSpan(max(start, beginOfBody()),
1306 return FontSpan(start,
1307 min(beginOfBody() - 1,
1310 start = cit->pos() + 1;
1313 // This should not happen, but if so, we take no chances.
1314 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1316 return FontSpan(pos, pos);
1320 // Gets uninstantiated font setting at position 0
1321 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1323 if (!empty() && !d->fontlist_.empty())
1324 return d->fontlist_.begin()->font();
1326 return Font(inherit_font, bparams.language);
1330 // Gets the fully instantiated font at a given position in a paragraph
1331 // This is basically the same function as Text::GetFont() in text2.cpp.
1332 // The difference is that this one is used for generating the LaTeX file,
1333 // and thus cosmetic "improvements" are disallowed: This has to deliver
1334 // the true picture of the buffer. (Asger)
1335 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1336 Font const & outerfont) const
1338 BOOST_ASSERT(pos >= 0);
1340 Font font = getFontSettings(bparams, pos);
1342 pos_type const body_pos = beginOfBody();
1344 font.fontInfo().realize(d->layout_->labelfont);
1346 font.fontInfo().realize(d->layout_->font);
1348 font.fontInfo().realize(outerfont.fontInfo());
1349 font.fontInfo().realize(bparams.getFont().fontInfo());
1355 Font const Paragraph::getLabelFont
1356 (BufferParams const & bparams, Font const & outerfont) const
1358 FontInfo tmpfont = d->layout_->labelfont;
1359 tmpfont.realize(outerfont.fontInfo());
1360 tmpfont.realize(bparams.getFont().fontInfo());
1361 return Font(tmpfont, getParLanguage(bparams));
1365 Font const Paragraph::getLayoutFont
1366 (BufferParams const & bparams, Font const & outerfont) const
1368 FontInfo tmpfont = d->layout_->font;
1369 tmpfont.realize(outerfont.fontInfo());
1370 tmpfont.realize(bparams.getFont().fontInfo());
1371 return Font(tmpfont, getParLanguage(bparams));
1375 /// Returns the height of the highest font in range
1376 FontSize Paragraph::highestFontInRange
1377 (pos_type startpos, pos_type endpos, FontSize def_size) const
1379 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1384 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1386 char_type c = d->text_[pos];
1387 if (!lyxrc.rtl_support)
1417 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1424 void Paragraph::setFont(pos_type pos, Font const & font)
1426 BOOST_ASSERT(pos <= size());
1428 // First, reduce font against layout/label font
1429 // Update: The setCharFont() routine in text2.cpp already
1430 // reduces font, so we don't need to do that here. (Asger)
1432 d->fontlist_.set(pos, font);
1436 void Paragraph::makeSameLayout(Paragraph const & par)
1438 d->layout_ = par.d->layout_;
1439 d->params_ = par.d->params_;
1443 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1445 if (isFreeSpacing())
1451 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1452 if (eraseChar(pos, trackChanges))
1458 return count > 0 || pos > 0;
1462 bool Paragraph::hasSameLayout(Paragraph const & par) const
1464 return par.d->layout_ == d->layout_
1465 && d->params_.sameLayout(par.d->params_);
1469 depth_type Paragraph::getDepth() const
1471 return d->params_.depth();
1475 depth_type Paragraph::getMaxDepthAfter() const
1477 if (d->layout_->isEnvironment())
1478 return d->params_.depth() + 1;
1480 return d->params_.depth();
1484 char Paragraph::getAlign() const
1486 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1487 return d->layout_->align;
1489 return d->params_.align();
1493 docstring const & Paragraph::labelString() const
1495 return d->params_.labelString();
1499 // the next two functions are for the manual labels
1500 docstring const Paragraph::getLabelWidthString() const
1502 if (d->layout_->margintype == MARGIN_MANUAL)
1503 return d->params_.labelWidthString();
1505 return _("Senseless with this layout!");
1509 void Paragraph::setLabelWidthString(docstring const & s)
1511 d->params_.labelWidthString(s);
1515 docstring const Paragraph::translateIfPossible(docstring const & s,
1516 BufferParams const & bparams) const
1518 if (!isAscii(s) || s.empty()) {
1519 // This must be a user defined layout. We cannot translate
1520 // this, since gettext accepts only ascii keys.
1523 // Probably standard layout, try to translate
1524 Messages & m = getMessages(getParLanguage(bparams)->code());
1525 return m.get(to_ascii(s));
1529 docstring Paragraph::expandLabel(Layout const & layout,
1530 BufferParams const & bparams, bool process_appendix) const
1532 DocumentClass const & tclass = bparams.documentClass();
1535 if (process_appendix && d->params_.appendix())
1536 fmt = translateIfPossible(layout.labelstring_appendix(),
1539 fmt = translateIfPossible(layout.labelstring(), bparams);
1541 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1542 && !layout.counter.empty())
1543 fmt = "\\the" + layout.counter;
1545 // handle 'inherited level parts' in 'fmt',
1546 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1547 size_t const i = fmt.find('@', 0);
1548 if (i != docstring::npos) {
1549 size_t const j = fmt.find('@', i + 1);
1550 if (j != docstring::npos) {
1551 docstring parent(fmt, i + 1, j - i - 1);
1552 docstring label = from_ascii("??");
1553 if (tclass.hasLayout(parent))
1554 docstring label = expandLabel(tclass[parent], bparams,
1556 fmt = docstring(fmt, 0, i) + label
1557 + docstring(fmt, j + 1, docstring::npos);
1561 return tclass.counters().counterLabel(fmt);
1565 void Paragraph::applyLayout(Layout const & new_layout)
1567 d->layout_ = &new_layout;
1568 LyXAlignment const oldAlign = d->params_.align();
1570 if (!(oldAlign & d->layout_->alignpossible)) {
1571 frontend::Alert::warning(_("Alignment not permitted"),
1572 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1573 d->params_.align(LYX_ALIGN_LAYOUT);
1578 pos_type Paragraph::beginOfBody() const
1580 return d->begin_of_body_;
1584 void Paragraph::setBeginOfBody()
1586 if (d->layout_->labeltype != LABEL_MANUAL) {
1587 d->begin_of_body_ = 0;
1591 // Unroll the first two cycles of the loop
1592 // and remember the previous character to
1593 // remove unnecessary getChar() calls
1595 pos_type end = size();
1596 if (i < end && !isNewline(i)) {
1598 char_type previous_char = 0;
1601 previous_char = d->text_[i];
1602 if (!isNewline(i)) {
1604 while (i < end && previous_char != ' ') {
1609 previous_char = temp;
1615 d->begin_of_body_ = i;
1619 bool Paragraph::forceEmptyLayout() const
1621 Inset const * const inset = inInset();
1622 return inset && inInset()->forceEmptyLayout();
1626 bool Paragraph::allowParagraphCustomization() const
1628 return inInset() && inInset()->allowParagraphCustomization(0);
1633 // This is a hack based upon one in InsetText::neverIndent().
1634 // When we have a real InsetTableCell, then we won't need this
1635 // method, because InsetTableCell will return the right values,
1636 // viz: InsetTableCell::useEmptyLayout() should return true, but
1637 // InsetTableCell::forceEmptyLayout() should still return false.
1639 // The #include "insets/InsetText.h" can also be removed then.
1640 bool inTableCell(Inset const * inset)
1642 InsetText const * txt = inset->asInsetText();
1645 return txt->isTableCell();
1650 bool Paragraph::useEmptyLayout() const
1652 Inset const * const inset = inInset();
1654 (inTableCell(inset) || inInset()->useEmptyLayout());
1660 // paragraphs inside floats need different alignment tags to avoid
1663 bool noTrivlistCentering(InsetCode code)
1665 return code == FLOAT_CODE || code == WRAP_CODE;
1669 string correction(string const & orig)
1671 if (orig == "flushleft")
1672 return "raggedright";
1673 if (orig == "flushright")
1674 return "raggedleft";
1675 if (orig == "center")
1681 string const corrected_env(string const & suffix, string const & env,
1684 string output = suffix + "{";
1685 if (noTrivlistCentering(code))
1686 output += correction(env);
1690 if (suffix == "\\begin")
1696 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1698 if (!contains(str, "\n"))
1699 column += str.size();
1703 column = rsplit(str, tmp, '\n').size();
1710 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1711 odocstream & os, TexRow & texrow,
1712 bool moving_arg) const
1716 if (params_.noindent()) {
1717 os << "\\noindent ";
1721 LyXAlignment const curAlign = params_.align();
1723 if (curAlign == layout_->align)
1727 case LYX_ALIGN_NONE:
1728 case LYX_ALIGN_BLOCK:
1729 case LYX_ALIGN_LAYOUT:
1730 case LYX_ALIGN_SPECIAL:
1732 case LYX_ALIGN_LEFT:
1733 case LYX_ALIGN_RIGHT:
1734 case LYX_ALIGN_CENTER:
1743 case LYX_ALIGN_NONE:
1744 case LYX_ALIGN_BLOCK:
1745 case LYX_ALIGN_LAYOUT:
1746 case LYX_ALIGN_SPECIAL:
1748 case LYX_ALIGN_LEFT: {
1750 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1751 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1753 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1754 os << from_ascii(output);
1755 adjust_row_column(output, texrow, column);
1757 } case LYX_ALIGN_RIGHT: {
1759 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1760 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1762 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1763 os << from_ascii(output);
1764 adjust_row_column(output, texrow, column);
1766 } case LYX_ALIGN_CENTER: {
1768 output = corrected_env("\\begin", "center", owner_->ownerCode());
1769 os << from_ascii(output);
1770 adjust_row_column(output, texrow, column);
1779 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1780 odocstream & os, TexRow & texrow,
1781 bool moving_arg) const
1785 switch (params_.align()) {
1786 case LYX_ALIGN_NONE:
1787 case LYX_ALIGN_BLOCK:
1788 case LYX_ALIGN_LAYOUT:
1789 case LYX_ALIGN_SPECIAL:
1791 case LYX_ALIGN_LEFT:
1792 case LYX_ALIGN_RIGHT:
1793 case LYX_ALIGN_CENTER:
1801 switch (params_.align()) {
1802 case LYX_ALIGN_NONE:
1803 case LYX_ALIGN_BLOCK:
1804 case LYX_ALIGN_LAYOUT:
1805 case LYX_ALIGN_SPECIAL:
1807 case LYX_ALIGN_LEFT: {
1809 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1810 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1812 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1813 os << from_ascii(output);
1814 adjust_row_column(output, texrow, column);
1816 } case LYX_ALIGN_RIGHT: {
1818 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1819 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1821 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1822 os << from_ascii(output);
1823 adjust_row_column(output, texrow, column);
1825 } case LYX_ALIGN_CENTER: {
1827 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1828 os << from_ascii(output);
1829 adjust_row_column(output, texrow, column);
1838 // This one spits out the text of the paragraph
1839 bool Paragraph::latex(BufferParams const & bparams,
1840 Font const & outerfont,
1841 odocstream & os, TexRow & texrow,
1842 OutputParams const & runparams) const
1844 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1846 bool return_value = false;
1848 bool asdefault = forceEmptyLayout();
1850 Layout const & style = asdefault ?
1851 bparams.documentClass().emptyLayout() :
1854 // Current base font for all inherited font changes, without any
1855 // change caused by an individual character, except for the language:
1856 // It is set to the language of the first character.
1857 // As long as we are in the label, this font is the base font of the
1858 // label. Before the first body character it is set to the base font
1862 // Maybe we have to create a optional argument.
1863 pos_type body_pos = beginOfBody();
1864 unsigned int column = 0;
1867 // the optional argument is kept in curly brackets in
1868 // case it contains a ']'
1871 basefont = getLabelFont(bparams, outerfont);
1873 basefont = getLayoutFont(bparams, outerfont);
1876 // Which font is currently active?
1877 Font running_font(basefont);
1878 // Do we have an open font change?
1879 bool open_font = false;
1881 Change runningChange = Change(Change::UNCHANGED);
1883 texrow.start(id(), 0);
1885 // if the paragraph is empty, the loop will not be entered at all
1887 if (style.isCommand()) {
1892 column += d->startTeXParParams(bparams, os, texrow,
1893 runparams.moving_arg);
1896 for (pos_type i = 0; i < size(); ++i) {
1897 // First char in paragraph or after label?
1898 if (i == body_pos) {
1901 column += running_font.latexWriteEndChanges(
1902 os, bparams, runparams,
1903 basefont, basefont);
1906 basefont = getLayoutFont(bparams, outerfont);
1907 running_font = basefont;
1909 column += Changes::latexMarkChange(os, bparams,
1910 runningChange, Change(Change::UNCHANGED));
1911 runningChange = Change(Change::UNCHANGED);
1916 if (style.isCommand()) {
1922 column += d->startTeXParParams(bparams, os,
1924 runparams.moving_arg);
1927 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1930 if (bparams.outputChanges && runningChange != change) {
1932 column += running_font.latexWriteEndChanges(
1933 os, bparams, runparams, basefont, basefont);
1936 basefont = getLayoutFont(bparams, outerfont);
1937 running_font = basefont;
1939 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1940 runningChange = change;
1943 // do not output text which is marked deleted
1944 // if change tracking output is disabled
1945 if (!bparams.outputChanges && change.type == Change::DELETED) {
1951 // Fully instantiated font
1952 Font const font = getFont(bparams, i, outerfont);
1954 Font const last_font = running_font;
1956 // Do we need to close the previous font?
1958 (font != running_font ||
1959 font.language() != running_font.language()))
1961 column += running_font.latexWriteEndChanges(
1962 os, bparams, runparams, basefont,
1963 (i == body_pos-1) ? basefont : font);
1964 running_font = basefont;
1968 // close babel's font environment before opening CJK.
1969 if (!running_font.language()->babel().empty() &&
1970 font.language()->encoding()->package() == Encoding::CJK) {
1971 string end_tag = subst(lyxrc.language_command_end,
1973 running_font.language()->babel());
1974 os << from_ascii(end_tag);
1975 column += end_tag.length();
1978 // Switch file encoding if necessary (and allowed)
1979 if (!runparams.verbatim &&
1980 runparams.encoding->package() == Encoding::none &&
1981 font.language()->encoding()->package() == Encoding::none) {
1982 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1983 runparams, *(font.language()->encoding()));
1984 if (enc_switch.first) {
1985 column += enc_switch.second;
1986 runparams.encoding = font.language()->encoding();
1990 char_type const c = d->text_[i];
1992 // Do we need to change font?
1993 if ((font != running_font ||
1994 font.language() != running_font.language()) &&
1997 odocstringstream ods;
1998 column += font.latexWriteStartChanges(ods, bparams,
1999 runparams, basefont,
2001 running_font = font;
2003 docstring fontchange = ods.str();
2004 // check if the fontchange ends with a trailing blank
2005 // (like "\small " (see bug 3382)
2006 if (suffixIs(fontchange, ' ') && c == ' ')
2007 os << fontchange.substr(0, fontchange.size() - 1)
2008 << from_ascii("{}");
2014 // FIXME: integrate this case in latexSpecialChar
2015 // Do not print the separation of the optional argument
2016 // if style.pass_thru is false. This works because
2017 // latexSpecialChar ignores spaces if
2018 // style.pass_thru is false.
2019 if (i != body_pos - 1) {
2020 if (d->simpleTeXBlanks(
2021 runparams, os, texrow,
2022 i, column, font, style)) {
2023 // A surrogate pair was output. We
2024 // must not call latexSpecialChar
2025 // in this iteration, since it would output
2026 // the combining character again.
2033 OutputParams rp = runparams;
2034 rp.free_spacing = style.free_spacing;
2035 rp.local_font = &font;
2036 rp.intitle = style.intitle;
2038 // Two major modes: LaTeX or plain
2039 // Handle here those cases common to both modes
2040 // and then split to handle the two modes separately.
2041 if (c == META_INSET)
2042 d->latexInset(bparams, os,
2043 texrow, rp, running_font,
2044 basefont, outerfont, open_font,
2045 runningChange, style, i, column);
2048 d->latexSpecialChar(os, rp, running_font, runningChange,
2050 } catch (EncodingException & e) {
2051 if (runparams.dryrun) {
2052 os << "<" << _("LyX Warning: ")
2053 << _("uncodable character") << " '";
2057 // add location information and throw again.
2065 // Set the encoding to that returned from simpleTeXSpecialChars (see
2066 // comment for encoding member in OutputParams.h)
2067 runparams.encoding = rp.encoding;
2070 // If we have an open font definition, we have to close it
2072 #ifdef FIXED_LANGUAGE_END_DETECTION
2075 .latexWriteEndChanges(os, bparams, runparams,
2077 next_->getFont(bparams, 0, outerfont));
2079 running_font.latexWriteEndChanges(os, bparams,
2080 runparams, basefont, basefont);
2083 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2084 //FIXME: there as we start another \selectlanguage with the next paragraph if
2085 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2086 running_font.latexWriteEndChanges(os, bparams, runparams,
2087 basefont, basefont);
2091 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2093 // Needed if there is an optional argument but no contents.
2094 if (body_pos > 0 && body_pos == size()) {
2096 return_value = false;
2100 column += d->endTeXParParams(bparams, os, texrow,
2101 runparams.moving_arg);
2104 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2105 return return_value;
2109 bool Paragraph::emptyTag() const
2111 for (pos_type i = 0; i < size(); ++i) {
2112 if (Inset const * inset = getInset(i)) {
2113 InsetCode lyx_code = inset->lyxCode();
2114 if (lyx_code != TOC_CODE &&
2115 lyx_code != INCLUDE_CODE &&
2116 lyx_code != GRAPHICS_CODE &&
2117 lyx_code != ERT_CODE &&
2118 lyx_code != LISTINGS_CODE &&
2119 lyx_code != FLOAT_CODE &&
2120 lyx_code != TABULAR_CODE) {
2124 char_type c = d->text_[i];
2125 if (c != ' ' && c != '\t')
2133 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2136 for (pos_type i = 0; i < size(); ++i) {
2137 if (Inset const * inset = getInset(i)) {
2138 InsetCode lyx_code = inset->lyxCode();
2139 if (lyx_code == LABEL_CODE) {
2140 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2141 docstring const & id = il->getParam("name");
2142 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2150 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2154 for (i = 0; i < size(); ++i) {
2155 if (Inset const * inset = getInset(i)) {
2156 inset->docbook(os, runparams);
2158 char_type c = d->text_[i];
2161 os << sgml::escapeChar(c);
2168 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2171 pos_type size = text_.size();
2172 for (pos_type i = initial; i < size; ++i) {
2173 Font font = owner_->getFont(buf.params(), i, outerfont);
2174 if (text_[i] == META_INSET)
2176 if (i != initial && font != font_old)
2185 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2187 OutputParams const & runparams,
2188 Font const & outerfont,
2189 pos_type initial) const
2191 bool emph_flag = false;
2193 Layout const & style = *d->layout_;
2195 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2197 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2200 // parsing main loop
2201 for (pos_type i = initial; i < size(); ++i) {
2202 Font font = getFont(buf.params(), i, outerfont);
2204 // handle <emphasis> tag
2205 if (font_old.emph() != font.fontInfo().emph()) {
2206 if (font.fontInfo().emph() == FONT_ON) {
2209 } else if (i != initial) {
2210 os << "</emphasis>";
2215 if (Inset const * inset = getInset(i)) {
2216 inset->docbook(os, runparams);
2218 char_type c = d->text_[i];
2220 if (style.pass_thru)
2223 os << sgml::escapeChar(c);
2225 font_old = font.fontInfo();
2229 os << "</emphasis>";
2232 if (style.free_spacing)
2234 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2239 bool Paragraph::isHfill(pos_type pos) const
2241 Inset const * inset = getInset(pos);
2242 return inset && (inset->lyxCode() == SPACE_CODE &&
2243 inset->isStretchableSpace());
2247 bool Paragraph::isNewline(pos_type pos) const
2249 Inset const * inset = getInset(pos);
2250 return inset && inset->lyxCode() == NEWLINE_CODE;
2254 bool Paragraph::isLineSeparator(pos_type pos) const
2256 char_type const c = d->text_[pos];
2257 if (isLineSeparatorChar(c))
2259 Inset const * inset = getInset(pos);
2260 return inset && inset->isLineSeparator();
2264 /// Used by the spellchecker
2265 bool Paragraph::isLetter(pos_type pos) const
2267 if (Inset const * inset = getInset(pos))
2268 return inset->isLetter();
2269 char_type const c = d->text_[pos];
2270 return isLetterChar(c) || isDigit(c);
2275 Paragraph::getParLanguage(BufferParams const & bparams) const
2278 return getFirstFontSettings(bparams).language();
2279 // FIXME: we should check the prev par as well (Lgb)
2280 return bparams.language;
2284 bool Paragraph::isRTL(BufferParams const & bparams) const
2286 return lyxrc.rtl_support
2287 && getParLanguage(bparams)->rightToLeft()
2288 && ownerCode() != ERT_CODE
2289 && ownerCode() != LISTINGS_CODE;
2293 void Paragraph::changeLanguage(BufferParams const & bparams,
2294 Language const * from, Language const * to)
2296 // change language including dummy font change at the end
2297 for (pos_type i = 0; i <= size(); ++i) {
2298 Font font = getFontSettings(bparams, i);
2299 if (font.language() == from) {
2300 font.setLanguage(to);
2307 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2309 Language const * doc_language = bparams.language;
2310 FontList::const_iterator cit = d->fontlist_.begin();
2311 FontList::const_iterator end = d->fontlist_.end();
2313 for (; cit != end; ++cit)
2314 if (cit->font().language() != ignore_language &&
2315 cit->font().language() != latex_language &&
2316 cit->font().language() != doc_language)
2322 docstring Paragraph::asString(bool label) const
2324 return asString(0, size(), label);
2328 docstring Paragraph::asString(pos_type beg, pos_type end, bool label) const
2331 odocstringstream os;
2333 if (beg == 0 && label && !d->params_.labelString().empty())
2334 os << d->params_.labelString() << ' ';
2336 for (pos_type i = beg; i < end; ++i) {
2337 char_type const c = d->text_[i];
2340 else if (c == META_INSET)
2341 getInset(i)->textString(os);
2348 void Paragraph::setInsetOwner(Inset * inset)
2350 d->inset_owner_ = inset;
2354 int Paragraph::id() const
2360 Layout const & Paragraph::layout() const
2366 void Paragraph::setLayout(Layout const & layout)
2368 d->layout_ = &layout;
2372 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2374 if (useEmptyLayout())
2375 setLayout(tclass.emptyLayout());
2377 setLayout(tclass.defaultLayout());
2381 Inset * Paragraph::inInset() const
2383 return d->inset_owner_;
2387 InsetCode Paragraph::ownerCode() const
2389 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2393 ParagraphParameters & Paragraph::params()
2399 ParagraphParameters const & Paragraph::params() const
2405 bool Paragraph::isFreeSpacing() const
2407 if (d->layout_->free_spacing)
2409 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2413 bool Paragraph::allowEmpty() const
2415 if (d->layout_->keepempty)
2417 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2421 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2423 if (!Encodings::is_arabic(c))
2426 char_type prev_char = ' ';
2427 char_type next_char = ' ';
2429 for (pos_type i = pos - 1; i >= 0; --i) {
2430 char_type const par_char = d->text_[i];
2431 if (!Encodings::isComposeChar_arabic(par_char)) {
2432 prev_char = par_char;
2437 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2438 char_type const par_char = d->text_[i];
2439 if (!Encodings::isComposeChar_arabic(par_char)) {
2440 next_char = par_char;
2445 if (Encodings::is_arabic(next_char)) {
2446 if (Encodings::is_arabic(prev_char) &&
2447 !Encodings::is_arabic_special(prev_char))
2448 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2450 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2452 if (Encodings::is_arabic(prev_char) &&
2453 !Encodings::is_arabic_special(prev_char))
2454 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2456 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2461 int Paragraph::checkBiblio(Buffer const & buffer)
2464 // This is getting more and more a mess. ...We really should clean
2465 // up this bibitem issue for 1.6. See also bug 2743.
2467 // Add bibitem insets if necessary
2468 if (d->layout_->labeltype != LABEL_BIBLIO)
2471 bool hasbibitem = !d->insetlist_.empty()
2472 // Insist on it being in pos 0
2473 && d->text_[0] == META_INSET
2474 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2476 bool track_changes = buffer.params().trackChanges;
2481 // remove a bibitem in pos != 0
2482 // restore it later in pos 0 if necessary
2483 // (e.g. if a user inserts contents _before_ the item)
2484 // we're assuming there's only one of these, which there
2486 int erasedInsetPosition = -1;
2487 InsetList::iterator it = d->insetlist_.begin();
2488 InsetList::iterator end = d->insetlist_.end();
2489 for (; it != end; ++it)
2490 if (it->inset->lyxCode() == BIBITEM_CODE
2492 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2493 oldkey = olditem->getParam("key");
2494 oldlabel = olditem->getParam("label");
2495 erasedInsetPosition = it->pos;
2496 eraseChar(erasedInsetPosition, track_changes);
2500 // There was an InsetBibitem at the beginning, and we didn't
2501 // have to erase one.
2502 if (hasbibitem && erasedInsetPosition < 0)
2505 // There was an InsetBibitem at the beginning and we did have to
2506 // erase one. So we give its properties to the beginning inset.
2508 InsetBibitem * inset =
2509 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2510 if (!oldkey.empty())
2511 inset->setParam("key", oldkey);
2512 inset->setParam("label", oldlabel);
2513 return -erasedInsetPosition;
2516 // There was no inset at the beginning, so we need to create one with
2517 // the key and label of the one we erased.
2518 InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2519 inset->setBuffer(const_cast<Buffer &>(buffer));
2520 // restore values of previously deleted item in this par.
2521 if (!oldkey.empty())
2522 inset->setParam("key", oldkey);
2523 inset->setParam("label", oldlabel);
2524 insertInset(0, static_cast<Inset *>(inset),
2525 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2531 void Paragraph::checkAuthors(AuthorList const & authorList)
2533 d->changes_.checkAuthors(authorList);
2537 bool Paragraph::isUnchanged(pos_type pos) const
2539 return lookupChange(pos).type == Change::UNCHANGED;
2543 bool Paragraph::isInserted(pos_type pos) const
2545 return lookupChange(pos).type == Change::INSERTED;
2549 bool Paragraph::isDeleted(pos_type pos) const
2551 return lookupChange(pos).type == Change::DELETED;
2555 InsetList const & Paragraph::insetList() const
2557 return d->insetlist_;
2561 Inset * Paragraph::releaseInset(pos_type pos)
2563 Inset * inset = d->insetlist_.release(pos);
2564 /// does not honour change tracking!
2565 eraseChar(pos, false);
2570 Inset * Paragraph::getInset(pos_type pos)
2572 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2573 ? d->insetlist_.get(pos) : 0;
2577 Inset const * Paragraph::getInset(pos_type pos) const
2579 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2580 ? d->insetlist_.get(pos) : 0;
2584 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2585 pos_type & right, TextCase action)
2587 // process sequences of modified characters; in change
2588 // tracking mode, this approach results in much better
2589 // usability than changing case on a char-by-char basis
2592 bool const trackChanges = bparams.trackChanges;
2594 bool capitalize = true;
2596 for (; pos < right; ++pos) {
2597 char_type oldChar = d->text_[pos];
2598 char_type newChar = oldChar;
2600 // ignore insets and don't play with deleted text!
2601 if (oldChar != META_INSET && !isDeleted(pos)) {
2603 case text_lowercase:
2604 newChar = lowercase(oldChar);
2606 case text_capitalization:
2608 newChar = uppercase(oldChar);
2612 case text_uppercase:
2613 newChar = uppercase(oldChar);
2618 if (!isLetter(pos) || isDeleted(pos)) {
2619 // permit capitalization again
2623 if (oldChar != newChar)
2626 if (oldChar == newChar || pos == right - 1) {
2627 if (oldChar != newChar) {
2628 // step behind the changing area
2631 int erasePos = pos - changes.size();
2632 for (size_t i = 0; i < changes.size(); i++) {
2633 insertChar(pos, changes[i],
2634 getFontSettings(bparams,
2637 if (!eraseChar(erasePos, trackChanges)) {
2640 ++right; // expand selection
2649 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2650 pos_type pos, bool del) const
2652 int const strsize = str.length();
2654 pos_type const parsize = d->text_.size();
2655 for (i = 0; pos + i < parsize; ++i) {
2658 if (cs && str[i] != d->text_[pos + i])
2660 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2662 if (!del && isDeleted(pos + i))
2669 // if necessary, check whether string matches word
2671 if (pos > 0 && isLetter(pos - 1))
2673 if (pos + strsize < parsize
2674 && isLetter(pos + strsize))
2682 char_type Paragraph::getChar(pos_type pos) const
2684 return d->text_[pos];
2688 pos_type Paragraph::size() const
2690 return d->text_.size();
2694 bool Paragraph::empty() const
2696 return d->text_.empty();
2700 bool Paragraph::isInset(pos_type pos) const
2702 return d->text_[pos] == META_INSET;
2706 bool Paragraph::isSeparator(pos_type pos) const
2708 //FIXME: Are we sure this can be the only separator?
2709 return d->text_[pos] == ' ';
2713 void Paragraph::deregisterWords()
2715 Private::Words::const_iterator it;
2716 WordList & wl = theWordList();
2717 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2723 void Paragraph::collectWords(CursorSlice const & sl)
2726 bool inword = false;
2728 //lyxerr << "Words: ";
2729 pos_type n = size();
2730 for (pos_type pos = 0; pos != n; ++pos) {
2734 if (!isLetter(pos)) {
2743 CursorSlice from = sl;
2744 CursorSlice to = sl;
2747 from.text()->getWord(from, to, WHOLE_WORD);
2748 if (to.pos() - from.pos() < 6)
2750 docstring word = asString(from.pos(), to.pos(), false);
2751 d->words_.insert(word);
2752 //lyxerr << word << " ";
2754 //lyxerr << std::endl;
2758 void Paragraph::registerWords()
2760 Private::Words::const_iterator it;
2761 WordList & wl = theWordList();
2762 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2767 void Paragraph::updateWords(CursorSlice const & sl)
2769 BOOST_ASSERT(&sl.paragraph() == this);