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"
38 #include "OutputParams.h"
39 #include "output_latex.h"
40 #include "paragraph_funcs.h"
41 #include "ParagraphParameters.h"
46 #include "frontends/alert.h"
47 #include "frontends/FontMetrics.h"
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
51 #include "insets/InsetOptArg.h"
53 #include "support/lstrings.h"
54 #include "support/textutils.h"
55 #include "support/convert.h"
56 #include "support/unicode.h"
67 using support::contains;
68 using support::lowercase;
69 using support::prefixIs;
70 using support::suffixIs;
71 using support::rsplit;
72 using support::uppercase;
75 /// Inset identifier (above 0x10ffff, for ucs-4)
76 char_type const META_INSET = 0x200001;
79 /////////////////////////////////////////////////////////////////////
83 /////////////////////////////////////////////////////////////////////
85 class Paragraph::Private
89 Private(Paragraph * owner);
90 /// "Copy constructor"
91 Private(Private const &, Paragraph * owner);
94 void insertChar(pos_type pos, char_type c, Change const & change);
96 /// Output the surrogate pair formed by \p c and \p next to \p os.
97 /// \return the number of characters written.
98 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
101 /// Output a space in appropriate formatting (or a surrogate pair
102 /// if the next character is a combining character).
103 /// \return whether a surrogate pair was output.
104 bool simpleTeXBlanks(Encoding const &,
105 odocstream &, TexRow & texrow,
107 unsigned int & column,
109 Layout const & style);
111 /// Output consecutive unicode chars, belonging to the same script as
112 /// specified by the latex macro \p ltx, to \p os starting from \p c.
113 /// \return the number of characters written.
114 int writeScriptChars(odocstream & os, char_type c, docstring const & ltx,
115 Change &, Encoding const &, pos_type &);
117 /// This could go to ParagraphParameters if we want to.
118 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
121 /// This could go to ParagraphParameters if we want to.
122 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
126 void latexInset(Buffer const &, BufferParams const &,
128 TexRow & texrow, OutputParams &,
131 Font const & outerfont,
133 Change & running_change,
134 Layout const & style,
136 unsigned int & column);
139 void latexSpecialChar(
141 OutputParams & runparams,
143 Change & running_change,
144 Layout const & style,
146 unsigned int & column);
153 unsigned int & column);
155 bool latexSpecialTypewriter(
159 unsigned int & column);
161 bool latexSpecialPhrase(
164 unsigned int & column);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(std::string const & str, pos_type pos) const;
177 /// Which Paragraph owns us?
181 Inset * inset_owner_;
189 static unsigned int paragraph_id;
191 ParagraphParameters params_;
193 /// for recording and looking up changes
197 InsetList insetlist_;
203 pos_type begin_of_body_;
205 typedef docstring TextContainer;
214 using std::upper_bound;
215 using std::lower_bound;
219 // Initialization of the counter for the paragraph id's,
220 unsigned int Paragraph::Private::paragraph_id = 0;
224 struct special_phrase {
230 special_phrase const special_phrases[] = {
231 { "LyX", from_ascii("\\protect\\LyX{}"), false },
232 { "TeX", from_ascii("\\protect\\TeX{}"), true },
233 { "LaTeX2e", from_ascii("\\protect\\LaTeXe{}"), true },
234 { "LaTeX", from_ascii("\\protect\\LaTeX{}"), true },
237 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
242 Paragraph::Private::Private(Paragraph * owner)
243 : owner_(owner), inset_owner_(0), begin_of_body_(0)
245 id_ = paragraph_id++;
250 Paragraph::Private::Private(Private const & p, Paragraph * owner)
251 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
252 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
253 layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_)
255 id_ = paragraph_id++;
259 bool Paragraph::isChanged(pos_type start, pos_type end) const
261 BOOST_ASSERT(start >= 0 && start <= size());
262 BOOST_ASSERT(end > start && end <= size() + 1);
264 return d->changes_.isChanged(start, end);
268 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const {
269 // keep the logic here in sync with the logic of eraseChars()
275 Change change = d->changes_.lookup(size());
277 return change.type == Change::INSERTED && change.author == 0;
281 void Paragraph::setChange(Change const & change)
283 // beware of the imaginary end-of-par character!
284 d->changes_.set(change, 0, size() + 1);
287 * Propagate the change recursively - but not in case of DELETED!
289 * Imagine that your co-author makes changes in an existing inset. He
290 * sends your document to you and you come to the conclusion that the
291 * inset should go completely. If you erase it, LyX must not delete all
292 * text within the inset. Otherwise, the change tracked insertions of
293 * your co-author get lost and there is no way to restore them later.
295 * Conclusion: An inset's content should remain untouched if you delete it
298 if (change.type != Change::DELETED) {
299 for (pos_type pos = 0; pos < size(); ++pos) {
301 getInset(pos)->setChange(change);
307 void Paragraph::setChange(pos_type pos, Change const & change)
309 BOOST_ASSERT(pos >= 0 && pos <= size());
311 d->changes_.set(change, pos);
313 // see comment in setChange(Change const &) above
315 if (change.type != Change::DELETED &&
316 pos < size() && isInset(pos)) {
317 getInset(pos)->setChange(change);
322 Change const & Paragraph::lookupChange(pos_type pos) const
324 BOOST_ASSERT(pos >= 0 && pos <= size());
326 return d->changes_.lookup(pos);
330 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
333 BOOST_ASSERT(start >= 0 && start <= size());
334 BOOST_ASSERT(end > start && end <= size() + 1);
336 for (pos_type pos = start; pos < end; ++pos) {
337 switch (lookupChange(pos).type) {
338 case Change::UNCHANGED:
339 // accept changes in nested inset
340 if (pos < size() && isInset(pos))
341 getInset(pos)->acceptChanges(bparams);
345 case Change::INSERTED:
346 d->changes_.set(Change(Change::UNCHANGED), pos);
347 // also accept changes in nested inset
348 if (pos < size() && isInset(pos)) {
349 getInset(pos)->acceptChanges(bparams);
353 case Change::DELETED:
354 // Suppress access to non-existent
355 // "end-of-paragraph char"
357 eraseChar(pos, false);
368 void Paragraph::rejectChanges(BufferParams const & bparams,
369 pos_type start, pos_type end)
371 BOOST_ASSERT(start >= 0 && start <= size());
372 BOOST_ASSERT(end > start && end <= size() + 1);
374 for (pos_type pos = start; pos < end; ++pos) {
375 switch (lookupChange(pos).type) {
376 case Change::UNCHANGED:
377 // reject changes in nested inset
378 if (pos < size() && isInset(pos)) {
379 getInset(pos)->rejectChanges(bparams);
383 case Change::INSERTED:
384 // Suppress access to non-existent
385 // "end-of-paragraph char"
387 eraseChar(pos, false);
393 case Change::DELETED:
394 d->changes_.set(Change(Change::UNCHANGED), pos);
396 // Do NOT reject changes within a deleted inset!
397 // There may be insertions of a co-author inside of it!
405 void Paragraph::Private::insertChar(pos_type pos, char_type c,
406 Change const & change)
408 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
411 changes_.insert(change, pos);
413 // This is actually very common when parsing buffers (and
414 // maybe inserting ascii text)
415 if (pos == text_.size()) {
416 // when appending characters, no need to update tables
421 text_.insert(text_.begin() + pos, c);
423 // Update the font table.
424 fontlist_.increasePosAfterPos(pos);
427 insetlist_.increasePosAfterPos(pos);
431 void Paragraph::insertInset(pos_type pos, Inset * inset,
432 Change const & change)
435 BOOST_ASSERT(pos >= 0 && pos <= size());
437 d->insertChar(pos, META_INSET, change);
438 BOOST_ASSERT(d->text_[pos] == META_INSET);
440 // Add a new entry in the insetlist_.
441 d->insetlist_.insert(inset, pos);
445 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
447 BOOST_ASSERT(pos >= 0 && pos <= size());
449 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
452 Change change = d->changes_.lookup(pos);
454 // set the character to DELETED if
455 // a) it was previously unchanged or
456 // b) it was inserted by a co-author
458 if (change.type == Change::UNCHANGED ||
459 (change.type == Change::INSERTED && change.author != 0)) {
460 setChange(pos, Change(Change::DELETED));
464 if (change.type == Change::DELETED)
468 // Don't physically access the imaginary end-of-paragraph character.
469 // eraseChar() can only mark it as DELETED. A physical deletion of
470 // end-of-par must be handled externally.
476 d->changes_.erase(pos);
478 // if it is an inset, delete the inset entry
479 if (d->text_[pos] == META_INSET)
480 d->insetlist_.erase(pos);
482 d->text_.erase(d->text_.begin() + pos);
484 // Update the fontlist_
485 d->fontlist_.erase(pos);
487 // Update the insetlist_
488 d->insetlist_.decreasePosAfterPos(pos);
494 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
496 BOOST_ASSERT(start >= 0 && start <= size());
497 BOOST_ASSERT(end >= start && end <= size() + 1);
500 for (pos_type count = end - start; count; --count) {
501 if (!eraseChar(i, trackChanges))
508 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
509 char_type next, Encoding const & encoding)
511 // Writing next here may circumvent a possible font change between
512 // c and next. Since next is only output if it forms a surrogate pair
513 // with c we can ignore this:
514 // A font change inside a surrogate pair does not make sense and is
515 // hopefully impossible to input.
516 // FIXME: change tracking
517 // Is this correct WRT change tracking?
518 docstring const latex1 = encoding.latexChar(next);
519 docstring const latex2 = encoding.latexChar(c);
520 os << latex1 << '{' << latex2 << '}';
521 return latex1.length() + latex2.length() + 2;
525 bool Paragraph::Private::simpleTeXBlanks(Encoding const & encoding,
526 odocstream & os, TexRow & texrow,
528 unsigned int & column,
530 Layout const & style)
535 if (i + 1 < int(text_.size())) {
536 char_type next = text_[i + 1];
537 if (Encodings::isCombiningChar(next)) {
538 // This space has an accent, so we must always output it.
539 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
544 if (lyxrc.plaintext_linelen > 0
545 && column > lyxrc.plaintext_linelen
547 && text_[i - 1] != ' '
548 && (i + 1 < int(text_.size()))
549 // same in FreeSpacing mode
550 && !owner_->isFreeSpacing()
551 // In typewriter mode, we want to avoid
552 // ! . ? : at the end of a line
553 && !(font.family() == Font::TYPEWRITER_FAMILY
554 && (text_[i - 1] == '.'
555 || text_[i - 1] == '?'
556 || text_[i - 1] == ':'
557 || text_[i - 1] == '!'))) {
560 texrow.start(owner_->id(), i + 1);
562 } else if (style.free_spacing) {
571 int Paragraph::Private::writeScriptChars(odocstream & os,
573 docstring const & ltx,
574 Change & runningChange,
575 Encoding const & encoding,
578 // We only arrive here when a proper language for character c has not
579 // been specified (i.e., it could not be translated in the current
580 // latex encoding) and it belongs to a known script.
581 // Parameter ltx contains the latex translation of c as specified in
582 // the unicodesymbols file and is something like "\textXXX{<spec>}".
583 // The latex macro name "textXXX" specifies the script to which c
584 // belongs and we use it in order to check whether characters from the
585 // same script immediately follow, such that we can collect them in a
586 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
587 // for the first char but only "<spec>" for all subsequent chars.
588 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
589 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
590 string script = to_ascii(ltx.substr(1, brace1 - 1));
591 int length = ltx.substr(0, brace2).length();
592 os << ltx.substr(0, brace2);
593 int size = text_.size();
594 while (i + 1 < size) {
595 char_type const next = text_[i + 1];
596 // Stop here if next character belongs to another script
597 // or there is a change in change tracking status.
598 if (!Encodings::isKnownScriptChar(next, script) ||
599 runningChange != owner_->lookupChange(i + 1))
603 FontList::const_iterator cit = fontlist_.begin();
604 FontList::const_iterator end = fontlist_.end();
605 for (; cit != end; ++cit) {
606 if (cit->pos() >= i && !found) {
607 prev_font = cit->font();
610 if (cit->pos() >= i + 1)
613 // Stop here if there is a font attribute or encoding change.
614 if (found && cit != end && prev_font != cit->font())
616 docstring const latex = encoding.latexChar(next);
617 docstring::size_type const b1 =
618 latex.find_first_of(from_ascii("{"));
619 docstring::size_type const b2 =
620 latex.find_last_of(from_ascii("}"));
621 int const len = b2 - b1 - 1;
622 os << latex.substr(b1 + 1, len);
632 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
634 pos_type const len = str.length();
636 // is the paragraph large enough?
637 if (pos + len > int(text_.size()))
640 // does the wanted text start at point?
641 for (string::size_type i = 0; i < str.length(); ++i) {
642 // Caution: direct comparison of characters works only
643 // because str is pure ASCII.
644 if (str[i] != text_[pos + i])
648 return fontlist_.hasChangeInRange(pos, len);
652 void Paragraph::Private::latexInset(Buffer const & buf,
653 BufferParams const & bparams,
656 OutputParams & runparams,
659 Font const & outerfont,
661 Change & running_change,
662 Layout const & style,
664 unsigned int & column)
666 Inset * inset = owner_->getInset(i);
669 if (style.pass_thru) {
670 inset->plaintext(buf, os, runparams);
674 // FIXME: move this to InsetNewline::latex
675 if (inset->lyxCode() == NEWLINE_CODE) {
676 // newlines are handled differently here than
677 // the default in simpleTeXSpecialChars().
678 if (!style.newline_allowed) {
682 column += running_font.latexWriteEndChanges(
683 os, bparams, runparams,
688 if (running_font.family() == Font::TYPEWRITER_FAMILY)
691 basefont = owner_->getLayoutFont(bparams, outerfont);
692 running_font = basefont;
694 if (runparams.moving_arg)
700 texrow.start(owner_->id(), i + 1);
704 if (owner_->lookupChange(i).type == Change::DELETED) {
705 if( ++runparams.inDeletedInset == 1)
706 runparams.changeOfDeletedInset = owner_->lookupChange(i);
709 if (inset->canTrackChanges()) {
710 column += Changes::latexMarkChange(os, bparams, running_change,
711 Change(Change::UNCHANGED));
712 running_change = Change(Change::UNCHANGED);
716 odocstream::pos_type const len = os.tellp();
718 if ((inset->lyxCode() == GRAPHICS_CODE
719 || inset->lyxCode() == MATH_CODE
720 || inset->lyxCode() == HYPERLINK_CODE)
721 && running_font.isRightToLeft()) {
722 if (running_font.language()->lang() == "farsi")
729 // FIXME: Bug: we can have an empty font change here!
730 // if there has just been a font change, we are going to close it
731 // right now, which means stupid latex code like \textsf{}. AFAIK,
732 // this does not harm dvi output. A minor bug, thus (JMarc)
734 // Some insets cannot be inside a font change command.
735 // However, even such insets *can* be placed in \L or \R
736 // or their equivalents (for RTL language switches), so we don't
737 // close the language in those cases.
738 // ArabTeX, though, cannot handle this special behavior, it seems.
739 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
740 || running_font.language()->lang() == "arabic_arabtex";
741 if (open_font && inset->noFontChange()) {
742 bool closeLanguage = arabtex
743 || basefont.isRightToLeft() == running_font.isRightToLeft();
744 unsigned int count = running_font.latexWriteEndChanges(os,
745 bparams, runparams, basefont, basefont, closeLanguage);
747 // if any font properties were closed, update the running_font,
748 // making sure, however, to leave the language as it was
750 // FIXME: probably a better way to keep track of the old
751 // language, than copying the entire font?
752 Font const copy_font(running_font);
753 basefont = owner_->getLayoutFont(bparams, outerfont);
754 running_font = basefont;
756 running_font.setLanguage(copy_font.language());
757 // leave font open if language is still open
758 open_font = (running_font.language() == basefont.language());
760 runparams.local_font = &basefont;
764 int tmp = inset->latex(buf, os, runparams);
767 if (running_font.language()->lang() == "farsi")
774 for (int j = 0; j < tmp; ++j)
777 texrow.start(owner_->id(), i + 1);
780 column += os.tellp() - len;
783 if (owner_->lookupChange(i).type == Change::DELETED)
784 --runparams.inDeletedInset;
788 void Paragraph::Private::latexSpecialChar(
790 OutputParams & runparams,
792 Change & running_change,
793 Layout const & style,
795 unsigned int & column)
797 char_type const c = text_[i];
799 if (style.pass_thru) {
801 // FIXME UNICODE: This can fail if c cannot
802 // be encoded in the current encoding.
807 if (runparams.verbatim) {
812 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
815 if (running_font.family() == Font::TYPEWRITER_FAMILY
816 && latexSpecialTypewriter(c, os, i, column))
819 // Otherwise, we use what LaTeX provides us.
822 os << "\\textbackslash{}";
826 os << "\\textless{}";
830 os << "\\textgreater{}";
841 os << "\\char`\\\"{}";
846 case '%': case '#': case '{':
854 os << "\\textasciitilde{}";
859 os << "\\textasciicircum{}";
864 // avoid being mistaken for optional arguments
872 // Blanks are printed before font switching.
873 // Sure? I am not! (try nice-latex)
874 // I am sure it's correct. LyX might be smarter
875 // in the future, but for now, nothing wrong is
882 if (latexSpecialPhrase(os, i, column))
888 Encoding const & encoding = *(runparams.encoding);
889 if (i + 1 < int(text_.size())) {
890 char_type next = text_[i + 1];
891 if (Encodings::isCombiningChar(next)) {
892 column += latexSurrogatePair(os, c, next, encoding) - 1;
898 docstring const latex = encoding.latexChar(c);
899 if (Encodings::isKnownScriptChar(c, script)
900 && prefixIs(latex, from_ascii("\\" + script)))
901 column += writeScriptChars(os, c, latex,
902 running_change, encoding, i) - 1;
903 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
904 // Prevent eating of a following
905 // space or command corruption by
906 // following characters
907 column += latex.length() + 1;
910 column += latex.length() - 1;
918 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
919 pos_type & i, unsigned int & column)
925 // In T1 encoding, these characters exist
926 // but we should avoid ligatures
927 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
932 //os << "\\textcompwordmark{}";
944 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
945 pos_type & i, unsigned int & column)
949 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
950 // "--" in Typewriter mode -> "-{}-"
957 // I assume this is hack treating typewriter as verbatim
958 // FIXME UNICODE: This can fail if c cannot be encoded
959 // in the current encoding.
964 // Those characters are not directly supported.
968 case '%': case '#': case '{':
977 // With Typewriter font, these characters exist.
984 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
985 unsigned int & column)
987 // FIXME: if we have "LaTeX" with a font
988 // change in the middle (before the 'T', then
989 // the "TeX" part is still special cased.
990 // Really we should only operate this on
991 // "words" for some definition of word
993 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
994 if (!isTextAt(special_phrases[pnr].phrase, i))
996 os << special_phrases[pnr].macro;
997 i += special_phrases[pnr].phrase.length() - 1;
998 column += special_phrases[pnr].macro.length() - 1;
1005 void Paragraph::Private::validate(LaTeXFeatures & features,
1006 Layout const & layout) const
1008 // check the params.
1009 if (!params_.spacing().isDefault())
1010 features.require("setspace");
1013 features.useLayout(layout.name());
1016 fontlist_.validate(features);
1018 // then the indentation
1019 if (!params_.leftIndent().zero())
1020 features.require("ParagraphLeftIndent");
1023 InsetList::const_iterator icit = insetlist_.begin();
1024 InsetList::const_iterator iend = insetlist_.end();
1025 for (; icit != iend; ++icit) {
1027 icit->inset->validate(features);
1028 if (layout.needprotect &&
1029 icit->inset->lyxCode() == FOOT_CODE)
1030 features.require("NeedLyXFootnoteCode");
1034 // then the contents
1035 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1036 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1037 if (!special_phrases[pnr].builtin
1038 && isTextAt(special_phrases[pnr].phrase, i)) {
1039 features.require(special_phrases[pnr].phrase);
1043 Encodings::validate(text_[i], features);
1047 /////////////////////////////////////////////////////////////////////
1051 /////////////////////////////////////////////////////////////////////
1053 Paragraph::Paragraph()
1054 : d(new Paragraph::Private(this))
1061 Paragraph::Paragraph(Paragraph const & par)
1062 : itemdepth(par.itemdepth),
1063 d(new Paragraph::Private(*par.d, this))
1068 Paragraph & Paragraph::operator=(Paragraph const & par)
1070 // needed as we will destroy the private part before copying it
1072 itemdepth = par.itemdepth;
1075 d = new Private(*par.d, this);
1081 Paragraph::~Paragraph()
1087 void Paragraph::write(Buffer const & buf, ostream & os,
1088 BufferParams const & bparams,
1089 depth_type & dth) const
1091 // The beginning or end of a deeper (i.e. nested) area?
1092 if (dth != params().depth()) {
1093 if (params().depth() > dth) {
1094 while (params().depth() > dth) {
1095 os << "\n\\begin_deeper";
1099 while (params().depth() < dth) {
1100 os << "\n\\end_deeper";
1106 // First write the layout
1107 os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1111 Font font1(Font::ALL_INHERIT, bparams.language);
1113 Change running_change = Change(Change::UNCHANGED);
1116 for (pos_type i = 0; i <= size(); ++i) {
1118 Change change = lookupChange(i);
1119 Changes::lyxMarkChange(os, column, running_change, change);
1120 running_change = change;
1125 // Write font changes
1126 Font font2 = getFontSettings(bparams, i);
1127 if (font2 != font1) {
1128 font2.lyxWriteChanges(font1, os);
1133 char_type const c = d->text_[i];
1137 Inset const * inset = getInset(i);
1139 if (inset->directWrite()) {
1140 // international char, let it write
1141 // code directly so it's shorter in
1143 inset->write(buf, os);
1147 os << "\\begin_inset ";
1148 inset->write(buf, os);
1149 os << "\n\\end_inset\n\n";
1155 os << "\n\\backslash\n";
1159 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1166 if ((column > 70 && c == ' ')
1171 // this check is to amend a bug. LyX sometimes
1172 // inserts '\0' this could cause problems.
1174 std::vector<char> tmp = ucs4_to_utf8(c);
1175 tmp.push_back('\0');
1178 lyxerr << "ERROR (Paragraph::writeFile):"
1179 " NULL char in structure." << endl;
1185 os << "\n\\end_layout\n";
1189 void Paragraph::validate(LaTeXFeatures & features) const
1191 d->validate(features, *layout());
1195 void Paragraph::insert(pos_type start, docstring const & str,
1196 Font const & font, Change const & change)
1198 for (size_t i = 0, n = str.size(); i != n ; ++i)
1199 insertChar(start + i, str[i], font, change);
1203 void Paragraph::appendChar(char_type c, Font const & font,
1204 Change const & change)
1207 d->changes_.insert(change, d->text_.size());
1208 // when appending characters, no need to update tables
1209 d->text_.push_back(c);
1210 setFont(d->text_.size() - 1, font);
1214 void Paragraph::appendString(docstring const & s, Font const & font,
1215 Change const & change)
1217 size_t end = s.size();
1218 size_t oldsize = d->text_.size();
1219 size_t newsize = oldsize + end;
1220 size_t capacity = d->text_.capacity();
1221 if (newsize >= capacity)
1222 d->text_.reserve(std::max(capacity + 100, newsize));
1224 // when appending characters, no need to update tables
1227 // FIXME: Optimize this!
1228 for (pos_type i = 0; i != end; ++i) {
1230 d->changes_.insert(change, i);
1232 d->fontlist_.setRange(oldsize, newsize, font);
1236 void Paragraph::insertChar(pos_type pos, char_type c,
1239 d->insertChar(pos, c, Change(trackChanges ?
1240 Change::INSERTED : Change::UNCHANGED));
1244 void Paragraph::insertChar(pos_type pos, char_type c,
1245 Font const & font, bool trackChanges)
1247 d->insertChar(pos, c, Change(trackChanges ?
1248 Change::INSERTED : Change::UNCHANGED));
1253 void Paragraph::insertChar(pos_type pos, char_type c,
1254 Font const & font, Change const & change)
1256 d->insertChar(pos, c, change);
1261 void Paragraph::insertInset(pos_type pos, Inset * inset,
1262 Font const & font, Change const & change)
1264 insertInset(pos, inset, change);
1265 // Set the font/language of the inset...
1270 bool Paragraph::insetAllowed(InsetCode code)
1272 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1276 // Gets uninstantiated font setting at position.
1277 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1281 lyxerr << " pos: " << pos << " size: " << size() << endl;
1282 BOOST_ASSERT(pos <= size());
1285 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1286 if (cit != d->fontlist_.end())
1289 if (pos == size() && !empty())
1290 return getFontSettings(bparams, pos - 1);
1292 return Font(Font::ALL_INHERIT, getParLanguage(bparams));
1296 FontSpan Paragraph::fontSpan(pos_type pos) const
1298 BOOST_ASSERT(pos <= size());
1301 FontList::const_iterator cit = d->fontlist_.begin();
1302 FontList::const_iterator end = d->fontlist_.end();
1303 for (; cit != end; ++cit) {
1304 if (cit->pos() >= pos) {
1305 if (pos >= beginOfBody())
1306 return FontSpan(std::max(start, beginOfBody()),
1309 return FontSpan(start,
1310 std::min(beginOfBody() - 1,
1313 start = cit->pos() + 1;
1316 // This should not happen, but if so, we take no chances.
1317 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1319 return FontSpan(pos, pos);
1323 // Gets uninstantiated font setting at position 0
1324 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1326 if (!empty() && !d->fontlist_.empty())
1327 return d->fontlist_.begin()->font();
1329 return Font(Font::ALL_INHERIT, bparams.language);
1333 // Gets the fully instantiated font at a given position in a paragraph
1334 // This is basically the same function as Text::GetFont() in text2.cpp.
1335 // The difference is that this one is used for generating the LaTeX file,
1336 // and thus cosmetic "improvements" are disallowed: This has to deliver
1337 // the true picture of the buffer. (Asger)
1338 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1339 Font const & outerfont) const
1341 BOOST_ASSERT(pos >= 0);
1343 Font font = getFontSettings(bparams, pos);
1345 pos_type const body_pos = beginOfBody();
1347 font.realize(d->layout_->labelfont);
1349 font.realize(d->layout_->font);
1351 font.realize(outerfont);
1352 font.realize(bparams.getFont());
1358 Font const Paragraph::getLabelFont
1359 (BufferParams const & bparams, Font const & outerfont) const
1361 Font tmpfont = layout()->labelfont;
1362 tmpfont.setLanguage(getParLanguage(bparams));
1363 tmpfont.realize(outerfont);
1364 tmpfont.realize(bparams.getFont());
1369 Font const Paragraph::getLayoutFont
1370 (BufferParams const & bparams, Font const & outerfont) const
1372 Font tmpfont = layout()->font;
1373 tmpfont.setLanguage(getParLanguage(bparams));
1374 tmpfont.realize(outerfont);
1375 tmpfont.realize(bparams.getFont());
1380 /// Returns the height of the highest font in range
1381 Font_size Paragraph::highestFontInRange
1382 (pos_type startpos, pos_type endpos, Font_size def_size) const
1384 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1389 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1391 char_type c = d->text_[pos];
1392 if (!lyxrc.rtl_support)
1422 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1429 void Paragraph::setFont(pos_type pos, Font const & font)
1431 BOOST_ASSERT(pos <= size());
1433 // First, reduce font against layout/label font
1434 // Update: The setCharFont() routine in text2.cpp already
1435 // reduces font, so we don't need to do that here. (Asger)
1437 d->fontlist_.set(pos, font);
1441 void Paragraph::makeSameLayout(Paragraph const & par)
1443 layout(par.layout());
1445 d->params_ = par.params();
1449 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1451 if (isFreeSpacing())
1457 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1458 if (eraseChar(pos, trackChanges))
1464 return count > 0 || pos > 0;
1468 bool Paragraph::hasSameLayout(Paragraph const & par) const
1470 return par.layout() == layout() && d->params_.sameLayout(par.params());
1474 depth_type Paragraph::getDepth() const
1476 return params().depth();
1480 depth_type Paragraph::getMaxDepthAfter() const
1482 if (layout()->isEnvironment())
1483 return params().depth() + 1;
1485 return params().depth();
1489 char Paragraph::getAlign() const
1491 if (params().align() == LYX_ALIGN_LAYOUT)
1492 return layout()->align;
1494 return params().align();
1498 docstring const & Paragraph::getLabelstring() const
1500 return params().labelString();
1504 // the next two functions are for the manual labels
1505 docstring const Paragraph::getLabelWidthString() const
1507 if (layout()->margintype == MARGIN_MANUAL)
1508 return params().labelWidthString();
1510 return _("Senseless with this layout!");
1514 void Paragraph::setLabelWidthString(docstring const & s)
1516 params().labelWidthString(s);
1520 docstring const Paragraph::translateIfPossible(docstring const & s,
1521 BufferParams const & bparams) const
1523 if (!support::isAscii(s) || s.empty()) {
1524 // This must be a user defined layout. We cannot translate
1525 // this, since gettext accepts only ascii keys.
1528 // Probably standard layout, try to translate
1529 Messages & m = getMessages(getParLanguage(bparams)->code());
1530 return m.get(to_ascii(s));
1534 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1535 BufferParams const & bparams, bool process_appendix) const
1537 TextClass const & tclass = bparams.getTextClass();
1540 if (process_appendix && params().appendix())
1541 fmt = translateIfPossible(layout->labelstring_appendix(),
1544 fmt = translateIfPossible(layout->labelstring(), bparams);
1546 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1547 && !layout->counter.empty())
1548 fmt = "\\the" + layout->counter;
1550 // handle 'inherited level parts' in 'fmt',
1551 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1552 size_t const i = fmt.find('@', 0);
1553 if (i != docstring::npos) {
1554 size_t const j = fmt.find('@', i + 1);
1555 if (j != docstring::npos) {
1556 docstring parent(fmt, i + 1, j - i - 1);
1557 docstring label = from_ascii("??");
1558 if (tclass.hasLayout(parent))
1559 docstring label = expandLabel(tclass[parent], bparams,
1561 fmt = docstring(fmt, 0, i) + label
1562 + docstring(fmt, j + 1, docstring::npos);
1566 return tclass.counters().counterLabel(fmt);
1570 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1573 LyXAlignment const oldAlign = params().align();
1575 if (!(oldAlign & layout()->alignpossible)) {
1576 frontend::Alert::warning(_("Alignment not permitted"),
1577 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1578 params().align(LYX_ALIGN_LAYOUT);
1583 pos_type Paragraph::beginOfBody() const
1585 return d->begin_of_body_;
1589 void Paragraph::setBeginOfBody()
1591 if (layout()->labeltype != LABEL_MANUAL) {
1592 d->begin_of_body_ = 0;
1596 // Unroll the first two cycles of the loop
1597 // and remember the previous character to
1598 // remove unnecessary getChar() calls
1600 pos_type end = size();
1601 if (i < end && !isNewline(i)) {
1603 char_type previous_char = 0;
1606 previous_char = d->text_[i];
1607 if (!isNewline(i)) {
1609 while (i < end && previous_char != ' ') {
1614 previous_char = temp;
1620 d->begin_of_body_ = i;
1624 bool Paragraph::forceDefaultParagraphs() const
1626 return inInset() && inInset()->forceDefaultParagraphs(0);
1632 // paragraphs inside floats need different alignment tags to avoid
1635 bool noTrivlistCentering(InsetCode code)
1637 return code == FLOAT_CODE || code == WRAP_CODE;
1641 string correction(string const & orig)
1643 if (orig == "flushleft")
1644 return "raggedright";
1645 if (orig == "flushright")
1646 return "raggedleft";
1647 if (orig == "center")
1653 string const corrected_env(string const & suffix, string const & env,
1656 string output = suffix + "{";
1657 if (noTrivlistCentering(code))
1658 output += correction(env);
1662 if (suffix == "\\begin")
1668 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1670 if (!contains(str, "\n"))
1671 column += str.size();
1675 column = rsplit(str, tmp, '\n').size();
1682 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1683 odocstream & os, TexRow & texrow,
1684 bool moving_arg) const
1688 if (params_.noindent()) {
1689 os << "\\noindent ";
1693 LyXAlignment const curAlign = params_.align();
1695 if (curAlign == layout_->align)
1699 case LYX_ALIGN_NONE:
1700 case LYX_ALIGN_BLOCK:
1701 case LYX_ALIGN_LAYOUT:
1702 case LYX_ALIGN_SPECIAL:
1704 case LYX_ALIGN_LEFT:
1705 case LYX_ALIGN_RIGHT:
1706 case LYX_ALIGN_CENTER:
1715 case LYX_ALIGN_NONE:
1716 case LYX_ALIGN_BLOCK:
1717 case LYX_ALIGN_LAYOUT:
1718 case LYX_ALIGN_SPECIAL:
1720 case LYX_ALIGN_LEFT: {
1722 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1723 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1725 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1726 os << from_ascii(output);
1727 adjust_row_column(output, texrow, column);
1729 } case LYX_ALIGN_RIGHT: {
1731 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1732 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1734 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1735 os << from_ascii(output);
1736 adjust_row_column(output, texrow, column);
1738 } case LYX_ALIGN_CENTER: {
1740 output = corrected_env("\\begin", "center", owner_->ownerCode());
1741 os << from_ascii(output);
1742 adjust_row_column(output, texrow, column);
1751 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1752 odocstream & os, TexRow & texrow,
1753 bool moving_arg) const
1757 switch (params_.align()) {
1758 case LYX_ALIGN_NONE:
1759 case LYX_ALIGN_BLOCK:
1760 case LYX_ALIGN_LAYOUT:
1761 case LYX_ALIGN_SPECIAL:
1763 case LYX_ALIGN_LEFT:
1764 case LYX_ALIGN_RIGHT:
1765 case LYX_ALIGN_CENTER:
1773 switch (params_.align()) {
1774 case LYX_ALIGN_NONE:
1775 case LYX_ALIGN_BLOCK:
1776 case LYX_ALIGN_LAYOUT:
1777 case LYX_ALIGN_SPECIAL:
1779 case LYX_ALIGN_LEFT: {
1781 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1782 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1784 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1785 os << from_ascii(output);
1786 adjust_row_column(output, texrow, column);
1788 } case LYX_ALIGN_RIGHT: {
1790 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1791 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1793 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1794 os << from_ascii(output);
1795 adjust_row_column(output, texrow, column);
1797 } case LYX_ALIGN_CENTER: {
1799 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1800 os << from_ascii(output);
1801 adjust_row_column(output, texrow, column);
1810 // This one spits out the text of the paragraph
1811 bool Paragraph::latex(Buffer const & buf,
1812 BufferParams const & bparams,
1813 Font const & outerfont,
1814 odocstream & os, TexRow & texrow,
1815 OutputParams const & runparams) const
1817 LYXERR(Debug::LATEX) << "SimpleTeXOnePar... " << this << endl;
1819 bool return_value = false;
1823 // well we have to check if we are in an inset with unlimited
1824 // length (all in one row) if that is true then we don't allow
1825 // any special options in the paragraph and also we don't allow
1826 // any environment other than the default layout of the text class
1828 bool asdefault = forceDefaultParagraphs();
1831 style = bparams.getTextClass().defaultLayout();
1836 // Current base font for all inherited font changes, without any
1837 // change caused by an individual character, except for the language:
1838 // It is set to the language of the first character.
1839 // As long as we are in the label, this font is the base font of the
1840 // label. Before the first body character it is set to the base font
1844 // Maybe we have to create a optional argument.
1845 pos_type body_pos = beginOfBody();
1846 unsigned int column = 0;
1849 // the optional argument is kept in curly brackets in
1850 // case it contains a ']'
1853 basefont = getLabelFont(bparams, outerfont);
1855 basefont = getLayoutFont(bparams, outerfont);
1858 // Which font is currently active?
1859 Font running_font(basefont);
1860 // Do we have an open font change?
1861 bool open_font = false;
1863 Change runningChange = Change(Change::UNCHANGED);
1865 texrow.start(id(), 0);
1867 // if the paragraph is empty, the loop will not be entered at all
1869 if (style->isCommand()) {
1874 column += d->startTeXParParams(bparams, os, texrow,
1875 runparams.moving_arg);
1878 for (pos_type i = 0; i < size(); ++i) {
1879 // First char in paragraph or after label?
1880 if (i == body_pos) {
1883 column += running_font.latexWriteEndChanges(
1884 os, bparams, runparams,
1885 basefont, basefont);
1888 basefont = getLayoutFont(bparams, outerfont);
1889 running_font = basefont;
1891 column += Changes::latexMarkChange(os, bparams,
1892 runningChange, Change(Change::UNCHANGED));
1893 runningChange = Change(Change::UNCHANGED);
1898 if (style->isCommand()) {
1904 column += d->startTeXParParams(bparams, os,
1906 runparams.moving_arg);
1909 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1912 if (bparams.outputChanges && runningChange != change) {
1914 column += running_font.latexWriteEndChanges(
1915 os, bparams, runparams, basefont, basefont);
1918 basefont = getLayoutFont(bparams, outerfont);
1919 running_font = basefont;
1921 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1922 runningChange = change;
1925 // do not output text which is marked deleted
1926 // if change tracking output is disabled
1927 if (!bparams.outputChanges && change.type == Change::DELETED) {
1933 // Fully instantiated font
1934 Font const font = getFont(bparams, i, outerfont);
1936 Font const last_font = running_font;
1938 // Do we need to close the previous font?
1940 (font != running_font ||
1941 font.language() != running_font.language()))
1943 column += running_font.latexWriteEndChanges(
1944 os, bparams, runparams, basefont,
1945 (i == body_pos-1) ? basefont : font);
1946 running_font = basefont;
1950 // Switch file encoding if necessary (and allowed)
1951 if (!runparams.verbatim &&
1952 runparams.encoding->package() == Encoding::inputenc &&
1953 font.language()->encoding()->package() == Encoding::inputenc) {
1954 std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1955 runparams.moving_arg, *(runparams.encoding),
1956 *(font.language()->encoding()));
1957 if (enc_switch.first) {
1958 column += enc_switch.second;
1959 runparams.encoding = font.language()->encoding();
1963 char_type const c = d->text_[i];
1965 // Do we need to change font?
1966 if ((font != running_font ||
1967 font.language() != running_font.language()) &&
1970 odocstringstream ods;
1971 column += font.latexWriteStartChanges(ods, bparams,
1972 runparams, basefont,
1974 running_font = font;
1976 docstring fontchange = ods.str();
1977 // check if the fontchange ends with a trailing blank
1978 // (like "\small " (see bug 3382)
1979 if (suffixIs(fontchange, ' ') && c == ' ')
1980 os << fontchange.substr(0, fontchange.size() - 1)
1981 << from_ascii("{}");
1987 // FIXME: integrate this case in latexSpecialChar
1988 // Do not print the separation of the optional argument
1989 // if style->pass_thru is false. This works because
1990 // latexSpecialChar ignores spaces if
1991 // style->pass_thru is false.
1992 if (i != body_pos - 1) {
1993 if (d->simpleTeXBlanks(
1994 *(runparams.encoding), os, texrow,
1995 i, column, font, *style)) {
1996 // A surrogate pair was output. We
1997 // must not call latexSpecialChar
1998 // in this iteration, since it would output
1999 // the combining character again.
2006 OutputParams rp = runparams;
2007 rp.free_spacing = style->free_spacing;
2008 rp.local_font = &font;
2009 rp.intitle = style->intitle;
2011 // Two major modes: LaTeX or plain
2012 // Handle here those cases common to both modes
2013 // and then split to handle the two modes separately.
2014 if (c == META_INSET)
2015 d->latexInset(buf, bparams, os,
2016 texrow, rp, running_font,
2017 basefont, outerfont, open_font,
2018 runningChange, *style, i, column);
2020 d->latexSpecialChar(os, rp, running_font, runningChange,
2023 // Set the encoding to that returned from simpleTeXSpecialChars (see
2024 // comment for encoding member in OutputParams.h)
2025 runparams.encoding = rp.encoding;
2028 // If we have an open font definition, we have to close it
2030 #ifdef FIXED_LANGUAGE_END_DETECTION
2033 .latexWriteEndChanges(os, bparams, runparams,
2035 next_->getFont(bparams, 0, outerfont));
2037 running_font.latexWriteEndChanges(os, bparams,
2038 runparams, basefont, basefont);
2041 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2042 //FIXME: there as we start another \selectlanguage with the next paragraph if
2043 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2044 running_font.latexWriteEndChanges(os, bparams, runparams,
2045 basefont, basefont);
2049 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2051 // Needed if there is an optional argument but no contents.
2052 if (body_pos > 0 && body_pos == size()) {
2054 return_value = false;
2058 column += d->endTeXParParams(bparams, os, texrow,
2059 runparams.moving_arg);
2062 LYXERR(Debug::LATEX) << "SimpleTeXOnePar...done " << this << endl;
2063 return return_value;
2067 bool Paragraph::emptyTag() const
2069 for (pos_type i = 0; i < size(); ++i) {
2071 Inset const * inset = getInset(i);
2072 InsetCode lyx_code = inset->lyxCode();
2073 if (lyx_code != TOC_CODE &&
2074 lyx_code != INCLUDE_CODE &&
2075 lyx_code != GRAPHICS_CODE &&
2076 lyx_code != ERT_CODE &&
2077 lyx_code != LISTINGS_CODE &&
2078 lyx_code != FLOAT_CODE &&
2079 lyx_code != TABULAR_CODE) {
2083 char_type c = d->text_[i];
2084 if (c != ' ' && c != '\t')
2092 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2094 for (pos_type i = 0; i < size(); ++i) {
2096 Inset const * inset = getInset(i);
2097 InsetCode lyx_code = inset->lyxCode();
2098 if (lyx_code == LABEL_CODE) {
2099 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2100 docstring const & id = il->getParam("name");
2101 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2110 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2113 for (i = 0; i < size(); ++i) {
2115 Inset const * inset = getInset(i);
2116 inset->docbook(buf, os, runparams);
2118 char_type c = d->text_[i];
2121 os << sgml::escapeChar(c);
2128 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2131 pos_type size = text_.size();
2132 for (pos_type i = initial; i < size; ++i) {
2133 Font font = owner_->getFont(buf.params(), i, outerfont);
2134 if (text_[i] == META_INSET)
2136 if (i != initial && font != font_old)
2145 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2147 OutputParams const & runparams,
2148 Font const & outerfont,
2149 pos_type initial) const
2151 bool emph_flag = false;
2153 LayoutPtr const & style = layout();
2155 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2157 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2160 // parsing main loop
2161 for (pos_type i = initial; i < size(); ++i) {
2162 Font font = getFont(buf.params(), i, outerfont);
2164 // handle <emphasis> tag
2165 if (font_old.emph() != font.emph()) {
2166 if (font.emph() == Font::ON) {
2169 } else if (i != initial) {
2170 os << "</emphasis>";
2176 Inset const * inset = getInset(i);
2177 inset->docbook(buf, os, runparams);
2179 char_type c = d->text_[i];
2181 if (style->pass_thru)
2184 os << sgml::escapeChar(c);
2190 os << "</emphasis>";
2193 if (style->free_spacing)
2195 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2200 bool Paragraph::isHfill(pos_type pos) const
2203 && getInset(pos)->lyxCode() == HFILL_CODE;
2207 bool Paragraph::isNewline(pos_type pos) const
2210 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2214 bool Paragraph::isLineSeparator(pos_type pos) const
2216 char_type const c = d->text_[pos];
2217 return isLineSeparatorChar(c)
2218 || (c == META_INSET && getInset(pos) &&
2219 getInset(pos)->isLineSeparator());
2223 /// Used by the spellchecker
2224 bool Paragraph::isLetter(pos_type pos) const
2227 return getInset(pos)->isLetter();
2229 char_type const c = d->text_[pos];
2230 return isLetterChar(c) || isDigit(c);
2236 Paragraph::getParLanguage(BufferParams const & bparams) const
2239 return getFirstFontSettings(bparams).language();
2240 // FIXME: we should check the prev par as well (Lgb)
2241 return bparams.language;
2245 bool Paragraph::isRTL(BufferParams const & bparams) const
2247 return lyxrc.rtl_support
2248 && getParLanguage(bparams)->rightToLeft()
2249 && ownerCode() != ERT_CODE
2250 && ownerCode() != LISTINGS_CODE;
2254 void Paragraph::changeLanguage(BufferParams const & bparams,
2255 Language const * from, Language const * to)
2257 // change language including dummy font change at the end
2258 for (pos_type i = 0; i <= size(); ++i) {
2259 Font font = getFontSettings(bparams, i);
2260 if (font.language() == from) {
2261 font.setLanguage(to);
2268 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2270 Language const * doc_language = bparams.language;
2271 FontList::const_iterator cit = d->fontlist_.begin();
2272 FontList::const_iterator end = d->fontlist_.end();
2274 for (; cit != end; ++cit)
2275 if (cit->font().language() != ignore_language &&
2276 cit->font().language() != latex_language &&
2277 cit->font().language() != doc_language)
2283 // Convert the paragraph to a string.
2284 // Used for building the table of contents
2285 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2287 return asString(buffer, 0, size(), label);
2291 docstring const Paragraph::asString(Buffer const & buffer,
2292 pos_type beg, pos_type end, bool label) const
2295 odocstringstream os;
2297 if (beg == 0 && label && !params().labelString().empty())
2298 os << params().labelString() << ' ';
2300 for (pos_type i = beg; i < end; ++i) {
2301 char_type const c = d->text_[i];
2304 else if (c == META_INSET)
2305 getInset(i)->textString(buffer, os);
2312 void Paragraph::setInsetOwner(Inset * inset)
2314 d->inset_owner_ = inset;
2318 int Paragraph::id() const
2324 LayoutPtr const & Paragraph::layout() const
2330 void Paragraph::layout(LayoutPtr const & new_layout)
2332 d->layout_ = new_layout;
2336 Inset * Paragraph::inInset() const
2338 return d->inset_owner_;
2342 InsetCode Paragraph::ownerCode() const
2344 return d->inset_owner_ ?
2345 d->inset_owner_->lyxCode() : NO_CODE;
2349 ParagraphParameters & Paragraph::params()
2355 ParagraphParameters const & Paragraph::params() const
2361 bool Paragraph::isFreeSpacing() const
2363 if (layout()->free_spacing)
2365 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2369 bool Paragraph::allowEmpty() const
2371 if (layout()->keepempty)
2373 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2377 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2379 if (!Encodings::is_arabic(c))
2382 char_type prev_char = ' ';
2383 char_type next_char = ' ';
2385 for (pos_type i = pos - 1; i >= 0; --i) {
2386 char_type const par_char = d->text_[i];
2387 if (!Encodings::isComposeChar_arabic(par_char)) {
2388 prev_char = par_char;
2393 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2394 char_type const par_char = d->text_[i];
2395 if (!Encodings::isComposeChar_arabic(par_char)) {
2396 next_char = par_char;
2401 if (Encodings::is_arabic(next_char)) {
2402 if (Encodings::is_arabic(prev_char) &&
2403 !Encodings::is_arabic_special(prev_char))
2404 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2406 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2408 if (Encodings::is_arabic(prev_char) &&
2409 !Encodings::is_arabic_special(prev_char))
2410 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2412 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2417 int Paragraph::checkBiblio(bool track_changes)
2420 //This is getting more and more a mess. ...We really should clean
2421 //up this bibitem issue for 1.6. See also bug 2743.
2423 // Add bibitem insets if necessary
2424 if (layout()->labeltype != LABEL_BIBLIO)
2427 bool hasbibitem = !d->insetlist_.empty()
2428 // Insist on it being in pos 0
2429 && d->text_[0] == META_INSET
2430 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2435 // remove a bibitem in pos != 0
2436 // restore it later in pos 0 if necessary
2437 // (e.g. if a user inserts contents _before_ the item)
2438 // we're assuming there's only one of these, which there
2440 int erasedInsetPosition = -1;
2441 InsetList::iterator it = d->insetlist_.begin();
2442 InsetList::iterator end = d->insetlist_.end();
2443 for (; it != end; ++it)
2444 if (it->inset->lyxCode() == BIBITEM_CODE
2446 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2447 oldkey = olditem->getParam("key");
2448 oldlabel = olditem->getParam("label");
2449 erasedInsetPosition = it->pos;
2450 eraseChar(erasedInsetPosition, track_changes);
2454 //There was an InsetBibitem at the beginning, and we didn't
2455 //have to erase one.
2456 if (hasbibitem && erasedInsetPosition < 0)
2459 //There was an InsetBibitem at the beginning and we did have to
2460 //erase one. So we give its properties to the beginning inset.
2462 InsetBibitem * inset =
2463 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2464 if (!oldkey.empty())
2465 inset->setParam("key", oldkey);
2466 inset->setParam("label", oldlabel);
2467 return -erasedInsetPosition;
2470 //There was no inset at the beginning, so we need to create one with
2471 //the key and label of the one we erased.
2472 InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2473 // restore values of previously deleted item in this par.
2474 if (!oldkey.empty())
2475 inset->setParam("key", oldkey);
2476 inset->setParam("label", oldlabel);
2477 insertInset(0, static_cast<Inset *>(inset),
2478 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2484 void Paragraph::checkAuthors(AuthorList const & authorList)
2486 d->changes_.checkAuthors(authorList);
2490 bool Paragraph::isUnchanged(pos_type pos) const
2492 return lookupChange(pos).type == Change::UNCHANGED;
2496 bool Paragraph::isInserted(pos_type pos) const
2498 return lookupChange(pos).type == Change::INSERTED;
2502 bool Paragraph::isDeleted(pos_type pos) const
2504 return lookupChange(pos).type == Change::DELETED;
2508 InsetList const & Paragraph::insetList() const
2510 return d->insetlist_;
2514 Inset * Paragraph::releaseInset(pos_type pos)
2516 Inset * inset = d->insetlist_.release(pos);
2517 /// does not honour change tracking!
2518 eraseChar(pos, false);
2523 Inset * Paragraph::getInset(pos_type pos)
2525 return d->insetlist_.get(pos);
2529 Inset const * Paragraph::getInset(pos_type pos) const
2531 return d->insetlist_.get(pos);
2535 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2536 pos_type right, TextCase action)
2538 // process sequences of modified characters; in change
2539 // tracking mode, this approach results in much better
2540 // usability than changing case on a char-by-char basis
2543 bool const trackChanges = bparams.trackChanges;
2545 bool capitalize = true;
2547 for (; pos < right; ++pos) {
2548 char_type oldChar = d->text_[pos];
2549 char_type newChar = oldChar;
2551 // ignore insets and don't play with deleted text!
2552 if (oldChar != META_INSET && !isDeleted(pos)) {
2554 case text_lowercase:
2555 newChar = lowercase(oldChar);
2557 case text_capitalization:
2559 newChar = uppercase(oldChar);
2563 case text_uppercase:
2564 newChar = uppercase(oldChar);
2569 if (!isLetter(pos) || isDeleted(pos)) {
2570 // permit capitalization again
2574 if (oldChar != newChar)
2577 if (oldChar == newChar || pos == right - 1) {
2578 if (oldChar != newChar) {
2579 // step behind the changing area
2582 int erasePos = pos - changes.size();
2583 for (size_t i = 0; i < changes.size(); i++) {
2584 insertChar(pos, changes[i],
2585 getFontSettings(bparams,
2588 if (!eraseChar(erasePos, trackChanges)) {
2591 ++right; // expand selection
2600 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2601 pos_type pos, bool del) const
2603 int const strsize = str.length();
2605 pos_type const parsize = d->text_.size();
2606 for (i = 0; pos + i < parsize; ++i) {
2609 if (cs && str[i] != d->text_[pos + i])
2611 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2613 if (!del && isDeleted(pos + i))
2620 // if necessary, check whether string matches word
2622 if (pos > 0 && isLetter(pos - 1))
2624 if (pos + strsize < parsize
2625 && isLetter(pos + strsize))
2633 char_type Paragraph::getChar(pos_type pos) const
2635 return d->text_[pos];
2639 pos_type Paragraph::size() const
2641 return d->text_.size();
2645 bool Paragraph::empty() const
2647 return d->text_.empty();
2651 bool Paragraph::isInset(pos_type pos) const
2653 return d->text_[pos] == META_INSET;
2657 bool Paragraph::isSeparator(pos_type pos) const
2659 //FIXME: Are we sure this can be the only separator?
2660 return d->text_[pos] == ' ';