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 if (docstring(1, next) == latex1) {
503 // the encoding supports the combination
504 os << latex2 << latex1;
505 return latex1.length() + latex2.length();
507 os << latex1 << '{' << latex2 << '}';
508 return latex1.length() + latex2.length() + 2;
512 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
513 odocstream & os, TexRow & texrow,
515 unsigned int & column,
517 Layout const & style)
519 if (style.pass_thru || runparams.verbatim)
522 if (i + 1 < int(text_.size())) {
523 char_type next = text_[i + 1];
524 if (Encodings::isCombiningChar(next)) {
525 Encoding const & encoding = *(runparams.encoding);
526 // This space has an accent, so we must always output it.
527 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
532 if (lyxrc.plaintext_linelen > 0
533 && column > lyxrc.plaintext_linelen
535 && text_[i - 1] != ' '
536 && (i + 1 < int(text_.size()))
537 // same in FreeSpacing mode
538 && !owner_->isFreeSpacing()
539 // In typewriter mode, we want to avoid
540 // ! . ? : at the end of a line
541 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
542 && (text_[i - 1] == '.'
543 || text_[i - 1] == '?'
544 || text_[i - 1] == ':'
545 || text_[i - 1] == '!'))) {
548 texrow.start(owner_->id(), i + 1);
550 } else if (style.free_spacing) {
559 int Paragraph::Private::writeScriptChars(odocstream & os,
560 docstring const & ltx,
561 Change & runningChange,
562 Encoding const & encoding,
565 // FIXME: modifying i here is not very nice...
567 // We only arrive here when a proper language for character text_[i] has
568 // not been specified (i.e., it could not be translated in the current
569 // latex encoding) and it belongs to a known script.
570 // Parameter ltx contains the latex translation of text_[i] as specified in
571 // the unicodesymbols file and is something like "\textXXX{<spec>}".
572 // The latex macro name "textXXX" specifies the script to which text_[i]
573 // belongs and we use it in order to check whether characters from the
574 // same script immediately follow, such that we can collect them in a
575 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
576 // for the first char but only "<spec>" for all subsequent chars.
577 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
578 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
579 string script = to_ascii(ltx.substr(1, brace1 - 1));
580 int length = ltx.substr(0, brace2).length();
581 os << ltx.substr(0, brace2);
582 int size = text_.size();
583 while (i + 1 < size) {
584 char_type const next = text_[i + 1];
585 // Stop here if next character belongs to another script
586 // or there is a change in change tracking status.
587 if (!Encodings::isKnownScriptChar(next, script) ||
588 runningChange != owner_->lookupChange(i + 1))
592 FontList::const_iterator cit = fontlist_.begin();
593 FontList::const_iterator end = fontlist_.end();
594 for (; cit != end; ++cit) {
595 if (cit->pos() >= i && !found) {
596 prev_font = cit->font();
599 if (cit->pos() >= i + 1)
602 // Stop here if there is a font attribute or encoding change.
603 if (found && cit != end && prev_font != cit->font())
605 docstring const latex = encoding.latexChar(next);
606 docstring::size_type const b1 =
607 latex.find_first_of(from_ascii("{"));
608 docstring::size_type const b2 =
609 latex.find_last_of(from_ascii("}"));
610 int const len = b2 - b1 - 1;
611 os << latex.substr(b1 + 1, len);
621 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
623 pos_type const len = str.length();
625 // is the paragraph large enough?
626 if (pos + len > int(text_.size()))
629 // does the wanted text start at point?
630 for (string::size_type i = 0; i < str.length(); ++i) {
631 // Caution: direct comparison of characters works only
632 // because str is pure ASCII.
633 if (str[i] != text_[pos + i])
637 return fontlist_.hasChangeInRange(pos, len);
641 void Paragraph::Private::latexInset(
642 BufferParams const & bparams,
645 OutputParams & runparams,
648 Font const & outerfont,
650 Change & running_change,
651 Layout const & style,
653 unsigned int & column)
655 Inset * inset = owner_->getInset(i);
656 LASSERT(inset, /**/);
658 if (style.pass_thru) {
659 inset->plaintext(os, runparams);
663 // FIXME: move this to InsetNewline::latex
664 if (inset->lyxCode() == NEWLINE_CODE) {
665 // newlines are handled differently here than
666 // the default in simpleTeXSpecialChars().
667 if (!style.newline_allowed) {
671 column += running_font.latexWriteEndChanges(
672 os, bparams, runparams,
677 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
680 basefont = owner_->getLayoutFont(bparams, outerfont);
681 running_font = basefont;
683 if (runparams.moving_arg)
688 texrow.start(owner_->id(), i + 1);
692 if (owner_->lookupChange(i).type == Change::DELETED) {
693 if( ++runparams.inDeletedInset == 1)
694 runparams.changeOfDeletedInset = owner_->lookupChange(i);
697 if (inset->canTrackChanges()) {
698 column += Changes::latexMarkChange(os, bparams, running_change,
699 Change(Change::UNCHANGED));
700 running_change = Change(Change::UNCHANGED);
704 odocstream::pos_type const len = os.tellp();
706 if (inset->forceLTR()
707 && running_font.isRightToLeft()
708 // ERT is an exception, it should be output with no decorations at all
709 && inset->lyxCode() != ERT_CODE) {
710 if (running_font.language()->lang() == "farsi")
717 // FIXME: Bug: we can have an empty font change here!
718 // if there has just been a font change, we are going to close it
719 // right now, which means stupid latex code like \textsf{}. AFAIK,
720 // this does not harm dvi output. A minor bug, thus (JMarc)
722 // Some insets cannot be inside a font change command.
723 // However, even such insets *can* be placed in \L or \R
724 // or their equivalents (for RTL language switches), so we don't
725 // close the language in those cases.
726 // ArabTeX, though, cannot handle this special behavior, it seems.
727 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
728 || running_font.language()->lang() == "arabic_arabtex";
729 if (open_font && inset->noFontChange()) {
730 bool closeLanguage = arabtex
731 || basefont.isRightToLeft() == running_font.isRightToLeft();
732 unsigned int count = running_font.latexWriteEndChanges(os,
733 bparams, runparams, basefont, basefont, closeLanguage);
735 // if any font properties were closed, update the running_font,
736 // making sure, however, to leave the language as it was
738 // FIXME: probably a better way to keep track of the old
739 // language, than copying the entire font?
740 Font const copy_font(running_font);
741 basefont = owner_->getLayoutFont(bparams, outerfont);
742 running_font = basefont;
744 running_font.setLanguage(copy_font.language());
745 // leave font open if language is still open
746 open_font = (running_font.language() == basefont.language());
748 runparams.local_font = &basefont;
755 tmp = inset->latex(os, runparams);
756 } catch (EncodingException & e) {
757 // add location information and throw again.
764 if (running_font.language()->lang() == "farsi")
771 for (int j = 0; j < tmp; ++j)
774 texrow.start(owner_->id(), i + 1);
777 column += os.tellp() - len;
780 if (owner_->lookupChange(i).type == Change::DELETED)
781 --runparams.inDeletedInset;
785 void Paragraph::Private::latexSpecialChar(
787 OutputParams & runparams,
789 Change & running_change,
790 Layout const & style,
792 unsigned int & column)
794 char_type const c = text_[i];
796 if (style.pass_thru) {
798 // FIXME UNICODE: This can fail if c cannot
799 // be encoded in the current encoding.
804 if (runparams.verbatim) {
809 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
812 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
813 && latexSpecialTypewriter(c, os, i, column))
816 // Otherwise, we use what LaTeX provides us.
819 os << "\\textbackslash{}";
823 os << "\\textless{}";
827 os << "\\textgreater{}";
838 os << "\\char`\\\"{}";
843 case '%': case '#': case '{':
851 os << "\\textasciitilde{}";
856 os << "\\textasciicircum{}";
861 // avoid being mistaken for optional arguments
869 // Blanks are printed before font switching.
870 // Sure? I am not! (try nice-latex)
871 // I am sure it's correct. LyX might be smarter
872 // in the future, but for now, nothing wrong is
879 if (latexSpecialPhrase(os, i, column, runparams))
885 Encoding const & encoding = *(runparams.encoding);
886 if (i + 1 < int(text_.size())) {
887 char_type next = text_[i + 1];
888 if (Encodings::isCombiningChar(next)) {
889 column += latexSurrogatePair(os, c, next, encoding) - 1;
895 docstring const latex = encoding.latexChar(c);
896 if (Encodings::isKnownScriptChar(c, script)
897 && prefixIs(latex, from_ascii("\\" + script)))
898 column += writeScriptChars(os, latex,
899 running_change, encoding, i) - 1;
900 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
901 // Prevent eating of a following
902 // space or command corruption by
903 // following characters
904 column += latex.length() + 1;
907 column += latex.length() - 1;
915 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
916 pos_type & i, unsigned int & column)
922 // In T1 encoding, these characters exist
923 // but we should avoid ligatures
924 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
929 //os << "\\textcompwordmark{}";
941 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
942 pos_type & i, unsigned int & column)
946 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
947 // "--" in Typewriter mode -> "-{}-"
954 // FIXME I assume this is hack treating typewriter as verbatim
955 // This should be re-evaluated eventually.
960 // // Those characters are not directly supported.
963 // case '$': case '&':
964 // case '%': case '#': case '{':
965 // case '}': case '_':
968 // case '*': case '[':
978 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
979 unsigned int & column, OutputParams & runparams)
981 // FIXME: if we have "LaTeX" with a font
982 // change in the middle (before the 'T', then
983 // the "TeX" part is still special cased.
984 // Really we should only operate this on
985 // "words" for some definition of word
987 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
988 if (!isTextAt(special_phrases[pnr].phrase, i))
990 if (runparams.moving_arg)
992 os << special_phrases[pnr].macro;
993 i += special_phrases[pnr].phrase.length() - 1;
994 column += special_phrases[pnr].macro.length() - 1;
1001 void Paragraph::Private::validate(LaTeXFeatures & features,
1002 Layout const & layout) const
1004 // check the params.
1005 if (!params_.spacing().isDefault())
1006 features.require("setspace");
1009 features.useLayout(layout.name());
1012 fontlist_.validate(features);
1014 // then the indentation
1015 if (!params_.leftIndent().zero())
1016 features.require("ParagraphLeftIndent");
1019 InsetList::const_iterator icit = insetlist_.begin();
1020 InsetList::const_iterator iend = insetlist_.end();
1021 for (; icit != iend; ++icit) {
1023 icit->inset->validate(features);
1024 if (layout.needprotect &&
1025 icit->inset->lyxCode() == FOOT_CODE)
1026 features.require("NeedLyXFootnoteCode");
1030 // then the contents
1031 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1032 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1033 if (!special_phrases[pnr].builtin
1034 && isTextAt(special_phrases[pnr].phrase, i)) {
1035 features.require(special_phrases[pnr].phrase);
1039 Encodings::validate(text_[i], features);
1043 /////////////////////////////////////////////////////////////////////
1047 /////////////////////////////////////////////////////////////////////
1050 Layout const emptyParagraphLayout;
1053 Paragraph::Paragraph()
1054 : d(new Paragraph::Private(this, emptyParagraphLayout))
1061 Paragraph::Paragraph(Paragraph const & par)
1062 : itemdepth(par.itemdepth),
1063 d(new Paragraph::Private(*par.d, this))
1069 Paragraph & Paragraph::operator=(Paragraph const & par)
1071 // needed as we will destroy the private part before copying it
1073 itemdepth = par.itemdepth;
1077 d = new Private(*par.d, this);
1084 Paragraph::~Paragraph()
1091 void Paragraph::write(ostream & os, BufferParams const & bparams,
1092 depth_type & dth) const
1094 // The beginning or end of a deeper (i.e. nested) area?
1095 if (dth != d->params_.depth()) {
1096 if (d->params_.depth() > dth) {
1097 while (d->params_.depth() > dth) {
1098 os << "\n\\begin_deeper";
1102 while (d->params_.depth() < dth) {
1103 os << "\n\\end_deeper";
1109 // First write the layout
1110 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1112 d->params_.write(os);
1114 Font font1(inherit_font, bparams.language);
1116 Change running_change = Change(Change::UNCHANGED);
1119 for (pos_type i = 0; i <= size(); ++i) {
1121 Change change = lookupChange(i);
1122 Changes::lyxMarkChange(os, column, running_change, change);
1123 running_change = change;
1128 // Write font changes
1129 Font font2 = getFontSettings(bparams, i);
1130 if (font2 != font1) {
1131 font2.lyxWriteChanges(font1, os);
1136 char_type const c = d->text_[i];
1139 if (Inset const * inset = getInset(i)) {
1140 if (inset->directWrite()) {
1141 // international char, let it write
1142 // code directly so it's shorter in
1148 os << "\\begin_inset ";
1150 os << "\n\\end_inset\n\n";
1156 os << "\n\\backslash\n";
1160 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1167 if ((column > 70 && c == ' ')
1172 // this check is to amend a bug. LyX sometimes
1173 // inserts '\0' this could cause problems.
1175 os << to_utf8(docstring(1, c));
1177 LYXERR0("NUL char in structure.");
1183 os << "\n\\end_layout\n";
1187 void Paragraph::validate(LaTeXFeatures & features) const
1189 d->validate(features, *d->layout_);
1193 void Paragraph::insert(pos_type start, docstring const & str,
1194 Font const & font, Change const & change)
1196 for (size_t i = 0, n = str.size(); i != n ; ++i)
1197 insertChar(start + i, str[i], font, change);
1201 void Paragraph::appendChar(char_type c, Font const & font,
1202 Change const & change)
1205 d->changes_.insert(change, d->text_.size());
1206 // when appending characters, no need to update tables
1207 d->text_.push_back(c);
1208 setFont(d->text_.size() - 1, font);
1212 void Paragraph::appendString(docstring const & s, Font const & font,
1213 Change const & change)
1215 pos_type end = s.size();
1216 size_t oldsize = d->text_.size();
1217 size_t newsize = oldsize + end;
1218 size_t capacity = d->text_.capacity();
1219 if (newsize >= capacity)
1220 d->text_.reserve(max(capacity + 100, newsize));
1222 // when appending characters, no need to update tables
1225 // FIXME: Optimize this!
1226 for (pos_type i = oldsize; i != newsize; ++i) {
1228 d->changes_.insert(change, i);
1230 d->fontlist_.set(oldsize, font);
1231 d->fontlist_.set(newsize - 1, font);
1235 void Paragraph::insertChar(pos_type pos, char_type c,
1238 d->insertChar(pos, c, Change(trackChanges ?
1239 Change::INSERTED : Change::UNCHANGED));
1243 void Paragraph::insertChar(pos_type pos, char_type c,
1244 Font const & font, bool trackChanges)
1246 d->insertChar(pos, c, Change(trackChanges ?
1247 Change::INSERTED : Change::UNCHANGED));
1252 void Paragraph::insertChar(pos_type pos, char_type c,
1253 Font const & font, Change const & change)
1255 d->insertChar(pos, c, change);
1260 void Paragraph::insertInset(pos_type pos, Inset * inset,
1261 Font const & font, Change const & change)
1263 insertInset(pos, inset, change);
1264 // Set the font/language of the inset...
1269 bool Paragraph::insetAllowed(InsetCode code)
1271 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
1275 void Paragraph::resetFonts(Font const & font)
1277 d->fontlist_.clear();
1278 d->fontlist_.set(0, font);
1279 d->fontlist_.set(d->text_.size() - 1, font);
1282 // Gets uninstantiated font setting at position.
1283 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1287 LYXERR0("pos: " << pos << " size: " << size());
1288 LASSERT(pos <= size(), /**/);
1291 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1292 if (cit != d->fontlist_.end())
1295 if (pos == size() && !empty())
1296 return getFontSettings(bparams, pos - 1);
1298 return Font(inherit_font, getParLanguage(bparams));
1302 FontSpan Paragraph::fontSpan(pos_type pos) const
1304 LASSERT(pos <= size(), /**/);
1307 FontList::const_iterator cit = d->fontlist_.begin();
1308 FontList::const_iterator end = d->fontlist_.end();
1309 for (; cit != end; ++cit) {
1310 if (cit->pos() >= pos) {
1311 if (pos >= beginOfBody())
1312 return FontSpan(max(start, beginOfBody()),
1315 return FontSpan(start,
1316 min(beginOfBody() - 1,
1319 start = cit->pos() + 1;
1322 // This should not happen, but if so, we take no chances.
1323 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1324 return FontSpan(pos, pos);
1328 // Gets uninstantiated font setting at position 0
1329 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1331 if (!empty() && !d->fontlist_.empty())
1332 return d->fontlist_.begin()->font();
1334 return Font(inherit_font, bparams.language);
1338 // Gets the fully instantiated font at a given position in a paragraph
1339 // This is basically the same function as Text::GetFont() in text2.cpp.
1340 // The difference is that this one is used for generating the LaTeX file,
1341 // and thus cosmetic "improvements" are disallowed: This has to deliver
1342 // the true picture of the buffer. (Asger)
1343 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1344 Font const & outerfont) const
1346 LASSERT(pos >= 0, /**/);
1348 Font font = getFontSettings(bparams, pos);
1350 pos_type const body_pos = beginOfBody();
1352 font.fontInfo().realize(d->layout_->labelfont);
1354 font.fontInfo().realize(d->layout_->font);
1356 font.fontInfo().realize(outerfont.fontInfo());
1357 font.fontInfo().realize(bparams.getFont().fontInfo());
1363 Font const Paragraph::getLabelFont
1364 (BufferParams const & bparams, Font const & outerfont) const
1366 FontInfo tmpfont = d->layout_->labelfont;
1367 tmpfont.realize(outerfont.fontInfo());
1368 tmpfont.realize(bparams.getFont().fontInfo());
1369 return Font(tmpfont, getParLanguage(bparams));
1373 Font const Paragraph::getLayoutFont
1374 (BufferParams const & bparams, Font const & outerfont) const
1376 FontInfo tmpfont = d->layout_->font;
1377 tmpfont.realize(outerfont.fontInfo());
1378 tmpfont.realize(bparams.getFont().fontInfo());
1379 return Font(tmpfont, getParLanguage(bparams));
1383 /// Returns the height of the highest font in range
1384 FontSize Paragraph::highestFontInRange
1385 (pos_type startpos, pos_type endpos, FontSize def_size) const
1387 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1391 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1393 char_type c = d->text_[pos];
1394 if (!lyxrc.rtl_support)
1424 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1430 void Paragraph::setFont(pos_type pos, Font const & font)
1432 LASSERT(pos <= size(), /**/);
1434 // First, reduce font against layout/label font
1435 // Update: The setCharFont() routine in text2.cpp already
1436 // reduces font, so we don't need to do that here. (Asger)
1438 d->fontlist_.set(pos, font);
1442 void Paragraph::makeSameLayout(Paragraph const & par)
1444 d->layout_ = par.d->layout_;
1445 d->params_ = par.d->params_;
1449 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1451 if (isFreeSpacing())
1457 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1458 if (eraseChar(pos, trackChanges))
1464 return count > 0 || pos > 0;
1468 bool Paragraph::hasSameLayout(Paragraph const & par) const
1470 return par.d->layout_ == d->layout_
1471 && d->params_.sameLayout(par.d->params_);
1475 depth_type Paragraph::getDepth() const
1477 return d->params_.depth();
1481 depth_type Paragraph::getMaxDepthAfter() const
1483 if (d->layout_->isEnvironment())
1484 return d->params_.depth() + 1;
1486 return d->params_.depth();
1490 char Paragraph::getAlign() const
1492 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1493 return d->layout_->align;
1495 return d->params_.align();
1499 docstring const & Paragraph::labelString() const
1501 return d->params_.labelString();
1505 // the next two functions are for the manual labels
1506 docstring const Paragraph::getLabelWidthString() const
1508 if (d->layout_->margintype == MARGIN_MANUAL)
1509 return d->params_.labelWidthString();
1511 return _("Senseless with this layout!");
1515 void Paragraph::setLabelWidthString(docstring const & s)
1517 d->params_.labelWidthString(s);
1521 docstring const Paragraph::translateIfPossible(docstring const & s,
1522 BufferParams const & bparams) const
1524 if (!isAscii(s) || s.empty()) {
1525 // This must be a user defined layout. We cannot translate
1526 // this, since gettext accepts only ascii keys.
1529 // Probably standard layout, try to translate
1530 Messages & m = getMessages(getParLanguage(bparams)->code());
1531 return m.get(to_ascii(s));
1535 docstring Paragraph::expandLabel(Layout const & layout,
1536 BufferParams const & bparams, bool process_appendix) const
1538 DocumentClass const & tclass = bparams.documentClass();
1541 if (process_appendix && d->params_.appendix())
1542 fmt = translateIfPossible(layout.labelstring_appendix(),
1545 fmt = translateIfPossible(layout.labelstring(), bparams);
1547 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1548 && !layout.counter.empty())
1549 fmt = "\\the" + layout.counter;
1551 // handle 'inherited level parts' in 'fmt',
1552 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1553 size_t const i = fmt.find('@', 0);
1554 if (i != docstring::npos) {
1555 size_t const j = fmt.find('@', i + 1);
1556 if (j != docstring::npos) {
1557 docstring parent(fmt, i + 1, j - i - 1);
1558 docstring label = from_ascii("??");
1559 if (tclass.hasLayout(parent))
1560 docstring label = expandLabel(tclass[parent], bparams,
1562 fmt = docstring(fmt, 0, i) + label
1563 + docstring(fmt, j + 1, docstring::npos);
1567 return tclass.counters().counterLabel(fmt);
1571 void Paragraph::applyLayout(Layout const & new_layout)
1573 d->layout_ = &new_layout;
1574 LyXAlignment const oldAlign = d->params_.align();
1576 if (!(oldAlign & d->layout_->alignpossible)) {
1577 frontend::Alert::warning(_("Alignment not permitted"),
1578 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1579 d->params_.align(LYX_ALIGN_LAYOUT);
1584 pos_type Paragraph::beginOfBody() const
1586 return d->begin_of_body_;
1590 void Paragraph::setBeginOfBody()
1592 if (d->layout_->labeltype != LABEL_MANUAL) {
1593 d->begin_of_body_ = 0;
1597 // Unroll the first two cycles of the loop
1598 // and remember the previous character to
1599 // remove unnecessary getChar() calls
1601 pos_type end = size();
1602 if (i < end && !isNewline(i)) {
1604 char_type previous_char = 0;
1607 previous_char = d->text_[i];
1608 if (!isNewline(i)) {
1610 while (i < end && previous_char != ' ') {
1615 previous_char = temp;
1621 d->begin_of_body_ = i;
1625 bool Paragraph::forceEmptyLayout() const
1627 Inset const * const inset = inInset();
1630 return inset->forceEmptyLayout();
1634 bool Paragraph::allowParagraphCustomization() const
1636 Inset const * const inset = inInset();
1639 return inset->allowParagraphCustomization();
1643 bool Paragraph::useEmptyLayout() const
1645 Inset const * const inset = inInset();
1648 return inset->useEmptyLayout();
1654 // paragraphs inside floats need different alignment tags to avoid
1657 bool noTrivlistCentering(InsetCode code)
1659 return code == FLOAT_CODE || code == WRAP_CODE;
1663 string correction(string const & orig)
1665 if (orig == "flushleft")
1666 return "raggedright";
1667 if (orig == "flushright")
1668 return "raggedleft";
1669 if (orig == "center")
1675 string const corrected_env(string const & suffix, string const & env,
1678 string output = suffix + "{";
1679 if (noTrivlistCentering(code))
1680 output += correction(env);
1684 if (suffix == "\\begin")
1690 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1692 if (!contains(str, "\n"))
1693 column += str.size();
1697 column = rsplit(str, tmp, '\n').size();
1704 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1705 odocstream & os, TexRow & texrow,
1706 bool moving_arg) const
1710 if (params_.noindent()) {
1711 os << "\\noindent ";
1715 LyXAlignment const curAlign = params_.align();
1717 if (curAlign == layout_->align)
1721 case LYX_ALIGN_NONE:
1722 case LYX_ALIGN_BLOCK:
1723 case LYX_ALIGN_LAYOUT:
1724 case LYX_ALIGN_SPECIAL:
1726 case LYX_ALIGN_LEFT:
1727 case LYX_ALIGN_RIGHT:
1728 case LYX_ALIGN_CENTER:
1737 case LYX_ALIGN_NONE:
1738 case LYX_ALIGN_BLOCK:
1739 case LYX_ALIGN_LAYOUT:
1740 case LYX_ALIGN_SPECIAL:
1742 case LYX_ALIGN_LEFT: {
1744 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1745 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1747 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1748 os << from_ascii(output);
1749 adjust_row_column(output, texrow, column);
1751 } case LYX_ALIGN_RIGHT: {
1753 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1754 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1756 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1757 os << from_ascii(output);
1758 adjust_row_column(output, texrow, column);
1760 } case LYX_ALIGN_CENTER: {
1762 output = corrected_env("\\begin", "center", owner_->ownerCode());
1763 os << from_ascii(output);
1764 adjust_row_column(output, texrow, column);
1773 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1774 odocstream & os, TexRow & texrow,
1775 bool moving_arg) const
1779 switch (params_.align()) {
1780 case LYX_ALIGN_NONE:
1781 case LYX_ALIGN_BLOCK:
1782 case LYX_ALIGN_LAYOUT:
1783 case LYX_ALIGN_SPECIAL:
1785 case LYX_ALIGN_LEFT:
1786 case LYX_ALIGN_RIGHT:
1787 case LYX_ALIGN_CENTER:
1795 switch (params_.align()) {
1796 case LYX_ALIGN_NONE:
1797 case LYX_ALIGN_BLOCK:
1798 case LYX_ALIGN_LAYOUT:
1799 case LYX_ALIGN_SPECIAL:
1801 case LYX_ALIGN_LEFT: {
1803 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1804 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1806 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1807 os << from_ascii(output);
1808 adjust_row_column(output, texrow, column);
1810 } case LYX_ALIGN_RIGHT: {
1812 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1813 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1815 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1816 os << from_ascii(output);
1817 adjust_row_column(output, texrow, column);
1819 } case LYX_ALIGN_CENTER: {
1821 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1822 os << from_ascii(output);
1823 adjust_row_column(output, texrow, column);
1832 // This one spits out the text of the paragraph
1833 bool Paragraph::latex(BufferParams const & bparams,
1834 Font const & outerfont,
1835 odocstream & os, TexRow & texrow,
1836 OutputParams const & runparams) const
1838 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1840 bool return_value = false;
1842 bool asdefault = forceEmptyLayout();
1844 Layout const & style = asdefault ?
1845 bparams.documentClass().emptyLayout() :
1848 // Current base font for all inherited font changes, without any
1849 // change caused by an individual character, except for the language:
1850 // It is set to the language of the first character.
1851 // As long as we are in the label, this font is the base font of the
1852 // label. Before the first body character it is set to the base font
1856 // Maybe we have to create a optional argument.
1857 pos_type body_pos = beginOfBody();
1858 unsigned int column = 0;
1861 // the optional argument is kept in curly brackets in
1862 // case it contains a ']'
1865 basefont = getLabelFont(bparams, outerfont);
1867 basefont = getLayoutFont(bparams, outerfont);
1870 // Which font is currently active?
1871 Font running_font(basefont);
1872 // Do we have an open font change?
1873 bool open_font = false;
1875 Change runningChange = Change(Change::UNCHANGED);
1877 texrow.start(id(), 0);
1879 // if the paragraph is empty, the loop will not be entered at all
1881 if (style.isCommand()) {
1886 column += d->startTeXParParams(bparams, os, texrow,
1887 runparams.moving_arg);
1890 for (pos_type i = 0; i < size(); ++i) {
1891 // First char in paragraph or after label?
1892 if (i == body_pos) {
1895 column += running_font.latexWriteEndChanges(
1896 os, bparams, runparams,
1897 basefont, basefont);
1900 basefont = getLayoutFont(bparams, outerfont);
1901 running_font = basefont;
1903 column += Changes::latexMarkChange(os, bparams,
1904 runningChange, Change(Change::UNCHANGED));
1905 runningChange = Change(Change::UNCHANGED);
1910 if (style.isCommand()) {
1916 column += d->startTeXParParams(bparams, os,
1918 runparams.moving_arg);
1921 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1924 if (bparams.outputChanges && runningChange != change) {
1926 column += running_font.latexWriteEndChanges(
1927 os, bparams, runparams, basefont, basefont);
1930 basefont = getLayoutFont(bparams, outerfont);
1931 running_font = basefont;
1933 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1934 runningChange = change;
1937 // do not output text which is marked deleted
1938 // if change tracking output is disabled
1939 if (!bparams.outputChanges && change.type == Change::DELETED) {
1945 // Fully instantiated font
1946 Font const font = getFont(bparams, i, outerfont);
1948 Font const last_font = running_font;
1950 // Do we need to close the previous font?
1952 (font != running_font ||
1953 font.language() != running_font.language()))
1955 column += running_font.latexWriteEndChanges(
1956 os, bparams, runparams, basefont,
1957 (i == body_pos-1) ? basefont : font);
1958 running_font = basefont;
1962 // close babel's font environment before opening CJK.
1963 if (!running_font.language()->babel().empty() &&
1964 font.language()->encoding()->package() == Encoding::CJK) {
1965 string end_tag = subst(lyxrc.language_command_end,
1967 running_font.language()->babel());
1968 os << from_ascii(end_tag);
1969 column += end_tag.length();
1972 // Switch file encoding if necessary (and allowed)
1973 if (!runparams.verbatim &&
1974 runparams.encoding->package() != Encoding::none &&
1975 font.language()->encoding()->package() != Encoding::none) {
1976 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
1977 runparams, *(font.language()->encoding()));
1978 if (enc_switch.first) {
1979 column += enc_switch.second;
1980 runparams.encoding = font.language()->encoding();
1984 char_type const c = d->text_[i];
1986 // Do we need to change font?
1987 if ((font != running_font ||
1988 font.language() != running_font.language()) &&
1991 odocstringstream ods;
1992 column += font.latexWriteStartChanges(ods, bparams,
1993 runparams, basefont,
1995 running_font = font;
1997 docstring fontchange = ods.str();
1998 // check if the fontchange ends with a trailing blank
1999 // (like "\small " (see bug 3382)
2000 if (suffixIs(fontchange, ' ') && c == ' ')
2001 os << fontchange.substr(0, fontchange.size() - 1)
2002 << from_ascii("{}");
2008 // FIXME: integrate this case in latexSpecialChar
2009 // Do not print the separation of the optional argument
2010 // if style.pass_thru is false. This works because
2011 // latexSpecialChar ignores spaces if
2012 // style.pass_thru is false.
2013 if (i != body_pos - 1) {
2014 if (d->simpleTeXBlanks(
2015 runparams, os, texrow,
2016 i, column, font, style)) {
2017 // A surrogate pair was output. We
2018 // must not call latexSpecialChar
2019 // in this iteration, since it would output
2020 // the combining character again.
2027 OutputParams rp = runparams;
2028 rp.free_spacing = style.free_spacing;
2029 rp.local_font = &font;
2030 rp.intitle = style.intitle;
2032 // Two major modes: LaTeX or plain
2033 // Handle here those cases common to both modes
2034 // and then split to handle the two modes separately.
2035 if (c == META_INSET)
2036 d->latexInset(bparams, os,
2037 texrow, rp, running_font,
2038 basefont, outerfont, open_font,
2039 runningChange, style, i, column);
2042 d->latexSpecialChar(os, rp, running_font, runningChange,
2044 } catch (EncodingException & e) {
2045 if (runparams.dryrun) {
2046 os << "<" << _("LyX Warning: ")
2047 << _("uncodable character") << " '";
2051 // add location information and throw again.
2059 // Set the encoding to that returned from simpleTeXSpecialChars (see
2060 // comment for encoding member in OutputParams.h)
2061 runparams.encoding = rp.encoding;
2064 // If we have an open font definition, we have to close it
2066 #ifdef FIXED_LANGUAGE_END_DETECTION
2069 .latexWriteEndChanges(os, bparams, runparams,
2071 next_->getFont(bparams, 0, outerfont));
2073 running_font.latexWriteEndChanges(os, bparams,
2074 runparams, basefont, basefont);
2077 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2078 //FIXME: there as we start another \selectlanguage with the next paragraph if
2079 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2080 running_font.latexWriteEndChanges(os, bparams, runparams,
2081 basefont, basefont);
2085 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2087 // Needed if there is an optional argument but no contents.
2088 if (body_pos > 0 && body_pos == size()) {
2090 return_value = false;
2094 column += d->endTeXParParams(bparams, os, texrow,
2095 runparams.moving_arg);
2098 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2099 return return_value;
2103 bool Paragraph::emptyTag() const
2105 for (pos_type i = 0; i < size(); ++i) {
2106 if (Inset const * inset = getInset(i)) {
2107 InsetCode lyx_code = inset->lyxCode();
2108 if (lyx_code != TOC_CODE &&
2109 lyx_code != INCLUDE_CODE &&
2110 lyx_code != GRAPHICS_CODE &&
2111 lyx_code != ERT_CODE &&
2112 lyx_code != LISTINGS_CODE &&
2113 lyx_code != FLOAT_CODE &&
2114 lyx_code != TABULAR_CODE) {
2118 char_type c = d->text_[i];
2119 if (c != ' ' && c != '\t')
2127 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2130 for (pos_type i = 0; i < size(); ++i) {
2131 if (Inset const * inset = getInset(i)) {
2132 InsetCode lyx_code = inset->lyxCode();
2133 if (lyx_code == LABEL_CODE) {
2134 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2135 docstring const & id = il->getParam("name");
2136 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2144 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2148 for (i = 0; i < size(); ++i) {
2149 if (Inset const * inset = getInset(i)) {
2150 inset->docbook(os, runparams);
2152 char_type c = d->text_[i];
2155 os << sgml::escapeChar(c);
2162 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2165 pos_type size = text_.size();
2166 for (pos_type i = initial; i < size; ++i) {
2167 Font font = owner_->getFont(buf.params(), i, outerfont);
2168 if (text_[i] == META_INSET)
2170 if (i != initial && font != font_old)
2179 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2181 OutputParams const & runparams,
2182 Font const & outerfont,
2183 pos_type initial) const
2185 bool emph_flag = false;
2187 Layout const & style = *d->layout_;
2189 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2191 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2194 // parsing main loop
2195 for (pos_type i = initial; i < size(); ++i) {
2196 Font font = getFont(buf.params(), i, outerfont);
2198 // handle <emphasis> tag
2199 if (font_old.emph() != font.fontInfo().emph()) {
2200 if (font.fontInfo().emph() == FONT_ON) {
2203 } else if (i != initial) {
2204 os << "</emphasis>";
2209 if (Inset const * inset = getInset(i)) {
2210 inset->docbook(os, runparams);
2212 char_type c = d->text_[i];
2214 if (style.pass_thru)
2217 os << sgml::escapeChar(c);
2219 font_old = font.fontInfo();
2223 os << "</emphasis>";
2226 if (style.free_spacing)
2228 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2233 bool Paragraph::isHfill(pos_type pos) const
2235 Inset const * inset = getInset(pos);
2236 return inset && (inset->lyxCode() == SPACE_CODE &&
2237 inset->isStretchableSpace());
2241 bool Paragraph::isNewline(pos_type pos) const
2243 Inset const * inset = getInset(pos);
2244 return inset && inset->lyxCode() == NEWLINE_CODE;
2248 bool Paragraph::isLineSeparator(pos_type pos) const
2250 char_type const c = d->text_[pos];
2251 if (isLineSeparatorChar(c))
2253 Inset const * inset = getInset(pos);
2254 return inset && inset->isLineSeparator();
2258 /// Used by the spellchecker
2259 bool Paragraph::isLetter(pos_type pos) const
2261 if (Inset const * inset = getInset(pos))
2262 return inset->isLetter();
2263 char_type const c = d->text_[pos];
2264 return isLetterChar(c) || isDigit(c);
2268 bool Paragraph::isChar(pos_type pos) const
2270 if (Inset const * inset = getInset(pos))
2271 return inset->isChar();
2272 char_type const c = d->text_[pos];
2273 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2277 bool Paragraph::isSpace(pos_type pos) const
2279 if (Inset const * inset = getInset(pos))
2280 return inset->isSpace();
2281 char_type const c = d->text_[pos];
2282 return lyx::isSpace(c);
2287 Paragraph::getParLanguage(BufferParams const & bparams) const
2290 return getFirstFontSettings(bparams).language();
2291 // FIXME: we should check the prev par as well (Lgb)
2292 return bparams.language;
2296 bool Paragraph::isRTL(BufferParams const & bparams) const
2298 return lyxrc.rtl_support
2299 && getParLanguage(bparams)->rightToLeft()
2300 && ownerCode() != ERT_CODE
2301 && ownerCode() != LISTINGS_CODE;
2305 void Paragraph::changeLanguage(BufferParams const & bparams,
2306 Language const * from, Language const * to)
2308 // change language including dummy font change at the end
2309 for (pos_type i = 0; i <= size(); ++i) {
2310 Font font = getFontSettings(bparams, i);
2311 if (font.language() == from) {
2312 font.setLanguage(to);
2319 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2321 Language const * doc_language = bparams.language;
2322 FontList::const_iterator cit = d->fontlist_.begin();
2323 FontList::const_iterator end = d->fontlist_.end();
2325 for (; cit != end; ++cit)
2326 if (cit->font().language() != ignore_language &&
2327 cit->font().language() != latex_language &&
2328 cit->font().language() != doc_language)
2334 docstring Paragraph::asString(int options) const
2336 return asString(0, size(), options);
2340 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2342 odocstringstream os;
2345 && options & AS_STR_LABEL
2346 && !d->params_.labelString().empty())
2347 os << d->params_.labelString() << ' ';
2349 for (pos_type i = beg; i < end; ++i) {
2350 char_type const c = d->text_[i];
2353 else if (c == META_INSET && options & AS_STR_INSETS)
2354 getInset(i)->textString(os);
2361 void Paragraph::setInsetOwner(Inset * inset)
2363 d->inset_owner_ = inset;
2367 int Paragraph::id() const
2373 Layout const & Paragraph::layout() const
2379 void Paragraph::setLayout(Layout const & layout)
2381 d->layout_ = &layout;
2385 void Paragraph::setEmptyOrDefaultLayout(DocumentClass const & tclass)
2387 if (useEmptyLayout())
2388 setLayout(tclass.emptyLayout());
2390 setLayout(tclass.defaultLayout());
2394 Inset * Paragraph::inInset() const
2396 return d->inset_owner_;
2400 InsetCode Paragraph::ownerCode() const
2402 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2406 ParagraphParameters & Paragraph::params()
2412 ParagraphParameters const & Paragraph::params() const
2418 bool Paragraph::isFreeSpacing() const
2420 if (d->layout_->free_spacing)
2422 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2426 bool Paragraph::allowEmpty() const
2428 if (d->layout_->keepempty)
2430 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2434 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2436 if (!Encodings::isArabicChar(c))
2439 char_type prev_char = ' ';
2440 char_type next_char = ' ';
2442 for (pos_type i = pos - 1; i >= 0; --i) {
2443 char_type const par_char = d->text_[i];
2444 if (!Encodings::isArabicComposeChar(par_char)) {
2445 prev_char = par_char;
2450 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2451 char_type const par_char = d->text_[i];
2452 if (!Encodings::isArabicComposeChar(par_char)) {
2453 next_char = par_char;
2458 if (Encodings::isArabicChar(next_char)) {
2459 if (Encodings::isArabicChar(prev_char) &&
2460 !Encodings::isArabicSpecialChar(prev_char))
2461 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2463 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2465 if (Encodings::isArabicChar(prev_char) &&
2466 !Encodings::isArabicSpecialChar(prev_char))
2467 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2469 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2474 int Paragraph::checkBiblio(Buffer const & buffer)
2477 // This is getting more and more a mess. ...We really should clean
2478 // up this bibitem issue for 1.6. See also bug 2743.
2480 // Add bibitem insets if necessary
2481 if (d->layout_->labeltype != LABEL_BIBLIO)
2484 bool hasbibitem = !d->insetlist_.empty()
2485 // Insist on it being in pos 0
2486 && d->text_[0] == META_INSET
2487 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2489 bool track_changes = buffer.params().trackChanges;
2494 // remove a bibitem in pos != 0
2495 // restore it later in pos 0 if necessary
2496 // (e.g. if a user inserts contents _before_ the item)
2497 // we're assuming there's only one of these, which there
2499 int erasedInsetPosition = -1;
2500 InsetList::iterator it = d->insetlist_.begin();
2501 InsetList::iterator end = d->insetlist_.end();
2502 for (; it != end; ++it)
2503 if (it->inset->lyxCode() == BIBITEM_CODE
2505 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2506 oldkey = olditem->getParam("key");
2507 oldlabel = olditem->getParam("label");
2508 erasedInsetPosition = it->pos;
2509 eraseChar(erasedInsetPosition, track_changes);
2513 // There was an InsetBibitem at the beginning, and we didn't
2514 // have to erase one.
2515 if (hasbibitem && erasedInsetPosition < 0)
2518 // There was an InsetBibitem at the beginning and we did have to
2519 // erase one. So we give its properties to the beginning inset.
2521 InsetBibitem * inset =
2522 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2523 if (!oldkey.empty())
2524 inset->setParam("key", oldkey);
2525 inset->setParam("label", oldlabel);
2526 return -erasedInsetPosition;
2529 // There was no inset at the beginning, so we need to create one with
2530 // the key and label of the one we erased.
2531 InsetBibitem * inset =
2532 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2533 // restore values of previously deleted item in this par.
2534 if (!oldkey.empty())
2535 inset->setParam("key", oldkey);
2536 inset->setParam("label", oldlabel);
2537 insertInset(0, static_cast<Inset *>(inset),
2538 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2544 void Paragraph::checkAuthors(AuthorList const & authorList)
2546 d->changes_.checkAuthors(authorList);
2550 bool Paragraph::isUnchanged(pos_type pos) const
2552 return lookupChange(pos).type == Change::UNCHANGED;
2556 bool Paragraph::isInserted(pos_type pos) const
2558 return lookupChange(pos).type == Change::INSERTED;
2562 bool Paragraph::isDeleted(pos_type pos) const
2564 return lookupChange(pos).type == Change::DELETED;
2568 InsetList const & Paragraph::insetList() const
2570 return d->insetlist_;
2574 Inset * Paragraph::releaseInset(pos_type pos)
2576 Inset * inset = d->insetlist_.release(pos);
2577 /// does not honour change tracking!
2578 eraseChar(pos, false);
2583 Inset * Paragraph::getInset(pos_type pos)
2585 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2586 ? d->insetlist_.get(pos) : 0;
2590 Inset const * Paragraph::getInset(pos_type pos) const
2592 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2593 ? d->insetlist_.get(pos) : 0;
2597 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2598 pos_type & right, TextCase action)
2600 // process sequences of modified characters; in change
2601 // tracking mode, this approach results in much better
2602 // usability than changing case on a char-by-char basis
2605 bool const trackChanges = bparams.trackChanges;
2607 bool capitalize = true;
2609 for (; pos < right; ++pos) {
2610 char_type oldChar = d->text_[pos];
2611 char_type newChar = oldChar;
2613 // ignore insets and don't play with deleted text!
2614 if (oldChar != META_INSET && !isDeleted(pos)) {
2616 case text_lowercase:
2617 newChar = lowercase(oldChar);
2619 case text_capitalization:
2621 newChar = uppercase(oldChar);
2625 case text_uppercase:
2626 newChar = uppercase(oldChar);
2631 if (!isLetter(pos) || isDeleted(pos)) {
2632 // permit capitalization again
2636 if (oldChar != newChar)
2639 if (oldChar == newChar || pos == right - 1) {
2640 if (oldChar != newChar) {
2641 // step behind the changing area
2644 int erasePos = pos - changes.size();
2645 for (size_t i = 0; i < changes.size(); i++) {
2646 insertChar(pos, changes[i],
2647 getFontSettings(bparams,
2650 if (!eraseChar(erasePos, trackChanges)) {
2653 ++right; // expand selection
2662 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2663 pos_type pos, bool del) const
2665 int const strsize = str.length();
2667 pos_type const parsize = d->text_.size();
2668 for (i = 0; pos + i < parsize; ++i) {
2671 if (cs && str[i] != d->text_[pos + i])
2673 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2675 if (!del && isDeleted(pos + i))
2682 // if necessary, check whether string matches word
2684 if (pos > 0 && isLetter(pos - 1))
2686 if (pos + strsize < parsize
2687 && isLetter(pos + strsize))
2695 char_type Paragraph::getChar(pos_type pos) const
2697 return d->text_[pos];
2701 pos_type Paragraph::size() const
2703 return d->text_.size();
2707 bool Paragraph::empty() const
2709 return d->text_.empty();
2713 bool Paragraph::isInset(pos_type pos) const
2715 return d->text_[pos] == META_INSET;
2719 bool Paragraph::isSeparator(pos_type pos) const
2721 //FIXME: Are we sure this can be the only separator?
2722 return d->text_[pos] == ' ';
2726 void Paragraph::deregisterWords()
2728 Private::Words::const_iterator it;
2729 WordList & wl = theWordList();
2730 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2736 void Paragraph::collectWords(CursorSlice const & sl)
2739 bool inword = false;
2741 //lyxerr << "Words: ";
2742 pos_type n = size();
2743 for (pos_type pos = 0; pos != n; ++pos) {
2747 if (!isLetter(pos)) {
2756 CursorSlice from = sl;
2757 CursorSlice to = sl;
2760 from.text()->getWord(from, to, WHOLE_WORD);
2761 if (to.pos() - from.pos() < 6)
2763 docstring word = asString(from.pos(), to.pos(), false);
2764 d->words_.insert(word);
2765 //lyxerr << word << " ";
2767 //lyxerr << std::endl;
2771 void Paragraph::registerWords()
2773 Private::Words::const_iterator it;
2774 WordList & wl = theWordList();
2775 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2780 void Paragraph::updateWords(CursorSlice const & sl)
2782 LASSERT(&sl.paragraph() == this, /**/);