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"
62 using namespace lyx::support;
67 /// Inset identifier (above 0x10ffff, for ucs-4)
68 char_type const META_INSET = 0x200001;
71 /////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////
77 class Paragraph::Private
81 Private(Paragraph * owner);
82 /// "Copy constructor"
83 Private(Private const &, Paragraph * owner);
86 void insertChar(pos_type pos, char_type c, Change const & change);
88 /// Output the surrogate pair formed by \p c and \p next to \p os.
89 /// \return the number of characters written.
90 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
93 /// Output a space in appropriate formatting (or a surrogate pair
94 /// if the next character is a combining character).
95 /// \return whether a surrogate pair was output.
96 bool simpleTeXBlanks(OutputParams const &,
97 odocstream &, TexRow & texrow,
99 unsigned int & column,
101 Layout const & style);
103 /// Output consecutive unicode chars, belonging to the same script as
104 /// specified by the latex macro \p ltx, to \p os starting from \p i.
105 /// \return the number of characters written.
106 int writeScriptChars(odocstream & os, docstring const & ltx,
107 Change &, Encoding const &, pos_type & i);
109 /// This could go to ParagraphParameters if we want to.
110 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
113 /// This could go to ParagraphParameters if we want to.
114 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 void latexInset(Buffer const &, BufferParams const &,
120 TexRow & texrow, OutputParams &,
123 Font const & outerfont,
125 Change & running_change,
126 Layout const & style,
128 unsigned int & column);
131 void latexSpecialChar(
133 OutputParams & runparams,
135 Change & running_change,
136 Layout const & style,
138 unsigned int & column);
145 unsigned int & column);
147 bool latexSpecialTypewriter(
151 unsigned int & column);
153 bool latexSpecialPhrase(
156 unsigned int & column,
157 OutputParams & runparams);
160 void validate(LaTeXFeatures & features,
161 Layout const & layout) const;
163 /// Checks if the paragraph contains only text and no inset or font change.
164 bool onlyText(Buffer const & buf, Font const & outerfont,
165 pos_type initial) const;
167 /// match a string against a particular point in the paragraph
168 bool isTextAt(string const & str, pos_type pos) const;
170 /// Which Paragraph owns us?
174 Inset * inset_owner_;
182 static unsigned int paragraph_id;
184 ParagraphParameters params_;
186 /// for recording and looking up changes
190 InsetList insetlist_;
196 pos_type begin_of_body_;
198 typedef docstring TextContainer;
204 // Initialization of the counter for the paragraph id's,
205 unsigned int Paragraph::Private::paragraph_id = 0;
209 struct special_phrase {
215 special_phrase const special_phrases[] = {
216 { "LyX", from_ascii("\\LyX{}"), false },
217 { "TeX", from_ascii("\\TeX{}"), true },
218 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
219 { "LaTeX", from_ascii("\\LaTeX{}"), true },
222 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
227 Paragraph::Private::Private(Paragraph * owner)
228 : owner_(owner), inset_owner_(0), begin_of_body_(0)
230 id_ = paragraph_id++;
235 Paragraph::Private::Private(Private const & p, Paragraph * owner)
236 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
237 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
238 layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
240 id_ = paragraph_id++;
244 bool Paragraph::isChanged(pos_type start, pos_type end) const
246 BOOST_ASSERT(start >= 0 && start <= size());
247 BOOST_ASSERT(end > start && end <= size() + 1);
249 return d->changes_.isChanged(start, end);
253 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
254 // keep the logic here in sync with the logic of eraseChars()
260 Change change = d->changes_.lookup(size());
262 return change.type == Change::INSERTED && change.author == 0;
266 void Paragraph::setChange(Change const & change)
268 // beware of the imaginary end-of-par character!
269 d->changes_.set(change, 0, size() + 1);
272 * Propagate the change recursively - but not in case of DELETED!
274 * Imagine that your co-author makes changes in an existing inset. He
275 * sends your document to you and you come to the conclusion that the
276 * inset should go completely. If you erase it, LyX must not delete all
277 * text within the inset. Otherwise, the change tracked insertions of
278 * your co-author get lost and there is no way to restore them later.
280 * Conclusion: An inset's content should remain untouched if you delete it
283 if (change.type != Change::DELETED) {
284 for (pos_type pos = 0; pos < size(); ++pos) {
286 getInset(pos)->setChange(change);
292 void Paragraph::setChange(pos_type pos, Change const & change)
294 BOOST_ASSERT(pos >= 0 && pos <= size());
296 d->changes_.set(change, pos);
298 // see comment in setChange(Change const &) above
300 if (change.type != Change::DELETED &&
301 pos < size() && isInset(pos)) {
302 getInset(pos)->setChange(change);
307 Change const & Paragraph::lookupChange(pos_type pos) const
309 BOOST_ASSERT(pos >= 0 && pos <= size());
311 return d->changes_.lookup(pos);
315 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
318 BOOST_ASSERT(start >= 0 && start <= size());
319 BOOST_ASSERT(end > start && end <= size() + 1);
321 for (pos_type pos = start; pos < end; ++pos) {
322 switch (lookupChange(pos).type) {
323 case Change::UNCHANGED:
324 // accept changes in nested inset
325 if (pos < size() && isInset(pos))
326 getInset(pos)->acceptChanges(bparams);
330 case Change::INSERTED:
331 d->changes_.set(Change(Change::UNCHANGED), pos);
332 // also accept changes in nested inset
333 if (pos < size() && isInset(pos)) {
334 getInset(pos)->acceptChanges(bparams);
338 case Change::DELETED:
339 // Suppress access to non-existent
340 // "end-of-paragraph char"
342 eraseChar(pos, false);
353 void Paragraph::rejectChanges(BufferParams const & bparams,
354 pos_type start, pos_type end)
356 BOOST_ASSERT(start >= 0 && start <= size());
357 BOOST_ASSERT(end > start && end <= size() + 1);
359 for (pos_type pos = start; pos < end; ++pos) {
360 switch (lookupChange(pos).type) {
361 case Change::UNCHANGED:
362 // reject changes in nested inset
363 if (pos < size() && isInset(pos)) {
364 getInset(pos)->rejectChanges(bparams);
368 case Change::INSERTED:
369 // Suppress access to non-existent
370 // "end-of-paragraph char"
372 eraseChar(pos, false);
378 case Change::DELETED:
379 d->changes_.set(Change(Change::UNCHANGED), pos);
381 // Do NOT reject changes within a deleted inset!
382 // There may be insertions of a co-author inside of it!
390 void Paragraph::Private::insertChar(pos_type pos, char_type c,
391 Change const & change)
393 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
396 changes_.insert(change, pos);
398 // This is actually very common when parsing buffers (and
399 // maybe inserting ascii text)
400 if (pos == pos_type(text_.size())) {
401 // when appending characters, no need to update tables
406 text_.insert(text_.begin() + pos, c);
408 // Update the font table.
409 fontlist_.increasePosAfterPos(pos);
412 insetlist_.increasePosAfterPos(pos);
416 void Paragraph::insertInset(pos_type pos, Inset * inset,
417 Change const & change)
420 BOOST_ASSERT(pos >= 0 && pos <= size());
422 d->insertChar(pos, META_INSET, change);
423 BOOST_ASSERT(d->text_[pos] == META_INSET);
425 // Add a new entry in the insetlist_.
426 d->insetlist_.insert(inset, pos);
430 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
432 BOOST_ASSERT(pos >= 0 && pos <= size());
434 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
437 Change change = d->changes_.lookup(pos);
439 // set the character to DELETED if
440 // a) it was previously unchanged or
441 // b) it was inserted by a co-author
443 if (change.type == Change::UNCHANGED ||
444 (change.type == Change::INSERTED && change.author != 0)) {
445 setChange(pos, Change(Change::DELETED));
449 if (change.type == Change::DELETED)
453 // Don't physically access the imaginary end-of-paragraph character.
454 // eraseChar() can only mark it as DELETED. A physical deletion of
455 // end-of-par must be handled externally.
461 d->changes_.erase(pos);
463 // if it is an inset, delete the inset entry
464 if (d->text_[pos] == META_INSET)
465 d->insetlist_.erase(pos);
467 d->text_.erase(d->text_.begin() + pos);
469 // Update the fontlist_
470 d->fontlist_.erase(pos);
472 // Update the insetlist_
473 d->insetlist_.decreasePosAfterPos(pos);
479 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
481 BOOST_ASSERT(start >= 0 && start <= size());
482 BOOST_ASSERT(end >= start && end <= size() + 1);
485 for (pos_type count = end - start; count; --count) {
486 if (!eraseChar(i, trackChanges))
493 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
494 char_type next, Encoding const & encoding)
496 // Writing next here may circumvent a possible font change between
497 // c and next. Since next is only output if it forms a surrogate pair
498 // with c we can ignore this:
499 // A font change inside a surrogate pair does not make sense and is
500 // hopefully impossible to input.
501 // FIXME: change tracking
502 // Is this correct WRT change tracking?
503 docstring const latex1 = encoding.latexChar(next);
504 docstring const latex2 = encoding.latexChar(c);
505 os << latex1 << '{' << latex2 << '}';
506 return latex1.length() + latex2.length() + 2;
510 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
511 odocstream & os, TexRow & texrow,
513 unsigned int & column,
515 Layout const & style)
517 if (style.pass_thru || runparams.verbatim)
520 if (i + 1 < int(text_.size())) {
521 char_type next = text_[i + 1];
522 if (Encodings::isCombiningChar(next)) {
523 Encoding const & encoding = *(runparams.encoding);
524 // This space has an accent, so we must always output it.
525 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
530 if (lyxrc.plaintext_linelen > 0
531 && column > lyxrc.plaintext_linelen
533 && text_[i - 1] != ' '
534 && (i + 1 < int(text_.size()))
535 // same in FreeSpacing mode
536 && !owner_->isFreeSpacing()
537 // In typewriter mode, we want to avoid
538 // ! . ? : at the end of a line
539 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
540 && (text_[i - 1] == '.'
541 || text_[i - 1] == '?'
542 || text_[i - 1] == ':'
543 || text_[i - 1] == '!'))) {
546 texrow.start(owner_->id(), i + 1);
548 } else if (style.free_spacing) {
557 int Paragraph::Private::writeScriptChars(odocstream & os,
558 docstring const & ltx,
559 Change & runningChange,
560 Encoding const & encoding,
563 // FIXME: modifying i here is not very nice...
565 // We only arrive here when a proper language for character text_[i] has
566 // not been specified (i.e., it could not be translated in the current
567 // latex encoding) and it belongs to a known script.
568 // Parameter ltx contains the latex translation of text_[i] as specified in
569 // the unicodesymbols file and is something like "\textXXX{<spec>}".
570 // The latex macro name "textXXX" specifies the script to which text_[i]
571 // belongs and we use it in order to check whether characters from the
572 // same script immediately follow, such that we can collect them in a
573 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
574 // for the first char but only "<spec>" for all subsequent chars.
575 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
576 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
577 string script = to_ascii(ltx.substr(1, brace1 - 1));
578 int length = ltx.substr(0, brace2).length();
579 os << ltx.substr(0, brace2);
580 int size = text_.size();
581 while (i + 1 < size) {
582 char_type const next = text_[i + 1];
583 // Stop here if next character belongs to another script
584 // or there is a change in change tracking status.
585 if (!Encodings::isKnownScriptChar(next, script) ||
586 runningChange != owner_->lookupChange(i + 1))
590 FontList::const_iterator cit = fontlist_.begin();
591 FontList::const_iterator end = fontlist_.end();
592 for (; cit != end; ++cit) {
593 if (cit->pos() >= i && !found) {
594 prev_font = cit->font();
597 if (cit->pos() >= i + 1)
600 // Stop here if there is a font attribute or encoding change.
601 if (found && cit != end && prev_font != cit->font())
603 docstring const latex = encoding.latexChar(next);
604 docstring::size_type const b1 =
605 latex.find_first_of(from_ascii("{"));
606 docstring::size_type const b2 =
607 latex.find_last_of(from_ascii("}"));
608 int const len = b2 - b1 - 1;
609 os << latex.substr(b1 + 1, len);
619 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
621 pos_type const len = str.length();
623 // is the paragraph large enough?
624 if (pos + len > int(text_.size()))
627 // does the wanted text start at point?
628 for (string::size_type i = 0; i < str.length(); ++i) {
629 // Caution: direct comparison of characters works only
630 // because str is pure ASCII.
631 if (str[i] != text_[pos + i])
635 return fontlist_.hasChangeInRange(pos, len);
639 void Paragraph::Private::latexInset(Buffer const & buf,
640 BufferParams const & bparams,
643 OutputParams & runparams,
646 Font const & outerfont,
648 Change & running_change,
649 Layout const & style,
651 unsigned int & column)
653 Inset * inset = owner_->getInset(i);
656 if (style.pass_thru) {
657 inset->plaintext(buf, os, runparams);
661 // FIXME: move this to InsetNewline::latex
662 if (inset->lyxCode() == NEWLINE_CODE) {
663 // newlines are handled differently here than
664 // the default in simpleTeXSpecialChars().
665 if (!style.newline_allowed) {
669 column += running_font.latexWriteEndChanges(
670 os, bparams, runparams,
675 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
678 basefont = owner_->getLayoutFont(bparams, outerfont);
679 running_font = basefont;
681 if (runparams.moving_arg)
686 texrow.start(owner_->id(), i + 1);
690 if (owner_->lookupChange(i).type == Change::DELETED) {
691 if( ++runparams.inDeletedInset == 1)
692 runparams.changeOfDeletedInset = owner_->lookupChange(i);
695 if (inset->canTrackChanges()) {
696 column += Changes::latexMarkChange(os, bparams, running_change,
697 Change(Change::UNCHANGED));
698 running_change = Change(Change::UNCHANGED);
702 odocstream::pos_type const len = os.tellp();
704 if (inset->forceLTR()
705 && running_font.isRightToLeft()
706 // ERT is an exception, it should be output with no decorations at all
707 && inset->lyxCode() != ERT_CODE) {
708 if (running_font.language()->lang() == "farsi")
715 // FIXME: Bug: we can have an empty font change here!
716 // if there has just been a font change, we are going to close it
717 // right now, which means stupid latex code like \textsf{}. AFAIK,
718 // this does not harm dvi output. A minor bug, thus (JMarc)
720 // Some insets cannot be inside a font change command.
721 // However, even such insets *can* be placed in \L or \R
722 // or their equivalents (for RTL language switches), so we don't
723 // close the language in those cases.
724 // ArabTeX, though, cannot handle this special behavior, it seems.
725 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
726 || running_font.language()->lang() == "arabic_arabtex";
727 if (open_font && inset->noFontChange()) {
728 bool closeLanguage = arabtex
729 || basefont.isRightToLeft() == running_font.isRightToLeft();
730 unsigned int count = running_font.latexWriteEndChanges(os,
731 bparams, runparams, basefont, basefont, closeLanguage);
733 // if any font properties were closed, update the running_font,
734 // making sure, however, to leave the language as it was
736 // FIXME: probably a better way to keep track of the old
737 // language, than copying the entire font?
738 Font const copy_font(running_font);
739 basefont = owner_->getLayoutFont(bparams, outerfont);
740 running_font = basefont;
742 running_font.setLanguage(copy_font.language());
743 // leave font open if language is still open
744 open_font = (running_font.language() == basefont.language());
746 runparams.local_font = &basefont;
750 int tmp = inset->latex(buf, os, runparams);
753 if (running_font.language()->lang() == "farsi")
760 for (int j = 0; j < tmp; ++j)
763 texrow.start(owner_->id(), i + 1);
766 column += os.tellp() - len;
769 if (owner_->lookupChange(i).type == Change::DELETED)
770 --runparams.inDeletedInset;
774 void Paragraph::Private::latexSpecialChar(
776 OutputParams & runparams,
778 Change & running_change,
779 Layout const & style,
781 unsigned int & column)
783 char_type const c = text_[i];
785 if (style.pass_thru) {
787 // FIXME UNICODE: This can fail if c cannot
788 // be encoded in the current encoding.
793 if (runparams.verbatim) {
798 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
801 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
802 && latexSpecialTypewriter(c, os, i, column))
805 // Otherwise, we use what LaTeX provides us.
808 os << "\\textbackslash{}";
812 os << "\\textless{}";
816 os << "\\textgreater{}";
827 os << "\\char`\\\"{}";
832 case '%': case '#': case '{':
840 os << "\\textasciitilde{}";
845 os << "\\textasciicircum{}";
850 // avoid being mistaken for optional arguments
858 // Blanks are printed before font switching.
859 // Sure? I am not! (try nice-latex)
860 // I am sure it's correct. LyX might be smarter
861 // in the future, but for now, nothing wrong is
868 if (latexSpecialPhrase(os, i, column, runparams))
874 Encoding const & encoding = *(runparams.encoding);
875 if (i + 1 < int(text_.size())) {
876 char_type next = text_[i + 1];
877 if (Encodings::isCombiningChar(next)) {
878 column += latexSurrogatePair(os, c, next, encoding) - 1;
884 docstring const latex = encoding.latexChar(c);
885 if (Encodings::isKnownScriptChar(c, script)
886 && prefixIs(latex, from_ascii("\\" + script)))
887 column += writeScriptChars(os, latex,
888 running_change, encoding, i) - 1;
889 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
890 // Prevent eating of a following
891 // space or command corruption by
892 // following characters
893 column += latex.length() + 1;
896 column += latex.length() - 1;
904 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
905 pos_type & i, unsigned int & column)
911 // In T1 encoding, these characters exist
912 // but we should avoid ligatures
913 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
918 //os << "\\textcompwordmark{}";
930 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
931 pos_type & i, unsigned int & column)
935 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
936 // "--" in Typewriter mode -> "-{}-"
943 // I assume this is hack treating typewriter as verbatim
944 // FIXME UNICODE: This can fail if c cannot be encoded
945 // in the current encoding.
950 // Those characters are not directly supported.
954 case '%': case '#': case '{':
963 // With Typewriter font, these characters exist.
970 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
971 unsigned int & column, OutputParams & runparams)
973 // FIXME: if we have "LaTeX" with a font
974 // change in the middle (before the 'T', then
975 // the "TeX" part is still special cased.
976 // Really we should only operate this on
977 // "words" for some definition of word
979 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
980 if (!isTextAt(special_phrases[pnr].phrase, i))
982 if (runparams.moving_arg)
984 os << special_phrases[pnr].macro;
985 i += special_phrases[pnr].phrase.length() - 1;
986 column += special_phrases[pnr].macro.length() - 1;
993 void Paragraph::Private::validate(LaTeXFeatures & features,
994 Layout const & layout) const
997 if (!params_.spacing().isDefault())
998 features.require("setspace");
1001 features.useLayout(layout.name());
1004 fontlist_.validate(features);
1006 // then the indentation
1007 if (!params_.leftIndent().zero())
1008 features.require("ParagraphLeftIndent");
1011 InsetList::const_iterator icit = insetlist_.begin();
1012 InsetList::const_iterator iend = insetlist_.end();
1013 for (; icit != iend; ++icit) {
1015 icit->inset->validate(features);
1016 if (layout.needprotect &&
1017 icit->inset->lyxCode() == FOOT_CODE)
1018 features.require("NeedLyXFootnoteCode");
1022 // then the contents
1023 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1024 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1025 if (!special_phrases[pnr].builtin
1026 && isTextAt(special_phrases[pnr].phrase, i)) {
1027 features.require(special_phrases[pnr].phrase);
1031 Encodings::validate(text_[i], features);
1035 /////////////////////////////////////////////////////////////////////
1039 /////////////////////////////////////////////////////////////////////
1041 Paragraph::Paragraph()
1042 : d(new Paragraph::Private(this))
1049 Paragraph::Paragraph(Paragraph const & par)
1050 : itemdepth(par.itemdepth),
1051 d(new Paragraph::Private(*par.d, this))
1056 Paragraph & Paragraph::operator=(Paragraph const & par)
1058 // needed as we will destroy the private part before copying it
1060 itemdepth = par.itemdepth;
1063 d = new Private(*par.d, this);
1069 Paragraph::~Paragraph()
1075 void Paragraph::write(Buffer const & buf, ostream & os,
1076 BufferParams const & bparams,
1077 depth_type & dth) const
1079 // The beginning or end of a deeper (i.e. nested) area?
1080 if (dth != params().depth()) {
1081 if (params().depth() > dth) {
1082 while (params().depth() > dth) {
1083 os << "\n\\begin_deeper";
1087 while (params().depth() < dth) {
1088 os << "\n\\end_deeper";
1094 // First write the layout
1095 os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1099 Font font1(inherit_font, bparams.language);
1101 Change running_change = Change(Change::UNCHANGED);
1104 for (pos_type i = 0; i <= size(); ++i) {
1106 Change change = lookupChange(i);
1107 Changes::lyxMarkChange(os, column, running_change, change);
1108 running_change = change;
1113 // Write font changes
1114 Font font2 = getFontSettings(bparams, i);
1115 if (font2 != font1) {
1116 font2.lyxWriteChanges(font1, os);
1121 char_type const c = d->text_[i];
1125 Inset const * inset = getInset(i);
1127 if (inset->directWrite()) {
1128 // international char, let it write
1129 // code directly so it's shorter in
1131 inset->write(buf, os);
1135 os << "\\begin_inset ";
1136 inset->write(buf, os);
1137 os << "\n\\end_inset\n\n";
1143 os << "\n\\backslash\n";
1147 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1154 if ((column > 70 && c == ' ')
1159 // this check is to amend a bug. LyX sometimes
1160 // inserts '\0' this could cause problems.
1162 vector<char> tmp = ucs4_to_utf8(c);
1163 tmp.push_back('\0');
1166 lyxerr << "ERROR (Paragraph::writeFile):"
1167 " NULL char in structure." << endl;
1173 os << "\n\\end_layout\n";
1177 void Paragraph::validate(LaTeXFeatures & features) const
1179 d->validate(features, *layout());
1183 void Paragraph::insert(pos_type start, docstring const & str,
1184 Font const & font, Change const & change)
1186 for (size_t i = 0, n = str.size(); i != n ; ++i)
1187 insertChar(start + i, str[i], font, change);
1191 void Paragraph::appendChar(char_type c, Font const & font,
1192 Change const & change)
1195 d->changes_.insert(change, d->text_.size());
1196 // when appending characters, no need to update tables
1197 d->text_.push_back(c);
1198 setFont(d->text_.size() - 1, font);
1202 void Paragraph::appendString(docstring const & s, Font const & font,
1203 Change const & change)
1205 pos_type end = s.size();
1206 size_t oldsize = d->text_.size();
1207 size_t newsize = oldsize + end;
1208 size_t capacity = d->text_.capacity();
1209 if (newsize >= capacity)
1210 d->text_.reserve(max(capacity + 100, newsize));
1212 // when appending characters, no need to update tables
1215 // FIXME: Optimize this!
1216 for (pos_type i = 0; i != end; ++i) {
1218 d->changes_.insert(change, i);
1220 d->fontlist_.set(oldsize, font);
1221 d->fontlist_.set(newsize - 1, font);
1225 void Paragraph::insertChar(pos_type pos, char_type c,
1228 d->insertChar(pos, c, Change(trackChanges ?
1229 Change::INSERTED : Change::UNCHANGED));
1233 void Paragraph::insertChar(pos_type pos, char_type c,
1234 Font const & font, bool trackChanges)
1236 d->insertChar(pos, c, Change(trackChanges ?
1237 Change::INSERTED : Change::UNCHANGED));
1242 void Paragraph::insertChar(pos_type pos, char_type c,
1243 Font const & font, Change const & change)
1245 d->insertChar(pos, c, change);
1250 void Paragraph::insertInset(pos_type pos, Inset * inset,
1251 Font const & font, Change const & change)
1253 insertInset(pos, inset, change);
1254 // Set the font/language of the inset...
1259 bool Paragraph::insetAllowed(InsetCode code)
1261 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1265 void Paragraph::resetFonts(Font const & font)
1267 d->fontlist_.clear();
1268 d->fontlist_.set(0, font);
1269 d->fontlist_.set(d->text_.size() - 1, font);
1272 // Gets uninstantiated font setting at position.
1273 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1277 lyxerr << " pos: " << pos << " size: " << size() << endl;
1278 BOOST_ASSERT(pos <= size());
1281 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1282 if (cit != d->fontlist_.end())
1285 if (pos == size() && !empty())
1286 return getFontSettings(bparams, pos - 1);
1288 return Font(inherit_font, getParLanguage(bparams));
1292 FontSpan Paragraph::fontSpan(pos_type pos) const
1294 BOOST_ASSERT(pos <= size());
1297 FontList::const_iterator cit = d->fontlist_.begin();
1298 FontList::const_iterator end = d->fontlist_.end();
1299 for (; cit != end; ++cit) {
1300 if (cit->pos() >= pos) {
1301 if (pos >= beginOfBody())
1302 return FontSpan(max(start, beginOfBody()),
1305 return FontSpan(start,
1306 min(beginOfBody() - 1,
1309 start = cit->pos() + 1;
1312 // This should not happen, but if so, we take no chances.
1313 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1315 return FontSpan(pos, pos);
1319 // Gets uninstantiated font setting at position 0
1320 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1322 if (!empty() && !d->fontlist_.empty())
1323 return d->fontlist_.begin()->font();
1325 return Font(inherit_font, bparams.language);
1329 // Gets the fully instantiated font at a given position in a paragraph
1330 // This is basically the same function as Text::GetFont() in text2.cpp.
1331 // The difference is that this one is used for generating the LaTeX file,
1332 // and thus cosmetic "improvements" are disallowed: This has to deliver
1333 // the true picture of the buffer. (Asger)
1334 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1335 Font const & outerfont) const
1337 BOOST_ASSERT(pos >= 0);
1339 Font font = getFontSettings(bparams, pos);
1341 pos_type const body_pos = beginOfBody();
1343 font.fontInfo().realize(d->layout_->labelfont);
1345 font.fontInfo().realize(d->layout_->font);
1347 font.fontInfo().realize(outerfont.fontInfo());
1348 font.fontInfo().realize(bparams.getFont().fontInfo());
1354 Font const Paragraph::getLabelFont
1355 (BufferParams const & bparams, Font const & outerfont) const
1357 FontInfo tmpfont = layout()->labelfont;
1358 tmpfont.realize(outerfont.fontInfo());
1359 tmpfont.realize(bparams.getFont().fontInfo());
1360 return Font(tmpfont, getParLanguage(bparams));
1364 Font const Paragraph::getLayoutFont
1365 (BufferParams const & bparams, Font const & outerfont) const
1367 FontInfo tmpfont = layout()->font;
1368 tmpfont.realize(outerfont.fontInfo());
1369 tmpfont.realize(bparams.getFont().fontInfo());
1370 return Font(tmpfont, getParLanguage(bparams));
1374 /// Returns the height of the highest font in range
1375 FontSize Paragraph::highestFontInRange
1376 (pos_type startpos, pos_type endpos, FontSize def_size) const
1378 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1383 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1385 char_type c = d->text_[pos];
1386 if (!lyxrc.rtl_support)
1416 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1423 void Paragraph::setFont(pos_type pos, Font const & font)
1425 BOOST_ASSERT(pos <= size());
1427 // First, reduce font against layout/label font
1428 // Update: The setCharFont() routine in text2.cpp already
1429 // reduces font, so we don't need to do that here. (Asger)
1431 d->fontlist_.set(pos, font);
1435 void Paragraph::makeSameLayout(Paragraph const & par)
1437 layout(par.layout());
1439 d->params_ = par.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.layout() == layout() && d->params_.sameLayout(par.params());
1468 depth_type Paragraph::getDepth() const
1470 return params().depth();
1474 depth_type Paragraph::getMaxDepthAfter() const
1476 if (layout()->isEnvironment())
1477 return params().depth() + 1;
1479 return params().depth();
1483 char Paragraph::getAlign() const
1485 if (params().align() == LYX_ALIGN_LAYOUT)
1486 return layout()->align;
1488 return params().align();
1492 docstring const & Paragraph::getLabelstring() const
1494 return params().labelString();
1498 // the next two functions are for the manual labels
1499 docstring const Paragraph::getLabelWidthString() const
1501 if (layout()->margintype == MARGIN_MANUAL)
1502 return params().labelWidthString();
1504 return _("Senseless with this layout!");
1508 void Paragraph::setLabelWidthString(docstring const & s)
1510 params().labelWidthString(s);
1514 docstring const Paragraph::translateIfPossible(docstring const & s,
1515 BufferParams const & bparams) const
1517 if (!isAscii(s) || s.empty()) {
1518 // This must be a user defined layout. We cannot translate
1519 // this, since gettext accepts only ascii keys.
1522 // Probably standard layout, try to translate
1523 Messages & m = getMessages(getParLanguage(bparams)->code());
1524 return m.get(to_ascii(s));
1528 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1529 BufferParams const & bparams, bool process_appendix) const
1531 TextClass const & tclass = bparams.getTextClass();
1534 if (process_appendix && params().appendix())
1535 fmt = translateIfPossible(layout->labelstring_appendix(),
1538 fmt = translateIfPossible(layout->labelstring(), bparams);
1540 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1541 && !layout->counter.empty())
1542 fmt = "\\the" + layout->counter;
1544 // handle 'inherited level parts' in 'fmt',
1545 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1546 size_t const i = fmt.find('@', 0);
1547 if (i != docstring::npos) {
1548 size_t const j = fmt.find('@', i + 1);
1549 if (j != docstring::npos) {
1550 docstring parent(fmt, i + 1, j - i - 1);
1551 docstring label = from_ascii("??");
1552 if (tclass.hasLayout(parent))
1553 docstring label = expandLabel(tclass[parent], bparams,
1555 fmt = docstring(fmt, 0, i) + label
1556 + docstring(fmt, j + 1, docstring::npos);
1560 return tclass.counters().counterLabel(fmt);
1564 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1567 LyXAlignment const oldAlign = params().align();
1569 if (!(oldAlign & layout()->alignpossible)) {
1570 frontend::Alert::warning(_("Alignment not permitted"),
1571 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1572 params().align(LYX_ALIGN_LAYOUT);
1577 pos_type Paragraph::beginOfBody() const
1579 return d->begin_of_body_;
1583 void Paragraph::setBeginOfBody()
1585 if (layout()->labeltype != LABEL_MANUAL) {
1586 d->begin_of_body_ = 0;
1590 // Unroll the first two cycles of the loop
1591 // and remember the previous character to
1592 // remove unnecessary getChar() calls
1594 pos_type end = size();
1595 if (i < end && !isNewline(i)) {
1597 char_type previous_char = 0;
1600 previous_char = d->text_[i];
1601 if (!isNewline(i)) {
1603 while (i < end && previous_char != ' ') {
1608 previous_char = temp;
1614 d->begin_of_body_ = i;
1618 bool Paragraph::forceDefaultParagraphs() const
1620 return inInset() && inInset()->forceDefaultParagraphs(0);
1626 // paragraphs inside floats need different alignment tags to avoid
1629 bool noTrivlistCentering(InsetCode code)
1631 return code == FLOAT_CODE || code == WRAP_CODE;
1635 string correction(string const & orig)
1637 if (orig == "flushleft")
1638 return "raggedright";
1639 if (orig == "flushright")
1640 return "raggedleft";
1641 if (orig == "center")
1647 string const corrected_env(string const & suffix, string const & env,
1650 string output = suffix + "{";
1651 if (noTrivlistCentering(code))
1652 output += correction(env);
1656 if (suffix == "\\begin")
1662 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1664 if (!contains(str, "\n"))
1665 column += str.size();
1669 column = rsplit(str, tmp, '\n').size();
1676 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1677 odocstream & os, TexRow & texrow,
1678 bool moving_arg) const
1682 if (params_.noindent()) {
1683 os << "\\noindent ";
1687 LyXAlignment const curAlign = params_.align();
1689 if (curAlign == layout_->align)
1693 case LYX_ALIGN_NONE:
1694 case LYX_ALIGN_BLOCK:
1695 case LYX_ALIGN_LAYOUT:
1696 case LYX_ALIGN_SPECIAL:
1698 case LYX_ALIGN_LEFT:
1699 case LYX_ALIGN_RIGHT:
1700 case LYX_ALIGN_CENTER:
1709 case LYX_ALIGN_NONE:
1710 case LYX_ALIGN_BLOCK:
1711 case LYX_ALIGN_LAYOUT:
1712 case LYX_ALIGN_SPECIAL:
1714 case LYX_ALIGN_LEFT: {
1716 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1717 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1719 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1720 os << from_ascii(output);
1721 adjust_row_column(output, texrow, column);
1723 } case LYX_ALIGN_RIGHT: {
1725 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1726 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1728 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1729 os << from_ascii(output);
1730 adjust_row_column(output, texrow, column);
1732 } case LYX_ALIGN_CENTER: {
1734 output = corrected_env("\\begin", "center", owner_->ownerCode());
1735 os << from_ascii(output);
1736 adjust_row_column(output, texrow, column);
1745 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1746 odocstream & os, TexRow & texrow,
1747 bool moving_arg) const
1751 switch (params_.align()) {
1752 case LYX_ALIGN_NONE:
1753 case LYX_ALIGN_BLOCK:
1754 case LYX_ALIGN_LAYOUT:
1755 case LYX_ALIGN_SPECIAL:
1757 case LYX_ALIGN_LEFT:
1758 case LYX_ALIGN_RIGHT:
1759 case LYX_ALIGN_CENTER:
1767 switch (params_.align()) {
1768 case LYX_ALIGN_NONE:
1769 case LYX_ALIGN_BLOCK:
1770 case LYX_ALIGN_LAYOUT:
1771 case LYX_ALIGN_SPECIAL:
1773 case LYX_ALIGN_LEFT: {
1775 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1776 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1778 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1779 os << from_ascii(output);
1780 adjust_row_column(output, texrow, column);
1782 } case LYX_ALIGN_RIGHT: {
1784 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1785 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1787 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1788 os << from_ascii(output);
1789 adjust_row_column(output, texrow, column);
1791 } case LYX_ALIGN_CENTER: {
1793 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1794 os << from_ascii(output);
1795 adjust_row_column(output, texrow, column);
1804 // This one spits out the text of the paragraph
1805 bool Paragraph::latex(Buffer const & buf,
1806 BufferParams const & bparams,
1807 Font const & outerfont,
1808 odocstream & os, TexRow & texrow,
1809 OutputParams const & runparams) const
1811 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1813 bool return_value = false;
1817 // well we have to check if we are in an inset with unlimited
1818 // length (all in one row) if that is true then we don't allow
1819 // any special options in the paragraph and also we don't allow
1820 // any environment other than the default layout of the text class
1822 bool asdefault = forceDefaultParagraphs();
1825 style = bparams.getTextClass().defaultLayout();
1830 // Current base font for all inherited font changes, without any
1831 // change caused by an individual character, except for the language:
1832 // It is set to the language of the first character.
1833 // As long as we are in the label, this font is the base font of the
1834 // label. Before the first body character it is set to the base font
1838 // Maybe we have to create a optional argument.
1839 pos_type body_pos = beginOfBody();
1840 unsigned int column = 0;
1843 // the optional argument is kept in curly brackets in
1844 // case it contains a ']'
1847 basefont = getLabelFont(bparams, outerfont);
1849 basefont = getLayoutFont(bparams, outerfont);
1852 // Which font is currently active?
1853 Font running_font(basefont);
1854 // Do we have an open font change?
1855 bool open_font = false;
1857 Change runningChange = Change(Change::UNCHANGED);
1859 texrow.start(id(), 0);
1861 // if the paragraph is empty, the loop will not be entered at all
1863 if (style->isCommand()) {
1868 column += d->startTeXParParams(bparams, os, texrow,
1869 runparams.moving_arg);
1872 for (pos_type i = 0; i < size(); ++i) {
1873 // First char in paragraph or after label?
1874 if (i == body_pos) {
1877 column += running_font.latexWriteEndChanges(
1878 os, bparams, runparams,
1879 basefont, basefont);
1882 basefont = getLayoutFont(bparams, outerfont);
1883 running_font = basefont;
1885 column += Changes::latexMarkChange(os, bparams,
1886 runningChange, Change(Change::UNCHANGED));
1887 runningChange = Change(Change::UNCHANGED);
1892 if (style->isCommand()) {
1898 column += d->startTeXParParams(bparams, os,
1900 runparams.moving_arg);
1903 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1906 if (bparams.outputChanges && runningChange != change) {
1908 column += running_font.latexWriteEndChanges(
1909 os, bparams, runparams, basefont, basefont);
1912 basefont = getLayoutFont(bparams, outerfont);
1913 running_font = basefont;
1915 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1916 runningChange = change;
1919 // do not output text which is marked deleted
1920 // if change tracking output is disabled
1921 if (!bparams.outputChanges && change.type == Change::DELETED) {
1927 // Fully instantiated font
1928 Font const font = getFont(bparams, i, outerfont);
1930 Font const last_font = running_font;
1932 // Do we need to close the previous font?
1934 (font != running_font ||
1935 font.language() != running_font.language()))
1937 column += running_font.latexWriteEndChanges(
1938 os, bparams, runparams, basefont,
1939 (i == body_pos-1) ? basefont : font);
1940 running_font = basefont;
1944 // close babel's font environment before opening CJK.
1945 if (!running_font.language()->babel().empty() &&
1946 font.language()->encoding()->package() == Encoding::CJK) {
1947 string end_tag = subst(lyxrc.language_command_end,
1949 running_font.language()->babel());
1950 os << from_ascii(end_tag);
1951 column += end_tag.length();
1954 // Switch file encoding if necessary (and allowed)
1955 if (!runparams.verbatim &&
1956 runparams.encoding->package() == Encoding::none &&
1957 font.language()->encoding()->package() == Encoding::none) {
1958 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1959 runparams, *(font.language()->encoding()));
1960 if (enc_switch.first) {
1961 column += enc_switch.second;
1962 runparams.encoding = font.language()->encoding();
1966 char_type const c = d->text_[i];
1968 // Do we need to change font?
1969 if ((font != running_font ||
1970 font.language() != running_font.language()) &&
1973 odocstringstream ods;
1974 column += font.latexWriteStartChanges(ods, bparams,
1975 runparams, basefont,
1977 running_font = font;
1979 docstring fontchange = ods.str();
1980 // check if the fontchange ends with a trailing blank
1981 // (like "\small " (see bug 3382)
1982 if (suffixIs(fontchange, ' ') && c == ' ')
1983 os << fontchange.substr(0, fontchange.size() - 1)
1984 << from_ascii("{}");
1990 // FIXME: integrate this case in latexSpecialChar
1991 // Do not print the separation of the optional argument
1992 // if style->pass_thru is false. This works because
1993 // latexSpecialChar ignores spaces if
1994 // style->pass_thru is false.
1995 if (i != body_pos - 1) {
1996 if (d->simpleTeXBlanks(
1997 runparams, os, texrow,
1998 i, column, font, *style)) {
1999 // A surrogate pair was output. We
2000 // must not call latexSpecialChar
2001 // in this iteration, since it would output
2002 // the combining character again.
2009 OutputParams rp = runparams;
2010 rp.free_spacing = style->free_spacing;
2011 rp.local_font = &font;
2012 rp.intitle = style->intitle;
2014 // Two major modes: LaTeX or plain
2015 // Handle here those cases common to both modes
2016 // and then split to handle the two modes separately.
2017 if (c == META_INSET)
2018 d->latexInset(buf, bparams, os,
2019 texrow, rp, running_font,
2020 basefont, outerfont, open_font,
2021 runningChange, *style, i, column);
2024 d->latexSpecialChar(os, rp, running_font, runningChange,
2026 } catch (EncodingException & e) {
2027 // add location information and throw again.
2034 // Set the encoding to that returned from simpleTeXSpecialChars (see
2035 // comment for encoding member in OutputParams.h)
2036 runparams.encoding = rp.encoding;
2039 // If we have an open font definition, we have to close it
2041 #ifdef FIXED_LANGUAGE_END_DETECTION
2044 .latexWriteEndChanges(os, bparams, runparams,
2046 next_->getFont(bparams, 0, outerfont));
2048 running_font.latexWriteEndChanges(os, bparams,
2049 runparams, basefont, basefont);
2052 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2053 //FIXME: there as we start another \selectlanguage with the next paragraph if
2054 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2055 running_font.latexWriteEndChanges(os, bparams, runparams,
2056 basefont, basefont);
2060 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2062 // Needed if there is an optional argument but no contents.
2063 if (body_pos > 0 && body_pos == size()) {
2065 return_value = false;
2069 column += d->endTeXParParams(bparams, os, texrow,
2070 runparams.moving_arg);
2073 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2074 return return_value;
2078 bool Paragraph::emptyTag() const
2080 for (pos_type i = 0; i < size(); ++i) {
2082 Inset const * inset = getInset(i);
2083 InsetCode lyx_code = inset->lyxCode();
2084 if (lyx_code != TOC_CODE &&
2085 lyx_code != INCLUDE_CODE &&
2086 lyx_code != GRAPHICS_CODE &&
2087 lyx_code != ERT_CODE &&
2088 lyx_code != LISTINGS_CODE &&
2089 lyx_code != FLOAT_CODE &&
2090 lyx_code != TABULAR_CODE) {
2094 char_type c = d->text_[i];
2095 if (c != ' ' && c != '\t')
2103 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2105 for (pos_type i = 0; i < size(); ++i) {
2107 Inset const * inset = getInset(i);
2108 InsetCode lyx_code = inset->lyxCode();
2109 if (lyx_code == LABEL_CODE) {
2110 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2111 docstring const & id = il->getParam("name");
2112 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2121 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2124 for (i = 0; i < size(); ++i) {
2126 Inset const * inset = getInset(i);
2127 inset->docbook(buf, os, runparams);
2129 char_type c = d->text_[i];
2132 os << sgml::escapeChar(c);
2139 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2142 pos_type size = text_.size();
2143 for (pos_type i = initial; i < size; ++i) {
2144 Font font = owner_->getFont(buf.params(), i, outerfont);
2145 if (text_[i] == META_INSET)
2147 if (i != initial && font != font_old)
2156 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2158 OutputParams const & runparams,
2159 Font const & outerfont,
2160 pos_type initial) const
2162 bool emph_flag = false;
2164 LayoutPtr const & style = layout();
2166 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2168 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2171 // parsing main loop
2172 for (pos_type i = initial; i < size(); ++i) {
2173 Font font = getFont(buf.params(), i, outerfont);
2175 // handle <emphasis> tag
2176 if (font_old.emph() != font.fontInfo().emph()) {
2177 if (font.fontInfo().emph() == FONT_ON) {
2180 } else if (i != initial) {
2181 os << "</emphasis>";
2187 Inset const * inset = getInset(i);
2188 inset->docbook(buf, os, runparams);
2190 char_type c = d->text_[i];
2192 if (style->pass_thru)
2195 os << sgml::escapeChar(c);
2197 font_old = font.fontInfo();
2201 os << "</emphasis>";
2204 if (style->free_spacing)
2206 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2211 bool Paragraph::isHfill(pos_type pos) const
2214 && getInset(pos)->lyxCode() == HFILL_CODE;
2218 bool Paragraph::isNewline(pos_type pos) const
2221 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2225 bool Paragraph::isLineSeparator(pos_type pos) const
2227 char_type const c = d->text_[pos];
2228 return isLineSeparatorChar(c)
2229 || (c == META_INSET && getInset(pos) &&
2230 getInset(pos)->isLineSeparator());
2234 /// Used by the spellchecker
2235 bool Paragraph::isLetter(pos_type pos) const
2238 return getInset(pos)->isLetter();
2240 char_type const c = d->text_[pos];
2241 return isLetterChar(c) || isDigit(c);
2247 Paragraph::getParLanguage(BufferParams const & bparams) const
2250 return getFirstFontSettings(bparams).language();
2251 // FIXME: we should check the prev par as well (Lgb)
2252 return bparams.language;
2256 bool Paragraph::isRTL(BufferParams const & bparams) const
2258 return lyxrc.rtl_support
2259 && getParLanguage(bparams)->rightToLeft()
2260 && ownerCode() != ERT_CODE
2261 && ownerCode() != LISTINGS_CODE;
2265 void Paragraph::changeLanguage(BufferParams const & bparams,
2266 Language const * from, Language const * to)
2268 // change language including dummy font change at the end
2269 for (pos_type i = 0; i <= size(); ++i) {
2270 Font font = getFontSettings(bparams, i);
2271 if (font.language() == from) {
2272 font.setLanguage(to);
2279 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2281 Language const * doc_language = bparams.language;
2282 FontList::const_iterator cit = d->fontlist_.begin();
2283 FontList::const_iterator end = d->fontlist_.end();
2285 for (; cit != end; ++cit)
2286 if (cit->font().language() != ignore_language &&
2287 cit->font().language() != latex_language &&
2288 cit->font().language() != doc_language)
2294 // Convert the paragraph to a string.
2295 // Used for building the table of contents
2296 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2298 return asString(buffer, 0, size(), label);
2302 docstring const Paragraph::asString(Buffer const & buffer,
2303 pos_type beg, pos_type end, bool label) const
2306 odocstringstream os;
2308 if (beg == 0 && label && !params().labelString().empty())
2309 os << params().labelString() << ' ';
2311 for (pos_type i = beg; i < end; ++i) {
2312 char_type const c = d->text_[i];
2315 else if (c == META_INSET)
2316 getInset(i)->textString(buffer, os);
2323 void Paragraph::setInsetOwner(Inset * inset)
2325 d->inset_owner_ = inset;
2329 int Paragraph::id() const
2335 LayoutPtr const & Paragraph::layout() const
2341 void Paragraph::layout(LayoutPtr const & new_layout)
2343 d->layout_ = new_layout;
2347 Inset * Paragraph::inInset() const
2349 return d->inset_owner_;
2353 InsetCode Paragraph::ownerCode() const
2355 return d->inset_owner_ ?
2356 d->inset_owner_->lyxCode() : NO_CODE;
2360 ParagraphParameters & Paragraph::params()
2366 ParagraphParameters const & Paragraph::params() const
2372 bool Paragraph::isFreeSpacing() const
2374 if (layout()->free_spacing)
2376 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2380 bool Paragraph::allowEmpty() const
2382 if (layout()->keepempty)
2384 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2388 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2390 if (!Encodings::is_arabic(c))
2393 char_type prev_char = ' ';
2394 char_type next_char = ' ';
2396 for (pos_type i = pos - 1; i >= 0; --i) {
2397 char_type const par_char = d->text_[i];
2398 if (!Encodings::isComposeChar_arabic(par_char)) {
2399 prev_char = par_char;
2404 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2405 char_type const par_char = d->text_[i];
2406 if (!Encodings::isComposeChar_arabic(par_char)) {
2407 next_char = par_char;
2412 if (Encodings::is_arabic(next_char)) {
2413 if (Encodings::is_arabic(prev_char) &&
2414 !Encodings::is_arabic_special(prev_char))
2415 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2417 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2419 if (Encodings::is_arabic(prev_char) &&
2420 !Encodings::is_arabic_special(prev_char))
2421 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2423 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2428 int Paragraph::checkBiblio(bool track_changes)
2431 //This is getting more and more a mess. ...We really should clean
2432 //up this bibitem issue for 1.6. See also bug 2743.
2434 // Add bibitem insets if necessary
2435 if (layout()->labeltype != LABEL_BIBLIO)
2438 bool hasbibitem = !d->insetlist_.empty()
2439 // Insist on it being in pos 0
2440 && d->text_[0] == META_INSET
2441 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2446 // remove a bibitem in pos != 0
2447 // restore it later in pos 0 if necessary
2448 // (e.g. if a user inserts contents _before_ the item)
2449 // we're assuming there's only one of these, which there
2451 int erasedInsetPosition = -1;
2452 InsetList::iterator it = d->insetlist_.begin();
2453 InsetList::iterator end = d->insetlist_.end();
2454 for (; it != end; ++it)
2455 if (it->inset->lyxCode() == BIBITEM_CODE
2457 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2458 oldkey = olditem->getParam("key");
2459 oldlabel = olditem->getParam("label");
2460 erasedInsetPosition = it->pos;
2461 eraseChar(erasedInsetPosition, track_changes);
2465 //There was an InsetBibitem at the beginning, and we didn't
2466 //have to erase one.
2467 if (hasbibitem && erasedInsetPosition < 0)
2470 //There was an InsetBibitem at the beginning and we did have to
2471 //erase one. So we give its properties to the beginning inset.
2473 InsetBibitem * inset =
2474 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2475 if (!oldkey.empty())
2476 inset->setParam("key", oldkey);
2477 inset->setParam("label", oldlabel);
2478 return -erasedInsetPosition;
2481 //There was no inset at the beginning, so we need to create one with
2482 //the key and label of the one we erased.
2483 InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2484 // restore values of previously deleted item in this par.
2485 if (!oldkey.empty())
2486 inset->setParam("key", oldkey);
2487 inset->setParam("label", oldlabel);
2488 insertInset(0, static_cast<Inset *>(inset),
2489 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2495 void Paragraph::checkAuthors(AuthorList const & authorList)
2497 d->changes_.checkAuthors(authorList);
2501 bool Paragraph::isUnchanged(pos_type pos) const
2503 return lookupChange(pos).type == Change::UNCHANGED;
2507 bool Paragraph::isInserted(pos_type pos) const
2509 return lookupChange(pos).type == Change::INSERTED;
2513 bool Paragraph::isDeleted(pos_type pos) const
2515 return lookupChange(pos).type == Change::DELETED;
2519 InsetList const & Paragraph::insetList() const
2521 return d->insetlist_;
2525 Inset * Paragraph::releaseInset(pos_type pos)
2527 Inset * inset = d->insetlist_.release(pos);
2528 /// does not honour change tracking!
2529 eraseChar(pos, false);
2534 Inset * Paragraph::getInset(pos_type pos)
2536 return d->insetlist_.get(pos);
2540 Inset const * Paragraph::getInset(pos_type pos) const
2542 return d->insetlist_.get(pos);
2546 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2547 pos_type right, TextCase action)
2549 // process sequences of modified characters; in change
2550 // tracking mode, this approach results in much better
2551 // usability than changing case on a char-by-char basis
2554 bool const trackChanges = bparams.trackChanges;
2556 bool capitalize = true;
2558 for (; pos < right; ++pos) {
2559 char_type oldChar = d->text_[pos];
2560 char_type newChar = oldChar;
2562 // ignore insets and don't play with deleted text!
2563 if (oldChar != META_INSET && !isDeleted(pos)) {
2565 case text_lowercase:
2566 newChar = lowercase(oldChar);
2568 case text_capitalization:
2570 newChar = uppercase(oldChar);
2574 case text_uppercase:
2575 newChar = uppercase(oldChar);
2580 if (!isLetter(pos) || isDeleted(pos)) {
2581 // permit capitalization again
2585 if (oldChar != newChar)
2588 if (oldChar == newChar || pos == right - 1) {
2589 if (oldChar != newChar) {
2590 // step behind the changing area
2593 int erasePos = pos - changes.size();
2594 for (size_t i = 0; i < changes.size(); i++) {
2595 insertChar(pos, changes[i],
2596 getFontSettings(bparams,
2599 if (!eraseChar(erasePos, trackChanges)) {
2602 ++right; // expand selection
2611 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2612 pos_type pos, bool del) const
2614 int const strsize = str.length();
2616 pos_type const parsize = d->text_.size();
2617 for (i = 0; pos + i < parsize; ++i) {
2620 if (cs && str[i] != d->text_[pos + i])
2622 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2624 if (!del && isDeleted(pos + i))
2631 // if necessary, check whether string matches word
2633 if (pos > 0 && isLetter(pos - 1))
2635 if (pos + strsize < parsize
2636 && isLetter(pos + strsize))
2644 char_type Paragraph::getChar(pos_type pos) const
2646 return d->text_[pos];
2650 pos_type Paragraph::size() const
2652 return d->text_.size();
2656 bool Paragraph::empty() const
2658 return d->text_.empty();
2662 bool Paragraph::isInset(pos_type pos) const
2664 return d->text_[pos] == META_INSET;
2668 bool Paragraph::isSeparator(pos_type pos) const
2670 //FIXME: Are we sure this can be the only separator?
2671 return d->text_[pos] == ' ';