3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
22 #include "BaseClassList.h"
24 #include "BufferParams.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
41 #include "TextClass.h"
47 #include "frontends/alert.h"
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
52 #include "support/convert.h"
53 #include "support/debug.h"
54 #include "support/gettext.h"
55 #include "support/lstrings.h"
56 #include "support/Messages.h"
57 #include "support/textutils.h"
63 using namespace lyx::support;
68 /// Inset identifier (above 0x10ffff, for ucs-4)
69 char_type const META_INSET = 0x200001;
72 /////////////////////////////////////////////////////////////////////
76 /////////////////////////////////////////////////////////////////////
78 class Paragraph::Private
82 Private(Paragraph * owner, Layout const & layout);
83 /// "Copy constructor"
84 Private(Private const &, Paragraph * owner);
87 void insertChar(pos_type pos, char_type c, Change const & change);
89 /// Output the surrogate pair formed by \p c and \p next to \p os.
90 /// \return the number of characters written.
91 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
94 /// Output a space in appropriate formatting (or a surrogate pair
95 /// if the next character is a combining character).
96 /// \return whether a surrogate pair was output.
97 bool simpleTeXBlanks(OutputParams const &,
98 odocstream &, TexRow & texrow,
100 unsigned int & column,
102 Layout const & style);
104 /// Output consecutive unicode chars, belonging to the same script as
105 /// specified by the latex macro \p ltx, to \p os starting from \p i.
106 /// \return the number of characters written.
107 int writeScriptChars(odocstream & os, docstring const & ltx,
108 Change &, Encoding const &, pos_type & i);
110 /// This could go to ParagraphParameters if we want to.
111 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
114 /// This could go to ParagraphParameters if we want to.
115 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
119 void latexInset(BufferParams const &,
121 TexRow & texrow, OutputParams &,
124 Font const & outerfont,
126 Change & running_change,
127 Layout const & style,
129 unsigned int & column);
132 void latexSpecialChar(
134 OutputParams & runparams,
136 Change & running_change,
137 Layout const & style,
139 unsigned int & column);
146 unsigned int & column);
148 bool latexSpecialTypewriter(
152 unsigned int & column);
154 bool latexSpecialPhrase(
157 unsigned int & column,
158 OutputParams & runparams);
161 void validate(LaTeXFeatures & features,
162 Layout const & layout) const;
164 /// Checks if the paragraph contains only text and no inset or font change.
165 bool onlyText(Buffer const & buf, Font const & outerfont,
166 pos_type initial) const;
168 /// match a string against a particular point in the paragraph
169 bool isTextAt(string const & str, pos_type pos) const;
171 /// Which Paragraph owns us?
175 Inset * inset_owner_;
183 static unsigned int paragraph_id;
185 ParagraphParameters params_;
187 /// for recording and looking up changes
191 InsetList insetlist_;
193 // This little bit of indirection is needed so that we can protect
194 // the layout as const but still be able to change layout_.
196 Layout const & layout() const { return *layout_; }
198 void setLayout(Layout const & layout) { layout_ = &layout; }
201 pos_type begin_of_body_;
203 typedef docstring TextContainer;
207 typedef std::set<docstring> Words;
212 Layout const * layout_;
216 // Initialization of the counter for the paragraph id's,
217 unsigned int Paragraph::Private::paragraph_id = 0;
221 struct special_phrase {
227 special_phrase const special_phrases[] = {
228 { "LyX", from_ascii("\\LyX{}"), false },
229 { "TeX", from_ascii("\\TeX{}"), true },
230 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
231 { "LaTeX", from_ascii("\\LaTeX{}"), true },
234 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
239 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
240 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
242 id_ = paragraph_id++;
247 Paragraph::Private::Private(Private const & p, Paragraph * owner)
248 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
249 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
250 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
253 id_ = paragraph_id++;
257 bool Paragraph::isChanged(pos_type start, pos_type end) const
259 BOOST_ASSERT(start >= 0 && start <= size());
260 BOOST_ASSERT(end > start && end <= size() + 1);
262 return d->changes_.isChanged(start, end);
266 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
268 // keep the logic here in sync with the logic of eraseChars()
272 Change const change = d->changes_.lookup(size());
273 return change.type == Change::INSERTED && change.author == 0;
277 void Paragraph::setChange(Change const & change)
279 // beware of the imaginary end-of-par character!
280 d->changes_.set(change, 0, size() + 1);
283 * Propagate the change recursively - but not in case of DELETED!
285 * Imagine that your co-author makes changes in an existing inset. He
286 * sends your document to you and you come to the conclusion that the
287 * inset should go completely. If you erase it, LyX must not delete all
288 * text within the inset. Otherwise, the change tracked insertions of
289 * your co-author get lost and there is no way to restore them later.
291 * Conclusion: An inset's content should remain untouched if you delete it
294 if (change.type != Change::DELETED) {
295 for (pos_type pos = 0; pos < size(); ++pos) {
296 if (Inset * inset = getInset(pos))
297 inset->setChange(change);
303 void Paragraph::setChange(pos_type pos, Change const & change)
305 BOOST_ASSERT(pos >= 0 && pos <= size());
306 d->changes_.set(change, pos);
308 // see comment in setChange(Change const &) above
309 if (change.type != Change::DELETED && pos < size())
310 if (Inset * inset = getInset(pos))
311 inset->setChange(change);
315 Change const & Paragraph::lookupChange(pos_type pos) const
317 BOOST_ASSERT(pos >= 0 && pos <= size());
318 return d->changes_.lookup(pos);
322 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
325 BOOST_ASSERT(start >= 0 && start <= size());
326 BOOST_ASSERT(end > start && end <= size() + 1);
328 for (pos_type pos = start; pos < end; ++pos) {
329 switch (lookupChange(pos).type) {
330 case Change::UNCHANGED:
331 // accept changes in nested inset
332 if (Inset * inset = getInset(pos))
333 inset->acceptChanges(bparams);
336 case Change::INSERTED:
337 d->changes_.set(Change(Change::UNCHANGED), pos);
338 // also accept changes in nested inset
339 if (Inset * inset = getInset(pos))
340 inset->acceptChanges(bparams);
343 case Change::DELETED:
344 // Suppress access to non-existent
345 // "end-of-paragraph char"
347 eraseChar(pos, false);
358 void Paragraph::rejectChanges(BufferParams const & bparams,
359 pos_type start, pos_type end)
361 BOOST_ASSERT(start >= 0 && start <= size());
362 BOOST_ASSERT(end > start && end <= size() + 1);
364 for (pos_type pos = start; pos < end; ++pos) {
365 switch (lookupChange(pos).type) {
366 case Change::UNCHANGED:
367 // reject changes in nested inset
368 if (Inset * inset = getInset(pos))
369 inset->rejectChanges(bparams);
372 case Change::INSERTED:
373 // Suppress access to non-existent
374 // "end-of-paragraph char"
376 eraseChar(pos, false);
382 case Change::DELETED:
383 d->changes_.set(Change(Change::UNCHANGED), pos);
385 // Do NOT reject changes within a deleted inset!
386 // There may be insertions of a co-author inside of it!
394 void Paragraph::Private::insertChar(pos_type pos, char_type c,
395 Change const & change)
397 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
400 changes_.insert(change, pos);
402 // This is actually very common when parsing buffers (and
403 // maybe inserting ascii text)
404 if (pos == pos_type(text_.size())) {
405 // when appending characters, no need to update tables
410 text_.insert(text_.begin() + pos, c);
412 // Update the font table.
413 fontlist_.increasePosAfterPos(pos);
416 insetlist_.increasePosAfterPos(pos);
420 void Paragraph::insertInset(pos_type pos, Inset * inset,
421 Change const & change)
424 BOOST_ASSERT(pos >= 0 && pos <= size());
426 d->insertChar(pos, META_INSET, change);
427 BOOST_ASSERT(d->text_[pos] == META_INSET);
429 // Add a new entry in the insetlist_.
430 d->insetlist_.insert(inset, pos);
434 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
436 BOOST_ASSERT(pos >= 0 && pos <= size());
438 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
441 Change change = d->changes_.lookup(pos);
443 // set the character to DELETED if
444 // a) it was previously unchanged or
445 // b) it was inserted by a co-author
447 if (change.type == Change::UNCHANGED ||
448 (change.type == Change::INSERTED && change.author != 0)) {
449 setChange(pos, Change(Change::DELETED));
453 if (change.type == Change::DELETED)
457 // Don't physically access the imaginary end-of-paragraph character.
458 // eraseChar() can only mark it as DELETED. A physical deletion of
459 // end-of-par must be handled externally.
465 d->changes_.erase(pos);
467 // if it is an inset, delete the inset entry
468 if (d->text_[pos] == META_INSET)
469 d->insetlist_.erase(pos);
471 d->text_.erase(d->text_.begin() + pos);
473 // Update the fontlist_
474 d->fontlist_.erase(pos);
476 // Update the insetlist_
477 d->insetlist_.decreasePosAfterPos(pos);
483 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
485 BOOST_ASSERT(start >= 0 && start <= size());
486 BOOST_ASSERT(end >= start && end <= size() + 1);
489 for (pos_type count = end - start; count; --count) {
490 if (!eraseChar(i, trackChanges))
497 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
498 char_type next, Encoding const & encoding)
500 // Writing next here may circumvent a possible font change between
501 // c and next. Since next is only output if it forms a surrogate pair
502 // with c we can ignore this:
503 // A font change inside a surrogate pair does not make sense and is
504 // hopefully impossible to input.
505 // FIXME: change tracking
506 // Is this correct WRT change tracking?
507 docstring const latex1 = encoding.latexChar(next);
508 docstring const latex2 = encoding.latexChar(c);
509 os << latex1 << '{' << latex2 << '}';
510 return latex1.length() + latex2.length() + 2;
514 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
515 odocstream & os, TexRow & texrow,
517 unsigned int & column,
519 Layout const & style)
521 if (style.pass_thru || runparams.verbatim)
524 if (i + 1 < int(text_.size())) {
525 char_type next = text_[i + 1];
526 if (Encodings::isCombiningChar(next)) {
527 Encoding const & encoding = *(runparams.encoding);
528 // This space has an accent, so we must always output it.
529 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
534 if (lyxrc.plaintext_linelen > 0
535 && column > lyxrc.plaintext_linelen
537 && text_[i - 1] != ' '
538 && (i + 1 < int(text_.size()))
539 // same in FreeSpacing mode
540 && !owner_->isFreeSpacing()
541 // In typewriter mode, we want to avoid
542 // ! . ? : at the end of a line
543 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
544 && (text_[i - 1] == '.'
545 || text_[i - 1] == '?'
546 || text_[i - 1] == ':'
547 || text_[i - 1] == '!'))) {
550 texrow.start(owner_->id(), i + 1);
552 } else if (style.free_spacing) {
561 int Paragraph::Private::writeScriptChars(odocstream & os,
562 docstring const & ltx,
563 Change & runningChange,
564 Encoding const & encoding,
567 // FIXME: modifying i here is not very nice...
569 // We only arrive here when a proper language for character text_[i] has
570 // not been specified (i.e., it could not be translated in the current
571 // latex encoding) and it belongs to a known script.
572 // Parameter ltx contains the latex translation of text_[i] as specified in
573 // the unicodesymbols file and is something like "\textXXX{<spec>}".
574 // The latex macro name "textXXX" specifies the script to which text_[i]
575 // belongs and we use it in order to check whether characters from the
576 // same script immediately follow, such that we can collect them in a
577 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
578 // for the first char but only "<spec>" for all subsequent chars.
579 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
580 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
581 string script = to_ascii(ltx.substr(1, brace1 - 1));
582 int length = ltx.substr(0, brace2).length();
583 os << ltx.substr(0, brace2);
584 int size = text_.size();
585 while (i + 1 < size) {
586 char_type const next = text_[i + 1];
587 // Stop here if next character belongs to another script
588 // or there is a change in change tracking status.
589 if (!Encodings::isKnownScriptChar(next, script) ||
590 runningChange != owner_->lookupChange(i + 1))
594 FontList::const_iterator cit = fontlist_.begin();
595 FontList::const_iterator end = fontlist_.end();
596 for (; cit != end; ++cit) {
597 if (cit->pos() >= i && !found) {
598 prev_font = cit->font();
601 if (cit->pos() >= i + 1)
604 // Stop here if there is a font attribute or encoding change.
605 if (found && cit != end && prev_font != cit->font())
607 docstring const latex = encoding.latexChar(next);
608 docstring::size_type const b1 =
609 latex.find_first_of(from_ascii("{"));
610 docstring::size_type const b2 =
611 latex.find_last_of(from_ascii("}"));
612 int const len = b2 - b1 - 1;
613 os << latex.substr(b1 + 1, len);
623 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
625 pos_type const len = str.length();
627 // is the paragraph large enough?
628 if (pos + len > int(text_.size()))
631 // does the wanted text start at point?
632 for (string::size_type i = 0; i < str.length(); ++i) {
633 // Caution: direct comparison of characters works only
634 // because str is pure ASCII.
635 if (str[i] != text_[pos + i])
639 return fontlist_.hasChangeInRange(pos, len);
643 void Paragraph::Private::latexInset(
644 BufferParams const & bparams,
647 OutputParams & runparams,
650 Font const & outerfont,
652 Change & running_change,
653 Layout const & style,
655 unsigned int & column)
657 Inset * inset = owner_->getInset(i);
660 if (style.pass_thru) {
661 inset->plaintext(os, runparams);
665 // FIXME: move this to InsetNewline::latex
666 if (inset->lyxCode() == NEWLINE_CODE) {
667 // newlines are handled differently here than
668 // the default in simpleTeXSpecialChars().
669 if (!style.newline_allowed) {
673 column += running_font.latexWriteEndChanges(
674 os, bparams, runparams,
679 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
682 basefont = owner_->getLayoutFont(bparams, outerfont);
683 running_font = basefont;
685 if (runparams.moving_arg)
690 texrow.start(owner_->id(), i + 1);
694 if (owner_->lookupChange(i).type == Change::DELETED) {
695 if( ++runparams.inDeletedInset == 1)
696 runparams.changeOfDeletedInset = owner_->lookupChange(i);
699 if (inset->canTrackChanges()) {
700 column += Changes::latexMarkChange(os, bparams, running_change,
701 Change(Change::UNCHANGED));
702 running_change = Change(Change::UNCHANGED);
706 odocstream::pos_type const len = os.tellp();
708 if (inset->forceLTR()
709 && running_font.isRightToLeft()
710 // ERT is an exception, it should be output with no decorations at all
711 && inset->lyxCode() != ERT_CODE) {
712 if (running_font.language()->lang() == "farsi")
719 // FIXME: Bug: we can have an empty font change here!
720 // if there has just been a font change, we are going to close it
721 // right now, which means stupid latex code like \textsf{}. AFAIK,
722 // this does not harm dvi output. A minor bug, thus (JMarc)
724 // Some insets cannot be inside a font change command.
725 // However, even such insets *can* be placed in \L or \R
726 // or their equivalents (for RTL language switches), so we don't
727 // close the language in those cases.
728 // ArabTeX, though, cannot handle this special behavior, it seems.
729 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
730 || running_font.language()->lang() == "arabic_arabtex";
731 if (open_font && inset->noFontChange()) {
732 bool closeLanguage = arabtex
733 || basefont.isRightToLeft() == running_font.isRightToLeft();
734 unsigned int count = running_font.latexWriteEndChanges(os,
735 bparams, runparams, basefont, basefont, closeLanguage);
737 // if any font properties were closed, update the running_font,
738 // making sure, however, to leave the language as it was
740 // FIXME: probably a better way to keep track of the old
741 // language, than copying the entire font?
742 Font const copy_font(running_font);
743 basefont = owner_->getLayoutFont(bparams, outerfont);
744 running_font = basefont;
746 running_font.setLanguage(copy_font.language());
747 // leave font open if language is still open
748 open_font = (running_font.language() == basefont.language());
750 runparams.local_font = &basefont;
754 int tmp = inset->latex(os, runparams);
757 if (running_font.language()->lang() == "farsi")
764 for (int j = 0; j < tmp; ++j)
767 texrow.start(owner_->id(), i + 1);
770 column += os.tellp() - len;
773 if (owner_->lookupChange(i).type == Change::DELETED)
774 --runparams.inDeletedInset;
778 void Paragraph::Private::latexSpecialChar(
780 OutputParams & runparams,
782 Change & running_change,
783 Layout const & style,
785 unsigned int & column)
787 char_type const c = text_[i];
789 if (style.pass_thru) {
791 // FIXME UNICODE: This can fail if c cannot
792 // be encoded in the current encoding.
797 if (runparams.verbatim) {
802 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
805 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
806 && latexSpecialTypewriter(c, os, i, column))
809 // Otherwise, we use what LaTeX provides us.
812 os << "\\textbackslash{}";
816 os << "\\textless{}";
820 os << "\\textgreater{}";
831 os << "\\char`\\\"{}";
836 case '%': case '#': case '{':
844 os << "\\textasciitilde{}";
849 os << "\\textasciicircum{}";
854 // avoid being mistaken for optional arguments
862 // Blanks are printed before font switching.
863 // Sure? I am not! (try nice-latex)
864 // I am sure it's correct. LyX might be smarter
865 // in the future, but for now, nothing wrong is
872 if (latexSpecialPhrase(os, i, column, runparams))
878 Encoding const & encoding = *(runparams.encoding);
879 if (i + 1 < int(text_.size())) {
880 char_type next = text_[i + 1];
881 if (Encodings::isCombiningChar(next)) {
882 column += latexSurrogatePair(os, c, next, encoding) - 1;
888 docstring const latex = encoding.latexChar(c);
889 if (Encodings::isKnownScriptChar(c, script)
890 && prefixIs(latex, from_ascii("\\" + script)))
891 column += writeScriptChars(os, latex,
892 running_change, encoding, i) - 1;
893 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
894 // Prevent eating of a following
895 // space or command corruption by
896 // following characters
897 column += latex.length() + 1;
900 column += latex.length() - 1;
908 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
909 pos_type & i, unsigned int & column)
915 // In T1 encoding, these characters exist
916 // but we should avoid ligatures
917 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
922 //os << "\\textcompwordmark{}";
934 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
935 pos_type & i, unsigned int & column)
939 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
940 // "--" in Typewriter mode -> "-{}-"
947 // I assume this is hack treating typewriter as verbatim
948 // FIXME UNICODE: This can fail if c cannot be encoded
949 // in the current encoding.
954 // Those characters are not directly supported.
958 case '%': case '#': case '{':
967 // With Typewriter font, these characters exist.
974 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
975 unsigned int & column, OutputParams & runparams)
977 // FIXME: if we have "LaTeX" with a font
978 // change in the middle (before the 'T', then
979 // the "TeX" part is still special cased.
980 // Really we should only operate this on
981 // "words" for some definition of word
983 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
984 if (!isTextAt(special_phrases[pnr].phrase, i))
986 if (runparams.moving_arg)
988 os << special_phrases[pnr].macro;
989 i += special_phrases[pnr].phrase.length() - 1;
990 column += special_phrases[pnr].macro.length() - 1;
997 void Paragraph::Private::validate(LaTeXFeatures & features,
998 Layout const & layout) const
1000 // check the params.
1001 if (!params_.spacing().isDefault())
1002 features.require("setspace");
1005 features.useLayout(layout.name());
1008 fontlist_.validate(features);
1010 // then the indentation
1011 if (!params_.leftIndent().zero())
1012 features.require("ParagraphLeftIndent");
1015 InsetList::const_iterator icit = insetlist_.begin();
1016 InsetList::const_iterator iend = insetlist_.end();
1017 for (; icit != iend; ++icit) {
1019 icit->inset->validate(features);
1020 if (layout.needprotect &&
1021 icit->inset->lyxCode() == FOOT_CODE)
1022 features.require("NeedLyXFootnoteCode");
1026 // then the contents
1027 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1028 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1029 if (!special_phrases[pnr].builtin
1030 && isTextAt(special_phrases[pnr].phrase, i)) {
1031 features.require(special_phrases[pnr].phrase);
1035 Encodings::validate(text_[i], features);
1039 /////////////////////////////////////////////////////////////////////
1043 /////////////////////////////////////////////////////////////////////
1046 Layout const emptyParagraphLayout;
1049 Paragraph::Paragraph()
1050 : d(new Paragraph::Private(this, emptyParagraphLayout))
1057 Paragraph::Paragraph(Paragraph const & par)
1058 : itemdepth(par.itemdepth),
1059 d(new Paragraph::Private(*par.d, this))
1065 Paragraph & Paragraph::operator=(Paragraph const & par)
1067 // needed as we will destroy the private part before copying it
1069 itemdepth = par.itemdepth;
1073 d = new Private(*par.d, this);
1080 Paragraph::~Paragraph()
1087 void Paragraph::write(ostream & os, BufferParams const & bparams,
1088 depth_type & dth) const
1090 // The beginning or end of a deeper (i.e. nested) area?
1091 if (dth != d->params_.depth()) {
1092 if (d->params_.depth() > dth) {
1093 while (d->params_.depth() > dth) {
1094 os << "\n\\begin_deeper";
1098 while (d->params_.depth() < dth) {
1099 os << "\n\\end_deeper";
1105 // First write the layout
1106 os << "\n\\begin_layout " << to_utf8(d->layout().name()) << '\n';
1108 d->params_.write(os);
1110 Font font1(inherit_font, bparams.language);
1112 Change running_change = Change(Change::UNCHANGED);
1115 for (pos_type i = 0; i <= size(); ++i) {
1117 Change change = lookupChange(i);
1118 Changes::lyxMarkChange(os, column, running_change, change);
1119 running_change = change;
1124 // Write font changes
1125 Font font2 = getFontSettings(bparams, i);
1126 if (font2 != font1) {
1127 font2.lyxWriteChanges(font1, os);
1132 char_type const c = d->text_[i];
1135 if (Inset const * inset = getInset(i)) {
1136 if (inset->directWrite()) {
1137 // international char, let it write
1138 // code directly so it's shorter in
1144 os << "\\begin_inset ";
1146 os << "\n\\end_inset\n\n";
1152 os << "\n\\backslash\n";
1156 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1163 if ((column > 70 && c == ' ')
1168 // this check is to amend a bug. LyX sometimes
1169 // inserts '\0' this could cause problems.
1171 os << to_utf8(docstring(1, c));
1173 lyxerr << "ERROR (Paragraph::writeFile):"
1174 " NULL char in structure." << endl;
1180 os << "\n\\end_layout\n";
1184 void Paragraph::validate(LaTeXFeatures & features) const
1186 d->validate(features, d->layout());
1190 void Paragraph::insert(pos_type start, docstring const & str,
1191 Font const & font, Change const & change)
1193 for (size_t i = 0, n = str.size(); i != n ; ++i)
1194 insertChar(start + i, str[i], font, change);
1198 void Paragraph::appendChar(char_type c, Font const & font,
1199 Change const & change)
1202 d->changes_.insert(change, d->text_.size());
1203 // when appending characters, no need to update tables
1204 d->text_.push_back(c);
1205 setFont(d->text_.size() - 1, font);
1209 void Paragraph::appendString(docstring const & s, Font const & font,
1210 Change const & change)
1212 pos_type end = s.size();
1213 size_t oldsize = d->text_.size();
1214 size_t newsize = oldsize + end;
1215 size_t capacity = d->text_.capacity();
1216 if (newsize >= capacity)
1217 d->text_.reserve(max(capacity + 100, newsize));
1219 // when appending characters, no need to update tables
1222 // FIXME: Optimize this!
1223 for (pos_type i = 0; i != end; ++i) {
1225 d->changes_.insert(change, i);
1227 d->fontlist_.set(oldsize, font);
1228 d->fontlist_.set(newsize - 1, font);
1232 void Paragraph::insertChar(pos_type pos, char_type c,
1235 d->insertChar(pos, c, Change(trackChanges ?
1236 Change::INSERTED : Change::UNCHANGED));
1240 void Paragraph::insertChar(pos_type pos, char_type c,
1241 Font const & font, bool trackChanges)
1243 d->insertChar(pos, c, Change(trackChanges ?
1244 Change::INSERTED : Change::UNCHANGED));
1249 void Paragraph::insertChar(pos_type pos, char_type c,
1250 Font const & font, Change const & change)
1252 d->insertChar(pos, c, change);
1257 void Paragraph::insertInset(pos_type pos, Inset * inset,
1258 Font const & font, Change const & change)
1260 insertInset(pos, inset, change);
1261 // Set the font/language of the inset...
1266 bool Paragraph::insetAllowed(InsetCode code)
1268 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1272 void Paragraph::resetFonts(Font const & font)
1274 d->fontlist_.clear();
1275 d->fontlist_.set(0, font);
1276 d->fontlist_.set(d->text_.size() - 1, font);
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(inherit_font, 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(max(start, beginOfBody()),
1312 return FontSpan(start,
1313 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(inherit_font, 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.fontInfo().realize(d->layout().labelfont);
1352 font.fontInfo().realize(d->layout().font);
1354 font.fontInfo().realize(outerfont.fontInfo());
1355 font.fontInfo().realize(bparams.getFont().fontInfo());
1361 Font const Paragraph::getLabelFont
1362 (BufferParams const & bparams, Font const & outerfont) const
1364 FontInfo tmpfont = d->layout().labelfont;
1365 tmpfont.realize(outerfont.fontInfo());
1366 tmpfont.realize(bparams.getFont().fontInfo());
1367 return Font(tmpfont, getParLanguage(bparams));
1371 Font const Paragraph::getLayoutFont
1372 (BufferParams const & bparams, Font const & outerfont) const
1374 FontInfo tmpfont = d->layout().font;
1375 tmpfont.realize(outerfont.fontInfo());
1376 tmpfont.realize(bparams.getFont().fontInfo());
1377 return Font(tmpfont, getParLanguage(bparams));
1381 /// Returns the height of the highest font in range
1382 FontSize Paragraph::highestFontInRange
1383 (pos_type startpos, pos_type endpos, FontSize def_size) const
1385 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1390 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1392 char_type c = d->text_[pos];
1393 if (!lyxrc.rtl_support)
1423 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1430 void Paragraph::setFont(pos_type pos, Font const & font)
1432 BOOST_ASSERT(pos <= size());
1434 // First, reduce font against layout/label font
1435 // Update: The setCharFont() routine in text2.cpp already
1436 // reduces font, so we don't need to do that here. (Asger)
1438 d->fontlist_.set(pos, font);
1442 void Paragraph::makeSameLayout(Paragraph const & par)
1444 d->setLayout(par.d->layout());
1445 d->params_ = par.d->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.d->layout() == d->layout()
1471 && d->params_.sameLayout(par.d->params_);
1475 depth_type Paragraph::getDepth() const
1477 return d->params_.depth();
1481 depth_type Paragraph::getMaxDepthAfter() const
1483 if (d->layout().isEnvironment())
1484 return d->params_.depth() + 1;
1486 return d->params_.depth();
1490 char Paragraph::getAlign() const
1492 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1493 return d->layout().align;
1495 return d->params_.align();
1499 docstring const & Paragraph::labelString() const
1501 return d->params_.labelString();
1505 // the next two functions are for the manual labels
1506 docstring const Paragraph::getLabelWidthString() const
1508 if (d->layout().margintype == MARGIN_MANUAL)
1509 return d->params_.labelWidthString();
1511 return _("Senseless with this layout!");
1515 void Paragraph::setLabelWidthString(docstring const & s)
1517 d->params_.labelWidthString(s);
1521 docstring const Paragraph::translateIfPossible(docstring const & s,
1522 BufferParams const & bparams) const
1524 if (!isAscii(s) || s.empty()) {
1525 // This must be a user defined layout. We cannot translate
1526 // this, since gettext accepts only ascii keys.
1529 // Probably standard layout, try to translate
1530 Messages & m = getMessages(getParLanguage(bparams)->code());
1531 return m.get(to_ascii(s));
1535 docstring Paragraph::expandLabel(Layout const & layout,
1536 BufferParams const & bparams, bool process_appendix) const
1538 DocumentClass const & tclass = bparams.documentClass();
1541 if (process_appendix && d->params_.appendix())
1542 fmt = translateIfPossible(layout.labelstring_appendix(),
1545 fmt = translateIfPossible(layout.labelstring(), bparams);
1547 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1548 && !layout.counter.empty())
1549 fmt = "\\the" + layout.counter;
1551 // handle 'inherited level parts' in 'fmt',
1552 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1553 size_t const i = fmt.find('@', 0);
1554 if (i != docstring::npos) {
1555 size_t const j = fmt.find('@', i + 1);
1556 if (j != docstring::npos) {
1557 docstring parent(fmt, i + 1, j - i - 1);
1558 docstring label = from_ascii("??");
1559 if (tclass.hasLayout(parent))
1560 docstring label = expandLabel(tclass[parent], bparams,
1562 fmt = docstring(fmt, 0, i) + label
1563 + docstring(fmt, j + 1, docstring::npos);
1567 return tclass.counters().counterLabel(fmt);
1571 void Paragraph::applyLayout(Layout const & new_layout)
1573 d->setLayout(new_layout);
1574 LyXAlignment const oldAlign = d->params_.align();
1576 if (!(oldAlign & d->layout().alignpossible)) {
1577 frontend::Alert::warning(_("Alignment not permitted"),
1578 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1579 d->params_.align(LYX_ALIGN_LAYOUT);
1584 pos_type Paragraph::beginOfBody() const
1586 return d->begin_of_body_;
1590 void Paragraph::setBeginOfBody()
1592 if (d->layout().labeltype != LABEL_MANUAL) {
1593 d->begin_of_body_ = 0;
1597 // Unroll the first two cycles of the loop
1598 // and remember the previous character to
1599 // remove unnecessary getChar() calls
1601 pos_type end = size();
1602 if (i < end && !isNewline(i)) {
1604 char_type previous_char = 0;
1607 previous_char = d->text_[i];
1608 if (!isNewline(i)) {
1610 while (i < end && previous_char != ' ') {
1615 previous_char = temp;
1621 d->begin_of_body_ = i;
1625 bool Paragraph::forceEmptyLayout() const
1627 return inInset() && inInset()->forceEmptyLayout();
1631 bool Paragraph::allowParagraphCustomization() const
1633 return inInset() && inInset()->allowParagraphCustomization(0);
1637 bool Paragraph::useEmptyLayout() const
1639 return inInset() && inInset()->useEmptyLayout();
1645 // paragraphs inside floats need different alignment tags to avoid
1648 bool noTrivlistCentering(InsetCode code)
1650 return code == FLOAT_CODE || code == WRAP_CODE;
1654 string correction(string const & orig)
1656 if (orig == "flushleft")
1657 return "raggedright";
1658 if (orig == "flushright")
1659 return "raggedleft";
1660 if (orig == "center")
1666 string const corrected_env(string const & suffix, string const & env,
1669 string output = suffix + "{";
1670 if (noTrivlistCentering(code))
1671 output += correction(env);
1675 if (suffix == "\\begin")
1681 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1683 if (!contains(str, "\n"))
1684 column += str.size();
1688 column = rsplit(str, tmp, '\n').size();
1695 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1696 odocstream & os, TexRow & texrow,
1697 bool moving_arg) const
1701 if (params_.noindent()) {
1702 os << "\\noindent ";
1706 LyXAlignment const curAlign = params_.align();
1708 if (curAlign == layout_->align)
1712 case LYX_ALIGN_NONE:
1713 case LYX_ALIGN_BLOCK:
1714 case LYX_ALIGN_LAYOUT:
1715 case LYX_ALIGN_SPECIAL:
1717 case LYX_ALIGN_LEFT:
1718 case LYX_ALIGN_RIGHT:
1719 case LYX_ALIGN_CENTER:
1728 case LYX_ALIGN_NONE:
1729 case LYX_ALIGN_BLOCK:
1730 case LYX_ALIGN_LAYOUT:
1731 case LYX_ALIGN_SPECIAL:
1733 case LYX_ALIGN_LEFT: {
1735 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1736 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1738 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1739 os << from_ascii(output);
1740 adjust_row_column(output, texrow, column);
1742 } case LYX_ALIGN_RIGHT: {
1744 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1745 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1747 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1748 os << from_ascii(output);
1749 adjust_row_column(output, texrow, column);
1751 } case LYX_ALIGN_CENTER: {
1753 output = corrected_env("\\begin", "center", owner_->ownerCode());
1754 os << from_ascii(output);
1755 adjust_row_column(output, texrow, column);
1764 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1765 odocstream & os, TexRow & texrow,
1766 bool moving_arg) const
1770 switch (params_.align()) {
1771 case LYX_ALIGN_NONE:
1772 case LYX_ALIGN_BLOCK:
1773 case LYX_ALIGN_LAYOUT:
1774 case LYX_ALIGN_SPECIAL:
1776 case LYX_ALIGN_LEFT:
1777 case LYX_ALIGN_RIGHT:
1778 case LYX_ALIGN_CENTER:
1786 switch (params_.align()) {
1787 case LYX_ALIGN_NONE:
1788 case LYX_ALIGN_BLOCK:
1789 case LYX_ALIGN_LAYOUT:
1790 case LYX_ALIGN_SPECIAL:
1792 case LYX_ALIGN_LEFT: {
1794 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1795 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1797 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1798 os << from_ascii(output);
1799 adjust_row_column(output, texrow, column);
1801 } case LYX_ALIGN_RIGHT: {
1803 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1804 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1806 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1807 os << from_ascii(output);
1808 adjust_row_column(output, texrow, column);
1810 } case LYX_ALIGN_CENTER: {
1812 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1813 os << from_ascii(output);
1814 adjust_row_column(output, texrow, column);
1823 // This one spits out the text of the paragraph
1824 bool Paragraph::latex(BufferParams const & bparams,
1825 Font const & outerfont,
1826 odocstream & os, TexRow & texrow,
1827 OutputParams const & runparams) const
1829 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1831 bool return_value = false;
1835 bool asdefault = forceEmptyLayout();
1838 style = bparams.documentClass().emptyLayout();
1840 style = d->layout();
1842 // Current base font for all inherited font changes, without any
1843 // change caused by an individual character, except for the language:
1844 // It is set to the language of the first character.
1845 // As long as we are in the label, this font is the base font of the
1846 // label. Before the first body character it is set to the base font
1850 // Maybe we have to create a optional argument.
1851 pos_type body_pos = beginOfBody();
1852 unsigned int column = 0;
1855 // the optional argument is kept in curly brackets in
1856 // case it contains a ']'
1859 basefont = getLabelFont(bparams, outerfont);
1861 basefont = getLayoutFont(bparams, outerfont);
1864 // Which font is currently active?
1865 Font running_font(basefont);
1866 // Do we have an open font change?
1867 bool open_font = false;
1869 Change runningChange = Change(Change::UNCHANGED);
1871 texrow.start(id(), 0);
1873 // if the paragraph is empty, the loop will not be entered at all
1875 if (style.isCommand()) {
1880 column += d->startTeXParParams(bparams, os, texrow,
1881 runparams.moving_arg);
1884 for (pos_type i = 0; i < size(); ++i) {
1885 // First char in paragraph or after label?
1886 if (i == body_pos) {
1889 column += running_font.latexWriteEndChanges(
1890 os, bparams, runparams,
1891 basefont, basefont);
1894 basefont = getLayoutFont(bparams, outerfont);
1895 running_font = basefont;
1897 column += Changes::latexMarkChange(os, bparams,
1898 runningChange, Change(Change::UNCHANGED));
1899 runningChange = Change(Change::UNCHANGED);
1904 if (style.isCommand()) {
1910 column += d->startTeXParParams(bparams, os,
1912 runparams.moving_arg);
1915 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1918 if (bparams.outputChanges && runningChange != change) {
1920 column += running_font.latexWriteEndChanges(
1921 os, bparams, runparams, basefont, basefont);
1924 basefont = getLayoutFont(bparams, outerfont);
1925 running_font = basefont;
1927 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1928 runningChange = change;
1931 // do not output text which is marked deleted
1932 // if change tracking output is disabled
1933 if (!bparams.outputChanges && change.type == Change::DELETED) {
1939 // Fully instantiated font
1940 Font const font = getFont(bparams, i, outerfont);
1942 Font const last_font = running_font;
1944 // Do we need to close the previous font?
1946 (font != running_font ||
1947 font.language() != running_font.language()))
1949 column += running_font.latexWriteEndChanges(
1950 os, bparams, runparams, basefont,
1951 (i == body_pos-1) ? basefont : font);
1952 running_font = basefont;
1956 // close babel's font environment before opening CJK.
1957 if (!running_font.language()->babel().empty() &&
1958 font.language()->encoding()->package() == Encoding::CJK) {
1959 string end_tag = subst(lyxrc.language_command_end,
1961 running_font.language()->babel());
1962 os << from_ascii(end_tag);
1963 column += end_tag.length();
1966 // Switch file encoding if necessary (and allowed)
1967 if (!runparams.verbatim &&
1968 runparams.encoding->package() == Encoding::none &&
1969 font.language()->encoding()->package() == Encoding::none) {
1970 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1971 runparams, *(font.language()->encoding()));
1972 if (enc_switch.first) {
1973 column += enc_switch.second;
1974 runparams.encoding = font.language()->encoding();
1978 char_type const c = d->text_[i];
1980 // Do we need to change font?
1981 if ((font != running_font ||
1982 font.language() != running_font.language()) &&
1985 odocstringstream ods;
1986 column += font.latexWriteStartChanges(ods, bparams,
1987 runparams, basefont,
1989 running_font = font;
1991 docstring fontchange = ods.str();
1992 // check if the fontchange ends with a trailing blank
1993 // (like "\small " (see bug 3382)
1994 if (suffixIs(fontchange, ' ') && c == ' ')
1995 os << fontchange.substr(0, fontchange.size() - 1)
1996 << from_ascii("{}");
2002 // FIXME: integrate this case in latexSpecialChar
2003 // Do not print the separation of the optional argument
2004 // if style.pass_thru is false. This works because
2005 // latexSpecialChar ignores spaces if
2006 // style.pass_thru is false.
2007 if (i != body_pos - 1) {
2008 if (d->simpleTeXBlanks(
2009 runparams, os, texrow,
2010 i, column, font, style)) {
2011 // A surrogate pair was output. We
2012 // must not call latexSpecialChar
2013 // in this iteration, since it would output
2014 // the combining character again.
2021 OutputParams rp = runparams;
2022 rp.free_spacing = style.free_spacing;
2023 rp.local_font = &font;
2024 rp.intitle = style.intitle;
2026 // Two major modes: LaTeX or plain
2027 // Handle here those cases common to both modes
2028 // and then split to handle the two modes separately.
2029 if (c == META_INSET)
2030 d->latexInset(bparams, os,
2031 texrow, rp, running_font,
2032 basefont, outerfont, open_font,
2033 runningChange, style, i, column);
2036 d->latexSpecialChar(os, rp, running_font, runningChange,
2038 } catch (EncodingException & e) {
2039 if (runparams.dryrun) {
2040 os << "<" << _("LyX Warning: ")
2041 << _("uncodable character") << " '";
2045 // add location information and throw again.
2053 // Set the encoding to that returned from simpleTeXSpecialChars (see
2054 // comment for encoding member in OutputParams.h)
2055 runparams.encoding = rp.encoding;
2058 // If we have an open font definition, we have to close it
2060 #ifdef FIXED_LANGUAGE_END_DETECTION
2063 .latexWriteEndChanges(os, bparams, runparams,
2065 next_->getFont(bparams, 0, outerfont));
2067 running_font.latexWriteEndChanges(os, bparams,
2068 runparams, basefont, basefont);
2071 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2072 //FIXME: there as we start another \selectlanguage with the next paragraph if
2073 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2074 running_font.latexWriteEndChanges(os, bparams, runparams,
2075 basefont, basefont);
2079 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2081 // Needed if there is an optional argument but no contents.
2082 if (body_pos > 0 && body_pos == size()) {
2084 return_value = false;
2088 column += d->endTeXParParams(bparams, os, texrow,
2089 runparams.moving_arg);
2092 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2093 return return_value;
2097 bool Paragraph::emptyTag() const
2099 for (pos_type i = 0; i < size(); ++i) {
2100 if (Inset const * inset = getInset(i)) {
2101 InsetCode lyx_code = inset->lyxCode();
2102 if (lyx_code != TOC_CODE &&
2103 lyx_code != INCLUDE_CODE &&
2104 lyx_code != GRAPHICS_CODE &&
2105 lyx_code != ERT_CODE &&
2106 lyx_code != LISTINGS_CODE &&
2107 lyx_code != FLOAT_CODE &&
2108 lyx_code != TABULAR_CODE) {
2112 char_type c = d->text_[i];
2113 if (c != ' ' && c != '\t')
2121 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2124 for (pos_type i = 0; i < size(); ++i) {
2125 if (Inset const * inset = getInset(i)) {
2126 InsetCode lyx_code = inset->lyxCode();
2127 if (lyx_code == LABEL_CODE) {
2128 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2129 docstring const & id = il->getParam("name");
2130 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2138 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2142 for (i = 0; i < size(); ++i) {
2143 if (Inset const * inset = getInset(i)) {
2144 inset->docbook(os, runparams);
2146 char_type c = d->text_[i];
2149 os << sgml::escapeChar(c);
2156 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2159 pos_type size = text_.size();
2160 for (pos_type i = initial; i < size; ++i) {
2161 Font font = owner_->getFont(buf.params(), i, outerfont);
2162 if (text_[i] == META_INSET)
2164 if (i != initial && font != font_old)
2173 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2175 OutputParams const & runparams,
2176 Font const & outerfont,
2177 pos_type initial) const
2179 bool emph_flag = false;
2181 Layout const & style = d->layout();
2183 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2185 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2188 // parsing main loop
2189 for (pos_type i = initial; i < size(); ++i) {
2190 Font font = getFont(buf.params(), i, outerfont);
2192 // handle <emphasis> tag
2193 if (font_old.emph() != font.fontInfo().emph()) {
2194 if (font.fontInfo().emph() == FONT_ON) {
2197 } else if (i != initial) {
2198 os << "</emphasis>";
2203 if (Inset const * inset = getInset(i)) {
2204 inset->docbook(os, runparams);
2206 char_type c = d->text_[i];
2208 if (style.pass_thru)
2211 os << sgml::escapeChar(c);
2213 font_old = font.fontInfo();
2217 os << "</emphasis>";
2220 if (style.free_spacing)
2222 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2227 bool Paragraph::isHfill(pos_type pos) const
2229 Inset const * inset = getInset(pos);
2230 return inset && inset->lyxCode() == HFILL_CODE;
2234 bool Paragraph::isNewline(pos_type pos) const
2236 Inset const * inset = getInset(pos);
2237 return inset && inset->lyxCode() == NEWLINE_CODE;
2241 bool Paragraph::isLineSeparator(pos_type pos) const
2243 char_type const c = d->text_[pos];
2244 if (isLineSeparatorChar(c))
2246 Inset const * inset = getInset(pos);
2247 return inset && inset->isLineSeparator();
2251 /// Used by the spellchecker
2252 bool Paragraph::isLetter(pos_type pos) const
2254 if (Inset const * inset = getInset(pos))
2255 return inset->isLetter();
2256 char_type const c = d->text_[pos];
2257 return isLetterChar(c) || isDigit(c);
2262 Paragraph::getParLanguage(BufferParams const & bparams) const
2265 return getFirstFontSettings(bparams).language();
2266 // FIXME: we should check the prev par as well (Lgb)
2267 return bparams.language;
2271 bool Paragraph::isRTL(BufferParams const & bparams) const
2273 return lyxrc.rtl_support
2274 && getParLanguage(bparams)->rightToLeft()
2275 && ownerCode() != ERT_CODE
2276 && ownerCode() != LISTINGS_CODE;
2280 void Paragraph::changeLanguage(BufferParams const & bparams,
2281 Language const * from, Language const * to)
2283 // change language including dummy font change at the end
2284 for (pos_type i = 0; i <= size(); ++i) {
2285 Font font = getFontSettings(bparams, i);
2286 if (font.language() == from) {
2287 font.setLanguage(to);
2294 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2296 Language const * doc_language = bparams.language;
2297 FontList::const_iterator cit = d->fontlist_.begin();
2298 FontList::const_iterator end = d->fontlist_.end();
2300 for (; cit != end; ++cit)
2301 if (cit->font().language() != ignore_language &&
2302 cit->font().language() != latex_language &&
2303 cit->font().language() != doc_language)
2309 docstring Paragraph::asString(bool label) const
2311 return asString(0, size(), label);
2315 docstring Paragraph::asString(pos_type beg, pos_type end, bool label) const
2318 odocstringstream os;
2320 if (beg == 0 && label && !d->params_.labelString().empty())
2321 os << d->params_.labelString() << ' ';
2323 for (pos_type i = beg; i < end; ++i) {
2324 char_type const c = d->text_[i];
2327 else if (c == META_INSET)
2328 getInset(i)->textString(os);
2335 void Paragraph::setInsetOwner(Inset * inset)
2337 d->inset_owner_ = inset;
2341 int Paragraph::id() const
2347 Layout const & Paragraph::layout() const
2353 void Paragraph::setLayout(Layout const & layout)
2355 d->setLayout(layout);
2359 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2361 if (useEmptyLayout())
2362 setLayout(tclass.emptyLayout());
2364 setLayout(tclass.defaultLayout());
2368 Inset * Paragraph::inInset() const
2370 return d->inset_owner_;
2374 InsetCode Paragraph::ownerCode() const
2376 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2380 ParagraphParameters & Paragraph::params()
2386 ParagraphParameters const & Paragraph::params() const
2392 bool Paragraph::isFreeSpacing() const
2394 if (d->layout().free_spacing)
2396 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2400 bool Paragraph::allowEmpty() const
2402 if (d->layout().keepempty)
2404 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2408 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2410 if (!Encodings::is_arabic(c))
2413 char_type prev_char = ' ';
2414 char_type next_char = ' ';
2416 for (pos_type i = pos - 1; i >= 0; --i) {
2417 char_type const par_char = d->text_[i];
2418 if (!Encodings::isComposeChar_arabic(par_char)) {
2419 prev_char = par_char;
2424 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2425 char_type const par_char = d->text_[i];
2426 if (!Encodings::isComposeChar_arabic(par_char)) {
2427 next_char = par_char;
2432 if (Encodings::is_arabic(next_char)) {
2433 if (Encodings::is_arabic(prev_char) &&
2434 !Encodings::is_arabic_special(prev_char))
2435 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2437 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2439 if (Encodings::is_arabic(prev_char) &&
2440 !Encodings::is_arabic_special(prev_char))
2441 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2443 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2448 int Paragraph::checkBiblio(Buffer const & buffer)
2451 // This is getting more and more a mess. ...We really should clean
2452 // up this bibitem issue for 1.6. See also bug 2743.
2454 // Add bibitem insets if necessary
2455 if (d->layout().labeltype != LABEL_BIBLIO)
2458 bool hasbibitem = !d->insetlist_.empty()
2459 // Insist on it being in pos 0
2460 && d->text_[0] == META_INSET
2461 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2463 bool track_changes = buffer.params().trackChanges;
2468 // remove a bibitem in pos != 0
2469 // restore it later in pos 0 if necessary
2470 // (e.g. if a user inserts contents _before_ the item)
2471 // we're assuming there's only one of these, which there
2473 int erasedInsetPosition = -1;
2474 InsetList::iterator it = d->insetlist_.begin();
2475 InsetList::iterator end = d->insetlist_.end();
2476 for (; it != end; ++it)
2477 if (it->inset->lyxCode() == BIBITEM_CODE
2479 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2480 oldkey = olditem->getParam("key");
2481 oldlabel = olditem->getParam("label");
2482 erasedInsetPosition = it->pos;
2483 eraseChar(erasedInsetPosition, track_changes);
2487 // There was an InsetBibitem at the beginning, and we didn't
2488 // have to erase one.
2489 if (hasbibitem && erasedInsetPosition < 0)
2492 // There was an InsetBibitem at the beginning and we did have to
2493 // erase one. So we give its properties to the beginning inset.
2495 InsetBibitem * inset =
2496 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2497 if (!oldkey.empty())
2498 inset->setParam("key", oldkey);
2499 inset->setParam("label", oldlabel);
2500 return -erasedInsetPosition;
2503 // There was no inset at the beginning, so we need to create one with
2504 // the key and label of the one we erased.
2505 InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2506 inset->setBuffer(const_cast<Buffer &>(buffer));
2507 // restore values of previously deleted item in this par.
2508 if (!oldkey.empty())
2509 inset->setParam("key", oldkey);
2510 inset->setParam("label", oldlabel);
2511 insertInset(0, static_cast<Inset *>(inset),
2512 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2518 void Paragraph::checkAuthors(AuthorList const & authorList)
2520 d->changes_.checkAuthors(authorList);
2524 bool Paragraph::isUnchanged(pos_type pos) const
2526 return lookupChange(pos).type == Change::UNCHANGED;
2530 bool Paragraph::isInserted(pos_type pos) const
2532 return lookupChange(pos).type == Change::INSERTED;
2536 bool Paragraph::isDeleted(pos_type pos) const
2538 return lookupChange(pos).type == Change::DELETED;
2542 InsetList const & Paragraph::insetList() const
2544 return d->insetlist_;
2548 Inset * Paragraph::releaseInset(pos_type pos)
2550 Inset * inset = d->insetlist_.release(pos);
2551 /// does not honour change tracking!
2552 eraseChar(pos, false);
2557 Inset * Paragraph::getInset(pos_type pos)
2559 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2560 ? d->insetlist_.get(pos) : 0;
2564 Inset const * Paragraph::getInset(pos_type pos) const
2566 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2567 ? d->insetlist_.get(pos) : 0;
2571 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2572 pos_type & right, TextCase action)
2574 // process sequences of modified characters; in change
2575 // tracking mode, this approach results in much better
2576 // usability than changing case on a char-by-char basis
2579 bool const trackChanges = bparams.trackChanges;
2581 bool capitalize = true;
2583 for (; pos < right; ++pos) {
2584 char_type oldChar = d->text_[pos];
2585 char_type newChar = oldChar;
2587 // ignore insets and don't play with deleted text!
2588 if (oldChar != META_INSET && !isDeleted(pos)) {
2590 case text_lowercase:
2591 newChar = lowercase(oldChar);
2593 case text_capitalization:
2595 newChar = uppercase(oldChar);
2599 case text_uppercase:
2600 newChar = uppercase(oldChar);
2605 if (!isLetter(pos) || isDeleted(pos)) {
2606 // permit capitalization again
2610 if (oldChar != newChar)
2613 if (oldChar == newChar || pos == right - 1) {
2614 if (oldChar != newChar) {
2615 // step behind the changing area
2618 int erasePos = pos - changes.size();
2619 for (size_t i = 0; i < changes.size(); i++) {
2620 insertChar(pos, changes[i],
2621 getFontSettings(bparams,
2624 if (!eraseChar(erasePos, trackChanges)) {
2627 ++right; // expand selection
2636 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2637 pos_type pos, bool del) const
2639 int const strsize = str.length();
2641 pos_type const parsize = d->text_.size();
2642 for (i = 0; pos + i < parsize; ++i) {
2645 if (cs && str[i] != d->text_[pos + i])
2647 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2649 if (!del && isDeleted(pos + i))
2656 // if necessary, check whether string matches word
2658 if (pos > 0 && isLetter(pos - 1))
2660 if (pos + strsize < parsize
2661 && isLetter(pos + strsize))
2669 char_type Paragraph::getChar(pos_type pos) const
2671 return d->text_[pos];
2675 pos_type Paragraph::size() const
2677 return d->text_.size();
2681 bool Paragraph::empty() const
2683 return d->text_.empty();
2687 bool Paragraph::isInset(pos_type pos) const
2689 return d->text_[pos] == META_INSET;
2693 bool Paragraph::isSeparator(pos_type pos) const
2695 //FIXME: Are we sure this can be the only separator?
2696 return d->text_[pos] == ' ';
2700 void Paragraph::deregisterWords()
2702 Private::Words::const_iterator it;
2703 WordList & wl = theWordList();
2704 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2710 void Paragraph::collectWords(CursorSlice const & sl)
2713 bool inword = false;
2715 //lyxerr << "Words: ";
2716 pos_type n = size();
2717 for (pos_type pos = 0; pos != n; ++pos) {
2721 if (!isLetter(pos)) {
2730 CursorSlice from = sl;
2731 CursorSlice to = sl;
2734 from.text()->getWord(from, to, WHOLE_WORD);
2735 if (to.pos() - from.pos() < 6)
2737 docstring word = asString(from.pos(), to.pos(), false);
2738 d->words_.insert(word);
2739 //lyxerr << word << " ";
2741 //lyxerr << std::endl;
2745 void Paragraph::registerWords()
2747 Private::Words::const_iterator it;
2748 WordList & wl = theWordList();
2749 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2754 void Paragraph::updateWords(CursorSlice const & sl)
2756 BOOST_ASSERT(&sl.paragraph() == this);