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/ExceptionMessage.h"
56 #include "support/gettext.h"
57 #include "support/lstrings.h"
58 #include "support/Messages.h"
59 #include "support/textutils.h"
65 using namespace lyx::support;
70 /// Inset identifier (above 0x10ffff, for ucs-4)
71 char_type const META_INSET = 0x200001;
74 /////////////////////////////////////////////////////////////////////
78 /////////////////////////////////////////////////////////////////////
80 class Paragraph::Private
84 Private(Paragraph * owner, Layout const & layout);
85 /// "Copy constructor"
86 Private(Private const &, Paragraph * owner);
87 /// Copy constructor from \p beg to \p end
88 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
91 void insertChar(pos_type pos, char_type c, Change const & change);
93 /// Output the surrogate pair formed by \p c and \p next to \p os.
94 /// \return the number of characters written.
95 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
98 /// Output a space in appropriate formatting (or a surrogate pair
99 /// if the next character is a combining character).
100 /// \return whether a surrogate pair was output.
101 bool simpleTeXBlanks(OutputParams const &,
102 odocstream &, TexRow & texrow,
104 unsigned int & column,
106 Layout const & style);
108 /// Output consecutive unicode chars, belonging to the same script as
109 /// specified by the latex macro \p ltx, to \p os starting from \p i.
110 /// \return the number of characters written.
111 int writeScriptChars(odocstream & os, docstring const & ltx,
112 Change &, Encoding const &, pos_type & i);
114 /// This could go to ParagraphParameters if we want to.
115 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 /// This could go to ParagraphParameters if we want to.
119 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
123 void latexInset(BufferParams const &,
125 TexRow & texrow, OutputParams &,
128 Font const & outerfont,
130 Change & running_change,
131 Layout const & style,
133 unsigned int & column);
136 void latexSpecialChar(
138 OutputParams & runparams,
140 Change & running_change,
141 Layout const & style,
143 unsigned int & column);
150 unsigned int & column);
152 bool latexSpecialTypewriter(
156 unsigned int & column);
158 bool latexSpecialPhrase(
161 unsigned int & column,
162 OutputParams & runparams);
165 void validate(LaTeXFeatures & features,
166 Layout const & layout) const;
168 /// Checks if the paragraph contains only text and no inset or font change.
169 bool onlyText(Buffer const & buf, Font const & outerfont,
170 pos_type initial) const;
172 /// match a string against a particular point in the paragraph
173 bool isTextAt(string const & str, pos_type pos) const;
175 /// Which Paragraph owns us?
179 Inset const * inset_owner_;
187 static unsigned int paragraph_id;
189 ParagraphParameters params_;
191 /// for recording and looking up changes
195 InsetList insetlist_;
198 pos_type begin_of_body_;
200 typedef docstring TextContainer;
204 typedef std::set<docstring> Words;
208 Layout const * layout_;
212 // Initialization of the counter for the paragraph id's,
213 unsigned int Paragraph::Private::paragraph_id = 0;
217 struct special_phrase {
223 special_phrase const special_phrases[] = {
224 { "LyX", from_ascii("\\LyX{}"), false },
225 { "TeX", from_ascii("\\TeX{}"), true },
226 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
227 { "LaTeX", from_ascii("\\LaTeX{}"), true },
230 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
235 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
236 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
238 id_ = paragraph_id++;
243 Paragraph::Private::Private(Private const & p, Paragraph * owner)
244 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
245 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
246 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
249 id_ = paragraph_id++;
253 Paragraph::Private::Private(Private const & p, Paragraph * owner,
254 pos_type beg, pos_type end)
255 : owner_(owner), inset_owner_(p.inset_owner_),
256 params_(p.params_), changes_(p.changes_),
257 insetlist_(p.insetlist_, beg, end),
258 begin_of_body_(p.begin_of_body_), words_(p.words_),
261 id_ = paragraph_id++;
262 if (beg >= pos_type(p.text_.size()))
264 text_ = p.text_.substr(beg, end - beg);
266 FontList::const_iterator fcit = fontlist_.begin();
267 FontList::const_iterator fend = fontlist_.end();
268 for (; fcit != fend; ++fcit) {
269 if (fcit->pos() < beg)
271 if (fcit->pos() >= end) {
272 // Add last entry in the fontlist_.
273 fontlist_.set(text_.size() - 1, fcit->font());
276 // Add a new entry in the fontlist_.
277 fontlist_.set(fcit->pos() - beg, fcit->font());
282 bool Paragraph::isChanged(pos_type start, pos_type end) const
284 LASSERT(start >= 0 && start <= size(), /**/);
285 LASSERT(end > start && end <= size() + 1, /**/);
287 return d->changes_.isChanged(start, end);
291 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
293 // keep the logic here in sync with the logic of eraseChars()
297 Change const change = d->changes_.lookup(size());
298 return change.type == Change::INSERTED && change.author == 0;
302 void Paragraph::setChange(Change const & change)
304 // beware of the imaginary end-of-par character!
305 d->changes_.set(change, 0, size() + 1);
308 * Propagate the change recursively - but not in case of DELETED!
310 * Imagine that your co-author makes changes in an existing inset. He
311 * sends your document to you and you come to the conclusion that the
312 * inset should go completely. If you erase it, LyX must not delete all
313 * text within the inset. Otherwise, the change tracked insertions of
314 * your co-author get lost and there is no way to restore them later.
316 * Conclusion: An inset's content should remain untouched if you delete it
319 if (change.type != Change::DELETED) {
320 for (pos_type pos = 0; pos < size(); ++pos) {
321 if (Inset * inset = getInset(pos))
322 inset->setChange(change);
328 void Paragraph::setChange(pos_type pos, Change const & change)
330 LASSERT(pos >= 0 && pos <= size(), /**/);
331 d->changes_.set(change, pos);
333 // see comment in setChange(Change const &) above
334 if (change.type != Change::DELETED && pos < size())
335 if (Inset * inset = getInset(pos))
336 inset->setChange(change);
340 Change const & Paragraph::lookupChange(pos_type pos) const
342 LASSERT(pos >= 0 && pos <= size(), /**/);
343 return d->changes_.lookup(pos);
347 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
350 LASSERT(start >= 0 && start <= size(), /**/);
351 LASSERT(end > start && end <= size() + 1, /**/);
353 for (pos_type pos = start; pos < end; ++pos) {
354 switch (lookupChange(pos).type) {
355 case Change::UNCHANGED:
356 // accept changes in nested inset
357 if (Inset * inset = getInset(pos))
358 inset->acceptChanges(bparams);
361 case Change::INSERTED:
362 d->changes_.set(Change(Change::UNCHANGED), pos);
363 // also accept changes in nested inset
364 if (Inset * inset = getInset(pos))
365 inset->acceptChanges(bparams);
368 case Change::DELETED:
369 // Suppress access to non-existent
370 // "end-of-paragraph char"
372 eraseChar(pos, false);
383 void Paragraph::rejectChanges(BufferParams const & bparams,
384 pos_type start, pos_type end)
386 LASSERT(start >= 0 && start <= size(), /**/);
387 LASSERT(end > start && end <= size() + 1, /**/);
389 for (pos_type pos = start; pos < end; ++pos) {
390 switch (lookupChange(pos).type) {
391 case Change::UNCHANGED:
392 // reject changes in nested inset
393 if (Inset * inset = getInset(pos))
394 inset->rejectChanges(bparams);
397 case Change::INSERTED:
398 // Suppress access to non-existent
399 // "end-of-paragraph char"
401 eraseChar(pos, false);
407 case Change::DELETED:
408 d->changes_.set(Change(Change::UNCHANGED), pos);
410 // Do NOT reject changes within a deleted inset!
411 // There may be insertions of a co-author inside of it!
419 void Paragraph::Private::insertChar(pos_type pos, char_type c,
420 Change const & change)
422 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
425 changes_.insert(change, pos);
427 // This is actually very common when parsing buffers (and
428 // maybe inserting ascii text)
429 if (pos == pos_type(text_.size())) {
430 // when appending characters, no need to update tables
435 text_.insert(text_.begin() + pos, c);
437 // Update the font table.
438 fontlist_.increasePosAfterPos(pos);
441 insetlist_.increasePosAfterPos(pos);
445 void Paragraph::insertInset(pos_type pos, Inset * inset,
446 Change const & change)
448 LASSERT(inset, /**/);
449 LASSERT(pos >= 0 && pos <= size(), /**/);
451 d->insertChar(pos, META_INSET, change);
452 LASSERT(d->text_[pos] == META_INSET, /**/);
454 // Add a new entry in the insetlist_.
455 d->insetlist_.insert(inset, pos);
459 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
461 LASSERT(pos >= 0 && pos <= size(), return false);
463 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
466 Change change = d->changes_.lookup(pos);
468 // set the character to DELETED if
469 // a) it was previously unchanged or
470 // b) it was inserted by a co-author
472 if (change.type == Change::UNCHANGED ||
473 (change.type == Change::INSERTED && change.author != 0)) {
474 setChange(pos, Change(Change::DELETED));
478 if (change.type == Change::DELETED)
482 // Don't physically access the imaginary end-of-paragraph character.
483 // eraseChar() can only mark it as DELETED. A physical deletion of
484 // end-of-par must be handled externally.
490 d->changes_.erase(pos);
492 // if it is an inset, delete the inset entry
493 if (d->text_[pos] == META_INSET)
494 d->insetlist_.erase(pos);
496 d->text_.erase(d->text_.begin() + pos);
498 // Update the fontlist_
499 d->fontlist_.erase(pos);
501 // Update the insetlist_
502 d->insetlist_.decreasePosAfterPos(pos);
508 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
510 LASSERT(start >= 0 && start <= size(), /**/);
511 LASSERT(end >= start && end <= size() + 1, /**/);
514 for (pos_type count = end - start; count; --count) {
515 if (!eraseChar(i, trackChanges))
522 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
523 char_type next, Encoding const & encoding)
525 // Writing next here may circumvent a possible font change between
526 // c and next. Since next is only output if it forms a surrogate pair
527 // with c we can ignore this:
528 // A font change inside a surrogate pair does not make sense and is
529 // hopefully impossible to input.
530 // FIXME: change tracking
531 // Is this correct WRT change tracking?
532 docstring const latex1 = encoding.latexChar(next);
533 docstring const latex2 = encoding.latexChar(c);
534 if (docstring(1, next) == latex1) {
535 // the encoding supports the combination
536 os << latex2 << latex1;
537 return latex1.length() + latex2.length();
539 os << latex1 << '{' << latex2 << '}';
540 return latex1.length() + latex2.length() + 2;
544 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
545 odocstream & os, TexRow & texrow,
547 unsigned int & column,
549 Layout const & style)
551 if (style.pass_thru || runparams.verbatim)
554 if (i + 1 < int(text_.size())) {
555 char_type next = text_[i + 1];
556 if (Encodings::isCombiningChar(next)) {
557 Encoding const & encoding = *(runparams.encoding);
558 // This space has an accent, so we must always output it.
559 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
564 if (lyxrc.plaintext_linelen > 0
565 && column > lyxrc.plaintext_linelen
567 && text_[i - 1] != ' '
568 && (i + 1 < int(text_.size()))
569 // same in FreeSpacing mode
570 && !owner_->isFreeSpacing()
571 // In typewriter mode, we want to avoid
572 // ! . ? : at the end of a line
573 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
574 && (text_[i - 1] == '.'
575 || text_[i - 1] == '?'
576 || text_[i - 1] == ':'
577 || text_[i - 1] == '!'))) {
580 texrow.start(owner_->id(), i + 1);
582 } else if (style.free_spacing) {
591 int Paragraph::Private::writeScriptChars(odocstream & os,
592 docstring const & ltx,
593 Change & runningChange,
594 Encoding const & encoding,
597 // FIXME: modifying i here is not very nice...
599 // We only arrive here when a proper language for character text_[i] has
600 // not been specified (i.e., it could not be translated in the current
601 // latex encoding) or its latex translation has been forced, and it
602 // belongs to a known script.
603 // Parameter ltx contains the latex translation of text_[i] as specified
604 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
605 // The latex macro name "textXXX" specifies the script to which text_[i]
606 // belongs and we use it in order to check whether characters from the
607 // same script immediately follow, such that we can collect them in a
608 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
609 // for the first char but only "<spec>" for all subsequent chars.
610 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
611 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
612 string script = to_ascii(ltx.substr(1, brace1 - 1));
615 bool closing_brace = true;
616 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
617 // Correct encoding is being used, so we can avoid \textgreek.
620 closing_brace = false;
622 os << ltx.substr(pos, length);
623 int size = text_.size();
624 while (i + 1 < size) {
625 char_type const next = text_[i + 1];
626 // Stop here if next character belongs to another script
627 // or there is a change in change tracking status.
628 if (!Encodings::isKnownScriptChar(next, script) ||
629 runningChange != owner_->lookupChange(i + 1))
633 FontList::const_iterator cit = fontlist_.begin();
634 FontList::const_iterator end = fontlist_.end();
635 for (; cit != end; ++cit) {
636 if (cit->pos() >= i && !found) {
637 prev_font = cit->font();
640 if (cit->pos() >= i + 1)
643 // Stop here if there is a font attribute or encoding change.
644 if (found && cit != end && prev_font != cit->font())
646 docstring const latex = encoding.latexChar(next);
647 docstring::size_type const b1 =
648 latex.find_first_of(from_ascii("{"));
649 docstring::size_type const b2 =
650 latex.find_last_of(from_ascii("}"));
651 int const len = b2 - b1 - 1;
652 os << latex.substr(b1 + 1, len);
664 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
666 pos_type const len = str.length();
668 // is the paragraph large enough?
669 if (pos + len > int(text_.size()))
672 // does the wanted text start at point?
673 for (string::size_type i = 0; i < str.length(); ++i) {
674 // Caution: direct comparison of characters works only
675 // because str is pure ASCII.
676 if (str[i] != text_[pos + i])
680 return fontlist_.hasChangeInRange(pos, len);
684 void Paragraph::Private::latexInset(
685 BufferParams const & bparams,
688 OutputParams & runparams,
691 Font const & outerfont,
693 Change & running_change,
694 Layout const & style,
696 unsigned int & column)
698 Inset * inset = owner_->getInset(i);
699 LASSERT(inset, /**/);
701 if (style.pass_thru) {
702 inset->plaintext(os, runparams);
706 // FIXME: move this to InsetNewline::latex
707 if (inset->lyxCode() == NEWLINE_CODE) {
708 // newlines are handled differently here than
709 // the default in simpleTeXSpecialChars().
710 if (!style.newline_allowed) {
714 column += running_font.latexWriteEndChanges(
715 os, bparams, runparams,
720 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
723 basefont = owner_->getLayoutFont(bparams, outerfont);
724 running_font = basefont;
726 if (runparams.moving_arg)
731 texrow.start(owner_->id(), i + 1);
735 if (owner_->lookupChange(i).type == Change::DELETED) {
736 if( ++runparams.inDeletedInset == 1)
737 runparams.changeOfDeletedInset = owner_->lookupChange(i);
740 if (inset->canTrackChanges()) {
741 column += Changes::latexMarkChange(os, bparams, running_change,
742 Change(Change::UNCHANGED));
743 running_change = Change(Change::UNCHANGED);
747 odocstream::pos_type const len = os.tellp();
749 if (inset->forceLTR()
750 && running_font.isRightToLeft()
751 // ERT is an exception, it should be output with no decorations at all
752 && inset->lyxCode() != ERT_CODE) {
753 if (running_font.language()->lang() == "farsi")
760 // FIXME: Bug: we can have an empty font change here!
761 // if there has just been a font change, we are going to close it
762 // right now, which means stupid latex code like \textsf{}. AFAIK,
763 // this does not harm dvi output. A minor bug, thus (JMarc)
765 // Some insets cannot be inside a font change command.
766 // However, even such insets *can* be placed in \L or \R
767 // or their equivalents (for RTL language switches), so we don't
768 // close the language in those cases.
769 // ArabTeX, though, cannot handle this special behavior, it seems.
770 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
771 || running_font.language()->lang() == "arabic_arabtex";
772 if (open_font && inset->noFontChange()) {
773 bool closeLanguage = arabtex
774 || basefont.isRightToLeft() == running_font.isRightToLeft();
775 unsigned int count = running_font.latexWriteEndChanges(os,
776 bparams, runparams, basefont, basefont, closeLanguage);
778 // if any font properties were closed, update the running_font,
779 // making sure, however, to leave the language as it was
781 // FIXME: probably a better way to keep track of the old
782 // language, than copying the entire font?
783 Font const copy_font(running_font);
784 basefont = owner_->getLayoutFont(bparams, outerfont);
785 running_font = basefont;
787 running_font.setLanguage(copy_font.language());
788 // leave font open if language is still open
789 open_font = (running_font.language() == basefont.language());
791 runparams.local_font = &basefont;
798 tmp = inset->latex(os, runparams);
799 } catch (EncodingException & e) {
800 // add location information and throw again.
807 if (running_font.language()->lang() == "farsi")
814 for (int j = 0; j < tmp; ++j)
817 texrow.start(owner_->id(), i + 1);
820 column += os.tellp() - len;
823 if (owner_->lookupChange(i).type == Change::DELETED)
824 --runparams.inDeletedInset;
828 void Paragraph::Private::latexSpecialChar(
830 OutputParams & runparams,
832 Change & running_change,
833 Layout const & style,
835 unsigned int & column)
837 char_type const c = text_[i];
839 if (style.pass_thru) {
841 // FIXME UNICODE: This can fail if c cannot
842 // be encoded in the current encoding.
847 if (runparams.verbatim) {
848 // FIXME UNICODE: This can fail if c cannot
849 // be encoded in the current encoding.
854 if (lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
857 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
858 && latexSpecialTypewriter(c, os, i, column))
861 // Otherwise, we use what LaTeX provides us.
864 os << "\\textbackslash{}";
868 os << "\\textless{}";
872 os << "\\textgreater{}";
883 os << "\\char`\\\"{}";
888 case '%': case '#': case '{':
896 os << "\\textasciitilde{}";
901 os << "\\textasciicircum{}";
906 // avoid being mistaken for optional arguments
914 // Blanks are printed before font switching.
915 // Sure? I am not! (try nice-latex)
916 // I am sure it's correct. LyX might be smarter
917 // in the future, but for now, nothing wrong is
923 if (latexSpecialPhrase(os, i, column, runparams))
929 Encoding const & encoding = *(runparams.encoding);
930 if (i + 1 < int(text_.size())) {
931 char_type next = text_[i + 1];
932 if (Encodings::isCombiningChar(next)) {
933 column += latexSurrogatePair(os, c, next, encoding) - 1;
939 docstring const latex = encoding.latexChar(c);
940 if (Encodings::isKnownScriptChar(c, script)
941 && prefixIs(latex, from_ascii("\\" + script)))
942 column += writeScriptChars(os, latex,
943 running_change, encoding, i) - 1;
944 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
945 // Prevent eating of a following
946 // space or command corruption by
947 // following characters
948 column += latex.length() + 1;
951 column += latex.length() - 1;
959 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
960 pos_type & i, unsigned int & column)
966 // In T1 encoding, these characters exist
967 // but we should avoid ligatures
968 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
970 os << "\\textcompwordmark{}";
977 // soul.sty breaks with \char`\"
978 os << "\\textquotedbl{}";
987 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
988 pos_type & i, unsigned int & column)
992 // within \ttfamily, "--" is merged to "-" (no endash)
993 // so we avoid this rather irritating ligature
994 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1001 // everything else has to be checked separately
1002 // (depending on the encoding)
1009 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1010 unsigned int & column, OutputParams & runparams)
1012 // FIXME: if we have "LaTeX" with a font
1013 // change in the middle (before the 'T', then
1014 // the "TeX" part is still special cased.
1015 // Really we should only operate this on
1016 // "words" for some definition of word
1018 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1019 if (!isTextAt(special_phrases[pnr].phrase, i))
1021 if (runparams.moving_arg)
1023 os << special_phrases[pnr].macro;
1024 i += special_phrases[pnr].phrase.length() - 1;
1025 column += special_phrases[pnr].macro.length() - 1;
1032 void Paragraph::Private::validate(LaTeXFeatures & features,
1033 Layout const & layout) const
1035 // check the params.
1036 if (!params_.spacing().isDefault())
1037 features.require("setspace");
1040 features.useLayout(layout.name());
1043 fontlist_.validate(features);
1045 // then the indentation
1046 if (!params_.leftIndent().zero())
1047 features.require("ParagraphLeftIndent");
1050 InsetList::const_iterator icit = insetlist_.begin();
1051 InsetList::const_iterator iend = insetlist_.end();
1052 for (; icit != iend; ++icit) {
1054 icit->inset->validate(features);
1055 if (layout.needprotect &&
1056 icit->inset->lyxCode() == FOOT_CODE)
1057 features.require("NeedLyXFootnoteCode");
1061 // then the contents
1062 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1063 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1064 if (!special_phrases[pnr].builtin
1065 && isTextAt(special_phrases[pnr].phrase, i)) {
1066 features.require(special_phrases[pnr].phrase);
1070 Encodings::validate(text_[i], features);
1074 /////////////////////////////////////////////////////////////////////
1078 /////////////////////////////////////////////////////////////////////
1081 Layout const emptyParagraphLayout;
1084 Paragraph::Paragraph()
1085 : d(new Paragraph::Private(this, emptyParagraphLayout))
1092 Paragraph::Paragraph(Paragraph const & par)
1093 : itemdepth(par.itemdepth),
1094 d(new Paragraph::Private(*par.d, this))
1100 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1101 : itemdepth(par.itemdepth),
1102 d(new Paragraph::Private(*par.d, this, beg, end))
1108 Paragraph & Paragraph::operator=(Paragraph const & par)
1110 // needed as we will destroy the private part before copying it
1112 itemdepth = par.itemdepth;
1116 d = new Private(*par.d, this);
1123 Paragraph::~Paragraph()
1130 void Paragraph::write(ostream & os, BufferParams const & bparams,
1131 depth_type & dth) const
1133 // The beginning or end of a deeper (i.e. nested) area?
1134 if (dth != d->params_.depth()) {
1135 if (d->params_.depth() > dth) {
1136 while (d->params_.depth() > dth) {
1137 os << "\n\\begin_deeper";
1141 while (d->params_.depth() < dth) {
1142 os << "\n\\end_deeper";
1148 // First write the layout
1149 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1151 d->params_.write(os);
1153 Font font1(inherit_font, bparams.language);
1155 Change running_change = Change(Change::UNCHANGED);
1158 for (pos_type i = 0; i <= size(); ++i) {
1160 Change change = lookupChange(i);
1161 Changes::lyxMarkChange(os, column, running_change, change);
1162 running_change = change;
1167 // Write font changes
1168 Font font2 = getFontSettings(bparams, i);
1169 if (font2 != font1) {
1170 font2.lyxWriteChanges(font1, os);
1175 char_type const c = d->text_[i];
1178 if (Inset const * inset = getInset(i)) {
1179 if (inset->directWrite()) {
1180 // international char, let it write
1181 // code directly so it's shorter in
1187 os << "\\begin_inset ";
1189 os << "\n\\end_inset\n\n";
1195 os << "\n\\backslash\n";
1199 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1206 if ((column > 70 && c == ' ')
1211 // this check is to amend a bug. LyX sometimes
1212 // inserts '\0' this could cause problems.
1214 os << to_utf8(docstring(1, c));
1216 LYXERR0("NUL char in structure.");
1222 os << "\n\\end_layout\n";
1226 void Paragraph::validate(LaTeXFeatures & features) const
1228 d->validate(features, *d->layout_);
1232 void Paragraph::insert(pos_type start, docstring const & str,
1233 Font const & font, Change const & change)
1235 for (size_t i = 0, n = str.size(); i != n ; ++i)
1236 insertChar(start + i, str[i], font, change);
1240 void Paragraph::appendChar(char_type c, Font const & font,
1241 Change const & change)
1244 d->changes_.insert(change, d->text_.size());
1245 // when appending characters, no need to update tables
1246 d->text_.push_back(c);
1247 setFont(d->text_.size() - 1, font);
1251 void Paragraph::appendString(docstring const & s, Font const & font,
1252 Change const & change)
1254 pos_type end = s.size();
1255 size_t oldsize = d->text_.size();
1256 size_t newsize = oldsize + end;
1257 size_t capacity = d->text_.capacity();
1258 if (newsize >= capacity)
1259 d->text_.reserve(max(capacity + 100, newsize));
1261 // when appending characters, no need to update tables
1264 // FIXME: Optimize this!
1265 for (pos_type i = oldsize; i != newsize; ++i) {
1267 d->changes_.insert(change, i);
1269 d->fontlist_.set(oldsize, font);
1270 d->fontlist_.set(newsize - 1, font);
1274 void Paragraph::insertChar(pos_type pos, char_type c,
1277 d->insertChar(pos, c, Change(trackChanges ?
1278 Change::INSERTED : Change::UNCHANGED));
1282 void Paragraph::insertChar(pos_type pos, char_type c,
1283 Font const & font, bool trackChanges)
1285 d->insertChar(pos, c, Change(trackChanges ?
1286 Change::INSERTED : Change::UNCHANGED));
1291 void Paragraph::insertChar(pos_type pos, char_type c,
1292 Font const & font, Change const & change)
1294 d->insertChar(pos, c, change);
1299 void Paragraph::insertInset(pos_type pos, Inset * inset,
1300 Font const & font, Change const & change)
1302 insertInset(pos, inset, change);
1303 // Set the font/language of the inset...
1308 void Paragraph::resetFonts(Font const & font)
1310 d->fontlist_.clear();
1311 d->fontlist_.set(0, font);
1312 d->fontlist_.set(d->text_.size() - 1, font);
1315 // Gets uninstantiated font setting at position.
1316 Font const Paragraph::getFontSettings(BufferParams const & bparams,
1320 LYXERR0("pos: " << pos << " size: " << size());
1321 LASSERT(pos <= size(), /**/);
1324 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1325 if (cit != d->fontlist_.end())
1328 if (pos == size() && !empty())
1329 return getFontSettings(bparams, pos - 1);
1331 return Font(inherit_font, getParLanguage(bparams));
1335 FontSpan Paragraph::fontSpan(pos_type pos) const
1337 LASSERT(pos <= size(), /**/);
1340 FontList::const_iterator cit = d->fontlist_.begin();
1341 FontList::const_iterator end = d->fontlist_.end();
1342 for (; cit != end; ++cit) {
1343 if (cit->pos() >= pos) {
1344 if (pos >= beginOfBody())
1345 return FontSpan(max(start, beginOfBody()),
1348 return FontSpan(start,
1349 min(beginOfBody() - 1,
1352 start = cit->pos() + 1;
1355 // This should not happen, but if so, we take no chances.
1356 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1357 return FontSpan(pos, pos);
1361 // Gets uninstantiated font setting at position 0
1362 Font const Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1364 if (!empty() && !d->fontlist_.empty())
1365 return d->fontlist_.begin()->font();
1367 return Font(inherit_font, bparams.language);
1371 // Gets the fully instantiated font at a given position in a paragraph
1372 // This is basically the same function as Text::GetFont() in text2.cpp.
1373 // The difference is that this one is used for generating the LaTeX file,
1374 // and thus cosmetic "improvements" are disallowed: This has to deliver
1375 // the true picture of the buffer. (Asger)
1376 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1377 Font const & outerfont) const
1379 LASSERT(pos >= 0, /**/);
1381 Font font = getFontSettings(bparams, pos);
1383 pos_type const body_pos = beginOfBody();
1385 font.fontInfo().realize(d->layout_->labelfont);
1387 font.fontInfo().realize(d->layout_->font);
1389 font.fontInfo().realize(outerfont.fontInfo());
1390 font.fontInfo().realize(bparams.getFont().fontInfo());
1396 Font const Paragraph::getLabelFont
1397 (BufferParams const & bparams, Font const & outerfont) const
1399 FontInfo tmpfont = d->layout_->labelfont;
1400 tmpfont.realize(outerfont.fontInfo());
1401 tmpfont.realize(bparams.getFont().fontInfo());
1402 return Font(tmpfont, getParLanguage(bparams));
1406 Font const Paragraph::getLayoutFont
1407 (BufferParams const & bparams, Font const & outerfont) const
1409 FontInfo tmpfont = d->layout_->font;
1410 tmpfont.realize(outerfont.fontInfo());
1411 tmpfont.realize(bparams.getFont().fontInfo());
1412 return Font(tmpfont, getParLanguage(bparams));
1416 /// Returns the height of the highest font in range
1417 FontSize Paragraph::highestFontInRange
1418 (pos_type startpos, pos_type endpos, FontSize def_size) const
1420 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1424 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1426 char_type c = d->text_[pos];
1427 if (!lyxrc.rtl_support)
1457 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1463 void Paragraph::setFont(pos_type pos, Font const & font)
1465 LASSERT(pos <= size(), /**/);
1467 // First, reduce font against layout/label font
1468 // Update: The setCharFont() routine in text2.cpp already
1469 // reduces font, so we don't need to do that here. (Asger)
1471 d->fontlist_.set(pos, font);
1475 void Paragraph::makeSameLayout(Paragraph const & par)
1477 d->layout_ = par.d->layout_;
1478 d->params_ = par.d->params_;
1482 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1484 if (isFreeSpacing())
1490 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1491 if (eraseChar(pos, trackChanges))
1497 return count > 0 || pos > 0;
1501 bool Paragraph::hasSameLayout(Paragraph const & par) const
1503 return par.d->layout_ == d->layout_
1504 && d->params_.sameLayout(par.d->params_);
1508 depth_type Paragraph::getDepth() const
1510 return d->params_.depth();
1514 depth_type Paragraph::getMaxDepthAfter() const
1516 if (d->layout_->isEnvironment())
1517 return d->params_.depth() + 1;
1519 return d->params_.depth();
1523 char Paragraph::getAlign() const
1525 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1526 return d->layout_->align;
1528 return d->params_.align();
1532 docstring const & Paragraph::labelString() const
1534 return d->params_.labelString();
1538 // the next two functions are for the manual labels
1539 docstring const Paragraph::getLabelWidthString() const
1541 if (d->layout_->margintype == MARGIN_MANUAL)
1542 return d->params_.labelWidthString();
1544 return _("Senseless with this layout!");
1548 void Paragraph::setLabelWidthString(docstring const & s)
1550 d->params_.labelWidthString(s);
1554 docstring const Paragraph::translateIfPossible(docstring const & s,
1555 BufferParams const & bparams) const
1557 if (!isAscii(s) || s.empty()) {
1558 // This must be a user defined layout. We cannot translate
1559 // this, since gettext accepts only ascii keys.
1562 // Probably standard layout, try to translate
1563 Messages & m = getMessages(getParLanguage(bparams)->code());
1564 return m.get(to_ascii(s));
1568 docstring Paragraph::expandLabel(Layout const & layout,
1569 BufferParams const & bparams, bool process_appendix) const
1571 DocumentClass const & tclass = bparams.documentClass();
1574 if (process_appendix && d->params_.appendix())
1575 fmt = translateIfPossible(layout.labelstring_appendix(),
1578 fmt = translateIfPossible(layout.labelstring(), bparams);
1580 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1581 && !layout.counter.empty())
1582 fmt = "\\the" + layout.counter;
1584 // handle 'inherited level parts' in 'fmt',
1585 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1586 size_t const i = fmt.find('@', 0);
1587 if (i != docstring::npos) {
1588 size_t const j = fmt.find('@', i + 1);
1589 if (j != docstring::npos) {
1590 docstring parent(fmt, i + 1, j - i - 1);
1591 docstring label = from_ascii("??");
1592 if (tclass.hasLayout(parent))
1593 docstring label = expandLabel(tclass[parent], bparams,
1595 fmt = docstring(fmt, 0, i) + label
1596 + docstring(fmt, j + 1, docstring::npos);
1600 return tclass.counters().counterLabel(fmt);
1604 void Paragraph::applyLayout(Layout const & new_layout)
1606 d->layout_ = &new_layout;
1607 LyXAlignment const oldAlign = d->params_.align();
1609 if (!(oldAlign & d->layout_->alignpossible)) {
1610 frontend::Alert::warning(_("Alignment not permitted"),
1611 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1612 d->params_.align(LYX_ALIGN_LAYOUT);
1617 pos_type Paragraph::beginOfBody() const
1619 return d->begin_of_body_;
1623 void Paragraph::setBeginOfBody()
1625 if (d->layout_->labeltype != LABEL_MANUAL) {
1626 d->begin_of_body_ = 0;
1630 // Unroll the first two cycles of the loop
1631 // and remember the previous character to
1632 // remove unnecessary getChar() calls
1634 pos_type end = size();
1635 if (i < end && !isNewline(i)) {
1637 char_type previous_char = 0;
1640 previous_char = d->text_[i];
1641 if (!isNewline(i)) {
1643 while (i < end && previous_char != ' ') {
1648 previous_char = temp;
1654 d->begin_of_body_ = i;
1658 bool Paragraph::forcePlainLayout() const
1660 return inInset().forcePlainLayout();
1664 bool Paragraph::allowParagraphCustomization() const
1666 return inInset().allowParagraphCustomization();
1670 bool Paragraph::usePlainLayout() const
1672 return inInset().usePlainLayout();
1678 // paragraphs inside floats need different alignment tags to avoid
1681 bool noTrivlistCentering(InsetCode code)
1683 return code == FLOAT_CODE || code == WRAP_CODE;
1687 string correction(string const & orig)
1689 if (orig == "flushleft")
1690 return "raggedright";
1691 if (orig == "flushright")
1692 return "raggedleft";
1693 if (orig == "center")
1699 string const corrected_env(string const & suffix, string const & env,
1702 string output = suffix + "{";
1703 if (noTrivlistCentering(code))
1704 output += correction(env);
1708 if (suffix == "\\begin")
1714 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1716 if (!contains(str, "\n"))
1717 column += str.size();
1721 column = rsplit(str, tmp, '\n').size();
1728 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1729 odocstream & os, TexRow & texrow,
1730 bool moving_arg) const
1734 if (params_.noindent()) {
1735 os << "\\noindent ";
1739 LyXAlignment const curAlign = params_.align();
1741 if (curAlign == layout_->align)
1745 case LYX_ALIGN_NONE:
1746 case LYX_ALIGN_BLOCK:
1747 case LYX_ALIGN_LAYOUT:
1748 case LYX_ALIGN_SPECIAL:
1750 case LYX_ALIGN_LEFT:
1751 case LYX_ALIGN_RIGHT:
1752 case LYX_ALIGN_CENTER:
1761 case LYX_ALIGN_NONE:
1762 case LYX_ALIGN_BLOCK:
1763 case LYX_ALIGN_LAYOUT:
1764 case LYX_ALIGN_SPECIAL:
1766 case LYX_ALIGN_LEFT: {
1768 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1769 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1771 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1772 os << from_ascii(output);
1773 adjust_row_column(output, texrow, column);
1775 } case LYX_ALIGN_RIGHT: {
1777 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1778 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1780 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1781 os << from_ascii(output);
1782 adjust_row_column(output, texrow, column);
1784 } case LYX_ALIGN_CENTER: {
1786 output = corrected_env("\\begin", "center", owner_->ownerCode());
1787 os << from_ascii(output);
1788 adjust_row_column(output, texrow, column);
1797 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1798 odocstream & os, TexRow & texrow,
1799 bool moving_arg) const
1803 switch (params_.align()) {
1804 case LYX_ALIGN_NONE:
1805 case LYX_ALIGN_BLOCK:
1806 case LYX_ALIGN_LAYOUT:
1807 case LYX_ALIGN_SPECIAL:
1809 case LYX_ALIGN_LEFT:
1810 case LYX_ALIGN_RIGHT:
1811 case LYX_ALIGN_CENTER:
1819 switch (params_.align()) {
1820 case LYX_ALIGN_NONE:
1821 case LYX_ALIGN_BLOCK:
1822 case LYX_ALIGN_LAYOUT:
1823 case LYX_ALIGN_SPECIAL:
1825 case LYX_ALIGN_LEFT: {
1827 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1828 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1830 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1831 os << from_ascii(output);
1832 adjust_row_column(output, texrow, column);
1834 } case LYX_ALIGN_RIGHT: {
1836 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1839 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1840 os << from_ascii(output);
1841 adjust_row_column(output, texrow, column);
1843 } case LYX_ALIGN_CENTER: {
1845 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1846 os << from_ascii(output);
1847 adjust_row_column(output, texrow, column);
1856 // This one spits out the text of the paragraph
1857 bool Paragraph::latex(BufferParams const & bparams,
1858 Font const & outerfont,
1859 odocstream & os, TexRow & texrow,
1860 OutputParams const & runparams) const
1862 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1864 bool return_value = false;
1866 bool asdefault = forcePlainLayout();
1868 Layout const & style = asdefault ?
1869 bparams.documentClass().plainLayout() :
1872 // Current base font for all inherited font changes, without any
1873 // change caused by an individual character, except for the language:
1874 // It is set to the language of the first character.
1875 // As long as we are in the label, this font is the base font of the
1876 // label. Before the first body character it is set to the base font
1880 // Maybe we have to create a optional argument.
1881 pos_type body_pos = beginOfBody();
1882 unsigned int column = 0;
1885 // the optional argument is kept in curly brackets in
1886 // case it contains a ']'
1889 basefont = getLabelFont(bparams, outerfont);
1891 basefont = getLayoutFont(bparams, outerfont);
1894 // Which font is currently active?
1895 Font running_font(basefont);
1896 // Do we have an open font change?
1897 bool open_font = false;
1899 Change runningChange = Change(Change::UNCHANGED);
1901 texrow.start(id(), 0);
1903 // if the paragraph is empty, the loop will not be entered at all
1905 if (style.isCommand()) {
1910 column += d->startTeXParParams(bparams, os, texrow,
1911 runparams.moving_arg);
1914 for (pos_type i = 0; i < size(); ++i) {
1915 // First char in paragraph or after label?
1916 if (i == body_pos) {
1919 column += running_font.latexWriteEndChanges(
1920 os, bparams, runparams,
1921 basefont, basefont);
1924 basefont = getLayoutFont(bparams, outerfont);
1925 running_font = basefont;
1927 column += Changes::latexMarkChange(os, bparams,
1928 runningChange, Change(Change::UNCHANGED));
1929 runningChange = Change(Change::UNCHANGED);
1934 if (style.isCommand()) {
1940 column += d->startTeXParParams(bparams, os,
1942 runparams.moving_arg);
1945 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1948 if (bparams.outputChanges && runningChange != change) {
1950 column += running_font.latexWriteEndChanges(
1951 os, bparams, runparams, basefont, basefont);
1954 basefont = getLayoutFont(bparams, outerfont);
1955 running_font = basefont;
1957 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1958 runningChange = change;
1961 // do not output text which is marked deleted
1962 // if change tracking output is disabled
1963 if (!bparams.outputChanges && change.type == Change::DELETED) {
1969 // Fully instantiated font
1970 Font const font = getFont(bparams, i, outerfont);
1972 Font const last_font = running_font;
1974 // Do we need to close the previous font?
1976 (font != running_font ||
1977 font.language() != running_font.language()))
1979 column += running_font.latexWriteEndChanges(
1980 os, bparams, runparams, basefont,
1981 (i == body_pos-1) ? basefont : font);
1982 running_font = basefont;
1986 // close babel's font environment before opening CJK.
1987 if (!running_font.language()->babel().empty() &&
1988 font.language()->encoding()->package() == Encoding::CJK) {
1989 string end_tag = subst(lyxrc.language_command_end,
1991 running_font.language()->babel());
1992 os << from_ascii(end_tag);
1993 column += end_tag.length();
1996 // Switch file encoding if necessary (and allowed)
1997 if (!runparams.verbatim &&
1998 runparams.encoding->package() != Encoding::none &&
1999 font.language()->encoding()->package() != Encoding::none) {
2000 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2001 runparams, *(font.language()->encoding()));
2002 if (enc_switch.first) {
2003 column += enc_switch.second;
2004 runparams.encoding = font.language()->encoding();
2008 char_type const c = d->text_[i];
2010 // Do we need to change font?
2011 if ((font != running_font ||
2012 font.language() != running_font.language()) &&
2015 odocstringstream ods;
2016 column += font.latexWriteStartChanges(ods, bparams,
2017 runparams, basefont,
2019 running_font = font;
2021 docstring fontchange = ods.str();
2022 // check if the fontchange ends with a trailing blank
2023 // (like "\small " (see bug 3382)
2024 if (suffixIs(fontchange, ' ') && c == ' ')
2025 os << fontchange.substr(0, fontchange.size() - 1)
2026 << from_ascii("{}");
2032 // FIXME: integrate this case in latexSpecialChar
2033 // Do not print the separation of the optional argument
2034 // if style.pass_thru is false. This works because
2035 // latexSpecialChar ignores spaces if
2036 // style.pass_thru is false.
2037 if (i != body_pos - 1) {
2038 if (d->simpleTeXBlanks(
2039 runparams, os, texrow,
2040 i, column, font, style)) {
2041 // A surrogate pair was output. We
2042 // must not call latexSpecialChar
2043 // in this iteration, since it would output
2044 // the combining character again.
2051 OutputParams rp = runparams;
2052 rp.free_spacing = style.free_spacing;
2053 rp.local_font = &font;
2054 rp.intitle = style.intitle;
2056 // Two major modes: LaTeX or plain
2057 // Handle here those cases common to both modes
2058 // and then split to handle the two modes separately.
2059 if (c == META_INSET)
2060 d->latexInset(bparams, os,
2061 texrow, rp, running_font,
2062 basefont, outerfont, open_font,
2063 runningChange, style, i, column);
2066 d->latexSpecialChar(os, rp, running_font, runningChange,
2068 } catch (EncodingException & e) {
2069 if (runparams.dryrun) {
2070 os << "<" << _("LyX Warning: ")
2071 << _("uncodable character") << " '";
2075 // add location information and throw again.
2083 // Set the encoding to that returned from latexSpecialChar (see
2084 // comment for encoding member in OutputParams.h)
2085 runparams.encoding = rp.encoding;
2088 // If we have an open font definition, we have to close it
2090 #ifdef FIXED_LANGUAGE_END_DETECTION
2093 .latexWriteEndChanges(os, bparams, runparams,
2095 next_->getFont(bparams, 0, outerfont));
2097 running_font.latexWriteEndChanges(os, bparams,
2098 runparams, basefont, basefont);
2101 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2102 //FIXME: there as we start another \selectlanguage with the next paragraph if
2103 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2104 running_font.latexWriteEndChanges(os, bparams, runparams,
2105 basefont, basefont);
2109 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2111 // Needed if there is an optional argument but no contents.
2112 if (body_pos > 0 && body_pos == size()) {
2114 return_value = false;
2118 column += d->endTeXParParams(bparams, os, texrow,
2119 runparams.moving_arg);
2122 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2123 return return_value;
2127 bool Paragraph::emptyTag() const
2129 for (pos_type i = 0; i < size(); ++i) {
2130 if (Inset const * inset = getInset(i)) {
2131 InsetCode lyx_code = inset->lyxCode();
2132 if (lyx_code != TOC_CODE &&
2133 lyx_code != INCLUDE_CODE &&
2134 lyx_code != GRAPHICS_CODE &&
2135 lyx_code != ERT_CODE &&
2136 lyx_code != LISTINGS_CODE &&
2137 lyx_code != FLOAT_CODE &&
2138 lyx_code != TABULAR_CODE) {
2142 char_type c = d->text_[i];
2143 if (c != ' ' && c != '\t')
2151 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2154 for (pos_type i = 0; i < size(); ++i) {
2155 if (Inset const * inset = getInset(i)) {
2156 InsetCode lyx_code = inset->lyxCode();
2157 if (lyx_code == LABEL_CODE) {
2158 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2159 docstring const & id = il->getParam("name");
2160 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2168 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2172 for (i = 0; i < size(); ++i) {
2173 if (Inset const * inset = getInset(i)) {
2174 inset->docbook(os, runparams);
2176 char_type c = d->text_[i];
2179 os << sgml::escapeChar(c);
2186 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2189 pos_type size = text_.size();
2190 for (pos_type i = initial; i < size; ++i) {
2191 Font font = owner_->getFont(buf.params(), i, outerfont);
2192 if (text_[i] == META_INSET)
2194 if (i != initial && font != font_old)
2203 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2205 OutputParams const & runparams,
2206 Font const & outerfont,
2207 pos_type initial) const
2209 bool emph_flag = false;
2211 Layout const & style = *d->layout_;
2213 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2215 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2218 // parsing main loop
2219 for (pos_type i = initial; i < size(); ++i) {
2220 Font font = getFont(buf.params(), i, outerfont);
2222 // handle <emphasis> tag
2223 if (font_old.emph() != font.fontInfo().emph()) {
2224 if (font.fontInfo().emph() == FONT_ON) {
2227 } else if (i != initial) {
2228 os << "</emphasis>";
2233 if (Inset const * inset = getInset(i)) {
2234 inset->docbook(os, runparams);
2236 char_type c = d->text_[i];
2238 if (style.pass_thru)
2241 os << sgml::escapeChar(c);
2243 font_old = font.fontInfo();
2247 os << "</emphasis>";
2250 if (style.free_spacing)
2252 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2257 bool Paragraph::isHfill(pos_type pos) const
2259 Inset const * inset = getInset(pos);
2260 return inset && (inset->lyxCode() == SPACE_CODE &&
2261 inset->isStretchableSpace());
2265 bool Paragraph::isNewline(pos_type pos) const
2267 Inset const * inset = getInset(pos);
2268 return inset && inset->lyxCode() == NEWLINE_CODE;
2272 bool Paragraph::isLineSeparator(pos_type pos) const
2274 char_type const c = d->text_[pos];
2275 if (isLineSeparatorChar(c))
2277 Inset const * inset = getInset(pos);
2278 return inset && inset->isLineSeparator();
2282 /// Used by the spellchecker
2283 bool Paragraph::isLetter(pos_type pos) const
2285 if (Inset const * inset = getInset(pos))
2286 return inset->isLetter();
2287 char_type const c = d->text_[pos];
2288 return isLetterChar(c) || isDigit(c);
2292 bool Paragraph::isChar(pos_type pos) const
2294 if (Inset const * inset = getInset(pos))
2295 return inset->isChar();
2296 char_type const c = d->text_[pos];
2297 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2301 bool Paragraph::isSpace(pos_type pos) const
2303 if (Inset const * inset = getInset(pos))
2304 return inset->isSpace();
2305 char_type const c = d->text_[pos];
2306 return lyx::isSpace(c);
2311 Paragraph::getParLanguage(BufferParams const & bparams) const
2314 return getFirstFontSettings(bparams).language();
2315 // FIXME: we should check the prev par as well (Lgb)
2316 return bparams.language;
2320 bool Paragraph::isRTL(BufferParams const & bparams) const
2322 return lyxrc.rtl_support
2323 && getParLanguage(bparams)->rightToLeft()
2324 && ownerCode() != ERT_CODE
2325 && ownerCode() != LISTINGS_CODE;
2329 void Paragraph::changeLanguage(BufferParams const & bparams,
2330 Language const * from, Language const * to)
2332 // change language including dummy font change at the end
2333 for (pos_type i = 0; i <= size(); ++i) {
2334 Font font = getFontSettings(bparams, i);
2335 if (font.language() == from) {
2336 font.setLanguage(to);
2343 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2345 Language const * doc_language = bparams.language;
2346 FontList::const_iterator cit = d->fontlist_.begin();
2347 FontList::const_iterator end = d->fontlist_.end();
2349 for (; cit != end; ++cit)
2350 if (cit->font().language() != ignore_language &&
2351 cit->font().language() != latex_language &&
2352 cit->font().language() != doc_language)
2358 docstring Paragraph::asString(int options) const
2360 return asString(0, size(), options);
2364 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2366 odocstringstream os;
2369 && options & AS_STR_LABEL
2370 && !d->params_.labelString().empty())
2371 os << d->params_.labelString() << ' ';
2373 for (pos_type i = beg; i < end; ++i) {
2374 char_type const c = d->text_[i];
2377 else if (c == META_INSET && options & AS_STR_INSETS)
2378 getInset(i)->textString(os);
2385 void Paragraph::setInsetOwner(Inset const * inset)
2387 d->inset_owner_ = inset;
2391 int Paragraph::id() const
2397 Layout const & Paragraph::layout() const
2403 void Paragraph::setLayout(Layout const & layout)
2405 d->layout_ = &layout;
2409 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2411 if (usePlainLayout())
2412 setLayout(tclass.plainLayout());
2414 setLayout(tclass.defaultLayout());
2418 Inset const & Paragraph::inInset() const
2420 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2421 _("Memory problem"), _("Paragraph not properly initiliazed")));
2422 return *d->inset_owner_;
2426 InsetCode Paragraph::ownerCode() const
2428 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2432 ParagraphParameters & Paragraph::params()
2438 ParagraphParameters const & Paragraph::params() const
2444 bool Paragraph::isFreeSpacing() const
2446 if (d->layout_->free_spacing)
2448 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2452 bool Paragraph::allowEmpty() const
2454 if (d->layout_->keepempty)
2456 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2460 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2462 if (!Encodings::isArabicChar(c))
2465 char_type prev_char = ' ';
2466 char_type next_char = ' ';
2468 for (pos_type i = pos - 1; i >= 0; --i) {
2469 char_type const par_char = d->text_[i];
2470 if (!Encodings::isArabicComposeChar(par_char)) {
2471 prev_char = par_char;
2476 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2477 char_type const par_char = d->text_[i];
2478 if (!Encodings::isArabicComposeChar(par_char)) {
2479 next_char = par_char;
2484 if (Encodings::isArabicChar(next_char)) {
2485 if (Encodings::isArabicChar(prev_char) &&
2486 !Encodings::isArabicSpecialChar(prev_char))
2487 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2489 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2491 if (Encodings::isArabicChar(prev_char) &&
2492 !Encodings::isArabicSpecialChar(prev_char))
2493 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2495 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2500 int Paragraph::checkBiblio(Buffer const & buffer)
2503 // This is getting more and more a mess. ...We really should clean
2504 // up this bibitem issue for 1.6. See also bug 2743.
2506 // Add bibitem insets if necessary
2507 if (d->layout_->labeltype != LABEL_BIBLIO)
2510 bool hasbibitem = !d->insetlist_.empty()
2511 // Insist on it being in pos 0
2512 && d->text_[0] == META_INSET
2513 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2515 bool track_changes = buffer.params().trackChanges;
2520 // remove a bibitem in pos != 0
2521 // restore it later in pos 0 if necessary
2522 // (e.g. if a user inserts contents _before_ the item)
2523 // we're assuming there's only one of these, which there
2525 int erasedInsetPosition = -1;
2526 InsetList::iterator it = d->insetlist_.begin();
2527 InsetList::iterator end = d->insetlist_.end();
2528 for (; it != end; ++it)
2529 if (it->inset->lyxCode() == BIBITEM_CODE
2531 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2532 oldkey = olditem->getParam("key");
2533 oldlabel = olditem->getParam("label");
2534 erasedInsetPosition = it->pos;
2535 eraseChar(erasedInsetPosition, track_changes);
2539 // There was an InsetBibitem at the beginning, and we didn't
2540 // have to erase one.
2541 if (hasbibitem && erasedInsetPosition < 0)
2544 // There was an InsetBibitem at the beginning and we did have to
2545 // erase one. So we give its properties to the beginning inset.
2547 InsetBibitem * inset =
2548 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2549 if (!oldkey.empty())
2550 inset->setParam("key", oldkey);
2551 inset->setParam("label", oldlabel);
2552 return -erasedInsetPosition;
2555 // There was no inset at the beginning, so we need to create one with
2556 // the key and label of the one we erased.
2557 InsetBibitem * inset =
2558 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2559 // restore values of previously deleted item in this par.
2560 if (!oldkey.empty())
2561 inset->setParam("key", oldkey);
2562 inset->setParam("label", oldlabel);
2563 insertInset(0, static_cast<Inset *>(inset),
2564 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2570 void Paragraph::checkAuthors(AuthorList const & authorList)
2572 d->changes_.checkAuthors(authorList);
2576 bool Paragraph::isUnchanged(pos_type pos) const
2578 return lookupChange(pos).type == Change::UNCHANGED;
2582 bool Paragraph::isInserted(pos_type pos) const
2584 return lookupChange(pos).type == Change::INSERTED;
2588 bool Paragraph::isDeleted(pos_type pos) const
2590 return lookupChange(pos).type == Change::DELETED;
2594 InsetList const & Paragraph::insetList() const
2596 return d->insetlist_;
2600 void Paragraph::setBuffer(Buffer & b)
2602 d->insetlist_.setBuffer(b);
2606 Inset * Paragraph::releaseInset(pos_type pos)
2608 Inset * inset = d->insetlist_.release(pos);
2609 /// does not honour change tracking!
2610 eraseChar(pos, false);
2615 Inset * Paragraph::getInset(pos_type pos)
2617 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2618 ? d->insetlist_.get(pos) : 0;
2622 Inset const * Paragraph::getInset(pos_type pos) const
2624 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2625 ? d->insetlist_.get(pos) : 0;
2629 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2630 pos_type & right, TextCase action)
2632 // process sequences of modified characters; in change
2633 // tracking mode, this approach results in much better
2634 // usability than changing case on a char-by-char basis
2637 bool const trackChanges = bparams.trackChanges;
2639 bool capitalize = true;
2641 for (; pos < right; ++pos) {
2642 char_type oldChar = d->text_[pos];
2643 char_type newChar = oldChar;
2645 // ignore insets and don't play with deleted text!
2646 if (oldChar != META_INSET && !isDeleted(pos)) {
2648 case text_lowercase:
2649 newChar = lowercase(oldChar);
2651 case text_capitalization:
2653 newChar = uppercase(oldChar);
2657 case text_uppercase:
2658 newChar = uppercase(oldChar);
2663 if (!isLetter(pos) || isDeleted(pos)) {
2664 // permit capitalization again
2668 if (oldChar != newChar)
2671 if (oldChar == newChar || pos == right - 1) {
2672 if (oldChar != newChar) {
2673 // step behind the changing area
2676 int erasePos = pos - changes.size();
2677 for (size_t i = 0; i < changes.size(); i++) {
2678 insertChar(pos, changes[i],
2679 getFontSettings(bparams,
2682 if (!eraseChar(erasePos, trackChanges)) {
2685 ++right; // expand selection
2694 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2695 pos_type pos, bool del) const
2697 int const strsize = str.length();
2699 pos_type const parsize = d->text_.size();
2700 for (i = 0; pos + i < parsize; ++i) {
2703 if (cs && str[i] != d->text_[pos + i])
2705 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2707 if (!del && isDeleted(pos + i))
2714 // if necessary, check whether string matches word
2716 if (pos > 0 && isLetter(pos - 1))
2718 if (pos + strsize < parsize
2719 && isLetter(pos + strsize))
2727 char_type Paragraph::getChar(pos_type pos) const
2729 return d->text_[pos];
2733 pos_type Paragraph::size() const
2735 return d->text_.size();
2739 bool Paragraph::empty() const
2741 return d->text_.empty();
2745 bool Paragraph::isInset(pos_type pos) const
2747 return d->text_[pos] == META_INSET;
2751 bool Paragraph::isSeparator(pos_type pos) const
2753 //FIXME: Are we sure this can be the only separator?
2754 return d->text_[pos] == ' ';
2758 void Paragraph::deregisterWords()
2760 Private::Words::const_iterator it;
2761 WordList & wl = theWordList();
2762 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2768 void Paragraph::collectWords(CursorSlice const & sl)
2771 bool inword = false;
2773 //lyxerr << "Words: ";
2774 pos_type n = size();
2775 for (pos_type pos = 0; pos != n; ++pos) {
2779 if (!isLetter(pos)) {
2788 CursorSlice from = sl;
2789 CursorSlice to = sl;
2792 from.text()->getWord(from, to, WHOLE_WORD);
2793 if (to.pos() - from.pos() < 6)
2795 docstring word = asString(from.pos(), to.pos(), false);
2796 d->words_.insert(word);
2797 //lyxerr << word << " ";
2799 //lyxerr << std::endl;
2803 void Paragraph::registerWords()
2805 Private::Words::const_iterator it;
2806 WordList & wl = theWordList();
2807 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2812 void Paragraph::updateWords(CursorSlice const & sl)
2814 LASSERT(&sl.paragraph() == this, /**/);