3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
23 #include "BufferParams.h"
27 #include "InsetList.h"
29 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "paragraph_funcs.h"
38 #include "ParagraphParameters.h"
40 #include "TextClass.h"
44 #include "frontends/alert.h"
45 #include "frontends/FontMetrics.h"
47 #include "insets/InsetBibitem.h"
48 #include "insets/InsetLabel.h"
50 #include "support/convert.h"
51 #include "support/debug.h"
52 #include "support/gettext.h"
53 #include "support/lstrings.h"
54 #include "support/Messages.h"
55 #include "support/textutils.h"
56 #include "support/unicode.h"
62 using namespace lyx::support;
67 /// Inset identifier (above 0x10ffff, for ucs-4)
68 char_type const META_INSET = 0x200001;
71 /////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////
77 class Paragraph::Private
81 Private(Paragraph * owner);
82 /// "Copy constructor"
83 Private(Private const &, Paragraph * owner);
86 void insertChar(pos_type pos, char_type c, Change const & change);
88 /// Output the surrogate pair formed by \p c and \p next to \p os.
89 /// \return the number of characters written.
90 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
93 /// Output a space in appropriate formatting (or a surrogate pair
94 /// if the next character is a combining character).
95 /// \return whether a surrogate pair was output.
96 bool simpleTeXBlanks(OutputParams const &,
97 odocstream &, TexRow & texrow,
99 unsigned int & column,
101 Layout const & style);
103 /// Output consecutive unicode chars, belonging to the same script as
104 /// specified by the latex macro \p ltx, to \p os starting from \p i.
105 /// \return the number of characters written.
106 int writeScriptChars(odocstream & os, docstring const & ltx,
107 Change &, Encoding const &, pos_type & i);
109 /// This could go to ParagraphParameters if we want to.
110 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
113 /// This could go to ParagraphParameters if we want to.
114 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 void latexInset(Buffer const &, BufferParams const &,
120 TexRow & texrow, OutputParams &,
123 Font const & outerfont,
125 Change & running_change,
126 Layout const & style,
128 unsigned int & column);
131 void latexSpecialChar(
133 OutputParams & runparams,
135 Change & running_change,
136 Layout const & style,
138 unsigned int & column);
145 unsigned int & column);
147 bool latexSpecialTypewriter(
151 unsigned int & column);
153 bool latexSpecialPhrase(
156 unsigned int & column,
157 OutputParams & runparams);
160 void validate(LaTeXFeatures & features,
161 Layout const & layout) const;
163 /// Checks if the paragraph contains only text and no inset or font change.
164 bool onlyText(Buffer const & buf, Font const & outerfont,
165 pos_type initial) const;
167 /// match a string against a particular point in the paragraph
168 bool isTextAt(std::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 /// position of the paragraph in the buffer. Only macros from
187 /// paragraphs strictly smaller are visible in this paragraph
188 unsigned int macrocontext_position_;
190 /// for recording and looking up changes
194 InsetList insetlist_;
200 pos_type begin_of_body_;
202 typedef docstring TextContainer;
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++;
235 macrocontext_position_ = 0;
240 Paragraph::Private::Private(Private const & p, Paragraph * owner)
241 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
242 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
243 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 {
259 // keep the logic here in sync with the logic of eraseChars()
265 Change change = d->changes_.lookup(size());
267 return change.type == Change::INSERTED && change.author == 0;
271 void Paragraph::setChange(Change const & change)
273 // beware of the imaginary end-of-par character!
274 d->changes_.set(change, 0, size() + 1);
277 * Propagate the change recursively - but not in case of DELETED!
279 * Imagine that your co-author makes changes in an existing inset. He
280 * sends your document to you and you come to the conclusion that the
281 * inset should go completely. If you erase it, LyX must not delete all
282 * text within the inset. Otherwise, the change tracked insertions of
283 * your co-author get lost and there is no way to restore them later.
285 * Conclusion: An inset's content should remain untouched if you delete it
288 if (change.type != Change::DELETED) {
289 for (pos_type pos = 0; pos < size(); ++pos) {
291 getInset(pos)->setChange(change);
297 void Paragraph::setChange(pos_type pos, Change const & change)
299 BOOST_ASSERT(pos >= 0 && pos <= size());
301 d->changes_.set(change, pos);
303 // see comment in setChange(Change const &) above
305 if (change.type != Change::DELETED &&
306 pos < size() && isInset(pos)) {
307 getInset(pos)->setChange(change);
312 Change const & Paragraph::lookupChange(pos_type pos) const
314 BOOST_ASSERT(pos >= 0 && pos <= size());
316 return d->changes_.lookup(pos);
320 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
323 BOOST_ASSERT(start >= 0 && start <= size());
324 BOOST_ASSERT(end > start && end <= size() + 1);
326 for (pos_type pos = start; pos < end; ++pos) {
327 switch (lookupChange(pos).type) {
328 case Change::UNCHANGED:
329 // accept changes in nested inset
330 if (pos < size() && isInset(pos))
331 getInset(pos)->acceptChanges(bparams);
335 case Change::INSERTED:
336 d->changes_.set(Change(Change::UNCHANGED), pos);
337 // also accept changes in nested inset
338 if (pos < size() && isInset(pos)) {
339 getInset(pos)->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 (pos < size() && isInset(pos)) {
369 getInset(pos)->rejectChanges(bparams);
373 case Change::INSERTED:
374 // Suppress access to non-existent
375 // "end-of-paragraph char"
377 eraseChar(pos, false);
383 case Change::DELETED:
384 d->changes_.set(Change(Change::UNCHANGED), pos);
386 // Do NOT reject changes within a deleted inset!
387 // There may be insertions of a co-author inside of it!
395 void Paragraph::Private::insertChar(pos_type pos, char_type c,
396 Change const & change)
398 BOOST_ASSERT(pos >= 0 && pos <= int(text_.size()));
401 changes_.insert(change, pos);
403 // This is actually very common when parsing buffers (and
404 // maybe inserting ascii text)
405 if (pos == pos_type(text_.size())) {
406 // when appending characters, no need to update tables
411 text_.insert(text_.begin() + pos, c);
413 // Update the font table.
414 fontlist_.increasePosAfterPos(pos);
417 insetlist_.increasePosAfterPos(pos);
421 void Paragraph::insertInset(pos_type pos, Inset * inset,
422 Change const & change)
425 BOOST_ASSERT(pos >= 0 && pos <= size());
427 d->insertChar(pos, META_INSET, change);
428 BOOST_ASSERT(d->text_[pos] == META_INSET);
430 // Add a new entry in the insetlist_.
431 d->insetlist_.insert(inset, pos);
435 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
437 BOOST_ASSERT(pos >= 0 && pos <= size());
439 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
442 Change change = d->changes_.lookup(pos);
444 // set the character to DELETED if
445 // a) it was previously unchanged or
446 // b) it was inserted by a co-author
448 if (change.type == Change::UNCHANGED ||
449 (change.type == Change::INSERTED && change.author != 0)) {
450 setChange(pos, Change(Change::DELETED));
454 if (change.type == Change::DELETED)
458 // Don't physically access the imaginary end-of-paragraph character.
459 // eraseChar() can only mark it as DELETED. A physical deletion of
460 // end-of-par must be handled externally.
466 d->changes_.erase(pos);
468 // if it is an inset, delete the inset entry
469 if (d->text_[pos] == META_INSET)
470 d->insetlist_.erase(pos);
472 d->text_.erase(d->text_.begin() + pos);
474 // Update the fontlist_
475 d->fontlist_.erase(pos);
477 // Update the insetlist_
478 d->insetlist_.decreasePosAfterPos(pos);
484 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
486 BOOST_ASSERT(start >= 0 && start <= size());
487 BOOST_ASSERT(end >= start && end <= size() + 1);
490 for (pos_type count = end - start; count; --count) {
491 if (!eraseChar(i, trackChanges))
498 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
499 char_type next, Encoding const & encoding)
501 // Writing next here may circumvent a possible font change between
502 // c and next. Since next is only output if it forms a surrogate pair
503 // with c we can ignore this:
504 // A font change inside a surrogate pair does not make sense and is
505 // hopefully impossible to input.
506 // FIXME: change tracking
507 // Is this correct WRT change tracking?
508 docstring const latex1 = encoding.latexChar(next);
509 docstring const latex2 = encoding.latexChar(c);
510 os << latex1 << '{' << latex2 << '}';
511 return latex1.length() + latex2.length() + 2;
515 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
516 odocstream & os, TexRow & texrow,
518 unsigned int & column,
520 Layout const & style)
522 if (style.pass_thru || runparams.verbatim)
525 if (i + 1 < int(text_.size())) {
526 char_type next = text_[i + 1];
527 if (Encodings::isCombiningChar(next)) {
528 Encoding const & encoding = *(runparams.encoding);
529 // This space has an accent, so we must always output it.
530 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
535 if (lyxrc.plaintext_linelen > 0
536 && column > lyxrc.plaintext_linelen
538 && text_[i - 1] != ' '
539 && (i + 1 < int(text_.size()))
540 // same in FreeSpacing mode
541 && !owner_->isFreeSpacing()
542 // In typewriter mode, we want to avoid
543 // ! . ? : at the end of a line
544 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
545 && (text_[i - 1] == '.'
546 || text_[i - 1] == '?'
547 || text_[i - 1] == ':'
548 || text_[i - 1] == '!'))) {
551 texrow.start(owner_->id(), i + 1);
553 } else if (style.free_spacing) {
562 int Paragraph::Private::writeScriptChars(odocstream & os,
563 docstring const & ltx,
564 Change & runningChange,
565 Encoding const & encoding,
568 // FIXME: modifying i here is not very nice...
570 // We only arrive here when a proper language for character text_[i] has
571 // not been specified (i.e., it could not be translated in the current
572 // latex encoding) and it belongs to a known script.
573 // Parameter ltx contains the latex translation of text_[i] as specified in
574 // the unicodesymbols file and is something like "\textXXX{<spec>}".
575 // The latex macro name "textXXX" specifies the script to which text_[i]
576 // belongs and we use it in order to check whether characters from the
577 // same script immediately follow, such that we can collect them in a
578 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
579 // for the first char but only "<spec>" for all subsequent chars.
580 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
581 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
582 string script = to_ascii(ltx.substr(1, brace1 - 1));
583 int length = ltx.substr(0, brace2).length();
584 os << ltx.substr(0, brace2);
585 int size = text_.size();
586 while (i + 1 < size) {
587 char_type const next = text_[i + 1];
588 // Stop here if next character belongs to another script
589 // or there is a change in change tracking status.
590 if (!Encodings::isKnownScriptChar(next, script) ||
591 runningChange != owner_->lookupChange(i + 1))
595 FontList::const_iterator cit = fontlist_.begin();
596 FontList::const_iterator end = fontlist_.end();
597 for (; cit != end; ++cit) {
598 if (cit->pos() >= i && !found) {
599 prev_font = cit->font();
602 if (cit->pos() >= i + 1)
605 // Stop here if there is a font attribute or encoding change.
606 if (found && cit != end && prev_font != cit->font())
608 docstring const latex = encoding.latexChar(next);
609 docstring::size_type const b1 =
610 latex.find_first_of(from_ascii("{"));
611 docstring::size_type const b2 =
612 latex.find_last_of(from_ascii("}"));
613 int const len = b2 - b1 - 1;
614 os << latex.substr(b1 + 1, len);
624 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
626 pos_type const len = str.length();
628 // is the paragraph large enough?
629 if (pos + len > int(text_.size()))
632 // does the wanted text start at point?
633 for (string::size_type i = 0; i < str.length(); ++i) {
634 // Caution: direct comparison of characters works only
635 // because str is pure ASCII.
636 if (str[i] != text_[pos + i])
640 return fontlist_.hasChangeInRange(pos, len);
644 void Paragraph::Private::latexInset(Buffer const & buf,
645 BufferParams const & bparams,
648 OutputParams & runparams,
651 Font const & outerfont,
653 Change & running_change,
654 Layout const & style,
656 unsigned int & column)
658 Inset * inset = owner_->getInset(i);
661 if (style.pass_thru) {
662 inset->plaintext(buf, os, runparams);
666 // FIXME: move this to InsetNewline::latex
667 if (inset->lyxCode() == NEWLINE_CODE) {
668 // newlines are handled differently here than
669 // the default in simpleTeXSpecialChars().
670 if (!style.newline_allowed) {
674 column += running_font.latexWriteEndChanges(
675 os, bparams, runparams,
680 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
683 basefont = owner_->getLayoutFont(bparams, outerfont);
684 running_font = basefont;
686 if (runparams.moving_arg)
691 texrow.start(owner_->id(), i + 1);
695 if (owner_->lookupChange(i).type == Change::DELETED) {
696 if( ++runparams.inDeletedInset == 1)
697 runparams.changeOfDeletedInset = owner_->lookupChange(i);
700 if (inset->canTrackChanges()) {
701 column += Changes::latexMarkChange(os, bparams, running_change,
702 Change(Change::UNCHANGED));
703 running_change = Change(Change::UNCHANGED);
707 odocstream::pos_type const len = os.tellp();
709 if (inset->forceLTR()
710 && running_font.isRightToLeft()
711 // ERT is an exception, it should be output with no decorations at all
712 && inset->lyxCode() != ERT_CODE) {
713 if (running_font.language()->lang() == "farsi")
720 // FIXME: Bug: we can have an empty font change here!
721 // if there has just been a font change, we are going to close it
722 // right now, which means stupid latex code like \textsf{}. AFAIK,
723 // this does not harm dvi output. A minor bug, thus (JMarc)
725 // Some insets cannot be inside a font change command.
726 // However, even such insets *can* be placed in \L or \R
727 // or their equivalents (for RTL language switches), so we don't
728 // close the language in those cases.
729 // ArabTeX, though, cannot handle this special behavior, it seems.
730 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
731 || running_font.language()->lang() == "arabic_arabtex";
732 if (open_font && inset->noFontChange()) {
733 bool closeLanguage = arabtex
734 || basefont.isRightToLeft() == running_font.isRightToLeft();
735 unsigned int count = running_font.latexWriteEndChanges(os,
736 bparams, runparams, basefont, basefont, closeLanguage);
738 // if any font properties were closed, update the running_font,
739 // making sure, however, to leave the language as it was
741 // FIXME: probably a better way to keep track of the old
742 // language, than copying the entire font?
743 Font const copy_font(running_font);
744 basefont = owner_->getLayoutFont(bparams, outerfont);
745 running_font = basefont;
747 running_font.setLanguage(copy_font.language());
748 // leave font open if language is still open
749 open_font = (running_font.language() == basefont.language());
751 runparams.local_font = &basefont;
755 int tmp = inset->latex(buf, os, runparams);
758 if (running_font.language()->lang() == "farsi")
765 for (int j = 0; j < tmp; ++j)
768 texrow.start(owner_->id(), i + 1);
771 column += os.tellp() - len;
774 if (owner_->lookupChange(i).type == Change::DELETED)
775 --runparams.inDeletedInset;
779 void Paragraph::Private::latexSpecialChar(
781 OutputParams & runparams,
783 Change & running_change,
784 Layout const & style,
786 unsigned int & column)
788 char_type const c = text_[i];
790 if (style.pass_thru) {
792 // FIXME UNICODE: This can fail if c cannot
793 // be encoded in the current encoding.
798 if (runparams.verbatim) {
803 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
806 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
807 && latexSpecialTypewriter(c, os, i, column))
810 // Otherwise, we use what LaTeX provides us.
813 os << "\\textbackslash{}";
817 os << "\\textless{}";
821 os << "\\textgreater{}";
832 os << "\\char`\\\"{}";
837 case '%': case '#': case '{':
845 os << "\\textasciitilde{}";
850 os << "\\textasciicircum{}";
855 // avoid being mistaken for optional arguments
863 // Blanks are printed before font switching.
864 // Sure? I am not! (try nice-latex)
865 // I am sure it's correct. LyX might be smarter
866 // in the future, but for now, nothing wrong is
873 if (latexSpecialPhrase(os, i, column, runparams))
879 Encoding const & encoding = *(runparams.encoding);
880 if (i + 1 < int(text_.size())) {
881 char_type next = text_[i + 1];
882 if (Encodings::isCombiningChar(next)) {
883 column += latexSurrogatePair(os, c, next, encoding) - 1;
889 docstring const latex = encoding.latexChar(c);
890 if (Encodings::isKnownScriptChar(c, script)
891 && prefixIs(latex, from_ascii("\\" + script)))
892 column += writeScriptChars(os, latex,
893 running_change, encoding, i) - 1;
894 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
895 // Prevent eating of a following
896 // space or command corruption by
897 // following characters
898 column += latex.length() + 1;
901 column += latex.length() - 1;
909 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
910 pos_type & i, unsigned int & column)
916 // In T1 encoding, these characters exist
917 // but we should avoid ligatures
918 if (i + 1 > int(text_.size()) || text_[i + 1] != c)
923 //os << "\\textcompwordmark{}";
935 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
936 pos_type & i, unsigned int & column)
940 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
941 // "--" in Typewriter mode -> "-{}-"
948 // I assume this is hack treating typewriter as verbatim
949 // FIXME UNICODE: This can fail if c cannot be encoded
950 // in the current encoding.
955 // Those characters are not directly supported.
959 case '%': case '#': case '{':
968 // With Typewriter font, these characters exist.
975 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
976 unsigned int & column, OutputParams & runparams)
978 // FIXME: if we have "LaTeX" with a font
979 // change in the middle (before the 'T', then
980 // the "TeX" part is still special cased.
981 // Really we should only operate this on
982 // "words" for some definition of word
984 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
985 if (!isTextAt(special_phrases[pnr].phrase, i))
987 if (runparams.moving_arg)
989 os << special_phrases[pnr].macro;
990 i += special_phrases[pnr].phrase.length() - 1;
991 column += special_phrases[pnr].macro.length() - 1;
998 void Paragraph::Private::validate(LaTeXFeatures & features,
999 Layout const & layout) const
1001 // check the params.
1002 if (!params_.spacing().isDefault())
1003 features.require("setspace");
1006 features.useLayout(layout.name());
1009 fontlist_.validate(features);
1011 // then the indentation
1012 if (!params_.leftIndent().zero())
1013 features.require("ParagraphLeftIndent");
1016 InsetList::const_iterator icit = insetlist_.begin();
1017 InsetList::const_iterator iend = insetlist_.end();
1018 for (; icit != iend; ++icit) {
1020 icit->inset->validate(features);
1021 if (layout.needprotect &&
1022 icit->inset->lyxCode() == FOOT_CODE)
1023 features.require("NeedLyXFootnoteCode");
1027 // then the contents
1028 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1029 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1030 if (!special_phrases[pnr].builtin
1031 && isTextAt(special_phrases[pnr].phrase, i)) {
1032 features.require(special_phrases[pnr].phrase);
1036 Encodings::validate(text_[i], features);
1040 /////////////////////////////////////////////////////////////////////
1044 /////////////////////////////////////////////////////////////////////
1046 Paragraph::Paragraph()
1047 : d(new Paragraph::Private(this))
1054 Paragraph::Paragraph(Paragraph const & par)
1055 : itemdepth(par.itemdepth),
1056 d(new Paragraph::Private(*par.d, this))
1061 Paragraph & Paragraph::operator=(Paragraph const & par)
1063 // needed as we will destroy the private part before copying it
1065 itemdepth = par.itemdepth;
1068 d = new Private(*par.d, this);
1074 Paragraph::~Paragraph()
1080 void Paragraph::write(Buffer const & buf, ostream & os,
1081 BufferParams const & bparams,
1082 depth_type & dth) const
1084 // The beginning or end of a deeper (i.e. nested) area?
1085 if (dth != params().depth()) {
1086 if (params().depth() > dth) {
1087 while (params().depth() > dth) {
1088 os << "\n\\begin_deeper";
1092 while (params().depth() < dth) {
1093 os << "\n\\end_deeper";
1099 // First write the layout
1100 os << "\n\\begin_layout " << to_utf8(layout()->name()) << '\n';
1104 Font font1(inherit_font, bparams.language);
1106 Change running_change = Change(Change::UNCHANGED);
1109 for (pos_type i = 0; i <= size(); ++i) {
1111 Change change = lookupChange(i);
1112 Changes::lyxMarkChange(os, column, running_change, change);
1113 running_change = change;
1118 // Write font changes
1119 Font font2 = getFontSettings(bparams, i);
1120 if (font2 != font1) {
1121 font2.lyxWriteChanges(font1, os);
1126 char_type const c = d->text_[i];
1130 Inset const * inset = getInset(i);
1132 if (inset->directWrite()) {
1133 // international char, let it write
1134 // code directly so it's shorter in
1136 inset->write(buf, os);
1140 os << "\\begin_inset ";
1141 inset->write(buf, os);
1142 os << "\n\\end_inset\n\n";
1148 os << "\n\\backslash\n";
1152 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1159 if ((column > 70 && c == ' ')
1164 // this check is to amend a bug. LyX sometimes
1165 // inserts '\0' this could cause problems.
1167 std::vector<char> tmp = ucs4_to_utf8(c);
1168 tmp.push_back('\0');
1171 lyxerr << "ERROR (Paragraph::writeFile):"
1172 " NULL char in structure." << endl;
1178 os << "\n\\end_layout\n";
1182 void Paragraph::validate(LaTeXFeatures & features) const
1184 d->validate(features, *layout());
1188 void Paragraph::insert(pos_type start, docstring const & str,
1189 Font const & font, Change const & change)
1191 for (size_t i = 0, n = str.size(); i != n ; ++i)
1192 insertChar(start + i, str[i], font, change);
1196 void Paragraph::appendChar(char_type c, Font const & font,
1197 Change const & change)
1200 d->changes_.insert(change, d->text_.size());
1201 // when appending characters, no need to update tables
1202 d->text_.push_back(c);
1203 setFont(d->text_.size() - 1, font);
1207 void Paragraph::appendString(docstring const & s, Font const & font,
1208 Change const & change)
1210 pos_type end = s.size();
1211 size_t oldsize = d->text_.size();
1212 size_t newsize = oldsize + end;
1213 size_t capacity = d->text_.capacity();
1214 if (newsize >= capacity)
1215 d->text_.reserve(std::max(capacity + 100, newsize));
1217 // when appending characters, no need to update tables
1220 // FIXME: Optimize this!
1221 for (pos_type i = 0; i != end; ++i) {
1223 d->changes_.insert(change, i);
1225 d->fontlist_.set(oldsize, font);
1226 d->fontlist_.set(newsize - 1, font);
1230 void Paragraph::insertChar(pos_type pos, char_type c,
1233 d->insertChar(pos, c, Change(trackChanges ?
1234 Change::INSERTED : Change::UNCHANGED));
1238 void Paragraph::insertChar(pos_type pos, char_type c,
1239 Font const & font, bool trackChanges)
1241 d->insertChar(pos, c, Change(trackChanges ?
1242 Change::INSERTED : Change::UNCHANGED));
1247 void Paragraph::insertChar(pos_type pos, char_type c,
1248 Font const & font, Change const & change)
1250 d->insertChar(pos, c, change);
1255 void Paragraph::insertInset(pos_type pos, Inset * inset,
1256 Font const & font, Change const & change)
1258 insertInset(pos, inset, change);
1259 // Set the font/language of the inset...
1264 bool Paragraph::insetAllowed(InsetCode code)
1266 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1270 void Paragraph::resetFonts(Font const & font)
1272 d->fontlist_.clear();
1273 d->fontlist_.set(0, font);
1274 d->fontlist_.set(d->text_.size() - 1, font);
1277 // Gets uninstantiated font setting at position.
1278 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1282 lyxerr << " pos: " << pos << " size: " << size() << endl;
1283 BOOST_ASSERT(pos <= size());
1286 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1287 if (cit != d->fontlist_.end())
1290 if (pos == size() && !empty())
1291 return getFontSettings(bparams, pos - 1);
1293 return Font(inherit_font, getParLanguage(bparams));
1297 FontSpan Paragraph::fontSpan(pos_type pos) const
1299 BOOST_ASSERT(pos <= size());
1302 FontList::const_iterator cit = d->fontlist_.begin();
1303 FontList::const_iterator end = d->fontlist_.end();
1304 for (; cit != end; ++cit) {
1305 if (cit->pos() >= pos) {
1306 if (pos >= beginOfBody())
1307 return FontSpan(std::max(start, beginOfBody()),
1310 return FontSpan(start,
1311 std::min(beginOfBody() - 1,
1314 start = cit->pos() + 1;
1317 // This should not happen, but if so, we take no chances.
1318 //lyxerr << "Paragraph::getEndPosOfFontSpan: This should not happen!"
1320 return FontSpan(pos, pos);
1324 // Gets uninstantiated font setting at position 0
1325 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1327 if (!empty() && !d->fontlist_.empty())
1328 return d->fontlist_.begin()->font();
1330 return Font(inherit_font, bparams.language);
1334 // Gets the fully instantiated font at a given position in a paragraph
1335 // This is basically the same function as Text::GetFont() in text2.cpp.
1336 // The difference is that this one is used for generating the LaTeX file,
1337 // and thus cosmetic "improvements" are disallowed: This has to deliver
1338 // the true picture of the buffer. (Asger)
1339 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1340 Font const & outerfont) const
1342 BOOST_ASSERT(pos >= 0);
1344 Font font = getFontSettings(bparams, pos);
1346 pos_type const body_pos = beginOfBody();
1348 font.fontInfo().realize(d->layout_->labelfont);
1350 font.fontInfo().realize(d->layout_->font);
1352 font.fontInfo().realize(outerfont.fontInfo());
1353 font.fontInfo().realize(bparams.getFont().fontInfo());
1359 Font const Paragraph::getLabelFont
1360 (BufferParams const & bparams, Font const & outerfont) const
1362 FontInfo tmpfont = layout()->labelfont;
1363 tmpfont.realize(outerfont.fontInfo());
1364 tmpfont.realize(bparams.getFont().fontInfo());
1365 return Font(tmpfont, getParLanguage(bparams));
1369 Font const Paragraph::getLayoutFont
1370 (BufferParams const & bparams, Font const & outerfont) const
1372 FontInfo tmpfont = layout()->font;
1373 tmpfont.realize(outerfont.fontInfo());
1374 tmpfont.realize(bparams.getFont().fontInfo());
1375 return Font(tmpfont, getParLanguage(bparams));
1379 /// Returns the height of the highest font in range
1380 FontSize Paragraph::highestFontInRange
1381 (pos_type startpos, pos_type endpos, FontSize def_size) const
1383 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1388 Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1390 char_type c = d->text_[pos];
1391 if (!lyxrc.rtl_support)
1421 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1428 void Paragraph::setFont(pos_type pos, Font const & font)
1430 BOOST_ASSERT(pos <= size());
1432 // First, reduce font against layout/label font
1433 // Update: The setCharFont() routine in text2.cpp already
1434 // reduces font, so we don't need to do that here. (Asger)
1436 d->fontlist_.set(pos, font);
1440 void Paragraph::makeSameLayout(Paragraph const & par)
1442 layout(par.layout());
1444 d->params_ = par.params();
1448 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1450 if (isFreeSpacing())
1456 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1457 if (eraseChar(pos, trackChanges))
1463 return count > 0 || pos > 0;
1467 bool Paragraph::hasSameLayout(Paragraph const & par) const
1469 return par.layout() == layout() && d->params_.sameLayout(par.params());
1473 depth_type Paragraph::getDepth() const
1475 return params().depth();
1479 depth_type Paragraph::getMaxDepthAfter() const
1481 if (layout()->isEnvironment())
1482 return params().depth() + 1;
1484 return params().depth();
1488 char Paragraph::getAlign() const
1490 if (params().align() == LYX_ALIGN_LAYOUT)
1491 return layout()->align;
1493 return params().align();
1497 docstring const & Paragraph::getLabelstring() const
1499 return params().labelString();
1503 // the next two functions are for the manual labels
1504 docstring const Paragraph::getLabelWidthString() const
1506 if (layout()->margintype == MARGIN_MANUAL)
1507 return params().labelWidthString();
1509 return _("Senseless with this layout!");
1513 void Paragraph::setLabelWidthString(docstring const & s)
1515 params().labelWidthString(s);
1519 docstring const Paragraph::translateIfPossible(docstring const & s,
1520 BufferParams const & bparams) const
1522 if (!support::isAscii(s) || s.empty()) {
1523 // This must be a user defined layout. We cannot translate
1524 // this, since gettext accepts only ascii keys.
1527 // Probably standard layout, try to translate
1528 Messages & m = getMessages(getParLanguage(bparams)->code());
1529 return m.get(to_ascii(s));
1533 docstring Paragraph::expandLabel(LayoutPtr const & layout,
1534 BufferParams const & bparams, bool process_appendix) const
1536 TextClass const & tclass = bparams.getTextClass();
1539 if (process_appendix && params().appendix())
1540 fmt = translateIfPossible(layout->labelstring_appendix(),
1543 fmt = translateIfPossible(layout->labelstring(), bparams);
1545 if (fmt.empty() && layout->labeltype == LABEL_COUNTER
1546 && !layout->counter.empty())
1547 fmt = "\\the" + layout->counter;
1549 // handle 'inherited level parts' in 'fmt',
1550 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1551 size_t const i = fmt.find('@', 0);
1552 if (i != docstring::npos) {
1553 size_t const j = fmt.find('@', i + 1);
1554 if (j != docstring::npos) {
1555 docstring parent(fmt, i + 1, j - i - 1);
1556 docstring label = from_ascii("??");
1557 if (tclass.hasLayout(parent))
1558 docstring label = expandLabel(tclass[parent], bparams,
1560 fmt = docstring(fmt, 0, i) + label
1561 + docstring(fmt, j + 1, docstring::npos);
1565 return tclass.counters().counterLabel(fmt);
1569 void Paragraph::applyLayout(LayoutPtr const & new_layout)
1572 LyXAlignment const oldAlign = params().align();
1574 if (!(oldAlign & layout()->alignpossible)) {
1575 frontend::Alert::warning(_("Alignment not permitted"),
1576 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1577 params().align(LYX_ALIGN_LAYOUT);
1582 pos_type Paragraph::beginOfBody() const
1584 return d->begin_of_body_;
1588 void Paragraph::setBeginOfBody()
1590 if (layout()->labeltype != LABEL_MANUAL) {
1591 d->begin_of_body_ = 0;
1595 // Unroll the first two cycles of the loop
1596 // and remember the previous character to
1597 // remove unnecessary getChar() calls
1599 pos_type end = size();
1600 if (i < end && !isNewline(i)) {
1602 char_type previous_char = 0;
1605 previous_char = d->text_[i];
1606 if (!isNewline(i)) {
1608 while (i < end && previous_char != ' ') {
1613 previous_char = temp;
1619 d->begin_of_body_ = i;
1623 bool Paragraph::forceDefaultParagraphs() const
1625 return inInset() && inInset()->forceDefaultParagraphs(0);
1631 // paragraphs inside floats need different alignment tags to avoid
1634 bool noTrivlistCentering(InsetCode code)
1636 return code == FLOAT_CODE || code == WRAP_CODE;
1640 string correction(string const & orig)
1642 if (orig == "flushleft")
1643 return "raggedright";
1644 if (orig == "flushright")
1645 return "raggedleft";
1646 if (orig == "center")
1652 string const corrected_env(string const & suffix, string const & env,
1655 string output = suffix + "{";
1656 if (noTrivlistCentering(code))
1657 output += correction(env);
1661 if (suffix == "\\begin")
1667 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1669 if (!contains(str, "\n"))
1670 column += str.size();
1674 column = rsplit(str, tmp, '\n').size();
1681 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1682 odocstream & os, TexRow & texrow,
1683 bool moving_arg) const
1687 if (params_.noindent()) {
1688 os << "\\noindent ";
1692 LyXAlignment const curAlign = params_.align();
1694 if (curAlign == layout_->align)
1698 case LYX_ALIGN_NONE:
1699 case LYX_ALIGN_BLOCK:
1700 case LYX_ALIGN_LAYOUT:
1701 case LYX_ALIGN_SPECIAL:
1703 case LYX_ALIGN_LEFT:
1704 case LYX_ALIGN_RIGHT:
1705 case LYX_ALIGN_CENTER:
1714 case LYX_ALIGN_NONE:
1715 case LYX_ALIGN_BLOCK:
1716 case LYX_ALIGN_LAYOUT:
1717 case LYX_ALIGN_SPECIAL:
1719 case LYX_ALIGN_LEFT: {
1721 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1722 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1724 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1725 os << from_ascii(output);
1726 adjust_row_column(output, texrow, column);
1728 } case LYX_ALIGN_RIGHT: {
1730 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1731 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1733 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1734 os << from_ascii(output);
1735 adjust_row_column(output, texrow, column);
1737 } case LYX_ALIGN_CENTER: {
1739 output = corrected_env("\\begin", "center", owner_->ownerCode());
1740 os << from_ascii(output);
1741 adjust_row_column(output, texrow, column);
1750 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1751 odocstream & os, TexRow & texrow,
1752 bool moving_arg) const
1756 switch (params_.align()) {
1757 case LYX_ALIGN_NONE:
1758 case LYX_ALIGN_BLOCK:
1759 case LYX_ALIGN_LAYOUT:
1760 case LYX_ALIGN_SPECIAL:
1762 case LYX_ALIGN_LEFT:
1763 case LYX_ALIGN_RIGHT:
1764 case LYX_ALIGN_CENTER:
1772 switch (params_.align()) {
1773 case LYX_ALIGN_NONE:
1774 case LYX_ALIGN_BLOCK:
1775 case LYX_ALIGN_LAYOUT:
1776 case LYX_ALIGN_SPECIAL:
1778 case LYX_ALIGN_LEFT: {
1780 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1781 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1783 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1784 os << from_ascii(output);
1785 adjust_row_column(output, texrow, column);
1787 } case LYX_ALIGN_RIGHT: {
1789 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1790 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1792 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1793 os << from_ascii(output);
1794 adjust_row_column(output, texrow, column);
1796 } case LYX_ALIGN_CENTER: {
1798 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1799 os << from_ascii(output);
1800 adjust_row_column(output, texrow, column);
1809 // This one spits out the text of the paragraph
1810 bool Paragraph::latex(Buffer const & buf,
1811 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 // well we have to check if we are in an inset with unlimited
1823 // length (all in one row) if that is true then we don't allow
1824 // any special options in the paragraph and also we don't allow
1825 // any environment other than the default layout of the text class
1827 bool asdefault = forceDefaultParagraphs();
1830 style = bparams.getTextClass().defaultLayout();
1835 // Current base font for all inherited font changes, without any
1836 // change caused by an individual character, except for the language:
1837 // It is set to the language of the first character.
1838 // As long as we are in the label, this font is the base font of the
1839 // label. Before the first body character it is set to the base font
1843 // Maybe we have to create a optional argument.
1844 pos_type body_pos = beginOfBody();
1845 unsigned int column = 0;
1848 // the optional argument is kept in curly brackets in
1849 // case it contains a ']'
1852 basefont = getLabelFont(bparams, outerfont);
1854 basefont = getLayoutFont(bparams, outerfont);
1857 // Which font is currently active?
1858 Font running_font(basefont);
1859 // Do we have an open font change?
1860 bool open_font = false;
1862 Change runningChange = Change(Change::UNCHANGED);
1864 texrow.start(id(), 0);
1866 // if the paragraph is empty, the loop will not be entered at all
1868 if (style->isCommand()) {
1873 column += d->startTeXParParams(bparams, os, texrow,
1874 runparams.moving_arg);
1877 for (pos_type i = 0; i < size(); ++i) {
1878 // First char in paragraph or after label?
1879 if (i == body_pos) {
1882 column += running_font.latexWriteEndChanges(
1883 os, bparams, runparams,
1884 basefont, basefont);
1887 basefont = getLayoutFont(bparams, outerfont);
1888 running_font = basefont;
1890 column += Changes::latexMarkChange(os, bparams,
1891 runningChange, Change(Change::UNCHANGED));
1892 runningChange = Change(Change::UNCHANGED);
1897 if (style->isCommand()) {
1903 column += d->startTeXParParams(bparams, os,
1905 runparams.moving_arg);
1908 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1911 if (bparams.outputChanges && runningChange != change) {
1913 column += running_font.latexWriteEndChanges(
1914 os, bparams, runparams, basefont, basefont);
1917 basefont = getLayoutFont(bparams, outerfont);
1918 running_font = basefont;
1920 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1921 runningChange = change;
1924 // do not output text which is marked deleted
1925 // if change tracking output is disabled
1926 if (!bparams.outputChanges && change.type == Change::DELETED) {
1932 // Fully instantiated font
1933 Font const font = getFont(bparams, i, outerfont);
1935 Font const last_font = running_font;
1937 // Do we need to close the previous font?
1939 (font != running_font ||
1940 font.language() != running_font.language()))
1942 column += running_font.latexWriteEndChanges(
1943 os, bparams, runparams, basefont,
1944 (i == body_pos-1) ? basefont : font);
1945 running_font = basefont;
1949 // close babel's font environment before opening CJK.
1950 if (!running_font.language()->babel().empty() &&
1951 font.language()->encoding()->package() == Encoding::CJK) {
1952 string end_tag = subst(lyxrc.language_command_end,
1954 running_font.language()->babel());
1955 os << from_ascii(end_tag);
1956 column += end_tag.length();
1959 // Switch file encoding if necessary (and allowed)
1960 if (!runparams.verbatim &&
1961 runparams.encoding->package() == Encoding::none &&
1962 font.language()->encoding()->package() == Encoding::none) {
1963 std::pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1964 runparams, *(runparams.encoding),
1965 *(font.language()->encoding()));
1966 if (enc_switch.first) {
1967 column += enc_switch.second;
1968 runparams.encoding = font.language()->encoding();
1972 char_type const c = d->text_[i];
1974 // Do we need to change font?
1975 if ((font != running_font ||
1976 font.language() != running_font.language()) &&
1979 odocstringstream ods;
1980 column += font.latexWriteStartChanges(ods, bparams,
1981 runparams, basefont,
1983 running_font = font;
1985 docstring fontchange = ods.str();
1986 // check if the fontchange ends with a trailing blank
1987 // (like "\small " (see bug 3382)
1988 if (suffixIs(fontchange, ' ') && c == ' ')
1989 os << fontchange.substr(0, fontchange.size() - 1)
1990 << from_ascii("{}");
1996 // FIXME: integrate this case in latexSpecialChar
1997 // Do not print the separation of the optional argument
1998 // if style->pass_thru is false. This works because
1999 // latexSpecialChar ignores spaces if
2000 // style->pass_thru is false.
2001 if (i != body_pos - 1) {
2002 if (d->simpleTeXBlanks(
2003 runparams, os, texrow,
2004 i, column, font, *style)) {
2005 // A surrogate pair was output. We
2006 // must not call latexSpecialChar
2007 // in this iteration, since it would output
2008 // the combining character again.
2015 OutputParams rp = runparams;
2016 rp.free_spacing = style->free_spacing;
2017 rp.local_font = &font;
2018 rp.intitle = style->intitle;
2020 // Two major modes: LaTeX or plain
2021 // Handle here those cases common to both modes
2022 // and then split to handle the two modes separately.
2023 if (c == META_INSET)
2024 d->latexInset(buf, bparams, os,
2025 texrow, rp, running_font,
2026 basefont, outerfont, open_font,
2027 runningChange, *style, i, column);
2029 d->latexSpecialChar(os, rp, running_font, runningChange,
2032 // Set the encoding to that returned from simpleTeXSpecialChars (see
2033 // comment for encoding member in OutputParams.h)
2034 runparams.encoding = rp.encoding;
2037 // If we have an open font definition, we have to close it
2039 #ifdef FIXED_LANGUAGE_END_DETECTION
2042 .latexWriteEndChanges(os, bparams, runparams,
2044 next_->getFont(bparams, 0, outerfont));
2046 running_font.latexWriteEndChanges(os, bparams,
2047 runparams, basefont, basefont);
2050 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2051 //FIXME: there as we start another \selectlanguage with the next paragraph if
2052 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2053 running_font.latexWriteEndChanges(os, bparams, runparams,
2054 basefont, basefont);
2058 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2060 // Needed if there is an optional argument but no contents.
2061 if (body_pos > 0 && body_pos == size()) {
2063 return_value = false;
2067 column += d->endTeXParParams(bparams, os, texrow,
2068 runparams.moving_arg);
2071 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2072 return return_value;
2076 bool Paragraph::emptyTag() const
2078 for (pos_type i = 0; i < size(); ++i) {
2080 Inset const * inset = getInset(i);
2081 InsetCode lyx_code = inset->lyxCode();
2082 if (lyx_code != TOC_CODE &&
2083 lyx_code != INCLUDE_CODE &&
2084 lyx_code != GRAPHICS_CODE &&
2085 lyx_code != ERT_CODE &&
2086 lyx_code != LISTINGS_CODE &&
2087 lyx_code != FLOAT_CODE &&
2088 lyx_code != TABULAR_CODE) {
2092 char_type c = d->text_[i];
2093 if (c != ' ' && c != '\t')
2101 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams) const
2103 for (pos_type i = 0; i < size(); ++i) {
2105 Inset const * inset = getInset(i);
2106 InsetCode lyx_code = inset->lyxCode();
2107 if (lyx_code == LABEL_CODE) {
2108 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2109 docstring const & id = il->getParam("name");
2110 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2119 pos_type Paragraph::getFirstWord(Buffer const & buf, odocstream & os, OutputParams const & runparams) const
2122 for (i = 0; i < size(); ++i) {
2124 Inset const * inset = getInset(i);
2125 inset->docbook(buf, os, runparams);
2127 char_type c = d->text_[i];
2130 os << sgml::escapeChar(c);
2137 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2140 pos_type size = text_.size();
2141 for (pos_type i = initial; i < size; ++i) {
2142 Font font = owner_->getFont(buf.params(), i, outerfont);
2143 if (text_[i] == META_INSET)
2145 if (i != initial && font != font_old)
2154 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2156 OutputParams const & runparams,
2157 Font const & outerfont,
2158 pos_type initial) const
2160 bool emph_flag = false;
2162 LayoutPtr const & style = layout();
2164 style->labeltype == LABEL_MANUAL ? style->labelfont : style->font;
2166 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2169 // parsing main loop
2170 for (pos_type i = initial; i < size(); ++i) {
2171 Font font = getFont(buf.params(), i, outerfont);
2173 // handle <emphasis> tag
2174 if (font_old.emph() != font.fontInfo().emph()) {
2175 if (font.fontInfo().emph() == FONT_ON) {
2178 } else if (i != initial) {
2179 os << "</emphasis>";
2185 Inset const * inset = getInset(i);
2186 inset->docbook(buf, os, runparams);
2188 char_type c = d->text_[i];
2190 if (style->pass_thru)
2193 os << sgml::escapeChar(c);
2195 font_old = font.fontInfo();
2199 os << "</emphasis>";
2202 if (style->free_spacing)
2204 if (style->pass_thru && !d->onlyText(buf, outerfont, initial))
2209 bool Paragraph::isHfill(pos_type pos) const
2212 && getInset(pos)->lyxCode() == HFILL_CODE;
2216 bool Paragraph::isNewline(pos_type pos) const
2219 && getInset(pos)->lyxCode() == NEWLINE_CODE;
2223 bool Paragraph::isLineSeparator(pos_type pos) const
2225 char_type const c = d->text_[pos];
2226 return isLineSeparatorChar(c)
2227 || (c == META_INSET && getInset(pos) &&
2228 getInset(pos)->isLineSeparator());
2232 /// Used by the spellchecker
2233 bool Paragraph::isLetter(pos_type pos) const
2236 return getInset(pos)->isLetter();
2238 char_type const c = d->text_[pos];
2239 return isLetterChar(c) || isDigit(c);
2245 Paragraph::getParLanguage(BufferParams const & bparams) const
2248 return getFirstFontSettings(bparams).language();
2249 // FIXME: we should check the prev par as well (Lgb)
2250 return bparams.language;
2254 bool Paragraph::isRTL(BufferParams const & bparams) const
2256 return lyxrc.rtl_support
2257 && getParLanguage(bparams)->rightToLeft()
2258 && ownerCode() != ERT_CODE
2259 && ownerCode() != LISTINGS_CODE;
2263 void Paragraph::changeLanguage(BufferParams const & bparams,
2264 Language const * from, Language const * to)
2266 // change language including dummy font change at the end
2267 for (pos_type i = 0; i <= size(); ++i) {
2268 Font font = getFontSettings(bparams, i);
2269 if (font.language() == from) {
2270 font.setLanguage(to);
2277 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2279 Language const * doc_language = bparams.language;
2280 FontList::const_iterator cit = d->fontlist_.begin();
2281 FontList::const_iterator end = d->fontlist_.end();
2283 for (; cit != end; ++cit)
2284 if (cit->font().language() != ignore_language &&
2285 cit->font().language() != latex_language &&
2286 cit->font().language() != doc_language)
2292 // Convert the paragraph to a string.
2293 // Used for building the table of contents
2294 docstring const Paragraph::asString(Buffer const & buffer, bool label) const
2296 return asString(buffer, 0, size(), label);
2300 docstring const Paragraph::asString(Buffer const & buffer,
2301 pos_type beg, pos_type end, bool label) const
2304 odocstringstream os;
2306 if (beg == 0 && label && !params().labelString().empty())
2307 os << params().labelString() << ' ';
2309 for (pos_type i = beg; i < end; ++i) {
2310 char_type const c = d->text_[i];
2313 else if (c == META_INSET)
2314 getInset(i)->textString(buffer, os);
2321 void Paragraph::setInsetOwner(Inset * inset)
2323 d->inset_owner_ = inset;
2327 int Paragraph::id() const
2333 LayoutPtr const & Paragraph::layout() const
2339 void Paragraph::layout(LayoutPtr const & new_layout)
2341 d->layout_ = new_layout;
2345 Inset * Paragraph::inInset() const
2347 return d->inset_owner_;
2351 InsetCode Paragraph::ownerCode() const
2353 return d->inset_owner_ ?
2354 d->inset_owner_->lyxCode() : NO_CODE;
2358 ParagraphParameters & Paragraph::params()
2364 ParagraphParameters const & Paragraph::params() const
2370 bool Paragraph::isFreeSpacing() const
2372 if (layout()->free_spacing)
2374 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2378 bool Paragraph::allowEmpty() const
2380 if (layout()->keepempty)
2382 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2386 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2388 if (!Encodings::is_arabic(c))
2391 char_type prev_char = ' ';
2392 char_type next_char = ' ';
2394 for (pos_type i = pos - 1; i >= 0; --i) {
2395 char_type const par_char = d->text_[i];
2396 if (!Encodings::isComposeChar_arabic(par_char)) {
2397 prev_char = par_char;
2402 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2403 char_type const par_char = d->text_[i];
2404 if (!Encodings::isComposeChar_arabic(par_char)) {
2405 next_char = par_char;
2410 if (Encodings::is_arabic(next_char)) {
2411 if (Encodings::is_arabic(prev_char) &&
2412 !Encodings::is_arabic_special(prev_char))
2413 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2415 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2417 if (Encodings::is_arabic(prev_char) &&
2418 !Encodings::is_arabic_special(prev_char))
2419 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2421 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2426 int Paragraph::checkBiblio(bool track_changes)
2429 //This is getting more and more a mess. ...We really should clean
2430 //up this bibitem issue for 1.6. See also bug 2743.
2432 // Add bibitem insets if necessary
2433 if (layout()->labeltype != LABEL_BIBLIO)
2436 bool hasbibitem = !d->insetlist_.empty()
2437 // Insist on it being in pos 0
2438 && d->text_[0] == META_INSET
2439 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2444 // remove a bibitem in pos != 0
2445 // restore it later in pos 0 if necessary
2446 // (e.g. if a user inserts contents _before_ the item)
2447 // we're assuming there's only one of these, which there
2449 int erasedInsetPosition = -1;
2450 InsetList::iterator it = d->insetlist_.begin();
2451 InsetList::iterator end = d->insetlist_.end();
2452 for (; it != end; ++it)
2453 if (it->inset->lyxCode() == BIBITEM_CODE
2455 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2456 oldkey = olditem->getParam("key");
2457 oldlabel = olditem->getParam("label");
2458 erasedInsetPosition = it->pos;
2459 eraseChar(erasedInsetPosition, track_changes);
2463 //There was an InsetBibitem at the beginning, and we didn't
2464 //have to erase one.
2465 if (hasbibitem && erasedInsetPosition < 0)
2468 //There was an InsetBibitem at the beginning and we did have to
2469 //erase one. So we give its properties to the beginning inset.
2471 InsetBibitem * inset =
2472 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2473 if (!oldkey.empty())
2474 inset->setParam("key", oldkey);
2475 inset->setParam("label", oldlabel);
2476 return -erasedInsetPosition;
2479 //There was no inset at the beginning, so we need to create one with
2480 //the key and label of the one we erased.
2481 InsetBibitem * inset(new InsetBibitem(InsetCommandParams(BIBITEM_CODE)));
2482 // restore values of previously deleted item in this par.
2483 if (!oldkey.empty())
2484 inset->setParam("key", oldkey);
2485 inset->setParam("label", oldlabel);
2486 insertInset(0, static_cast<Inset *>(inset),
2487 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2493 unsigned int Paragraph::macrocontextPosition() const
2495 return d->macrocontext_position_;
2499 void Paragraph::setMacrocontextPosition(unsigned int pos)
2501 d->macrocontext_position_ = pos;
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 d->insetlist_.get(pos);
2550 Inset const * Paragraph::getInset(pos_type pos) const
2552 return d->insetlist_.get(pos);
2556 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2557 pos_type right, TextCase action)
2559 // process sequences of modified characters; in change
2560 // tracking mode, this approach results in much better
2561 // usability than changing case on a char-by-char basis
2564 bool const trackChanges = bparams.trackChanges;
2566 bool capitalize = true;
2568 for (; pos < right; ++pos) {
2569 char_type oldChar = d->text_[pos];
2570 char_type newChar = oldChar;
2572 // ignore insets and don't play with deleted text!
2573 if (oldChar != META_INSET && !isDeleted(pos)) {
2575 case text_lowercase:
2576 newChar = lowercase(oldChar);
2578 case text_capitalization:
2580 newChar = uppercase(oldChar);
2584 case text_uppercase:
2585 newChar = uppercase(oldChar);
2590 if (!isLetter(pos) || isDeleted(pos)) {
2591 // permit capitalization again
2595 if (oldChar != newChar)
2598 if (oldChar == newChar || pos == right - 1) {
2599 if (oldChar != newChar) {
2600 // step behind the changing area
2603 int erasePos = pos - changes.size();
2604 for (size_t i = 0; i < changes.size(); i++) {
2605 insertChar(pos, changes[i],
2606 getFontSettings(bparams,
2609 if (!eraseChar(erasePos, trackChanges)) {
2612 ++right; // expand selection
2621 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2622 pos_type pos, bool del) const
2624 int const strsize = str.length();
2626 pos_type const parsize = d->text_.size();
2627 for (i = 0; pos + i < parsize; ++i) {
2630 if (cs && str[i] != d->text_[pos + i])
2632 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2634 if (!del && isDeleted(pos + i))
2641 // if necessary, check whether string matches word
2643 if (pos > 0 && isLetter(pos - 1))
2645 if (pos + strsize < parsize
2646 && isLetter(pos + strsize))
2654 char_type Paragraph::getChar(pos_type pos) const
2656 return d->text_[pos];
2660 pos_type Paragraph::size() const
2662 return d->text_.size();
2666 bool Paragraph::empty() const
2668 return d->text_.empty();
2672 bool Paragraph::isInset(pos_type pos) const
2674 return d->text_[pos] == META_INSET;
2678 bool Paragraph::isSeparator(pos_type pos) const
2680 //FIXME: Are we sure this can be the only separator?
2681 return d->text_[pos] == ' ';