3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Jean-Marc Lasgouttes
9 * \author Angus Leeming
11 * \author André Pönitz
13 * \author Jürgen Vigna
15 * Full author contact details are available in file CREDITS.
20 #include "Paragraph.h"
22 #include "LayoutFile.h"
24 #include "BufferParams.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "paragraph_funcs.h"
39 #include "ParagraphParameters.h"
41 #include "TextClass.h"
47 #include "frontends/alert.h"
49 #include "insets/InsetBibitem.h"
50 #include "insets/InsetLabel.h"
52 #include "support/lassert.h"
53 #include "support/convert.h"
54 #include "support/debug.h"
55 #include "support/gettext.h"
56 #include "support/lstrings.h"
57 #include "support/Messages.h"
58 #include "support/textutils.h"
64 using namespace lyx::support;
69 /// Inset identifier (above 0x10ffff, for ucs-4)
70 char_type const META_INSET = 0x200001;
73 /////////////////////////////////////////////////////////////////////
77 /////////////////////////////////////////////////////////////////////
79 class Paragraph::Private
83 Private(Paragraph * owner, Layout const & layout);
84 /// "Copy constructor"
85 Private(Private const &, Paragraph * owner);
88 void insertChar(pos_type pos, char_type c, Change const & change);
90 /// Output the surrogate pair formed by \p c and \p next to \p os.
91 /// \return the number of characters written.
92 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
95 /// Output a space in appropriate formatting (or a surrogate pair
96 /// if the next character is a combining character).
97 /// \return whether a surrogate pair was output.
98 bool simpleTeXBlanks(OutputParams const &,
99 odocstream &, TexRow & texrow,
101 unsigned int & column,
103 Layout const & style);
105 /// Output consecutive unicode chars, belonging to the same script as
106 /// specified by the latex macro \p ltx, to \p os starting from \p i.
107 /// \return the number of characters written.
108 int writeScriptChars(odocstream & os, docstring const & ltx,
109 Change &, Encoding const &, pos_type & i);
111 /// This could go to ParagraphParameters if we want to.
112 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
115 /// This could go to ParagraphParameters if we want to.
116 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
120 void latexInset(BufferParams const &,
122 TexRow & texrow, OutputParams &,
125 Font const & outerfont,
127 Change & running_change,
128 Layout const & style,
130 unsigned int & column);
133 void latexSpecialChar(
135 OutputParams & runparams,
137 Change & running_change,
138 Layout const & style,
140 unsigned int & column);
147 unsigned int & column);
149 bool latexSpecialTypewriter(
153 unsigned int & column);
155 bool latexSpecialPhrase(
158 unsigned int & column,
159 OutputParams & runparams);
162 void validate(LaTeXFeatures & features,
163 Layout const & layout) const;
165 /// Checks if the paragraph contains only text and no inset or font change.
166 bool onlyText(Buffer const & buf, Font const & outerfont,
167 pos_type initial) const;
169 /// match a string against a particular point in the paragraph
170 bool isTextAt(string const & str, pos_type pos) const;
172 /// Which Paragraph owns us?
176 Inset * inset_owner_;
184 static unsigned int paragraph_id;
186 ParagraphParameters params_;
188 /// for recording and looking up changes
192 InsetList insetlist_;
195 pos_type begin_of_body_;
197 typedef docstring TextContainer;
201 typedef std::set<docstring> Words;
205 Layout const * layout_;
209 // Initialization of the counter for the paragraph id's,
210 unsigned int Paragraph::Private::paragraph_id = 0;
214 struct special_phrase {
220 special_phrase const special_phrases[] = {
221 { "LyX", from_ascii("\\LyX{}"), false },
222 { "TeX", from_ascii("\\TeX{}"), true },
223 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
224 { "LaTeX", from_ascii("\\LaTeX{}"), true },
227 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
232 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
233 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
235 id_ = paragraph_id++;
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 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
246 id_ = paragraph_id++;
250 bool Paragraph::isChanged(pos_type start, pos_type end) const
252 LASSERT(start >= 0 && start <= size(), /**/);
253 LASSERT(end > start && end <= size() + 1, /**/);
255 return d->changes_.isChanged(start, end);
259 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
261 // keep the logic here in sync with the logic of eraseChars()
265 Change const change = d->changes_.lookup(size());
266 return change.type == Change::INSERTED && change.author == 0;
270 void Paragraph::setChange(Change const & change)
272 // beware of the imaginary end-of-par character!
273 d->changes_.set(change, 0, size() + 1);
276 * Propagate the change recursively - but not in case of DELETED!
278 * Imagine that your co-author makes changes in an existing inset. He
279 * sends your document to you and you come to the conclusion that the
280 * inset should go completely. If you erase it, LyX must not delete all
281 * text within the inset. Otherwise, the change tracked insertions of
282 * your co-author get lost and there is no way to restore them later.
284 * Conclusion: An inset's content should remain untouched if you delete it
287 if (change.type != Change::DELETED) {
288 for (pos_type pos = 0; pos < size(); ++pos) {
289 if (Inset * inset = getInset(pos))
290 inset->setChange(change);
296 void Paragraph::setChange(pos_type pos, Change const & change)
298 LASSERT(pos >= 0 && pos <= size(), /**/);
299 d->changes_.set(change, pos);
301 // see comment in setChange(Change const &) above
302 if (change.type != Change::DELETED && pos < size())
303 if (Inset * inset = getInset(pos))
304 inset->setChange(change);
308 Change const & Paragraph::lookupChange(pos_type pos) const
310 LASSERT(pos >= 0 && pos <= size(), /**/);
311 return d->changes_.lookup(pos);
315 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
318 LASSERT(start >= 0 && start <= size(), /**/);
319 LASSERT(end > start && end <= size() + 1, /**/);
321 for (pos_type pos = start; pos < end; ++pos) {
322 switch (lookupChange(pos).type) {
323 case Change::UNCHANGED:
324 // accept changes in nested inset
325 if (Inset * inset = getInset(pos))
326 inset->acceptChanges(bparams);
329 case Change::INSERTED:
330 d->changes_.set(Change(Change::UNCHANGED), pos);
331 // also accept changes in nested inset
332 if (Inset * inset = getInset(pos))
333 inset->acceptChanges(bparams);
336 case Change::DELETED:
337 // Suppress access to non-existent
338 // "end-of-paragraph char"
340 eraseChar(pos, false);
351 void Paragraph::rejectChanges(BufferParams const & bparams,
352 pos_type start, pos_type end)
354 LASSERT(start >= 0 && start <= size(), /**/);
355 LASSERT(end > start && end <= size() + 1, /**/);
357 for (pos_type pos = start; pos < end; ++pos) {
358 switch (lookupChange(pos).type) {
359 case Change::UNCHANGED:
360 // reject changes in nested inset
361 if (Inset * inset = getInset(pos))
362 inset->rejectChanges(bparams);
365 case Change::INSERTED:
366 // Suppress access to non-existent
367 // "end-of-paragraph char"
369 eraseChar(pos, false);
375 case Change::DELETED:
376 d->changes_.set(Change(Change::UNCHANGED), pos);
378 // Do NOT reject changes within a deleted inset!
379 // There may be insertions of a co-author inside of it!
387 void Paragraph::Private::insertChar(pos_type pos, char_type c,
388 Change const & change)
390 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
393 changes_.insert(change, pos);
395 // This is actually very common when parsing buffers (and
396 // maybe inserting ascii text)
397 if (pos == pos_type(text_.size())) {
398 // when appending characters, no need to update tables
403 text_.insert(text_.begin() + pos, c);
405 // Update the font table.
406 fontlist_.increasePosAfterPos(pos);
409 insetlist_.increasePosAfterPos(pos);
413 void Paragraph::insertInset(pos_type pos, Inset * inset,
414 Change const & change)
416 LASSERT(inset, /**/);
417 LASSERT(pos >= 0 && pos <= size(), /**/);
419 d->insertChar(pos, META_INSET, change);
420 LASSERT(d->text_[pos] == META_INSET, /**/);
422 // Add a new entry in the insetlist_.
423 d->insetlist_.insert(inset, pos);
427 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
429 LASSERT(pos >= 0 && pos <= size(), /**/);
431 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
434 Change change = d->changes_.lookup(pos);
436 // set the character to DELETED if
437 // a) it was previously unchanged or
438 // b) it was inserted by a co-author
440 if (change.type == Change::UNCHANGED ||
441 (change.type == Change::INSERTED && change.author != 0)) {
442 setChange(pos, Change(Change::DELETED));
446 if (change.type == Change::DELETED)
450 // Don't physically access the imaginary end-of-paragraph character.
451 // eraseChar() can only mark it as DELETED. A physical deletion of
452 // end-of-par must be handled externally.
458 d->changes_.erase(pos);
460 // if it is an inset, delete the inset entry
461 if (d->text_[pos] == META_INSET)
462 d->insetlist_.erase(pos);
464 d->text_.erase(d->text_.begin() + pos);
466 // Update the fontlist_
467 d->fontlist_.erase(pos);
469 // Update the insetlist_
470 d->insetlist_.decreasePosAfterPos(pos);
476 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
478 LASSERT(start >= 0 && start <= size(), /**/);
479 LASSERT(end >= start && end <= size() + 1, /**/);
482 for (pos_type count = end - start; count; --count) {
483 if (!eraseChar(i, trackChanges))
490 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
491 char_type next, Encoding const & encoding)
493 // Writing next here may circumvent a possible font change between
494 // c and next. Since next is only output if it forms a surrogate pair
495 // with c we can ignore this:
496 // A font change inside a surrogate pair does not make sense and is
497 // hopefully impossible to input.
498 // FIXME: change tracking
499 // Is this correct WRT change tracking?
500 docstring const latex1 = encoding.latexChar(next);
501 docstring const latex2 = encoding.latexChar(c);
502 os << latex1 << '{' << latex2 << '}';
503 return latex1.length() + latex2.length() + 2;
507 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
508 odocstream & os, TexRow & texrow,
510 unsigned int & column,
512 Layout const & style)
514 if (style.pass_thru || runparams.verbatim)
517 if (i + 1 < int(text_.size())) {
518 char_type next = text_[i + 1];
519 if (Encodings::isCombiningChar(next)) {
520 Encoding const & encoding = *(runparams.encoding);
521 // This space has an accent, so we must always output it.
522 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
527 if (lyxrc.plaintext_linelen > 0
528 && column > lyxrc.plaintext_linelen
530 && text_[i - 1] != ' '
531 && (i + 1 < int(text_.size()))
532 // same in FreeSpacing mode
533 && !owner_->isFreeSpacing()
534 // In typewriter mode, we want to avoid
535 // ! . ? : at the end of a line
536 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
537 && (text_[i - 1] == '.'
538 || text_[i - 1] == '?'
539 || text_[i - 1] == ':'
540 || text_[i - 1] == '!'))) {
543 texrow.start(owner_->id(), i + 1);
545 } else if (style.free_spacing) {
554 int Paragraph::Private::writeScriptChars(odocstream & os,
555 docstring const & ltx,
556 Change & runningChange,
557 Encoding const & encoding,
560 // FIXME: modifying i here is not very nice...
562 // We only arrive here when a proper language for character text_[i] has
563 // not been specified (i.e., it could not be translated in the current
564 // latex encoding) and it belongs to a known script.
565 // Parameter ltx contains the latex translation of text_[i] as specified in
566 // the unicodesymbols file and is something like "\textXXX{<spec>}".
567 // The latex macro name "textXXX" specifies the script to which text_[i]
568 // belongs and we use it in order to check whether characters from the
569 // same script immediately follow, such that we can collect them in a
570 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
571 // for the first char but only "<spec>" for all subsequent chars.
572 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
573 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
574 string script = to_ascii(ltx.substr(1, brace1 - 1));
575 int length = ltx.substr(0, brace2).length();
576 os << ltx.substr(0, brace2);
577 int size = text_.size();
578 while (i + 1 < size) {
579 char_type const next = text_[i + 1];
580 // Stop here if next character belongs to another script
581 // or there is a change in change tracking status.
582 if (!Encodings::isKnownScriptChar(next, script) ||
583 runningChange != owner_->lookupChange(i + 1))
587 FontList::const_iterator cit = fontlist_.begin();
588 FontList::const_iterator end = fontlist_.end();
589 for (; cit != end; ++cit) {
590 if (cit->pos() >= i && !found) {
591 prev_font = cit->font();
594 if (cit->pos() >= i + 1)
597 // Stop here if there is a font attribute or encoding change.
598 if (found && cit != end && prev_font != cit->font())
600 docstring const latex = encoding.latexChar(next);
601 docstring::size_type const b1 =
602 latex.find_first_of(from_ascii("{"));
603 docstring::size_type const b2 =
604 latex.find_last_of(from_ascii("}"));
605 int const len = b2 - b1 - 1;
606 os << latex.substr(b1 + 1, len);
616 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
618 pos_type const len = str.length();
620 // is the paragraph large enough?
621 if (pos + len > int(text_.size()))
624 // does the wanted text start at point?
625 for (string::size_type i = 0; i < str.length(); ++i) {
626 // Caution: direct comparison of characters works only
627 // because str is pure ASCII.
628 if (str[i] != text_[pos + i])
632 return fontlist_.hasChangeInRange(pos, len);
636 void Paragraph::Private::latexInset(
637 BufferParams const & bparams,
640 OutputParams & runparams,
643 Font const & outerfont,
645 Change & running_change,
646 Layout const & style,
648 unsigned int & column)
650 Inset * inset = owner_->getInset(i);
651 LASSERT(inset, /**/);
653 if (style.pass_thru) {
654 inset->plaintext(os, runparams);
658 // FIXME: move this to InsetNewline::latex
659 if (inset->lyxCode() == NEWLINE_CODE) {
660 // newlines are handled differently here than
661 // the default in simpleTeXSpecialChars().
662 if (!style.newline_allowed) {
666 column += running_font.latexWriteEndChanges(
667 os, bparams, runparams,
672 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
675 basefont = owner_->getLayoutFont(bparams, outerfont);
676 running_font = basefont;
678 if (runparams.moving_arg)
683 texrow.start(owner_->id(), i + 1);
687 if (owner_->lookupChange(i).type == Change::DELETED) {
688 if( ++runparams.inDeletedInset == 1)
689 runparams.changeOfDeletedInset = owner_->lookupChange(i);
692 if (inset->canTrackChanges()) {
693 column += Changes::latexMarkChange(os, bparams, running_change,
694 Change(Change::UNCHANGED));
695 running_change = Change(Change::UNCHANGED);
699 odocstream::pos_type const len = os.tellp();
701 if (inset->forceLTR()
702 && running_font.isRightToLeft()
703 // ERT is an exception, it should be output with no decorations at all
704 && inset->lyxCode() != ERT_CODE) {
705 if (running_font.language()->lang() == "farsi")
712 // FIXME: Bug: we can have an empty font change here!
713 // if there has just been a font change, we are going to close it
714 // right now, which means stupid latex code like \textsf{}. AFAIK,
715 // this does not harm dvi output. A minor bug, thus (JMarc)
717 // Some insets cannot be inside a font change command.
718 // However, even such insets *can* be placed in \L or \R
719 // or their equivalents (for RTL language switches), so we don't
720 // close the language in those cases.
721 // ArabTeX, though, cannot handle this special behavior, it seems.
722 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
723 || running_font.language()->lang() == "arabic_arabtex";
724 if (open_font && inset->noFontChange()) {
725 bool closeLanguage = arabtex
726 || basefont.isRightToLeft() == running_font.isRightToLeft();
727 unsigned int count = running_font.latexWriteEndChanges(os,
728 bparams, runparams, basefont, basefont, closeLanguage);
730 // if any font properties were closed, update the running_font,
731 // making sure, however, to leave the language as it was
733 // FIXME: probably a better way to keep track of the old
734 // language, than copying the entire font?
735 Font const copy_font(running_font);
736 basefont = owner_->getLayoutFont(bparams, outerfont);
737 running_font = basefont;
739 running_font.setLanguage(copy_font.language());
740 // leave font open if language is still open
741 open_font = (running_font.language() == basefont.language());
743 runparams.local_font = &basefont;
747 int tmp = inset->latex(os, runparams);
750 if (running_font.language()->lang() == "farsi")
757 for (int j = 0; j < tmp; ++j)
760 texrow.start(owner_->id(), i + 1);
763 column += os.tellp() - len;
766 if (owner_->lookupChange(i).type == Change::DELETED)
767 --runparams.inDeletedInset;
771 void Paragraph::Private::latexSpecialChar(
773 OutputParams & runparams,
775 Change & running_change,
776 Layout const & style,
778 unsigned int & column)
780 char_type const c = text_[i];
782 if (style.pass_thru) {
784 // FIXME UNICODE: This can fail if c cannot
785 // be encoded in the current encoding.
790 if (runparams.verbatim) {
795 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
798 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
799 && latexSpecialTypewriter(c, os, i, column))
802 // Otherwise, we use what LaTeX provides us.
805 os << "\\textbackslash{}";
809 os << "\\textless{}";
813 os << "\\textgreater{}";
824 os << "\\char`\\\"{}";
829 case '%': case '#': case '{':
837 os << "\\textasciitilde{}";
842 os << "\\textasciicircum{}";
847 // avoid being mistaken for optional arguments
855 // Blanks are printed before font switching.
856 // Sure? I am not! (try nice-latex)
857 // I am sure it's correct. LyX might be smarter
858 // in the future, but for now, nothing wrong is
865 if (latexSpecialPhrase(os, i, column, runparams))
871 Encoding const & encoding = *(runparams.encoding);
872 if (i + 1 < int(text_.size())) {
873 char_type next = text_[i + 1];
874 if (Encodings::isCombiningChar(next)) {
875 column += latexSurrogatePair(os, c, next, encoding) - 1;
881 docstring const latex = encoding.latexChar(c);
882 if (Encodings::isKnownScriptChar(c, script)
883 && prefixIs(latex, from_ascii("\\" + script)))
884 column += writeScriptChars(os, latex,
885 running_change, encoding, i) - 1;
886 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
887 // Prevent eating of a following
888 // space or command corruption by
889 // following characters
890 column += latex.length() + 1;
893 column += latex.length() - 1;
901 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
902 pos_type & i, unsigned int & column)
908 // In T1 encoding, these characters exist
909 // but we should avoid ligatures
910 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
915 //os << "\\textcompwordmark{}";
927 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
928 pos_type & i, unsigned int & column)
932 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
933 // "--" in Typewriter mode -> "-{}-"
940 // I assume this is hack treating typewriter as verbatim
941 // FIXME UNICODE: This can fail if c cannot be encoded
942 // in the current encoding.
947 // Those characters are not directly supported.
951 case '%': case '#': case '{':
960 // With Typewriter font, these characters exist.
967 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
968 unsigned int & column, OutputParams & runparams)
970 // FIXME: if we have "LaTeX" with a font
971 // change in the middle (before the 'T', then
972 // the "TeX" part is still special cased.
973 // Really we should only operate this on
974 // "words" for some definition of word
976 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
977 if (!isTextAt(special_phrases[pnr].phrase, i))
979 if (runparams.moving_arg)
981 os << special_phrases[pnr].macro;
982 i += special_phrases[pnr].phrase.length() - 1;
983 column += special_phrases[pnr].macro.length() - 1;
990 void Paragraph::Private::validate(LaTeXFeatures & features,
991 Layout const & layout) const
994 if (!params_.spacing().isDefault())
995 features.require("setspace");
998 features.useLayout(layout.name());
1001 fontlist_.validate(features);
1003 // then the indentation
1004 if (!params_.leftIndent().zero())
1005 features.require("ParagraphLeftIndent");
1008 InsetList::const_iterator icit = insetlist_.begin();
1009 InsetList::const_iterator iend = insetlist_.end();
1010 for (; icit != iend; ++icit) {
1012 icit->inset->validate(features);
1013 if (layout.needprotect &&
1014 icit->inset->lyxCode() == FOOT_CODE)
1015 features.require("NeedLyXFootnoteCode");
1019 // then the contents
1020 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1021 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1022 if (!special_phrases[pnr].builtin
1023 && isTextAt(special_phrases[pnr].phrase, i)) {
1024 features.require(special_phrases[pnr].phrase);
1028 Encodings::validate(text_[i], features);
1032 /////////////////////////////////////////////////////////////////////
1036 /////////////////////////////////////////////////////////////////////
1039 Layout const emptyParagraphLayout;
1042 Paragraph::Paragraph()
1043 : d(new Paragraph::Private(this, emptyParagraphLayout))
1050 Paragraph::Paragraph(Paragraph const & par)
1051 : itemdepth(par.itemdepth),
1052 d(new Paragraph::Private(*par.d, this))
1058 Paragraph & Paragraph::operator=(Paragraph const & par)
1060 // needed as we will destroy the private part before copying it
1062 itemdepth = par.itemdepth;
1066 d = new Private(*par.d, this);
1073 Paragraph::~Paragraph()
1080 void Paragraph::write(ostream & os, BufferParams const & bparams,
1081 depth_type & dth) const
1083 // The beginning or end of a deeper (i.e. nested) area?
1084 if (dth != d->params_.depth()) {
1085 if (d->params_.depth() > dth) {
1086 while (d->params_.depth() > dth) {
1087 os << "\n\\begin_deeper";
1091 while (d->params_.depth() < dth) {
1092 os << "\n\\end_deeper";
1098 // First write the layout
1099 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1101 d->params_.write(os);
1103 Font font1(inherit_font, bparams.language);
1105 Change running_change = Change(Change::UNCHANGED);
1108 for (pos_type i = 0; i <= size(); ++i) {
1110 Change change = lookupChange(i);
1111 Changes::lyxMarkChange(os, column, running_change, change);
1112 running_change = change;
1117 // Write font changes
1118 Font font2 = getFontSettings(bparams, i);
1119 if (font2 != font1) {
1120 font2.lyxWriteChanges(font1, os);
1125 char_type const c = d->text_[i];
1128 if (Inset const * inset = getInset(i)) {
1129 if (inset->directWrite()) {
1130 // international char, let it write
1131 // code directly so it's shorter in
1137 os << "\\begin_inset ";
1139 os << "\n\\end_inset\n\n";
1145 os << "\n\\backslash\n";
1149 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1156 if ((column > 70 && c == ' ')
1161 // this check is to amend a bug. LyX sometimes
1162 // inserts '\0' this could cause problems.
1164 os << to_utf8(docstring(1, c));
1166 LYXERR0("NUL char in structure.");
1172 os << "\n\\end_layout\n";
1176 void Paragraph::validate(LaTeXFeatures & features) const
1178 d->validate(features, *d->layout_);
1182 void Paragraph::insert(pos_type start, docstring const & str,
1183 Font const & font, Change const & change)
1185 for (size_t i = 0, n = str.size(); i != n ; ++i)
1186 insertChar(start + i, str[i], font, change);
1190 void Paragraph::appendChar(char_type c, Font const & font,
1191 Change const & change)
1194 d->changes_.insert(change, d->text_.size());
1195 // when appending characters, no need to update tables
1196 d->text_.push_back(c);
1197 setFont(d->text_.size() - 1, font);
1201 void Paragraph::appendString(docstring const & s, Font const & font,
1202 Change const & change)
1204 pos_type end = s.size();
1205 size_t oldsize = d->text_.size();
1206 size_t newsize = oldsize + end;
1207 size_t capacity = d->text_.capacity();
1208 if (newsize >= capacity)
1209 d->text_.reserve(max(capacity + 100, newsize));
1211 // when appending characters, no need to update tables
1214 // FIXME: Optimize this!
1215 for (pos_type i = 0; i != end; ++i) {
1217 d->changes_.insert(change, i);
1219 d->fontlist_.set(oldsize, font);
1220 d->fontlist_.set(newsize - 1, font);
1224 void Paragraph::insertChar(pos_type pos, char_type c,
1227 d->insertChar(pos, c, Change(trackChanges ?
1228 Change::INSERTED : Change::UNCHANGED));
1232 void Paragraph::insertChar(pos_type pos, char_type c,
1233 Font const & font, bool trackChanges)
1235 d->insertChar(pos, c, Change(trackChanges ?
1236 Change::INSERTED : Change::UNCHANGED));
1241 void Paragraph::insertChar(pos_type pos, char_type c,
1242 Font const & font, Change const & change)
1244 d->insertChar(pos, c, change);
1249 void Paragraph::insertInset(pos_type pos, Inset * inset,
1250 Font const & font, Change const & change)
1252 insertInset(pos, inset, change);
1253 // Set the font/language of the inset...
1258 bool Paragraph::insetAllowed(InsetCode code)
1260 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1264 void Paragraph::resetFonts(Font const & font)
1266 d->fontlist_.clear();
1267 d->fontlist_.set(0, font);
1268 d->fontlist_.set(d->text_.size() - 1, font);
1271 // Gets uninstantiated font setting at position.
1272 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1276 LYXERR0("pos: " << pos << " size: " << size());
1277 LASSERT(pos <= size(), /**/);
1280 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1281 if (cit != d->fontlist_.end())
1284 if (pos == size() && !empty())
1285 return getFontSettings(bparams, pos - 1);
1287 return Font(inherit_font, getParLanguage(bparams));
1291 FontSpan Paragraph::fontSpan(pos_type pos) const
1293 LASSERT(pos <= size(), /**/);
1296 FontList::const_iterator cit = d->fontlist_.begin();
1297 FontList::const_iterator end = d->fontlist_.end();
1298 for (; cit != end; ++cit) {
1299 if (cit->pos() >= pos) {
1300 if (pos >= beginOfBody())
1301 return FontSpan(max(start, beginOfBody()),
1304 return FontSpan(start,
1305 min(beginOfBody() - 1,
1308 start = cit->pos() + 1;
1311 // This should not happen, but if so, we take no chances.
1312 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1313 return FontSpan(pos, pos);
1317 // Gets uninstantiated font setting at position 0
1318 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1320 if (!empty() && !d->fontlist_.empty())
1321 return d->fontlist_.begin()->font();
1323 return Font(inherit_font, bparams.language);
1327 // Gets the fully instantiated font at a given position in a paragraph
1328 // This is basically the same function as Text::GetFont() in text2.cpp.
1329 // The difference is that this one is used for generating the LaTeX file,
1330 // and thus cosmetic "improvements" are disallowed: This has to deliver
1331 // the true picture of the buffer. (Asger)
1332 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1333 Font const & outerfont) const
1335 LASSERT(pos >= 0, /**/);
1337 Font font = getFontSettings(bparams, pos);
1339 pos_type const body_pos = beginOfBody();
1341 font.fontInfo().realize(d->layout_->labelfont);
1343 font.fontInfo().realize(d->layout_->font);
1345 font.fontInfo().realize(outerfont.fontInfo());
1346 font.fontInfo().realize(bparams.getFont().fontInfo());
1352 Font const Paragraph::getLabelFont
1353 (BufferParams const & bparams, Font const & outerfont) const
1355 FontInfo tmpfont = d->layout_->labelfont;
1356 tmpfont.realize(outerfont.fontInfo());
1357 tmpfont.realize(bparams.getFont().fontInfo());
1358 return Font(tmpfont, getParLanguage(bparams));
1362 Font const Paragraph::getLayoutFont
1363 (BufferParams const & bparams, Font const & outerfont) const
1365 FontInfo tmpfont = d->layout_->font;
1366 tmpfont.realize(outerfont.fontInfo());
1367 tmpfont.realize(bparams.getFont().fontInfo());
1368 return Font(tmpfont, getParLanguage(bparams));
1372 /// Returns the height of the highest font in range
1373 FontSize Paragraph::highestFontInRange
1374 (pos_type startpos, pos_type endpos, FontSize def_size) const
1376 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1380 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1382 char_type c = d->text_[pos];
1383 if (!lyxrc.rtl_support)
1413 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1419 void Paragraph::setFont(pos_type pos, Font const & font)
1421 LASSERT(pos <= size(), /**/);
1423 // First, reduce font against layout/label font
1424 // Update: The setCharFont() routine in text2.cpp already
1425 // reduces font, so we don't need to do that here. (Asger)
1427 d->fontlist_.set(pos, font);
1431 void Paragraph::makeSameLayout(Paragraph const & par)
1433 d->layout_ = par.d->layout_;
1434 d->params_ = par.d->params_;
1438 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1440 if (isFreeSpacing())
1446 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1447 if (eraseChar(pos, trackChanges))
1453 return count > 0 || pos > 0;
1457 bool Paragraph::hasSameLayout(Paragraph const & par) const
1459 return par.d->layout_ == d->layout_
1460 && d->params_.sameLayout(par.d->params_);
1464 depth_type Paragraph::getDepth() const
1466 return d->params_.depth();
1470 depth_type Paragraph::getMaxDepthAfter() const
1472 if (d->layout_->isEnvironment())
1473 return d->params_.depth() + 1;
1475 return d->params_.depth();
1479 char Paragraph::getAlign() const
1481 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1482 return d->layout_->align;
1484 return d->params_.align();
1488 docstring const & Paragraph::labelString() const
1490 return d->params_.labelString();
1494 // the next two functions are for the manual labels
1495 docstring const Paragraph::getLabelWidthString() const
1497 if (d->layout_->margintype == MARGIN_MANUAL)
1498 return d->params_.labelWidthString();
1500 return _("Senseless with this layout!");
1504 void Paragraph::setLabelWidthString(docstring const & s)
1506 d->params_.labelWidthString(s);
1510 docstring const Paragraph::translateIfPossible(docstring const & s,
1511 BufferParams const & bparams) const
1513 if (!isAscii(s) || s.empty()) {
1514 // This must be a user defined layout. We cannot translate
1515 // this, since gettext accepts only ascii keys.
1518 // Probably standard layout, try to translate
1519 Messages & m = getMessages(getParLanguage(bparams)->code());
1520 return m.get(to_ascii(s));
1524 docstring Paragraph::expandLabel(Layout const & layout,
1525 BufferParams const & bparams, bool process_appendix) const
1527 DocumentClass const & tclass = bparams.documentClass();
1530 if (process_appendix && d->params_.appendix())
1531 fmt = translateIfPossible(layout.labelstring_appendix(),
1534 fmt = translateIfPossible(layout.labelstring(), bparams);
1536 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1537 && !layout.counter.empty())
1538 fmt = "\\the" + layout.counter;
1540 // handle 'inherited level parts' in 'fmt',
1541 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1542 size_t const i = fmt.find('@', 0);
1543 if (i != docstring::npos) {
1544 size_t const j = fmt.find('@', i + 1);
1545 if (j != docstring::npos) {
1546 docstring parent(fmt, i + 1, j - i - 1);
1547 docstring label = from_ascii("??");
1548 if (tclass.hasLayout(parent))
1549 docstring label = expandLabel(tclass[parent], bparams,
1551 fmt = docstring(fmt, 0, i) + label
1552 + docstring(fmt, j + 1, docstring::npos);
1556 return tclass.counters().counterLabel(fmt);
1560 void Paragraph::applyLayout(Layout const & new_layout)
1562 d->layout_ = &new_layout;
1563 LyXAlignment const oldAlign = d->params_.align();
1565 if (!(oldAlign & d->layout_->alignpossible)) {
1566 frontend::Alert::warning(_("Alignment not permitted"),
1567 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1568 d->params_.align(LYX_ALIGN_LAYOUT);
1573 pos_type Paragraph::beginOfBody() const
1575 return d->begin_of_body_;
1579 void Paragraph::setBeginOfBody()
1581 if (d->layout_->labeltype != LABEL_MANUAL) {
1582 d->begin_of_body_ = 0;
1586 // Unroll the first two cycles of the loop
1587 // and remember the previous character to
1588 // remove unnecessary getChar() calls
1590 pos_type end = size();
1591 if (i < end && !isNewline(i)) {
1593 char_type previous_char = 0;
1596 previous_char = d->text_[i];
1597 if (!isNewline(i)) {
1599 while (i < end && previous_char != ' ') {
1604 previous_char = temp;
1610 d->begin_of_body_ = i;
1614 bool Paragraph::forceEmptyLayout() const
1616 Inset const * const inset = inInset();
1619 return inset->forceEmptyLayout();
1623 bool Paragraph::allowParagraphCustomization() const
1625 Inset const * const inset = inInset();
1628 return inset->allowParagraphCustomization();
1632 bool Paragraph::useEmptyLayout() const
1634 Inset const * const inset = inInset();
1637 return inset->useEmptyLayout();
1643 // paragraphs inside floats need different alignment tags to avoid
1646 bool noTrivlistCentering(InsetCode code)
1648 return code == FLOAT_CODE || code == WRAP_CODE;
1652 string correction(string const & orig)
1654 if (orig == "flushleft")
1655 return "raggedright";
1656 if (orig == "flushright")
1657 return "raggedleft";
1658 if (orig == "center")
1664 string const corrected_env(string const & suffix, string const & env,
1667 string output = suffix + "{";
1668 if (noTrivlistCentering(code))
1669 output += correction(env);
1673 if (suffix == "\\begin")
1679 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1681 if (!contains(str, "\n"))
1682 column += str.size();
1686 column = rsplit(str, tmp, '\n').size();
1693 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1694 odocstream & os, TexRow & texrow,
1695 bool moving_arg) const
1699 if (params_.noindent()) {
1700 os << "\\noindent ";
1704 LyXAlignment const curAlign = params_.align();
1706 if (curAlign == layout_->align)
1710 case LYX_ALIGN_NONE:
1711 case LYX_ALIGN_BLOCK:
1712 case LYX_ALIGN_LAYOUT:
1713 case LYX_ALIGN_SPECIAL:
1715 case LYX_ALIGN_LEFT:
1716 case LYX_ALIGN_RIGHT:
1717 case LYX_ALIGN_CENTER:
1726 case LYX_ALIGN_NONE:
1727 case LYX_ALIGN_BLOCK:
1728 case LYX_ALIGN_LAYOUT:
1729 case LYX_ALIGN_SPECIAL:
1731 case LYX_ALIGN_LEFT: {
1733 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1734 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1736 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1737 os << from_ascii(output);
1738 adjust_row_column(output, texrow, column);
1740 } case LYX_ALIGN_RIGHT: {
1742 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1743 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1745 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1746 os << from_ascii(output);
1747 adjust_row_column(output, texrow, column);
1749 } case LYX_ALIGN_CENTER: {
1751 output = corrected_env("\\begin", "center", owner_->ownerCode());
1752 os << from_ascii(output);
1753 adjust_row_column(output, texrow, column);
1762 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1763 odocstream & os, TexRow & texrow,
1764 bool moving_arg) const
1768 switch (params_.align()) {
1769 case LYX_ALIGN_NONE:
1770 case LYX_ALIGN_BLOCK:
1771 case LYX_ALIGN_LAYOUT:
1772 case LYX_ALIGN_SPECIAL:
1774 case LYX_ALIGN_LEFT:
1775 case LYX_ALIGN_RIGHT:
1776 case LYX_ALIGN_CENTER:
1784 switch (params_.align()) {
1785 case LYX_ALIGN_NONE:
1786 case LYX_ALIGN_BLOCK:
1787 case LYX_ALIGN_LAYOUT:
1788 case LYX_ALIGN_SPECIAL:
1790 case LYX_ALIGN_LEFT: {
1792 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1793 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1795 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1796 os << from_ascii(output);
1797 adjust_row_column(output, texrow, column);
1799 } case LYX_ALIGN_RIGHT: {
1801 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1802 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1804 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1805 os << from_ascii(output);
1806 adjust_row_column(output, texrow, column);
1808 } case LYX_ALIGN_CENTER: {
1810 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1811 os << from_ascii(output);
1812 adjust_row_column(output, texrow, column);
1821 // This one spits out the text of the paragraph
1822 bool Paragraph::latex(BufferParams const & bparams,
1823 Font const & outerfont,
1824 odocstream & os, TexRow & texrow,
1825 OutputParams const & runparams) const
1827 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1829 bool return_value = false;
1831 bool asdefault = forceEmptyLayout();
1833 Layout const & style = asdefault ?
1834 bparams.documentClass().emptyLayout() :
1837 // Current base font for all inherited font changes, without any
1838 // change caused by an individual character, except for the language:
1839 // It is set to the language of the first character.
1840 // As long as we are in the label, this font is the base font of the
1841 // label. Before the first body character it is set to the base font
1845 // Maybe we have to create a optional argument.
1846 pos_type body_pos = beginOfBody();
1847 unsigned int column = 0;
1850 // the optional argument is kept in curly brackets in
1851 // case it contains a ']'
1854 basefont = getLabelFont(bparams, outerfont);
1856 basefont = getLayoutFont(bparams, outerfont);
1859 // Which font is currently active?
1860 Font running_font(basefont);
1861 // Do we have an open font change?
1862 bool open_font = false;
1864 Change runningChange = Change(Change::UNCHANGED);
1866 texrow.start(id(), 0);
1868 // if the paragraph is empty, the loop will not be entered at all
1870 if (style.isCommand()) {
1875 column += d->startTeXParParams(bparams, os, texrow,
1876 runparams.moving_arg);
1879 for (pos_type i = 0; i < size(); ++i) {
1880 // First char in paragraph or after label?
1881 if (i == body_pos) {
1884 column += running_font.latexWriteEndChanges(
1885 os, bparams, runparams,
1886 basefont, basefont);
1889 basefont = getLayoutFont(bparams, outerfont);
1890 running_font = basefont;
1892 column += Changes::latexMarkChange(os, bparams,
1893 runningChange, Change(Change::UNCHANGED));
1894 runningChange = Change(Change::UNCHANGED);
1899 if (style.isCommand()) {
1905 column += d->startTeXParParams(bparams, os,
1907 runparams.moving_arg);
1910 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1913 if (bparams.outputChanges && runningChange != change) {
1915 column += running_font.latexWriteEndChanges(
1916 os, bparams, runparams, basefont, basefont);
1919 basefont = getLayoutFont(bparams, outerfont);
1920 running_font = basefont;
1922 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1923 runningChange = change;
1926 // do not output text which is marked deleted
1927 // if change tracking output is disabled
1928 if (!bparams.outputChanges && change.type == Change::DELETED) {
1934 // Fully instantiated font
1935 Font const font = getFont(bparams, i, outerfont);
1937 Font const last_font = running_font;
1939 // Do we need to close the previous font?
1941 (font != running_font ||
1942 font.language() != running_font.language()))
1944 column += running_font.latexWriteEndChanges(
1945 os, bparams, runparams, basefont,
1946 (i == body_pos-1) ? basefont : font);
1947 running_font = basefont;
1951 // close babel's font environment before opening CJK.
1952 if (!running_font.language()->babel().empty() &&
1953 font.language()->encoding()->package() == Encoding::CJK) {
1954 string end_tag = subst(lyxrc.language_command_end,
1956 running_font.language()->babel());
1957 os << from_ascii(end_tag);
1958 column += end_tag.length();
1961 // Switch file encoding if necessary (and allowed)
1962 if (!runparams.verbatim &&
1963 runparams.encoding->package() == Encoding::none &&
1964 font.language()->encoding()->package() == Encoding::none) {
1965 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1966 runparams, *(font.language()->encoding()));
1967 if (enc_switch.first) {
1968 column += enc_switch.second;
1969 runparams.encoding = font.language()->encoding();
1973 char_type const c = d->text_[i];
1975 // Do we need to change font?
1976 if ((font != running_font ||
1977 font.language() != running_font.language()) &&
1980 odocstringstream ods;
1981 column += font.latexWriteStartChanges(ods, bparams,
1982 runparams, basefont,
1984 running_font = font;
1986 docstring fontchange = ods.str();
1987 // check if the fontchange ends with a trailing blank
1988 // (like "\small " (see bug 3382)
1989 if (suffixIs(fontchange, ' ') && c == ' ')
1990 os << fontchange.substr(0, fontchange.size() - 1)
1991 << from_ascii("{}");
1997 // FIXME: integrate this case in latexSpecialChar
1998 // Do not print the separation of the optional argument
1999 // if style.pass_thru is false. This works because
2000 // latexSpecialChar ignores spaces if
2001 // style.pass_thru is false.
2002 if (i != body_pos - 1) {
2003 if (d->simpleTeXBlanks(
2004 runparams, os, texrow,
2005 i, column, font, style)) {
2006 // A surrogate pair was output. We
2007 // must not call latexSpecialChar
2008 // in this iteration, since it would output
2009 // the combining character again.
2016 OutputParams rp = runparams;
2017 rp.free_spacing = style.free_spacing;
2018 rp.local_font = &font;
2019 rp.intitle = style.intitle;
2021 // Two major modes: LaTeX or plain
2022 // Handle here those cases common to both modes
2023 // and then split to handle the two modes separately.
2024 if (c == META_INSET)
2025 d->latexInset(bparams, os,
2026 texrow, rp, running_font,
2027 basefont, outerfont, open_font,
2028 runningChange, style, i, column);
2031 d->latexSpecialChar(os, rp, running_font, runningChange,
2033 } catch (EncodingException & e) {
2034 if (runparams.dryrun) {
2035 os << "<" << _("LyX Warning: ")
2036 << _("uncodable character") << " '";
2040 // add location information and throw again.
2048 // Set the encoding to that returned from simpleTeXSpecialChars (see
2049 // comment for encoding member in OutputParams.h)
2050 runparams.encoding = rp.encoding;
2053 // If we have an open font definition, we have to close it
2055 #ifdef FIXED_LANGUAGE_END_DETECTION
2058 .latexWriteEndChanges(os, bparams, runparams,
2060 next_->getFont(bparams, 0, outerfont));
2062 running_font.latexWriteEndChanges(os, bparams,
2063 runparams, basefont, basefont);
2066 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2067 //FIXME: there as we start another \selectlanguage with the next paragraph if
2068 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2069 running_font.latexWriteEndChanges(os, bparams, runparams,
2070 basefont, basefont);
2074 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2076 // Needed if there is an optional argument but no contents.
2077 if (body_pos > 0 && body_pos == size()) {
2079 return_value = false;
2083 column += d->endTeXParParams(bparams, os, texrow,
2084 runparams.moving_arg);
2087 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2088 return return_value;
2092 bool Paragraph::emptyTag() const
2094 for (pos_type i = 0; i < size(); ++i) {
2095 if (Inset const * inset = getInset(i)) {
2096 InsetCode lyx_code = inset->lyxCode();
2097 if (lyx_code != TOC_CODE &&
2098 lyx_code != INCLUDE_CODE &&
2099 lyx_code != GRAPHICS_CODE &&
2100 lyx_code != ERT_CODE &&
2101 lyx_code != LISTINGS_CODE &&
2102 lyx_code != FLOAT_CODE &&
2103 lyx_code != TABULAR_CODE) {
2107 char_type c = d->text_[i];
2108 if (c != ' ' && c != '\t')
2116 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2119 for (pos_type i = 0; i < size(); ++i) {
2120 if (Inset const * inset = getInset(i)) {
2121 InsetCode lyx_code = inset->lyxCode();
2122 if (lyx_code == LABEL_CODE) {
2123 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2124 docstring const & id = il->getParam("name");
2125 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2133 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2137 for (i = 0; i < size(); ++i) {
2138 if (Inset const * inset = getInset(i)) {
2139 inset->docbook(os, runparams);
2141 char_type c = d->text_[i];
2144 os << sgml::escapeChar(c);
2151 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2154 pos_type size = text_.size();
2155 for (pos_type i = initial; i < size; ++i) {
2156 Font font = owner_->getFont(buf.params(), i, outerfont);
2157 if (text_[i] == META_INSET)
2159 if (i != initial && font != font_old)
2168 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2170 OutputParams const & runparams,
2171 Font const & outerfont,
2172 pos_type initial) const
2174 bool emph_flag = false;
2176 Layout const & style = *d->layout_;
2178 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2180 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2183 // parsing main loop
2184 for (pos_type i = initial; i < size(); ++i) {
2185 Font font = getFont(buf.params(), i, outerfont);
2187 // handle <emphasis> tag
2188 if (font_old.emph() != font.fontInfo().emph()) {
2189 if (font.fontInfo().emph() == FONT_ON) {
2192 } else if (i != initial) {
2193 os << "</emphasis>";
2198 if (Inset const * inset = getInset(i)) {
2199 inset->docbook(os, runparams);
2201 char_type c = d->text_[i];
2203 if (style.pass_thru)
2206 os << sgml::escapeChar(c);
2208 font_old = font.fontInfo();
2212 os << "</emphasis>";
2215 if (style.free_spacing)
2217 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2222 bool Paragraph::isHfill(pos_type pos) const
2224 Inset const * inset = getInset(pos);
2225 return inset && (inset->lyxCode() == SPACE_CODE &&
2226 inset->isStretchableSpace());
2230 bool Paragraph::isNewline(pos_type pos) const
2232 Inset const * inset = getInset(pos);
2233 return inset && inset->lyxCode() == NEWLINE_CODE;
2237 bool Paragraph::isLineSeparator(pos_type pos) const
2239 char_type const c = d->text_[pos];
2240 if (isLineSeparatorChar(c))
2242 Inset const * inset = getInset(pos);
2243 return inset && inset->isLineSeparator();
2247 /// Used by the spellchecker
2248 bool Paragraph::isLetter(pos_type pos) const
2250 if (Inset const * inset = getInset(pos))
2251 return inset->isLetter();
2252 char_type const c = d->text_[pos];
2253 return isLetterChar(c) || isDigit(c);
2258 Paragraph::getParLanguage(BufferParams const & bparams) const
2261 return getFirstFontSettings(bparams).language();
2262 // FIXME: we should check the prev par as well (Lgb)
2263 return bparams.language;
2267 bool Paragraph::isRTL(BufferParams const & bparams) const
2269 return lyxrc.rtl_support
2270 && getParLanguage(bparams)->rightToLeft()
2271 && ownerCode() != ERT_CODE
2272 && ownerCode() != LISTINGS_CODE;
2276 void Paragraph::changeLanguage(BufferParams const & bparams,
2277 Language const * from, Language const * to)
2279 // change language including dummy font change at the end
2280 for (pos_type i = 0; i <= size(); ++i) {
2281 Font font = getFontSettings(bparams, i);
2282 if (font.language() == from) {
2283 font.setLanguage(to);
2290 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2292 Language const * doc_language = bparams.language;
2293 FontList::const_iterator cit = d->fontlist_.begin();
2294 FontList::const_iterator end = d->fontlist_.end();
2296 for (; cit != end; ++cit)
2297 if (cit->font().language() != ignore_language &&
2298 cit->font().language() != latex_language &&
2299 cit->font().language() != doc_language)
2305 docstring Paragraph::asString(int options) const
2307 return asString(0, size(), options);
2311 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2313 odocstringstream os;
2316 && options & AS_STR_LABEL
2317 && !d->params_.labelString().empty())
2318 os << d->params_.labelString() << ' ';
2320 for (pos_type i = beg; i < end; ++i) {
2321 char_type const c = d->text_[i];
2324 else if (c == META_INSET && options & AS_STR_INSETS)
2325 getInset(i)->textString(os);
2332 void Paragraph::setInsetOwner(Inset * inset)
2334 d->inset_owner_ = inset;
2338 int Paragraph::id() const
2344 Layout const & Paragraph::layout() const
2350 void Paragraph::setLayout(Layout const & layout)
2352 d->layout_ = &layout;
2356 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2358 if (useEmptyLayout())
2359 setLayout(tclass.emptyLayout());
2361 setLayout(tclass.defaultLayout());
2365 Inset * Paragraph::inInset() const
2367 return d->inset_owner_;
2371 InsetCode Paragraph::ownerCode() const
2373 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2377 ParagraphParameters & Paragraph::params()
2383 ParagraphParameters const & Paragraph::params() const
2389 bool Paragraph::isFreeSpacing() const
2391 if (d->layout_->free_spacing)
2393 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2397 bool Paragraph::allowEmpty() const
2399 if (d->layout_->keepempty)
2401 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2405 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2407 if (!Encodings::isArabicChar(c))
2410 char_type prev_char = ' ';
2411 char_type next_char = ' ';
2413 for (pos_type i = pos - 1; i >= 0; --i) {
2414 char_type const par_char = d->text_[i];
2415 if (!Encodings::isArabicComposeChar(par_char)) {
2416 prev_char = par_char;
2421 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2422 char_type const par_char = d->text_[i];
2423 if (!Encodings::isArabicComposeChar(par_char)) {
2424 next_char = par_char;
2429 if (Encodings::isArabicChar(next_char)) {
2430 if (Encodings::isArabicChar(prev_char) &&
2431 !Encodings::isArabicSpecialChar(prev_char))
2432 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2434 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2436 if (Encodings::isArabicChar(prev_char) &&
2437 !Encodings::isArabicSpecialChar(prev_char))
2438 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2440 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2445 int Paragraph::checkBiblio(Buffer const & buffer)
2448 // This is getting more and more a mess. ...We really should clean
2449 // up this bibitem issue for 1.6. See also bug 2743.
2451 // Add bibitem insets if necessary
2452 if (d->layout_->labeltype != LABEL_BIBLIO)
2455 bool hasbibitem = !d->insetlist_.empty()
2456 // Insist on it being in pos 0
2457 && d->text_[0] == META_INSET
2458 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2460 bool track_changes = buffer.params().trackChanges;
2465 // remove a bibitem in pos != 0
2466 // restore it later in pos 0 if necessary
2467 // (e.g. if a user inserts contents _before_ the item)
2468 // we're assuming there's only one of these, which there
2470 int erasedInsetPosition = -1;
2471 InsetList::iterator it = d->insetlist_.begin();
2472 InsetList::iterator end = d->insetlist_.end();
2473 for (; it != end; ++it)
2474 if (it->inset->lyxCode() == BIBITEM_CODE
2476 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2477 oldkey = olditem->getParam("key");
2478 oldlabel = olditem->getParam("label");
2479 erasedInsetPosition = it->pos;
2480 eraseChar(erasedInsetPosition, track_changes);
2484 // There was an InsetBibitem at the beginning, and we didn't
2485 // have to erase one.
2486 if (hasbibitem && erasedInsetPosition < 0)
2489 // There was an InsetBibitem at the beginning and we did have to
2490 // erase one. So we give its properties to the beginning inset.
2492 InsetBibitem * inset =
2493 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2494 if (!oldkey.empty())
2495 inset->setParam("key", oldkey);
2496 inset->setParam("label", oldlabel);
2497 return -erasedInsetPosition;
2500 // There was no inset at the beginning, so we need to create one with
2501 // the key and label of the one we erased.
2502 InsetBibitem * inset = new InsetBibitem(InsetCommandParams(BIBITEM_CODE));
2503 inset->setBuffer(const_cast<Buffer &>(buffer));
2504 // restore values of previously deleted item in this par.
2505 if (!oldkey.empty())
2506 inset->setParam("key", oldkey);
2507 inset->setParam("label", oldlabel);
2508 insertInset(0, static_cast<Inset *>(inset),
2509 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2515 void Paragraph::checkAuthors(AuthorList const & authorList)
2517 d->changes_.checkAuthors(authorList);
2521 bool Paragraph::isUnchanged(pos_type pos) const
2523 return lookupChange(pos).type == Change::UNCHANGED;
2527 bool Paragraph::isInserted(pos_type pos) const
2529 return lookupChange(pos).type == Change::INSERTED;
2533 bool Paragraph::isDeleted(pos_type pos) const
2535 return lookupChange(pos).type == Change::DELETED;
2539 InsetList const & Paragraph::insetList() const
2541 return d->insetlist_;
2545 Inset * Paragraph::releaseInset(pos_type pos)
2547 Inset * inset = d->insetlist_.release(pos);
2548 /// does not honour change tracking!
2549 eraseChar(pos, false);
2554 Inset * Paragraph::getInset(pos_type pos)
2556 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2557 ? d->insetlist_.get(pos) : 0;
2561 Inset const * Paragraph::getInset(pos_type pos) const
2563 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2564 ? d->insetlist_.get(pos) : 0;
2568 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2569 pos_type & right, TextCase action)
2571 // process sequences of modified characters; in change
2572 // tracking mode, this approach results in much better
2573 // usability than changing case on a char-by-char basis
2576 bool const trackChanges = bparams.trackChanges;
2578 bool capitalize = true;
2580 for (; pos < right; ++pos) {
2581 char_type oldChar = d->text_[pos];
2582 char_type newChar = oldChar;
2584 // ignore insets and don't play with deleted text!
2585 if (oldChar != META_INSET && !isDeleted(pos)) {
2587 case text_lowercase:
2588 newChar = lowercase(oldChar);
2590 case text_capitalization:
2592 newChar = uppercase(oldChar);
2596 case text_uppercase:
2597 newChar = uppercase(oldChar);
2602 if (!isLetter(pos) || isDeleted(pos)) {
2603 // permit capitalization again
2607 if (oldChar != newChar)
2610 if (oldChar == newChar || pos == right - 1) {
2611 if (oldChar != newChar) {
2612 // step behind the changing area
2615 int erasePos = pos - changes.size();
2616 for (size_t i = 0; i < changes.size(); i++) {
2617 insertChar(pos, changes[i],
2618 getFontSettings(bparams,
2621 if (!eraseChar(erasePos, trackChanges)) {
2624 ++right; // expand selection
2633 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2634 pos_type pos, bool del) const
2636 int const strsize = str.length();
2638 pos_type const parsize = d->text_.size();
2639 for (i = 0; pos + i < parsize; ++i) {
2642 if (cs && str[i] != d->text_[pos + i])
2644 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2646 if (!del && isDeleted(pos + i))
2653 // if necessary, check whether string matches word
2655 if (pos > 0 && isLetter(pos - 1))
2657 if (pos + strsize < parsize
2658 && isLetter(pos + strsize))
2666 char_type Paragraph::getChar(pos_type pos) const
2668 return d->text_[pos];
2672 pos_type Paragraph::size() const
2674 return d->text_.size();
2678 bool Paragraph::empty() const
2680 return d->text_.empty();
2684 bool Paragraph::isInset(pos_type pos) const
2686 return d->text_[pos] == META_INSET;
2690 bool Paragraph::isSeparator(pos_type pos) const
2692 //FIXME: Are we sure this can be the only separator?
2693 return d->text_[pos] == ' ';
2697 void Paragraph::deregisterWords()
2699 Private::Words::const_iterator it;
2700 WordList & wl = theWordList();
2701 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2707 void Paragraph::collectWords(CursorSlice const & sl)
2710 bool inword = false;
2712 //lyxerr << "Words: ";
2713 pos_type n = size();
2714 for (pos_type pos = 0; pos != n; ++pos) {
2718 if (!isLetter(pos)) {
2727 CursorSlice from = sl;
2728 CursorSlice to = sl;
2731 from.text()->getWord(from, to, WHOLE_WORD);
2732 if (to.pos() - from.pos() < 6)
2734 docstring word = asString(from.pos(), to.pos(), false);
2735 d->words_.insert(word);
2736 //lyxerr << word << " ";
2738 //lyxerr << std::endl;
2742 void Paragraph::registerWords()
2744 Private::Words::const_iterator it;
2745 WordList & wl = theWordList();
2746 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2751 void Paragraph::updateWords(CursorSlice const & sl)
2753 LASSERT(&sl.paragraph() == this, /**/);