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 * 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{}";
981 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
982 pos_type & i, unsigned int & column)
986 // within \ttfamily, "--" is merged to "-" (no endash)
987 // so we avoid this rather irritating ligature
988 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
995 // everything else has to be checked separately
996 // (depending on the encoding)
1003 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1004 unsigned int & column, OutputParams & runparams)
1006 // FIXME: if we have "LaTeX" with a font
1007 // change in the middle (before the 'T', then
1008 // the "TeX" part is still special cased.
1009 // Really we should only operate this on
1010 // "words" for some definition of word
1012 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1013 if (!isTextAt(special_phrases[pnr].phrase, i))
1015 if (runparams.moving_arg)
1017 os << special_phrases[pnr].macro;
1018 i += special_phrases[pnr].phrase.length() - 1;
1019 column += special_phrases[pnr].macro.length() - 1;
1026 void Paragraph::Private::validate(LaTeXFeatures & features,
1027 Layout const & layout) const
1029 // check the params.
1030 if (!params_.spacing().isDefault())
1031 features.require("setspace");
1034 features.useLayout(layout.name());
1037 fontlist_.validate(features);
1039 // then the indentation
1040 if (!params_.leftIndent().zero())
1041 features.require("ParagraphLeftIndent");
1044 InsetList::const_iterator icit = insetlist_.begin();
1045 InsetList::const_iterator iend = insetlist_.end();
1046 for (; icit != iend; ++icit) {
1048 icit->inset->validate(features);
1049 if (layout.needprotect &&
1050 icit->inset->lyxCode() == FOOT_CODE)
1051 features.require("NeedLyXFootnoteCode");
1055 // then the contents
1056 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1057 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1058 if (!special_phrases[pnr].builtin
1059 && isTextAt(special_phrases[pnr].phrase, i)) {
1060 features.require(special_phrases[pnr].phrase);
1064 Encodings::validate(text_[i], features);
1068 /////////////////////////////////////////////////////////////////////
1072 /////////////////////////////////////////////////////////////////////
1075 Layout const emptyParagraphLayout;
1078 Paragraph::Paragraph()
1079 : d(new Paragraph::Private(this, emptyParagraphLayout))
1086 Paragraph::Paragraph(Paragraph const & par)
1087 : itemdepth(par.itemdepth),
1088 d(new Paragraph::Private(*par.d, this))
1094 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1095 : itemdepth(par.itemdepth),
1096 d(new Paragraph::Private(*par.d, this, beg, end))
1102 Paragraph & Paragraph::operator=(Paragraph const & par)
1104 // needed as we will destroy the private part before copying it
1106 itemdepth = par.itemdepth;
1110 d = new Private(*par.d, this);
1117 Paragraph::~Paragraph()
1124 void Paragraph::write(ostream & os, BufferParams const & bparams,
1125 depth_type & dth) const
1127 // The beginning or end of a deeper (i.e. nested) area?
1128 if (dth != d->params_.depth()) {
1129 if (d->params_.depth() > dth) {
1130 while (d->params_.depth() > dth) {
1131 os << "\n\\begin_deeper";
1135 while (d->params_.depth() < dth) {
1136 os << "\n\\end_deeper";
1142 // First write the layout
1143 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1145 d->params_.write(os);
1147 Font font1(inherit_font, bparams.language);
1149 Change running_change = Change(Change::UNCHANGED);
1152 for (pos_type i = 0; i <= size(); ++i) {
1154 Change change = lookupChange(i);
1155 Changes::lyxMarkChange(os, column, running_change, change);
1156 running_change = change;
1161 // Write font changes
1162 Font font2 = getFontSettings(bparams, i);
1163 if (font2 != font1) {
1164 font2.lyxWriteChanges(font1, os);
1169 char_type const c = d->text_[i];
1172 if (Inset const * inset = getInset(i)) {
1173 if (inset->directWrite()) {
1174 // international char, let it write
1175 // code directly so it's shorter in
1181 os << "\\begin_inset ";
1183 os << "\n\\end_inset\n\n";
1189 os << "\n\\backslash\n";
1193 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1200 if ((column > 70 && c == ' ')
1205 // this check is to amend a bug. LyX sometimes
1206 // inserts '\0' this could cause problems.
1208 os << to_utf8(docstring(1, c));
1210 LYXERR0("NUL char in structure.");
1216 os << "\n\\end_layout\n";
1220 void Paragraph::validate(LaTeXFeatures & features) const
1222 d->validate(features, *d->layout_);
1226 void Paragraph::insert(pos_type start, docstring const & str,
1227 Font const & font, Change const & change)
1229 for (size_t i = 0, n = str.size(); i != n ; ++i)
1230 insertChar(start + i, str[i], font, change);
1234 void Paragraph::appendChar(char_type c, Font const & font,
1235 Change const & change)
1238 d->changes_.insert(change, d->text_.size());
1239 // when appending characters, no need to update tables
1240 d->text_.push_back(c);
1241 setFont(d->text_.size() - 1, font);
1245 void Paragraph::appendString(docstring const & s, Font const & font,
1246 Change const & change)
1248 pos_type end = s.size();
1249 size_t oldsize = d->text_.size();
1250 size_t newsize = oldsize + end;
1251 size_t capacity = d->text_.capacity();
1252 if (newsize >= capacity)
1253 d->text_.reserve(max(capacity + 100, newsize));
1255 // when appending characters, no need to update tables
1258 // FIXME: Optimize this!
1259 for (pos_type i = oldsize; i != newsize; ++i) {
1261 d->changes_.insert(change, i);
1263 d->fontlist_.set(oldsize, font);
1264 d->fontlist_.set(newsize - 1, font);
1268 void Paragraph::insertChar(pos_type pos, char_type c,
1271 d->insertChar(pos, c, Change(trackChanges ?
1272 Change::INSERTED : Change::UNCHANGED));
1276 void Paragraph::insertChar(pos_type pos, char_type c,
1277 Font const & font, bool trackChanges)
1279 d->insertChar(pos, c, Change(trackChanges ?
1280 Change::INSERTED : Change::UNCHANGED));
1285 void Paragraph::insertChar(pos_type pos, char_type c,
1286 Font const & font, Change const & change)
1288 d->insertChar(pos, c, change);
1293 void Paragraph::insertInset(pos_type pos, Inset * inset,
1294 Font const & font, Change const & change)
1296 insertInset(pos, inset, change);
1297 // Set the font/language of the inset...
1302 bool Paragraph::insetAllowed(InsetCode code)
1304 return !d->inset_owner_ || d->inset_owner_->insetAllowed(code);
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 Inset const * const inset = inInset();
1663 return inset->forcePlainLayout();
1667 bool Paragraph::allowParagraphCustomization() const
1669 Inset const * const inset = inInset();
1672 return inset->allowParagraphCustomization();
1676 bool Paragraph::usePlainLayout() const
1678 Inset const * const inset = inInset();
1681 return inset->usePlainLayout();
1687 // paragraphs inside floats need different alignment tags to avoid
1690 bool noTrivlistCentering(InsetCode code)
1692 return code == FLOAT_CODE || code == WRAP_CODE;
1696 string correction(string const & orig)
1698 if (orig == "flushleft")
1699 return "raggedright";
1700 if (orig == "flushright")
1701 return "raggedleft";
1702 if (orig == "center")
1708 string const corrected_env(string const & suffix, string const & env,
1711 string output = suffix + "{";
1712 if (noTrivlistCentering(code))
1713 output += correction(env);
1717 if (suffix == "\\begin")
1723 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1725 if (!contains(str, "\n"))
1726 column += str.size();
1730 column = rsplit(str, tmp, '\n').size();
1737 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1738 odocstream & os, TexRow & texrow,
1739 bool moving_arg) const
1743 if (params_.noindent()) {
1744 os << "\\noindent ";
1748 LyXAlignment const curAlign = params_.align();
1750 if (curAlign == layout_->align)
1754 case LYX_ALIGN_NONE:
1755 case LYX_ALIGN_BLOCK:
1756 case LYX_ALIGN_LAYOUT:
1757 case LYX_ALIGN_SPECIAL:
1759 case LYX_ALIGN_LEFT:
1760 case LYX_ALIGN_RIGHT:
1761 case LYX_ALIGN_CENTER:
1770 case LYX_ALIGN_NONE:
1771 case LYX_ALIGN_BLOCK:
1772 case LYX_ALIGN_LAYOUT:
1773 case LYX_ALIGN_SPECIAL:
1775 case LYX_ALIGN_LEFT: {
1777 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1778 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1780 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1781 os << from_ascii(output);
1782 adjust_row_column(output, texrow, column);
1784 } case LYX_ALIGN_RIGHT: {
1786 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1787 output = corrected_env("\\begin", "flushright", owner_->ownerCode());
1789 output = corrected_env("\\begin", "flushleft", owner_->ownerCode());
1790 os << from_ascii(output);
1791 adjust_row_column(output, texrow, column);
1793 } case LYX_ALIGN_CENTER: {
1795 output = corrected_env("\\begin", "center", owner_->ownerCode());
1796 os << from_ascii(output);
1797 adjust_row_column(output, texrow, column);
1806 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1807 odocstream & os, TexRow & texrow,
1808 bool moving_arg) const
1812 switch (params_.align()) {
1813 case LYX_ALIGN_NONE:
1814 case LYX_ALIGN_BLOCK:
1815 case LYX_ALIGN_LAYOUT:
1816 case LYX_ALIGN_SPECIAL:
1818 case LYX_ALIGN_LEFT:
1819 case LYX_ALIGN_RIGHT:
1820 case LYX_ALIGN_CENTER:
1828 switch (params_.align()) {
1829 case LYX_ALIGN_NONE:
1830 case LYX_ALIGN_BLOCK:
1831 case LYX_ALIGN_LAYOUT:
1832 case LYX_ALIGN_SPECIAL:
1834 case LYX_ALIGN_LEFT: {
1836 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1837 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1839 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1840 os << from_ascii(output);
1841 adjust_row_column(output, texrow, column);
1843 } case LYX_ALIGN_RIGHT: {
1845 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1846 output = corrected_env("\n\\par\\end", "flushright", owner_->ownerCode());
1848 output = corrected_env("\n\\par\\end", "flushleft", owner_->ownerCode());
1849 os << from_ascii(output);
1850 adjust_row_column(output, texrow, column);
1852 } case LYX_ALIGN_CENTER: {
1854 output = corrected_env("\n\\par\\end", "center", owner_->ownerCode());
1855 os << from_ascii(output);
1856 adjust_row_column(output, texrow, column);
1865 // This one spits out the text of the paragraph
1866 bool Paragraph::latex(BufferParams const & bparams,
1867 Font const & outerfont,
1868 odocstream & os, TexRow & texrow,
1869 OutputParams const & runparams) const
1871 LYXERR(Debug::LATEX, "SimpleTeXOnePar... " << this);
1873 bool return_value = false;
1875 bool asdefault = forcePlainLayout();
1877 Layout const & style = asdefault ?
1878 bparams.documentClass().plainLayout() :
1881 // Current base font for all inherited font changes, without any
1882 // change caused by an individual character, except for the language:
1883 // It is set to the language of the first character.
1884 // As long as we are in the label, this font is the base font of the
1885 // label. Before the first body character it is set to the base font
1889 // Maybe we have to create a optional argument.
1890 pos_type body_pos = beginOfBody();
1891 unsigned int column = 0;
1894 // the optional argument is kept in curly brackets in
1895 // case it contains a ']'
1898 basefont = getLabelFont(bparams, outerfont);
1900 basefont = getLayoutFont(bparams, outerfont);
1903 // Which font is currently active?
1904 Font running_font(basefont);
1905 // Do we have an open font change?
1906 bool open_font = false;
1908 Change runningChange = Change(Change::UNCHANGED);
1910 texrow.start(id(), 0);
1912 // if the paragraph is empty, the loop will not be entered at all
1914 if (style.isCommand()) {
1919 column += d->startTeXParParams(bparams, os, texrow,
1920 runparams.moving_arg);
1923 for (pos_type i = 0; i < size(); ++i) {
1924 // First char in paragraph or after label?
1925 if (i == body_pos) {
1928 column += running_font.latexWriteEndChanges(
1929 os, bparams, runparams,
1930 basefont, basefont);
1933 basefont = getLayoutFont(bparams, outerfont);
1934 running_font = basefont;
1936 column += Changes::latexMarkChange(os, bparams,
1937 runningChange, Change(Change::UNCHANGED));
1938 runningChange = Change(Change::UNCHANGED);
1943 if (style.isCommand()) {
1949 column += d->startTeXParParams(bparams, os,
1951 runparams.moving_arg);
1954 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
1957 if (bparams.outputChanges && runningChange != change) {
1959 column += running_font.latexWriteEndChanges(
1960 os, bparams, runparams, basefont, basefont);
1963 basefont = getLayoutFont(bparams, outerfont);
1964 running_font = basefont;
1966 column += Changes::latexMarkChange(os, bparams, runningChange, change);
1967 runningChange = change;
1970 // do not output text which is marked deleted
1971 // if change tracking output is disabled
1972 if (!bparams.outputChanges && change.type == Change::DELETED) {
1978 // Fully instantiated font
1979 Font const font = getFont(bparams, i, outerfont);
1981 Font const last_font = running_font;
1983 // Do we need to close the previous font?
1985 (font != running_font ||
1986 font.language() != running_font.language()))
1988 column += running_font.latexWriteEndChanges(
1989 os, bparams, runparams, basefont,
1990 (i == body_pos-1) ? basefont : font);
1991 running_font = basefont;
1995 // close babel's font environment before opening CJK.
1996 if (!running_font.language()->babel().empty() &&
1997 font.language()->encoding()->package() == Encoding::CJK) {
1998 string end_tag = subst(lyxrc.language_command_end,
2000 running_font.language()->babel());
2001 os << from_ascii(end_tag);
2002 column += end_tag.length();
2005 // Switch file encoding if necessary (and allowed)
2006 if (!runparams.verbatim &&
2007 runparams.encoding->package() != Encoding::none &&
2008 font.language()->encoding()->package() != Encoding::none) {
2009 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2010 runparams, *(font.language()->encoding()));
2011 if (enc_switch.first) {
2012 column += enc_switch.second;
2013 runparams.encoding = font.language()->encoding();
2017 char_type const c = d->text_[i];
2019 // Do we need to change font?
2020 if ((font != running_font ||
2021 font.language() != running_font.language()) &&
2024 odocstringstream ods;
2025 column += font.latexWriteStartChanges(ods, bparams,
2026 runparams, basefont,
2028 running_font = font;
2030 docstring fontchange = ods.str();
2031 // check if the fontchange ends with a trailing blank
2032 // (like "\small " (see bug 3382)
2033 if (suffixIs(fontchange, ' ') && c == ' ')
2034 os << fontchange.substr(0, fontchange.size() - 1)
2035 << from_ascii("{}");
2041 // FIXME: integrate this case in latexSpecialChar
2042 // Do not print the separation of the optional argument
2043 // if style.pass_thru is false. This works because
2044 // latexSpecialChar ignores spaces if
2045 // style.pass_thru is false.
2046 if (i != body_pos - 1) {
2047 if (d->simpleTeXBlanks(
2048 runparams, os, texrow,
2049 i, column, font, style)) {
2050 // A surrogate pair was output. We
2051 // must not call latexSpecialChar
2052 // in this iteration, since it would output
2053 // the combining character again.
2060 OutputParams rp = runparams;
2061 rp.free_spacing = style.free_spacing;
2062 rp.local_font = &font;
2063 rp.intitle = style.intitle;
2065 // Two major modes: LaTeX or plain
2066 // Handle here those cases common to both modes
2067 // and then split to handle the two modes separately.
2068 if (c == META_INSET)
2069 d->latexInset(bparams, os,
2070 texrow, rp, running_font,
2071 basefont, outerfont, open_font,
2072 runningChange, style, i, column);
2075 d->latexSpecialChar(os, rp, running_font, runningChange,
2077 } catch (EncodingException & e) {
2078 if (runparams.dryrun) {
2079 os << "<" << _("LyX Warning: ")
2080 << _("uncodable character") << " '";
2084 // add location information and throw again.
2092 // Set the encoding to that returned from latexSpecialChar (see
2093 // comment for encoding member in OutputParams.h)
2094 runparams.encoding = rp.encoding;
2097 // If we have an open font definition, we have to close it
2099 #ifdef FIXED_LANGUAGE_END_DETECTION
2102 .latexWriteEndChanges(os, bparams, runparams,
2104 next_->getFont(bparams, 0, outerfont));
2106 running_font.latexWriteEndChanges(os, bparams,
2107 runparams, basefont, basefont);
2110 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2111 //FIXME: there as we start another \selectlanguage with the next paragraph if
2112 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2113 running_font.latexWriteEndChanges(os, bparams, runparams,
2114 basefont, basefont);
2118 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2120 // Needed if there is an optional argument but no contents.
2121 if (body_pos > 0 && body_pos == size()) {
2123 return_value = false;
2127 column += d->endTeXParParams(bparams, os, texrow,
2128 runparams.moving_arg);
2131 LYXERR(Debug::LATEX, "SimpleTeXOnePar...done " << this);
2132 return return_value;
2136 bool Paragraph::emptyTag() const
2138 for (pos_type i = 0; i < size(); ++i) {
2139 if (Inset const * inset = getInset(i)) {
2140 InsetCode lyx_code = inset->lyxCode();
2141 if (lyx_code != TOC_CODE &&
2142 lyx_code != INCLUDE_CODE &&
2143 lyx_code != GRAPHICS_CODE &&
2144 lyx_code != ERT_CODE &&
2145 lyx_code != LISTINGS_CODE &&
2146 lyx_code != FLOAT_CODE &&
2147 lyx_code != TABULAR_CODE) {
2151 char_type c = d->text_[i];
2152 if (c != ' ' && c != '\t')
2160 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2163 for (pos_type i = 0; i < size(); ++i) {
2164 if (Inset const * inset = getInset(i)) {
2165 InsetCode lyx_code = inset->lyxCode();
2166 if (lyx_code == LABEL_CODE) {
2167 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2168 docstring const & id = il->getParam("name");
2169 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2177 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2181 for (i = 0; i < size(); ++i) {
2182 if (Inset const * inset = getInset(i)) {
2183 inset->docbook(os, runparams);
2185 char_type c = d->text_[i];
2188 os << sgml::escapeChar(c);
2195 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2198 pos_type size = text_.size();
2199 for (pos_type i = initial; i < size; ++i) {
2200 Font font = owner_->getFont(buf.params(), i, outerfont);
2201 if (text_[i] == META_INSET)
2203 if (i != initial && font != font_old)
2212 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2214 OutputParams const & runparams,
2215 Font const & outerfont,
2216 pos_type initial) const
2218 bool emph_flag = false;
2220 Layout const & style = *d->layout_;
2222 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2224 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2227 // parsing main loop
2228 for (pos_type i = initial; i < size(); ++i) {
2229 Font font = getFont(buf.params(), i, outerfont);
2231 // handle <emphasis> tag
2232 if (font_old.emph() != font.fontInfo().emph()) {
2233 if (font.fontInfo().emph() == FONT_ON) {
2236 } else if (i != initial) {
2237 os << "</emphasis>";
2242 if (Inset const * inset = getInset(i)) {
2243 inset->docbook(os, runparams);
2245 char_type c = d->text_[i];
2247 if (style.pass_thru)
2250 os << sgml::escapeChar(c);
2252 font_old = font.fontInfo();
2256 os << "</emphasis>";
2259 if (style.free_spacing)
2261 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2266 bool Paragraph::isHfill(pos_type pos) const
2268 Inset const * inset = getInset(pos);
2269 return inset && (inset->lyxCode() == SPACE_CODE &&
2270 inset->isStretchableSpace());
2274 bool Paragraph::isNewline(pos_type pos) const
2276 Inset const * inset = getInset(pos);
2277 return inset && inset->lyxCode() == NEWLINE_CODE;
2281 bool Paragraph::isLineSeparator(pos_type pos) const
2283 char_type const c = d->text_[pos];
2284 if (isLineSeparatorChar(c))
2286 Inset const * inset = getInset(pos);
2287 return inset && inset->isLineSeparator();
2291 /// Used by the spellchecker
2292 bool Paragraph::isLetter(pos_type pos) const
2294 if (Inset const * inset = getInset(pos))
2295 return inset->isLetter();
2296 char_type const c = d->text_[pos];
2297 return isLetterChar(c) || isDigit(c);
2301 bool Paragraph::isChar(pos_type pos) const
2303 if (Inset const * inset = getInset(pos))
2304 return inset->isChar();
2305 char_type const c = d->text_[pos];
2306 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2310 bool Paragraph::isSpace(pos_type pos) const
2312 if (Inset const * inset = getInset(pos))
2313 return inset->isSpace();
2314 char_type const c = d->text_[pos];
2315 return lyx::isSpace(c);
2320 Paragraph::getParLanguage(BufferParams const & bparams) const
2323 return getFirstFontSettings(bparams).language();
2324 // FIXME: we should check the prev par as well (Lgb)
2325 return bparams.language;
2329 bool Paragraph::isRTL(BufferParams const & bparams) const
2331 return lyxrc.rtl_support
2332 && getParLanguage(bparams)->rightToLeft()
2333 && ownerCode() != ERT_CODE
2334 && ownerCode() != LISTINGS_CODE;
2338 void Paragraph::changeLanguage(BufferParams const & bparams,
2339 Language const * from, Language const * to)
2341 // change language including dummy font change at the end
2342 for (pos_type i = 0; i <= size(); ++i) {
2343 Font font = getFontSettings(bparams, i);
2344 if (font.language() == from) {
2345 font.setLanguage(to);
2352 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2354 Language const * doc_language = bparams.language;
2355 FontList::const_iterator cit = d->fontlist_.begin();
2356 FontList::const_iterator end = d->fontlist_.end();
2358 for (; cit != end; ++cit)
2359 if (cit->font().language() != ignore_language &&
2360 cit->font().language() != latex_language &&
2361 cit->font().language() != doc_language)
2367 docstring Paragraph::asString(int options) const
2369 return asString(0, size(), options);
2373 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2375 odocstringstream os;
2378 && options & AS_STR_LABEL
2379 && !d->params_.labelString().empty())
2380 os << d->params_.labelString() << ' ';
2382 for (pos_type i = beg; i < end; ++i) {
2383 char_type const c = d->text_[i];
2386 else if (c == META_INSET && options & AS_STR_INSETS)
2387 getInset(i)->textString(os);
2394 void Paragraph::setInsetOwner(Inset * inset)
2396 d->inset_owner_ = inset;
2400 int Paragraph::id() const
2406 Layout const & Paragraph::layout() const
2412 void Paragraph::setLayout(Layout const & layout)
2414 d->layout_ = &layout;
2418 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2420 if (usePlainLayout())
2421 setLayout(tclass.plainLayout());
2423 setLayout(tclass.defaultLayout());
2427 Inset * Paragraph::inInset() const
2429 return d->inset_owner_;
2433 InsetCode Paragraph::ownerCode() const
2435 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2439 ParagraphParameters & Paragraph::params()
2445 ParagraphParameters const & Paragraph::params() const
2451 bool Paragraph::isFreeSpacing() const
2453 if (d->layout_->free_spacing)
2455 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2459 bool Paragraph::allowEmpty() const
2461 if (d->layout_->keepempty)
2463 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2467 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2469 if (!Encodings::isArabicChar(c))
2472 char_type prev_char = ' ';
2473 char_type next_char = ' ';
2475 for (pos_type i = pos - 1; i >= 0; --i) {
2476 char_type const par_char = d->text_[i];
2477 if (!Encodings::isArabicComposeChar(par_char)) {
2478 prev_char = par_char;
2483 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2484 char_type const par_char = d->text_[i];
2485 if (!Encodings::isArabicComposeChar(par_char)) {
2486 next_char = par_char;
2491 if (Encodings::isArabicChar(next_char)) {
2492 if (Encodings::isArabicChar(prev_char) &&
2493 !Encodings::isArabicSpecialChar(prev_char))
2494 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2496 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2498 if (Encodings::isArabicChar(prev_char) &&
2499 !Encodings::isArabicSpecialChar(prev_char))
2500 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2502 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2507 int Paragraph::checkBiblio(Buffer const & buffer)
2510 // This is getting more and more a mess. ...We really should clean
2511 // up this bibitem issue for 1.6. See also bug 2743.
2513 // Add bibitem insets if necessary
2514 if (d->layout_->labeltype != LABEL_BIBLIO)
2517 bool hasbibitem = !d->insetlist_.empty()
2518 // Insist on it being in pos 0
2519 && d->text_[0] == META_INSET
2520 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2522 bool track_changes = buffer.params().trackChanges;
2527 // remove a bibitem in pos != 0
2528 // restore it later in pos 0 if necessary
2529 // (e.g. if a user inserts contents _before_ the item)
2530 // we're assuming there's only one of these, which there
2532 int erasedInsetPosition = -1;
2533 InsetList::iterator it = d->insetlist_.begin();
2534 InsetList::iterator end = d->insetlist_.end();
2535 for (; it != end; ++it)
2536 if (it->inset->lyxCode() == BIBITEM_CODE
2538 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2539 oldkey = olditem->getParam("key");
2540 oldlabel = olditem->getParam("label");
2541 erasedInsetPosition = it->pos;
2542 eraseChar(erasedInsetPosition, track_changes);
2546 // There was an InsetBibitem at the beginning, and we didn't
2547 // have to erase one.
2548 if (hasbibitem && erasedInsetPosition < 0)
2551 // There was an InsetBibitem at the beginning and we did have to
2552 // erase one. So we give its properties to the beginning inset.
2554 InsetBibitem * inset =
2555 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2556 if (!oldkey.empty())
2557 inset->setParam("key", oldkey);
2558 inset->setParam("label", oldlabel);
2559 return -erasedInsetPosition;
2562 // There was no inset at the beginning, so we need to create one with
2563 // the key and label of the one we erased.
2564 InsetBibitem * inset =
2565 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2566 // restore values of previously deleted item in this par.
2567 if (!oldkey.empty())
2568 inset->setParam("key", oldkey);
2569 inset->setParam("label", oldlabel);
2570 insertInset(0, static_cast<Inset *>(inset),
2571 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2577 void Paragraph::checkAuthors(AuthorList const & authorList)
2579 d->changes_.checkAuthors(authorList);
2583 bool Paragraph::isUnchanged(pos_type pos) const
2585 return lookupChange(pos).type == Change::UNCHANGED;
2589 bool Paragraph::isInserted(pos_type pos) const
2591 return lookupChange(pos).type == Change::INSERTED;
2595 bool Paragraph::isDeleted(pos_type pos) const
2597 return lookupChange(pos).type == Change::DELETED;
2601 InsetList const & Paragraph::insetList() const
2603 return d->insetlist_;
2607 void Paragraph::setBuffer(Buffer & b)
2609 d->insetlist_.setBuffer(b);
2613 Inset * Paragraph::releaseInset(pos_type pos)
2615 Inset * inset = d->insetlist_.release(pos);
2616 /// does not honour change tracking!
2617 eraseChar(pos, false);
2622 Inset * Paragraph::getInset(pos_type pos)
2624 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2625 ? d->insetlist_.get(pos) : 0;
2629 Inset const * Paragraph::getInset(pos_type pos) const
2631 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2632 ? d->insetlist_.get(pos) : 0;
2636 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2637 pos_type & right, TextCase action)
2639 // process sequences of modified characters; in change
2640 // tracking mode, this approach results in much better
2641 // usability than changing case on a char-by-char basis
2644 bool const trackChanges = bparams.trackChanges;
2646 bool capitalize = true;
2648 for (; pos < right; ++pos) {
2649 char_type oldChar = d->text_[pos];
2650 char_type newChar = oldChar;
2652 // ignore insets and don't play with deleted text!
2653 if (oldChar != META_INSET && !isDeleted(pos)) {
2655 case text_lowercase:
2656 newChar = lowercase(oldChar);
2658 case text_capitalization:
2660 newChar = uppercase(oldChar);
2664 case text_uppercase:
2665 newChar = uppercase(oldChar);
2670 if (!isLetter(pos) || isDeleted(pos)) {
2671 // permit capitalization again
2675 if (oldChar != newChar)
2678 if (oldChar == newChar || pos == right - 1) {
2679 if (oldChar != newChar) {
2680 // step behind the changing area
2683 int erasePos = pos - changes.size();
2684 for (size_t i = 0; i < changes.size(); i++) {
2685 insertChar(pos, changes[i],
2686 getFontSettings(bparams,
2689 if (!eraseChar(erasePos, trackChanges)) {
2692 ++right; // expand selection
2701 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2702 pos_type pos, bool del) const
2704 int const strsize = str.length();
2706 pos_type const parsize = d->text_.size();
2707 for (i = 0; pos + i < parsize; ++i) {
2710 if (cs && str[i] != d->text_[pos + i])
2712 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2714 if (!del && isDeleted(pos + i))
2721 // if necessary, check whether string matches word
2723 if (pos > 0 && isLetter(pos - 1))
2725 if (pos + strsize < parsize
2726 && isLetter(pos + strsize))
2734 char_type Paragraph::getChar(pos_type pos) const
2736 return d->text_[pos];
2740 pos_type Paragraph::size() const
2742 return d->text_.size();
2746 bool Paragraph::empty() const
2748 return d->text_.empty();
2752 bool Paragraph::isInset(pos_type pos) const
2754 return d->text_[pos] == META_INSET;
2758 bool Paragraph::isSeparator(pos_type pos) const
2760 //FIXME: Are we sure this can be the only separator?
2761 return d->text_[pos] == ' ';
2765 void Paragraph::deregisterWords()
2767 Private::Words::const_iterator it;
2768 WordList & wl = theWordList();
2769 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2775 void Paragraph::collectWords(CursorSlice const & sl)
2778 bool inword = false;
2780 //lyxerr << "Words: ";
2781 pos_type n = size();
2782 for (pos_type pos = 0; pos != n; ++pos) {
2786 if (!isLetter(pos)) {
2795 CursorSlice from = sl;
2796 CursorSlice to = sl;
2799 from.text()->getWord(from, to, WHOLE_WORD);
2800 if (to.pos() - from.pos() < 6)
2802 docstring word = asString(from.pos(), to.pos(), false);
2803 d->words_.insert(word);
2804 //lyxerr << word << " ";
2806 //lyxerr << std::endl;
2810 void Paragraph::registerWords()
2812 Private::Words::const_iterator it;
2813 WordList & wl = theWordList();
2814 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2819 void Paragraph::updateWords(CursorSlice const & sl)
2821 LASSERT(&sl.paragraph() == this, /**/);