3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
23 #include "BufferParams.h"
27 #include "InsetList.h"
29 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
40 #include "TextClass.h"
46 #include "frontends/alert.h"
48 #include "insets/InsetBibitem.h"
49 #include "insets/InsetLabel.h"
51 #include "support/convert.h"
52 #include "support/debug.h"
53 #include "support/gettext.h"
54 #include "support/lstrings.h"
55 #include "support/Messages.h"
56 #include "support/textutils.h"
62 using namespace lyx::support;
67 /// Inset identifier (above 0x10ffff, for ucs-4)
68 char_type const META_INSET = 0x200001;
71 /////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////
77 class Paragraph::Private
81 Private(Paragraph * owner);
82 /// "Copy constructor"
83 Private(Private const &, Paragraph * owner);
86 void insertChar(pos_type pos, char_type c, Change const & change);
88 /// Output the surrogate pair formed by \p c and \p next to \p os.
89 /// \return the number of characters written.
90 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
93 /// Output a space in appropriate formatting (or a surrogate pair
94 /// if the next character is a combining character).
95 /// \return whether a surrogate pair was output.
96 bool simpleTeXBlanks(OutputParams const &,
97 odocstream &, TexRow & texrow,
99 unsigned int & column,
101 Layout const & style);
103 /// Output consecutive unicode chars, belonging to the same script as
104 /// specified by the latex macro \p ltx, to \p os starting from \p i.
105 /// \return the number of characters written.
106 int writeScriptChars(odocstream & os, docstring const & ltx,
107 Change &, Encoding const &, pos_type & i);
109 /// This could go to ParagraphParameters if we want to.
110 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
113 /// This could go to ParagraphParameters if we want to.
114 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 void latexInset(BufferParams const &,
120 TexRow & texrow, OutputParams &,
123 Font const & outerfont,
125 Change & running_change,
126 Layout const & style,
128 unsigned int & column);
131 void latexSpecialChar(
133 OutputParams & runparams,
135 Change & running_change,
136 Layout const & style,
138 unsigned int & column);
145 unsigned int & column);
147 bool latexSpecialTypewriter(
151 unsigned int & column);
153 bool latexSpecialPhrase(
156 unsigned int & column,
157 OutputParams & runparams);
160 void validate(LaTeXFeatures & features,
161 Layout const & layout) const;
163 /// Checks if the paragraph contains only text and no inset or font change.
164 bool onlyText(Buffer const & buf, Font const & outerfont,
165 pos_type initial) const;
167 /// match a string against a particular point in the paragraph
168 bool isTextAt(string const & str, pos_type pos) const;
170 /// Which Paragraph owns us?
174 Inset * inset_owner_;
182 static unsigned int paragraph_id;
184 ParagraphParameters params_;
186 /// for recording and looking up changes
190 InsetList insetlist_;
196 pos_type begin_of_body_;
198 typedef docstring TextContainer;
202 typedef std::set<docstring> Words;
208 // Initialization of the counter for the paragraph id's,
209 unsigned int Paragraph::Private::paragraph_id = 0;
213 struct special_phrase {
219 special_phrase const special_phrases[] = {
220 { "LyX", from_ascii("\\LyX{}"), false },
221 { "TeX", from_ascii("\\TeX{}"), true },
222 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
223 { "LaTeX", from_ascii("\\LaTeX{}"), true },
226 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
231 Paragraph::Private::Private(Paragraph * owner)
232 : owner_(owner), inset_owner_(0), begin_of_body_(0)
234 id_ = paragraph_id++;
239 Paragraph::Private::Private(Private const & p, Paragraph * owner)
240 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
241 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
242 layout_(p.layout_), begin_of_body_(p.begin_of_body_), text_(p.text_),
245 id_ = paragraph_id++;
249 bool Paragraph::isChanged(pos_type start, pos_type end) const
251 BOOST_ASSERT(start >= 0 && start <= size());
252 BOOST_ASSERT(end > start && end <= size() + 1);
254 return d->changes_.isChanged(start, end);
258 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
260 // keep the logic here in sync with the logic of eraseChars()
264 Change const change = d->changes_.lookup(size());
265 return change.type == Change::INSERTED && change.author == 0;
269 void Paragraph::setChange(Change const & change)
271 // beware of the imaginary end-of-par character!
272 d->changes_.set(change, 0, size() + 1);
275 * Propagate the change recursively - but not in case of DELETED!
277 * Imagine that your co-author makes changes in an existing inset. He
278 * sends your document to you and you come to the conclusion that the
279 * inset should go completely. If you erase it, LyX must not delete all
280 * text within the inset. Otherwise, the change tracked insertions of
281 * your co-author get lost and there is no way to restore them later.
283 * Conclusion: An inset's content should remain untouched if you delete it
286 if (change.type != Change::DELETED) {
287 for (pos_type pos = 0; pos < size(); ++pos) {
288 if (Inset * inset = getInset(pos))
289 inset->setChange(change);
295 void Paragraph::setChange(pos_type pos, Change const & change)
297 BOOST_ASSERT(pos >= 0 && pos <= size());
298 d->changes_.set(change, pos);
300 // see comment in setChange(Change const &) above
301 if (change.type != Change::DELETED && pos < size())
302 if (Inset * inset = getInset(pos))
303 inset->setChange(change);
307 Change const & Paragraph::lookupChange(pos_type pos) const
309 BOOST_ASSERT(pos >= 0 && pos <= size());
310 return d->changes_.lookup(pos);
314 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
317 BOOST_ASSERT(start >= 0 && start <= size());
318 BOOST_ASSERT(end > start && end <= size() + 1);
320 for (pos_type pos = start; pos < end; ++pos) {
321 switch (lookupChange(pos).type) {
322 case Change::UNCHANGED:
323 // accept changes in nested inset
324 if (Inset * inset = getInset(pos))
325 inset->acceptChanges(bparams);
328 case Change::INSERTED:
329 d->changes_.set(Change(Change::UNCHANGED), pos);
330 // also accept changes in nested inset
331 if (Inset * inset = getInset(pos))
332 inset->acceptChanges(bparams);
335 case Change::DELETED:
336 // Suppress access to non-existent
337 // "end-of-paragraph char"
339 eraseChar(pos, false);
350 void Paragraph::rejectChanges(BufferParams const & bparams,
351 pos_type start, pos_type end)
353 BOOST_ASSERT(start >= 0 && start <= size());
354 BOOST_ASSERT(end > start && end <= size() + 1);
356 for (pos_type pos = start; pos < end; ++pos) {
357 switch (lookupChange(pos).type) {
358 case Change::UNCHANGED:
359 // reject changes in nested inset
360 if (Inset * inset = getInset(pos))
361 inset->rejectChanges(bparams);
364 case Change::INSERTED:
365 // Suppress access to non-existent
366 // "end-of-paragraph char"
368 eraseChar(pos, false);
374 case Change::DELETED:
375 d->changes_.set(Change(Change::UNCHANGED), pos);
377 // Do NOT reject changes within a deleted inset!
378 // There may be insertions of a co-author inside of it!
386 void Paragraph::Private::insertChar(pos_type pos, char_type c,
387 Change const & change)
389 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
392 changes_.insert(change, pos);
394 // This is actually very common when parsing buffers (and
395 // maybe inserting ascii text)
396 if (pos == pos_type(text_.size())) {
397 // when appending characters, no need to update tables
402 text_.insert(text_.begin() + pos, c);
404 // Update the font table.
405 fontlist_.increasePosAfterPos(pos);
408 insetlist_.increasePosAfterPos(pos);
412 void Paragraph::insertInset(pos_type pos, Inset * inset,
413 Change const & change)
416 BOOST_ASSERT(pos >= 0 && pos <= size());
418 d->insertChar(pos, META_INSET, change);
419 BOOST_ASSERT(d->text_[pos] == META_INSET);
421 // Add a new entry in the insetlist_.
422 d->insetlist_.insert(inset, pos);
426 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
428 BOOST_ASSERT(pos >= 0 && pos <= size());
430 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
433 Change change = d->changes_.lookup(pos);
435 // set the character to DELETED if
436 // a) it was previously unchanged or
437 // b) it was inserted by a co-author
439 if (change.type == Change::UNCHANGED ||
440 (change.type == Change::INSERTED && change.author != 0)) {
441 setChange(pos, Change(Change::DELETED));
445 if (change.type == Change::DELETED)
449 // Don't physically access the imaginary end-of-paragraph character.
450 // eraseChar() can only mark it as DELETED. A physical deletion of
451 // end-of-par must be handled externally.
457 d->changes_.erase(pos);
459 // if it is an inset, delete the inset entry
460 if (d->text_[pos] == META_INSET)
461 d->insetlist_.erase(pos);
463 d->text_.erase(d->text_.begin() + pos);
465 // Update the fontlist_
466 d->fontlist_.erase(pos);
468 // Update the insetlist_
469 d->insetlist_.decreasePosAfterPos(pos);
475 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
477 BOOST_ASSERT(start >= 0 && start <= size());
478 BOOST_ASSERT(end >= start && end <= size() + 1);
481 for (pos_type count = end - start; count; --count) {
482 if (!eraseChar(i, trackChanges))
489 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
490 char_type next, Encoding const & encoding)
492 // Writing next here may circumvent a possible font change between
493 // c and next. Since next is only output if it forms a surrogate pair
494 // with c we can ignore this:
495 // A font change inside a surrogate pair does not make sense and is
496 // hopefully impossible to input.
497 // FIXME: change tracking
498 // Is this correct WRT change tracking?
499 docstring const latex1 = encoding.latexChar(next);
500 docstring const latex2 = encoding.latexChar(c);
501 os << latex1 << '{' << latex2 << '}';
502 return latex1.length() + latex2.length() + 2;
506 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
507 odocstream & os, TexRow & texrow,
509 unsigned int & column,
511 Layout const & style)
513 if (style.pass_thru || runparams.verbatim)
516 if (i + 1 < int(text_.size())) {
517 char_type next = text_[i + 1];
518 if (Encodings::isCombiningChar(next)) {
519 Encoding const & encoding = *(runparams.encoding);
520 // This space has an accent, so we must always output it.
521 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
526 if (lyxrc.plaintext_linelen > 0
527 && column > lyxrc.plaintext_linelen
529 && text_[i - 1] != ' '
530 && (i + 1 < int(text_.size()))
531 // same in FreeSpacing mode
532 && !owner_->isFreeSpacing()
533 // In typewriter mode, we want to avoid
534 // ! . ? : at the end of a line
535 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
536 && (text_[i - 1] == '.'
537 || text_[i - 1] == '?'
538 || text_[i - 1] == ':'
539 || text_[i - 1] == '!'))) {
542 texrow.start(owner_->id(), i + 1);
544 } else if (style.free_spacing) {
553 int Paragraph::Private::writeScriptChars(odocstream & os,
554 docstring const & ltx,
555 Change & runningChange,
556 Encoding const & encoding,
559 // FIXME: modifying i here is not very nice...
561 // We only arrive here when a proper language for character text_[i] has
562 // not been specified (i.e., it could not be translated in the current
563 // latex encoding) and it belongs to a known script.
564 // Parameter ltx contains the latex translation of text_[i] as specified in
565 // the unicodesymbols file and is something like "\textXXX{<spec>}".
566 // The latex macro name "textXXX" specifies the script to which text_[i]
567 // belongs and we use it in order to check whether characters from the
568 // same script immediately follow, such that we can collect them in a
569 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
570 // for the first char but only "<spec>" for all subsequent chars.
571 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
572 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
573 string script = to_ascii(ltx.substr(1, brace1 - 1));
574 int length = ltx.substr(0, brace2).length();
575 os << ltx.substr(0, brace2);
576 int size = text_.size();
577 while (i + 1 < size) {
578 char_type const next = text_[i + 1];
579 // Stop here if next character belongs to another script
580 // or there is a change in change tracking status.
581 if (!Encodings::isKnownScriptChar(next, script) ||
582 runningChange != owner_->lookupChange(i + 1))
586 FontList::const_iterator cit = fontlist_.begin();
587 FontList::const_iterator end = fontlist_.end();
588 for (; cit != end; ++cit) {
589 if (cit->pos() >= i && !found) {
590 prev_font = cit->font();
593 if (cit->pos() >= i + 1)
596 // Stop here if there is a font attribute or encoding change.
597 if (found && cit != end && prev_font != cit->font())
599 docstring const latex = encoding.latexChar(next);
600 docstring::size_type const b1 =
601 latex.find_first_of(from_ascii("{"));
602 docstring::size_type const b2 =
603 latex.find_last_of(from_ascii("}"));
604 int const len = b2 - b1 - 1;
605 os << latex.substr(b1 + 1, len);
615 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
617 pos_type const len = str.length();
619 // is the paragraph large enough?
620 if (pos + len > int(text_.size()))
623 // does the wanted text start at point?
624 for (string::size_type i = 0; i < str.length(); ++i) {
625 // Caution: direct comparison of characters works only
626 // because str is pure ASCII.
627 if (str[i] != text_[pos + i])
631 return fontlist_.hasChangeInRange(pos, len);
635 void Paragraph::Private::latexInset(
636 BufferParams const & bparams,
639 OutputParams & runparams,
642 Font const & outerfont,
644 Change & running_change,
645 Layout const & style,
647 unsigned int & column)
649 Inset * inset = owner_->getInset(i);
652 if (style.pass_thru) {
653 inset->plaintext(os, runparams);
657 // FIXME: move this to InsetNewline::latex
658 if (inset->lyxCode() == NEWLINE_CODE) {
659 // newlines are handled differently here than
660 // the default in simpleTeXSpecialChars().
661 if (!style.newline_allowed) {
665 column += running_font.latexWriteEndChanges(
666 os, bparams, runparams,
671 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
674 basefont = owner_->getLayoutFont(bparams, outerfont);
675 running_font = basefont;
677 if (runparams.moving_arg)
682 texrow.start(owner_->id(), i + 1);
686 if (owner_->lookupChange(i).type == Change::DELETED) {
687 if( ++runparams.inDeletedInset == 1)
688 runparams.changeOfDeletedInset = owner_->lookupChange(i);
691 if (inset->canTrackChanges()) {
692 column += Changes::latexMarkChange(os, bparams, running_change,
693 Change(Change::UNCHANGED));
694 running_change = Change(Change::UNCHANGED);
698 odocstream::pos_type const len = os.tellp();
700 if (inset->forceLTR()
701 && running_font.isRightToLeft()
702 // ERT is an exception, it should be output with no decorations at all
703 && inset->lyxCode() != ERT_CODE) {
704 if (running_font.language()->lang() == "farsi")
711 // FIXME: Bug: we can have an empty font change here!
712 // if there has just been a font change, we are going to close it
713 // right now, which means stupid latex code like \textsf{}. AFAIK,
714 // this does not harm dvi output. A minor bug, thus (JMarc)
716 // Some insets cannot be inside a font change command.
717 // However, even such insets *can* be placed in \L or \R
718 // or their equivalents (for RTL language switches), so we don't
719 // close the language in those cases.
720 // ArabTeX, though, cannot handle this special behavior, it seems.
721 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
722 || running_font.language()->lang() == "arabic_arabtex";
723 if (open_font && inset->noFontChange()) {
724 bool closeLanguage = arabtex
725 || basefont.isRightToLeft() == running_font.isRightToLeft();
726 unsigned int count = running_font.latexWriteEndChanges(os,
727 bparams, runparams, basefont, basefont, closeLanguage);
729 // if any font properties were closed, update the running_font,
730 // making sure, however, to leave the language as it was
732 // FIXME: probably a better way to keep track of the old
733 // language, than copying the entire font?
734 Font const copy_font(running_font);
735 basefont = owner_->getLayoutFont(bparams, outerfont);
736 running_font = basefont;
738 running_font.setLanguage(copy_font.language());
739 // leave font open if language is still open
740 open_font = (running_font.language() == basefont.language());
742 runparams.local_font = &basefont;
746 int tmp = inset->latex(os, runparams);
749 if (running_font.language()->lang() == "farsi")
756 for (int j = 0; j < tmp; ++j)
759 texrow.start(owner_->id(), i + 1);
762 column += os.tellp() - len;
765 if (owner_->lookupChange(i).type == Change::DELETED)
766 --runparams.inDeletedInset;
770 void Paragraph::Private::latexSpecialChar(
772 OutputParams & runparams,
774 Change & running_change,
775 Layout const & style,
777 unsigned int & column)
779 char_type const c = text_[i];
781 if (style.pass_thru) {
783 // FIXME UNICODE: This can fail if c cannot
784 // be encoded in the current encoding.
789 if (runparams.verbatim) {
794 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
797 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
798 && latexSpecialTypewriter(c, os, i, column))
801 // Otherwise, we use what LaTeX provides us.
804 os << "\\textbackslash{}";
808 os << "\\textless{}";
812 os << "\\textgreater{}";
823 os << "\\char`\\\"{}";
828 case '%': case '#': case '{':
836 os << "\\textasciitilde{}";
841 os << "\\textasciicircum{}";
846 // avoid being mistaken for optional arguments
854 // Blanks are printed before font switching.
855 // Sure? I am not! (try nice-latex)
856 // I am sure it's correct. LyX might be smarter
857 // in the future, but for now, nothing wrong is
864 if (latexSpecialPhrase(os, i, column, runparams))
870 Encoding const & encoding = *(runparams.encoding);
871 if (i + 1 < int(text_.size())) {
872 char_type next = text_[i + 1];
873 if (Encodings::isCombiningChar(next)) {
874 column += latexSurrogatePair(os, c, next, encoding) - 1;
880 docstring const latex = encoding.latexChar(c);
881 if (Encodings::isKnownScriptChar(c, script)
882 && prefixIs(latex, from_ascii("\\" + script)))
883 column += writeScriptChars(os, latex,
884 running_change, encoding, i) - 1;
885 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
886 // Prevent eating of a following
887 // space or command corruption by
888 // following characters
889 column += latex.length() + 1;
892 column += latex.length() - 1;
900 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
901 pos_type & i, unsigned int & column)
907 // In T1 encoding, these characters exist
908 // but we should avoid ligatures
909 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
914 //os << "\\textcompwordmark{}";
926 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
927 pos_type & i, unsigned int & column)
931 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
932 // "--" in Typewriter mode -> "-{}-"
939 // I assume this is hack treating typewriter as verbatim
940 // FIXME UNICODE: This can fail if c cannot be encoded
941 // in the current encoding.
946 // Those characters are not directly supported.
950 case '%': case '#': case '{':
959 // With Typewriter font, these characters exist.
966 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
967 unsigned int & column, OutputParams & runparams)
969 // FIXME: if we have "LaTeX" with a font
970 // change in the middle (before the 'T', then
971 // the "TeX" part is still special cased.
972 // Really we should only operate this on
973 // "words" for some definition of word
975 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
976 if (!isTextAt(special_phrases[pnr].phrase, i))
978 if (runparams.moving_arg)
980 os << special_phrases[pnr].macro;
981 i += special_phrases[pnr].phrase.length() - 1;
982 column += special_phrases[pnr].macro.length() - 1;
989 void Paragraph::Private::validate(LaTeXFeatures & features,
990 Layout const & layout) const
993 if (!params_.spacing().isDefault())
994 features.require("setspace");
997 features.useLayout(layout.name());
1000 fontlist_.validate(features);
1002 // then the indentation
1003 if (!params_.leftIndent().zero())
1004 features.require("ParagraphLeftIndent");
1007 InsetList::const_iterator icit = insetlist_.begin();
1008 InsetList::const_iterator iend = insetlist_.end();
1009 for (; icit != iend; ++icit) {
1011 icit->inset->validate(features);
1012 if (layout.needprotect &&
1013 icit->inset->lyxCode() == FOOT_CODE)
1014 features.require("NeedLyXFootnoteCode");
1018 // then the contents
1019 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1020 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1021 if (!special_phrases[pnr].builtin
1022 && isTextAt(special_phrases[pnr].phrase, i)) {
1023 features.require(special_phrases[pnr].phrase);
1027 Encodings::validate(text_[i], features);
1031 /////////////////////////////////////////////////////////////////////
1035 /////////////////////////////////////////////////////////////////////
1037 Paragraph::Paragraph()
1038 : d(new Paragraph::Private(this))
1045 Paragraph::Paragraph(Paragraph const & par)
1046 : itemdepth(par.itemdepth),
1047 d(new Paragraph::Private(*par.d, this))
1053 Paragraph & Paragraph::operator=(Paragraph const & par)
1055 // needed as we will destroy the private part before copying it
1057 itemdepth = par.itemdepth;
1061 d = new Private(*par.d, this);
1068 Paragraph::~Paragraph()
1075 void Paragraph::write(ostream & os, BufferParams const & bparams,
1076 depth_type & dth) const
1078 // The beginning or end of a deeper (i.e. nested) area?
1079 if (dth != d->params_.depth()) {
1080 if (d->params_.depth() > dth) {
1081 while (d->params_.depth() > dth) {
1082 os << "\n\\begin_deeper";
1086 while (d->params_.depth() < dth) {
1087 os << "\n\\end_deeper";
1093 // First write the layout
1094 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1096 d->params_.write(os);
1098 Font font1(inherit_font, bparams.language);
1100 Change running_change = Change(Change::UNCHANGED);
1103 for (pos_type i = 0; i <= size(); ++i) {
1105 Change change = lookupChange(i);
1106 Changes::lyxMarkChange(os, column, running_change, change);
1107 running_change = change;
1112 // Write font changes
1113 Font font2 = getFontSettings(bparams, i);
1114 if (font2 != font1) {
1115 font2.lyxWriteChanges(font1, os);
1120 char_type const c = d->text_[i];
1123 if (Inset const * inset = getInset(i)) {
1124 if (inset->directWrite()) {
1125 // international char, let it write
1126 // code directly so it's shorter in
1132 os << "\\begin_inset ";
1134 os << "\n\\end_inset\n\n";
1140 os << "\n\\backslash\n";
1144 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1151 if ((column > 70 && c == ' ')
1156 // this check is to amend a bug. LyX sometimes
1157 // inserts '\0' this could cause problems.
1159 os << to_utf8(docstring(1, c));
1161 lyxerr << "ERROR (Paragraph::writeFile):"
1162 " NULL char in structure." << endl;
1168 os << "\n\\end_layout\n";
1172 void Paragraph::validate(LaTeXFeatures & features) const
1174 d->validate(features, *d->layout_);
1178 void Paragraph::insert(pos_type start, docstring const & str,
1179 Font const & font, Change const & change)
1181 for (size_t i = 0, n = str.size(); i != n ; ++i)
1182 insertChar(start + i, str[i], font, change);
1186 void Paragraph::appendChar(char_type c, Font const & font,
1187 Change const & change)
1190 d->changes_.insert(change, d->text_.size());
1191 // when appending characters, no need to update tables
1192 d->text_.push_back(c);
1193 setFont(d->text_.size() - 1, font);
1197 void Paragraph::appendString(docstring const & s, Font const & font,
1198 Change const & change)
1200 pos_type end = s.size();
1201 size_t oldsize = d->text_.size();
1202 size_t newsize = oldsize + end;
1203 size_t capacity = d->text_.capacity();
1204 if (newsize >= capacity)
1205 d->text_.reserve(max(capacity + 100, newsize));
1207 // when appending characters, no need to update tables
1210 // FIXME: Optimize this!
1211 for (pos_type i = 0; i != end; ++i) {
1213 d->changes_.insert(change, i);
1215 d->fontlist_.set(oldsize, font);
1216 d->fontlist_.set(newsize - 1, font);
1220 void Paragraph::insertChar(pos_type pos, char_type c,
1223 d->insertChar(pos, c, Change(trackChanges ?
1224 Change::INSERTED : Change::UNCHANGED));
1228 void Paragraph::insertChar(pos_type pos, char_type c,
1229 Font const & font, bool trackChanges)
1231 d->insertChar(pos, c, Change(trackChanges ?
1232 Change::INSERTED : Change::UNCHANGED));
1237 void Paragraph::insertChar(pos_type pos, char_type c,
1238 Font const & font, Change const & change)
1240 d->insertChar(pos, c, change);
1245 void Paragraph::insertInset(pos_type pos, Inset * inset,
1246 Font const & font, Change const & change)
1248 insertInset(pos, inset, change);
1249 // Set the font/language of the inset...
1254 bool Paragraph::insetAllowed(InsetCode code)
1256 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1260 void Paragraph::resetFonts(Font const & font)
1262 d->fontlist_.clear();
1263 d->fontlist_.set(0, font);
1264 d->fontlist_.set(d->text_.size() - 1, font);
1267 // Gets uninstantiated font setting at position.
1268 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1272 lyxerr << " pos: " << pos << " size: " << size() << endl;
1273 BOOST_ASSERT(pos <= size());
1276 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1277 if (cit != d->fontlist_.end())
1280 if (pos == size() && !empty())
1281 return getFontSettings(bparams, pos - 1);
1283 return Font(inherit_font, getParLanguage(bparams));
1287 FontSpan Paragraph::fontSpan(pos_type pos) const
1289 BOOST_ASSERT(pos <= size());
1292 FontList::const_iterator cit = d->fontlist_.begin();
1293 FontList::const_iterator end = d->fontlist_.end();
1294 for (; cit != end; ++cit) {
1295 if (cit->pos() >= pos) {
1296 if (pos >= beginOfBody())
1297 return FontSpan(max(start, beginOfBody()),
1300 return FontSpan(start,
1301 min(beginOfBody() - 1,
1304 start = cit->pos() + 1;
1307 // This should not happen, but if so, we take no chances.
1308 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1310 return FontSpan(pos, pos);
1314 // Gets uninstantiated font setting at position 0
1315 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1317 if (!empty() && !d->fontlist_.empty())
1318 return d->fontlist_.begin()->font();
1320 return Font(inherit_font, bparams.language);
1324 // Gets the fully instantiated font at a given position in a paragraph
1325 // This is basically the same function as Text::GetFont() in text2.cpp.
1326 // The difference is that this one is used for generating the LaTeX file,
1327 // and thus cosmetic "improvements" are disallowed: This has to deliver
1328 // the true picture of the buffer. (Asger)
1329 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1330 Font const & outerfont) const
1332 BOOST_ASSERT(pos >= 0);
1334 Font font = getFontSettings(bparams, pos);
1336 pos_type const body_pos = beginOfBody();
1338 font.fontInfo().realize(d->layout_->labelfont);
1340 font.fontInfo().realize(d->layout_->font);
1342 font.fontInfo().realize(outerfont.fontInfo());
1343 font.fontInfo().realize(bparams.getFont().fontInfo());
1349 Font const Paragraph::getLabelFont
1350 (BufferParams const & bparams, Font const & outerfont) const
1352 FontInfo tmpfont = d->layout_->labelfont;
1353 tmpfont.realize(outerfont.fontInfo());
1354 tmpfont.realize(bparams.getFont().fontInfo());
1355 return Font(tmpfont, getParLanguage(bparams));
1359 Font const Paragraph::getLayoutFont
1360 (BufferParams const & bparams, Font const & outerfont) const
1362 FontInfo tmpfont = d->layout_->font;
1363 tmpfont.realize(outerfont.fontInfo());
1364 tmpfont.realize(bparams.getFont().fontInfo());
1365 return Font(tmpfont, getParLanguage(bparams));
1369 /// Returns the height of the highest font in range
1370 FontSize Paragraph::highestFontInRange
1371 (pos_type startpos, pos_type endpos, FontSize def_size) const
1373 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1378 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1380 char_type c = d->text_[pos];
1381 if (!lyxrc.rtl_support)
1411 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1418 void Paragraph::setFont(pos_type pos, Font const & font)
1420 BOOST_ASSERT(pos <= size());
1422 // First, reduce font against layout/label font
1423 // Update: The setCharFont() routine in text2.cpp already
1424 // reduces font, so we don't need to do that here. (Asger)
1426 d->fontlist_.set(pos, font);
1430 void Paragraph::makeSameLayout(Paragraph const & par)
1432 d->layout_ = par.d->layout_;
1433 d->params_ = par.d->params_;
1437 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1439 if (isFreeSpacing())
1445 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1446 if (eraseChar(pos, trackChanges))
1452 return count > 0 || pos > 0;
1456 bool Paragraph::hasSameLayout(Paragraph const & par) const
1458 return par.d->layout_ == d->layout_ && d->params_.sameLayout(par.d->params_);
1462 depth_type Paragraph::getDepth() const
1464 return d->params_.depth();
1468 depth_type Paragraph::getMaxDepthAfter() const
1470 if (d->layout_->isEnvironment())
1471 return d->params_.depth() + 1;
1473 return d->params_.depth();
1477 char Paragraph::getAlign() const
1479 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1480 return d->layout_->align;
1482 return d->params_.align();
1486 docstring const & Paragraph::labelString() const
1488 return d->params_.labelString();
1492 // the next two functions are for the manual labels
1493 docstring const Paragraph::getLabelWidthString() const
1495 if (d->layout_->margintype == MARGIN_MANUAL)
1496 return d->params_.labelWidthString();
1498 return _("Senseless with this layout!");
1502 void Paragraph::setLabelWidthString(docstring const & s)
1504 d->params_.labelWidthString(s);
1508 docstring const Paragraph::translateIfPossible(docstring const & s,
1509 BufferParams const & bparams) const
1511 if (!isAscii(s) || s.empty()) {
1512 // This must be a user defined layout. We cannot translate
1513 // this, since gettext accepts only ascii keys.
1516 // Probably standard layout, try to translate
1517 Messages & m = getMessages(getParLanguage(bparams)->code());
1518 return m.get(to_ascii(s));
1522 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1523 BufferParams const & bparams, bool process_appendix) const
1525 DocumentClass const & tclass = bparams.documentClass();
1528 if (process_appendix && d->params_.appendix())
1529 fmt = translateIfPossible(layout->labelstring_appendix(),
1532 fmt = translateIfPossible(layout->labelstring(), bparams);
1534 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1535 && !layout->counter.empty())
1536 fmt = "\\the" + layout->counter;
1538 // handle 'inherited level parts' in 'fmt',
1539 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1540 size_t const i = fmt.find('@', 0);
1541 if (i != docstring::npos) {
1542 size_t const j = fmt.find('@', i + 1);
1543 if (j != docstring::npos) {
1544 docstring parent(fmt, i + 1, j - i - 1);
1545 docstring label = from_ascii("??");
1546 if (tclass.hasLayout(parent))
1547 docstring label = expandLabel(&(tclass[parent]), bparams,
1549 fmt = docstring(fmt, 0, i) + label
1550 + docstring(fmt, j + 1, docstring::npos);
1554 return tclass.counters().counterLabel(fmt);
1558 void Paragraph::applyLayout(Layout const & new_layout)
1560 d->layout_ = &new_layout;
1561 LyXAlignment const oldAlign = d->params_.align();
1563 if (!(oldAlign & d->layout_->alignpossible)) {
1564 frontend::Alert::warning(_("Alignment not permitted"),
1565 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1566 d->params_.align(LYX_ALIGN_LAYOUT);
1571 pos_type Paragraph::beginOfBody() const
1573 return d->begin_of_body_;
1577 void Paragraph::setBeginOfBody()
1579 if (d->layout_->labeltype != LABEL_MANUAL) {
1580 d->begin_of_body_ = 0;
1584 // Unroll the first two cycles of the loop
1585 // and remember the previous character to
1586 // remove unnecessary getChar() calls
1588 pos_type end = size();
1589 if (i < end && !isNewline(i)) {
1591 char_type previous_char = 0;
1594 previous_char = d->text_[i];
1595 if (!isNewline(i)) {
1597 while (i < end && previous_char != ' ') {
1602 previous_char = temp;
1608 d->begin_of_body_ = i;
1612 bool Paragraph::forceEmptyLayout() const
1614 return inInset() && inInset()->forceEmptyLayout();
1618 bool Paragraph::allowParagraphCustomization() const
1620 return inInset() && inInset()->allowParagraphCustomization(0);
1624 bool Paragraph::useEmptyLayout() const
1626 return inInset() && inInset()->useEmptyLayout();
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(BufferParams const & bparams,
1812 Font const & outerfont,
1813 odocstream & os, TexRow & texrow,
1814 OutputParams const & runparams) const
1816 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1818 bool return_value = false;
1822 bool asdefault = forceEmptyLayout();
1825 style = &(bparams.documentClass().emptyLayout());
1829 // Current base font for all inherited font changes, without any
1830 // change caused by an individual character, except for the language:
1831 // It is set to the language of the first character.
1832 // As long as we are in the label, this font is the base font of the
1833 // label. Before the first body character it is set to the base font
1837 // Maybe we have to create a optional argument.
1838 pos_type body_pos = beginOfBody();
1839 unsigned int column = 0;
1842 // the optional argument is kept in curly brackets in
1843 // case it contains a ']'
1846 basefont = getLabelFont(bparams, outerfont);
1848 basefont = getLayoutFont(bparams, outerfont);
1851 // Which font is currently active?
1852 Font running_font(basefont);
1853 // Do we have an open font change?
1854 bool open_font = false;
1856 Change runningChange = Change(Change::UNCHANGED);
1858 texrow.start(id(), 0);
1860 // if the paragraph is empty, the loop will not be entered at all
1862 if (style->isCommand()) {
1867 column += d->startTeXParParams(bparams, os, texrow,
1868 runparams.moving_arg);
1871 for (pos_type i = 0; i < size(); ++i) {
1872 // First char in paragraph or after label?
1873 if (i == body_pos) {
1876 column += running_font.latexWriteEndChanges(
1877 os, bparams, runparams,
1878 basefont, basefont);
1881 basefont = getLayoutFont(bparams, outerfont);
1882 running_font = basefont;
1884 column += Changes::latexMarkChange(os, bparams,
1885 runningChange, Change(Change::UNCHANGED));
1886 runningChange = Change(Change::UNCHANGED);
1891 if (style->isCommand()) {
1897 column += d->startTeXParParams(bparams, os,
1899 runparams.moving_arg);
1902 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1905 if (bparams.outputChanges && runningChange != change) {
1907 column += running_font.latexWriteEndChanges(
1908 os, bparams, runparams, basefont, basefont);
1911 basefont = getLayoutFont(bparams, outerfont);
1912 running_font = basefont;
1914 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1915 runningChange = change;
1918 // do not output text which is marked deleted
1919 // if change tracking output is disabled
1920 if (!bparams.outputChanges && change.type == Change::DELETED) {
1926 // Fully instantiated font
1927 Font const font = getFont(bparams, i, outerfont);
1929 Font const last_font = running_font;
1931 // Do we need to close the previous font?
1933 (font != running_font ||
1934 font.language() != running_font.language()))
1936 column += running_font.latexWriteEndChanges(
1937 os, bparams, runparams, basefont,
1938 (i == body_pos-1) ? basefont : font);
1939 running_font = basefont;
1943 // close babel's font environment before opening CJK.
1944 if (!running_font.language()->babel().empty() &&
1945 font.language()->encoding()->package() == Encoding::CJK) {
1946 string end_tag = subst(lyxrc.language_command_end,
1948 running_font.language()->babel());
1949 os << from_ascii(end_tag);
1950 column += end_tag.length();
1953 // Switch file encoding if necessary (and allowed)
1954 if (!runparams.verbatim &&
1955 runparams.encoding->package() == Encoding::none &&
1956 font.language()->encoding()->package() == Encoding::none) {
1957 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1958 runparams, *(font.language()->encoding()));
1959 if (enc_switch.first) {
1960 column += enc_switch.second;
1961 runparams.encoding = font.language()->encoding();
1965 char_type const c = d->text_[i];
1967 // Do we need to change font?
1968 if ((font != running_font ||
1969 font.language() != running_font.language()) &&
1972 odocstringstream ods;
1973 column += font.latexWriteStartChanges(ods, bparams,
1974 runparams, basefont,
1976 running_font = font;
1978 docstring fontchange = ods.str();
1979 // check if the fontchange ends with a trailing blank
1980 // (like "\small " (see bug 3382)
1981 if (suffixIs(fontchange, ' ') && c == ' ')
1982 os << fontchange.substr(0, fontchange.size() - 1)
1983 << from_ascii("{}");
1989 // FIXME: integrate this case in latexSpecialChar
1990 // Do not print the separation of the optional argument
1991 // if style->pass_thru is false. This works because
1992 // latexSpecialChar ignores spaces if
1993 // style->pass_thru is false.
1994 if (i != body_pos - 1) {
1995 if (d->simpleTeXBlanks(
1996 runparams, os, texrow,
1997 i, column, font, *style)) {
1998 // A surrogate pair was output. We
1999 // must not call latexSpecialChar
2000 // in this iteration, since it would output
2001 // the combining character again.
2008 OutputParams rp = runparams;
2009 rp.free_spacing = style->free_spacing;
2010 rp.local_font = &font;
2011 rp.intitle = style->intitle;
2013 // Two major modes: LaTeX or plain
2014 // Handle here those cases common to both modes
2015 // and then split to handle the two modes separately.
2016 if (c == META_INSET)
2017 d->latexInset(bparams, os,
2018 texrow, rp, running_font,
2019 basefont, outerfont, open_font,
2020 runningChange, *style, i, column);
2023 d->latexSpecialChar(os, rp, running_font, runningChange,
2025 } catch (EncodingException & e) {
2026 if (runparams.dryrun) {
2027 os << "<" << _("LyX Warning: ")
2028 << _("uncodable character") << " '";
2032 // add location information and throw again.
2040 // Set the encoding to that returned from simpleTeXSpecialChars (see
2041 // comment for encoding member in OutputParams.h)
2042 runparams.encoding = rp.encoding;
2045 // If we have an open font definition, we have to close it
2047 #ifdef FIXED_LANGUAGE_END_DETECTION
2050 .latexWriteEndChanges(os, bparams, runparams,
2052 next_->getFont(bparams, 0, outerfont));
2054 running_font.latexWriteEndChanges(os, bparams,
2055 runparams, basefont, basefont);
2058 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2059 //FIXME: there as we start another \selectlanguage with the next paragraph if
2060 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2061 running_font.latexWriteEndChanges(os, bparams, runparams,
2062 basefont, basefont);
2066 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2068 // Needed if there is an optional argument but no contents.
2069 if (body_pos > 0 && body_pos == size()) {
2071 return_value = false;
2075 column += d->endTeXParParams(bparams, os, texrow,
2076 runparams.moving_arg);
2079 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2080 return return_value;
2084 bool Paragraph::emptyTag() const
2086 for (pos_type i = 0; i < size(); ++i) {
2087 if (Inset const * inset = getInset(i)) {
2088 InsetCode lyx_code = inset->lyxCode();
2089 if (lyx_code != TOC_CODE &&
2090 lyx_code != INCLUDE_CODE &&
2091 lyx_code != GRAPHICS_CODE &&
2092 lyx_code != ERT_CODE &&
2093 lyx_code != LISTINGS_CODE &&
2094 lyx_code != FLOAT_CODE &&
2095 lyx_code != TABULAR_CODE) {
2099 char_type c = d->text_[i];
2100 if (c != ' ' && c != '\t')
2108 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2111 for (pos_type i = 0; i < size(); ++i) {
2112 if (Inset const * inset = getInset(i)) {
2113 InsetCode lyx_code = inset->lyxCode();
2114 if (lyx_code == LABEL_CODE) {
2115 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2116 docstring const & id = il->getParam("name");
2117 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2125 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2129 for (i = 0; i < size(); ++i) {
2130 if (Inset const * inset = getInset(i)) {
2131 inset->docbook(os, runparams);
2133 char_type c = d->text_[i];
2136 os << sgml::escapeChar(c);
2143 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2146 pos_type size = text_.size();
2147 for (pos_type i = initial; i < size; ++i) {
2148 Font font = owner_->getFont(buf.params(), i, outerfont);
2149 if (text_[i] == META_INSET)
2151 if (i != initial && font != font_old)
2160 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2162 OutputParams const & runparams,
2163 Font const & outerfont,
2164 pos_type initial) const
2166 bool emph_flag = false;
2168 LayoutPtr const & style = d->layout_;
2170 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2172 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2175 // parsing main loop
2176 for (pos_type i = initial; i < size(); ++i) {
2177 Font font = getFont(buf.params(), i, outerfont);
2179 // handle <emphasis> tag
2180 if (font_old.emph() != font.fontInfo().emph()) {
2181 if (font.fontInfo().emph() == FONT_ON) {
2184 } else if (i != initial) {
2185 os << "</emphasis>";
2190 if (Inset const * inset = getInset(i)) {
2191 inset->docbook(os, runparams);
2193 char_type c = d->text_[i];
2195 if (style->pass_thru)
2198 os << sgml::escapeChar(c);
2200 font_old = font.fontInfo();
2204 os << "</emphasis>";
2207 if (style->free_spacing)
2209 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2214 bool Paragraph::isHfill(pos_type pos) const
2216 Inset const * inset = getInset(pos);
2217 return inset && inset->lyxCode() == HFILL_CODE;
2221 bool Paragraph::isNewline(pos_type pos) const
2223 Inset const * inset = getInset(pos);
2224 return inset && inset->lyxCode() == NEWLINE_CODE;
2228 bool Paragraph::isLineSeparator(pos_type pos) const
2230 char_type const c = d->text_[pos];
2231 if (isLineSeparatorChar(c))
2233 Inset const * inset = getInset(pos);
2234 return inset && inset->isLineSeparator();
2238 /// Used by the spellchecker
2239 bool Paragraph::isLetter(pos_type pos) const
2241 if (Inset const * inset = getInset(pos))
2242 return inset->isLetter();
2243 char_type const c = d->text_[pos];
2244 return isLetterChar(c) || isDigit(c);
2249 Paragraph::getParLanguage(BufferParams const & bparams) const
2252 return getFirstFontSettings(bparams).language();
2253 // FIXME: we should check the prev par as well (Lgb)
2254 return bparams.language;
2258 bool Paragraph::isRTL(BufferParams const & bparams) const
2260 return lyxrc.rtl_support
2261 && getParLanguage(bparams)->rightToLeft()
2262 && ownerCode() != ERT_CODE
2263 && ownerCode() != LISTINGS_CODE;
2267 void Paragraph::changeLanguage(BufferParams const & bparams,
2268 Language const * from, Language const * to)
2270 // change language including dummy font change at the end
2271 for (pos_type i = 0; i <= size(); ++i) {
2272 Font font = getFontSettings(bparams, i);
2273 if (font.language() == from) {
2274 font.setLanguage(to);
2281 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2283 Language const * doc_language = bparams.language;
2284 FontList::const_iterator cit = d->fontlist_.begin();
2285 FontList::const_iterator end = d->fontlist_.end();
2287 for (; cit != end; ++cit)
2288 if (cit->font().language() != ignore_language &&
2289 cit->font().language() != latex_language &&
2290 cit->font().language() != doc_language)
2296 docstring Paragraph::asString(bool label) const
2298 return asString(0, size(), label);
2302 docstring Paragraph::asString(pos_type beg, pos_type end, bool label) const
2305 odocstringstream os;
2307 if (beg == 0 && label && !d->params_.labelString().empty())
2308 os << d->params_.labelString() << ' ';
2310 for (pos_type i = beg; i < end; ++i) {
2311 char_type const c = d->text_[i];
2314 else if (c == META_INSET)
2315 getInset(i)->textString(os);
2322 void Paragraph::setInsetOwner(Inset * inset)
2324 d->inset_owner_ = inset;
2328 int Paragraph::id() const
2334 LayoutPtr const & Paragraph::layout() const
2340 void Paragraph::setLayout(LayoutPtr const & layout)
2342 d->layout_ = layout;
2346 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2348 if (useEmptyLayout())
2349 setLayout(tclass.emptyLayout());
2351 setLayout(tclass.defaultLayout());
2355 Inset * Paragraph::inInset() const
2357 return d->inset_owner_;
2361 InsetCode Paragraph::ownerCode() const
2363 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2367 ParagraphParameters & Paragraph::params()
2373 ParagraphParameters const & Paragraph::params() const
2379 bool Paragraph::isFreeSpacing() const
2381 if (d->layout_->free_spacing)
2383 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2387 bool Paragraph::allowEmpty() const
2389 if (d->layout_->keepempty)
2391 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2395 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2397 if (!Encodings::is_arabic(c))
2400 char_type prev_char = ' ';
2401 char_type next_char = ' ';
2403 for (pos_type i = pos - 1; i >= 0; --i) {
2404 char_type const par_char = d->text_[i];
2405 if (!Encodings::isComposeChar_arabic(par_char)) {
2406 prev_char = par_char;
2411 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2412 char_type const par_char = d->text_[i];
2413 if (!Encodings::isComposeChar_arabic(par_char)) {
2414 next_char = par_char;
2419 if (Encodings::is_arabic(next_char)) {
2420 if (Encodings::is_arabic(prev_char) &&
2421 !Encodings::is_arabic_special(prev_char))
2422 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2424 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2426 if (Encodings::is_arabic(prev_char) &&
2427 !Encodings::is_arabic_special(prev_char))
2428 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2430 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2435 int Paragraph::checkBiblio(Buffer const & buffer)
2438 // This is getting more and more a mess. ...We really should clean
2439 // up this bibitem issue for 1.6. See also bug 2743.
2441 // Add bibitem insets if necessary
2442 if (d->layout_->labeltype != LABEL_BIBLIO)
2445 bool hasbibitem = !d->insetlist_.empty()
2446 // Insist on it being in pos 0
2447 && d->text_[0] == META_INSET
2448 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2450 bool track_changes = buffer.params().trackChanges;
2455 // remove a bibitem in pos != 0
2456 // restore it later in pos 0 if necessary
2457 // (e.g. if a user inserts contents _before_ the item)
2458 // we're assuming there's only one of these, which there
2460 int erasedInsetPosition = -1;
2461 InsetList::iterator it = d->insetlist_.begin();
2462 InsetList::iterator end = d->insetlist_.end();
2463 for (; it != end; ++it)
2464 if (it->inset->lyxCode() == BIBITEM_CODE
2466 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2467 oldkey = olditem->getParam("key");
2468 oldlabel = olditem->getParam("label");
2469 erasedInsetPosition = it->pos;
2470 eraseChar(erasedInsetPosition, track_changes);
2474 // There was an InsetBibitem at the beginning, and we didn't
2475 // have to erase one.
2476 if (hasbibitem && erasedInsetPosition < 0)
2479 // There was an InsetBibitem at the beginning and we did have to
2480 // erase one. So we give its properties to the beginning inset.
2482 InsetBibitem * inset =
2483 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2484 if (!oldkey.empty())
2485 inset->setParam("key", oldkey);
2486 inset->setParam("label", oldlabel);
2487 return -erasedInsetPosition;
2490 // There was no inset at the beginning, so we need to create one with
2491 // the key and label of the one we erased.
2492 InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2493 inset->setBuffer(const_cast<Buffer &>(buffer));
2494 // restore values of previously deleted item in this par.
2495 if (!oldkey.empty())
2496 inset->setParam("key", oldkey);
2497 inset->setParam("label", oldlabel);
2498 insertInset(0, static_cast<Inset *>(inset),
2499 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2505 void Paragraph::checkAuthors(AuthorList const & authorList)
2507 d->changes_.checkAuthors(authorList);
2511 bool Paragraph::isUnchanged(pos_type pos) const
2513 return lookupChange(pos).type == Change::UNCHANGED;
2517 bool Paragraph::isInserted(pos_type pos) const
2519 return lookupChange(pos).type == Change::INSERTED;
2523 bool Paragraph::isDeleted(pos_type pos) const
2525 return lookupChange(pos).type == Change::DELETED;
2529 InsetList const & Paragraph::insetList() const
2531 return d->insetlist_;
2535 Inset * Paragraph::releaseInset(pos_type pos)
2537 Inset * inset = d->insetlist_.release(pos);
2538 /// does not honour change tracking!
2539 eraseChar(pos, false);
2544 Inset * Paragraph::getInset(pos_type pos)
2546 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2547 ? d->insetlist_.get(pos) : 0;
2551 Inset const * Paragraph::getInset(pos_type pos) const
2553 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2554 ? d->insetlist_.get(pos) : 0;
2558 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2559 pos_type & right, TextCase action)
2561 // process sequences of modified characters; in change
2562 // tracking mode, this approach results in much better
2563 // usability than changing case on a char-by-char basis
2566 bool const trackChanges = bparams.trackChanges;
2568 bool capitalize = true;
2570 for (; pos < right; ++pos) {
2571 char_type oldChar = d->text_[pos];
2572 char_type newChar = oldChar;
2574 // ignore insets and don't play with deleted text!
2575 if (oldChar != META_INSET && !isDeleted(pos)) {
2577 case text_lowercase:
2578 newChar = lowercase(oldChar);
2580 case text_capitalization:
2582 newChar = uppercase(oldChar);
2586 case text_uppercase:
2587 newChar = uppercase(oldChar);
2592 if (!isLetter(pos) || isDeleted(pos)) {
2593 // permit capitalization again
2597 if (oldChar != newChar)
2600 if (oldChar == newChar || pos == right - 1) {
2601 if (oldChar != newChar) {
2602 // step behind the changing area
2605 int erasePos = pos - changes.size();
2606 for (size_t i = 0; i < changes.size(); i++) {
2607 insertChar(pos, changes[i],
2608 getFontSettings(bparams,
2611 if (!eraseChar(erasePos, trackChanges)) {
2614 ++right; // expand selection
2623 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2624 pos_type pos, bool del) const
2626 int const strsize = str.length();
2628 pos_type const parsize = d->text_.size();
2629 for (i = 0; pos + i < parsize; ++i) {
2632 if (cs && str[i] != d->text_[pos + i])
2634 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2636 if (!del && isDeleted(pos + i))
2643 // if necessary, check whether string matches word
2645 if (pos > 0 && isLetter(pos - 1))
2647 if (pos + strsize < parsize
2648 && isLetter(pos + strsize))
2656 char_type Paragraph::getChar(pos_type pos) const
2658 return d->text_[pos];
2662 pos_type Paragraph::size() const
2664 return d->text_.size();
2668 bool Paragraph::empty() const
2670 return d->text_.empty();
2674 bool Paragraph::isInset(pos_type pos) const
2676 return d->text_[pos] == META_INSET;
2680 bool Paragraph::isSeparator(pos_type pos) const
2682 //FIXME: Are we sure this can be the only separator?
2683 return d->text_[pos] == ' ';
2687 void Paragraph::deregisterWords()
2689 Private::Words::const_iterator it;
2690 WordList & wl = theWordList();
2691 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2697 void Paragraph::collectWords(CursorSlice const & sl)
2700 bool inword = false;
2702 //lyxerr << "Words: ";
2703 pos_type n = size();
2704 for (pos_type pos = 0; pos != n; ++pos) {
2708 if (!isLetter(pos)) {
2717 CursorSlice from = sl;
2718 CursorSlice to = sl;
2721 from.text()->getWord(from, to, WHOLE_WORD);
2722 if (to.pos() - from.pos() < 6)
2724 docstring word = asString(from.pos(), to.pos(), false);
2725 d->words_.insert(word);
2726 //lyxerr << word << " ";
2728 //lyxerr << std::endl;
2732 void Paragraph::registerWords()
2734 Private::Words::const_iterator it;
2735 WordList & wl = theWordList();
2736 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2741 void Paragraph::updateWords(CursorSlice const & sl)
2743 BOOST_ASSERT(&sl.paragraph() == this);