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 Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.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,
98 OutputParams const &);
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) 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;
177 InsetCode ownerCode() const
179 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
182 /// Which Paragraph owns us?
186 Inset const * inset_owner_;
195 ParagraphParameters params_;
197 /// for recording and looking up changes
201 InsetList insetlist_;
204 pos_type begin_of_body_;
206 typedef docstring TextContainer;
210 typedef set<docstring> Words;
212 map<Language, Words> words_;
214 Layout const * layout_;
220 struct special_phrase {
226 special_phrase const special_phrases[] = {
227 { "LyX", from_ascii("\\LyX{}"), false },
228 { "TeX", from_ascii("\\TeX{}"), true },
229 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
230 { "LaTeX", from_ascii("\\LaTeX{}"), true },
233 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
238 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
239 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
245 // Initialization of the counter for the paragraph id's,
247 // FIXME: There should be a more intelligent way to generate and use the
248 // paragraph ids per buffer instead a global static counter for all InsetText
249 // in the running program.
250 static int paragraph_id = -1;
252 Paragraph::Private::Private(Private const & p, Paragraph * owner)
253 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
254 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
255 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
258 id_ = ++paragraph_id;
262 Paragraph::Private::Private(Private const & p, Paragraph * owner,
263 pos_type beg, pos_type end)
264 : owner_(owner), inset_owner_(p.inset_owner_),
265 params_(p.params_), changes_(p.changes_),
266 insetlist_(p.insetlist_, beg, end),
267 begin_of_body_(p.begin_of_body_), words_(p.words_),
270 id_ = ++paragraph_id;
271 if (beg >= pos_type(p.text_.size()))
273 text_ = p.text_.substr(beg, end - beg);
275 FontList::const_iterator fcit = fontlist_.begin();
276 FontList::const_iterator fend = fontlist_.end();
277 for (; fcit != fend; ++fcit) {
278 if (fcit->pos() < beg)
280 if (fcit->pos() >= end) {
281 // Add last entry in the fontlist_.
282 fontlist_.set(text_.size() - 1, fcit->font());
285 // Add a new entry in the fontlist_.
286 fontlist_.set(fcit->pos() - beg, fcit->font());
291 void Paragraph::addChangesToToc(DocIterator const & cdit,
292 Buffer const & buf) const
294 d->changes_.addToToc(cdit, buf);
298 bool Paragraph::isDeleted(pos_type start, pos_type end) const
300 LASSERT(start >= 0 && start <= size(), /**/);
301 LASSERT(end > start && end <= size() + 1, /**/);
303 return d->changes_.isDeleted(start, end);
307 bool Paragraph::isChanged(pos_type start, pos_type end) const
309 LASSERT(start >= 0 && start <= size(), /**/);
310 LASSERT(end > start && end <= size() + 1, /**/);
312 return d->changes_.isChanged(start, end);
316 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
318 // keep the logic here in sync with the logic of eraseChars()
322 Change const change = d->changes_.lookup(size());
323 return change.inserted() && change.currentAuthor();
327 void Paragraph::setChange(Change const & change)
329 // beware of the imaginary end-of-par character!
330 d->changes_.set(change, 0, size() + 1);
333 * Propagate the change recursively - but not in case of DELETED!
335 * Imagine that your co-author makes changes in an existing inset. He
336 * sends your document to you and you come to the conclusion that the
337 * inset should go completely. If you erase it, LyX must not delete all
338 * text within the inset. Otherwise, the change tracked insertions of
339 * your co-author get lost and there is no way to restore them later.
341 * Conclusion: An inset's content should remain untouched if you delete it
344 if (!change.deleted()) {
345 for (pos_type pos = 0; pos < size(); ++pos) {
346 if (Inset * inset = getInset(pos))
347 inset->setChange(change);
353 void Paragraph::setChange(pos_type pos, Change const & change)
355 LASSERT(pos >= 0 && pos <= size(), /**/);
356 d->changes_.set(change, pos);
358 // see comment in setChange(Change const &) above
359 if (!change.deleted() && pos < size())
360 if (Inset * inset = getInset(pos))
361 inset->setChange(change);
365 Change const & Paragraph::lookupChange(pos_type pos) const
367 LASSERT(pos >= 0 && pos <= size(), /**/);
368 return d->changes_.lookup(pos);
372 void Paragraph::acceptChanges(pos_type start, pos_type end)
374 LASSERT(start >= 0 && start <= size(), /**/);
375 LASSERT(end > start && end <= size() + 1, /**/);
377 for (pos_type pos = start; pos < end; ++pos) {
378 switch (lookupChange(pos).type) {
379 case Change::UNCHANGED:
380 // accept changes in nested inset
381 if (Inset * inset = getInset(pos))
382 inset->acceptChanges();
385 case Change::INSERTED:
386 d->changes_.set(Change(Change::UNCHANGED), pos);
387 // also accept changes in nested inset
388 if (Inset * inset = getInset(pos))
389 inset->acceptChanges();
392 case Change::DELETED:
393 // Suppress access to non-existent
394 // "end-of-paragraph char"
396 eraseChar(pos, false);
407 void Paragraph::rejectChanges(pos_type start, pos_type end)
409 LASSERT(start >= 0 && start <= size(), /**/);
410 LASSERT(end > start && end <= size() + 1, /**/);
412 for (pos_type pos = start; pos < end; ++pos) {
413 switch (lookupChange(pos).type) {
414 case Change::UNCHANGED:
415 // reject changes in nested inset
416 if (Inset * inset = getInset(pos))
417 inset->rejectChanges();
420 case Change::INSERTED:
421 // Suppress access to non-existent
422 // "end-of-paragraph char"
424 eraseChar(pos, false);
430 case Change::DELETED:
431 d->changes_.set(Change(Change::UNCHANGED), pos);
433 // Do NOT reject changes within a deleted inset!
434 // There may be insertions of a co-author inside of it!
442 void Paragraph::Private::insertChar(pos_type pos, char_type c,
443 Change const & change)
445 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
448 changes_.insert(change, pos);
450 // This is actually very common when parsing buffers (and
451 // maybe inserting ascii text)
452 if (pos == pos_type(text_.size())) {
453 // when appending characters, no need to update tables
458 text_.insert(text_.begin() + pos, c);
460 // Update the font table.
461 fontlist_.increasePosAfterPos(pos);
464 insetlist_.increasePosAfterPos(pos);
468 bool Paragraph::insertInset(pos_type pos, Inset * inset,
469 Change const & change)
471 LASSERT(inset, /**/);
472 LASSERT(pos >= 0 && pos <= size(), /**/);
474 // Paragraph::insertInset() can be used in cut/copy/paste operation where
475 // d->inset_owner_ is not set yet.
476 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
479 d->insertChar(pos, META_INSET, change);
480 LASSERT(d->text_[pos] == META_INSET, /**/);
482 // Add a new entry in the insetlist_.
483 d->insetlist_.insert(inset, pos);
488 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
490 LASSERT(pos >= 0 && pos <= size(), return false);
492 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
495 Change change = d->changes_.lookup(pos);
497 // set the character to DELETED if
498 // a) it was previously unchanged or
499 // b) it was inserted by a co-author
501 if (!change.changed() ||
502 (change.inserted() && !change.currentAuthor())) {
503 setChange(pos, Change(Change::DELETED));
507 if (change.deleted())
511 // Don't physically access the imaginary end-of-paragraph character.
512 // eraseChar() can only mark it as DELETED. A physical deletion of
513 // end-of-par must be handled externally.
519 d->changes_.erase(pos);
521 // if it is an inset, delete the inset entry
522 if (d->text_[pos] == META_INSET)
523 d->insetlist_.erase(pos);
525 d->text_.erase(d->text_.begin() + pos);
527 // Update the fontlist_
528 d->fontlist_.erase(pos);
530 // Update the insetlist_
531 d->insetlist_.decreasePosAfterPos(pos);
537 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
539 LASSERT(start >= 0 && start <= size(), /**/);
540 LASSERT(end >= start && end <= size() + 1, /**/);
543 for (pos_type count = end - start; count; --count) {
544 if (!eraseChar(i, trackChanges))
551 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
552 char_type next, OutputParams const & runparams)
554 // Writing next here may circumvent a possible font change between
555 // c and next. Since next is only output if it forms a surrogate pair
556 // with c we can ignore this:
557 // A font change inside a surrogate pair does not make sense and is
558 // hopefully impossible to input.
559 // FIXME: change tracking
560 // Is this correct WRT change tracking?
561 Encoding const & encoding = *(runparams.encoding);
562 docstring const latex1 = encoding.latexChar(next);
563 docstring const latex2 = encoding.latexChar(c);
564 if (docstring(1, next) == latex1) {
565 // the encoding supports the combination
566 os << latex2 << latex1;
567 return latex1.length() + latex2.length();
568 } else if (runparams.local_font &&
569 runparams.local_font->language()->lang() == "polutonikogreek") {
570 // polutonikogreek only works without the brackets
571 os << latex1 << latex2;
572 return latex1.length() + latex2.length();
574 os << latex1 << '{' << latex2 << '}';
575 return latex1.length() + latex2.length() + 2;
579 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
580 odocstream & os, TexRow & texrow,
582 unsigned int & column,
584 Layout const & style)
586 if (style.pass_thru || runparams.verbatim)
589 if (i + 1 < int(text_.size())) {
590 char_type next = text_[i + 1];
591 if (Encodings::isCombiningChar(next)) {
592 // This space has an accent, so we must always output it.
593 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
598 if (runparams.linelen > 0
599 && column > runparams.linelen
601 && text_[i - 1] != ' '
602 && (i + 1 < int(text_.size()))
603 // same in FreeSpacing mode
604 && !owner_->isFreeSpacing()
605 // In typewriter mode, we want to avoid
606 // ! . ? : at the end of a line
607 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
608 && (text_[i - 1] == '.'
609 || text_[i - 1] == '?'
610 || text_[i - 1] == ':'
611 || text_[i - 1] == '!'))) {
614 texrow.start(owner_->id(), i + 1);
616 } else if (style.free_spacing) {
625 int Paragraph::Private::writeScriptChars(odocstream & os,
626 docstring const & ltx,
627 Change const & runningChange,
628 Encoding const & encoding,
631 // FIXME: modifying i here is not very nice...
633 // We only arrive here when a proper language for character text_[i] has
634 // not been specified (i.e., it could not be translated in the current
635 // latex encoding) or its latex translation has been forced, and it
636 // belongs to a known script.
637 // Parameter ltx contains the latex translation of text_[i] as specified
638 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
639 // The latex macro name "textXXX" specifies the script to which text_[i]
640 // belongs and we use it in order to check whether characters from the
641 // same script immediately follow, such that we can collect them in a
642 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
643 // for the first char but only "<spec>" for all subsequent chars.
644 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
645 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
646 string script = to_ascii(ltx.substr(1, brace1 - 1));
649 bool closing_brace = true;
650 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
651 // Correct encoding is being used, so we can avoid \textgreek.
654 closing_brace = false;
656 os << ltx.substr(pos, length);
657 int size = text_.size();
658 while (i + 1 < size) {
659 char_type const next = text_[i + 1];
660 // Stop here if next character belongs to another script
661 // or there is a change in change tracking status.
662 if (!Encodings::isKnownScriptChar(next, script) ||
663 runningChange != owner_->lookupChange(i + 1))
667 FontList::const_iterator cit = fontlist_.begin();
668 FontList::const_iterator end = fontlist_.end();
669 for (; cit != end; ++cit) {
670 if (cit->pos() >= i && !found) {
671 prev_font = cit->font();
674 if (cit->pos() >= i + 1)
677 // Stop here if there is a font attribute or encoding change.
678 if (found && cit != end && prev_font != cit->font())
680 docstring const latex = encoding.latexChar(next);
681 docstring::size_type const b1 =
682 latex.find_first_of(from_ascii("{"));
683 docstring::size_type const b2 =
684 latex.find_last_of(from_ascii("}"));
685 int const len = b2 - b1 - 1;
686 os << latex.substr(b1 + 1, len);
698 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
700 pos_type const len = str.length();
702 // is the paragraph large enough?
703 if (pos + len > int(text_.size()))
706 // does the wanted text start at point?
707 for (string::size_type i = 0; i < str.length(); ++i) {
708 // Caution: direct comparison of characters works only
709 // because str is pure ASCII.
710 if (str[i] != text_[pos + i])
714 return fontlist_.hasChangeInRange(pos, len);
718 void Paragraph::Private::latexInset(
719 BufferParams const & bparams,
722 OutputParams & runparams,
725 Font const & outerfont,
727 Change & running_change,
728 Layout const & style,
730 unsigned int & column)
732 Inset * inset = owner_->getInset(i);
733 LASSERT(inset, /**/);
735 if (style.pass_thru) {
736 inset->plaintext(os, runparams);
740 // FIXME: move this to InsetNewline::latex
741 if (inset->lyxCode() == NEWLINE_CODE) {
742 // newlines are handled differently here than
743 // the default in simpleTeXSpecialChars().
744 if (!style.newline_allowed) {
748 column += running_font.latexWriteEndChanges(
749 os, bparams, runparams,
754 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
757 basefont = owner_->getLayoutFont(bparams, outerfont);
758 running_font = basefont;
760 if (runparams.moving_arg)
765 texrow.start(owner_->id(), i + 1);
769 if (owner_->isDeleted(i)) {
770 if( ++runparams.inDeletedInset == 1)
771 runparams.changeOfDeletedInset = owner_->lookupChange(i);
774 if (inset->canTrackChanges()) {
775 column += Changes::latexMarkChange(os, bparams, running_change,
776 Change(Change::UNCHANGED), runparams);
777 running_change = Change(Change::UNCHANGED);
781 odocstream::pos_type const len = os.tellp();
783 if (inset->forceLTR()
784 && running_font.isRightToLeft()
785 // ERT is an exception, it should be output with no
786 // decorations at all
787 && inset->lyxCode() != ERT_CODE) {
788 if (running_font.language()->lang() == "farsi")
795 // FIXME: Bug: we can have an empty font change here!
796 // if there has just been a font change, we are going to close it
797 // right now, which means stupid latex code like \textsf{}. AFAIK,
798 // this does not harm dvi output. A minor bug, thus (JMarc)
800 // Some insets cannot be inside a font change command.
801 // However, even such insets *can* be placed in \L or \R
802 // or their equivalents (for RTL language switches), so we don't
803 // close the language in those cases.
804 // ArabTeX, though, cannot handle this special behavior, it seems.
805 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
806 || running_font.language()->lang() == "arabic_arabtex";
807 if (open_font && inset->noFontChange()) {
808 bool closeLanguage = arabtex
809 || basefont.isRightToLeft() == running_font.isRightToLeft();
810 unsigned int count = running_font.latexWriteEndChanges(os,
811 bparams, runparams, basefont, basefont, closeLanguage);
813 // if any font properties were closed, update the running_font,
814 // making sure, however, to leave the language as it was
816 // FIXME: probably a better way to keep track of the old
817 // language, than copying the entire font?
818 Font const copy_font(running_font);
819 basefont = owner_->getLayoutFont(bparams, outerfont);
820 running_font = basefont;
822 running_font.setLanguage(copy_font.language());
823 // leave font open if language is still open
824 open_font = (running_font.language() == basefont.language());
826 runparams.local_font = &basefont;
833 tmp = inset->latex(os, runparams);
834 } catch (EncodingException & e) {
835 // add location information and throw again.
842 if (running_font.language()->lang() == "farsi")
849 texrow.newlines(tmp);
850 texrow.start(owner_->id(), i + 1);
853 column += os.tellp() - len;
856 if (owner_->isDeleted(i))
857 --runparams.inDeletedInset;
861 void Paragraph::Private::latexSpecialChar(
863 OutputParams const & runparams,
864 Font const & running_font,
865 Change const & running_change,
866 Layout const & style,
868 unsigned int & column)
870 char_type const c = text_[i];
872 if (style.pass_thru) {
874 // FIXME UNICODE: This can fail if c cannot
875 // be encoded in the current encoding.
880 if (runparams.verbatim) {
881 // FIXME UNICODE: This can fail if c cannot
882 // be encoded in the current encoding.
887 // If T1 font encoding is used, use the special
888 // characters it provides.
889 // NOTE: some languages reset the font encoding
891 if (!running_font.language()->internalFontEncoding()
892 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
895 // \tt font needs special treatment
896 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
897 && latexSpecialTypewriter(c, os, i, column))
900 // Otherwise, we use what LaTeX provides us.
903 os << "\\textbackslash{}";
907 os << "\\textless{}";
911 os << "\\textgreater{}";
922 os << "\\char`\\\"{}";
927 case '%': case '#': case '{':
935 os << "\\textasciitilde{}";
940 os << "\\textasciicircum{}";
947 // avoid being mistaken for optional arguments
955 // Blanks are printed before font switching.
956 // Sure? I am not! (try nice-latex)
957 // I am sure it's correct. LyX might be smarter
958 // in the future, but for now, nothing wrong is
964 if (latexSpecialPhrase(os, i, column, runparams))
970 Encoding const & encoding = *(runparams.encoding);
971 if (i + 1 < int(text_.size())) {
972 char_type next = text_[i + 1];
973 if (Encodings::isCombiningChar(next)) {
974 column += latexSurrogatePair(os, c, next, runparams) - 1;
980 docstring const latex = encoding.latexChar(c);
981 if (Encodings::isKnownScriptChar(c, script)
982 && prefixIs(latex, from_ascii("\\" + script)))
983 column += writeScriptChars(os, latex,
984 running_change, encoding, i) - 1;
985 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
986 // Prevent eating of a following
987 // space or command corruption by
988 // following characters
989 column += latex.length() + 1;
992 column += latex.length() - 1;
1000 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1001 pos_type i, unsigned int & column)
1007 // In T1 encoding, these characters exist
1008 // but we should avoid ligatures
1009 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1011 os << "\\textcompwordmark{}";
1018 // soul.sty breaks with \char`\"
1019 os << "\\textquotedbl{}";
1028 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1029 pos_type i, unsigned int & column)
1033 // within \ttfamily, "--" is merged to "-" (no endash)
1034 // so we avoid this rather irritating ligature
1035 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1042 // everything else has to be checked separately
1043 // (depending on the encoding)
1050 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1051 unsigned int & column, OutputParams const & runparams)
1053 // FIXME: if we have "LaTeX" with a font
1054 // change in the middle (before the 'T', then
1055 // the "TeX" part is still special cased.
1056 // Really we should only operate this on
1057 // "words" for some definition of word
1059 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1060 if (!isTextAt(special_phrases[pnr].phrase, i))
1062 if (runparams.moving_arg)
1064 os << special_phrases[pnr].macro;
1065 i += special_phrases[pnr].phrase.length() - 1;
1066 column += special_phrases[pnr].macro.length() - 1;
1073 void Paragraph::Private::validate(LaTeXFeatures & features) const
1075 if (layout_->inpreamble && inset_owner_) {
1076 Buffer const & buf = inset_owner_->buffer();
1077 BufferParams const & bp = buf.params();
1080 odocstringstream ods;
1081 owner_->latex(bp, f, ods, tr, features.runparams());
1082 docstring d = ods.str();
1084 features.addPreambleSnippet(to_utf8(d));
1087 if (features.runparams().flavor == OutputParams::HTML
1088 && layout_->htmltitle()) {
1089 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1092 // check the params.
1093 if (!params_.spacing().isDefault())
1094 features.require("setspace");
1097 features.useLayout(layout_->name());
1100 fontlist_.validate(features);
1102 // then the indentation
1103 if (!params_.leftIndent().zero())
1104 features.require("ParagraphLeftIndent");
1107 InsetList::const_iterator icit = insetlist_.begin();
1108 InsetList::const_iterator iend = insetlist_.end();
1109 for (; icit != iend; ++icit) {
1111 icit->inset->validate(features);
1112 if (layout_->needprotect &&
1113 icit->inset->lyxCode() == FOOT_CODE)
1114 features.require("NeedLyXFootnoteCode");
1118 // then the contents
1119 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1120 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1121 if (!special_phrases[pnr].builtin
1122 && isTextAt(special_phrases[pnr].phrase, i)) {
1123 features.require(special_phrases[pnr].phrase);
1127 Encodings::validate(text_[i], features);
1131 /////////////////////////////////////////////////////////////////////
1135 /////////////////////////////////////////////////////////////////////
1138 Layout const emptyParagraphLayout;
1141 Paragraph::Paragraph()
1142 : d(new Paragraph::Private(this, emptyParagraphLayout))
1149 Paragraph::Paragraph(Paragraph const & par)
1150 : itemdepth(par.itemdepth),
1151 d(new Paragraph::Private(*par.d, this))
1157 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1158 : itemdepth(par.itemdepth),
1159 d(new Paragraph::Private(*par.d, this, beg, end))
1165 Paragraph & Paragraph::operator=(Paragraph const & par)
1167 // needed as we will destroy the private part before copying it
1169 itemdepth = par.itemdepth;
1173 d = new Private(*par.d, this);
1180 Paragraph::~Paragraph()
1189 // this shall be called just before every "os << ..." action.
1190 void flushString(ostream & os, docstring & s)
1199 void Paragraph::write(ostream & os, BufferParams const & bparams,
1200 depth_type & dth) const
1202 // The beginning or end of a deeper (i.e. nested) area?
1203 if (dth != d->params_.depth()) {
1204 if (d->params_.depth() > dth) {
1205 while (d->params_.depth() > dth) {
1206 os << "\n\\begin_deeper";
1210 while (d->params_.depth() < dth) {
1211 os << "\n\\end_deeper";
1217 // First write the layout
1218 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1220 d->params_.write(os);
1222 Font font1(inherit_font, bparams.language);
1224 Change running_change = Change(Change::UNCHANGED);
1226 // this string is used as a buffer to avoid repetitive calls
1227 // to to_utf8(), which turn out to be expensive (JMarc)
1228 docstring write_buffer;
1231 for (pos_type i = 0; i <= size(); ++i) {
1233 Change const change = lookupChange(i);
1234 if (change != running_change)
1235 flushString(os, write_buffer);
1236 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1237 running_change = change;
1242 // Write font changes (ignore spelling markers)
1243 Font font2 = getFontSettings(bparams, i);
1244 font2.setMisspelled(false);
1245 if (font2 != font1) {
1246 flushString(os, write_buffer);
1247 font2.lyxWriteChanges(font1, os);
1252 char_type const c = d->text_[i];
1255 if (Inset const * inset = getInset(i)) {
1256 flushString(os, write_buffer);
1257 if (inset->directWrite()) {
1258 // international char, let it write
1259 // code directly so it's shorter in
1265 os << "\\begin_inset ";
1267 os << "\n\\end_inset\n\n";
1273 flushString(os, write_buffer);
1274 os << "\n\\backslash\n";
1278 flushString(os, write_buffer);
1279 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1286 if ((column > 70 && c == ' ')
1288 flushString(os, write_buffer);
1292 // this check is to amend a bug. LyX sometimes
1293 // inserts '\0' this could cause problems.
1295 write_buffer.push_back(c);
1297 LYXERR0("NUL char in structure.");
1303 flushString(os, write_buffer);
1304 os << "\n\\end_layout\n";
1308 void Paragraph::validate(LaTeXFeatures & features) const
1310 d->validate(features);
1314 void Paragraph::insert(pos_type start, docstring const & str,
1315 Font const & font, Change const & change)
1317 for (size_t i = 0, n = str.size(); i != n ; ++i)
1318 insertChar(start + i, str[i], font, change);
1322 void Paragraph::appendChar(char_type c, Font const & font,
1323 Change const & change)
1326 d->changes_.insert(change, d->text_.size());
1327 // when appending characters, no need to update tables
1328 d->text_.push_back(c);
1329 setFont(d->text_.size() - 1, font);
1333 void Paragraph::appendString(docstring const & s, Font const & font,
1334 Change const & change)
1336 pos_type end = s.size();
1337 size_t oldsize = d->text_.size();
1338 size_t newsize = oldsize + end;
1339 size_t capacity = d->text_.capacity();
1340 if (newsize >= capacity)
1341 d->text_.reserve(max(capacity + 100, newsize));
1343 // when appending characters, no need to update tables
1346 // FIXME: Optimize this!
1347 for (size_t i = oldsize; i != newsize; ++i) {
1349 d->changes_.insert(change, i);
1351 d->fontlist_.set(oldsize, font);
1352 d->fontlist_.set(newsize - 1, font);
1356 void Paragraph::insertChar(pos_type pos, char_type c,
1359 d->insertChar(pos, c, Change(trackChanges ?
1360 Change::INSERTED : Change::UNCHANGED));
1364 void Paragraph::insertChar(pos_type pos, char_type c,
1365 Font const & font, bool trackChanges)
1367 d->insertChar(pos, c, Change(trackChanges ?
1368 Change::INSERTED : Change::UNCHANGED));
1373 void Paragraph::insertChar(pos_type pos, char_type c,
1374 Font const & font, Change const & change)
1376 d->insertChar(pos, c, change);
1381 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1382 Font const & font, Change const & change)
1384 bool const success = insertInset(pos, inset, change);
1385 // Set the font/language of the inset...
1391 void Paragraph::resetFonts(Font const & font)
1393 d->fontlist_.clear();
1394 d->fontlist_.set(0, font);
1395 d->fontlist_.set(d->text_.size() - 1, font);
1398 // Gets uninstantiated font setting at position.
1399 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1403 LYXERR0("pos: " << pos << " size: " << size());
1404 LASSERT(pos <= size(), /**/);
1407 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1408 if (cit != d->fontlist_.end())
1411 if (pos == size() && !empty())
1412 return getFontSettings(bparams, pos - 1);
1414 // Optimisation: avoid a full font instantiation if there is no
1415 // language change from previous call.
1416 static Font previous_font;
1417 static Language const * previous_lang = 0;
1418 Language const * lang = getParLanguage(bparams);
1419 if (lang != previous_lang) {
1420 previous_lang = lang;
1421 previous_font = Font(inherit_font, lang);
1423 return previous_font;
1427 FontSpan Paragraph::fontSpan(pos_type pos) const
1429 LASSERT(pos <= size(), /**/);
1432 FontList::const_iterator cit = d->fontlist_.begin();
1433 FontList::const_iterator end = d->fontlist_.end();
1434 for (; cit != end; ++cit) {
1435 if (cit->pos() >= pos) {
1436 if (pos >= beginOfBody())
1437 return FontSpan(max(start, beginOfBody()),
1440 return FontSpan(start,
1441 min(beginOfBody() - 1,
1444 start = cit->pos() + 1;
1447 // This should not happen, but if so, we take no chances.
1448 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1449 return FontSpan(pos, pos);
1453 // Gets uninstantiated font setting at position 0
1454 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1456 if (!empty() && !d->fontlist_.empty())
1457 return d->fontlist_.begin()->font();
1459 // Optimisation: avoid a full font instantiation if there is no
1460 // language change from previous call.
1461 static Font previous_font;
1462 static Language const * previous_lang = 0;
1463 if (bparams.language != previous_lang) {
1464 previous_lang = bparams.language;
1465 previous_font = Font(inherit_font, bparams.language);
1468 return previous_font;
1472 // Gets the fully instantiated font at a given position in a paragraph
1473 // This is basically the same function as Text::GetFont() in text2.cpp.
1474 // The difference is that this one is used for generating the LaTeX file,
1475 // and thus cosmetic "improvements" are disallowed: This has to deliver
1476 // the true picture of the buffer. (Asger)
1477 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1478 Font const & outerfont) const
1480 LASSERT(pos >= 0, /**/);
1482 Font font = getFontSettings(bparams, pos);
1484 pos_type const body_pos = beginOfBody();
1485 FontInfo & fi = font.fontInfo();
1487 fi.realize(d->layout_->labelfont);
1489 fi.realize(d->layout_->font);
1491 fi.realize(outerfont.fontInfo());
1492 fi.realize(bparams.getFont().fontInfo());
1498 Font const Paragraph::getLabelFont
1499 (BufferParams const & bparams, Font const & outerfont) const
1501 FontInfo tmpfont = d->layout_->labelfont;
1502 tmpfont.realize(outerfont.fontInfo());
1503 tmpfont.realize(bparams.getFont().fontInfo());
1504 return Font(tmpfont, getParLanguage(bparams));
1508 Font const Paragraph::getLayoutFont
1509 (BufferParams const & bparams, Font const & outerfont) const
1511 FontInfo tmpfont = d->layout_->font;
1512 tmpfont.realize(outerfont.fontInfo());
1513 tmpfont.realize(bparams.getFont().fontInfo());
1514 return Font(tmpfont, getParLanguage(bparams));
1518 /// Returns the height of the highest font in range
1519 FontSize Paragraph::highestFontInRange
1520 (pos_type startpos, pos_type endpos, FontSize def_size) const
1522 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1526 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1528 char_type c = d->text_[pos];
1529 if (!lyxrc.rtl_support)
1559 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1565 void Paragraph::setFont(pos_type pos, Font const & font)
1567 LASSERT(pos <= size(), /**/);
1569 // First, reduce font against layout/label font
1570 // Update: The setCharFont() routine in text2.cpp already
1571 // reduces font, so we don't need to do that here. (Asger)
1573 d->fontlist_.set(pos, font);
1577 void Paragraph::makeSameLayout(Paragraph const & par)
1579 d->layout_ = par.d->layout_;
1580 d->params_ = par.d->params_;
1584 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1586 if (isFreeSpacing())
1592 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1593 if (eraseChar(pos, trackChanges))
1599 return count > 0 || pos > 0;
1603 bool Paragraph::hasSameLayout(Paragraph const & par) const
1605 return par.d->layout_ == d->layout_
1606 && d->params_.sameLayout(par.d->params_);
1610 depth_type Paragraph::getDepth() const
1612 return d->params_.depth();
1616 depth_type Paragraph::getMaxDepthAfter() const
1618 if (d->layout_->isEnvironment())
1619 return d->params_.depth() + 1;
1621 return d->params_.depth();
1625 char Paragraph::getAlign() const
1627 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1628 return d->layout_->align;
1630 return d->params_.align();
1634 docstring const & Paragraph::labelString() const
1636 return d->params_.labelString();
1640 // the next two functions are for the manual labels
1641 docstring const Paragraph::getLabelWidthString() const
1643 if (d->layout_->margintype == MARGIN_MANUAL
1644 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1645 return d->params_.labelWidthString();
1647 return _("Senseless with this layout!");
1651 void Paragraph::setLabelWidthString(docstring const & s)
1653 d->params_.labelWidthString(s);
1657 docstring Paragraph::expandLabel(Layout const & layout,
1658 BufferParams const & bparams) const
1660 return expandParagraphLabel(layout, bparams, true);
1664 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1665 BufferParams const & bparams) const
1667 return expandParagraphLabel(layout, bparams, false);
1671 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1672 BufferParams const & bparams, bool process_appendix) const
1674 DocumentClass const & tclass = bparams.documentClass();
1675 string const & lang = getParLanguage(bparams)->code();
1676 bool const in_appendix = process_appendix && d->params_.appendix();
1677 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1679 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1680 && !layout.counter.empty())
1681 return tclass.counters().theCounter(layout.counter, lang);
1683 // handle 'inherited level parts' in 'fmt',
1684 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1685 size_t const i = fmt.find('@', 0);
1686 if (i != docstring::npos) {
1687 size_t const j = fmt.find('@', i + 1);
1688 if (j != docstring::npos) {
1689 docstring parent(fmt, i + 1, j - i - 1);
1690 docstring label = from_ascii("??");
1691 if (tclass.hasLayout(parent))
1692 docstring label = expandParagraphLabel(tclass[parent], bparams,
1694 fmt = docstring(fmt, 0, i) + label
1695 + docstring(fmt, j + 1, docstring::npos);
1699 return tclass.counters().counterLabel(fmt, lang);
1703 void Paragraph::applyLayout(Layout const & new_layout)
1705 d->layout_ = &new_layout;
1706 LyXAlignment const oldAlign = d->params_.align();
1708 if (!(oldAlign & d->layout_->alignpossible)) {
1709 frontend::Alert::warning(_("Alignment not permitted"),
1710 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1711 d->params_.align(LYX_ALIGN_LAYOUT);
1716 pos_type Paragraph::beginOfBody() const
1718 return d->begin_of_body_;
1722 void Paragraph::setBeginOfBody()
1724 if (d->layout_->labeltype != LABEL_MANUAL) {
1725 d->begin_of_body_ = 0;
1729 // Unroll the first two cycles of the loop
1730 // and remember the previous character to
1731 // remove unnecessary getChar() calls
1733 pos_type end = size();
1734 if (i < end && !isNewline(i)) {
1736 char_type previous_char = 0;
1739 previous_char = d->text_[i];
1740 if (!isNewline(i)) {
1742 while (i < end && previous_char != ' ') {
1747 previous_char = temp;
1753 d->begin_of_body_ = i;
1757 bool Paragraph::allowParagraphCustomization() const
1759 return inInset().allowParagraphCustomization();
1763 bool Paragraph::usePlainLayout() const
1765 return inInset().usePlainLayout();
1771 // paragraphs inside floats need different alignment tags to avoid
1774 bool noTrivlistCentering(InsetCode code)
1776 return code == FLOAT_CODE
1777 || code == WRAP_CODE
1778 || code == CELL_CODE;
1782 string correction(string const & orig)
1784 if (orig == "flushleft")
1785 return "raggedright";
1786 if (orig == "flushright")
1787 return "raggedleft";
1788 if (orig == "center")
1794 string const corrected_env(string const & suffix, string const & env,
1795 InsetCode code, bool const lastpar)
1797 string output = suffix + "{";
1798 if (noTrivlistCentering(code)) {
1800 // the last paragraph in non-trivlist-aligned
1801 // context is special (to avoid unwanted whitespace)
1802 if (suffix == "\\begin")
1803 return "\\" + correction(env) + "{}";
1806 output += correction(env);
1810 if (suffix == "\\begin")
1816 void adjust_row_column(string const & str, TexRow & texrow, int & column)
1818 if (!contains(str, "\n"))
1819 column += str.size();
1823 column = rsplit(str, tmp, '\n').size();
1830 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
1831 odocstream & os, TexRow & texrow,
1832 OutputParams const & runparams) const
1836 if (params_.noindent()) {
1837 os << "\\noindent ";
1841 LyXAlignment const curAlign = params_.align();
1843 if (curAlign == layout_->align)
1847 case LYX_ALIGN_NONE:
1848 case LYX_ALIGN_BLOCK:
1849 case LYX_ALIGN_LAYOUT:
1850 case LYX_ALIGN_SPECIAL:
1851 case LYX_ALIGN_DECIMAL:
1853 case LYX_ALIGN_LEFT:
1854 case LYX_ALIGN_RIGHT:
1855 case LYX_ALIGN_CENTER:
1856 if (runparams.moving_arg) {
1863 string const begin_tag = "\\begin";
1864 InsetCode code = ownerCode();
1865 bool const lastpar = runparams.isLastPar;
1868 case LYX_ALIGN_NONE:
1869 case LYX_ALIGN_BLOCK:
1870 case LYX_ALIGN_LAYOUT:
1871 case LYX_ALIGN_SPECIAL:
1872 case LYX_ALIGN_DECIMAL:
1874 case LYX_ALIGN_LEFT: {
1876 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1877 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1879 output = corrected_env(begin_tag, "flushright", code, lastpar);
1880 os << from_ascii(output);
1881 adjust_row_column(output, texrow, column);
1883 } case LYX_ALIGN_RIGHT: {
1885 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1886 output = corrected_env(begin_tag, "flushright", code, lastpar);
1888 output = corrected_env(begin_tag, "flushleft", code, lastpar);
1889 os << from_ascii(output);
1890 adjust_row_column(output, texrow, column);
1892 } case LYX_ALIGN_CENTER: {
1894 output = corrected_env(begin_tag, "center", code, lastpar);
1895 os << from_ascii(output);
1896 adjust_row_column(output, texrow, column);
1905 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
1906 odocstream & os, TexRow & texrow,
1907 OutputParams const & runparams) const
1911 LyXAlignment const curAlign = params_.align();
1913 if (curAlign == layout_->align)
1917 case LYX_ALIGN_NONE:
1918 case LYX_ALIGN_BLOCK:
1919 case LYX_ALIGN_LAYOUT:
1920 case LYX_ALIGN_SPECIAL:
1921 case LYX_ALIGN_DECIMAL:
1923 case LYX_ALIGN_LEFT:
1924 case LYX_ALIGN_RIGHT:
1925 case LYX_ALIGN_CENTER:
1926 if (runparams.moving_arg) {
1933 string const end_tag = "\n\\par\\end";
1934 InsetCode code = ownerCode();
1935 bool const lastpar = runparams.isLastPar;
1938 case LYX_ALIGN_NONE:
1939 case LYX_ALIGN_BLOCK:
1940 case LYX_ALIGN_LAYOUT:
1941 case LYX_ALIGN_SPECIAL:
1942 case LYX_ALIGN_DECIMAL:
1944 case LYX_ALIGN_LEFT: {
1946 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1947 output = corrected_env(end_tag, "flushleft", code, lastpar);
1949 output = corrected_env(end_tag, "flushright", code, lastpar);
1950 os << from_ascii(output);
1951 adjust_row_column(output, texrow, column);
1953 } case LYX_ALIGN_RIGHT: {
1955 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
1956 output = corrected_env(end_tag, "flushright", code, lastpar);
1958 output = corrected_env(end_tag, "flushleft", code, lastpar);
1959 os << from_ascii(output);
1960 adjust_row_column(output, texrow, column);
1962 } case LYX_ALIGN_CENTER: {
1964 output = corrected_env(end_tag, "center", code, lastpar);
1965 os << from_ascii(output);
1966 adjust_row_column(output, texrow, column);
1975 // This one spits out the text of the paragraph
1976 bool Paragraph::latex(BufferParams const & bparams,
1977 Font const & outerfont,
1978 odocstream & os, TexRow & texrow,
1979 OutputParams const & runparams,
1980 int start_pos, int end_pos) const
1982 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
1984 if (layout().inpreamble)
1987 bool return_value = false;
1989 bool const allowcust = allowParagraphCustomization();
1991 // FIXME This check should not be needed. Perhaps issue an
1992 // error if it triggers.
1993 Layout const & style = inInset().forcePlainLayout() ?
1994 bparams.documentClass().plainLayout() : *d->layout_;
1996 // Current base font for all inherited font changes, without any
1997 // change caused by an individual character, except for the language:
1998 // It is set to the language of the first character.
1999 // As long as we are in the label, this font is the base font of the
2000 // label. Before the first body character it is set to the base font
2004 // Maybe we have to create a optional argument.
2005 pos_type body_pos = beginOfBody();
2006 unsigned int column = 0;
2009 // the optional argument is kept in curly brackets in
2010 // case it contains a ']'
2013 basefont = getLabelFont(bparams, outerfont);
2015 basefont = getLayoutFont(bparams, outerfont);
2018 // Which font is currently active?
2019 Font running_font(basefont);
2020 // Do we have an open font change?
2021 bool open_font = false;
2023 Change runningChange = Change(Change::UNCHANGED);
2025 Encoding const * const prev_encoding = runparams.encoding;
2027 texrow.start(id(), 0);
2029 // if the paragraph is empty, the loop will not be entered at all
2031 if (style.isCommand()) {
2036 column += d->startTeXParParams(bparams, os, texrow,
2040 for (pos_type i = 0; i < size(); ++i) {
2041 // First char in paragraph or after label?
2042 if (i == body_pos) {
2045 column += running_font.latexWriteEndChanges(
2046 os, bparams, runparams,
2047 basefont, basefont);
2050 basefont = getLayoutFont(bparams, outerfont);
2051 running_font = basefont;
2053 column += Changes::latexMarkChange(os, bparams,
2054 runningChange, Change(Change::UNCHANGED),
2056 runningChange = Change(Change::UNCHANGED);
2061 if (style.isCommand()) {
2067 column += d->startTeXParParams(bparams, os,
2072 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2075 if (bparams.outputChanges && runningChange != change) {
2077 column += running_font.latexWriteEndChanges(
2078 os, bparams, runparams, basefont, basefont);
2081 basefont = getLayoutFont(bparams, outerfont);
2082 running_font = basefont;
2084 column += Changes::latexMarkChange(os, bparams, runningChange,
2086 runningChange = change;
2089 // do not output text which is marked deleted
2090 // if change tracking output is disabled
2091 if (!bparams.outputChanges && change.deleted()) {
2097 // Fully instantiated font
2098 Font const font = getFont(bparams, i, outerfont);
2100 Font const last_font = running_font;
2102 // Do we need to close the previous font?
2104 (font != running_font ||
2105 font.language() != running_font.language()))
2107 column += running_font.latexWriteEndChanges(
2108 os, bparams, runparams, basefont,
2109 (i == body_pos-1) ? basefont : font);
2110 running_font = basefont;
2114 // close babel's font environment before opening CJK.
2115 if (!running_font.language()->babel().empty() &&
2116 font.language()->encoding()->package() == Encoding::CJK) {
2117 string end_tag = subst(lyxrc.language_command_end,
2119 running_font.language()->babel());
2120 os << from_ascii(end_tag);
2121 column += end_tag.length();
2124 // Switch file encoding if necessary (and allowed)
2125 if (!runparams.verbatim &&
2126 runparams.encoding->package() != Encoding::none &&
2127 font.language()->encoding()->package() != Encoding::none) {
2128 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2129 runparams, *(font.language()->encoding()));
2130 if (enc_switch.first) {
2131 column += enc_switch.second;
2132 runparams.encoding = font.language()->encoding();
2136 char_type const c = d->text_[i];
2138 // Do we need to change font?
2139 if ((font != running_font ||
2140 font.language() != running_font.language()) &&
2143 odocstringstream ods;
2144 column += font.latexWriteStartChanges(ods, bparams,
2145 runparams, basefont,
2147 running_font = font;
2149 docstring fontchange = ods.str();
2150 // check whether the fontchange ends with a \\textcolor
2151 // modifier and the text starts with a space (bug 4473)
2152 docstring const last_modifier = rsplit(fontchange, '\\');
2153 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2154 os << fontchange << from_ascii("{}");
2155 // check if the fontchange ends with a trailing blank
2156 // (like "\small " (see bug 3382)
2157 else if (suffixIs(fontchange, ' ') && c == ' ')
2158 os << fontchange.substr(0, fontchange.size() - 1)
2159 << from_ascii("{}");
2164 // FIXME: think about end_pos implementation...
2165 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2166 // FIXME: integrate this case in latexSpecialChar
2167 // Do not print the separation of the optional argument
2168 // if style.pass_thru is false. This works because
2169 // latexSpecialChar ignores spaces if
2170 // style.pass_thru is false.
2171 if (i != body_pos - 1) {
2172 if (d->simpleTeXBlanks(
2173 runparams, os, texrow,
2174 i, column, font, style)) {
2175 // A surrogate pair was output. We
2176 // must not call latexSpecialChar
2177 // in this iteration, since it would output
2178 // the combining character again.
2185 OutputParams rp = runparams;
2186 rp.free_spacing = style.free_spacing;
2187 rp.local_font = &font;
2188 rp.intitle = style.intitle;
2190 // Two major modes: LaTeX or plain
2191 // Handle here those cases common to both modes
2192 // and then split to handle the two modes separately.
2193 if (c == META_INSET) {
2194 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2195 d->latexInset(bparams, os,
2196 texrow, rp, running_font,
2197 basefont, outerfont, open_font,
2198 runningChange, style, i, column);
2201 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2203 d->latexSpecialChar(os, rp, running_font, runningChange,
2205 } catch (EncodingException & e) {
2206 if (runparams.dryrun) {
2207 os << "<" << _("LyX Warning: ")
2208 << _("uncodable character") << " '";
2212 // add location information and throw again.
2221 // Set the encoding to that returned from latexSpecialChar (see
2222 // comment for encoding member in OutputParams.h)
2223 runparams.encoding = rp.encoding;
2226 // If we have an open font definition, we have to close it
2228 #ifdef FIXED_LANGUAGE_END_DETECTION
2231 .latexWriteEndChanges(os, bparams, runparams,
2233 next_->getFont(bparams, 0, outerfont));
2235 running_font.latexWriteEndChanges(os, bparams,
2236 runparams, basefont, basefont);
2239 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2240 //FIXME: there as we start another \selectlanguage with the next paragraph if
2241 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2242 running_font.latexWriteEndChanges(os, bparams, runparams,
2243 basefont, basefont);
2247 column += Changes::latexMarkChange(os, bparams, runningChange,
2248 Change(Change::UNCHANGED), runparams);
2250 // Needed if there is an optional argument but no contents.
2251 if (body_pos > 0 && body_pos == size()) {
2253 return_value = false;
2256 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2257 && runparams.encoding != prev_encoding) {
2258 runparams.encoding = prev_encoding;
2259 if (!bparams.useXetex)
2260 os << setEncoding(prev_encoding->iconvName());
2263 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2264 return return_value;
2268 bool Paragraph::emptyTag() const
2270 for (pos_type i = 0; i < size(); ++i) {
2271 if (Inset const * inset = getInset(i)) {
2272 InsetCode lyx_code = inset->lyxCode();
2273 // FIXME testing like that is wrong. What is
2275 if (lyx_code != TOC_CODE &&
2276 lyx_code != INCLUDE_CODE &&
2277 lyx_code != GRAPHICS_CODE &&
2278 lyx_code != ERT_CODE &&
2279 lyx_code != LISTINGS_CODE &&
2280 lyx_code != FLOAT_CODE &&
2281 lyx_code != TABULAR_CODE) {
2285 char_type c = d->text_[i];
2286 if (c != ' ' && c != '\t')
2294 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2297 for (pos_type i = 0; i < size(); ++i) {
2298 if (Inset const * inset = getInset(i)) {
2299 InsetCode lyx_code = inset->lyxCode();
2300 if (lyx_code == LABEL_CODE) {
2301 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2302 docstring const & id = il->getParam("name");
2303 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2311 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2315 for (i = 0; i < size(); ++i) {
2316 if (Inset const * inset = getInset(i)) {
2317 inset->docbook(os, runparams);
2319 char_type c = d->text_[i];
2322 os << sgml::escapeChar(c);
2329 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2333 for (i = 0; i < size(); ++i) {
2334 if (Inset const * inset = getInset(i)) {
2335 inset->xhtml(xs, runparams);
2337 char_type c = d->text_[i];
2347 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2350 pos_type size = text_.size();
2351 for (pos_type i = initial; i < size; ++i) {
2352 Font font = owner_->getFont(buf.params(), i, outerfont);
2353 if (text_[i] == META_INSET)
2355 if (i != initial && font != font_old)
2364 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2366 OutputParams const & runparams,
2367 Font const & outerfont,
2368 pos_type initial) const
2370 bool emph_flag = false;
2372 Layout const & style = *d->layout_;
2374 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2376 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2379 // parsing main loop
2380 for (pos_type i = initial; i < size(); ++i) {
2381 Font font = getFont(buf.params(), i, outerfont);
2383 // handle <emphasis> tag
2384 if (font_old.emph() != font.fontInfo().emph()) {
2385 if (font.fontInfo().emph() == FONT_ON) {
2388 } else if (i != initial) {
2389 os << "</emphasis>";
2394 if (Inset const * inset = getInset(i)) {
2395 inset->docbook(os, runparams);
2397 char_type c = d->text_[i];
2399 if (style.pass_thru)
2402 os << sgml::escapeChar(c);
2404 font_old = font.fontInfo();
2408 os << "</emphasis>";
2411 if (style.free_spacing)
2413 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2418 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2420 OutputParams const & runparams,
2421 Font const & outerfont,
2422 pos_type initial) const
2426 bool emph_flag = false;
2427 bool bold_flag = false;
2430 Layout const & style = *d->layout_;
2432 if (!runparams.for_toc && runparams.html_make_pars) {
2433 // generate a magic label for this paragraph
2434 string const attr = "id='" + magicLabel() + "'";
2435 xs << html::CompTag("a", attr);
2439 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2441 // parsing main loop
2442 for (pos_type i = initial; i < size(); ++i) {
2443 // let's not show deleted material in the output
2447 Font font = getFont(buf.params(), i, outerfont);
2450 if (font_old.emph() != font.fontInfo().emph()) {
2451 if (font.fontInfo().emph() == FONT_ON) {
2452 xs << html::StartTag("em");
2454 } else if (emph_flag && i != initial) {
2455 xs << html::EndTag("em");
2460 if (font_old.series() != font.fontInfo().series()) {
2461 if (font.fontInfo().series() == BOLD_SERIES) {
2462 xs << html::StartTag("strong");
2464 } else if (bold_flag && i != initial) {
2465 xs << html::EndTag("strong");
2470 // Other such tags? What about the other text ranges?
2472 Inset const * inset = getInset(i);
2474 InsetCommand const * ic = inset->asInsetCommand();
2475 InsetLayout const & il = inset->getLayout();
2476 InsetMath const * im = inset->asInsetMath();
2477 if (!runparams.for_toc
2478 || im || il.isInToc() || (ic && ic->isInToc())) {
2479 OutputParams np = runparams;
2480 if (!il.htmlisblock())
2481 np.html_in_par = true;
2482 retval += inset->xhtml(xs, np);
2485 char_type c = d->text_[i];
2487 if (style.pass_thru)
2489 else if (c == '-') {
2492 if (j < size() && d->text_[j] == '-') {
2494 if (j < size() && d->text_[j] == '-') {
2495 str += from_ascii("—");
2498 str += from_ascii("–");
2504 // We don't want to escape the entities. Note that
2505 // it is safe to do this, since str can otherwise
2506 // only be "-". E.g., it can't be "<".
2507 xs << XHTMLStream::NextRaw() << str;
2511 font_old = font.fontInfo();
2519 bool Paragraph::isHfill(pos_type pos) const
2521 Inset const * inset = getInset(pos);
2522 return inset && (inset->lyxCode() == SPACE_CODE &&
2523 inset->isStretchableSpace());
2527 bool Paragraph::isNewline(pos_type pos) const
2529 Inset const * inset = getInset(pos);
2530 return inset && inset->lyxCode() == NEWLINE_CODE;
2534 bool Paragraph::isLineSeparator(pos_type pos) const
2536 char_type const c = d->text_[pos];
2537 if (isLineSeparatorChar(c))
2539 Inset const * inset = getInset(pos);
2540 return inset && inset->isLineSeparator();
2544 bool Paragraph::isWordSeparator(pos_type pos) const
2546 if (Inset const * inset = getInset(pos))
2547 return !inset->isLetter();
2548 char_type const c = d->text_[pos];
2549 // We want to pass the ' and escape chars to the spellchecker
2550 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2551 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2556 bool Paragraph::isChar(pos_type pos) const
2558 if (Inset const * inset = getInset(pos))
2559 return inset->isChar();
2560 char_type const c = d->text_[pos];
2561 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2565 bool Paragraph::isSpace(pos_type pos) const
2567 if (Inset const * inset = getInset(pos))
2568 return inset->isSpace();
2569 char_type const c = d->text_[pos];
2570 return lyx::isSpace(c);
2575 Paragraph::getParLanguage(BufferParams const & bparams) const
2578 return getFirstFontSettings(bparams).language();
2579 // FIXME: we should check the prev par as well (Lgb)
2580 return bparams.language;
2584 bool Paragraph::isRTL(BufferParams const & bparams) const
2586 return lyxrc.rtl_support
2587 && getParLanguage(bparams)->rightToLeft()
2588 && !inInset().getLayout().forceLTR();
2592 void Paragraph::changeLanguage(BufferParams const & bparams,
2593 Language const * from, Language const * to)
2595 // change language including dummy font change at the end
2596 for (pos_type i = 0; i <= size(); ++i) {
2597 Font font = getFontSettings(bparams, i);
2598 if (font.language() == from) {
2599 font.setLanguage(to);
2606 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2608 Language const * doc_language = bparams.language;
2609 FontList::const_iterator cit = d->fontlist_.begin();
2610 FontList::const_iterator end = d->fontlist_.end();
2612 for (; cit != end; ++cit)
2613 if (cit->font().language() != ignore_language &&
2614 cit->font().language() != latex_language &&
2615 cit->font().language() != doc_language)
2621 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2623 FontList::const_iterator cit = d->fontlist_.begin();
2624 FontList::const_iterator end = d->fontlist_.end();
2626 for (; cit != end; ++cit) {
2627 Language const * lang = cit->font().language();
2628 if (lang != ignore_language &&
2629 lang != latex_language)
2630 languages.insert(lang);
2635 docstring Paragraph::asString(int options) const
2637 return asString(0, size(), options);
2641 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2643 odocstringstream os;
2646 && options & AS_STR_LABEL
2647 && !d->params_.labelString().empty())
2648 os << d->params_.labelString() << ' ';
2650 for (pos_type i = beg; i < end; ++i) {
2651 char_type const c = d->text_[i];
2652 if (isPrintable(c) || c == '\t'
2653 || (c == '\n' && (options & AS_STR_NEWLINES)))
2655 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2656 getInset(i)->tocString(os);
2657 if (getInset(i)->asInsetMath())
2666 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2668 odocstringstream os;
2671 && options & AS_STR_LABEL
2672 && !d->params_.labelString().empty())
2673 os << d->params_.labelString() << ' ';
2675 for (pos_type i = beg; i < end; ++i) {
2676 char_type const c = d->text_[i];
2677 if (isPrintable(c) || c == '\t'
2678 || (c == '\n' && (options & AS_STR_NEWLINES)))
2680 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2681 getInset(i)->plaintext(os, runparams);
2689 void Paragraph::setInsetOwner(Inset const * inset)
2691 d->inset_owner_ = inset;
2695 int Paragraph::id() const
2701 void Paragraph::setId(int id)
2707 Layout const & Paragraph::layout() const
2713 void Paragraph::setLayout(Layout const & layout)
2715 d->layout_ = &layout;
2719 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2721 setLayout(tc.defaultLayout());
2725 void Paragraph::setPlainLayout(DocumentClass const & tc)
2727 setLayout(tc.plainLayout());
2731 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2733 if (usePlainLayout())
2734 setPlainLayout(tclass);
2736 setDefaultLayout(tclass);
2740 Inset const & Paragraph::inInset() const
2742 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2743 _("Memory problem"), _("Paragraph not properly initialized")));
2744 return *d->inset_owner_;
2748 ParagraphParameters & Paragraph::params()
2754 ParagraphParameters const & Paragraph::params() const
2760 bool Paragraph::isFreeSpacing() const
2762 if (d->layout_->free_spacing)
2764 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2768 bool Paragraph::allowEmpty() const
2770 if (d->layout_->keepempty)
2772 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2776 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2778 if (!Encodings::isArabicChar(c))
2781 char_type prev_char = ' ';
2782 char_type next_char = ' ';
2784 for (pos_type i = pos - 1; i >= 0; --i) {
2785 char_type const par_char = d->text_[i];
2786 if (!Encodings::isArabicComposeChar(par_char)) {
2787 prev_char = par_char;
2792 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2793 char_type const par_char = d->text_[i];
2794 if (!Encodings::isArabicComposeChar(par_char)) {
2795 next_char = par_char;
2800 if (Encodings::isArabicChar(next_char)) {
2801 if (Encodings::isArabicChar(prev_char) &&
2802 !Encodings::isArabicSpecialChar(prev_char))
2803 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
2805 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
2807 if (Encodings::isArabicChar(prev_char) &&
2808 !Encodings::isArabicSpecialChar(prev_char))
2809 return Encodings::transformChar(c, Encodings::FORM_FINAL);
2811 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
2816 int Paragraph::checkBiblio(Buffer const & buffer)
2819 // This is getting more and more a mess. ...We really should clean
2820 // up this bibitem issue for 1.6. See also bug 2743.
2822 // Add bibitem insets if necessary
2823 if (d->layout_->labeltype != LABEL_BIBLIO)
2826 bool hasbibitem = !d->insetlist_.empty()
2827 // Insist on it being in pos 0
2828 && d->text_[0] == META_INSET
2829 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
2831 bool track_changes = buffer.params().trackChanges;
2836 // remove a bibitem in pos != 0
2837 // restore it later in pos 0 if necessary
2838 // (e.g. if a user inserts contents _before_ the item)
2839 // we're assuming there's only one of these, which there
2841 int erasedInsetPosition = -1;
2842 InsetList::iterator it = d->insetlist_.begin();
2843 InsetList::iterator end = d->insetlist_.end();
2844 for (; it != end; ++it)
2845 if (it->inset->lyxCode() == BIBITEM_CODE
2847 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
2848 oldkey = olditem->getParam("key");
2849 oldlabel = olditem->getParam("label");
2850 erasedInsetPosition = it->pos;
2851 eraseChar(erasedInsetPosition, track_changes);
2855 // There was an InsetBibitem at the beginning, and we didn't
2856 // have to erase one.
2857 if (hasbibitem && erasedInsetPosition < 0)
2860 // There was an InsetBibitem at the beginning and we did have to
2861 // erase one. So we give its properties to the beginning inset.
2863 InsetBibitem * inset =
2864 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
2865 if (!oldkey.empty())
2866 inset->setParam("key", oldkey);
2867 inset->setParam("label", oldlabel);
2868 return -erasedInsetPosition;
2871 // There was no inset at the beginning, so we need to create one with
2872 // the key and label of the one we erased.
2873 InsetBibitem * inset =
2874 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
2875 // restore values of previously deleted item in this par.
2876 if (!oldkey.empty())
2877 inset->setParam("key", oldkey);
2878 inset->setParam("label", oldlabel);
2879 insertInset(0, static_cast<Inset *>(inset),
2880 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
2886 void Paragraph::checkAuthors(AuthorList const & authorList)
2888 d->changes_.checkAuthors(authorList);
2892 bool Paragraph::isChanged(pos_type pos) const
2894 return lookupChange(pos).changed();
2898 bool Paragraph::isInserted(pos_type pos) const
2900 return lookupChange(pos).inserted();
2904 bool Paragraph::isDeleted(pos_type pos) const
2906 return lookupChange(pos).deleted();
2910 InsetList const & Paragraph::insetList() const
2912 return d->insetlist_;
2916 void Paragraph::setBuffer(Buffer & b)
2918 d->insetlist_.setBuffer(b);
2922 Inset * Paragraph::releaseInset(pos_type pos)
2924 Inset * inset = d->insetlist_.release(pos);
2925 /// does not honour change tracking!
2926 eraseChar(pos, false);
2931 Inset * Paragraph::getInset(pos_type pos)
2933 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2934 ? d->insetlist_.get(pos) : 0;
2938 Inset const * Paragraph::getInset(pos_type pos) const
2940 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
2941 ? d->insetlist_.get(pos) : 0;
2945 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
2946 pos_type & right, TextCase action)
2948 // process sequences of modified characters; in change
2949 // tracking mode, this approach results in much better
2950 // usability than changing case on a char-by-char basis
2953 bool const trackChanges = bparams.trackChanges;
2955 bool capitalize = true;
2957 for (; pos < right; ++pos) {
2958 char_type oldChar = d->text_[pos];
2959 char_type newChar = oldChar;
2961 // ignore insets and don't play with deleted text!
2962 if (oldChar != META_INSET && !isDeleted(pos)) {
2964 case text_lowercase:
2965 newChar = lowercase(oldChar);
2967 case text_capitalization:
2969 newChar = uppercase(oldChar);
2973 case text_uppercase:
2974 newChar = uppercase(oldChar);
2979 if (isWordSeparator(pos) || isDeleted(pos)) {
2980 // permit capitalization again
2984 if (oldChar != newChar) {
2986 if (pos != right - 1)
2988 // step behind the changing area
2992 int erasePos = pos - changes.size();
2993 for (size_t i = 0; i < changes.size(); i++) {
2994 insertChar(pos, changes[i],
2995 getFontSettings(bparams,
2998 if (!eraseChar(erasePos, trackChanges)) {
3001 ++right; // expand selection
3009 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3010 pos_type pos, bool del) const
3012 int const strsize = str.length();
3014 pos_type const parsize = d->text_.size();
3015 for (i = 0; pos + i < parsize; ++i) {
3018 if (cs && str[i] != d->text_[pos + i])
3020 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3022 if (!del && isDeleted(pos + i))
3029 // if necessary, check whether string matches word
3031 if (pos > 0 && !isWordSeparator(pos - 1))
3033 if (pos + strsize < parsize
3034 && !isWordSeparator(pos + strsize))
3042 char_type Paragraph::getChar(pos_type pos) const
3044 return d->text_[pos];
3048 pos_type Paragraph::size() const
3050 return d->text_.size();
3054 bool Paragraph::empty() const
3056 return d->text_.empty();
3060 bool Paragraph::isInset(pos_type pos) const
3062 return d->text_[pos] == META_INSET;
3066 bool Paragraph::isSeparator(pos_type pos) const
3068 //FIXME: Are we sure this can be the only separator?
3069 return d->text_[pos] == ' ';
3073 void Paragraph::deregisterWords()
3075 map<Language, Private::Words>::const_iterator itl = d->words_.begin();
3076 map<Language, Private::Words>::const_iterator ite = d->words_.end();
3077 for (; itl != ite; ++itl) {
3078 WordList * wl = theWordList(itl->first);
3079 Private::Words::const_iterator it = (itl->second).begin();
3080 Private::Words::const_iterator et = (itl->second).end();
3081 for (; it != et; ++it)
3088 void Paragraph::locateWord(pos_type & from, pos_type & to,
3089 word_location const loc) const
3092 case WHOLE_WORD_STRICT:
3093 if (from == 0 || from == size()
3094 || isWordSeparator(from)
3095 || isWordSeparator(from - 1)) {
3099 // no break here, we go to the next
3102 // If we are already at the beginning of a word, do nothing
3103 if (!from || isWordSeparator(from - 1))
3105 // no break here, we go to the next
3108 // always move the cursor to the beginning of previous word
3109 while (from && !isWordSeparator(from - 1))
3113 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3116 // no need to move the 'from' cursor
3120 while (to < size() && !isWordSeparator(to))
3125 void Paragraph::collectWords()
3127 pos_type n = size();
3128 for (pos_type pos = 0; pos < n; ++pos) {
3129 if (isWordSeparator(pos))
3131 pos_type from = pos;
3132 locateWord(from, pos, WHOLE_WORD);
3133 if (pos - from >= 6) {
3134 docstring word = asString(from, pos, AS_STR_NONE);
3135 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3136 if (cit == d->fontlist_.end())
3138 Language const * lang = cit->font().language();
3139 d->words_[*lang].insert(word);
3145 void Paragraph::registerWords()
3147 map<Language, Private::Words>::const_iterator itl;
3148 Private::Words::const_iterator it;
3149 for (itl = d->words_.begin(); itl != d->words_.end(); ++itl) {
3150 WordList * wl = theWordList(itl->first);
3151 for (it = (itl->second).begin(); it != (itl->second).end(); ++it)
3157 void Paragraph::updateWords()
3165 bool Paragraph::spellCheck(pos_type & from, pos_type & to, WordLangTuple & wl,
3166 docstring_list & suggestions, bool do_suggestion) const
3168 SpellChecker * speller = theSpellChecker();
3172 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3175 locateWord(from, to, WHOLE_WORD);
3176 if (from == to || from >= pos_type(d->text_.size()))
3179 docstring word = asString(from, to, AS_STR_INSETS);
3180 // Ignore words with digits
3181 // FIXME: make this customizable
3182 // (note that hunspell ignores words with digits by default)
3183 bool const ignored = hasDigit(word);
3184 Language * lang = const_cast<Language *>(getFontSettings(
3185 d->inset_owner_->buffer().params(), from).language());
3186 if (lang == d->inset_owner_->buffer().params().language
3187 && !lyxrc.spellchecker_alt_lang.empty()) {
3189 string const lang_variety =
3190 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3191 lang->setCode(lang_code);
3192 lang->setVariety(lang_variety);
3194 wl = WordLangTuple(word, lang);
3195 SpellChecker::Result res = ignored ?
3196 SpellChecker::OK : speller->check(wl);
3198 // FIXME: the code below makes aspell abort if a word in an unknown
3199 // language is checked.
3200 // Just ignore any error that the spellchecker reports.
3201 // FIXME: we should through out an exception and catch it in the GUI to
3202 // display the error.
3203 if (!speller->error().empty())
3207 bool const misspelled = res != SpellChecker::OK
3208 && res != SpellChecker::IGNORED_WORD;
3210 if (lyxrc.spellcheck_continuously)
3211 d->fontlist_.setMisspelled(from, to, misspelled);
3213 if (misspelled && do_suggestion)
3214 speller->suggest(wl, suggestions);
3216 suggestions.clear();
3222 bool Paragraph::isMisspelled(pos_type pos) const
3224 pos_type from = pos;
3227 docstring_list suggestions;
3228 return spellCheck(from, to, wl, suggestions, false);
3232 string Paragraph::magicLabel() const
3235 ss << "magicparlabel-" << id();