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"
40 #include "SpellChecker.h"
42 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
54 #include "support/lassert.h"
55 #include "support/debug.h"
56 #include "support/ExceptionMessage.h"
57 #include "support/gettext.h"
58 #include "support/lstrings.h"
59 #include "support/Messages.h"
60 #include "support/textutils.h"
66 using namespace lyx::support;
71 /// Inset identifier (above 0x10ffff, for ucs-4)
72 char_type const META_INSET = 0x200001;
75 /////////////////////////////////////////////////////////////////////
79 /////////////////////////////////////////////////////////////////////
81 class Paragraph::Private
85 Private(Paragraph * owner, Layout const & layout);
86 /// "Copy constructor"
87 Private(Private const &, Paragraph * owner);
88 /// Copy constructor from \p beg to \p end
89 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
92 void insertChar(pos_type pos, char_type c, Change const & change);
94 /// Output the surrogate pair formed by \p c and \p next to \p os.
95 /// \return the number of characters written.
96 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
99 /// Output a space in appropriate formatting (or a surrogate pair
100 /// if the next character is a combining character).
101 /// \return whether a surrogate pair was output.
102 bool simpleTeXBlanks(OutputParams const &,
103 odocstream &, TexRow & texrow,
105 unsigned int & column,
107 Layout const & style);
109 /// Output consecutive unicode chars, belonging to the same script as
110 /// specified by the latex macro \p ltx, to \p os starting from \p i.
111 /// \return the number of characters written.
112 int writeScriptChars(odocstream & os, docstring const & ltx,
113 Change const &, Encoding const &, pos_type & i);
115 /// This could go to ParagraphParameters if we want to.
116 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
117 OutputParams const &) const;
119 /// This could go to ParagraphParameters if we want to.
120 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
121 OutputParams const &) const;
124 void latexInset(BufferParams const &,
126 TexRow & texrow, OutputParams &,
129 Font const & outerfont,
131 Change & running_change,
132 Layout const & style,
134 unsigned int & column);
137 void latexSpecialChar(
139 OutputParams const & runparams,
140 Font const & running_font,
141 Change const & running_change,
142 Layout const & style,
144 unsigned int & column);
151 unsigned int & column);
153 bool latexSpecialTypewriter(
157 unsigned int & column);
159 bool latexSpecialPhrase(
162 unsigned int & column,
163 OutputParams const & runparams);
166 void validate(LaTeXFeatures & features,
167 Layout const & layout) const;
169 /// Checks if the paragraph contains only text and no inset or font change.
170 bool onlyText(Buffer const & buf, Font const & outerfont,
171 pos_type initial) const;
173 /// match a string against a particular point in the paragraph
174 bool isTextAt(string const & str, pos_type pos) const;
176 /// Which Paragraph owns us?
180 Inset const * inset_owner_;
188 static unsigned int paragraph_id;
190 ParagraphParameters params_;
192 /// for recording and looking up changes
196 InsetList insetlist_;
199 pos_type begin_of_body_;
201 typedef docstring TextContainer;
205 typedef std::set<docstring> Words;
209 Layout const * layout_;
213 // Initialization of the counter for the paragraph id's,
214 unsigned int Paragraph::Private::paragraph_id = 0;
218 struct special_phrase {
224 special_phrase const special_phrases[] = {
225 { "LyX", from_ascii("\\LyX{}"), false },
226 { "TeX", from_ascii("\\TeX{}"), true },
227 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
228 { "LaTeX", from_ascii("\\LaTeX{}"), true },
231 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
236 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
237 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
239 id_ = paragraph_id++;
244 Paragraph::Private::Private(Private const & p, Paragraph * owner)
245 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
246 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
247 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
250 id_ = paragraph_id++;
254 Paragraph::Private::Private(Private const & p, Paragraph * owner,
255 pos_type beg, pos_type end)
256 : owner_(owner), inset_owner_(p.inset_owner_),
257 params_(p.params_), changes_(p.changes_),
258 insetlist_(p.insetlist_, beg, end),
259 begin_of_body_(p.begin_of_body_), words_(p.words_),
262 id_ = paragraph_id++;
263 if (beg >= pos_type(p.text_.size()))
265 text_ = p.text_.substr(beg, end - beg);
267 FontList::const_iterator fcit = fontlist_.begin();
268 FontList::const_iterator fend = fontlist_.end();
269 for (; fcit != fend; ++fcit) {
270 if (fcit->pos() < beg)
272 if (fcit->pos() >= end) {
273 // Add last entry in the fontlist_.
274 fontlist_.set(text_.size() - 1, fcit->font());
277 // Add a new entry in the fontlist_.
278 fontlist_.set(fcit->pos() - beg, fcit->font());
283 void Paragraph::addChangesToToc(DocIterator const & cdit,
284 Buffer const & buf) const
286 d->changes_.addToToc(cdit, buf);
290 bool Paragraph::isFullyDeleted(pos_type start, pos_type end) const
292 LASSERT(start >= 0 && start <= size(), /**/);
293 LASSERT(end > start && end <= size() + 1, /**/);
295 return d->changes_.isFullyDeleted(start, end);
299 bool Paragraph::isChanged(pos_type start, pos_type end) const
301 LASSERT(start >= 0 && start <= size(), /**/);
302 LASSERT(end > start && end <= size() + 1, /**/);
304 return d->changes_.isChanged(start, end);
308 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
310 // keep the logic here in sync with the logic of eraseChars()
314 Change const change = d->changes_.lookup(size());
315 return change.type == Change::INSERTED && change.author == 0;
319 void Paragraph::setChange(Change const & change)
321 // beware of the imaginary end-of-par character!
322 d->changes_.set(change, 0, size() + 1);
325 * Propagate the change recursively - but not in case of DELETED!
327 * Imagine that your co-author makes changes in an existing inset. He
328 * sends your document to you and you come to the conclusion that the
329 * inset should go completely. If you erase it, LyX must not delete all
330 * text within the inset. Otherwise, the change tracked insertions of
331 * your co-author get lost and there is no way to restore them later.
333 * Conclusion: An inset's content should remain untouched if you delete it
336 if (change.type != Change::DELETED) {
337 for (pos_type pos = 0; pos < size(); ++pos) {
338 if (Inset * inset = getInset(pos))
339 inset->setChange(change);
345 void Paragraph::setChange(pos_type pos, Change const & change)
347 LASSERT(pos >= 0 && pos <= size(), /**/);
348 d->changes_.set(change, pos);
350 // see comment in setChange(Change const &) above
351 if (change.type != Change::DELETED && pos < size())
352 if (Inset * inset = getInset(pos))
353 inset->setChange(change);
357 Change const & Paragraph::lookupChange(pos_type pos) const
359 LASSERT(pos >= 0 && pos <= size(), /**/);
360 return d->changes_.lookup(pos);
364 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
367 LASSERT(start >= 0 && start <= size(), /**/);
368 LASSERT(end > start && end <= size() + 1, /**/);
370 for (pos_type pos = start; pos < end; ++pos) {
371 switch (lookupChange(pos).type) {
372 case Change::UNCHANGED:
373 // accept changes in nested inset
374 if (Inset * inset = getInset(pos))
375 inset->acceptChanges(bparams);
378 case Change::INSERTED:
379 d->changes_.set(Change(Change::UNCHANGED), pos);
380 // also accept changes in nested inset
381 if (Inset * inset = getInset(pos))
382 inset->acceptChanges(bparams);
385 case Change::DELETED:
386 // Suppress access to non-existent
387 // "end-of-paragraph char"
389 eraseChar(pos, false);
400 void Paragraph::rejectChanges(BufferParams const & bparams,
401 pos_type start, pos_type end)
403 LASSERT(start >= 0 && start <= size(), /**/);
404 LASSERT(end > start && end <= size() + 1, /**/);
406 for (pos_type pos = start; pos < end; ++pos) {
407 switch (lookupChange(pos).type) {
408 case Change::UNCHANGED:
409 // reject changes in nested inset
410 if (Inset * inset = getInset(pos))
411 inset->rejectChanges(bparams);
414 case Change::INSERTED:
415 // Suppress access to non-existent
416 // "end-of-paragraph char"
418 eraseChar(pos, false);
424 case Change::DELETED:
425 d->changes_.set(Change(Change::UNCHANGED), pos);
427 // Do NOT reject changes within a deleted inset!
428 // There may be insertions of a co-author inside of it!
436 void Paragraph::Private::insertChar(pos_type pos, char_type c,
437 Change const & change)
439 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
442 changes_.insert(change, pos);
444 // This is actually very common when parsing buffers (and
445 // maybe inserting ascii text)
446 if (pos == pos_type(text_.size())) {
447 // when appending characters, no need to update tables
452 text_.insert(text_.begin() + pos, c);
454 // Update the font table.
455 fontlist_.increasePosAfterPos(pos);
458 insetlist_.increasePosAfterPos(pos);
462 bool Paragraph::insertInset(pos_type pos, Inset * inset,
463 Change const & change)
465 LASSERT(inset, /**/);
466 LASSERT(pos >= 0 && pos <= size(), /**/);
468 // Paragraph::insertInset() can be used in cut/copy/paste operation where
469 // d->inset_owner_ is not set yet.
470 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
473 d->insertChar(pos, META_INSET, change);
474 LASSERT(d->text_[pos] == META_INSET, /**/);
476 // Add a new entry in the insetlist_.
477 d->insetlist_.insert(inset, pos);
482 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
484 LASSERT(pos >= 0 && pos <= size(), return false);
486 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
489 Change change = d->changes_.lookup(pos);
491 // set the character to DELETED if
492 // a) it was previously unchanged or
493 // b) it was inserted by a co-author
495 if (change.type == Change::UNCHANGED ||
496 (change.type == Change::INSERTED && change.author != 0)) {
497 setChange(pos, Change(Change::DELETED));
501 if (change.type == Change::DELETED)
505 // Don't physically access the imaginary end-of-paragraph character.
506 // eraseChar() can only mark it as DELETED. A physical deletion of
507 // end-of-par must be handled externally.
513 d->changes_.erase(pos);
515 // if it is an inset, delete the inset entry
516 if (d->text_[pos] == META_INSET)
517 d->insetlist_.erase(pos);
519 d->text_.erase(d->text_.begin() + pos);
521 // Update the fontlist_
522 d->fontlist_.erase(pos);
524 // Update the insetlist_
525 d->insetlist_.decreasePosAfterPos(pos);
531 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
533 LASSERT(start >= 0 && start <= size(), /**/);
534 LASSERT(end >= start && end <= size() + 1, /**/);
537 for (pos_type count = end - start; count; --count) {
538 if (!eraseChar(i, trackChanges))
545 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
546 char_type next, Encoding const & encoding)
548 // Writing next here may circumvent a possible font change between
549 // c and next. Since next is only output if it forms a surrogate pair
550 // with c we can ignore this:
551 // A font change inside a surrogate pair does not make sense and is
552 // hopefully impossible to input.
553 // FIXME: change tracking
554 // Is this correct WRT change tracking?
555 docstring const latex1 = encoding.latexChar(next);
556 docstring const latex2 = encoding.latexChar(c);
557 if (docstring(1, next) == latex1) {
558 // the encoding supports the combination
559 os << latex2 << latex1;
560 return latex1.length() + latex2.length();
562 os << latex1 << '{' << latex2 << '}';
563 return latex1.length() + latex2.length() + 2;
567 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
568 odocstream & os, TexRow & texrow,
570 unsigned int & column,
572 Layout const & style)
574 if (style.pass_thru || runparams.verbatim)
577 if (i + 1 < int(text_.size())) {
578 char_type next = text_[i + 1];
579 if (Encodings::isCombiningChar(next)) {
580 Encoding const & encoding = *(runparams.encoding);
581 // This space has an accent, so we must always output it.
582 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
587 if (lyxrc.plaintext_linelen > 0
588 && column > lyxrc.plaintext_linelen
590 && text_[i - 1] != ' '
591 && (i + 1 < int(text_.size()))
592 // same in FreeSpacing mode
593 && !owner_->isFreeSpacing()
594 // In typewriter mode, we want to avoid
595 // ! . ? : at the end of a line
596 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
597 && (text_[i - 1] == '.'
598 || text_[i - 1] == '?'
599 || text_[i - 1] == ':'
600 || text_[i - 1] == '!'))) {
603 texrow.start(owner_->id(), i + 1);
605 } else if (style.free_spacing) {
614 int Paragraph::Private::writeScriptChars(odocstream & os,
615 docstring const & ltx,
616 Change const & runningChange,
617 Encoding const & encoding,
620 // FIXME: modifying i here is not very nice...
622 // We only arrive here when a proper language for character text_[i] has
623 // not been specified (i.e., it could not be translated in the current
624 // latex encoding) or its latex translation has been forced, and it
625 // belongs to a known script.
626 // Parameter ltx contains the latex translation of text_[i] as specified
627 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
628 // The latex macro name "textXXX" specifies the script to which text_[i]
629 // belongs and we use it in order to check whether characters from the
630 // same script immediately follow, such that we can collect them in a
631 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
632 // for the first char but only "<spec>" for all subsequent chars.
633 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
634 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
635 string script = to_ascii(ltx.substr(1, brace1 - 1));
638 bool closing_brace = true;
639 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
640 // Correct encoding is being used, so we can avoid \textgreek.
643 closing_brace = false;
645 os << ltx.substr(pos, length);
646 int size = text_.size();
647 while (i + 1 < size) {
648 char_type const next = text_[i + 1];
649 // Stop here if next character belongs to another script
650 // or there is a change in change tracking status.
651 if (!Encodings::isKnownScriptChar(next, script) ||
652 runningChange != owner_->lookupChange(i + 1))
656 FontList::const_iterator cit = fontlist_.begin();
657 FontList::const_iterator end = fontlist_.end();
658 for (; cit != end; ++cit) {
659 if (cit->pos() >= i && !found) {
660 prev_font = cit->font();
663 if (cit->pos() >= i + 1)
666 // Stop here if there is a font attribute or encoding change.
667 if (found && cit != end && prev_font != cit->font())
669 docstring const latex = encoding.latexChar(next);
670 docstring::size_type const b1 =
671 latex.find_first_of(from_ascii("{"));
672 docstring::size_type const b2 =
673 latex.find_last_of(from_ascii("}"));
674 int const len = b2 - b1 - 1;
675 os << latex.substr(b1 + 1, len);
687 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
689 pos_type const len = str.length();
691 // is the paragraph large enough?
692 if (pos + len > int(text_.size()))
695 // does the wanted text start at point?
696 for (string::size_type i = 0; i < str.length(); ++i) {
697 // Caution: direct comparison of characters works only
698 // because str is pure ASCII.
699 if (str[i] != text_[pos + i])
703 return fontlist_.hasChangeInRange(pos, len);
707 void Paragraph::Private::latexInset(
708 BufferParams const & bparams,
711 OutputParams & runparams,
714 Font const & outerfont,
716 Change & running_change,
717 Layout const & style,
719 unsigned int & column)
721 Inset * inset = owner_->getInset(i);
722 LASSERT(inset, /**/);
724 if (style.pass_thru) {
725 inset->plaintext(os, runparams);
729 // FIXME: move this to InsetNewline::latex
730 if (inset->lyxCode() == NEWLINE_CODE) {
731 // newlines are handled differently here than
732 // the default in simpleTeXSpecialChars().
733 if (!style.newline_allowed) {
737 column += running_font.latexWriteEndChanges(
738 os, bparams, runparams,
743 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
746 basefont = owner_->getLayoutFont(bparams, outerfont);
747 running_font = basefont;
749 if (runparams.moving_arg)
754 texrow.start(owner_->id(), i + 1);
758 if (owner_->lookupChange(i).type == Change::DELETED) {
759 if( ++runparams.inDeletedInset == 1)
760 runparams.changeOfDeletedInset = owner_->lookupChange(i);
763 if (inset->canTrackChanges()) {
764 column += Changes::latexMarkChange(os, bparams, running_change,
765 Change(Change::UNCHANGED));
766 running_change = Change(Change::UNCHANGED);
770 odocstream::pos_type const len = os.tellp();
772 if (inset->forceLTR()
773 && running_font.isRightToLeft()
774 // ERT is an exception, it should be output with no decorations at all
775 && inset->lyxCode() != ERT_CODE) {
776 if (running_font.language()->lang() == "farsi")
783 // FIXME: Bug: we can have an empty font change here!
784 // if there has just been a font change, we are going to close it
785 // right now, which means stupid latex code like \textsf{}. AFAIK,
786 // this does not harm dvi output. A minor bug, thus (JMarc)
788 // Some insets cannot be inside a font change command.
789 // However, even such insets *can* be placed in \L or \R
790 // or their equivalents (for RTL language switches), so we don't
791 // close the language in those cases.
792 // ArabTeX, though, cannot handle this special behavior, it seems.
793 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
794 || running_font.language()->lang() == "arabic_arabtex";
795 if (open_font && inset->noFontChange()) {
796 bool closeLanguage = arabtex
797 || basefont.isRightToLeft() == running_font.isRightToLeft();
798 unsigned int count = running_font.latexWriteEndChanges(os,
799 bparams, runparams, basefont, basefont, closeLanguage);
801 // if any font properties were closed, update the running_font,
802 // making sure, however, to leave the language as it was
804 // FIXME: probably a better way to keep track of the old
805 // language, than copying the entire font?
806 Font const copy_font(running_font);
807 basefont = owner_->getLayoutFont(bparams, outerfont);
808 running_font = basefont;
810 running_font.setLanguage(copy_font.language());
811 // leave font open if language is still open
812 open_font = (running_font.language() == basefont.language());
814 runparams.local_font = &basefont;
821 tmp = inset->latex(os, runparams);
822 } catch (EncodingException & e) {
823 // add location information and throw again.
830 if (running_font.language()->lang() == "farsi")
837 for (int j = 0; j < tmp; ++j)
840 texrow.start(owner_->id(), i + 1);
843 column += os.tellp() - len;
846 if (owner_->lookupChange(i).type == Change::DELETED)
847 --runparams.inDeletedInset;
851 void Paragraph::Private::latexSpecialChar(
853 OutputParams const & runparams,
854 Font const & running_font,
855 Change const & running_change,
856 Layout const & style,
858 unsigned int & column)
860 char_type const c = text_[i];
862 if (style.pass_thru) {
864 // FIXME UNICODE: This can fail if c cannot
865 // be encoded in the current encoding.
870 if (runparams.verbatim) {
871 // FIXME UNICODE: This can fail if c cannot
872 // be encoded in the current encoding.
877 // If T1 font encoding is used, use the special
878 // characters it provides.
879 // NOTE: some languages reset the font encoding
881 if (!running_font.language()->internalFontEncoding()
882 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
885 // \tt font needs special treatment
886 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
887 && latexSpecialTypewriter(c, os, i, column))
890 // Otherwise, we use what LaTeX provides us.
893 os << "\\textbackslash{}";
897 os << "\\textless{}";
901 os << "\\textgreater{}";
912 os << "\\char`\\\"{}";
917 case '%': case '#': case '{':
925 os << "\\textasciitilde{}";
930 os << "\\textasciicircum{}";
937 // avoid being mistaken for optional arguments
945 // Blanks are printed before font switching.
946 // Sure? I am not! (try nice-latex)
947 // I am sure it's correct. LyX might be smarter
948 // in the future, but for now, nothing wrong is
954 if (latexSpecialPhrase(os, i, column, runparams))
960 Encoding const & encoding = *(runparams.encoding);
961 if (i + 1 < int(text_.size())) {
962 char_type next = text_[i + 1];
963 if (Encodings::isCombiningChar(next)) {
964 column += latexSurrogatePair(os, c, next, encoding) - 1;
970 docstring const latex = encoding.latexChar(c);
971 if (Encodings::isKnownScriptChar(c, script)
972 && prefixIs(latex, from_ascii("\\" + script)))
973 column += writeScriptChars(os, latex,
974 running_change, encoding, i) - 1;
975 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
976 // Prevent eating of a following
977 // space or command corruption by
978 // following characters
979 column += latex.length() + 1;
982 column += latex.length() - 1;
990 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
991 pos_type i, unsigned int & column)
997 // In T1 encoding, these characters exist
998 // but we should avoid ligatures
999 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1001 os << "\\textcompwordmark{}";
1008 // soul.sty breaks with \char`\"
1009 os << "\\textquotedbl{}";
1018 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1019 pos_type i, unsigned int & column)
1023 // within \ttfamily, "--" is merged to "-" (no endash)
1024 // so we avoid this rather irritating ligature
1025 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1032 // everything else has to be checked separately
1033 // (depending on the encoding)
1040 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1041 unsigned int & column, OutputParams const & runparams)
1043 // FIXME: if we have "LaTeX" with a font
1044 // change in the middle (before the 'T', then
1045 // the "TeX" part is still special cased.
1046 // Really we should only operate this on
1047 // "words" for some definition of word
1049 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1050 if (!isTextAt(special_phrases[pnr].phrase, i))
1052 if (runparams.moving_arg)
1054 os << special_phrases[pnr].macro;
1055 i += special_phrases[pnr].phrase.length() - 1;
1056 column += special_phrases[pnr].macro.length() - 1;
1063 void Paragraph::Private::validate(LaTeXFeatures & features,
1064 Layout const & layout) const
1066 // check the params.
1067 if (!params_.spacing().isDefault())
1068 features.require("setspace");
1071 features.useLayout(layout.name());
1074 fontlist_.validate(features);
1076 // then the indentation
1077 if (!params_.leftIndent().zero())
1078 features.require("ParagraphLeftIndent");
1081 InsetList::const_iterator icit = insetlist_.begin();
1082 InsetList::const_iterator iend = insetlist_.end();
1083 for (; icit != iend; ++icit) {
1085 icit->inset->validate(features);
1086 if (layout.needprotect &&
1087 icit->inset->lyxCode() == FOOT_CODE)
1088 features.require("NeedLyXFootnoteCode");
1092 // then the contents
1093 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1094 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1095 if (!special_phrases[pnr].builtin
1096 && isTextAt(special_phrases[pnr].phrase, i)) {
1097 features.require(special_phrases[pnr].phrase);
1101 Encodings::validate(text_[i], features);
1105 /////////////////////////////////////////////////////////////////////
1109 /////////////////////////////////////////////////////////////////////
1112 Layout const emptyParagraphLayout;
1115 Paragraph::Paragraph()
1116 : d(new Paragraph::Private(this, emptyParagraphLayout))
1123 Paragraph::Paragraph(Paragraph const & par)
1124 : itemdepth(par.itemdepth),
1125 d(new Paragraph::Private(*par.d, this))
1131 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1132 : itemdepth(par.itemdepth),
1133 d(new Paragraph::Private(*par.d, this, beg, end))
1139 Paragraph & Paragraph::operator=(Paragraph const & par)
1141 // needed as we will destroy the private part before copying it
1143 itemdepth = par.itemdepth;
1147 d = new Private(*par.d, this);
1154 Paragraph::~Paragraph()
1161 void Paragraph::write(ostream & os, BufferParams const & bparams,
1162 depth_type & dth) const
1164 // The beginning or end of a deeper (i.e. nested) area?
1165 if (dth != d->params_.depth()) {
1166 if (d->params_.depth() > dth) {
1167 while (d->params_.depth() > dth) {
1168 os << "\n\\begin_deeper";
1172 while (d->params_.depth() < dth) {
1173 os << "\n\\end_deeper";
1179 // First write the layout
1180 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1182 d->params_.write(os);
1184 Font font1(inherit_font, bparams.language);
1186 Change running_change = Change(Change::UNCHANGED);
1189 for (pos_type i = 0; i <= size(); ++i) {
1191 Change change = lookupChange(i);
1192 Changes::lyxMarkChange(os, column, running_change, change);
1193 running_change = change;
1198 // Write font changes
1199 Font const & font2 = getFontSettings(bparams, i);
1200 if (font2 != font1) {
1201 font2.lyxWriteChanges(font1, os);
1206 char_type const c = d->text_[i];
1209 if (Inset const * inset = getInset(i)) {
1210 if (inset->directWrite()) {
1211 // international char, let it write
1212 // code directly so it's shorter in
1218 os << "\\begin_inset ";
1220 os << "\n\\end_inset\n\n";
1226 os << "\n\\backslash\n";
1230 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1237 if ((column > 70 && c == ' ')
1242 // this check is to amend a bug. LyX sometimes
1243 // inserts '\0' this could cause problems.
1245 os << to_utf8(docstring(1, c));
1247 LYXERR0("NUL char in structure.");
1253 os << "\n\\end_layout\n";
1257 void Paragraph::validate(LaTeXFeatures & features) const
1259 d->validate(features, *d->layout_);
1263 void Paragraph::insert(pos_type start, docstring const & str,
1264 Font const & font, Change const & change)
1266 for (size_t i = 0, n = str.size(); i != n ; ++i)
1267 insertChar(start + i, str[i], font, change);
1271 void Paragraph::appendChar(char_type c, Font const & font,
1272 Change const & change)
1275 d->changes_.insert(change, d->text_.size());
1276 // when appending characters, no need to update tables
1277 d->text_.push_back(c);
1278 setFont(d->text_.size() - 1, font);
1282 void Paragraph::appendString(docstring const & s, Font const & font,
1283 Change const & change)
1285 pos_type end = s.size();
1286 size_t oldsize = d->text_.size();
1287 size_t newsize = oldsize + end;
1288 size_t capacity = d->text_.capacity();
1289 if (newsize >= capacity)
1290 d->text_.reserve(max(capacity + 100, newsize));
1292 // when appending characters, no need to update tables
1295 // FIXME: Optimize this!
1296 for (size_t i = oldsize; i != newsize; ++i) {
1298 d->changes_.insert(change, i);
1300 d->fontlist_.set(oldsize, font);
1301 d->fontlist_.set(newsize - 1, font);
1305 void Paragraph::insertChar(pos_type pos, char_type c,
1308 d->insertChar(pos, c, Change(trackChanges ?
1309 Change::INSERTED : Change::UNCHANGED));
1313 void Paragraph::insertChar(pos_type pos, char_type c,
1314 Font const & font, bool trackChanges)
1316 d->insertChar(pos, c, Change(trackChanges ?
1317 Change::INSERTED : Change::UNCHANGED));
1322 void Paragraph::insertChar(pos_type pos, char_type c,
1323 Font const & font, Change const & change)
1325 d->insertChar(pos, c, change);
1330 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1331 Font const & font, Change const & change)
1333 bool const success = insertInset(pos, inset, change);
1334 // Set the font/language of the inset...
1340 void Paragraph::resetFonts(Font const & font)
1342 d->fontlist_.clear();
1343 d->fontlist_.set(0, font);
1344 d->fontlist_.set(d->text_.size() - 1, font);
1347 // Gets uninstantiated font setting at position.
1348 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1352 LYXERR0("pos: " << pos << " size: " << size());
1353 LASSERT(pos <= size(), /**/);
1356 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1357 if (cit != d->fontlist_.end())
1360 if (pos == size() && !empty())
1361 return getFontSettings(bparams, pos - 1);
1363 // Optimisation: avoid a full font instantiation if there is no
1364 // language change from previous call.
1365 static Font previous_font;
1366 static Language const * previous_lang = 0;
1367 Language const * lang = getParLanguage(bparams);
1368 if (lang != previous_lang) {
1369 previous_lang = lang;
1370 previous_font = Font(inherit_font, lang);
1372 return previous_font;
1376 FontSpan Paragraph::fontSpan(pos_type pos) const
1378 LASSERT(pos <= size(), /**/);
1381 FontList::const_iterator cit = d->fontlist_.begin();
1382 FontList::const_iterator end = d->fontlist_.end();
1383 for (; cit != end; ++cit) {
1384 if (cit->pos() >= pos) {
1385 if (pos >= beginOfBody())
1386 return FontSpan(max(start, beginOfBody()),
1389 return FontSpan(start,
1390 min(beginOfBody() - 1,
1393 start = cit->pos() + 1;
1396 // This should not happen, but if so, we take no chances.
1397 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1398 return FontSpan(pos, pos);
1402 // Gets uninstantiated font setting at position 0
1403 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1405 if (!empty() && !d->fontlist_.empty())
1406 return d->fontlist_.begin()->font();
1408 // Optimisation: avoid a full font instantiation if there is no
1409 // language change from previous call.
1410 static Font previous_font;
1411 static Language const * previous_lang = 0;
1412 if (bparams.language != previous_lang) {
1413 previous_lang = bparams.language;
1414 previous_font = Font(inherit_font, bparams.language);
1417 return previous_font;
1421 // Gets the fully instantiated font at a given position in a paragraph
1422 // This is basically the same function as Text::GetFont() in text2.cpp.
1423 // The difference is that this one is used for generating the LaTeX file,
1424 // and thus cosmetic "improvements" are disallowed: This has to deliver
1425 // the true picture of the buffer. (Asger)
1426 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1427 Font const & outerfont) const
1429 LASSERT(pos >= 0, /**/);
1431 Font font = getFontSettings(bparams, pos);
1433 pos_type const body_pos = beginOfBody();
1434 FontInfo & fi = font.fontInfo();
1436 fi.realize(d->layout_->labelfont);
1438 fi.realize(d->layout_->font);
1440 fi.realize(outerfont.fontInfo());
1441 fi.realize(bparams.getFont().fontInfo());
1447 Font const Paragraph::getLabelFont
1448 (BufferParams const & bparams, Font const & outerfont) const
1450 FontInfo tmpfont = d->layout_->labelfont;
1451 tmpfont.realize(outerfont.fontInfo());
1452 tmpfont.realize(bparams.getFont().fontInfo());
1453 return Font(tmpfont, getParLanguage(bparams));
1457 Font const Paragraph::getLayoutFont
1458 (BufferParams const & bparams, Font const & outerfont) const
1460 FontInfo tmpfont = d->layout_->font;
1461 tmpfont.realize(outerfont.fontInfo());
1462 tmpfont.realize(bparams.getFont().fontInfo());
1463 return Font(tmpfont, getParLanguage(bparams));
1467 /// Returns the height of the highest font in range
1468 FontSize Paragraph::highestFontInRange
1469 (pos_type startpos, pos_type endpos, FontSize def_size) const
1471 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1475 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1477 char_type c = d->text_[pos];
1478 if (!lyxrc.rtl_support)
1508 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1514 void Paragraph::setFont(pos_type pos, Font const & font)
1516 LASSERT(pos <= size(), /**/);
1518 // First, reduce font against layout/label font
1519 // Update: The setCharFont() routine in text2.cpp already
1520 // reduces font, so we don't need to do that here. (Asger)
1522 d->fontlist_.set(pos, font);
1526 void Paragraph::makeSameLayout(Paragraph const & par)
1528 d->layout_ = par.d->layout_;
1529 d->params_ = par.d->params_;
1533 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1535 if (isFreeSpacing())
1541 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1542 if (eraseChar(pos, trackChanges))
1548 return count > 0 || pos > 0;
1552 bool Paragraph::hasSameLayout(Paragraph const & par) const
1554 return par.d->layout_ == d->layout_
1555 && d->params_.sameLayout(par.d->params_);
1559 depth_type Paragraph::getDepth() const
1561 return d->params_.depth();
1565 depth_type Paragraph::getMaxDepthAfter() const
1567 if (d->layout_->isEnvironment())
1568 return d->params_.depth() + 1;
1570 return d->params_.depth();
1574 char Paragraph::getAlign() const
1576 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1577 return d->layout_->align;
1579 return d->params_.align();
1583 docstring const & Paragraph::labelString() const
1585 return d->params_.labelString();
1589 // the next two functions are for the manual labels
1590 docstring const Paragraph::getLabelWidthString() const
1592 if (d->layout_->margintype == MARGIN_MANUAL)
1593 return d->params_.labelWidthString();
1595 return _("Senseless with this layout!");
1599 void Paragraph::setLabelWidthString(docstring const & s)
1601 d->params_.labelWidthString(s);
1605 docstring const Paragraph::translateIfPossible(docstring const & s,
1606 BufferParams const & bparams) const
1608 if (!isAscii(s) || s.empty()) {
1609 // This must be a user defined layout. We cannot translate
1610 // this, since gettext accepts only ascii keys.
1613 // Probably standard layout, try to translate
1614 Messages & m = getMessages(getParLanguage(bparams)->code());
1615 return m.get(to_ascii(s));
1619 docstring Paragraph::expandLabel(Layout const & layout,
1620 BufferParams const & bparams, bool process_appendix) const
1622 DocumentClass const & tclass = bparams.documentClass();
1625 if (process_appendix && d->params_.appendix())
1626 fmt = translateIfPossible(layout.labelstring_appendix(),
1629 fmt = translateIfPossible(layout.labelstring(), bparams);
1631 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1632 && !layout.counter.empty())
1633 return tclass.counters().theCounter(layout.counter);
1635 // handle 'inherited level parts' in 'fmt',
1636 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1637 size_t const i = fmt.find('@', 0);
1638 if (i != docstring::npos) {
1639 size_t const j = fmt.find('@', i + 1);
1640 if (j != docstring::npos) {
1641 docstring parent(fmt, i + 1, j - i - 1);
1642 docstring label = from_ascii("??");
1643 if (tclass.hasLayout(parent))
1644 docstring label = expandLabel(tclass[parent], bparams,
1646 fmt = docstring(fmt, 0, i) + label
1647 + docstring(fmt, j + 1, docstring::npos);
1651 return tclass.counters().counterLabel(fmt);
1655 void Paragraph::applyLayout(Layout const & new_layout)
1657 d->layout_ = &new_layout;
1658 LyXAlignment const oldAlign = d->params_.align();
1660 if (!(oldAlign & d->layout_->alignpossible)) {
1661 frontend::Alert::warning(_("Alignment not permitted"),
1662 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1663 d->params_.align(LYX_ALIGN_LAYOUT);
1668 pos_type Paragraph::beginOfBody() const
1670 return d->begin_of_body_;
1674 void Paragraph::setBeginOfBody()
1676 if (d->layout_->labeltype != LABEL_MANUAL) {
1677 d->begin_of_body_ = 0;
1681 // Unroll the first two cycles of the loop
1682 // and remember the previous character to
1683 // remove unnecessary getChar() calls
1685 pos_type end = size();
1686 if (i < end && !isNewline(i)) {
1688 char_type previous_char = 0;
1691 previous_char = d->text_[i];
1692 if (!isNewline(i)) {
1694 while (i < end && previous_char != ' ') {
1699 previous_char = temp;
1705 d->begin_of_body_ = i;
1709 bool Paragraph::forcePlainLayout() const
1711 return inInset().forcePlainLayout();
1715 bool Paragraph::allowParagraphCustomization() const
1717 return inInset().allowParagraphCustomization();
1721 bool Paragraph::usePlainLayout() const
1723 return inInset().usePlainLayout();
1729 // paragraphs inside floats need different alignment tags to avoid
1732 bool noTrivlistCentering(InsetCode code)
1734 return code == FLOAT_CODE
1735 || code == WRAP_CODE
1736 || code == CELL_CODE;
1740 string correction(string const & orig)
1742 if (orig == "flushleft")
1743 return "raggedright";
1744 if (orig == "flushright")
1745 return "raggedleft";
1746 if (orig == "center")
1752 string const corrected_env(string const & suffix, string const & env,
1753 InsetCode code, bool const lastpar)
1755 string output = suffix + "{";
1756 if (noTrivlistCentering(code)) {
1758 // the last paragraph in non-trivlist-aligned
1759 // context is special (to avoid unwanted whitespace)
1760 if (suffix == "\\begin")
1761 return "\\" + correction(env) + "{}";
1764 output += correction(env);
1768 if (suffix == "\\begin")
1774 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1776 if (!contains(str, "\n"))
1777 column += str.size();
1781 column = rsplit(str, tmp, '\n').size();
1788 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1789 odocstream & os, TexRow & texrow,
1790 OutputParams const & runparams) const
1794 if (params_.noindent()) {
1795 os << "\\noindent ";
1799 LyXAlignment const curAlign = params_.align();
1801 if (curAlign == layout_->align)
1805 case LYX_ALIGN_NONE:
1806 case LYX_ALIGN_BLOCK:
1807 case LYX_ALIGN_LAYOUT:
1808 case LYX_ALIGN_SPECIAL:
1810 case LYX_ALIGN_LEFT:
1811 case LYX_ALIGN_RIGHT:
1812 case LYX_ALIGN_CENTER:
1813 if (runparams.moving_arg) {
1820 string const begin_tag = "\\begin";
1821 InsetCode code = owner_->ownerCode();
1822 bool const lastpar = runparams.isLastPar;
1825 case LYX_ALIGN_NONE:
1826 case LYX_ALIGN_BLOCK:
1827 case LYX_ALIGN_LAYOUT:
1828 case LYX_ALIGN_SPECIAL:
1830 case LYX_ALIGN_LEFT: {
1832 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1833 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1835 output = corrected_env(begin_tag, "flushright", code, lastpar);
1836 os << from_ascii(output);
1837 adjust_row_column(output, texrow, column);
1839 } case LYX_ALIGN_RIGHT: {
1841 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1842 output = corrected_env(begin_tag, "flushright", code, lastpar);
1844 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1845 os << from_ascii(output);
1846 adjust_row_column(output, texrow, column);
1848 } case LYX_ALIGN_CENTER: {
1850 output = corrected_env(begin_tag, "center", code, lastpar);
1851 os << from_ascii(output);
1852 adjust_row_column(output, texrow, column);
1861 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1862 odocstream & os, TexRow & texrow,
1863 OutputParams const & runparams) const
1867 switch (params_.align()) {
1868 case LYX_ALIGN_NONE:
1869 case LYX_ALIGN_BLOCK:
1870 case LYX_ALIGN_LAYOUT:
1871 case LYX_ALIGN_SPECIAL:
1873 case LYX_ALIGN_LEFT:
1874 case LYX_ALIGN_RIGHT:
1875 case LYX_ALIGN_CENTER:
1876 if (runparams.moving_arg) {
1883 string const end_tag = "\n\\par\\end";
1884 InsetCode code = owner_->ownerCode();
1885 bool const lastpar = runparams.isLastPar;
1887 switch (params_.align()) {
1888 case LYX_ALIGN_NONE:
1889 case LYX_ALIGN_BLOCK:
1890 case LYX_ALIGN_LAYOUT:
1891 case LYX_ALIGN_SPECIAL:
1893 case LYX_ALIGN_LEFT: {
1895 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1896 output = corrected_env(end_tag, "flushleft", code, lastpar);
1898 output = corrected_env(end_tag, "flushright", code, lastpar);
1899 os << from_ascii(output);
1900 adjust_row_column(output, texrow, column);
1902 } case LYX_ALIGN_RIGHT: {
1904 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1905 output = corrected_env(end_tag, "flushright", code, lastpar);
1907 output = corrected_env(end_tag, "flushleft", code, lastpar);
1908 os << from_ascii(output);
1909 adjust_row_column(output, texrow, column);
1911 } case LYX_ALIGN_CENTER: {
1913 output = corrected_env(end_tag, "center", code, lastpar);
1914 os << from_ascii(output);
1915 adjust_row_column(output, texrow, column);
1924 // This one spits out the text of the paragraph
1925 bool Paragraph::latex(BufferParams const & bparams,
1926 Font const & outerfont,
1927 odocstream & os, TexRow & texrow,
1928 OutputParams const & runparams,
1929 int start_pos, int end_pos) const
1931 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1933 bool return_value = false;
1935 bool const allowcust = allowParagraphCustomization();
1937 // FIXME This check should not be needed. Perhaps issue an
1938 // error if it triggers.
1939 Layout const & style = forcePlainLayout() ?
1940 bparams.documentClass().plainLayout() : *d->layout_;
1942 // Current base font for all inherited font changes, without any
1943 // change caused by an individual character, except for the language:
1944 // It is set to the language of the first character.
1945 // As long as we are in the label, this font is the base font of the
1946 // label. Before the first body character it is set to the base font
1950 // Maybe we have to create a optional argument.
1951 pos_type body_pos = beginOfBody();
1952 unsigned int column = 0;
1955 // the optional argument is kept in curly brackets in
1956 // case it contains a ']'
1959 basefont = getLabelFont(bparams, outerfont);
1961 basefont = getLayoutFont(bparams, outerfont);
1964 // Which font is currently active?
1965 Font running_font(basefont);
1966 // Do we have an open font change?
1967 bool open_font = false;
1969 Change runningChange = Change(Change::UNCHANGED);
1971 texrow.start(id(), 0);
1973 // if the paragraph is empty, the loop will not be entered at all
1975 if (style.isCommand()) {
1980 column += d->startTeXParParams(bparams, os, texrow,
1984 for (pos_type i = 0; i < size(); ++i) {
1985 // First char in paragraph or after label?
1986 if (i == body_pos) {
1989 column += running_font.latexWriteEndChanges(
1990 os, bparams, runparams,
1991 basefont, basefont);
1994 basefont = getLayoutFont(bparams, outerfont);
1995 running_font = basefont;
1997 column += Changes::latexMarkChange(os, bparams,
1998 runningChange, Change(Change::UNCHANGED));
1999 runningChange = Change(Change::UNCHANGED);
2004 if (style.isCommand()) {
2010 column += d->startTeXParParams(bparams, os,
2015 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2018 if (bparams.outputChanges && runningChange != change) {
2020 column += running_font.latexWriteEndChanges(
2021 os, bparams, runparams, basefont, basefont);
2024 basefont = getLayoutFont(bparams, outerfont);
2025 running_font = basefont;
2027 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2028 runningChange = change;
2031 // do not output text which is marked deleted
2032 // if change tracking output is disabled
2033 if (!bparams.outputChanges && change.type == Change::DELETED) {
2039 // Fully instantiated font
2040 Font const font = getFont(bparams, i, outerfont);
2042 Font const last_font = running_font;
2044 // Do we need to close the previous font?
2046 (font != running_font ||
2047 font.language() != running_font.language()))
2049 column += running_font.latexWriteEndChanges(
2050 os, bparams, runparams, basefont,
2051 (i == body_pos-1) ? basefont : font);
2052 running_font = basefont;
2056 // close babel's font environment before opening CJK.
2057 if (!running_font.language()->babel().empty() &&
2058 font.language()->encoding()->package() == Encoding::CJK) {
2059 string end_tag = subst(lyxrc.language_command_end,
2061 running_font.language()->babel());
2062 os << from_ascii(end_tag);
2063 column += end_tag.length();
2066 // Switch file encoding if necessary (and allowed)
2067 if (!runparams.verbatim &&
2068 runparams.encoding->package() != Encoding::none &&
2069 font.language()->encoding()->package() != Encoding::none) {
2070 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2071 runparams, *(font.language()->encoding()));
2072 if (enc_switch.first) {
2073 column += enc_switch.second;
2074 runparams.encoding = font.language()->encoding();
2078 char_type const c = d->text_[i];
2080 // Do we need to change font?
2081 if ((font != running_font ||
2082 font.language() != running_font.language()) &&
2085 odocstringstream ods;
2086 column += font.latexWriteStartChanges(ods, bparams,
2087 runparams, basefont,
2089 running_font = font;
2091 docstring fontchange = ods.str();
2092 // check if the fontchange ends with a trailing blank
2093 // (like "\small " (see bug 3382)
2094 if (suffixIs(fontchange, ' ') && c == ' ')
2095 os << fontchange.substr(0, fontchange.size() - 1)
2096 << from_ascii("{}");
2101 // FIXME: think about end_pos implementation...
2102 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2103 // FIXME: integrate this case in latexSpecialChar
2104 // Do not print the separation of the optional argument
2105 // if style.pass_thru is false. This works because
2106 // latexSpecialChar ignores spaces if
2107 // style.pass_thru is false.
2108 if (i != body_pos - 1) {
2109 if (d->simpleTeXBlanks(
2110 runparams, os, texrow,
2111 i, column, font, style)) {
2112 // A surrogate pair was output. We
2113 // must not call latexSpecialChar
2114 // in this iteration, since it would output
2115 // the combining character again.
2122 OutputParams rp = runparams;
2123 rp.free_spacing = style.free_spacing;
2124 rp.local_font = &font;
2125 rp.intitle = style.intitle;
2127 // Two major modes: LaTeX or plain
2128 // Handle here those cases common to both modes
2129 // and then split to handle the two modes separately.
2130 if (c == META_INSET) {
2131 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2132 d->latexInset(bparams, os,
2133 texrow, rp, running_font,
2134 basefont, outerfont, open_font,
2135 runningChange, style, i, column);
2138 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2140 d->latexSpecialChar(os, rp, running_font, runningChange,
2142 } catch (EncodingException & e) {
2143 if (runparams.dryrun) {
2144 os << "<" << _("LyX Warning: ")
2145 << _("uncodable character") << " '";
2149 // add location information and throw again.
2158 // Set the encoding to that returned from latexSpecialChar (see
2159 // comment for encoding member in OutputParams.h)
2160 runparams.encoding = rp.encoding;
2163 // If we have an open font definition, we have to close it
2165 #ifdef FIXED_LANGUAGE_END_DETECTION
2168 .latexWriteEndChanges(os, bparams, runparams,
2170 next_->getFont(bparams, 0, outerfont));
2172 running_font.latexWriteEndChanges(os, bparams,
2173 runparams, basefont, basefont);
2176 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2177 //FIXME: there as we start another \selectlanguage with the next paragraph if
2178 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2179 running_font.latexWriteEndChanges(os, bparams, runparams,
2180 basefont, basefont);
2184 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2186 // Needed if there is an optional argument but no contents.
2187 if (body_pos > 0 && body_pos == size()) {
2189 return_value = false;
2193 column += d->endTeXParParams(bparams, os, texrow,
2197 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2198 return return_value;
2202 bool Paragraph::emptyTag() const
2204 for (pos_type i = 0; i < size(); ++i) {
2205 if (Inset const * inset = getInset(i)) {
2206 InsetCode lyx_code = inset->lyxCode();
2207 if (lyx_code != TOC_CODE &&
2208 lyx_code != INCLUDE_CODE &&
2209 lyx_code != GRAPHICS_CODE &&
2210 lyx_code != ERT_CODE &&
2211 lyx_code != LISTINGS_CODE &&
2212 lyx_code != FLOAT_CODE &&
2213 lyx_code != TABULAR_CODE) {
2217 char_type c = d->text_[i];
2218 if (c != ' ' && c != '\t')
2226 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2229 for (pos_type i = 0; i < size(); ++i) {
2230 if (Inset const * inset = getInset(i)) {
2231 InsetCode lyx_code = inset->lyxCode();
2232 if (lyx_code == LABEL_CODE) {
2233 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2234 docstring const & id = il->getParam("name");
2235 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2243 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2247 for (i = 0; i < size(); ++i) {
2248 if (Inset const * inset = getInset(i)) {
2249 inset->docbook(os, runparams);
2251 char_type c = d->text_[i];
2254 os << sgml::escapeChar(c);
2261 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2264 pos_type size = text_.size();
2265 for (pos_type i = initial; i < size; ++i) {
2266 Font font = owner_->getFont(buf.params(), i, outerfont);
2267 if (text_[i] == META_INSET)
2269 if (i != initial && font != font_old)
2278 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2280 OutputParams const & runparams,
2281 Font const & outerfont,
2282 pos_type initial) const
2284 bool emph_flag = false;
2286 Layout const & style = *d->layout_;
2288 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2290 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2293 // parsing main loop
2294 for (pos_type i = initial; i < size(); ++i) {
2295 Font font = getFont(buf.params(), i, outerfont);
2297 // handle <emphasis> tag
2298 if (font_old.emph() != font.fontInfo().emph()) {
2299 if (font.fontInfo().emph() == FONT_ON) {
2302 } else if (i != initial) {
2303 os << "</emphasis>";
2308 if (Inset const * inset = getInset(i)) {
2309 inset->docbook(os, runparams);
2311 char_type c = d->text_[i];
2313 if (style.pass_thru)
2316 os << sgml::escapeChar(c);
2318 font_old = font.fontInfo();
2322 os << "</emphasis>";
2325 if (style.free_spacing)
2327 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2332 bool Paragraph::isHfill(pos_type pos) const
2334 Inset const * inset = getInset(pos);
2335 return inset && (inset->lyxCode() == SPACE_CODE &&
2336 inset->isStretchableSpace());
2340 bool Paragraph::isNewline(pos_type pos) const
2342 Inset const * inset = getInset(pos);
2343 return inset && inset->lyxCode() == NEWLINE_CODE;
2347 bool Paragraph::isLineSeparator(pos_type pos) const
2349 char_type const c = d->text_[pos];
2350 if (isLineSeparatorChar(c))
2352 Inset const * inset = getInset(pos);
2353 return inset && inset->isLineSeparator();
2357 /// Used by the spellchecker
2358 bool Paragraph::isLetter(pos_type pos) const
2360 if (Inset const * inset = getInset(pos))
2361 return inset->isLetter();
2362 char_type const c = d->text_[pos];
2363 // We want to pass the ' and escape chars to the spellchecker
2364 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2365 return (isLetterChar(c) || isDigit(c) || contains(quote, c))
2366 && (!d->inset_owner_ || d->inset_owner_->allowSpellCheck())
2372 bool Paragraph::isChar(pos_type pos) const
2374 if (Inset const * inset = getInset(pos))
2375 return inset->isChar();
2376 char_type const c = d->text_[pos];
2377 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2381 bool Paragraph::isSpace(pos_type pos) const
2383 if (Inset const * inset = getInset(pos))
2384 return inset->isSpace();
2385 char_type const c = d->text_[pos];
2386 return lyx::isSpace(c);
2391 Paragraph::getParLanguage(BufferParams const & bparams) const
2394 return getFirstFontSettings(bparams).language();
2395 // FIXME: we should check the prev par as well (Lgb)
2396 return bparams.language;
2400 bool Paragraph::isRTL(BufferParams const & bparams) const
2402 return lyxrc.rtl_support
2403 && getParLanguage(bparams)->rightToLeft()
2404 && ownerCode() != ERT_CODE
2405 && ownerCode() != LISTINGS_CODE;
2409 void Paragraph::changeLanguage(BufferParams const & bparams,
2410 Language const * from, Language const * to)
2412 // change language including dummy font change at the end
2413 for (pos_type i = 0; i <= size(); ++i) {
2414 Font font = getFontSettings(bparams, i);
2415 if (font.language() == from) {
2416 font.setLanguage(to);
2423 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2425 Language const * doc_language = bparams.language;
2426 FontList::const_iterator cit = d->fontlist_.begin();
2427 FontList::const_iterator end = d->fontlist_.end();
2429 for (; cit != end; ++cit)
2430 if (cit->font().language() != ignore_language &&
2431 cit->font().language() != latex_language &&
2432 cit->font().language() != doc_language)
2438 docstring Paragraph::asString(int options) const
2440 return asString(0, size(), options);
2444 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2446 odocstringstream os;
2449 && options & AS_STR_LABEL
2450 && !d->params_.labelString().empty())
2451 os << d->params_.labelString() << ' ';
2453 for (pos_type i = beg; i < end; ++i) {
2454 char_type const c = d->text_[i];
2455 if (isPrintable(c) || c == '\t'
2456 || (c == '\n' && options & AS_STR_NEWLINES))
2458 else if (c == META_INSET && options & AS_STR_INSETS)
2459 getInset(i)->tocString(os);
2466 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2468 odocstringstream os;
2471 && options & AS_STR_LABEL
2472 && !d->params_.labelString().empty())
2473 os << d->params_.labelString() << ' ';
2475 for (pos_type i = beg; i < end; ++i) {
2476 char_type const c = d->text_[i];
2477 if (isPrintable(c) || c == '\t'
2478 || (c == '\n' && options & AS_STR_NEWLINES))
2480 else if (c == META_INSET && options & AS_STR_INSETS) {
2481 getInset(i)->plaintext(os, runparams);
2489 void Paragraph::setInsetOwner(Inset const * inset)
2491 d->inset_owner_ = inset;
2495 int Paragraph::id() const
2501 Layout const & Paragraph::layout() const
2507 void Paragraph::setLayout(Layout const & layout)
2509 d->layout_ = &layout;
2513 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2515 setLayout(tc.defaultLayout());
2519 void Paragraph::setPlainLayout(DocumentClass const & tc)
2521 setLayout(tc.plainLayout());
2525 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2527 if (usePlainLayout())
2528 setPlainLayout(tclass);
2530 setDefaultLayout(tclass);
2534 Inset const & Paragraph::inInset() const
2536 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2537 _("Memory problem"), _("Paragraph not properly initialized")));
2538 return *d->inset_owner_;
2542 InsetCode Paragraph::ownerCode() const
2544 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2548 ParagraphParameters & Paragraph::params()
2554 ParagraphParameters const & Paragraph::params() const
2560 bool Paragraph::isFreeSpacing() const
2562 if (d->layout_->free_spacing)
2564 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2568 bool Paragraph::allowEmpty() const
2570 if (d->layout_->keepempty)
2572 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2576 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2578 if (!Encodings::isArabicChar(c))
2581 char_type prev_char = ' ';
2582 char_type next_char = ' ';
2584 for (pos_type i = pos - 1; i >= 0; --i) {
2585 char_type const par_char = d->text_[i];
2586 if (!Encodings::isArabicComposeChar(par_char)) {
2587 prev_char = par_char;
2592 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2593 char_type const par_char = d->text_[i];
2594 if (!Encodings::isArabicComposeChar(par_char)) {
2595 next_char = par_char;
2600 if (Encodings::isArabicChar(next_char)) {
2601 if (Encodings::isArabicChar(prev_char) &&
2602 !Encodings::isArabicSpecialChar(prev_char))
2603 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2605 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2607 if (Encodings::isArabicChar(prev_char) &&
2608 !Encodings::isArabicSpecialChar(prev_char))
2609 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2611 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2616 int Paragraph::checkBiblio(Buffer const & buffer)
2619 // This is getting more and more a mess. ...We really should clean
2620 // up this bibitem issue for 1.6. See also bug 2743.
2622 // Add bibitem insets if necessary
2623 if (d->layout_->labeltype != LABEL_BIBLIO)
2626 bool hasbibitem = !d->insetlist_.empty()
2627 // Insist on it being in pos 0
2628 && d->text_[0] == META_INSET
2629 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2631 bool track_changes = buffer.params().trackChanges;
2636 // remove a bibitem in pos != 0
2637 // restore it later in pos 0 if necessary
2638 // (e.g. if a user inserts contents _before_ the item)
2639 // we're assuming there's only one of these, which there
2641 int erasedInsetPosition = -1;
2642 InsetList::iterator it = d->insetlist_.begin();
2643 InsetList::iterator end = d->insetlist_.end();
2644 for (; it != end; ++it)
2645 if (it->inset->lyxCode() == BIBITEM_CODE
2647 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2648 oldkey = olditem->getParam("key");
2649 oldlabel = olditem->getParam("label");
2650 erasedInsetPosition = it->pos;
2651 eraseChar(erasedInsetPosition, track_changes);
2655 // There was an InsetBibitem at the beginning, and we didn't
2656 // have to erase one.
2657 if (hasbibitem && erasedInsetPosition < 0)
2660 // There was an InsetBibitem at the beginning and we did have to
2661 // erase one. So we give its properties to the beginning inset.
2663 InsetBibitem * inset =
2664 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2665 if (!oldkey.empty())
2666 inset->setParam("key", oldkey);
2667 inset->setParam("label", oldlabel);
2668 return -erasedInsetPosition;
2671 // There was no inset at the beginning, so we need to create one with
2672 // the key and label of the one we erased.
2673 InsetBibitem * inset =
2674 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2675 // restore values of previously deleted item in this par.
2676 if (!oldkey.empty())
2677 inset->setParam("key", oldkey);
2678 inset->setParam("label", oldlabel);
2679 insertInset(0, static_cast<Inset *>(inset),
2680 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2686 void Paragraph::checkAuthors(AuthorList const & authorList)
2688 d->changes_.checkAuthors(authorList);
2692 bool Paragraph::isUnchanged(pos_type pos) const
2694 return lookupChange(pos).type == Change::UNCHANGED;
2698 bool Paragraph::isInserted(pos_type pos) const
2700 return lookupChange(pos).type == Change::INSERTED;
2704 bool Paragraph::isDeleted(pos_type pos) const
2706 return lookupChange(pos).type == Change::DELETED;
2710 InsetList const & Paragraph::insetList() const
2712 return d->insetlist_;
2716 void Paragraph::setBuffer(Buffer & b)
2718 d->insetlist_.setBuffer(b);
2722 Inset * Paragraph::releaseInset(pos_type pos)
2724 Inset * inset = d->insetlist_.release(pos);
2725 /// does not honour change tracking!
2726 eraseChar(pos, false);
2731 Inset * Paragraph::getInset(pos_type pos)
2733 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2734 ? d->insetlist_.get(pos) : 0;
2738 Inset const * Paragraph::getInset(pos_type pos) const
2740 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2741 ? d->insetlist_.get(pos) : 0;
2745 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2746 pos_type & right, TextCase action)
2748 // process sequences of modified characters; in change
2749 // tracking mode, this approach results in much better
2750 // usability than changing case on a char-by-char basis
2753 bool const trackChanges = bparams.trackChanges;
2755 bool capitalize = true;
2757 for (; pos < right; ++pos) {
2758 char_type oldChar = d->text_[pos];
2759 char_type newChar = oldChar;
2761 // ignore insets and don't play with deleted text!
2762 if (oldChar != META_INSET && !isDeleted(pos)) {
2764 case text_lowercase:
2765 newChar = lowercase(oldChar);
2767 case text_capitalization:
2769 newChar = uppercase(oldChar);
2773 case text_uppercase:
2774 newChar = uppercase(oldChar);
2779 if (!isLetter(pos) || isDeleted(pos)) {
2780 // permit capitalization again
2784 if (oldChar != newChar)
2787 if (oldChar == newChar || pos == right - 1) {
2788 if (oldChar != newChar) {
2789 // step behind the changing area
2792 int erasePos = pos - changes.size();
2793 for (size_t i = 0; i < changes.size(); i++) {
2794 insertChar(pos, changes[i],
2795 getFontSettings(bparams,
2798 if (!eraseChar(erasePos, trackChanges)) {
2801 ++right; // expand selection
2810 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2811 pos_type pos, bool del) const
2813 int const strsize = str.length();
2815 pos_type const parsize = d->text_.size();
2816 for (i = 0; pos + i < parsize; ++i) {
2819 if (cs && str[i] != d->text_[pos + i])
2821 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2823 if (!del && isDeleted(pos + i))
2830 // if necessary, check whether string matches word
2832 if (pos > 0 && isLetter(pos - 1))
2834 if (pos + strsize < parsize
2835 && isLetter(pos + strsize))
2843 char_type Paragraph::getChar(pos_type pos) const
2845 return d->text_[pos];
2849 pos_type Paragraph::size() const
2851 return d->text_.size();
2855 bool Paragraph::empty() const
2857 return d->text_.empty();
2861 bool Paragraph::isInset(pos_type pos) const
2863 return d->text_[pos] == META_INSET;
2867 bool Paragraph::isSeparator(pos_type pos) const
2869 //FIXME: Are we sure this can be the only separator?
2870 return d->text_[pos] == ' ';
2874 void Paragraph::deregisterWords()
2876 Private::Words::const_iterator it;
2877 WordList & wl = theWordList();
2878 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2884 void Paragraph::locateWord(pos_type & from, pos_type & to,
2885 word_location const loc) const
2888 case WHOLE_WORD_STRICT:
2889 if (from == 0 || from == size()
2891 || !isLetter(from - 1)) {
2895 // no break here, we go to the next
2898 // If we are already at the beginning of a word, do nothing
2899 if (!from || !isLetter(from - 1))
2901 // no break here, we go to the next
2904 // always move the cursor to the beginning of previous word
2905 while (from && isLetter(from - 1))
2909 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
2912 // no need to move the 'from' cursor
2916 while (to < size() && isLetter(to))
2921 void Paragraph::collectWords()
2923 SpellChecker * speller = theSpellChecker();
2925 //lyxerr << "Words: ";
2926 pos_type n = size();
2927 for (pos_type pos = 0; pos < n; ++pos) {
2930 pos_type from = pos;
2931 locateWord(from, pos, WHOLE_WORD);
2932 if (!lyxrc.spellcheck_continuously && pos - from < 6)
2935 docstring word = asString(from, pos, false);
2936 if (pos - from >= 6)
2937 d->words_.insert(word);
2939 if (!lyxrc.spellcheck_continuously || !speller)
2942 string lang_code = lyxrc.spellchecker_use_alt_lang
2943 ? lyxrc.spellchecker_alt_lang
2944 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2945 WordLangTuple wl(word, lang_code);
2946 SpellChecker::Result res = speller->check(wl);
2947 // ... just ignore any error that the spellchecker reports.
2948 if (!speller->error().empty())
2950 bool const misspelled = res != SpellChecker::OK
2951 && res != SpellChecker::IGNORED_WORD;
2952 d->fontlist_.setMisspelled(from, pos, misspelled);
2954 //lyxerr << word << " ";
2956 //lyxerr << std::endl;
2960 void Paragraph::registerWords()
2962 Private::Words::const_iterator it;
2963 WordList & wl = theWordList();
2964 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2969 void Paragraph::updateWords()
2977 bool Paragraph::isMisspelled(pos_type pos) const
2979 SpellChecker * speller = theSpellChecker();
2980 pos_type from = pos;
2982 locateWord(from, to, WHOLE_WORD);
2983 docstring word = asString(from, to, false);
2987 string lang_code = lyxrc.spellchecker_use_alt_lang
2988 ? lyxrc.spellchecker_alt_lang
2989 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2990 WordLangTuple wl(word, lang_code);
2991 SpellChecker::Result res = speller->check(wl);
2992 // ... just ignore any error that the spellchecker reports.
2993 if (!speller->error().empty())
2996 bool const misspelled = res != SpellChecker::OK
2997 && res != SpellChecker::IGNORED_WORD;
2998 if (lyxrc.spellcheck_continuously)
2999 d->fontlist_.setMisspelled(from, pos, misspelled);