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/convert.h"
56 #include "support/debug.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lstrings.h"
60 #include "support/Messages.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
76 /////////////////////////////////////////////////////////////////////
80 /////////////////////////////////////////////////////////////////////
82 class Paragraph::Private
86 Private(Paragraph * owner, Layout const & layout);
87 /// "Copy constructor"
88 Private(Private const &, Paragraph * owner);
89 /// Copy constructor from \p beg to \p end
90 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
93 void insertChar(pos_type pos, char_type c, Change const & change);
95 /// Output the surrogate pair formed by \p c and \p next to \p os.
96 /// \return the number of characters written.
97 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
100 /// Output a space in appropriate formatting (or a surrogate pair
101 /// if the next character is a combining character).
102 /// \return whether a surrogate pair was output.
103 bool simpleTeXBlanks(OutputParams const &,
104 odocstream &, TexRow & texrow,
106 unsigned int & column,
108 Layout const & style);
110 /// Output consecutive unicode chars, belonging to the same script as
111 /// specified by the latex macro \p ltx, to \p os starting from \p i.
112 /// \return the number of characters written.
113 int writeScriptChars(odocstream & os, docstring const & ltx,
114 Change const &, Encoding const &, pos_type & i);
116 /// This could go to ParagraphParameters if we want to.
117 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
118 OutputParams const &) const;
120 /// This could go to ParagraphParameters if we want to.
121 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
122 OutputParams const &) const;
125 void latexInset(BufferParams const &,
127 TexRow & texrow, OutputParams &,
130 Font const & outerfont,
132 Change & running_change,
133 Layout const & style,
135 unsigned int & column);
138 void latexSpecialChar(
140 OutputParams const & runparams,
141 Font const & running_font,
142 Change const & running_change,
143 Layout const & style,
145 unsigned int & column);
152 unsigned int & column);
154 bool latexSpecialTypewriter(
158 unsigned int & column);
160 bool latexSpecialPhrase(
163 unsigned int & column,
164 OutputParams const & runparams);
167 void validate(LaTeXFeatures & features,
168 Layout const & layout) const;
170 /// Checks if the paragraph contains only text and no inset or font change.
171 bool onlyText(Buffer const & buf, Font const & outerfont,
172 pos_type initial) const;
174 /// match a string against a particular point in the paragraph
175 bool isTextAt(string const & str, pos_type pos) const;
177 /// Which Paragraph owns us?
181 Inset const * inset_owner_;
189 static unsigned int paragraph_id;
191 ParagraphParameters params_;
193 /// for recording and looking up changes
197 InsetList insetlist_;
200 pos_type begin_of_body_;
202 typedef docstring TextContainer;
206 typedef std::set<docstring> Words;
210 Layout const * layout_;
214 // Initialization of the counter for the paragraph id's,
215 unsigned int Paragraph::Private::paragraph_id = 0;
219 struct special_phrase {
225 special_phrase const special_phrases[] = {
226 { "LyX", from_ascii("\\LyX{}"), false },
227 { "TeX", from_ascii("\\TeX{}"), true },
228 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
229 { "LaTeX", from_ascii("\\LaTeX{}"), true },
232 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
237 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
238 : owner_(owner), inset_owner_(0), begin_of_body_(0), layout_(&layout)
240 id_ = paragraph_id++;
245 Paragraph::Private::Private(Private const & p, Paragraph * owner)
246 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
247 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
248 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
251 id_ = paragraph_id++;
255 Paragraph::Private::Private(Private const & p, Paragraph * owner,
256 pos_type beg, pos_type end)
257 : owner_(owner), inset_owner_(p.inset_owner_),
258 params_(p.params_), changes_(p.changes_),
259 insetlist_(p.insetlist_, beg, end),
260 begin_of_body_(p.begin_of_body_), words_(p.words_),
263 id_ = paragraph_id++;
264 if (beg >= pos_type(p.text_.size()))
266 text_ = p.text_.substr(beg, end - beg);
268 FontList::const_iterator fcit = fontlist_.begin();
269 FontList::const_iterator fend = fontlist_.end();
270 for (; fcit != fend; ++fcit) {
271 if (fcit->pos() < beg)
273 if (fcit->pos() >= end) {
274 // Add last entry in the fontlist_.
275 fontlist_.set(text_.size() - 1, fcit->font());
278 // Add a new entry in the fontlist_.
279 fontlist_.set(fcit->pos() - beg, fcit->font());
284 void Paragraph::addChangesToToc(DocIterator const & cdit,
285 Buffer const & buf) const
287 d->changes_.addToToc(cdit, buf);
291 bool Paragraph::isChanged(pos_type start, pos_type end) const
293 LASSERT(start >= 0 && start <= size(), /**/);
294 LASSERT(end > start && end <= size() + 1, /**/);
296 return d->changes_.isChanged(start, end);
300 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
302 // keep the logic here in sync with the logic of eraseChars()
306 Change const change = d->changes_.lookup(size());
307 return change.type == Change::INSERTED && change.author == 0;
311 void Paragraph::setChange(Change const & change)
313 // beware of the imaginary end-of-par character!
314 d->changes_.set(change, 0, size() + 1);
317 * Propagate the change recursively - but not in case of DELETED!
319 * Imagine that your co-author makes changes in an existing inset. He
320 * sends your document to you and you come to the conclusion that the
321 * inset should go completely. If you erase it, LyX must not delete all
322 * text within the inset. Otherwise, the change tracked insertions of
323 * your co-author get lost and there is no way to restore them later.
325 * Conclusion: An inset's content should remain untouched if you delete it
328 if (change.type != Change::DELETED) {
329 for (pos_type pos = 0; pos < size(); ++pos) {
330 if (Inset * inset = getInset(pos))
331 inset->setChange(change);
337 void Paragraph::setChange(pos_type pos, Change const & change)
339 LASSERT(pos >= 0 && pos <= size(), /**/);
340 d->changes_.set(change, pos);
342 // see comment in setChange(Change const &) above
343 if (change.type != Change::DELETED && pos < size())
344 if (Inset * inset = getInset(pos))
345 inset->setChange(change);
349 Change const & Paragraph::lookupChange(pos_type pos) const
351 LASSERT(pos >= 0 && pos <= size(), /**/);
352 return d->changes_.lookup(pos);
356 void Paragraph::acceptChanges(BufferParams const & bparams, pos_type start,
359 LASSERT(start >= 0 && start <= size(), /**/);
360 LASSERT(end > start && end <= size() + 1, /**/);
362 for (pos_type pos = start; pos < end; ++pos) {
363 switch (lookupChange(pos).type) {
364 case Change::UNCHANGED:
365 // accept changes in nested inset
366 if (Inset * inset = getInset(pos))
367 inset->acceptChanges(bparams);
370 case Change::INSERTED:
371 d->changes_.set(Change(Change::UNCHANGED), pos);
372 // also accept changes in nested inset
373 if (Inset * inset = getInset(pos))
374 inset->acceptChanges(bparams);
377 case Change::DELETED:
378 // Suppress access to non-existent
379 // "end-of-paragraph char"
381 eraseChar(pos, false);
392 void Paragraph::rejectChanges(BufferParams const & bparams,
393 pos_type start, pos_type end)
395 LASSERT(start >= 0 && start <= size(), /**/);
396 LASSERT(end > start && end <= size() + 1, /**/);
398 for (pos_type pos = start; pos < end; ++pos) {
399 switch (lookupChange(pos).type) {
400 case Change::UNCHANGED:
401 // reject changes in nested inset
402 if (Inset * inset = getInset(pos))
403 inset->rejectChanges(bparams);
406 case Change::INSERTED:
407 // Suppress access to non-existent
408 // "end-of-paragraph char"
410 eraseChar(pos, false);
416 case Change::DELETED:
417 d->changes_.set(Change(Change::UNCHANGED), pos);
419 // Do NOT reject changes within a deleted inset!
420 // There may be insertions of a co-author inside of it!
428 void Paragraph::Private::insertChar(pos_type pos, char_type c,
429 Change const & change)
431 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
434 changes_.insert(change, pos);
436 // This is actually very common when parsing buffers (and
437 // maybe inserting ascii text)
438 if (pos == pos_type(text_.size())) {
439 // when appending characters, no need to update tables
444 text_.insert(text_.begin() + pos, c);
446 // Update the font table.
447 fontlist_.increasePosAfterPos(pos);
450 insetlist_.increasePosAfterPos(pos);
454 bool Paragraph::insertInset(pos_type pos, Inset * inset,
455 Change const & change)
457 LASSERT(inset, /**/);
458 LASSERT(pos >= 0 && pos <= size(), /**/);
460 // Paragraph::insertInset() can be used in cut/copy/paste operation where
461 // d->inset_owner_ is not set yet.
462 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
465 d->insertChar(pos, META_INSET, change);
466 LASSERT(d->text_[pos] == META_INSET, /**/);
468 // Add a new entry in the insetlist_.
469 d->insetlist_.insert(inset, pos);
474 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
476 LASSERT(pos >= 0 && pos <= size(), return false);
478 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
481 Change change = d->changes_.lookup(pos);
483 // set the character to DELETED if
484 // a) it was previously unchanged or
485 // b) it was inserted by a co-author
487 if (change.type == Change::UNCHANGED ||
488 (change.type == Change::INSERTED && change.author != 0)) {
489 setChange(pos, Change(Change::DELETED));
493 if (change.type == Change::DELETED)
497 // Don't physically access the imaginary end-of-paragraph character.
498 // eraseChar() can only mark it as DELETED. A physical deletion of
499 // end-of-par must be handled externally.
505 d->changes_.erase(pos);
507 // if it is an inset, delete the inset entry
508 if (d->text_[pos] == META_INSET)
509 d->insetlist_.erase(pos);
511 d->text_.erase(d->text_.begin() + pos);
513 // Update the fontlist_
514 d->fontlist_.erase(pos);
516 // Update the insetlist_
517 d->insetlist_.decreasePosAfterPos(pos);
523 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
525 LASSERT(start >= 0 && start <= size(), /**/);
526 LASSERT(end >= start && end <= size() + 1, /**/);
529 for (pos_type count = end - start; count; --count) {
530 if (!eraseChar(i, trackChanges))
537 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
538 char_type next, Encoding const & encoding)
540 // Writing next here may circumvent a possible font change between
541 // c and next. Since next is only output if it forms a surrogate pair
542 // with c we can ignore this:
543 // A font change inside a surrogate pair does not make sense and is
544 // hopefully impossible to input.
545 // FIXME: change tracking
546 // Is this correct WRT change tracking?
547 docstring const latex1 = encoding.latexChar(next);
548 docstring const latex2 = encoding.latexChar(c);
549 if (docstring(1, next) == latex1) {
550 // the encoding supports the combination
551 os << latex2 << latex1;
552 return latex1.length() + latex2.length();
554 os << latex1 << '{' << latex2 << '}';
555 return latex1.length() + latex2.length() + 2;
559 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
560 odocstream & os, TexRow & texrow,
562 unsigned int & column,
564 Layout const & style)
566 if (style.pass_thru || runparams.verbatim)
569 if (i + 1 < int(text_.size())) {
570 char_type next = text_[i + 1];
571 if (Encodings::isCombiningChar(next)) {
572 Encoding const & encoding = *(runparams.encoding);
573 // This space has an accent, so we must always output it.
574 column += latexSurrogatePair(os, ' ', next, encoding) - 1;
579 if (lyxrc.plaintext_linelen > 0
580 && column > lyxrc.plaintext_linelen
582 && text_[i - 1] != ' '
583 && (i + 1 < int(text_.size()))
584 // same in FreeSpacing mode
585 && !owner_->isFreeSpacing()
586 // In typewriter mode, we want to avoid
587 // ! . ? : at the end of a line
588 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
589 && (text_[i - 1] == '.'
590 || text_[i - 1] == '?'
591 || text_[i - 1] == ':'
592 || text_[i - 1] == '!'))) {
595 texrow.start(owner_->id(), i + 1);
597 } else if (style.free_spacing) {
606 int Paragraph::Private::writeScriptChars(odocstream & os,
607 docstring const & ltx,
608 Change const & runningChange,
609 Encoding const & encoding,
612 // FIXME: modifying i here is not very nice...
614 // We only arrive here when a proper language for character text_[i] has
615 // not been specified (i.e., it could not be translated in the current
616 // latex encoding) or its latex translation has been forced, and it
617 // belongs to a known script.
618 // Parameter ltx contains the latex translation of text_[i] as specified
619 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
620 // The latex macro name "textXXX" specifies the script to which text_[i]
621 // belongs and we use it in order to check whether characters from the
622 // same script immediately follow, such that we can collect them in a
623 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
624 // for the first char but only "<spec>" for all subsequent chars.
625 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
626 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
627 string script = to_ascii(ltx.substr(1, brace1 - 1));
630 bool closing_brace = true;
631 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
632 // Correct encoding is being used, so we can avoid \textgreek.
635 closing_brace = false;
637 os << ltx.substr(pos, length);
638 int size = text_.size();
639 while (i + 1 < size) {
640 char_type const next = text_[i + 1];
641 // Stop here if next character belongs to another script
642 // or there is a change in change tracking status.
643 if (!Encodings::isKnownScriptChar(next, script) ||
644 runningChange != owner_->lookupChange(i + 1))
648 FontList::const_iterator cit = fontlist_.begin();
649 FontList::const_iterator end = fontlist_.end();
650 for (; cit != end; ++cit) {
651 if (cit->pos() >= i && !found) {
652 prev_font = cit->font();
655 if (cit->pos() >= i + 1)
658 // Stop here if there is a font attribute or encoding change.
659 if (found && cit != end && prev_font != cit->font())
661 docstring const latex = encoding.latexChar(next);
662 docstring::size_type const b1 =
663 latex.find_first_of(from_ascii("{"));
664 docstring::size_type const b2 =
665 latex.find_last_of(from_ascii("}"));
666 int const len = b2 - b1 - 1;
667 os << latex.substr(b1 + 1, len);
679 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
681 pos_type const len = str.length();
683 // is the paragraph large enough?
684 if (pos + len > int(text_.size()))
687 // does the wanted text start at point?
688 for (string::size_type i = 0; i < str.length(); ++i) {
689 // Caution: direct comparison of characters works only
690 // because str is pure ASCII.
691 if (str[i] != text_[pos + i])
695 return fontlist_.hasChangeInRange(pos, len);
699 void Paragraph::Private::latexInset(
700 BufferParams const & bparams,
703 OutputParams & runparams,
706 Font const & outerfont,
708 Change & running_change,
709 Layout const & style,
711 unsigned int & column)
713 Inset * inset = owner_->getInset(i);
714 LASSERT(inset, /**/);
716 if (style.pass_thru) {
717 inset->plaintext(os, runparams);
721 // FIXME: move this to InsetNewline::latex
722 if (inset->lyxCode() == NEWLINE_CODE) {
723 // newlines are handled differently here than
724 // the default in simpleTeXSpecialChars().
725 if (!style.newline_allowed) {
729 column += running_font.latexWriteEndChanges(
730 os, bparams, runparams,
735 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
738 basefont = owner_->getLayoutFont(bparams, outerfont);
739 running_font = basefont;
741 if (runparams.moving_arg)
746 texrow.start(owner_->id(), i + 1);
750 if (owner_->lookupChange(i).type == Change::DELETED) {
751 if( ++runparams.inDeletedInset == 1)
752 runparams.changeOfDeletedInset = owner_->lookupChange(i);
755 if (inset->canTrackChanges()) {
756 column += Changes::latexMarkChange(os, bparams, running_change,
757 Change(Change::UNCHANGED));
758 running_change = Change(Change::UNCHANGED);
762 odocstream::pos_type const len = os.tellp();
764 if (inset->forceLTR()
765 && running_font.isRightToLeft()
766 // ERT is an exception, it should be output with no decorations at all
767 && inset->lyxCode() != ERT_CODE) {
768 if (running_font.language()->lang() == "farsi")
775 // FIXME: Bug: we can have an empty font change here!
776 // if there has just been a font change, we are going to close it
777 // right now, which means stupid latex code like \textsf{}. AFAIK,
778 // this does not harm dvi output. A minor bug, thus (JMarc)
780 // Some insets cannot be inside a font change command.
781 // However, even such insets *can* be placed in \L or \R
782 // or their equivalents (for RTL language switches), so we don't
783 // close the language in those cases.
784 // ArabTeX, though, cannot handle this special behavior, it seems.
785 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
786 || running_font.language()->lang() == "arabic_arabtex";
787 if (open_font && inset->noFontChange()) {
788 bool closeLanguage = arabtex
789 || basefont.isRightToLeft() == running_font.isRightToLeft();
790 unsigned int count = running_font.latexWriteEndChanges(os,
791 bparams, runparams, basefont, basefont, closeLanguage);
793 // if any font properties were closed, update the running_font,
794 // making sure, however, to leave the language as it was
796 // FIXME: probably a better way to keep track of the old
797 // language, than copying the entire font?
798 Font const copy_font(running_font);
799 basefont = owner_->getLayoutFont(bparams, outerfont);
800 running_font = basefont;
802 running_font.setLanguage(copy_font.language());
803 // leave font open if language is still open
804 open_font = (running_font.language() == basefont.language());
806 runparams.local_font = &basefont;
813 tmp = inset->latex(os, runparams);
814 } catch (EncodingException & e) {
815 // add location information and throw again.
822 if (running_font.language()->lang() == "farsi")
829 for (int j = 0; j < tmp; ++j)
832 texrow.start(owner_->id(), i + 1);
835 column += os.tellp() - len;
838 if (owner_->lookupChange(i).type == Change::DELETED)
839 --runparams.inDeletedInset;
843 void Paragraph::Private::latexSpecialChar(
845 OutputParams const & runparams,
846 Font const & running_font,
847 Change const & running_change,
848 Layout const & style,
850 unsigned int & column)
852 char_type const c = text_[i];
854 if (style.pass_thru) {
856 // FIXME UNICODE: This can fail if c cannot
857 // be encoded in the current encoding.
862 if (runparams.verbatim) {
863 // FIXME UNICODE: This can fail if c cannot
864 // be encoded in the current encoding.
869 // If T1 font encoding is used, use the special
870 // characters it provides.
871 // NOTE: some languages reset the font encoding
873 if (!running_font.language()->internalFontEncoding()
874 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
877 // \tt font needs special treatment
878 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
879 && latexSpecialTypewriter(c, os, i, column))
882 // Otherwise, we use what LaTeX provides us.
885 os << "\\textbackslash{}";
889 os << "\\textless{}";
893 os << "\\textgreater{}";
904 os << "\\char`\\\"{}";
909 case '%': case '#': case '{':
917 os << "\\textasciitilde{}";
922 os << "\\textasciicircum{}";
929 // avoid being mistaken for optional arguments
937 // Blanks are printed before font switching.
938 // Sure? I am not! (try nice-latex)
939 // I am sure it's correct. LyX might be smarter
940 // in the future, but for now, nothing wrong is
946 if (latexSpecialPhrase(os, i, column, runparams))
952 Encoding const & encoding = *(runparams.encoding);
953 if (i + 1 < int(text_.size())) {
954 char_type next = text_[i + 1];
955 if (Encodings::isCombiningChar(next)) {
956 column += latexSurrogatePair(os, c, next, encoding) - 1;
962 docstring const latex = encoding.latexChar(c);
963 if (Encodings::isKnownScriptChar(c, script)
964 && prefixIs(latex, from_ascii("\\" + script)))
965 column += writeScriptChars(os, latex,
966 running_change, encoding, i) - 1;
967 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
968 // Prevent eating of a following
969 // space or command corruption by
970 // following characters
971 column += latex.length() + 1;
974 column += latex.length() - 1;
982 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
983 pos_type i, unsigned int & column)
989 // In T1 encoding, these characters exist
990 // but we should avoid ligatures
991 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
993 os << "\\textcompwordmark{}";
1000 // soul.sty breaks with \char`\"
1001 os << "\\textquotedbl{}";
1010 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1011 pos_type i, unsigned int & column)
1015 // within \ttfamily, "--" is merged to "-" (no endash)
1016 // so we avoid this rather irritating ligature
1017 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1024 // everything else has to be checked separately
1025 // (depending on the encoding)
1032 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1033 unsigned int & column, OutputParams const & runparams)
1035 // FIXME: if we have "LaTeX" with a font
1036 // change in the middle (before the 'T', then
1037 // the "TeX" part is still special cased.
1038 // Really we should only operate this on
1039 // "words" for some definition of word
1041 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1042 if (!isTextAt(special_phrases[pnr].phrase, i))
1044 if (runparams.moving_arg)
1046 os << special_phrases[pnr].macro;
1047 i += special_phrases[pnr].phrase.length() - 1;
1048 column += special_phrases[pnr].macro.length() - 1;
1055 void Paragraph::Private::validate(LaTeXFeatures & features,
1056 Layout const & layout) const
1058 // check the params.
1059 if (!params_.spacing().isDefault())
1060 features.require("setspace");
1063 features.useLayout(layout.name());
1066 fontlist_.validate(features);
1068 // then the indentation
1069 if (!params_.leftIndent().zero())
1070 features.require("ParagraphLeftIndent");
1073 InsetList::const_iterator icit = insetlist_.begin();
1074 InsetList::const_iterator iend = insetlist_.end();
1075 for (; icit != iend; ++icit) {
1077 icit->inset->validate(features);
1078 if (layout.needprotect &&
1079 icit->inset->lyxCode() == FOOT_CODE)
1080 features.require("NeedLyXFootnoteCode");
1084 // then the contents
1085 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1086 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1087 if (!special_phrases[pnr].builtin
1088 && isTextAt(special_phrases[pnr].phrase, i)) {
1089 features.require(special_phrases[pnr].phrase);
1093 Encodings::validate(text_[i], features);
1097 /////////////////////////////////////////////////////////////////////
1101 /////////////////////////////////////////////////////////////////////
1104 Layout const emptyParagraphLayout;
1107 Paragraph::Paragraph()
1108 : d(new Paragraph::Private(this, emptyParagraphLayout))
1115 Paragraph::Paragraph(Paragraph const & par)
1116 : itemdepth(par.itemdepth),
1117 d(new Paragraph::Private(*par.d, this))
1123 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1124 : itemdepth(par.itemdepth),
1125 d(new Paragraph::Private(*par.d, this, beg, end))
1131 Paragraph & Paragraph::operator=(Paragraph const & par)
1133 // needed as we will destroy the private part before copying it
1135 itemdepth = par.itemdepth;
1139 d = new Private(*par.d, this);
1146 Paragraph::~Paragraph()
1153 void Paragraph::write(ostream & os, BufferParams const & bparams,
1154 depth_type & dth) const
1156 // The beginning or end of a deeper (i.e. nested) area?
1157 if (dth != d->params_.depth()) {
1158 if (d->params_.depth() > dth) {
1159 while (d->params_.depth() > dth) {
1160 os << "\n\\begin_deeper";
1164 while (d->params_.depth() < dth) {
1165 os << "\n\\end_deeper";
1171 // First write the layout
1172 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1174 d->params_.write(os);
1176 Font font1(inherit_font, bparams.language);
1178 Change running_change = Change(Change::UNCHANGED);
1181 for (pos_type i = 0; i <= size(); ++i) {
1183 Change change = lookupChange(i);
1184 Changes::lyxMarkChange(os, column, running_change, change);
1185 running_change = change;
1190 // Write font changes
1191 Font const & font2 = getFontSettings(bparams, i);
1192 if (font2 != font1) {
1193 font2.lyxWriteChanges(font1, os);
1198 char_type const c = d->text_[i];
1201 if (Inset const * inset = getInset(i)) {
1202 if (inset->directWrite()) {
1203 // international char, let it write
1204 // code directly so it's shorter in
1210 os << "\\begin_inset ";
1212 os << "\n\\end_inset\n\n";
1218 os << "\n\\backslash\n";
1222 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1229 if ((column > 70 && c == ' ')
1234 // this check is to amend a bug. LyX sometimes
1235 // inserts '\0' this could cause problems.
1237 os << to_utf8(docstring(1, c));
1239 LYXERR0("NUL char in structure.");
1245 os << "\n\\end_layout\n";
1249 void Paragraph::validate(LaTeXFeatures & features) const
1251 d->validate(features, *d->layout_);
1255 void Paragraph::insert(pos_type start, docstring const & str,
1256 Font const & font, Change const & change)
1258 for (size_t i = 0, n = str.size(); i != n ; ++i)
1259 insertChar(start + i, str[i], font, change);
1263 void Paragraph::appendChar(char_type c, Font const & font,
1264 Change const & change)
1267 d->changes_.insert(change, d->text_.size());
1268 // when appending characters, no need to update tables
1269 d->text_.push_back(c);
1270 setFont(d->text_.size() - 1, font);
1274 void Paragraph::appendString(docstring const & s, Font const & font,
1275 Change const & change)
1277 pos_type end = s.size();
1278 size_t oldsize = d->text_.size();
1279 size_t newsize = oldsize + end;
1280 size_t capacity = d->text_.capacity();
1281 if (newsize >= capacity)
1282 d->text_.reserve(max(capacity + 100, newsize));
1284 // when appending characters, no need to update tables
1287 // FIXME: Optimize this!
1288 for (size_t i = oldsize; i != newsize; ++i) {
1290 d->changes_.insert(change, i);
1292 d->fontlist_.set(oldsize, font);
1293 d->fontlist_.set(newsize - 1, font);
1297 void Paragraph::insertChar(pos_type pos, char_type c,
1300 d->insertChar(pos, c, Change(trackChanges ?
1301 Change::INSERTED : Change::UNCHANGED));
1305 void Paragraph::insertChar(pos_type pos, char_type c,
1306 Font const & font, bool trackChanges)
1308 d->insertChar(pos, c, Change(trackChanges ?
1309 Change::INSERTED : Change::UNCHANGED));
1314 void Paragraph::insertChar(pos_type pos, char_type c,
1315 Font const & font, Change const & change)
1317 d->insertChar(pos, c, change);
1322 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1323 Font const & font, Change const & change)
1325 bool const success = insertInset(pos, inset, change);
1326 // Set the font/language of the inset...
1332 void Paragraph::resetFonts(Font const & font)
1334 d->fontlist_.clear();
1335 d->fontlist_.set(0, font);
1336 d->fontlist_.set(d->text_.size() - 1, font);
1339 // Gets uninstantiated font setting at position.
1340 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1344 LYXERR0("pos: " << pos << " size: " << size());
1345 LASSERT(pos <= size(), /**/);
1348 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1349 if (cit != d->fontlist_.end())
1352 if (pos == size() && !empty())
1353 return getFontSettings(bparams, pos - 1);
1355 // Optimisation: avoid a full font instantiation if there is no
1356 // language change from previous call.
1357 static Font previous_font;
1358 static Language const * previous_lang = 0;
1359 Language const * lang = getParLanguage(bparams);
1360 if (lang != previous_lang) {
1361 previous_lang = lang;
1362 previous_font = Font(inherit_font, lang);
1364 return previous_font;
1368 FontSpan Paragraph::fontSpan(pos_type pos) const
1370 LASSERT(pos <= size(), /**/);
1373 FontList::const_iterator cit = d->fontlist_.begin();
1374 FontList::const_iterator end = d->fontlist_.end();
1375 for (; cit != end; ++cit) {
1376 if (cit->pos() >= pos) {
1377 if (pos >= beginOfBody())
1378 return FontSpan(max(start, beginOfBody()),
1381 return FontSpan(start,
1382 min(beginOfBody() - 1,
1385 start = cit->pos() + 1;
1388 // This should not happen, but if so, we take no chances.
1389 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1390 return FontSpan(pos, pos);
1394 // Gets uninstantiated font setting at position 0
1395 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1397 if (!empty() && !d->fontlist_.empty())
1398 return d->fontlist_.begin()->font();
1400 // Optimisation: avoid a full font instantiation if there is no
1401 // language change from previous call.
1402 static Font previous_font;
1403 static Language const * previous_lang = 0;
1404 if (bparams.language != previous_lang) {
1405 previous_lang = bparams.language;
1406 previous_font = Font(inherit_font, bparams.language);
1409 return previous_font;
1413 // Gets the fully instantiated font at a given position in a paragraph
1414 // This is basically the same function as Text::GetFont() in text2.cpp.
1415 // The difference is that this one is used for generating the LaTeX file,
1416 // and thus cosmetic "improvements" are disallowed: This has to deliver
1417 // the true picture of the buffer. (Asger)
1418 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1419 Font const & outerfont) const
1421 LASSERT(pos >= 0, /**/);
1423 Font font = getFontSettings(bparams, pos);
1425 pos_type const body_pos = beginOfBody();
1426 FontInfo & fi = font.fontInfo();
1428 fi.realize(d->layout_->labelfont);
1430 fi.realize(d->layout_->font);
1432 fi.realize(outerfont.fontInfo());
1433 fi.realize(bparams.getFont().fontInfo());
1439 Font const Paragraph::getLabelFont
1440 (BufferParams const & bparams, Font const & outerfont) const
1442 FontInfo tmpfont = d->layout_->labelfont;
1443 tmpfont.realize(outerfont.fontInfo());
1444 tmpfont.realize(bparams.getFont().fontInfo());
1445 return Font(tmpfont, getParLanguage(bparams));
1449 Font const Paragraph::getLayoutFont
1450 (BufferParams const & bparams, Font const & outerfont) const
1452 FontInfo tmpfont = d->layout_->font;
1453 tmpfont.realize(outerfont.fontInfo());
1454 tmpfont.realize(bparams.getFont().fontInfo());
1455 return Font(tmpfont, getParLanguage(bparams));
1459 /// Returns the height of the highest font in range
1460 FontSize Paragraph::highestFontInRange
1461 (pos_type startpos, pos_type endpos, FontSize def_size) const
1463 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1467 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1469 char_type c = d->text_[pos];
1470 if (!lyxrc.rtl_support)
1500 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1506 void Paragraph::setFont(pos_type pos, Font const & font)
1508 LASSERT(pos <= size(), /**/);
1510 // First, reduce font against layout/label font
1511 // Update: The setCharFont() routine in text2.cpp already
1512 // reduces font, so we don't need to do that here. (Asger)
1514 d->fontlist_.set(pos, font);
1518 void Paragraph::makeSameLayout(Paragraph const & par)
1520 d->layout_ = par.d->layout_;
1521 d->params_ = par.d->params_;
1525 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1527 if (isFreeSpacing())
1533 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1534 if (eraseChar(pos, trackChanges))
1540 return count > 0 || pos > 0;
1544 bool Paragraph::hasSameLayout(Paragraph const & par) const
1546 return par.d->layout_ == d->layout_
1547 && d->params_.sameLayout(par.d->params_);
1551 depth_type Paragraph::getDepth() const
1553 return d->params_.depth();
1557 depth_type Paragraph::getMaxDepthAfter() const
1559 if (d->layout_->isEnvironment())
1560 return d->params_.depth() + 1;
1562 return d->params_.depth();
1566 char Paragraph::getAlign() const
1568 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1569 return d->layout_->align;
1571 return d->params_.align();
1575 docstring const & Paragraph::labelString() const
1577 return d->params_.labelString();
1581 // the next two functions are for the manual labels
1582 docstring const Paragraph::getLabelWidthString() const
1584 if (d->layout_->margintype == MARGIN_MANUAL)
1585 return d->params_.labelWidthString();
1587 return _("Senseless with this layout!");
1591 void Paragraph::setLabelWidthString(docstring const & s)
1593 d->params_.labelWidthString(s);
1597 docstring const Paragraph::translateIfPossible(docstring const & s,
1598 BufferParams const & bparams) const
1600 if (!isAscii(s) || s.empty()) {
1601 // This must be a user defined layout. We cannot translate
1602 // this, since gettext accepts only ascii keys.
1605 // Probably standard layout, try to translate
1606 Messages & m = getMessages(getParLanguage(bparams)->code());
1607 return m.get(to_ascii(s));
1611 docstring Paragraph::expandLabel(Layout const & layout,
1612 BufferParams const & bparams, bool process_appendix) const
1614 DocumentClass const & tclass = bparams.documentClass();
1617 if (process_appendix && d->params_.appendix())
1618 fmt = translateIfPossible(layout.labelstring_appendix(),
1621 fmt = translateIfPossible(layout.labelstring(), bparams);
1623 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1624 && !layout.counter.empty())
1625 return tclass.counters().theCounter(layout.counter);
1627 // handle 'inherited level parts' in 'fmt',
1628 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1629 size_t const i = fmt.find('@', 0);
1630 if (i != docstring::npos) {
1631 size_t const j = fmt.find('@', i + 1);
1632 if (j != docstring::npos) {
1633 docstring parent(fmt, i + 1, j - i - 1);
1634 docstring label = from_ascii("??");
1635 if (tclass.hasLayout(parent))
1636 docstring label = expandLabel(tclass[parent], bparams,
1638 fmt = docstring(fmt, 0, i) + label
1639 + docstring(fmt, j + 1, docstring::npos);
1643 return tclass.counters().counterLabel(fmt);
1647 void Paragraph::applyLayout(Layout const & new_layout)
1649 d->layout_ = &new_layout;
1650 LyXAlignment const oldAlign = d->params_.align();
1652 if (!(oldAlign & d->layout_->alignpossible)) {
1653 frontend::Alert::warning(_("Alignment not permitted"),
1654 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1655 d->params_.align(LYX_ALIGN_LAYOUT);
1660 pos_type Paragraph::beginOfBody() const
1662 return d->begin_of_body_;
1666 void Paragraph::setBeginOfBody()
1668 if (d->layout_->labeltype != LABEL_MANUAL) {
1669 d->begin_of_body_ = 0;
1673 // Unroll the first two cycles of the loop
1674 // and remember the previous character to
1675 // remove unnecessary getChar() calls
1677 pos_type end = size();
1678 if (i < end && !isNewline(i)) {
1680 char_type previous_char = 0;
1683 previous_char = d->text_[i];
1684 if (!isNewline(i)) {
1686 while (i < end && previous_char != ' ') {
1691 previous_char = temp;
1697 d->begin_of_body_ = i;
1701 bool Paragraph::forcePlainLayout() const
1703 return inInset().forcePlainLayout();
1707 bool Paragraph::allowParagraphCustomization() const
1709 return inInset().allowParagraphCustomization();
1713 bool Paragraph::usePlainLayout() const
1715 return inInset().usePlainLayout();
1721 // paragraphs inside floats need different alignment tags to avoid
1724 bool noTrivlistCentering(InsetCode code)
1726 return code == FLOAT_CODE
1727 || code == WRAP_CODE
1728 || code == CELL_CODE;
1732 string correction(string const & orig)
1734 if (orig == "flushleft")
1735 return "raggedright";
1736 if (orig == "flushright")
1737 return "raggedleft";
1738 if (orig == "center")
1744 string const corrected_env(string const & suffix, string const & env,
1745 InsetCode code, bool const lastpar)
1747 string output = suffix + "{";
1748 if (noTrivlistCentering(code)) {
1750 // the last paragraph in non-trivlist-aligned
1751 // context is special (to avoid unwanted whitespace)
1752 if (suffix == "\\begin")
1753 return "\\" + correction(env) + "{}";
1756 output += correction(env);
1760 if (suffix == "\\begin")
1766 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1768 if (!contains(str, "\n"))
1769 column += str.size();
1773 column = rsplit(str, tmp, '\n').size();
1780 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1781 odocstream & os, TexRow & texrow,
1782 OutputParams const & runparams) const
1786 if (params_.noindent()) {
1787 os << "\\noindent ";
1791 LyXAlignment const curAlign = params_.align();
1793 if (curAlign == layout_->align)
1797 case LYX_ALIGN_NONE:
1798 case LYX_ALIGN_BLOCK:
1799 case LYX_ALIGN_LAYOUT:
1800 case LYX_ALIGN_SPECIAL:
1802 case LYX_ALIGN_LEFT:
1803 case LYX_ALIGN_RIGHT:
1804 case LYX_ALIGN_CENTER:
1805 if (runparams.moving_arg) {
1812 string const begin_tag = "\\begin";
1813 InsetCode code = owner_->ownerCode();
1814 bool const lastpar = runparams.isLastPar;
1817 case LYX_ALIGN_NONE:
1818 case LYX_ALIGN_BLOCK:
1819 case LYX_ALIGN_LAYOUT:
1820 case LYX_ALIGN_SPECIAL:
1822 case LYX_ALIGN_LEFT: {
1824 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1825 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1827 output = corrected_env(begin_tag, "flushright", code, lastpar);
1828 os << from_ascii(output);
1829 adjust_row_column(output, texrow, column);
1831 } case LYX_ALIGN_RIGHT: {
1833 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1834 output = corrected_env(begin_tag, "flushright", code, lastpar);
1836 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1837 os << from_ascii(output);
1838 adjust_row_column(output, texrow, column);
1840 } case LYX_ALIGN_CENTER: {
1842 output = corrected_env(begin_tag, "center", code, lastpar);
1843 os << from_ascii(output);
1844 adjust_row_column(output, texrow, column);
1853 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1854 odocstream & os, TexRow & texrow,
1855 OutputParams const & runparams) const
1859 switch (params_.align()) {
1860 case LYX_ALIGN_NONE:
1861 case LYX_ALIGN_BLOCK:
1862 case LYX_ALIGN_LAYOUT:
1863 case LYX_ALIGN_SPECIAL:
1865 case LYX_ALIGN_LEFT:
1866 case LYX_ALIGN_RIGHT:
1867 case LYX_ALIGN_CENTER:
1868 if (runparams.moving_arg) {
1875 string const end_tag = "\n\\par\\end";
1876 InsetCode code = owner_->ownerCode();
1877 bool const lastpar = runparams.isLastPar;
1879 switch (params_.align()) {
1880 case LYX_ALIGN_NONE:
1881 case LYX_ALIGN_BLOCK:
1882 case LYX_ALIGN_LAYOUT:
1883 case LYX_ALIGN_SPECIAL:
1885 case LYX_ALIGN_LEFT: {
1887 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1888 output = corrected_env(end_tag, "flushleft", code, lastpar);
1890 output = corrected_env(end_tag, "flushright", code, lastpar);
1891 os << from_ascii(output);
1892 adjust_row_column(output, texrow, column);
1894 } case LYX_ALIGN_RIGHT: {
1896 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1897 output = corrected_env(end_tag, "flushright", code, lastpar);
1899 output = corrected_env(end_tag, "flushleft", code, lastpar);
1900 os << from_ascii(output);
1901 adjust_row_column(output, texrow, column);
1903 } case LYX_ALIGN_CENTER: {
1905 output = corrected_env(end_tag, "center", code, lastpar);
1906 os << from_ascii(output);
1907 adjust_row_column(output, texrow, column);
1916 // This one spits out the text of the paragraph
1917 bool Paragraph::latex(BufferParams const & bparams,
1918 Font const & outerfont,
1919 odocstream & os, TexRow & texrow,
1920 OutputParams const & runparams,
1921 int start_pos, int end_pos) const
1923 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1925 bool return_value = false;
1927 bool const allowcust = allowParagraphCustomization();
1929 // FIXME This check should not be needed. Perhaps issue an
1930 // error if it triggers.
1931 Layout const & style = forcePlainLayout() ?
1932 bparams.documentClass().plainLayout() : *d->layout_;
1934 // Current base font for all inherited font changes, without any
1935 // change caused by an individual character, except for the language:
1936 // It is set to the language of the first character.
1937 // As long as we are in the label, this font is the base font of the
1938 // label. Before the first body character it is set to the base font
1942 // Maybe we have to create a optional argument.
1943 pos_type body_pos = beginOfBody();
1944 unsigned int column = 0;
1947 // the optional argument is kept in curly brackets in
1948 // case it contains a ']'
1951 basefont = getLabelFont(bparams, outerfont);
1953 basefont = getLayoutFont(bparams, outerfont);
1956 // Which font is currently active?
1957 Font running_font(basefont);
1958 // Do we have an open font change?
1959 bool open_font = false;
1961 Change runningChange = Change(Change::UNCHANGED);
1963 texrow.start(id(), 0);
1965 // if the paragraph is empty, the loop will not be entered at all
1967 if (style.isCommand()) {
1972 column += d->startTeXParParams(bparams, os, texrow,
1976 for (pos_type i = 0; i < size(); ++i) {
1977 // First char in paragraph or after label?
1978 if (i == body_pos) {
1981 column += running_font.latexWriteEndChanges(
1982 os, bparams, runparams,
1983 basefont, basefont);
1986 basefont = getLayoutFont(bparams, outerfont);
1987 running_font = basefont;
1989 column += Changes::latexMarkChange(os, bparams,
1990 runningChange, Change(Change::UNCHANGED));
1991 runningChange = Change(Change::UNCHANGED);
1996 if (style.isCommand()) {
2002 column += d->startTeXParParams(bparams, os,
2007 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2010 if (bparams.outputChanges && runningChange != change) {
2012 column += running_font.latexWriteEndChanges(
2013 os, bparams, runparams, basefont, basefont);
2016 basefont = getLayoutFont(bparams, outerfont);
2017 running_font = basefont;
2019 column += Changes::latexMarkChange(os, bparams, runningChange, change);
2020 runningChange = change;
2023 // do not output text which is marked deleted
2024 // if change tracking output is disabled
2025 if (!bparams.outputChanges && change.type == Change::DELETED) {
2031 // Fully instantiated font
2032 Font const font = getFont(bparams, i, outerfont);
2034 Font const last_font = running_font;
2036 // Do we need to close the previous font?
2038 (font != running_font ||
2039 font.language() != running_font.language()))
2041 column += running_font.latexWriteEndChanges(
2042 os, bparams, runparams, basefont,
2043 (i == body_pos-1) ? basefont : font);
2044 running_font = basefont;
2048 // close babel's font environment before opening CJK.
2049 if (!running_font.language()->babel().empty() &&
2050 font.language()->encoding()->package() == Encoding::CJK) {
2051 string end_tag = subst(lyxrc.language_command_end,
2053 running_font.language()->babel());
2054 os << from_ascii(end_tag);
2055 column += end_tag.length();
2058 // Switch file encoding if necessary (and allowed)
2059 if (!runparams.verbatim &&
2060 runparams.encoding->package() != Encoding::none &&
2061 font.language()->encoding()->package() != Encoding::none) {
2062 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2063 runparams, *(font.language()->encoding()));
2064 if (enc_switch.first) {
2065 column += enc_switch.second;
2066 runparams.encoding = font.language()->encoding();
2070 char_type const c = d->text_[i];
2072 // Do we need to change font?
2073 if ((font != running_font ||
2074 font.language() != running_font.language()) &&
2077 odocstringstream ods;
2078 column += font.latexWriteStartChanges(ods, bparams,
2079 runparams, basefont,
2081 running_font = font;
2083 docstring fontchange = ods.str();
2084 // check if the fontchange ends with a trailing blank
2085 // (like "\small " (see bug 3382)
2086 if (suffixIs(fontchange, ' ') && c == ' ')
2087 os << fontchange.substr(0, fontchange.size() - 1)
2088 << from_ascii("{}");
2093 // FIXME: think about end_pos implementation...
2094 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2095 // FIXME: integrate this case in latexSpecialChar
2096 // Do not print the separation of the optional argument
2097 // if style.pass_thru is false. This works because
2098 // latexSpecialChar ignores spaces if
2099 // style.pass_thru is false.
2100 if (i != body_pos - 1) {
2101 if (d->simpleTeXBlanks(
2102 runparams, os, texrow,
2103 i, column, font, style)) {
2104 // A surrogate pair was output. We
2105 // must not call latexSpecialChar
2106 // in this iteration, since it would output
2107 // the combining character again.
2114 OutputParams rp = runparams;
2115 rp.free_spacing = style.free_spacing;
2116 rp.local_font = &font;
2117 rp.intitle = style.intitle;
2119 // Two major modes: LaTeX or plain
2120 // Handle here those cases common to both modes
2121 // and then split to handle the two modes separately.
2122 if (c == META_INSET) {
2123 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2124 d->latexInset(bparams, os,
2125 texrow, rp, running_font,
2126 basefont, outerfont, open_font,
2127 runningChange, style, i, column);
2130 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2132 d->latexSpecialChar(os, rp, running_font, runningChange,
2134 } catch (EncodingException & e) {
2135 if (runparams.dryrun) {
2136 os << "<" << _("LyX Warning: ")
2137 << _("uncodable character") << " '";
2141 // add location information and throw again.
2150 // Set the encoding to that returned from latexSpecialChar (see
2151 // comment for encoding member in OutputParams.h)
2152 runparams.encoding = rp.encoding;
2155 // If we have an open font definition, we have to close it
2157 #ifdef FIXED_LANGUAGE_END_DETECTION
2160 .latexWriteEndChanges(os, bparams, runparams,
2162 next_->getFont(bparams, 0, outerfont));
2164 running_font.latexWriteEndChanges(os, bparams,
2165 runparams, basefont, basefont);
2168 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2169 //FIXME: there as we start another \selectlanguage with the next paragraph if
2170 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2171 running_font.latexWriteEndChanges(os, bparams, runparams,
2172 basefont, basefont);
2176 column += Changes::latexMarkChange(os, bparams, runningChange, Change(Change::UNCHANGED));
2178 // Needed if there is an optional argument but no contents.
2179 if (body_pos > 0 && body_pos == size()) {
2181 return_value = false;
2185 column += d->endTeXParParams(bparams, os, texrow,
2189 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2190 return return_value;
2194 bool Paragraph::emptyTag() const
2196 for (pos_type i = 0; i < size(); ++i) {
2197 if (Inset const * inset = getInset(i)) {
2198 InsetCode lyx_code = inset->lyxCode();
2199 if (lyx_code != TOC_CODE &&
2200 lyx_code != INCLUDE_CODE &&
2201 lyx_code != GRAPHICS_CODE &&
2202 lyx_code != ERT_CODE &&
2203 lyx_code != LISTINGS_CODE &&
2204 lyx_code != FLOAT_CODE &&
2205 lyx_code != TABULAR_CODE) {
2209 char_type c = d->text_[i];
2210 if (c != ' ' && c != '\t')
2218 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2221 for (pos_type i = 0; i < size(); ++i) {
2222 if (Inset const * inset = getInset(i)) {
2223 InsetCode lyx_code = inset->lyxCode();
2224 if (lyx_code == LABEL_CODE) {
2225 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2226 docstring const & id = il->getParam("name");
2227 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2235 pos_type Paragraph::firstWord(odocstream & os, OutputParams const & runparams)
2239 for (i = 0; i < size(); ++i) {
2240 if (Inset const * inset = getInset(i)) {
2241 inset->docbook(os, runparams);
2243 char_type c = d->text_[i];
2246 os << sgml::escapeChar(c);
2253 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2256 pos_type size = text_.size();
2257 for (pos_type i = initial; i < size; ++i) {
2258 Font font = owner_->getFont(buf.params(), i, outerfont);
2259 if (text_[i] == META_INSET)
2261 if (i != initial && font != font_old)
2270 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2272 OutputParams const & runparams,
2273 Font const & outerfont,
2274 pos_type initial) const
2276 bool emph_flag = false;
2278 Layout const & style = *d->layout_;
2280 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2282 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2285 // parsing main loop
2286 for (pos_type i = initial; i < size(); ++i) {
2287 Font font = getFont(buf.params(), i, outerfont);
2289 // handle <emphasis> tag
2290 if (font_old.emph() != font.fontInfo().emph()) {
2291 if (font.fontInfo().emph() == FONT_ON) {
2294 } else if (i != initial) {
2295 os << "</emphasis>";
2300 if (Inset const * inset = getInset(i)) {
2301 inset->docbook(os, runparams);
2303 char_type c = d->text_[i];
2305 if (style.pass_thru)
2308 os << sgml::escapeChar(c);
2310 font_old = font.fontInfo();
2314 os << "</emphasis>";
2317 if (style.free_spacing)
2319 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2324 bool Paragraph::isHfill(pos_type pos) const
2326 Inset const * inset = getInset(pos);
2327 return inset && (inset->lyxCode() == SPACE_CODE &&
2328 inset->isStretchableSpace());
2332 bool Paragraph::isNewline(pos_type pos) const
2334 Inset const * inset = getInset(pos);
2335 return inset && inset->lyxCode() == NEWLINE_CODE;
2339 bool Paragraph::isLineSeparator(pos_type pos) const
2341 char_type const c = d->text_[pos];
2342 if (isLineSeparatorChar(c))
2344 Inset const * inset = getInset(pos);
2345 return inset && inset->isLineSeparator();
2349 /// Used by the spellchecker
2350 bool Paragraph::isLetter(pos_type pos) const
2352 if (Inset const * inset = getInset(pos))
2353 return inset->isLetter();
2354 char_type const c = d->text_[pos];
2355 // We want to pass the ' and escape chars to the spellchecker
2356 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2357 return (isLetterChar(c) || isDigit(c) || contains(quote, c))
2358 && (!d->inset_owner_ || d->inset_owner_->allowSpellCheck())
2364 bool Paragraph::isChar(pos_type pos) const
2366 if (Inset const * inset = getInset(pos))
2367 return inset->isChar();
2368 char_type const c = d->text_[pos];
2369 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2373 bool Paragraph::isSpace(pos_type pos) const
2375 if (Inset const * inset = getInset(pos))
2376 return inset->isSpace();
2377 char_type const c = d->text_[pos];
2378 return lyx::isSpace(c);
2383 Paragraph::getParLanguage(BufferParams const & bparams) const
2386 return getFirstFontSettings(bparams).language();
2387 // FIXME: we should check the prev par as well (Lgb)
2388 return bparams.language;
2392 bool Paragraph::isRTL(BufferParams const & bparams) const
2394 return lyxrc.rtl_support
2395 && getParLanguage(bparams)->rightToLeft()
2396 && ownerCode() != ERT_CODE
2397 && ownerCode() != LISTINGS_CODE;
2401 void Paragraph::changeLanguage(BufferParams const & bparams,
2402 Language const * from, Language const * to)
2404 // change language including dummy font change at the end
2405 for (pos_type i = 0; i <= size(); ++i) {
2406 Font font = getFontSettings(bparams, i);
2407 if (font.language() == from) {
2408 font.setLanguage(to);
2415 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2417 Language const * doc_language = bparams.language;
2418 FontList::const_iterator cit = d->fontlist_.begin();
2419 FontList::const_iterator end = d->fontlist_.end();
2421 for (; cit != end; ++cit)
2422 if (cit->font().language() != ignore_language &&
2423 cit->font().language() != latex_language &&
2424 cit->font().language() != doc_language)
2430 docstring Paragraph::asString(int options) const
2432 return asString(0, size(), options);
2436 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2438 odocstringstream os;
2441 && options & AS_STR_LABEL
2442 && !d->params_.labelString().empty())
2443 os << d->params_.labelString() << ' ';
2445 for (pos_type i = beg; i < end; ++i) {
2446 char_type const c = d->text_[i];
2447 if (isPrintable(c) || c == '\t'
2448 || (c == '\n' && options & AS_STR_NEWLINES))
2450 else if (c == META_INSET && options & AS_STR_INSETS)
2451 getInset(i)->tocString(os);
2458 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2460 odocstringstream os;
2463 && options & AS_STR_LABEL
2464 && !d->params_.labelString().empty())
2465 os << d->params_.labelString() << ' ';
2467 for (pos_type i = beg; i < end; ++i) {
2468 char_type const c = d->text_[i];
2469 if (isPrintable(c) || c == '\t'
2470 || (c == '\n' && options & AS_STR_NEWLINES))
2472 else if (c == META_INSET && options & AS_STR_INSETS) {
2473 getInset(i)->plaintext(os, runparams);
2481 void Paragraph::setInsetOwner(Inset const * inset)
2483 d->inset_owner_ = inset;
2487 int Paragraph::id() const
2493 Layout const & Paragraph::layout() const
2499 void Paragraph::setLayout(Layout const & layout)
2501 d->layout_ = &layout;
2505 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2507 setLayout(tc.defaultLayout());
2511 void Paragraph::setPlainLayout(DocumentClass const & tc)
2513 setLayout(tc.plainLayout());
2517 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2519 if (usePlainLayout())
2520 setPlainLayout(tclass);
2522 setDefaultLayout(tclass);
2526 Inset const & Paragraph::inInset() const
2528 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2529 _("Memory problem"), _("Paragraph not properly initialized")));
2530 return *d->inset_owner_;
2534 InsetCode Paragraph::ownerCode() const
2536 return d->inset_owner_ ? d->inset_owner_->lyxCode() : NO_CODE;
2540 ParagraphParameters & Paragraph::params()
2546 ParagraphParameters const & Paragraph::params() const
2552 bool Paragraph::isFreeSpacing() const
2554 if (d->layout_->free_spacing)
2556 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2560 bool Paragraph::allowEmpty() const
2562 if (d->layout_->keepempty)
2564 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2568 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2570 if (!Encodings::isArabicChar(c))
2573 char_type prev_char = ' ';
2574 char_type next_char = ' ';
2576 for (pos_type i = pos - 1; i >= 0; --i) {
2577 char_type const par_char = d->text_[i];
2578 if (!Encodings::isArabicComposeChar(par_char)) {
2579 prev_char = par_char;
2584 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2585 char_type const par_char = d->text_[i];
2586 if (!Encodings::isArabicComposeChar(par_char)) {
2587 next_char = par_char;
2592 if (Encodings::isArabicChar(next_char)) {
2593 if (Encodings::isArabicChar(prev_char) &&
2594 !Encodings::isArabicSpecialChar(prev_char))
2595 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2597 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2599 if (Encodings::isArabicChar(prev_char) &&
2600 !Encodings::isArabicSpecialChar(prev_char))
2601 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2603 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2608 int Paragraph::checkBiblio(Buffer const & buffer)
2611 // This is getting more and more a mess. ...We really should clean
2612 // up this bibitem issue for 1.6. See also bug 2743.
2614 // Add bibitem insets if necessary
2615 if (d->layout_->labeltype != LABEL_BIBLIO)
2618 bool hasbibitem = !d->insetlist_.empty()
2619 // Insist on it being in pos 0
2620 && d->text_[0] == META_INSET
2621 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2623 bool track_changes = buffer.params().trackChanges;
2628 // remove a bibitem in pos != 0
2629 // restore it later in pos 0 if necessary
2630 // (e.g. if a user inserts contents _before_ the item)
2631 // we're assuming there's only one of these, which there
2633 int erasedInsetPosition = -1;
2634 InsetList::iterator it = d->insetlist_.begin();
2635 InsetList::iterator end = d->insetlist_.end();
2636 for (; it != end; ++it)
2637 if (it->inset->lyxCode() == BIBITEM_CODE
2639 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2640 oldkey = olditem->getParam("key");
2641 oldlabel = olditem->getParam("label");
2642 erasedInsetPosition = it->pos;
2643 eraseChar(erasedInsetPosition, track_changes);
2647 // There was an InsetBibitem at the beginning, and we didn't
2648 // have to erase one.
2649 if (hasbibitem && erasedInsetPosition < 0)
2652 // There was an InsetBibitem at the beginning and we did have to
2653 // erase one. So we give its properties to the beginning inset.
2655 InsetBibitem * inset =
2656 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2657 if (!oldkey.empty())
2658 inset->setParam("key", oldkey);
2659 inset->setParam("label", oldlabel);
2660 return -erasedInsetPosition;
2663 // There was no inset at the beginning, so we need to create one with
2664 // the key and label of the one we erased.
2665 InsetBibitem * inset =
2666 new InsetBibitem(buffer, InsetCommandParams(BIBITEM_CODE));
2667 // restore values of previously deleted item in this par.
2668 if (!oldkey.empty())
2669 inset->setParam("key", oldkey);
2670 inset->setParam("label", oldlabel);
2671 insertInset(0, static_cast<Inset *>(inset),
2672 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2678 void Paragraph::checkAuthors(AuthorList const & authorList)
2680 d->changes_.checkAuthors(authorList);
2684 bool Paragraph::isUnchanged(pos_type pos) const
2686 return lookupChange(pos).type == Change::UNCHANGED;
2690 bool Paragraph::isInserted(pos_type pos) const
2692 return lookupChange(pos).type == Change::INSERTED;
2696 bool Paragraph::isDeleted(pos_type pos) const
2698 return lookupChange(pos).type == Change::DELETED;
2702 InsetList const & Paragraph::insetList() const
2704 return d->insetlist_;
2708 void Paragraph::setBuffer(Buffer & b)
2710 d->insetlist_.setBuffer(b);
2714 Inset * Paragraph::releaseInset(pos_type pos)
2716 Inset * inset = d->insetlist_.release(pos);
2717 /// does not honour change tracking!
2718 eraseChar(pos, false);
2723 Inset * Paragraph::getInset(pos_type pos)
2725 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2726 ? d->insetlist_.get(pos) : 0;
2730 Inset const * Paragraph::getInset(pos_type pos) const
2732 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2733 ? d->insetlist_.get(pos) : 0;
2737 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2738 pos_type & right, TextCase action)
2740 // process sequences of modified characters; in change
2741 // tracking mode, this approach results in much better
2742 // usability than changing case on a char-by-char basis
2745 bool const trackChanges = bparams.trackChanges;
2747 bool capitalize = true;
2749 for (; pos < right; ++pos) {
2750 char_type oldChar = d->text_[pos];
2751 char_type newChar = oldChar;
2753 // ignore insets and don't play with deleted text!
2754 if (oldChar != META_INSET && !isDeleted(pos)) {
2756 case text_lowercase:
2757 newChar = lowercase(oldChar);
2759 case text_capitalization:
2761 newChar = uppercase(oldChar);
2765 case text_uppercase:
2766 newChar = uppercase(oldChar);
2771 if (!isLetter(pos) || isDeleted(pos)) {
2772 // permit capitalization again
2776 if (oldChar != newChar)
2779 if (oldChar == newChar || pos == right - 1) {
2780 if (oldChar != newChar) {
2781 // step behind the changing area
2784 int erasePos = pos - changes.size();
2785 for (size_t i = 0; i < changes.size(); i++) {
2786 insertChar(pos, changes[i],
2787 getFontSettings(bparams,
2790 if (!eraseChar(erasePos, trackChanges)) {
2793 ++right; // expand selection
2802 bool Paragraph::find(docstring const & str, bool cs, bool mw,
2803 pos_type pos, bool del) const
2805 int const strsize = str.length();
2807 pos_type const parsize = d->text_.size();
2808 for (i = 0; pos + i < parsize; ++i) {
2811 if (cs && str[i] != d->text_[pos + i])
2813 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
2815 if (!del && isDeleted(pos + i))
2822 // if necessary, check whether string matches word
2824 if (pos > 0 && isLetter(pos - 1))
2826 if (pos + strsize < parsize
2827 && isLetter(pos + strsize))
2835 char_type Paragraph::getChar(pos_type pos) const
2837 return d->text_[pos];
2841 pos_type Paragraph::size() const
2843 return d->text_.size();
2847 bool Paragraph::empty() const
2849 return d->text_.empty();
2853 bool Paragraph::isInset(pos_type pos) const
2855 return d->text_[pos] == META_INSET;
2859 bool Paragraph::isSeparator(pos_type pos) const
2861 //FIXME: Are we sure this can be the only separator?
2862 return d->text_[pos] == ' ';
2866 void Paragraph::deregisterWords()
2868 Private::Words::const_iterator it;
2869 WordList & wl = theWordList();
2870 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2876 void Paragraph::locateWord(pos_type & from, pos_type & to,
2877 word_location const loc) const
2880 case WHOLE_WORD_STRICT:
2881 if (from == 0 || from == size()
2883 || !isLetter(from - 1)) {
2887 // no break here, we go to the next
2890 // If we are already at the beginning of a word, do nothing
2891 if (!from || !isLetter(from - 1))
2893 // no break here, we go to the next
2896 // always move the cursor to the beginning of previous word
2897 while (from && isLetter(from - 1))
2901 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
2904 // no need to move the 'from' cursor
2908 while (to < size() && isLetter(to))
2913 void Paragraph::collectWords()
2915 SpellChecker * speller = theSpellChecker();
2917 //lyxerr << "Words: ";
2918 pos_type n = size();
2919 for (pos_type pos = 0; pos < n; ++pos) {
2922 pos_type from = pos;
2923 locateWord(from, pos, WHOLE_WORD);
2924 if (!lyxrc.spellcheck_continuously && pos - from < 6)
2927 docstring word = asString(from, pos, false);
2928 if (pos - from >= 6)
2929 d->words_.insert(word);
2931 if (!lyxrc.spellcheck_continuously || !speller)
2934 string lang_code = lyxrc.spellchecker_use_alt_lang
2935 ? lyxrc.spellchecker_alt_lang
2936 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2937 WordLangTuple wl(word, lang_code);
2938 SpellChecker::Result res = speller->check(wl);
2939 // ... just ignore any error that the spellchecker reports.
2940 if (!speller->error().empty())
2942 bool const misspelled = res != SpellChecker::OK
2943 && res != SpellChecker::IGNORED_WORD;
2944 d->fontlist_.setMisspelled(from, pos, misspelled);
2946 //lyxerr << word << " ";
2948 //lyxerr << std::endl;
2952 void Paragraph::registerWords()
2954 Private::Words::const_iterator it;
2955 WordList & wl = theWordList();
2956 for (it = d->words_.begin(); it != d->words_.end(); ++it)
2961 void Paragraph::updateWords()
2969 bool Paragraph::isMisspelled(pos_type pos) const
2971 SpellChecker * speller = theSpellChecker();
2972 pos_type from = pos;
2974 locateWord(from, to, WHOLE_WORD);
2975 docstring word = asString(from, to, false);
2979 string lang_code = lyxrc.spellchecker_use_alt_lang
2980 ? lyxrc.spellchecker_alt_lang
2981 : getFontSettings(d->inset_owner_->buffer().params(), from).language()->code();
2982 WordLangTuple wl(word, lang_code);
2983 SpellChecker::Result res = speller->check(wl);
2984 // ... just ignore any error that the spellchecker reports.
2985 if (!speller->error().empty())
2988 bool const misspelled = res != SpellChecker::OK
2989 && res != SpellChecker::IGNORED_WORD;
2990 if (lyxrc.spellcheck_continuously)
2991 d->fontlist_.setMisspelled(from, pos, misspelled);