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"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
39 #include "OutputParams.h"
40 #include "output_latex.h"
41 #include "paragraph_funcs.h"
42 #include "ParagraphParameters.h"
47 #include "frontends/alert.h"
48 #include "frontends/FontMetrics.h"
50 #include "insets/InsetBibitem.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetOptArg.h"
54 #include "support/lstrings.h"
55 #include "support/textutils.h"
56 #include "support/convert.h"
57 #include "support/unicode.h"
68 using support::contains;
69 using support::lowercase;
70 using support::prefixIs;
71 using support::suffixIs;
72 using support::rsplit;
74 using support::uppercase;
77 /// Inset identifier (above 0x10ffff, for ucs-4)
78 char_type const META_INSET = 0x200001;
81 /////////////////////////////////////////////////////////////////////
85 /////////////////////////////////////////////////////////////////////
87 class Paragraph::Private
91 Private(Paragraph * owner);
92 /// "Copy constructor"
93 Private(Private const &, Paragraph * owner);
96 void insertChar(pos_type pos, char_type c, Change const & change);
98 /// Output the surrogate pair formed by \p c and \p next to \p os.
99 /// \return the number of characters written.
100 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
103 /// Output a space in appropriate formatting (or a surrogate pair
104 /// if the next character is a combining character).
105 /// \return whether a surrogate pair was output.
106 bool simpleTeXBlanks(Encoding const &,
107 odocstream &, TexRow & texrow,
109 unsigned int & column,
111 Layout const & style);
113 /// Output consecutive known unicode chars, belonging to the same
114 /// language as specified by \p preamble, to \p os starting from \p c.
115 /// \return the number of characters written.
116 int knownLangChars(odocstream & os, char_type c, string & preamble,
117 Change &, Encoding const &, pos_type &);
119 /// This could go to ParagraphParameters if we want to.
120 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
123 /// This could go to ParagraphParameters if we want to.
124 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
128 void latexInset(Buffer const &, BufferParams const &,
130 TexRow & texrow, OutputParams &,
133 Font const & outerfont,
135 Change & running_change,
136 Layout const & style,
138 unsigned int & column);
141 void latexSpecialChar(
143 OutputParams & runparams,
145 Change & running_change,
146 Layout const & style,
148 unsigned int & column);
155 unsigned int & column);
157 bool latexSpecialTypewriter(
161 unsigned int & column);
163 bool latexSpecialPhrase(
166 unsigned int & column);
169 void validate(LaTeXFeatures & features,
170 Layout const & layout) const;
172 /// Checks if the paragraph contains only text and no inset or font change.
173 bool onlyText(Buffer const & buf, Font const & outerfont,
174 pos_type initial) const;
176 /// match a string against a particular point in the paragraph
177 bool isTextAt(std::string const & str, pos_type pos) const;
179 /// Which Paragraph owns us?
183 Inset * inset_owner_;
191 static unsigned int paragraph_id;
193 ParagraphParameters params_;
195 /// for recording and looking up changes
199 InsetList insetlist_;
205 pos_type begin_of_body_;
207 typedef docstring TextContainer;
216 using std::upper_bound;
217 using std::lower_bound;
221 // Initialization of the counter for the paragraph id's,
222 unsigned int Paragraph::Private::paragraph_id = 0;
226 struct special_phrase {
232 special_phrase const special_phrases[] = {
233 { "LyX", from_ascii("\\protect\\LyX{}"), false },
234 { "TeX", from_ascii("\\protect\\TeX{}"), true },
235 { "LaTeX2e", from_ascii("\\protect\\LaTeXe{}"), true },
236 { "LaTeX", from_ascii("\\protect\\LaTeX{}"), true },
239 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
244 Paragraph::Private::Private(Paragraph * owner)
245 : owner_(owner), inset_owner_(0), begin_of_body_(0)
247 id_ = paragraph_id++;
252 Paragraph::Private::Private(Private const & p, Paragraph * owner)
253 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
254 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
255 layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
257 id_ = paragraph_id++;
261 bool Paragraph::isChanged(pos_type start, pos_type end) const
263 BOOST_ASSERT(start >= 0 && start <= size());
264 BOOST_ASSERT(end > start && end <= size() + 1);
266 return d->changes_.isChanged(start, end);
270 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
271 // keep the logic here in sync with the logic of eraseChars()
277 Change change = d->changes_.lookup(size());
279 return change.type == Change::INSERTED && change.author == 0;
283 void Paragraph::setChange(Change const & change)
285 // beware of the imaginary end-of-par character!
286 d->changes_.set(change, 0, size() + 1);
289 * Propagate the change recursively - but not in case of DELETED!
291 * Imagine that your co-author makes changes in an existing inset. He
292 * sends your document to you and you come to the conclusion that the
293 * inset should go completely. If you erase it, LyX must not delete all
294 * text within the inset. Otherwise, the change tracked insertions of
295 * your co-author get lost and there is no way to restore them later.
297 * Conclusion: An inset's content should remain untouched if you delete it
300 if (change.type != Change::DELETED) {
301 for (pos_type pos = 0; pos < size(); ++pos) {
303 getInset(pos)->setChange(change);
309 void Paragraph::setChange(pos_type pos, Change const & change)
311 BOOST_ASSERT(pos >= 0 && pos <= size());
313 d->changes_.set(change, pos);
315 // see comment in setChange(Change const &) above
317 if (change.type != Change::DELETED &&
318 pos < size() && isInset(pos)) {
319 getInset(pos)->setChange(change);
324 Change const & Paragraph::lookupChange(pos_type pos) const
326 BOOST_ASSERT(pos >= 0 && pos <= size());
328 return d->changes_.lookup(pos);
332 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
335 BOOST_ASSERT(start >= 0 && start <= size());
336 BOOST_ASSERT(end > start && end <= size() + 1);
338 for (pos_type pos = start; pos < end; ++pos) {
339 switch (lookupChange(pos).type) {
340 case Change::UNCHANGED:
341 // accept changes in nested inset
342 if (pos < size() && isInset(pos))
343 getInset(pos)->acceptChanges(bparams);
347 case Change::INSERTED:
348 d->changes_.set(Change(Change::UNCHANGED), pos);
349 // also accept changes in nested inset
350 if (pos < size() && isInset(pos)) {
351 getInset(pos)->acceptChanges(bparams);
355 case Change::DELETED:
356 // Suppress access to non-existent
357 // "end-of-paragraph char"
359 eraseChar(pos, false);
370 void Paragraph::rejectChanges(BufferParams const & bparams,
371 pos_type start, pos_type end)
373 BOOST_ASSERT(start >= 0 && start <= size());
374 BOOST_ASSERT(end > start && end <= size() + 1);
376 for (pos_type pos = start; pos < end; ++pos) {
377 switch (lookupChange(pos).type) {
378 case Change::UNCHANGED:
379 // reject changes in nested inset
380 if (pos < size() && isInset(pos)) {
381 getInset(pos)->rejectChanges(bparams);
385 case Change::INSERTED:
386 // Suppress access to non-existent
387 // "end-of-paragraph char"
389 eraseChar(pos, false);
395 case Change::DELETED:
396 d->changes_.set(Change(Change::UNCHANGED), pos);
398 // Do NOT reject changes within a deleted inset!
399 // There may be insertions of a co-author inside of it!
407 void Paragraph::Private::insertChar(pos_type pos, char_type c,
408 Change const & change)
410 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
413 changes_.insert(change, pos);
415 // This is actually very common when parsing buffers (and
416 // maybe inserting ascii text)
417 if (pos == text_.size()) {
418 // when appending characters, no need to update tables
423 text_.insert(text_.begin() + pos, c);
425 // Update the font table.
426 fontlist_.increasePosAfterPos(pos);
429 insetlist_.increasePosAfterPos(pos);
433 void Paragraph::insertInset(pos_type pos, Inset * inset,
434 Change const & change)
437 BOOST_ASSERT(pos >= 0 && pos <= size());
439 d->insertChar(pos, META_INSET, change);
440 BOOST_ASSERT(d->text_[pos] == META_INSET);
442 // Add a new entry in the insetlist_.
443 d->insetlist_.insert(inset, pos);
447 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
449 BOOST_ASSERT(pos >= 0 && pos <= size());
451 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
454 Change change = d->changes_.lookup(pos);
456 // set the character to DELETED if
457 // a) it was previously unchanged or
458 // b) it was inserted by a co-author
460 if (change.type == Change::UNCHANGED ||
461 (change.type == Change::INSERTED && change.author != 0)) {
462 setChange(pos, Change(Change::DELETED));
466 if (change.type == Change::DELETED)
470 // Don't physically access the imaginary end-of-paragraph character.
471 // eraseChar() can only mark it as DELETED. A physical deletion of
472 // end-of-par must be handled externally.
478 d->changes_.erase(pos);
480 // if it is an inset, delete the inset entry
481 if (d->text_[pos] == META_INSET)
482 d->insetlist_.erase(pos);
484 d->text_.erase(d->text_.begin() + pos);
486 // Update the fontlist_
487 d->fontlist_.erase(pos);
489 // Update the insetlist_
490 d->insetlist_.decreasePosAfterPos(pos);
496 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
498 BOOST_ASSERT(start >= 0 && start <= size());
499 BOOST_ASSERT(end >= start && end <= size() + 1);
502 for (pos_type count = end - start; count; --count) {
503 if (!eraseChar(i, trackChanges))
510 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
511 char_type next, Encoding const & encoding)
513 // Writing next here may circumvent a possible font change between
514 // c and next. Since next is only output if it forms a surrogate pair
515 // with c we can ignore this:
516 // A font change inside a surrogate pair does not make sense and is
517 // hopefully impossible to input.
518 // FIXME: change tracking
519 // Is this correct WRT change tracking?
520 docstring const latex1 = encoding.latexChar(next);
521 docstring const latex2 = encoding.latexChar(c);
522 os << latex1 << '{' << latex2 << '}';
523 return latex1.length() + latex2.length() + 2;
527 bool Paragraph::Private::simpleTeXBlanks(Encoding const & encoding,
528 odocstream & os, TexRow & texrow,
530 unsigned int & column,
532 Layout const & style)
537 if (i + 1 < int(text_.size())) {
538 char_type next = text_[i + 1];
539 if (Encodings::isCombiningChar(next)) {
540 // This space has an accent, so we must always output it.
541 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
546 if (lyxrc.plaintext_linelen > 0
547 && column > lyxrc.plaintext_linelen
549 && text_[i - 1] != ' '
550 && (i + 1 < int(text_.size()))
551 // same in FreeSpacing mode
552 && !owner_->isFreeSpacing()
553 // In typewriter mode, we want to avoid
554 // ! . ? : at the end of a line
555 && !(font.family() == Font::TYPEWRITER_FAMILY
556 && (text_[i - 1] == '.'
557 || text_[i - 1] == '?'
558 || text_[i - 1] == ':'
559 || text_[i - 1] == '!'))) {
562 texrow.start(owner_->id(), i + 1);
564 } else if (style.free_spacing) {
573 int Paragraph::Private::knownLangChars(odocstream & os,
576 Change & runningChange,
577 Encoding const & encoding,
580 // When the character is marked by the proper language, we simply
581 // get its code point in some encoding, otherwise we get the
582 // translation specified in the unicodesymbols file, which is
583 // something like "\textLANG{<spec>}". So, we have to retain
584 // "\textLANG{<spec>" for the first char but only "<spec>" for
585 // all subsequent chars.
586 docstring const latex1 = rtrim(encoding.latexChar(c), "}");
587 int length = latex1.length();
589 int size = text_.size();
590 while (i + 1 < size) {
591 char_type next = text_[i + 1];
592 // Stop here if next character belongs to another
593 // language or there is a change tracking status.
594 if (!Encodings::isKnownLangChar(next, preamble) ||
595 runningChange != owner_->lookupChange(i + 1))
599 FontList::const_iterator cit = fontlist_.begin();
600 FontList::const_iterator end = fontlist_.end();
601 for (; cit != end; ++cit) {
602 if (cit->pos() >= i && !found) {
603 prev_font = cit->font();
606 if (cit->pos() >= i + 1)
609 // Stop here if there is a font attribute change.
610 if (found && cit != end && prev_font != cit->font())
612 docstring const latex = rtrim(encoding.latexChar(next), "}");
613 docstring::size_type const j =
614 latex.find_first_of(from_ascii("{"));
615 if (j == docstring::npos) {
617 length += latex.length();
619 os << latex.substr(j + 1);
620 length += latex.substr(j + 1).length();
624 // When the proper language is set, we are simply passed a code
625 // point, so we should not try to close the \textLANG command.
626 if (prefixIs(latex1, from_ascii("\\" + preamble))) {
634 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
636 pos_type const len = str.length();
638 // is the paragraph large enough?
639 if (pos + len > int(text_.size()))
642 // does the wanted text start at point?
643 for (string::size_type i = 0; i < str.length(); ++i) {
644 // Caution: direct comparison of characters works only
645 // because str is pure ASCII.
646 if (str[i] != text_[pos + i])
650 return fontlist_.hasChangeInRange(pos, len);
654 void Paragraph::Private::latexInset(Buffer const & buf,
655 BufferParams const & bparams,
658 OutputParams & runparams,
661 Font const & outerfont,
663 Change & running_change,
664 Layout const & style,
666 unsigned int & column)
668 Inset * inset = owner_->getInset(i);
671 if (style.pass_thru) {
672 inset->plaintext(buf, os, runparams);
676 // FIXME: move this to InsetNewline::latex
677 if (inset->lyxCode() == NEWLINE_CODE) {
678 // newlines are handled differently here than
679 // the default in simpleTeXSpecialChars().
680 if (!style.newline_allowed) {
684 column += running_font.latexWriteEndChanges(
685 os, bparams, runparams,
690 if (running_font.family() == Font::TYPEWRITER_FAMILY)
693 basefont = owner_->getLayoutFont(bparams, outerfont);
694 running_font = basefont;
696 if (runparams.moving_arg)
702 texrow.start(owner_->id(), i + 1);
706 if (owner_->lookupChange(i).type == Change::DELETED) {
707 if( ++runparams.inDeletedInset == 1)
708 runparams.changeOfDeletedInset = owner_->lookupChange(i);
711 if (inset->canTrackChanges()) {
712 column += Changes::latexMarkChange(os, bparams, running_change,
713 Change(Change::UNCHANGED));
714 running_change = Change(Change::UNCHANGED);
718 odocstream::pos_type const len = os.tellp();
720 if ((inset->lyxCode() == GRAPHICS_CODE
721 || inset->lyxCode() == MATH_CODE
722 || inset->lyxCode() == HYPERLINK_CODE)
723 && running_font.isRightToLeft()) {
724 if (running_font.language()->lang() == "farsi")
731 // FIXME: Bug: we can have an empty font change here!
732 // if there has just been a font change, we are going to close it
733 // right now, which means stupid latex code like \textsf{}. AFAIK,
734 // this does not harm dvi output. A minor bug, thus (JMarc)
736 // Some insets cannot be inside a font change command.
737 // However, even such insets *can* be placed in \L or \R
738 // or their equivalents (for RTL language switches), so we don't
739 // close the language in those cases.
740 // ArabTeX, though, cannot handle this special behavior, it seems.
741 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
742 || running_font.language()->lang() == "arabic_arabtex";
743 if (open_font && inset->noFontChange()) {
744 bool closeLanguage = arabtex
745 || basefont.isRightToLeft() == running_font.isRightToLeft();
746 unsigned int count = running_font.latexWriteEndChanges(os,
747 bparams, runparams, basefont, basefont, closeLanguage);
749 // if any font properties were closed, update the running_font,
750 // making sure, however, to leave the language as it was
752 // FIXME: probably a better way to keep track of the old
753 // language, than copying the entire font?
754 Font const copy_font(running_font);
755 basefont = owner_->getLayoutFont(bparams, outerfont);
756 running_font = basefont;
758 running_font.setLanguage(copy_font.language());
759 // leave font open if language is still open
760 open_font = (running_font.language() == basefont.language());
762 runparams.local_font = &basefont;
766 int tmp = inset->latex(buf, os, runparams);
769 if (running_font.language()->lang() == "farsi")
776 for (int j = 0; j < tmp; ++j)
779 texrow.start(owner_->id(), i + 1);
782 column += os.tellp() - len;
785 if (owner_->lookupChange(i).type == Change::DELETED)
786 --runparams.inDeletedInset;
790 void Paragraph::Private::latexSpecialChar(
792 OutputParams & runparams,
794 Change & running_change,
795 Layout const & style,
797 unsigned int & column)
799 char_type const c = text_[i];
801 if (style.pass_thru) {
803 // FIXME UNICODE: This can fail if c cannot
804 // be encoded in the current encoding.
809 if (runparams.verbatim) {
814 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
817 if (running_font.family() == Font::TYPEWRITER_FAMILY
818 && latexSpecialTypewriter(c, os, i, column))
821 // Otherwise, we use what LaTeX provides us.
824 os << "\\textbackslash{}";
828 os << "\\textless{}";
832 os << "\\textgreater{}";
843 os << "\\char`\\\"{}";
848 case '%': case '#': case '{':
856 os << "\\textasciitilde{}";
861 os << "\\textasciicircum{}";
866 // avoid being mistaken for optional arguments
874 // Blanks are printed before font switching.
875 // Sure? I am not! (try nice-latex)
876 // I am sure it's correct. LyX might be smarter
877 // in the future, but for now, nothing wrong is
884 if (latexSpecialPhrase(os, i, column))
890 Encoding const & encoding = *(runparams.encoding);
891 if (i + 1 < int(text_.size())) {
892 char_type next = text_[i + 1];
893 if (Encodings::isCombiningChar(next)) {
894 column += latexSurrogatePair(os, c, next, encoding) - 1;
900 if (Encodings::isKnownLangChar(c, preamble)) {
901 column += knownLangChars(os, c, preamble, running_change,
905 docstring const latex = encoding.latexChar(c);
906 if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
907 // Prevent eating of a following
908 // space or command corruption by
909 // following characters
910 column += latex.length() + 1;
913 column += latex.length() - 1;
921 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
922 pos_type & i, unsigned int & column)
928 // In T1 encoding, these characters exist
929 // but we should avoid ligatures
930 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
935 //os << "\\textcompwordmark{}";
947 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
948 pos_type & i, unsigned int & column)
952 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
953 // "--" in Typewriter mode -> "-{}-"
960 // I assume this is hack treating typewriter as verbatim
961 // FIXME UNICODE: This can fail if c cannot be encoded
962 // in the current encoding.
967 // Those characters are not directly supported.
971 case '%': case '#': case '{':
980 // With Typewriter font, these characters exist.
987 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
988 unsigned int & column)
990 // FIXME: if we have "LaTeX" with a font
991 // change in the middle (before the 'T', then
992 // the "TeX" part is still special cased.
993 // Really we should only operate this on
994 // "words" for some definition of word
996 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
997 if (!isTextAt(special_phrases[pnr].phrase, i))
999 os << special_phrases[pnr].macro;
1000 i += special_phrases[pnr].phrase.length() - 1;
1001 column += special_phrases[pnr].macro.length() - 1;
1008 void Paragraph::Private::validate(LaTeXFeatures & features,
1009 Layout const & layout) const
1011 // check the params.
1012 if (!params_.spacing().isDefault())
1013 features.require("setspace");
1016 features.useLayout(layout.name());
1019 fontlist_.validate(features);
1021 // then the indentation
1022 if (!params_.leftIndent().zero())
1023 features.require("ParagraphLeftIndent");
1026 InsetList::const_iterator icit = insetlist_.begin();
1027 InsetList::const_iterator iend = insetlist_.end();
1028 for (; icit != iend; ++icit) {
1030 icit->inset->validate(features);
1031 if (layout.needprotect &&
1032 icit->inset->lyxCode() == FOOT_CODE)
1033 features.require("NeedLyXFootnoteCode");
1037 // then the contents
1038 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1039 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1040 if (!special_phrases[pnr].builtin
1041 && isTextAt(special_phrases[pnr].phrase, i)) {
1042 features.require(special_phrases[pnr].phrase);
1046 Encodings::validate(text_[i], features);
1050 /////////////////////////////////////////////////////////////////////
1054 /////////////////////////////////////////////////////////////////////
1056 Paragraph::Paragraph()
1057 : d(new Paragraph::Private(this))
1064 Paragraph::Paragraph(Paragraph const & par)
1065 : itemdepth(par.itemdepth),
1066 d(new Paragraph::Private(*par.d, this))
1071 Paragraph & Paragraph::operator=(Paragraph const & par)
1073 // needed as we will destroy the private part before copying it
1075 itemdepth = par.itemdepth;
1078 d = new Private(*par.d, this);
1084 Paragraph::~Paragraph()
1090 void Paragraph::write(Buffer const & buf, ostream & os,
1091 BufferParams const & bparams,
1092 depth_type & dth) const
1094 // The beginning or end of a deeper (i.e. nested) area?
1095 if (dth != params().depth()) {
1096 if (params().depth() > dth) {
1097 while (params().depth() > dth) {
1098 os << "\n\\begin_deeper";
1102 while (params().depth() < dth) {
1103 os << "\n\\end_deeper";
1109 // First write the layout
1110 os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1114 Font font1(Font::ALL_INHERIT, bparams.language);
1116 Change running_change = Change(Change::UNCHANGED);
1119 for (pos_type i = 0; i <= size(); ++i) {
1121 Change change = lookupChange(i);
1122 Changes::lyxMarkChange(os, column, running_change, change);
1123 running_change = change;
1128 // Write font changes
1129 Font font2 = getFontSettings(bparams, i);
1130 if (font2 != font1) {
1131 font2.lyxWriteChanges(font1, os);
1136 char_type const c = d->text_[i];
1140 Inset const * inset = getInset(i);
1142 if (inset->directWrite()) {
1143 // international char, let it write
1144 // code directly so it's shorter in
1146 inset->write(buf, os);
1150 os << "\\begin_inset ";
1151 inset->write(buf, os);
1152 os << "\n\\end_inset\n\n";
1158 os << "\n\\backslash\n";
1162 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1169 if ((column > 70 && c == ' ')
1174 // this check is to amend a bug. LyX sometimes
1175 // inserts '\0' this could cause problems.
1177 std::vector<char> tmp = ucs4_to_utf8(c);
1178 tmp.push_back('\0');
1181 lyxerr << "ERROR (Paragraph::writeFile):"
1182 " NULL char in structure." << endl;
1188 os << "\n\\end_layout\n";
1192 void Paragraph::validate(LaTeXFeatures & features) const
1194 d->validate(features, *layout());
1198 void Paragraph::insert(pos_type start, docstring const & str,
1199 Font const & font, Change const & change)
1201 for (size_t i = 0, n = str.size(); i != n ; ++i)
1202 insertChar(start + i, str[i], font, change);
1206 void Paragraph::appendChar(char_type c, Font const & font,
1207 Change const & change)
1210 d->changes_.insert(change, d->text_.size());
1211 // when appending characters, no need to update tables
1212 d->text_.push_back(c);
1213 setFont(d->text_.size() - 1, font);
1217 void Paragraph::appendString(docstring const & s, Font const & font,
1218 Change const & change)
1220 size_t end = s.size();
1221 size_t oldsize = d->text_.size();
1222 size_t newsize = oldsize + end;
1223 size_t capacity = d->text_.capacity();
1224 if (newsize >= capacity)
1225 d->text_.reserve(std::max(capacity + 100, newsize));
1227 // when appending characters, no need to update tables
1230 // FIXME: Optimize this!
1231 for (pos_type i = 0; i != end; ++i) {
1233 d->changes_.insert(change, i);
1235 d->fontlist_.setRange(oldsize, newsize, font);
1239 void Paragraph::insertChar(pos_type pos, char_type c,
1242 d->insertChar(pos, c, Change(trackChanges ?
1243 Change::INSERTED : Change::UNCHANGED));
1247 void Paragraph::insertChar(pos_type pos, char_type c,
1248 Font const & font, bool trackChanges)
1250 d->insertChar(pos, c, Change(trackChanges ?
1251 Change::INSERTED : Change::UNCHANGED));
1256 void Paragraph::insertChar(pos_type pos, char_type c,
1257 Font const & font, Change const & change)
1259 d->insertChar(pos, c, change);
1264 void Paragraph::insertInset(pos_type pos, Inset * inset,
1265 Font const & font, Change const & change)
1267 insertInset(pos, inset, change);
1268 // Set the font/language of the inset...
1273 bool Paragraph::insetAllowed(InsetCode code)
1275 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1279 // Gets uninstantiated font setting at position.
1280 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1284 lyxerr << " pos: " << pos << " size: " << size() << endl;
1285 BOOST_ASSERT(pos <= size());
1288 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1289 if (cit != d->fontlist_.end())
1292 if (pos == size() && !empty())
1293 return getFontSettings(bparams, pos - 1);
1295 return Font(Font::ALL_INHERIT, getParLanguage(bparams));
1299 FontSpan Paragraph::fontSpan(pos_type pos) const
1301 BOOST_ASSERT(pos <= size());
1304 FontList::const_iterator cit = d->fontlist_.begin();
1305 FontList::const_iterator end = d->fontlist_.end();
1306 for (; cit != end; ++cit) {
1307 if (cit->pos() >= pos) {
1308 if (pos >= beginOfBody())
1309 return FontSpan(std::max(start, beginOfBody()),
1312 return FontSpan(start,
1313 std::min(beginOfBody() - 1,
1316 start = cit->pos() + 1;
1319 // This should not happen, but if so, we take no chances.
1320 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1322 return FontSpan(pos, pos);
1326 // Gets uninstantiated font setting at position 0
1327 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1329 if (!empty() && !d->fontlist_.empty())
1330 return d->fontlist_.begin()->font();
1332 return Font(Font::ALL_INHERIT, bparams.language);
1336 // Gets the fully instantiated font at a given position in a paragraph
1337 // This is basically the same function as Text::GetFont() in text2.cpp.
1338 // The difference is that this one is used for generating the LaTeX file,
1339 // and thus cosmetic "improvements" are disallowed: This has to deliver
1340 // the true picture of the buffer. (Asger)
1341 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1342 Font const & outerfont) const
1344 BOOST_ASSERT(pos >= 0);
1346 Font font = getFontSettings(bparams, pos);
1348 pos_type const body_pos = beginOfBody();
1350 font.realize(d->layout_->labelfont);
1352 font.realize(d->layout_->font);
1354 font.realize(outerfont);
1355 font.realize(bparams.getFont());
1361 Font const Paragraph::getLabelFont
1362 (BufferParams const & bparams, Font const & outerfont) const
1364 Font tmpfont = layout()->labelfont;
1365 tmpfont.setLanguage(getParLanguage(bparams));
1366 tmpfont.realize(outerfont);
1367 tmpfont.realize(bparams.getFont());
1372 Font const Paragraph::getLayoutFont
1373 (BufferParams const & bparams, Font const & outerfont) const
1375 Font tmpfont = layout()->font;
1376 tmpfont.setLanguage(getParLanguage(bparams));
1377 tmpfont.realize(outerfont);
1378 tmpfont.realize(bparams.getFont());
1383 /// Returns the height of the highest font in range
1384 Font_size Paragraph::highestFontInRange
1385 (pos_type startpos, pos_type endpos, Font_size def_size) const
1387 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1392 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1394 char_type c = d->text_[pos];
1395 if (!lyxrc.rtl_support)
1425 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1432 void Paragraph::setFont(pos_type pos, Font const & font)
1434 BOOST_ASSERT(pos <= size());
1436 // First, reduce font against layout/label font
1437 // Update: The setCharFont() routine in text2.cpp already
1438 // reduces font, so we don't need to do that here. (Asger)
1440 d->fontlist_.set(pos, font);
1444 void Paragraph::makeSameLayout(Paragraph const & par)
1446 layout(par.layout());
1448 d->params_ = par.params();
1452 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1454 if (isFreeSpacing())
1460 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1461 if (eraseChar(pos, trackChanges))
1467 return count > 0 || pos > 0;
1471 bool Paragraph::hasSameLayout(Paragraph const & par) const
1473 return par.layout() == layout() && d->params_.sameLayout(par.params());
1477 depth_type Paragraph::getDepth() const
1479 return params().depth();
1483 depth_type Paragraph::getMaxDepthAfter() const
1485 if (layout()->isEnvironment())
1486 return params().depth() + 1;
1488 return params().depth();
1492 char Paragraph::getAlign() const
1494 if (params().align() == LYX_ALIGN_LAYOUT)
1495 return layout()->align;
1497 return params().align();
1501 docstring const & Paragraph::getLabelstring() const
1503 return params().labelString();
1507 // the next two functions are for the manual labels
1508 docstring const Paragraph::getLabelWidthString() const
1510 if (layout()->margintype == MARGIN_MANUAL)
1511 return params().labelWidthString();
1513 return _("Senseless with this layout!");
1517 void Paragraph::setLabelWidthString(docstring const & s)
1519 params().labelWidthString(s);
1523 docstring const Paragraph::translateIfPossible(docstring const & s,
1524 BufferParams const & bparams) const
1526 if (!support::isAscii(s) || s.empty()) {
1527 // This must be a user defined layout. We cannot translate
1528 // this, since gettext accepts only ascii keys.
1531 // Probably standard layout, try to translate
1532 Messages & m = getMessages(getParLanguage(bparams)->code());
1533 return m.get(to_ascii(s));
1537 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1538 BufferParams const & bparams, bool process_appendix) const
1540 TextClass const & tclass = bparams.getTextClass();
1543 if (process_appendix && params().appendix())
1544 fmt = translateIfPossible(layout->labelstring_appendix(),
1547 fmt = translateIfPossible(layout->labelstring(), bparams);
1549 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1550 && !layout->counter.empty())
1551 fmt = "\\the" + layout->counter;
1553 // handle 'inherited level parts' in 'fmt',
1554 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1555 size_t const i = fmt.find('@', 0);
1556 if (i != docstring::npos) {
1557 size_t const j = fmt.find('@', i + 1);
1558 if (j != docstring::npos) {
1559 docstring parent(fmt, i + 1, j - i - 1);
1560 docstring label = from_ascii("??");
1561 if (tclass.hasLayout(parent))
1562 docstring label = expandLabel(tclass[parent], bparams,
1564 fmt = docstring(fmt, 0, i) + label
1565 + docstring(fmt, j + 1, docstring::npos);
1569 return tclass.counters().counterLabel(fmt);
1573 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1576 LyXAlignment const oldAlign = params().align();
1578 if (!(oldAlign & layout()->alignpossible)) {
1579 frontend::Alert::warning(_("Alignment not permitted"),
1580 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1581 params().align(LYX_ALIGN_LAYOUT);
1586 pos_type Paragraph::beginOfBody() const
1588 return d->begin_of_body_;
1592 void Paragraph::setBeginOfBody()
1594 if (layout()->labeltype != LABEL_MANUAL) {
1595 d->begin_of_body_ = 0;
1599 // Unroll the first two cycles of the loop
1600 // and remember the previous character to
1601 // remove unnecessary getChar() calls
1603 pos_type end = size();
1604 if (i < end && !isNewline(i)) {
1606 char_type previous_char = 0;
1609 previous_char = d->text_[i];
1610 if (!isNewline(i)) {
1612 while (i < end && previous_char != ' ') {
1617 previous_char = temp;
1623 d->begin_of_body_ = i;
1627 bool Paragraph::forceDefaultParagraphs() const
1629 return inInset() && inInset()->forceDefaultParagraphs(0);
1635 // paragraphs inside floats need different alignment tags to avoid
1638 bool noTrivlistCentering(InsetCode code)
1640 return code == FLOAT_CODE || code == WRAP_CODE;
1644 string correction(string const & orig)
1646 if (orig == "flushleft")
1647 return "raggedright";
1648 if (orig == "flushright")
1649 return "raggedleft";
1650 if (orig == "center")
1656 string const corrected_env(string const & suffix, string const & env,
1659 string output = suffix + "{";
1660 if (noTrivlistCentering(code))
1661 output += correction(env);
1665 if (suffix == "\\begin")
1671 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1673 if (!contains(str, "\n"))
1674 column += str.size();
1678 column = rsplit(str, tmp, '\n').size();
1685 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1686 odocstream & os, TexRow & texrow,
1687 bool moving_arg) const
1691 if (params_.noindent()) {
1692 os << "\\noindent ";
1696 LyXAlignment const curAlign = params_.align();
1698 if (curAlign == layout_->align)
1702 case LYX_ALIGN_NONE:
1703 case LYX_ALIGN_BLOCK:
1704 case LYX_ALIGN_LAYOUT:
1705 case LYX_ALIGN_SPECIAL:
1707 case LYX_ALIGN_LEFT:
1708 case LYX_ALIGN_RIGHT:
1709 case LYX_ALIGN_CENTER:
1718 case LYX_ALIGN_NONE:
1719 case LYX_ALIGN_BLOCK:
1720 case LYX_ALIGN_LAYOUT:
1721 case LYX_ALIGN_SPECIAL:
1723 case LYX_ALIGN_LEFT: {
1725 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1726 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1728 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1729 os << from_ascii(output);
1730 adjust_row_column(output, texrow, column);
1732 } case LYX_ALIGN_RIGHT: {
1734 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1735 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1737 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1738 os << from_ascii(output);
1739 adjust_row_column(output, texrow, column);
1741 } case LYX_ALIGN_CENTER: {
1743 output = corrected_env("\\begin", "center", owner_->ownerCode());
1744 os << from_ascii(output);
1745 adjust_row_column(output, texrow, column);
1754 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1755 odocstream & os, TexRow & texrow,
1756 bool moving_arg) const
1760 switch (params_.align()) {
1761 case LYX_ALIGN_NONE:
1762 case LYX_ALIGN_BLOCK:
1763 case LYX_ALIGN_LAYOUT:
1764 case LYX_ALIGN_SPECIAL:
1766 case LYX_ALIGN_LEFT:
1767 case LYX_ALIGN_RIGHT:
1768 case LYX_ALIGN_CENTER:
1776 switch (params_.align()) {
1777 case LYX_ALIGN_NONE:
1778 case LYX_ALIGN_BLOCK:
1779 case LYX_ALIGN_LAYOUT:
1780 case LYX_ALIGN_SPECIAL:
1782 case LYX_ALIGN_LEFT: {
1784 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1785 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1787 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1788 os << from_ascii(output);
1789 adjust_row_column(output, texrow, column);
1791 } case LYX_ALIGN_RIGHT: {
1793 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1794 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1796 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1797 os << from_ascii(output);
1798 adjust_row_column(output, texrow, column);
1800 } case LYX_ALIGN_CENTER: {
1802 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1803 os << from_ascii(output);
1804 adjust_row_column(output, texrow, column);
1813 // This one spits out the text of the paragraph
1814 bool Paragraph::latex(Buffer const & buf,
1815 BufferParams const & bparams,
1816 Font const & outerfont,
1817 odocstream & os, TexRow & texrow,
1818 OutputParams const & runparams) const
1820 LYXERR(Debug::LATEX) << "SimpleTeXOnePar... " << this << endl;
1822 bool return_value = false;
1826 // well we have to check if we are in an inset with unlimited
1827 // length (all in one row) if that is true then we don't allow
1828 // any special options in the paragraph and also we don't allow
1829 // any environment other than the default layout of the text class
1831 bool asdefault = forceDefaultParagraphs();
1834 style = bparams.getTextClass().defaultLayout();
1839 // Current base font for all inherited font changes, without any
1840 // change caused by an individual character, except for the language:
1841 // It is set to the language of the first character.
1842 // As long as we are in the label, this font is the base font of the
1843 // label. Before the first body character it is set to the base font
1847 // Maybe we have to create a optional argument.
1848 pos_type body_pos = beginOfBody();
1849 unsigned int column = 0;
1852 // the optional argument is kept in curly brackets in
1853 // case it contains a ']'
1856 basefont = getLabelFont(bparams, outerfont);
1858 basefont = getLayoutFont(bparams, outerfont);
1861 // Which font is currently active?
1862 Font running_font(basefont);
1863 // Do we have an open font change?
1864 bool open_font = false;
1866 Change runningChange = Change(Change::UNCHANGED);
1868 texrow.start(id(), 0);
1870 // if the paragraph is empty, the loop will not be entered at all
1872 if (style->isCommand()) {
1877 column += d->startTeXParParams(bparams, os, texrow,
1878 runparams.moving_arg);
1881 for (pos_type i = 0; i < size(); ++i) {
1882 // First char in paragraph or after label?
1883 if (i == body_pos) {
1886 column += running_font.latexWriteEndChanges(
1887 os, bparams, runparams,
1888 basefont, basefont);
1891 basefont = getLayoutFont(bparams, outerfont);
1892 running_font = basefont;
1894 column += Changes::latexMarkChange(os, bparams,
1895 runningChange, Change(Change::UNCHANGED));
1896 runningChange = Change(Change::UNCHANGED);
1901 if (style->isCommand()) {
1907 column += d->startTeXParParams(bparams, os,
1909 runparams.moving_arg);
1912 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1915 if (bparams.outputChanges && runningChange != change) {
1917 column += running_font.latexWriteEndChanges(
1918 os, bparams, runparams, basefont, basefont);
1921 basefont = getLayoutFont(bparams, outerfont);
1922 running_font = basefont;
1924 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1925 runningChange = change;
1928 // do not output text which is marked deleted
1929 // if change tracking output is disabled
1930 if (!bparams.outputChanges && change.type == Change::DELETED) {
1936 // Fully instantiated font
1937 Font const font = getFont(bparams, i, outerfont);
1939 Font const last_font = running_font;
1941 // Do we need to close the previous font?
1943 (font != running_font ||
1944 font.language() != running_font.language()))
1946 column += running_font.latexWriteEndChanges(
1947 os, bparams, runparams, basefont,
1948 (i == body_pos-1) ? basefont : font);
1949 running_font = basefont;
1953 // Switch file encoding if necessary (and allowed)
1954 if (!runparams.verbatim &&
1955 runparams.encoding->package() == Encoding::inputenc &&
1956 font.language()->encoding()->package() == Encoding::inputenc) {
1957 std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1958 runparams.moving_arg, *(runparams.encoding),
1959 *(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.encoding), 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);
2023 d->latexSpecialChar(os, rp, running_font, runningChange,
2026 // Set the encoding to that returned from simpleTeXSpecialChars (see
2027 // comment for encoding member in OutputParams.h)
2028 runparams.encoding = rp.encoding;
2031 // If we have an open font definition, we have to close it
2033 #ifdef FIXED_LANGUAGE_END_DETECTION
2036 .latexWriteEndChanges(os, bparams, runparams,
2038 next_->getFont(bparams, 0, outerfont));
2040 running_font.latexWriteEndChanges(os, bparams,
2041 runparams, basefont, basefont);
2044 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2045 //FIXME: there as we start another \selectlanguage with the next paragraph if
2046 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2047 running_font.latexWriteEndChanges(os, bparams, runparams,
2048 basefont, basefont);
2052 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2054 // Needed if there is an optional argument but no contents.
2055 if (body_pos > 0 && body_pos == size()) {
2057 return_value = false;
2061 column += d->endTeXParParams(bparams, os, texrow,
2062 runparams.moving_arg);
2065 LYXERR(Debug::LATEX) << "SimpleTeXOnePar...done " << this << endl;
2066 return return_value;
2083 string tag_name(PAR_TAG const & pt) {
2085 case PAR_NONE: return "!-- --";
2086 case TT: return "tt";
2087 case SF: return "sf";
2088 case BF: return "bf";
2089 case IT: return "it";
2090 case SL: return "sl";
2091 case EM: return "em";
2098 void operator|=(PAR_TAG & p1, PAR_TAG const & p2)
2100 p1 = static_cast<PAR_TAG>(p1 | p2);
2105 void reset(PAR_TAG & p1, PAR_TAG const & p2)
2107 p1 = static_cast<PAR_TAG>(p1 & ~p2);
2113 bool Paragraph::emptyTag() const
2115 for (pos_type i = 0; i < size(); ++i) {
2117 Inset const * inset = getInset(i);
2118 InsetCode lyx_code = inset->lyxCode();
2119 if (lyx_code != TOC_CODE &&
2120 lyx_code != INCLUDE_CODE &&
2121 lyx_code != GRAPHICS_CODE &&
2122 lyx_code != ERT_CODE &&
2123 lyx_code != LISTINGS_CODE &&
2124 lyx_code != FLOAT_CODE &&
2125 lyx_code != TABULAR_CODE) {
2129 char_type c = d->text_[i];
2130 if (c != ' ' && c != '\t')
2138 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2140 for (pos_type i = 0; i < size(); ++i) {
2142 Inset const * inset = getInset(i);
2143 InsetCode lyx_code = inset->lyxCode();
2144 if (lyx_code == LABEL_CODE) {
2145 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2146 docstring const & id = il->getParam("name");
2147 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2156 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2159 for (i = 0; i < size(); ++i) {
2161 Inset const * inset = getInset(i);
2162 inset->docbook(buf, os, runparams);
2164 char_type c = d->text_[i];
2167 os << sgml::escapeChar(c);
2174 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2177 pos_type size = text_.size();
2178 for (pos_type i = initial; i < size; ++i) {
2179 Font font = owner_->getFont(buf.params(), i, outerfont);
2180 if (text_[i] == META_INSET)
2182 if (i != initial && font != font_old)
2191 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2193 OutputParams const & runparams,
2194 Font const & outerfont,
2195 pos_type initial) const
2197 bool emph_flag = false;
2199 LayoutPtr const & style = layout();
2201 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2203 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2206 // parsing main loop
2207 for (pos_type i = initial; i < size(); ++i) {
2208 Font font = getFont(buf.params(), i, outerfont);
2210 // handle <emphasis> tag
2211 if (font_old.emph() != font.emph()) {
2212 if (font.emph() == Font::ON) {
2215 } else if (i != initial) {
2216 os << "</emphasis>";
2222 Inset const * inset = getInset(i);
2223 inset->docbook(buf, os, runparams);
2225 char_type c = d->text_[i];
2227 if (style->pass_thru)
2230 os << sgml::escapeChar(c);
2236 os << "</emphasis>";
2239 if (style->free_spacing)
2241 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2246 bool Paragraph::isHfill(pos_type pos) const
2249 && getInset(pos)->lyxCode() == HFILL_CODE;
2253 bool Paragraph::isNewline(pos_type pos) const
2256 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2260 bool Paragraph::isLineSeparator(pos_type pos) const
2262 char_type const c = d->text_[pos];
2263 return isLineSeparatorChar(c)
2264 || (c == META_INSET && getInset(pos) &&
2265 getInset(pos)->isLineSeparator());
2269 /// Used by the spellchecker
2270 bool Paragraph::isLetter(pos_type pos) const
2273 return getInset(pos)->isLetter();
2275 char_type const c = d->text_[pos];
2276 return isLetterChar(c) || isDigit(c);
2282 Paragraph::getParLanguage(BufferParams const & bparams) const
2285 return getFirstFontSettings(bparams).language();
2286 // FIXME: we should check the prev par as well (Lgb)
2287 return bparams.language;
2291 bool Paragraph::isRTL(BufferParams const & bparams) const
2293 return lyxrc.rtl_support
2294 && getParLanguage(bparams)->rightToLeft()
2295 && ownerCode() != ERT_CODE
2296 && ownerCode() != LISTINGS_CODE;
2300 void Paragraph::changeLanguage(BufferParams const & bparams,
2301 Language const * from, Language const * to)
2303 // change language including dummy font change at the end
2304 for (pos_type i = 0; i <= size(); ++i) {
2305 Font font = getFontSettings(bparams, i);
2306 if (font.language() == from) {
2307 font.setLanguage(to);
2314 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2316 Language const * doc_language = bparams.language;
2317 FontList::const_iterator cit = d->fontlist_.begin();
2318 FontList::const_iterator end = d->fontlist_.end();
2320 for (; cit != end; ++cit)
2321 if (cit->font().language() != ignore_language &&
2322 cit->font().language() != latex_language &&
2323 cit->font().language() != doc_language)
2329 // Convert the paragraph to a string.
2330 // Used for building the table of contents
2331 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2333 return asString(buffer, 0, size(), label);
2337 docstring const Paragraph::asString(Buffer const & buffer,
2338 pos_type beg, pos_type end, bool label) const
2341 odocstringstream os;
2343 if (beg == 0 && label && !params().labelString().empty())
2344 os << params().labelString() << ' ';
2346 for (pos_type i = beg; i < end; ++i) {
2347 char_type const c = d->text_[i];
2350 else if (c == META_INSET)
2351 getInset(i)->textString(buffer, os);
2358 void Paragraph::setInsetOwner(Inset * inset)
2360 d->inset_owner_ = inset;
2364 int Paragraph::id() const
2370 LayoutPtr const & Paragraph::layout() const
2376 void Paragraph::layout(LayoutPtr const & new_layout)
2378 d->layout_ = new_layout;
2382 Inset * Paragraph::inInset() const
2384 return d->inset_owner_;
2388 InsetCode Paragraph::ownerCode() const
2390 return d->inset_owner_ ?
2391 d->inset_owner_->lyxCode() : NO_CODE;
2395 ParagraphParameters & Paragraph::params()
2401 ParagraphParameters const & Paragraph::params() const
2407 bool Paragraph::isFreeSpacing() const
2409 if (layout()->free_spacing)
2412 // for now we just need this, later should we need this in some
2413 // other way we can always add a function to Inset too.
2414 return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2418 bool Paragraph::allowEmpty() const
2420 if (layout()->keepempty)
2422 return ownerCode() == ERT_CODE || ownerCode() == LISTINGS_CODE;
2426 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2428 if (!Encodings::is_arabic(c))
2431 char_type prev_char = ' ';
2432 char_type next_char = ' ';
2434 for (pos_type i = pos - 1; i >= 0; --i) {
2435 char_type const par_char = d->text_[i];
2436 if (!Encodings::isComposeChar_arabic(par_char)) {
2437 prev_char = par_char;
2442 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2443 char_type const par_char = d->text_[i];
2444 if (!Encodings::isComposeChar_arabic(par_char)) {
2445 next_char = par_char;
2450 if (Encodings::is_arabic(next_char)) {
2451 if (Encodings::is_arabic(prev_char) &&
2452 !Encodings::is_arabic_special(prev_char))
2453 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2455 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2457 if (Encodings::is_arabic(prev_char) &&
2458 !Encodings::is_arabic_special(prev_char))
2459 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2461 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2466 int Paragraph::checkBiblio(bool track_changes)
2469 //This is getting more and more a mess. ...We really should clean
2470 //up this bibitem issue for 1.6. See also bug 2743.
2472 // Add bibitem insets if necessary
2473 if (layout()->labeltype != LABEL_BIBLIO)
2476 bool hasbibitem = !d->insetlist_.empty()
2477 // Insist on it being in pos 0
2478 && d->text_[0] == META_INSET
2479 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2484 // remove a bibitem in pos != 0
2485 // restore it later in pos 0 if necessary
2486 // (e.g. if a user inserts contents _before_ the item)
2487 // we're assuming there's only one of these, which there
2489 int erasedInsetPosition = -1;
2490 InsetList::iterator it = d->insetlist_.begin();
2491 InsetList::iterator end = d->insetlist_.end();
2492 for (; it != end; ++it)
2493 if (it->inset->lyxCode() == BIBITEM_CODE
2495 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2496 oldkey = olditem->getParam("key");
2497 oldlabel = olditem->getParam("label");
2498 erasedInsetPosition = it->pos;
2499 eraseChar(erasedInsetPosition, track_changes);
2503 //There was an InsetBibitem at the beginning, and we didn't
2504 //have to erase one.
2505 if (hasbibitem && erasedInsetPosition < 0)
2508 //There was an InsetBibitem at the beginning and we did have to
2509 //erase one. So we give its properties to the beginning inset.
2511 InsetBibitem * inset =
2512 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2513 if (!oldkey.empty())
2514 inset->setParam("key", oldkey);
2515 inset->setParam("label", oldlabel);
2516 return -erasedInsetPosition;
2519 //There was no inset at the beginning, so we need to create one with
2520 //the key and label of the one we erased.
2521 InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2522 // restore values of previously deleted item in this par.
2523 if (!oldkey.empty())
2524 inset->setParam("key", oldkey);
2525 inset->setParam("label", oldlabel);
2526 insertInset(0, static_cast<Inset *>(inset),
2527 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2533 void Paragraph::checkAuthors(AuthorList const & authorList)
2535 d->changes_.checkAuthors(authorList);
2539 bool Paragraph::isUnchanged(pos_type pos) const
2541 return lookupChange(pos).type == Change::UNCHANGED;
2545 bool Paragraph::isInserted(pos_type pos) const
2547 return lookupChange(pos).type == Change::INSERTED;
2551 bool Paragraph::isDeleted(pos_type pos) const
2553 return lookupChange(pos).type == Change::DELETED;
2557 InsetList const & Paragraph::insetList() const
2559 return d->insetlist_;
2563 Inset * Paragraph::releaseInset(pos_type pos)
2565 Inset * inset = d->insetlist_.release(pos);
2566 /// does not honour change tracking!
2567 eraseChar(pos, false);
2572 Inset * Paragraph::getInset(pos_type pos)
2574 return d->insetlist_.get(pos);
2578 Inset const * Paragraph::getInset(pos_type pos) const
2580 return d->insetlist_.get(pos);
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] == ' ';