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);
86 /// Copy constructor from \p beg to \p end
87 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
90 void insertChar(pos_type pos, char_type c, Change const & change);
92 /// Output the surrogate pair formed by \p c and \p next to \p os.
93 /// \return the number of characters written.
94 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
97 /// Output a space in appropriate formatting (or a surrogate pair
98 /// if the next character is a combining character).
99 /// \return whether a surrogate pair was output.
100 bool simpleTeXBlanks(OutputParams const &,
101 odocstream &, TexRow & texrow,
103 unsigned int & column,
105 Layout const & style);
107 /// Output consecutive unicode chars, belonging to the same script as
108 /// specified by the latex macro \p ltx, to \p os starting from \p i.
109 /// \return the number of characters written.
110 int writeScriptChars(odocstream & os, docstring const & ltx,
111 Change &, Encoding const &, pos_type & i);
113 /// This could go to ParagraphParameters if we want to.
114 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
117 /// This could go to ParagraphParameters if we want to.
118 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122 void latexInset(BufferParams const &,
124 TexRow & texrow, OutputParams &,
127 Font const & outerfont,
129 Change & running_change,
130 Layout const & style,
132 unsigned int & column);
135 void latexSpecialChar(
137 OutputParams & runparams,
139 Change & running_change,
140 Layout const & style,
142 unsigned int & column);
149 unsigned int & column);
151 bool latexSpecialTypewriter(
155 unsigned int & column);
157 bool latexSpecialPhrase(
160 unsigned int & column,
161 OutputParams & runparams);
164 void validate(LaTeXFeatures & features,
165 Layout const & layout) const;
167 /// Checks if the paragraph contains only text and no inset or font change.
168 bool onlyText(Buffer const & buf, Font const & outerfont,
169 pos_type initial) const;
171 /// match a string against a particular point in the paragraph
172 bool isTextAt(string const & str, pos_type pos) const;
174 /// Which Paragraph owns us?
178 Inset const * inset_owner_;
186 static unsigned int paragraph_id;
188 ParagraphParameters params_;
190 /// for recording and looking up changes
194 InsetList insetlist_;
197 pos_type begin_of_body_;
199 typedef docstring TextContainer;
203 typedef std::set<docstring> Words;
207 Layout const * layout_;
211 // Initialization of the counter for the paragraph id's,
212 unsigned int Paragraph::Private::paragraph_id = 0;
216 struct special_phrase {
222 special_phrase const special_phrases[] = {
223 { "LyX", from_ascii("\\LyX{}"), false },
224 { "TeX", from_ascii("\\TeX{}"), true },
225 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
226 { "LaTeX", from_ascii("\\LaTeX{}"), true },
229 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
234 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
235 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
237 id_ = paragraph_id++;
242 Paragraph::Private::Private(Private const & p, Paragraph * owner)
243 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
244 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
245 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
248 id_ = paragraph_id++;
252 Paragraph::Private::Private(Private const & p, Paragraph * owner,
253 pos_type beg, pos_type end)
254 : owner_(owner), inset_owner_(p.inset_owner_),
255 params_(p.params_), changes_(p.changes_),
256 insetlist_(p.insetlist_, beg, end),
257 begin_of_body_(p.begin_of_body_), words_(p.words_),
260 id_ = paragraph_id++;
261 if (beg >= pos_type(p.text_.size()))
263 text_ = p.text_.substr(beg, end - beg);
265 FontList::const_iterator fcit = fontlist_.begin();
266 FontList::const_iterator fend = fontlist_.end();
267 for (; fcit != fend; ++fcit) {
268 if (fcit->pos() < beg)
270 if (fcit->pos() >= end) {
271 // Add last entry in the fontlist_.
272 fontlist_.set(text_.size() - 1, fcit->font());
275 // Add a new entry in the fontlist_.
276 fontlist_.set(fcit->pos() - beg, fcit->font());
281 bool Paragraph::isChanged(pos_type start, pos_type end) const
283 LASSERT(start >= 0 && start <= size(), /**/);
284 LASSERT(end > start && end <= size() + 1, /**/);
286 return d->changes_.isChanged(start, end);
290 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
292 // keep the logic here in sync with the logic of eraseChars()
296 Change const change = d->changes_.lookup(size());
297 return change.type == Change::INSERTED && change.author == 0;
301 void Paragraph::setChange(Change const & change)
303 // beware of the imaginary end-of-par character!
304 d->changes_.set(change, 0, size() + 1);
307 * Propagate the change recursively - but not in case of DELETED!
309 * Imagine that your co-author makes changes in an existing inset. He
310 * sends your document to you and you come to the conclusion that the
311 * inset should go completely. If you erase it, LyX must not delete all
312 * text within the inset. Otherwise, the change tracked insertions of
313 * your co-author get lost and there is no way to restore them later.
315 * Conclusion: An inset's content should remain untouched if you delete it
318 if (change.type != Change::DELETED) {
319 for (pos_type pos = 0; pos < size(); ++pos) {
320 if (Inset * inset = getInset(pos))
321 inset->setChange(change);
327 void Paragraph::setChange(pos_type pos, Change const & change)
329 LASSERT(pos >= 0 && pos <= size(), /**/);
330 d->changes_.set(change, pos);
332 // see comment in setChange(Change const &) above
333 if (change.type != Change::DELETED && pos < size())
334 if (Inset * inset = getInset(pos))
335 inset->setChange(change);
339 Change const & Paragraph::lookupChange(pos_type pos) const
341 LASSERT(pos >= 0 && pos <= size(), /**/);
342 return d->changes_.lookup(pos);
346 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
349 LASSERT(start >= 0 && start <= size(), /**/);
350 LASSERT(end > start && end <= size() + 1, /**/);
352 for (pos_type pos = start; pos < end; ++pos) {
353 switch (lookupChange(pos).type) {
354 case Change::UNCHANGED:
355 // accept changes in nested inset
356 if (Inset * inset = getInset(pos))
357 inset->acceptChanges(bparams);
360 case Change::INSERTED:
361 d->changes_.set(Change(Change::UNCHANGED), pos);
362 // also accept changes in nested inset
363 if (Inset * inset = getInset(pos))
364 inset->acceptChanges(bparams);
367 case Change::DELETED:
368 // Suppress access to non-existent
369 // "end-of-paragraph char"
371 eraseChar(pos, false);
382 void Paragraph::rejectChanges(BufferParams const & bparams,
383 pos_type start, pos_type end)
385 LASSERT(start >= 0 && start <= size(), /**/);
386 LASSERT(end > start && end <= size() + 1, /**/);
388 for (pos_type pos = start; pos < end; ++pos) {
389 switch (lookupChange(pos).type) {
390 case Change::UNCHANGED:
391 // reject changes in nested inset
392 if (Inset * inset = getInset(pos))
393 inset->rejectChanges(bparams);
396 case Change::INSERTED:
397 // Suppress access to non-existent
398 // "end-of-paragraph char"
400 eraseChar(pos, false);
406 case Change::DELETED:
407 d->changes_.set(Change(Change::UNCHANGED), pos);
409 // Do NOT reject changes within a deleted inset!
410 // There may be insertions of a co-author inside of it!
418 void Paragraph::Private::insertChar(pos_type pos, char_type c,
419 Change const & change)
421 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
424 changes_.insert(change, pos);
426 // This is actually very common when parsing buffers (and
427 // maybe inserting ascii text)
428 if (pos == pos_type(text_.size())) {
429 // when appending characters, no need to update tables
434 text_.insert(text_.begin() + pos, c);
436 // Update the font table.
437 fontlist_.increasePosAfterPos(pos);
440 insetlist_.increasePosAfterPos(pos);
444 void Paragraph::insertInset(pos_type pos, Inset * inset,
445 Change const & change)
447 LASSERT(inset, /**/);
448 LASSERT(pos >= 0 && pos <= size(), /**/);
450 d->insertChar(pos, META_INSET, change);
451 LASSERT(d->text_[pos] == META_INSET, /**/);
453 // Add a new entry in the insetlist_.
454 d->insetlist_.insert(inset, pos);
458 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
460 LASSERT(pos >= 0 && pos <= size(), /**/);
462 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
465 Change change = d->changes_.lookup(pos);
467 // set the character to DELETED if
468 // a) it was previously unchanged or
469 // b) it was inserted by a co-author
471 if (change.type == Change::UNCHANGED ||
472 (change.type == Change::INSERTED && change.author != 0)) {
473 setChange(pos, Change(Change::DELETED));
477 if (change.type == Change::DELETED)
481 // Don't physically access the imaginary end-of-paragraph character.
482 // eraseChar() can only mark it as DELETED. A physical deletion of
483 // end-of-par must be handled externally.
489 d->changes_.erase(pos);
491 // if it is an inset, delete the inset entry
492 if (d->text_[pos] == META_INSET)
493 d->insetlist_.erase(pos);
495 d->text_.erase(d->text_.begin() + pos);
497 // Update the fontlist_
498 d->fontlist_.erase(pos);
500 // Update the insetlist_
501 d->insetlist_.decreasePosAfterPos(pos);
507 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
509 LASSERT(start >= 0 && start <= size(), /**/);
510 LASSERT(end >= start && end <= size() + 1, /**/);
513 for (pos_type count = end - start; count; --count) {
514 if (!eraseChar(i, trackChanges))
521 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
522 char_type next, Encoding const & encoding)
524 // Writing next here may circumvent a possible font change between
525 // c and next. Since next is only output if it forms a surrogate pair
526 // with c we can ignore this:
527 // A font change inside a surrogate pair does not make sense and is
528 // hopefully impossible to input.
529 // FIXME: change tracking
530 // Is this correct WRT change tracking?
531 docstring const latex1 = encoding.latexChar(next);
532 docstring const latex2 = encoding.latexChar(c);
533 if (docstring(1, next) == latex1) {
534 // the encoding supports the combination
535 os << latex2 << latex1;
536 return latex1.length() + latex2.length();
538 os << latex1 << '{' << latex2 << '}';
539 return latex1.length() + latex2.length() + 2;
543 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
544 odocstream & os, TexRow & texrow,
546 unsigned int & column,
548 Layout const & style)
550 if (style.pass_thru || runparams.verbatim)
553 if (i + 1 < int(text_.size())) {
554 char_type next = text_[i + 1];
555 if (Encodings::isCombiningChar(next)) {
556 Encoding const & encoding = *(runparams.encoding);
557 // This space has an accent, so we must always output it.
558 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
563 if (lyxrc.plaintext_linelen > 0
564 && column > lyxrc.plaintext_linelen
566 && text_[i - 1] != ' '
567 && (i + 1 < int(text_.size()))
568 // same in FreeSpacing mode
569 && !owner_->isFreeSpacing()
570 // In typewriter mode, we want to avoid
571 // ! . ? : at the end of a line
572 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
573 && (text_[i - 1] == '.'
574 || text_[i - 1] == '?'
575 || text_[i - 1] == ':'
576 || text_[i - 1] == '!'))) {
579 texrow.start(owner_->id(), i + 1);
581 } else if (style.free_spacing) {
590 int Paragraph::Private::writeScriptChars(odocstream & os,
591 docstring const & ltx,
592 Change & runningChange,
593 Encoding const & encoding,
596 // FIXME: modifying i here is not very nice...
598 // We only arrive here when a proper language for character text_[i] has
599 // not been specified (i.e., it could not be translated in the current
600 // latex encoding) or its latex translation has been forced, and it
601 // belongs to a known script.
602 // Parameter ltx contains the latex translation of text_[i] as specified
603 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
604 // The latex macro name "textXXX" specifies the script to which text_[i]
605 // belongs and we use it in order to check whether characters from the
606 // same script immediately follow, such that we can collect them in a
607 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
608 // for the first char but only "<spec>" for all subsequent chars.
609 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
610 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
611 string script = to_ascii(ltx.substr(1, brace1 - 1));
614 bool closing_brace = true;
615 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
616 // Correct encoding is being used, so we can avoid \textgreek.
619 closing_brace = false;
621 os << ltx.substr(pos, length);
622 int size = text_.size();
623 while (i + 1 < size) {
624 char_type const next = text_[i + 1];
625 // Stop here if next character belongs to another script
626 // or there is a change in change tracking status.
627 if (!Encodings::isKnownScriptChar(next, script) ||
628 runningChange != owner_->lookupChange(i + 1))
632 FontList::const_iterator cit = fontlist_.begin();
633 FontList::const_iterator end = fontlist_.end();
634 for (; cit != end; ++cit) {
635 if (cit->pos() >= i && !found) {
636 prev_font = cit->font();
639 if (cit->pos() >= i + 1)
642 // Stop here if there is a font attribute or encoding change.
643 if (found && cit != end && prev_font != cit->font())
645 docstring const latex = encoding.latexChar(next);
646 docstring::size_type const b1 =
647 latex.find_first_of(from_ascii("{"));
648 docstring::size_type const b2 =
649 latex.find_last_of(from_ascii("}"));
650 int const len = b2 - b1 - 1;
651 os << latex.substr(b1 + 1, len);
663 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
665 pos_type const len = str.length();
667 // is the paragraph large enough?
668 if (pos + len > int(text_.size()))
671 // does the wanted text start at point?
672 for (string::size_type i = 0; i < str.length(); ++i) {
673 // Caution: direct comparison of characters works only
674 // because str is pure ASCII.
675 if (str[i] != text_[pos + i])
679 return fontlist_.hasChangeInRange(pos, len);
683 void Paragraph::Private::latexInset(
684 BufferParams const & bparams,
687 OutputParams & runparams,
690 Font const & outerfont,
692 Change & running_change,
693 Layout const & style,
695 unsigned int & column)
697 Inset * inset = owner_->getInset(i);
698 LASSERT(inset, /**/);
700 if (style.pass_thru) {
701 inset->plaintext(os, runparams);
705 // FIXME: move this to InsetNewline::latex
706 if (inset->lyxCode() == NEWLINE_CODE) {
707 // newlines are handled differently here than
708 // the default in simpleTeXSpecialChars().
709 if (!style.newline_allowed) {
713 column += running_font.latexWriteEndChanges(
714 os, bparams, runparams,
719 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
722 basefont = owner_->getLayoutFont(bparams, outerfont);
723 running_font = basefont;
725 if (runparams.moving_arg)
730 texrow.start(owner_->id(), i + 1);
734 if (owner_->lookupChange(i).type == Change::DELETED) {
735 if( ++runparams.inDeletedInset == 1)
736 runparams.changeOfDeletedInset = owner_->lookupChange(i);
739 if (inset->canTrackChanges()) {
740 column += Changes::latexMarkChange(os, bparams, running_change,
741 Change(Change::UNCHANGED));
742 running_change = Change(Change::UNCHANGED);
746 odocstream::pos_type const len = os.tellp();
748 if (inset->forceLTR()
749 && running_font.isRightToLeft()
750 // ERT is an exception, it should be output with no decorations at all
751 && inset->lyxCode() != ERT_CODE) {
752 if (running_font.language()->lang() == "farsi")
759 // FIXME: Bug: we can have an empty font change here!
760 // if there has just been a font change, we are going to close it
761 // right now, which means stupid latex code like \textsf{}. AFAIK,
762 // this does not harm dvi output. A minor bug, thus (JMarc)
764 // Some insets cannot be inside a font change command.
765 // However, even such insets *can* be placed in \L or \R
766 // or their equivalents (for RTL language switches), so we don't
767 // close the language in those cases.
768 // ArabTeX, though, cannot handle this special behavior, it seems.
769 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
770 || running_font.language()->lang() == "arabic_arabtex";
771 if (open_font && inset->noFontChange()) {
772 bool closeLanguage = arabtex
773 || basefont.isRightToLeft() == running_font.isRightToLeft();
774 unsigned int count = running_font.latexWriteEndChanges(os,
775 bparams, runparams, basefont, basefont, closeLanguage);
777 // if any font properties were closed, update the running_font,
778 // making sure, however, to leave the language as it was
780 // FIXME: probably a better way to keep track of the old
781 // language, than copying the entire font?
782 Font const copy_font(running_font);
783 basefont = owner_->getLayoutFont(bparams, outerfont);
784 running_font = basefont;
786 running_font.setLanguage(copy_font.language());
787 // leave font open if language is still open
788 open_font = (running_font.language() == basefont.language());
790 runparams.local_font = &basefont;
797 tmp = inset->latex(os, runparams);
798 } catch (EncodingException & e) {
799 // add location information and throw again.
806 if (running_font.language()->lang() == "farsi")
813 for (int j = 0; j < tmp; ++j)
816 texrow.start(owner_->id(), i + 1);
819 column += os.tellp() - len;
822 if (owner_->lookupChange(i).type == Change::DELETED)
823 --runparams.inDeletedInset;
827 void Paragraph::Private::latexSpecialChar(
829 OutputParams & runparams,
831 Change & running_change,
832 Layout const & style,
834 unsigned int & column)
836 char_type const c = text_[i];
838 if (style.pass_thru) {
840 // FIXME UNICODE: This can fail if c cannot
841 // be encoded in the current encoding.
846 if (runparams.verbatim) {
847 // FIXME UNICODE: This can fail if c cannot
848 // be encoded in the current encoding.
853 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
856 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
857 && latexSpecialTypewriter(c, os, i, column))
860 // Otherwise, we use what LaTeX provides us.
863 os << "\\textbackslash{}";
867 os << "\\textless{}";
871 os << "\\textgreater{}";
882 os << "\\char`\\\"{}";
887 case '%': case '#': case '{':
895 os << "\\textasciitilde{}";
900 os << "\\textasciicircum{}";
905 // avoid being mistaken for optional arguments
913 // Blanks are printed before font switching.
914 // Sure? I am not! (try nice-latex)
915 // I am sure it's correct. LyX might be smarter
916 // in the future, but for now, nothing wrong is
922 if (latexSpecialPhrase(os, i, column, runparams))
928 Encoding const & encoding = *(runparams.encoding);
929 if (i + 1 < int(text_.size())) {
930 char_type next = text_[i + 1];
931 if (Encodings::isCombiningChar(next)) {
932 column += latexSurrogatePair(os, c, next, encoding) - 1;
938 docstring const latex = encoding.latexChar(c);
939 if (Encodings::isKnownScriptChar(c, script)
940 && prefixIs(latex, from_ascii("\\" + script)))
941 column += writeScriptChars(os, latex,
942 running_change, encoding, i) - 1;
943 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
944 // Prevent eating of a following
945 // space or command corruption by
946 // following characters
947 column += latex.length() + 1;
950 column += latex.length() - 1;
958 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
959 pos_type & i, unsigned int & column)
965 // In T1 encoding, these characters exist
966 // but we should avoid ligatures
967 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
969 os << "\\textcompwordmark{}";
976 // soul.sty breaks with \char`\"
977 os << "\\textquotedbl{}";
986 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
987 pos_type & i, unsigned int & column)
991 // within \ttfamily, "--" is merged to "-" (no endash)
992 // so we avoid this rather irritating ligature
993 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1000 // everything else has to be checked separately
1001 // (depending on the encoding)
1008 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1009 unsigned int & column, OutputParams & runparams)
1011 // FIXME: if we have "LaTeX" with a font
1012 // change in the middle (before the 'T', then
1013 // the "TeX" part is still special cased.
1014 // Really we should only operate this on
1015 // "words" for some definition of word
1017 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1018 if (!isTextAt(special_phrases[pnr].phrase, i))
1020 if (runparams.moving_arg)
1022 os << special_phrases[pnr].macro;
1023 i += special_phrases[pnr].phrase.length() - 1;
1024 column += special_phrases[pnr].macro.length() - 1;
1031 void Paragraph::Private::validate(LaTeXFeatures & features,
1032 Layout const & layout) const
1034 // check the params.
1035 if (!params_.spacing().isDefault())
1036 features.require("setspace");
1039 features.useLayout(layout.name());
1042 fontlist_.validate(features);
1044 // then the indentation
1045 if (!params_.leftIndent().zero())
1046 features.require("ParagraphLeftIndent");
1049 InsetList::const_iterator icit = insetlist_.begin();
1050 InsetList::const_iterator iend = insetlist_.end();
1051 for (; icit != iend; ++icit) {
1053 icit->inset->validate(features);
1054 if (layout.needprotect &&
1055 icit->inset->lyxCode() == FOOT_CODE)
1056 features.require("NeedLyXFootnoteCode");
1060 // then the contents
1061 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1062 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1063 if (!special_phrases[pnr].builtin
1064 && isTextAt(special_phrases[pnr].phrase, i)) {
1065 features.require(special_phrases[pnr].phrase);
1069 Encodings::validate(text_[i], features);
1073 /////////////////////////////////////////////////////////////////////
1077 /////////////////////////////////////////////////////////////////////
1080 Layout const emptyParagraphLayout;
1083 Paragraph::Paragraph()
1084 : d(new Paragraph::Private(this, emptyParagraphLayout))
1091 Paragraph::Paragraph(Paragraph const & par)
1092 : itemdepth(par.itemdepth),
1093 d(new Paragraph::Private(*par.d, this))
1099 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1100 : itemdepth(par.itemdepth),
1101 d(new Paragraph::Private(*par.d, this, beg, end))
1107 Paragraph & Paragraph::operator=(Paragraph const & par)
1109 // needed as we will destroy the private part before copying it
1111 itemdepth = par.itemdepth;
1115 d = new Private(*par.d, this);
1122 Paragraph::~Paragraph()
1129 void Paragraph::write(ostream & os, BufferParams const & bparams,
1130 depth_type & dth) const
1132 // The beginning or end of a deeper (i.e. nested) area?
1133 if (dth != d->params_.depth()) {
1134 if (d->params_.depth() > dth) {
1135 while (d->params_.depth() > dth) {
1136 os << "\n\\begin_deeper";
1140 while (d->params_.depth() < dth) {
1141 os << "\n\\end_deeper";
1147 // First write the layout
1148 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1150 d->params_.write(os);
1152 Font font1(inherit_font, bparams.language);
1154 Change running_change = Change(Change::UNCHANGED);
1157 for (pos_type i = 0; i <= size(); ++i) {
1159 Change change = lookupChange(i);
1160 Changes::lyxMarkChange(os, column, running_change, change);
1161 running_change = change;
1166 // Write font changes
1167 Font font2 = getFontSettings(bparams, i);
1168 if (font2 != font1) {
1169 font2.lyxWriteChanges(font1, os);
1174 char_type const c = d->text_[i];
1177 if (Inset const * inset = getInset(i)) {
1178 if (inset->directWrite()) {
1179 // international char, let it write
1180 // code directly so it's shorter in
1186 os << "\\begin_inset ";
1188 os << "\n\\end_inset\n\n";
1194 os << "\n\\backslash\n";
1198 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1205 if ((column > 70 && c == ' ')
1210 // this check is to amend a bug. LyX sometimes
1211 // inserts '\0' this could cause problems.
1213 os << to_utf8(docstring(1, c));
1215 LYXERR0("NUL char in structure.");
1221 os << "\n\\end_layout\n";
1225 void Paragraph::validate(LaTeXFeatures & features) const
1227 d->validate(features, *d->layout_);
1231 void Paragraph::insert(pos_type start, docstring const & str,
1232 Font const & font, Change const & change)
1234 for (size_t i = 0, n = str.size(); i != n ; ++i)
1235 insertChar(start + i, str[i], font, change);
1239 void Paragraph::appendChar(char_type c, Font const & font,
1240 Change const & change)
1243 d->changes_.insert(change, d->text_.size());
1244 // when appending characters, no need to update tables
1245 d->text_.push_back(c);
1246 setFont(d->text_.size() - 1, font);
1250 void Paragraph::appendString(docstring const & s, Font const & font,
1251 Change const & change)
1253 pos_type end = s.size();
1254 size_t oldsize = d->text_.size();
1255 size_t newsize = oldsize + end;
1256 size_t capacity = d->text_.capacity();
1257 if (newsize >= capacity)
1258 d->text_.reserve(max(capacity + 100, newsize));
1260 // when appending characters, no need to update tables
1263 // FIXME: Optimize this!
1264 for (pos_type i = oldsize; i != newsize; ++i) {
1266 d->changes_.insert(change, i);
1268 d->fontlist_.set(oldsize, font);
1269 d->fontlist_.set(newsize - 1, font);
1273 void Paragraph::insertChar(pos_type pos, char_type c,
1276 d->insertChar(pos, c, Change(trackChanges ?
1277 Change::INSERTED : Change::UNCHANGED));
1281 void Paragraph::insertChar(pos_type pos, char_type c,
1282 Font const & font, bool trackChanges)
1284 d->insertChar(pos, c, Change(trackChanges ?
1285 Change::INSERTED : Change::UNCHANGED));
1290 void Paragraph::insertChar(pos_type pos, char_type c,
1291 Font const & font, Change const & change)
1293 d->insertChar(pos, c, change);
1298 void Paragraph::insertInset(pos_type pos, Inset * inset,
1299 Font const & font, Change const & change)
1301 insertInset(pos, inset, change);
1302 // Set the font/language of the inset...
1307 void Paragraph::resetFonts(Font const & font)
1309 d->fontlist_.clear();
1310 d->fontlist_.set(0, font);
1311 d->fontlist_.set(d->text_.size() - 1, font);
1314 // Gets uninstantiated font setting at position.
1315 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1319 LYXERR0("pos: " << pos << " size: " << size());
1320 LASSERT(pos <= size(), /**/);
1323 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1324 if (cit != d->fontlist_.end())
1327 if (pos == size() && !empty())
1328 return getFontSettings(bparams, pos - 1);
1330 return Font(inherit_font, getParLanguage(bparams));
1334 FontSpan Paragraph::fontSpan(pos_type pos) const
1336 LASSERT(pos <= size(), /**/);
1339 FontList::const_iterator cit = d->fontlist_.begin();
1340 FontList::const_iterator end = d->fontlist_.end();
1341 for (; cit != end; ++cit) {
1342 if (cit->pos() >= pos) {
1343 if (pos >= beginOfBody())
1344 return FontSpan(max(start, beginOfBody()),
1347 return FontSpan(start,
1348 min(beginOfBody() - 1,
1351 start = cit->pos() + 1;
1354 // This should not happen, but if so, we take no chances.
1355 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1356 return FontSpan(pos, pos);
1360 // Gets uninstantiated font setting at position 0
1361 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1363 if (!empty() && !d->fontlist_.empty())
1364 return d->fontlist_.begin()->font();
1366 return Font(inherit_font, bparams.language);
1370 // Gets the fully instantiated font at a given position in a paragraph
1371 // This is basically the same function as Text::GetFont() in text2.cpp.
1372 // The difference is that this one is used for generating the LaTeX file,
1373 // and thus cosmetic "improvements" are disallowed: This has to deliver
1374 // the true picture of the buffer. (Asger)
1375 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1376 Font const & outerfont) const
1378 LASSERT(pos >= 0, /**/);
1380 Font font = getFontSettings(bparams, pos);
1382 pos_type const body_pos = beginOfBody();
1384 font.fontInfo().realize(d->layout_->labelfont);
1386 font.fontInfo().realize(d->layout_->font);
1388 font.fontInfo().realize(outerfont.fontInfo());
1389 font.fontInfo().realize(bparams.getFont().fontInfo());
1395 Font const Paragraph::getLabelFont
1396 (BufferParams const & bparams, Font const & outerfont) const
1398 FontInfo tmpfont = d->layout_->labelfont;
1399 tmpfont.realize(outerfont.fontInfo());
1400 tmpfont.realize(bparams.getFont().fontInfo());
1401 return Font(tmpfont, getParLanguage(bparams));
1405 Font const Paragraph::getLayoutFont
1406 (BufferParams const & bparams, Font const & outerfont) const
1408 FontInfo tmpfont = d->layout_->font;
1409 tmpfont.realize(outerfont.fontInfo());
1410 tmpfont.realize(bparams.getFont().fontInfo());
1411 return Font(tmpfont, getParLanguage(bparams));
1415 /// Returns the height of the highest font in range
1416 FontSize Paragraph::highestFontInRange
1417 (pos_type startpos, pos_type endpos, FontSize def_size) const
1419 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1423 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1425 char_type c = d->text_[pos];
1426 if (!lyxrc.rtl_support)
1456 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1462 void Paragraph::setFont(pos_type pos, Font const & font)
1464 LASSERT(pos <= size(), /**/);
1466 // First, reduce font against layout/label font
1467 // Update: The setCharFont() routine in text2.cpp already
1468 // reduces font, so we don't need to do that here. (Asger)
1470 d->fontlist_.set(pos, font);
1474 void Paragraph::makeSameLayout(Paragraph const & par)
1476 d->layout_ = par.d->layout_;
1477 d->params_ = par.d->params_;
1481 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1483 if (isFreeSpacing())
1489 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1490 if (eraseChar(pos, trackChanges))
1496 return count > 0 || pos > 0;
1500 bool Paragraph::hasSameLayout(Paragraph const & par) const
1502 return par.d->layout_ == d->layout_
1503 && d->params_.sameLayout(par.d->params_);
1507 depth_type Paragraph::getDepth() const
1509 return d->params_.depth();
1513 depth_type Paragraph::getMaxDepthAfter() const
1515 if (d->layout_->isEnvironment())
1516 return d->params_.depth() + 1;
1518 return d->params_.depth();
1522 char Paragraph::getAlign() const
1524 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1525 return d->layout_->align;
1527 return d->params_.align();
1531 docstring const & Paragraph::labelString() const
1533 return d->params_.labelString();
1537 // the next two functions are for the manual labels
1538 docstring const Paragraph::getLabelWidthString() const
1540 if (d->layout_->margintype == MARGIN_MANUAL)
1541 return d->params_.labelWidthString();
1543 return _("Senseless with this layout!");
1547 void Paragraph::setLabelWidthString(docstring const & s)
1549 d->params_.labelWidthString(s);
1553 docstring const Paragraph::translateIfPossible(docstring const & s,
1554 BufferParams const & bparams) const
1556 if (!isAscii(s) || s.empty()) {
1557 // This must be a user defined layout. We cannot translate
1558 // this, since gettext accepts only ascii keys.
1561 // Probably standard layout, try to translate
1562 Messages & m = getMessages(getParLanguage(bparams)->code());
1563 return m.get(to_ascii(s));
1567 docstring Paragraph::expandLabel(Layout const & layout,
1568 BufferParams const & bparams, bool process_appendix) const
1570 DocumentClass const & tclass = bparams.documentClass();
1573 if (process_appendix && d->params_.appendix())
1574 fmt = translateIfPossible(layout.labelstring_appendix(),
1577 fmt = translateIfPossible(layout.labelstring(), bparams);
1579 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1580 && !layout.counter.empty())
1581 fmt = "\\the" + layout.counter;
1583 // handle 'inherited level parts' in 'fmt',
1584 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1585 size_t const i = fmt.find('@', 0);
1586 if (i != docstring::npos) {
1587 size_t const j = fmt.find('@', i + 1);
1588 if (j != docstring::npos) {
1589 docstring parent(fmt, i + 1, j - i - 1);
1590 docstring label = from_ascii("??");
1591 if (tclass.hasLayout(parent))
1592 docstring label = expandLabel(tclass[parent], bparams,
1594 fmt = docstring(fmt, 0, i) + label
1595 + docstring(fmt, j + 1, docstring::npos);
1599 return tclass.counters().counterLabel(fmt);
1603 void Paragraph::applyLayout(Layout const & new_layout)
1605 d->layout_ = &new_layout;
1606 LyXAlignment const oldAlign = d->params_.align();
1608 if (!(oldAlign & d->layout_->alignpossible)) {
1609 frontend::Alert::warning(_("Alignment not permitted"),
1610 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1611 d->params_.align(LYX_ALIGN_LAYOUT);
1616 pos_type Paragraph::beginOfBody() const
1618 return d->begin_of_body_;
1622 void Paragraph::setBeginOfBody()
1624 if (d->layout_->labeltype != LABEL_MANUAL) {
1625 d->begin_of_body_ = 0;
1629 // Unroll the first two cycles of the loop
1630 // and remember the previous character to
1631 // remove unnecessary getChar() calls
1633 pos_type end = size();
1634 if (i < end && !isNewline(i)) {
1636 char_type previous_char = 0;
1639 previous_char = d->text_[i];
1640 if (!isNewline(i)) {
1642 while (i < end && previous_char != ' ') {
1647 previous_char = temp;
1653 d->begin_of_body_ = i;
1657 bool Paragraph::forcePlainLayout() const
1659 return inInset().forcePlainLayout();
1663 bool Paragraph::allowParagraphCustomization() const
1665 return inInset().allowParagraphCustomization();
1669 bool Paragraph::usePlainLayout() const
1671 return inInset().usePlainLayout();
1677 // paragraphs inside floats need different alignment tags to avoid
1680 bool noTrivlistCentering(InsetCode code)
1682 return code == FLOAT_CODE || code == WRAP_CODE;
1686 string correction(string const & orig)
1688 if (orig == "flushleft")
1689 return "raggedright";
1690 if (orig == "flushright")
1691 return "raggedleft";
1692 if (orig == "center")
1698 string const corrected_env(string const & suffix, string const & env,
1701 string output = suffix + "{";
1702 if (noTrivlistCentering(code))
1703 output += correction(env);
1707 if (suffix == "\\begin")
1713 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1715 if (!contains(str, "\n"))
1716 column += str.size();
1720 column = rsplit(str, tmp, '\n').size();
1727 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1728 odocstream & os, TexRow & texrow,
1729 bool moving_arg) const
1733 if (params_.noindent()) {
1734 os << "\\noindent ";
1738 LyXAlignment const curAlign = params_.align();
1740 if (curAlign == layout_->align)
1744 case LYX_ALIGN_NONE:
1745 case LYX_ALIGN_BLOCK:
1746 case LYX_ALIGN_LAYOUT:
1747 case LYX_ALIGN_SPECIAL:
1749 case LYX_ALIGN_LEFT:
1750 case LYX_ALIGN_RIGHT:
1751 case LYX_ALIGN_CENTER:
1760 case LYX_ALIGN_NONE:
1761 case LYX_ALIGN_BLOCK:
1762 case LYX_ALIGN_LAYOUT:
1763 case LYX_ALIGN_SPECIAL:
1765 case LYX_ALIGN_LEFT: {
1767 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1768 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1770 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1771 os << from_ascii(output);
1772 adjust_row_column(output, texrow, column);
1774 } case LYX_ALIGN_RIGHT: {
1776 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1777 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1779 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1780 os << from_ascii(output);
1781 adjust_row_column(output, texrow, column);
1783 } case LYX_ALIGN_CENTER: {
1785 output = corrected_env("\\begin", "center", owner_->ownerCode());
1786 os << from_ascii(output);
1787 adjust_row_column(output, texrow, column);
1796 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1797 odocstream & os, TexRow & texrow,
1798 bool moving_arg) const
1802 switch (params_.align()) {
1803 case LYX_ALIGN_NONE:
1804 case LYX_ALIGN_BLOCK:
1805 case LYX_ALIGN_LAYOUT:
1806 case LYX_ALIGN_SPECIAL:
1808 case LYX_ALIGN_LEFT:
1809 case LYX_ALIGN_RIGHT:
1810 case LYX_ALIGN_CENTER:
1818 switch (params_.align()) {
1819 case LYX_ALIGN_NONE:
1820 case LYX_ALIGN_BLOCK:
1821 case LYX_ALIGN_LAYOUT:
1822 case LYX_ALIGN_SPECIAL:
1824 case LYX_ALIGN_LEFT: {
1826 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1827 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1829 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1830 os << from_ascii(output);
1831 adjust_row_column(output, texrow, column);
1833 } case LYX_ALIGN_RIGHT: {
1835 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1836 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1838 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1839 os << from_ascii(output);
1840 adjust_row_column(output, texrow, column);
1842 } case LYX_ALIGN_CENTER: {
1844 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1845 os << from_ascii(output);
1846 adjust_row_column(output, texrow, column);
1855 // This one spits out the text of the paragraph
1856 bool Paragraph::latex(BufferParams const & bparams,
1857 Font const & outerfont,
1858 odocstream & os, TexRow & texrow,
1859 OutputParams const & runparams) const
1861 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1863 bool return_value = false;
1865 bool asdefault = forcePlainLayout();
1867 Layout const & style = asdefault ?
1868 bparams.documentClass().plainLayout() :
1871 // Current base font for all inherited font changes, without any
1872 // change caused by an individual character, except for the language:
1873 // It is set to the language of the first character.
1874 // As long as we are in the label, this font is the base font of the
1875 // label. Before the first body character it is set to the base font
1879 // Maybe we have to create a optional argument.
1880 pos_type body_pos = beginOfBody();
1881 unsigned int column = 0;
1884 // the optional argument is kept in curly brackets in
1885 // case it contains a ']'
1888 basefont = getLabelFont(bparams, outerfont);
1890 basefont = getLayoutFont(bparams, outerfont);
1893 // Which font is currently active?
1894 Font running_font(basefont);
1895 // Do we have an open font change?
1896 bool open_font = false;
1898 Change runningChange = Change(Change::UNCHANGED);
1900 texrow.start(id(), 0);
1902 // if the paragraph is empty, the loop will not be entered at all
1904 if (style.isCommand()) {
1909 column += d->startTeXParParams(bparams, os, texrow,
1910 runparams.moving_arg);
1913 for (pos_type i = 0; i < size(); ++i) {
1914 // First char in paragraph or after label?
1915 if (i == body_pos) {
1918 column += running_font.latexWriteEndChanges(
1919 os, bparams, runparams,
1920 basefont, basefont);
1923 basefont = getLayoutFont(bparams, outerfont);
1924 running_font = basefont;
1926 column += Changes::latexMarkChange(os, bparams,
1927 runningChange, Change(Change::UNCHANGED));
1928 runningChange = Change(Change::UNCHANGED);
1933 if (style.isCommand()) {
1939 column += d->startTeXParParams(bparams, os,
1941 runparams.moving_arg);
1944 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1947 if (bparams.outputChanges && runningChange != change) {
1949 column += running_font.latexWriteEndChanges(
1950 os, bparams, runparams, basefont, basefont);
1953 basefont = getLayoutFont(bparams, outerfont);
1954 running_font = basefont;
1956 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1957 runningChange = change;
1960 // do not output text which is marked deleted
1961 // if change tracking output is disabled
1962 if (!bparams.outputChanges && change.type == Change::DELETED) {
1968 // Fully instantiated font
1969 Font const font = getFont(bparams, i, outerfont);
1971 Font const last_font = running_font;
1973 // Do we need to close the previous font?
1975 (font != running_font ||
1976 font.language() != running_font.language()))
1978 column += running_font.latexWriteEndChanges(
1979 os, bparams, runparams, basefont,
1980 (i == body_pos-1) ? basefont : font);
1981 running_font = basefont;
1985 // close babel's font environment before opening CJK.
1986 if (!running_font.language()->babel().empty() &&
1987 font.language()->encoding()->package() == Encoding::CJK) {
1988 string end_tag = subst(lyxrc.language_command_end,
1990 running_font.language()->babel());
1991 os << from_ascii(end_tag);
1992 column += end_tag.length();
1995 // Switch file encoding if necessary (and allowed)
1996 if (!runparams.verbatim &&
1997 runparams.encoding->package() != Encoding::none &&
1998 font.language()->encoding()->package() != Encoding::none) {
1999 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2000 runparams, *(font.language()->encoding()));
2001 if (enc_switch.first) {
2002 column += enc_switch.second;
2003 runparams.encoding = font.language()->encoding();
2007 char_type const c = d->text_[i];
2009 // Do we need to change font?
2010 if ((font != running_font ||
2011 font.language() != running_font.language()) &&
2014 odocstringstream ods;
2015 column += font.latexWriteStartChanges(ods, bparams,
2016 runparams, basefont,
2018 running_font = font;
2020 docstring fontchange = ods.str();
2021 // check if the fontchange ends with a trailing blank
2022 // (like "\small " (see bug 3382)
2023 if (suffixIs(fontchange, ' ') && c == ' ')
2024 os << fontchange.substr(0, fontchange.size() - 1)
2025 << from_ascii("{}");
2031 // FIXME: integrate this case in latexSpecialChar
2032 // Do not print the separation of the optional argument
2033 // if style.pass_thru is false. This works because
2034 // latexSpecialChar ignores spaces if
2035 // style.pass_thru is false.
2036 if (i != body_pos - 1) {
2037 if (d->simpleTeXBlanks(
2038 runparams, os, texrow,
2039 i, column, font, style)) {
2040 // A surrogate pair was output. We
2041 // must not call latexSpecialChar
2042 // in this iteration, since it would output
2043 // the combining character again.
2050 OutputParams rp = runparams;
2051 rp.free_spacing = style.free_spacing;
2052 rp.local_font = &font;
2053 rp.intitle = style.intitle;
2055 // Two major modes: LaTeX or plain
2056 // Handle here those cases common to both modes
2057 // and then split to handle the two modes separately.
2058 if (c == META_INSET)
2059 d->latexInset(bparams, os,
2060 texrow, rp, running_font,
2061 basefont, outerfont, open_font,
2062 runningChange, style, i, column);
2065 d->latexSpecialChar(os, rp, running_font, runningChange,
2067 } catch (EncodingException & e) {
2068 if (runparams.dryrun) {
2069 os << "<" << _("LyX Warning: ")
2070 << _("uncodable character") << " '";
2074 // add location information and throw again.
2082 // Set the encoding to that returned from latexSpecialChar (see
2083 // comment for encoding member in OutputParams.h)
2084 runparams.encoding = rp.encoding;
2087 // If we have an open font definition, we have to close it
2089 #ifdef FIXED_LANGUAGE_END_DETECTION
2092 .latexWriteEndChanges(os, bparams, runparams,
2094 next_->getFont(bparams, 0, outerfont));
2096 running_font.latexWriteEndChanges(os, bparams,
2097 runparams, basefont, basefont);
2100 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2101 //FIXME: there as we start another \selectlanguage with the next paragraph if
2102 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2103 running_font.latexWriteEndChanges(os, bparams, runparams,
2104 basefont, basefont);
2108 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2110 // Needed if there is an optional argument but no contents.
2111 if (body_pos > 0 && body_pos == size()) {
2113 return_value = false;
2117 column += d->endTeXParParams(bparams, os, texrow,
2118 runparams.moving_arg);
2121 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2122 return return_value;
2126 bool Paragraph::emptyTag() const
2128 for (pos_type i = 0; i < size(); ++i) {
2129 if (Inset const * inset = getInset(i)) {
2130 InsetCode lyx_code = inset->lyxCode();
2131 if (lyx_code != TOC_CODE &&
2132 lyx_code != INCLUDE_CODE &&
2133 lyx_code != GRAPHICS_CODE &&
2134 lyx_code != ERT_CODE &&
2135 lyx_code != LISTINGS_CODE &&
2136 lyx_code != FLOAT_CODE &&
2137 lyx_code != TABULAR_CODE) {
2141 char_type c = d->text_[i];
2142 if (c != ' ' && c != '\t')
2150 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2153 for (pos_type i = 0; i < size(); ++i) {
2154 if (Inset const * inset = getInset(i)) {
2155 InsetCode lyx_code = inset->lyxCode();
2156 if (lyx_code == LABEL_CODE) {
2157 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2158 docstring const & id = il->getParam("name");
2159 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2167 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2171 for (i = 0; i < size(); ++i) {
2172 if (Inset const * inset = getInset(i)) {
2173 inset->docbook(os, runparams);
2175 char_type c = d->text_[i];
2178 os << sgml::escapeChar(c);
2185 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2188 pos_type size = text_.size();
2189 for (pos_type i = initial; i < size; ++i) {
2190 Font font = owner_->getFont(buf.params(), i, outerfont);
2191 if (text_[i] == META_INSET)
2193 if (i != initial && font != font_old)
2202 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2204 OutputParams const & runparams,
2205 Font const & outerfont,
2206 pos_type initial) const
2208 bool emph_flag = false;
2210 Layout const & style = *d->layout_;
2212 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2214 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2217 // parsing main loop
2218 for (pos_type i = initial; i < size(); ++i) {
2219 Font font = getFont(buf.params(), i, outerfont);
2221 // handle <emphasis> tag
2222 if (font_old.emph() != font.fontInfo().emph()) {
2223 if (font.fontInfo().emph() == FONT_ON) {
2226 } else if (i != initial) {
2227 os << "</emphasis>";
2232 if (Inset const * inset = getInset(i)) {
2233 inset->docbook(os, runparams);
2235 char_type c = d->text_[i];
2237 if (style.pass_thru)
2240 os << sgml::escapeChar(c);
2242 font_old = font.fontInfo();
2246 os << "</emphasis>";
2249 if (style.free_spacing)
2251 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2256 bool Paragraph::isHfill(pos_type pos) const
2258 Inset const * inset = getInset(pos);
2259 return inset && (inset->lyxCode() == SPACE_CODE &&
2260 inset->isStretchableSpace());
2264 bool Paragraph::isNewline(pos_type pos) const
2266 Inset const * inset = getInset(pos);
2267 return inset && inset->lyxCode() == NEWLINE_CODE;
2271 bool Paragraph::isLineSeparator(pos_type pos) const
2273 char_type const c = d->text_[pos];
2274 if (isLineSeparatorChar(c))
2276 Inset const * inset = getInset(pos);
2277 return inset && inset->isLineSeparator();
2281 /// Used by the spellchecker
2282 bool Paragraph::isLetter(pos_type pos) const
2284 if (Inset const * inset = getInset(pos))
2285 return inset->isLetter();
2286 char_type const c = d->text_[pos];
2287 return isLetterChar(c) || isDigit(c);
2291 bool Paragraph::isChar(pos_type pos) const
2293 if (Inset const * inset = getInset(pos))
2294 return inset->isChar();
2295 char_type const c = d->text_[pos];
2296 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2300 bool Paragraph::isSpace(pos_type pos) const
2302 if (Inset const * inset = getInset(pos))
2303 return inset->isSpace();
2304 char_type const c = d->text_[pos];
2305 return lyx::isSpace(c);
2310 Paragraph::getParLanguage(BufferParams const & bparams) const
2313 return getFirstFontSettings(bparams).language();
2314 // FIXME: we should check the prev par as well (Lgb)
2315 return bparams.language;
2319 bool Paragraph::isRTL(BufferParams const & bparams) const
2321 return lyxrc.rtl_support
2322 && getParLanguage(bparams)->rightToLeft()
2323 && ownerCode() != ERT_CODE
2324 && ownerCode() != LISTINGS_CODE;
2328 void Paragraph::changeLanguage(BufferParams const & bparams,
2329 Language const * from, Language const * to)
2331 // change language including dummy font change at the end
2332 for (pos_type i = 0; i <= size(); ++i) {
2333 Font font = getFontSettings(bparams, i);
2334 if (font.language() == from) {
2335 font.setLanguage(to);
2342 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2344 Language const * doc_language = bparams.language;
2345 FontList::const_iterator cit = d->fontlist_.begin();
2346 FontList::const_iterator end = d->fontlist_.end();
2348 for (; cit != end; ++cit)
2349 if (cit->font().language() != ignore_language &&
2350 cit->font().language() != latex_language &&
2351 cit->font().language() != doc_language)
2357 docstring Paragraph::asString(int options) const
2359 return asString(0, size(), options);
2363 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2365 odocstringstream os;
2368 && options & AS_STR_LABEL
2369 && !d->params_.labelString().empty())
2370 os << d->params_.labelString() << ' ';
2372 for (pos_type i = beg; i < end; ++i) {
2373 char_type const c = d->text_[i];
2376 else if (c == META_INSET && options & AS_STR_INSETS)
2377 getInset(i)->textString(os);
2384 void Paragraph::setInsetOwner(Inset const * inset)
2386 d->inset_owner_ = inset;
2390 int Paragraph::id() const
2396 Layout const & Paragraph::layout() const
2402 void Paragraph::setLayout(Layout const & layout)
2404 d->layout_ = &layout;
2408 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2410 if (usePlainLayout())
2411 setLayout(tclass.plainLayout());
2413 setLayout(tclass.defaultLayout());
2417 Inset const & Paragraph::inInset() const
2419 LASSERT(d->inset_owner_, exit(10));
2420 return *d->inset_owner_;
2424 InsetCode Paragraph::ownerCode() const
2426 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2430 ParagraphParameters & Paragraph::params()
2436 ParagraphParameters const & Paragraph::params() const
2442 bool Paragraph::isFreeSpacing() const
2444 if (d->layout_->free_spacing)
2446 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2450 bool Paragraph::allowEmpty() const
2452 if (d->layout_->keepempty)
2454 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2458 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2460 if (!Encodings::isArabicChar(c))
2463 char_type prev_char = ' ';
2464 char_type next_char = ' ';
2466 for (pos_type i = pos - 1; i >= 0; --i) {
2467 char_type const par_char = d->text_[i];
2468 if (!Encodings::isArabicComposeChar(par_char)) {
2469 prev_char = par_char;
2474 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2475 char_type const par_char = d->text_[i];
2476 if (!Encodings::isArabicComposeChar(par_char)) {
2477 next_char = par_char;
2482 if (Encodings::isArabicChar(next_char)) {
2483 if (Encodings::isArabicChar(prev_char) &&
2484 !Encodings::isArabicSpecialChar(prev_char))
2485 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2487 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2489 if (Encodings::isArabicChar(prev_char) &&
2490 !Encodings::isArabicSpecialChar(prev_char))
2491 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2493 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2498 int Paragraph::checkBiblio(Buffer const & buffer)
2501 // This is getting more and more a mess. ...We really should clean
2502 // up this bibitem issue for 1.6. See also bug 2743.
2504 // Add bibitem insets if necessary
2505 if (d->layout_->labeltype != LABEL_BIBLIO)
2508 bool hasbibitem = !d->insetlist_.empty()
2509 // Insist on it being in pos 0
2510 && d->text_[0] == META_INSET
2511 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2513 bool track_changes = buffer.params().trackChanges;
2518 // remove a bibitem in pos != 0
2519 // restore it later in pos 0 if necessary
2520 // (e.g. if a user inserts contents _before_ the item)
2521 // we're assuming there's only one of these, which there
2523 int erasedInsetPosition = -1;
2524 InsetList::iterator it = d->insetlist_.begin();
2525 InsetList::iterator end = d->insetlist_.end();
2526 for (; it != end; ++it)
2527 if (it->inset->lyxCode() == BIBITEM_CODE
2529 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2530 oldkey = olditem->getParam("key");
2531 oldlabel = olditem->getParam("label");
2532 erasedInsetPosition = it->pos;
2533 eraseChar(erasedInsetPosition, track_changes);
2537 // There was an InsetBibitem at the beginning, and we didn't
2538 // have to erase one.
2539 if (hasbibitem && erasedInsetPosition < 0)
2542 // There was an InsetBibitem at the beginning and we did have to
2543 // erase one. So we give its properties to the beginning inset.
2545 InsetBibitem * inset =
2546 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2547 if (!oldkey.empty())
2548 inset->setParam("key", oldkey);
2549 inset->setParam("label", oldlabel);
2550 return -erasedInsetPosition;
2553 // There was no inset at the beginning, so we need to create one with
2554 // the key and label of the one we erased.
2555 InsetBibitem * inset =
2556 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2557 // restore values of previously deleted item in this par.
2558 if (!oldkey.empty())
2559 inset->setParam("key", oldkey);
2560 inset->setParam("label", oldlabel);
2561 insertInset(0, static_cast<Inset *>(inset),
2562 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2568 void Paragraph::checkAuthors(AuthorList const & authorList)
2570 d->changes_.checkAuthors(authorList);
2574 bool Paragraph::isUnchanged(pos_type pos) const
2576 return lookupChange(pos).type == Change::UNCHANGED;
2580 bool Paragraph::isInserted(pos_type pos) const
2582 return lookupChange(pos).type == Change::INSERTED;
2586 bool Paragraph::isDeleted(pos_type pos) const
2588 return lookupChange(pos).type == Change::DELETED;
2592 InsetList const & Paragraph::insetList() const
2594 return d->insetlist_;
2598 void Paragraph::setBuffer(Buffer & b)
2600 d->insetlist_.setBuffer(b);
2604 Inset * Paragraph::releaseInset(pos_type pos)
2606 Inset * inset = d->insetlist_.release(pos);
2607 /// does not honour change tracking!
2608 eraseChar(pos, false);
2613 Inset * Paragraph::getInset(pos_type pos)
2615 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2616 ? d->insetlist_.get(pos) : 0;
2620 Inset const * Paragraph::getInset(pos_type pos) const
2622 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2623 ? d->insetlist_.get(pos) : 0;
2627 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2628 pos_type & right, TextCase action)
2630 // process sequences of modified characters; in change
2631 // tracking mode, this approach results in much better
2632 // usability than changing case on a char-by-char basis
2635 bool const trackChanges = bparams.trackChanges;
2637 bool capitalize = true;
2639 for (; pos < right; ++pos) {
2640 char_type oldChar = d->text_[pos];
2641 char_type newChar = oldChar;
2643 // ignore insets and don't play with deleted text!
2644 if (oldChar != META_INSET && !isDeleted(pos)) {
2646 case text_lowercase:
2647 newChar = lowercase(oldChar);
2649 case text_capitalization:
2651 newChar = uppercase(oldChar);
2655 case text_uppercase:
2656 newChar = uppercase(oldChar);
2661 if (!isLetter(pos) || isDeleted(pos)) {
2662 // permit capitalization again
2666 if (oldChar != newChar)
2669 if (oldChar == newChar || pos == right - 1) {
2670 if (oldChar != newChar) {
2671 // step behind the changing area
2674 int erasePos = pos - changes.size();
2675 for (size_t i = 0; i < changes.size(); i++) {
2676 insertChar(pos, changes[i],
2677 getFontSettings(bparams,
2680 if (!eraseChar(erasePos, trackChanges)) {
2683 ++right; // expand selection
2692 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2693 pos_type pos, bool del) const
2695 int const strsize = str.length();
2697 pos_type const parsize = d->text_.size();
2698 for (i = 0; pos + i < parsize; ++i) {
2701 if (cs && str[i] != d->text_[pos + i])
2703 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2705 if (!del && isDeleted(pos + i))
2712 // if necessary, check whether string matches word
2714 if (pos > 0 && isLetter(pos - 1))
2716 if (pos + strsize < parsize
2717 && isLetter(pos + strsize))
2725 char_type Paragraph::getChar(pos_type pos) const
2727 return d->text_[pos];
2731 pos_type Paragraph::size() const
2733 return d->text_.size();
2737 bool Paragraph::empty() const
2739 return d->text_.empty();
2743 bool Paragraph::isInset(pos_type pos) const
2745 return d->text_[pos] == META_INSET;
2749 bool Paragraph::isSeparator(pos_type pos) const
2751 //FIXME: Are we sure this can be the only separator?
2752 return d->text_[pos] == ' ';
2756 void Paragraph::deregisterWords()
2758 Private::Words::const_iterator it;
2759 WordList & wl = theWordList();
2760 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2766 void Paragraph::collectWords(CursorSlice const & sl)
2769 bool inword = false;
2771 //lyxerr << "Words: ";
2772 pos_type n = size();
2773 for (pos_type pos = 0; pos != n; ++pos) {
2777 if (!isLetter(pos)) {
2786 CursorSlice from = sl;
2787 CursorSlice to = sl;
2790 from.text()->getWord(from, to, WHOLE_WORD);
2791 if (to.pos() - from.pos() < 6)
2793 docstring word = asString(from.pos(), to.pos(), false);
2794 d->words_.insert(word);
2795 //lyxerr << word << " ";
2797 //lyxerr << std::endl;
2801 void Paragraph::registerWords()
2803 Private::Words::const_iterator it;
2804 WordList & wl = theWordList();
2805 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2810 void Paragraph::updateWords(CursorSlice const & sl)
2812 LASSERT(&sl.paragraph() == this, /**/);