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 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1594 return d->params_.labelWidthString();
1596 return _("Senseless with this layout!");
1600 void Paragraph::setLabelWidthString(docstring const & s)
1602 d->params_.labelWidthString(s);
1606 docstring const Paragraph::translateIfPossible(docstring const & s,
1607 BufferParams const & bparams) const
1609 if (!isAscii(s) || s.empty()) {
1610 // This must be a user defined layout. We cannot translate
1611 // this, since gettext accepts only ascii keys.
1614 // Probably standard layout, try to translate
1615 Messages & m = getMessages(getParLanguage(bparams)->code());
1616 return m.get(to_ascii(s));
1620 docstring Paragraph::expandLabel(Layout const & layout,
1621 BufferParams const & bparams, bool process_appendix) const
1623 DocumentClass const & tclass = bparams.documentClass();
1626 if (process_appendix && d->params_.appendix())
1627 fmt = translateIfPossible(layout.labelstring_appendix(),
1630 fmt = translateIfPossible(layout.labelstring(), bparams);
1632 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1633 && !layout.counter.empty())
1634 return tclass.counters().theCounter(layout.counter);
1636 // handle 'inherited level parts' in 'fmt',
1637 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1638 size_t const i = fmt.find('@', 0);
1639 if (i != docstring::npos) {
1640 size_t const j = fmt.find('@', i + 1);
1641 if (j != docstring::npos) {
1642 docstring parent(fmt, i + 1, j - i - 1);
1643 docstring label = from_ascii("??");
1644 if (tclass.hasLayout(parent))
1645 docstring label = expandLabel(tclass[parent], bparams,
1647 fmt = docstring(fmt, 0, i) + label
1648 + docstring(fmt, j + 1, docstring::npos);
1652 return tclass.counters().counterLabel(fmt);
1656 void Paragraph::applyLayout(Layout const & new_layout)
1658 d->layout_ = &new_layout;
1659 LyXAlignment const oldAlign = d->params_.align();
1661 if (!(oldAlign & d->layout_->alignpossible)) {
1662 frontend::Alert::warning(_("Alignment not permitted"),
1663 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1664 d->params_.align(LYX_ALIGN_LAYOUT);
1669 pos_type Paragraph::beginOfBody() const
1671 return d->begin_of_body_;
1675 void Paragraph::setBeginOfBody()
1677 if (d->layout_->labeltype != LABEL_MANUAL) {
1678 d->begin_of_body_ = 0;
1682 // Unroll the first two cycles of the loop
1683 // and remember the previous character to
1684 // remove unnecessary getChar() calls
1686 pos_type end = size();
1687 if (i < end && !isNewline(i)) {
1689 char_type previous_char = 0;
1692 previous_char = d->text_[i];
1693 if (!isNewline(i)) {
1695 while (i < end && previous_char != ' ') {
1700 previous_char = temp;
1706 d->begin_of_body_ = i;
1710 bool Paragraph::forcePlainLayout() const
1712 return inInset().forcePlainLayout();
1716 bool Paragraph::allowParagraphCustomization() const
1718 return inInset().allowParagraphCustomization();
1722 bool Paragraph::usePlainLayout() const
1724 return inInset().usePlainLayout();
1730 // paragraphs inside floats need different alignment tags to avoid
1733 bool noTrivlistCentering(InsetCode code)
1735 return code == FLOAT_CODE
1736 || code == WRAP_CODE
1737 || code == CELL_CODE;
1741 string correction(string const & orig)
1743 if (orig == "flushleft")
1744 return "raggedright";
1745 if (orig == "flushright")
1746 return "raggedleft";
1747 if (orig == "center")
1753 string const corrected_env(string const & suffix, string const & env,
1754 InsetCode code, bool const lastpar)
1756 string output = suffix + "{";
1757 if (noTrivlistCentering(code)) {
1759 // the last paragraph in non-trivlist-aligned
1760 // context is special (to avoid unwanted whitespace)
1761 if (suffix == "\\begin")
1762 return "\\" + correction(env) + "{}";
1765 output += correction(env);
1769 if (suffix == "\\begin")
1775 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1777 if (!contains(str, "\n"))
1778 column += str.size();
1782 column = rsplit(str, tmp, '\n').size();
1789 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1790 odocstream & os, TexRow & texrow,
1791 OutputParams const & runparams) const
1795 if (params_.noindent()) {
1796 os << "\\noindent ";
1800 LyXAlignment const curAlign = params_.align();
1802 if (curAlign == layout_->align)
1806 case LYX_ALIGN_NONE:
1807 case LYX_ALIGN_BLOCK:
1808 case LYX_ALIGN_LAYOUT:
1809 case LYX_ALIGN_SPECIAL:
1811 case LYX_ALIGN_LEFT:
1812 case LYX_ALIGN_RIGHT:
1813 case LYX_ALIGN_CENTER:
1814 if (runparams.moving_arg) {
1821 string const begin_tag = "\\begin";
1822 InsetCode code = owner_->ownerCode();
1823 bool const lastpar = runparams.isLastPar;
1826 case LYX_ALIGN_NONE:
1827 case LYX_ALIGN_BLOCK:
1828 case LYX_ALIGN_LAYOUT:
1829 case LYX_ALIGN_SPECIAL:
1831 case LYX_ALIGN_LEFT: {
1833 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1834 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1836 output = corrected_env(begin_tag, "flushright", code, lastpar);
1837 os << from_ascii(output);
1838 adjust_row_column(output, texrow, column);
1840 } case LYX_ALIGN_RIGHT: {
1842 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1843 output = corrected_env(begin_tag, "flushright", code, lastpar);
1845 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1846 os << from_ascii(output);
1847 adjust_row_column(output, texrow, column);
1849 } case LYX_ALIGN_CENTER: {
1851 output = corrected_env(begin_tag, "center", code, lastpar);
1852 os << from_ascii(output);
1853 adjust_row_column(output, texrow, column);
1862 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1863 odocstream & os, TexRow & texrow,
1864 OutputParams const & runparams) const
1868 switch (params_.align()) {
1869 case LYX_ALIGN_NONE:
1870 case LYX_ALIGN_BLOCK:
1871 case LYX_ALIGN_LAYOUT:
1872 case LYX_ALIGN_SPECIAL:
1874 case LYX_ALIGN_LEFT:
1875 case LYX_ALIGN_RIGHT:
1876 case LYX_ALIGN_CENTER:
1877 if (runparams.moving_arg) {
1884 string const end_tag = "\n\\par\\end";
1885 InsetCode code = owner_->ownerCode();
1886 bool const lastpar = runparams.isLastPar;
1888 switch (params_.align()) {
1889 case LYX_ALIGN_NONE:
1890 case LYX_ALIGN_BLOCK:
1891 case LYX_ALIGN_LAYOUT:
1892 case LYX_ALIGN_SPECIAL:
1894 case LYX_ALIGN_LEFT: {
1896 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1897 output = corrected_env(end_tag, "flushleft", code, lastpar);
1899 output = corrected_env(end_tag, "flushright", code, lastpar);
1900 os << from_ascii(output);
1901 adjust_row_column(output, texrow, column);
1903 } case LYX_ALIGN_RIGHT: {
1905 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1906 output = corrected_env(end_tag, "flushright", code, lastpar);
1908 output = corrected_env(end_tag, "flushleft", code, lastpar);
1909 os << from_ascii(output);
1910 adjust_row_column(output, texrow, column);
1912 } case LYX_ALIGN_CENTER: {
1914 output = corrected_env(end_tag, "center", code, lastpar);
1915 os << from_ascii(output);
1916 adjust_row_column(output, texrow, column);
1925 // This one spits out the text of the paragraph
1926 bool Paragraph::latex(BufferParams const & bparams,
1927 Font const & outerfont,
1928 odocstream & os, TexRow & texrow,
1929 OutputParams const & runparams,
1930 int start_pos, int end_pos) const
1932 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1934 bool return_value = false;
1936 bool const allowcust = allowParagraphCustomization();
1938 // FIXME This check should not be needed. Perhaps issue an
1939 // error if it triggers.
1940 Layout const & style = forcePlainLayout() ?
1941 bparams.documentClass().plainLayout() : *d->layout_;
1943 // Current base font for all inherited font changes, without any
1944 // change caused by an individual character, except for the language:
1945 // It is set to the language of the first character.
1946 // As long as we are in the label, this font is the base font of the
1947 // label. Before the first body character it is set to the base font
1951 // Maybe we have to create a optional argument.
1952 pos_type body_pos = beginOfBody();
1953 unsigned int column = 0;
1956 // the optional argument is kept in curly brackets in
1957 // case it contains a ']'
1960 basefont = getLabelFont(bparams, outerfont);
1962 basefont = getLayoutFont(bparams, outerfont);
1965 // Which font is currently active?
1966 Font running_font(basefont);
1967 // Do we have an open font change?
1968 bool open_font = false;
1970 Change runningChange = Change(Change::UNCHANGED);
1972 texrow.start(id(), 0);
1974 // if the paragraph is empty, the loop will not be entered at all
1976 if (style.isCommand()) {
1981 column += d->startTeXParParams(bparams, os, texrow,
1985 for (pos_type i = 0; i < size(); ++i) {
1986 // First char in paragraph or after label?
1987 if (i == body_pos) {
1990 column += running_font.latexWriteEndChanges(
1991 os, bparams, runparams,
1992 basefont, basefont);
1995 basefont = getLayoutFont(bparams, outerfont);
1996 running_font = basefont;
1998 column += Changes::latexMarkChange(os, bparams,
1999 runningChange, Change(Change::UNCHANGED));
2000 runningChange = Change(Change::UNCHANGED);
2005 if (style.isCommand()) {
2011 column += d->startTeXParParams(bparams, os,
2016 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2019 if (bparams.outputChanges && runningChange != change) {
2021 column += running_font.latexWriteEndChanges(
2022 os, bparams, runparams, basefont, basefont);
2025 basefont = getLayoutFont(bparams, outerfont);
2026 running_font = basefont;
2028 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2029 runningChange = change;
2032 // do not output text which is marked deleted
2033 // if change tracking output is disabled
2034 if (!bparams.outputChanges && change.type == Change::DELETED) {
2040 // Fully instantiated font
2041 Font const font = getFont(bparams, i, outerfont);
2043 Font const last_font = running_font;
2045 // Do we need to close the previous font?
2047 (font != running_font ||
2048 font.language() != running_font.language()))
2050 column += running_font.latexWriteEndChanges(
2051 os, bparams, runparams, basefont,
2052 (i == body_pos-1) ? basefont : font);
2053 running_font = basefont;
2057 // close babel's font environment before opening CJK.
2058 if (!running_font.language()->babel().empty() &&
2059 font.language()->encoding()->package() == Encoding::CJK) {
2060 string end_tag = subst(lyxrc.language_command_end,
2062 running_font.language()->babel());
2063 os << from_ascii(end_tag);
2064 column += end_tag.length();
2067 // Switch file encoding if necessary (and allowed)
2068 if (!runparams.verbatim &&
2069 runparams.encoding->package() != Encoding::none &&
2070 font.language()->encoding()->package() != Encoding::none) {
2071 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2072 runparams, *(font.language()->encoding()));
2073 if (enc_switch.first) {
2074 column += enc_switch.second;
2075 runparams.encoding = font.language()->encoding();
2079 char_type const c = d->text_[i];
2081 // Do we need to change font?
2082 if ((font != running_font ||
2083 font.language() != running_font.language()) &&
2086 odocstringstream ods;
2087 column += font.latexWriteStartChanges(ods, bparams,
2088 runparams, basefont,
2090 running_font = font;
2092 docstring fontchange = ods.str();
2093 // check if the fontchange ends with a trailing blank
2094 // (like "\small " (see bug 3382)
2095 if (suffixIs(fontchange, ' ') && c == ' ')
2096 os << fontchange.substr(0, fontchange.size() - 1)
2097 << from_ascii("{}");
2102 // FIXME: think about end_pos implementation...
2103 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2104 // FIXME: integrate this case in latexSpecialChar
2105 // Do not print the separation of the optional argument
2106 // if style.pass_thru is false. This works because
2107 // latexSpecialChar ignores spaces if
2108 // style.pass_thru is false.
2109 if (i != body_pos - 1) {
2110 if (d->simpleTeXBlanks(
2111 runparams, os, texrow,
2112 i, column, font, style)) {
2113 // A surrogate pair was output. We
2114 // must not call latexSpecialChar
2115 // in this iteration, since it would output
2116 // the combining character again.
2123 OutputParams rp = runparams;
2124 rp.free_spacing = style.free_spacing;
2125 rp.local_font = &font;
2126 rp.intitle = style.intitle;
2128 // Two major modes: LaTeX or plain
2129 // Handle here those cases common to both modes
2130 // and then split to handle the two modes separately.
2131 if (c == META_INSET) {
2132 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2133 d->latexInset(bparams, os,
2134 texrow, rp, running_font,
2135 basefont, outerfont, open_font,
2136 runningChange, style, i, column);
2139 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2141 d->latexSpecialChar(os, rp, running_font, runningChange,
2143 } catch (EncodingException & e) {
2144 if (runparams.dryrun) {
2145 os << "<" << _("LyX Warning: ")
2146 << _("uncodable character") << " '";
2150 // add location information and throw again.
2159 // Set the encoding to that returned from latexSpecialChar (see
2160 // comment for encoding member in OutputParams.h)
2161 runparams.encoding = rp.encoding;
2164 // If we have an open font definition, we have to close it
2166 #ifdef FIXED_LANGUAGE_END_DETECTION
2169 .latexWriteEndChanges(os, bparams, runparams,
2171 next_->getFont(bparams, 0, outerfont));
2173 running_font.latexWriteEndChanges(os, bparams,
2174 runparams, basefont, basefont);
2177 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2178 //FIXME: there as we start another \selectlanguage with the next paragraph if
2179 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2180 running_font.latexWriteEndChanges(os, bparams, runparams,
2181 basefont, basefont);
2185 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2187 // Needed if there is an optional argument but no contents.
2188 if (body_pos > 0 && body_pos == size()) {
2190 return_value = false;
2194 column += d->endTeXParParams(bparams, os, texrow,
2198 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2199 return return_value;
2203 bool Paragraph::emptyTag() const
2205 for (pos_type i = 0; i < size(); ++i) {
2206 if (Inset const * inset = getInset(i)) {
2207 InsetCode lyx_code = inset->lyxCode();
2208 if (lyx_code != TOC_CODE &&
2209 lyx_code != INCLUDE_CODE &&
2210 lyx_code != GRAPHICS_CODE &&
2211 lyx_code != ERT_CODE &&
2212 lyx_code != LISTINGS_CODE &&
2213 lyx_code != FLOAT_CODE &&
2214 lyx_code != TABULAR_CODE) {
2218 char_type c = d->text_[i];
2219 if (c != ' ' && c != '\t')
2227 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2230 for (pos_type i = 0; i < size(); ++i) {
2231 if (Inset const * inset = getInset(i)) {
2232 InsetCode lyx_code = inset->lyxCode();
2233 if (lyx_code == LABEL_CODE) {
2234 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2235 docstring const & id = il->getParam("name");
2236 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2244 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2248 for (i = 0; i < size(); ++i) {
2249 if (Inset const * inset = getInset(i)) {
2250 inset->docbook(os, runparams);
2252 char_type c = d->text_[i];
2255 os << sgml::escapeChar(c);
2262 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2265 pos_type size = text_.size();
2266 for (pos_type i = initial; i < size; ++i) {
2267 Font font = owner_->getFont(buf.params(), i, outerfont);
2268 if (text_[i] == META_INSET)
2270 if (i != initial && font != font_old)
2279 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2281 OutputParams const & runparams,
2282 Font const & outerfont,
2283 pos_type initial) const
2285 bool emph_flag = false;
2287 Layout const & style = *d->layout_;
2289 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2291 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2294 // parsing main loop
2295 for (pos_type i = initial; i < size(); ++i) {
2296 Font font = getFont(buf.params(), i, outerfont);
2298 // handle <emphasis> tag
2299 if (font_old.emph() != font.fontInfo().emph()) {
2300 if (font.fontInfo().emph() == FONT_ON) {
2303 } else if (i != initial) {
2304 os << "</emphasis>";
2309 if (Inset const * inset = getInset(i)) {
2310 inset->docbook(os, runparams);
2312 char_type c = d->text_[i];
2314 if (style.pass_thru)
2317 os << sgml::escapeChar(c);
2319 font_old = font.fontInfo();
2323 os << "</emphasis>";
2326 if (style.free_spacing)
2328 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2333 bool Paragraph::isHfill(pos_type pos) const
2335 Inset const * inset = getInset(pos);
2336 return inset && (inset->lyxCode() == SPACE_CODE &&
2337 inset->isStretchableSpace());
2341 bool Paragraph::isNewline(pos_type pos) const
2343 Inset const * inset = getInset(pos);
2344 return inset && inset->lyxCode() == NEWLINE_CODE;
2348 bool Paragraph::isLineSeparator(pos_type pos) const
2350 char_type const c = d->text_[pos];
2351 if (isLineSeparatorChar(c))
2353 Inset const * inset = getInset(pos);
2354 return inset && inset->isLineSeparator();
2358 /// Used by the spellchecker
2359 bool Paragraph::isLetter(pos_type pos) const
2361 if (Inset const * inset = getInset(pos))
2362 return inset->isLetter();
2363 char_type const c = d->text_[pos];
2364 // We want to pass the ' and escape chars to the spellchecker
2365 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2366 return (isLetterChar(c) || isDigit(c) || contains(quote, c))
2367 && (!d->inset_owner_ || d->inset_owner_->allowSpellCheck())
2373 bool Paragraph::isChar(pos_type pos) const
2375 if (Inset const * inset = getInset(pos))
2376 return inset->isChar();
2377 char_type const c = d->text_[pos];
2378 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2382 bool Paragraph::isSpace(pos_type pos) const
2384 if (Inset const * inset = getInset(pos))
2385 return inset->isSpace();
2386 char_type const c = d->text_[pos];
2387 return lyx::isSpace(c);
2392 Paragraph::getParLanguage(BufferParams const & bparams) const
2395 return getFirstFontSettings(bparams).language();
2396 // FIXME: we should check the prev par as well (Lgb)
2397 return bparams.language;
2401 bool Paragraph::isRTL(BufferParams const & bparams) const
2403 return lyxrc.rtl_support
2404 && getParLanguage(bparams)->rightToLeft()
2405 && ownerCode() != ERT_CODE
2406 && ownerCode() != LISTINGS_CODE;
2410 void Paragraph::changeLanguage(BufferParams const & bparams,
2411 Language const * from, Language const * to)
2413 // change language including dummy font change at the end
2414 for (pos_type i = 0; i <= size(); ++i) {
2415 Font font = getFontSettings(bparams, i);
2416 if (font.language() == from) {
2417 font.setLanguage(to);
2424 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2426 Language const * doc_language = bparams.language;
2427 FontList::const_iterator cit = d->fontlist_.begin();
2428 FontList::const_iterator end = d->fontlist_.end();
2430 for (; cit != end; ++cit)
2431 if (cit->font().language() != ignore_language &&
2432 cit->font().language() != latex_language &&
2433 cit->font().language() != doc_language)
2439 docstring Paragraph::asString(int options) const
2441 return asString(0, size(), options);
2445 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2447 odocstringstream os;
2450 && options & AS_STR_LABEL
2451 && !d->params_.labelString().empty())
2452 os << d->params_.labelString() << ' ';
2454 for (pos_type i = beg; i < end; ++i) {
2455 char_type const c = d->text_[i];
2456 if (isPrintable(c) || c == '\t'
2457 || (c == '\n' && options & AS_STR_NEWLINES))
2459 else if (c == META_INSET && options & AS_STR_INSETS)
2460 getInset(i)->tocString(os);
2467 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2469 odocstringstream os;
2472 && options & AS_STR_LABEL
2473 && !d->params_.labelString().empty())
2474 os << d->params_.labelString() << ' ';
2476 for (pos_type i = beg; i < end; ++i) {
2477 char_type const c = d->text_[i];
2478 if (isPrintable(c) || c == '\t'
2479 || (c == '\n' && options & AS_STR_NEWLINES))
2481 else if (c == META_INSET && options & AS_STR_INSETS) {
2482 getInset(i)->plaintext(os, runparams);
2490 void Paragraph::setInsetOwner(Inset const * inset)
2492 d->inset_owner_ = inset;
2496 int Paragraph::id() const
2502 Layout const & Paragraph::layout() const
2508 void Paragraph::setLayout(Layout const & layout)
2510 d->layout_ = &layout;
2514 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2516 setLayout(tc.defaultLayout());
2520 void Paragraph::setPlainLayout(DocumentClass const & tc)
2522 setLayout(tc.plainLayout());
2526 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2528 if (usePlainLayout())
2529 setPlainLayout(tclass);
2531 setDefaultLayout(tclass);
2535 Inset const & Paragraph::inInset() const
2537 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2538 _("Memory problem"), _("Paragraph not properly initialized")));
2539 return *d->inset_owner_;
2543 InsetCode Paragraph::ownerCode() const
2545 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2549 ParagraphParameters & Paragraph::params()
2555 ParagraphParameters const & Paragraph::params() const
2561 bool Paragraph::isFreeSpacing() const
2563 if (d->layout_->free_spacing)
2565 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2569 bool Paragraph::allowEmpty() const
2571 if (d->layout_->keepempty)
2573 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2577 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2579 if (!Encodings::isArabicChar(c))
2582 char_type prev_char = ' ';
2583 char_type next_char = ' ';
2585 for (pos_type i = pos - 1; i >= 0; --i) {
2586 char_type const par_char = d->text_[i];
2587 if (!Encodings::isArabicComposeChar(par_char)) {
2588 prev_char = par_char;
2593 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2594 char_type const par_char = d->text_[i];
2595 if (!Encodings::isArabicComposeChar(par_char)) {
2596 next_char = par_char;
2601 if (Encodings::isArabicChar(next_char)) {
2602 if (Encodings::isArabicChar(prev_char) &&
2603 !Encodings::isArabicSpecialChar(prev_char))
2604 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2606 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2608 if (Encodings::isArabicChar(prev_char) &&
2609 !Encodings::isArabicSpecialChar(prev_char))
2610 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2612 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2617 int Paragraph::checkBiblio(Buffer const & buffer)
2620 // This is getting more and more a mess. ...We really should clean
2621 // up this bibitem issue for 1.6. See also bug 2743.
2623 // Add bibitem insets if necessary
2624 if (d->layout_->labeltype != LABEL_BIBLIO)
2627 bool hasbibitem = !d->insetlist_.empty()
2628 // Insist on it being in pos 0
2629 && d->text_[0] == META_INSET
2630 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2632 bool track_changes = buffer.params().trackChanges;
2637 // remove a bibitem in pos != 0
2638 // restore it later in pos 0 if necessary
2639 // (e.g. if a user inserts contents _before_ the item)
2640 // we're assuming there's only one of these, which there
2642 int erasedInsetPosition = -1;
2643 InsetList::iterator it = d->insetlist_.begin();
2644 InsetList::iterator end = d->insetlist_.end();
2645 for (; it != end; ++it)
2646 if (it->inset->lyxCode() == BIBITEM_CODE
2648 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2649 oldkey = olditem->getParam("key");
2650 oldlabel = olditem->getParam("label");
2651 erasedInsetPosition = it->pos;
2652 eraseChar(erasedInsetPosition, track_changes);
2656 // There was an InsetBibitem at the beginning, and we didn't
2657 // have to erase one.
2658 if (hasbibitem && erasedInsetPosition < 0)
2661 // There was an InsetBibitem at the beginning and we did have to
2662 // erase one. So we give its properties to the beginning inset.
2664 InsetBibitem * inset =
2665 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2666 if (!oldkey.empty())
2667 inset->setParam("key", oldkey);
2668 inset->setParam("label", oldlabel);
2669 return -erasedInsetPosition;
2672 // There was no inset at the beginning, so we need to create one with
2673 // the key and label of the one we erased.
2674 InsetBibitem * inset =
2675 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2676 // restore values of previously deleted item in this par.
2677 if (!oldkey.empty())
2678 inset->setParam("key", oldkey);
2679 inset->setParam("label", oldlabel);
2680 insertInset(0, static_cast<Inset *>(inset),
2681 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2687 void Paragraph::checkAuthors(AuthorList const & authorList)
2689 d->changes_.checkAuthors(authorList);
2693 bool Paragraph::isUnchanged(pos_type pos) const
2695 return lookupChange(pos).type == Change::UNCHANGED;
2699 bool Paragraph::isInserted(pos_type pos) const
2701 return lookupChange(pos).type == Change::INSERTED;
2705 bool Paragraph::isDeleted(pos_type pos) const
2707 return lookupChange(pos).type == Change::DELETED;
2711 InsetList const & Paragraph::insetList() const
2713 return d->insetlist_;
2717 void Paragraph::setBuffer(Buffer & b)
2719 d->insetlist_.setBuffer(b);
2723 Inset * Paragraph::releaseInset(pos_type pos)
2725 Inset * inset = d->insetlist_.release(pos);
2726 /// does not honour change tracking!
2727 eraseChar(pos, false);
2732 Inset * Paragraph::getInset(pos_type pos)
2734 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2735 ? d->insetlist_.get(pos) : 0;
2739 Inset const * Paragraph::getInset(pos_type pos) const
2741 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2742 ? d->insetlist_.get(pos) : 0;
2746 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2747 pos_type & right, TextCase action)
2749 // process sequences of modified characters; in change
2750 // tracking mode, this approach results in much better
2751 // usability than changing case on a char-by-char basis
2754 bool const trackChanges = bparams.trackChanges;
2756 bool capitalize = true;
2758 for (; pos < right; ++pos) {
2759 char_type oldChar = d->text_[pos];
2760 char_type newChar = oldChar;
2762 // ignore insets and don't play with deleted text!
2763 if (oldChar != META_INSET && !isDeleted(pos)) {
2765 case text_lowercase:
2766 newChar = lowercase(oldChar);
2768 case text_capitalization:
2770 newChar = uppercase(oldChar);
2774 case text_uppercase:
2775 newChar = uppercase(oldChar);
2780 if (!isLetter(pos) || isDeleted(pos)) {
2781 // permit capitalization again
2785 if (oldChar != newChar)
2788 if (oldChar == newChar || pos == right - 1) {
2789 if (oldChar != newChar) {
2790 // step behind the changing area
2793 int erasePos = pos - changes.size();
2794 for (size_t i = 0; i < changes.size(); i++) {
2795 insertChar(pos, changes[i],
2796 getFontSettings(bparams,
2799 if (!eraseChar(erasePos, trackChanges)) {
2802 ++right; // expand selection
2811 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2812 pos_type pos, bool del) const
2814 int const strsize = str.length();
2816 pos_type const parsize = d->text_.size();
2817 for (i = 0; pos + i < parsize; ++i) {
2820 if (cs && str[i] != d->text_[pos + i])
2822 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2824 if (!del && isDeleted(pos + i))
2831 // if necessary, check whether string matches word
2833 if (pos > 0 && isLetter(pos - 1))
2835 if (pos + strsize < parsize
2836 && isLetter(pos + strsize))
2844 char_type Paragraph::getChar(pos_type pos) const
2846 return d->text_[pos];
2850 pos_type Paragraph::size() const
2852 return d->text_.size();
2856 bool Paragraph::empty() const
2858 return d->text_.empty();
2862 bool Paragraph::isInset(pos_type pos) const
2864 return d->text_[pos] == META_INSET;
2868 bool Paragraph::isSeparator(pos_type pos) const
2870 //FIXME: Are we sure this can be the only separator?
2871 return d->text_[pos] == ' ';
2875 void Paragraph::deregisterWords()
2877 Private::Words::const_iterator it;
2878 WordList & wl = theWordList();
2879 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2885 void Paragraph::locateWord(pos_type & from, pos_type & to,
2886 word_location const loc) const
2889 case WHOLE_WORD_STRICT:
2890 if (from == 0 || from == size()
2892 || !isLetter(from - 1)) {
2896 // no break here, we go to the next
2899 // If we are already at the beginning of a word, do nothing
2900 if (!from || !isLetter(from - 1))
2902 // no break here, we go to the next
2905 // always move the cursor to the beginning of previous word
2906 while (from && isLetter(from - 1))
2910 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
2913 // no need to move the 'from' cursor
2917 while (to < size() && isLetter(to))
2922 void Paragraph::collectWords()
2924 SpellChecker * speller = theSpellChecker();
2926 //lyxerr << "Words: ";
2927 pos_type n = size();
2928 for (pos_type pos = 0; pos < n; ++pos) {
2931 pos_type from = pos;
2932 locateWord(from, pos, WHOLE_WORD);
2933 if (!lyxrc.spellcheck_continuously && pos - from < 6)
2936 docstring word = asString(from, pos, false);
2937 if (pos - from >= 6)
2938 d->words_.insert(word);
2940 if (!lyxrc.spellcheck_continuously || !speller)
2943 string lang_code = lyxrc.spellchecker_use_alt_lang
2944 ? lyxrc.spellchecker_alt_lang
2945 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2946 WordLangTuple wl(word, lang_code);
2947 SpellChecker::Result res = speller->check(wl);
2948 // ... just ignore any error that the spellchecker reports.
2949 if (!speller->error().empty())
2951 bool const misspelled = res != SpellChecker::OK
2952 && res != SpellChecker::IGNORED_WORD;
2953 d->fontlist_.setMisspelled(from, pos, misspelled);
2955 //lyxerr << word << " ";
2957 //lyxerr << std::endl;
2961 void Paragraph::registerWords()
2963 Private::Words::const_iterator it;
2964 WordList & wl = theWordList();
2965 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2970 void Paragraph::updateWords()
2978 bool Paragraph::isMisspelled(pos_type pos) const
2980 SpellChecker * speller = theSpellChecker();
2981 pos_type from = pos;
2983 locateWord(from, to, WHOLE_WORD);
2984 docstring word = asString(from, to, false);
2988 string lang_code = lyxrc.spellchecker_use_alt_lang
2989 ? lyxrc.spellchecker_alt_lang
2990 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2991 WordLangTuple wl(word, lang_code);
2992 SpellChecker::Result res = speller->check(wl);
2993 // ... just ignore any error that the spellchecker reports.
2994 if (!speller->error().empty())
2997 bool const misspelled = res != SpellChecker::OK
2998 && res != SpellChecker::IGNORED_WORD;
2999 if (lyxrc.spellcheck_continuously)
3000 d->fontlist_.setMisspelled(from, pos, misspelled);