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;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 class SpellCheckerState {
86 needs_refresh_ = true;
87 current_change_number_ = 0;
90 void setRange(FontSpan const fp, SpellChecker::Result state)
92 eraseCoveredRanges(fp);
93 if (state != SpellChecker::WORD_OK)
97 void increasePosAfterPos(pos_type pos)
99 correctRangesAfterPos(pos, 1);
103 void decreasePosAfterPos(pos_type pos)
105 correctRangesAfterPos(pos, -1);
109 SpellChecker::Result getState(pos_type pos) const
111 SpellChecker::Result result = SpellChecker::WORD_OK;
112 RangesIterator et = ranges_.end();
113 RangesIterator it = ranges_.begin();
114 for (; it != et; ++it) {
115 FontSpan fc = it->first;
116 if(fc.first <= pos && pos <= fc.last) {
124 bool needsRefresh() const {
125 return needs_refresh_;
128 SpellChecker::ChangeNumber currentChangeNumber() const {
129 return current_change_number_;
132 void refreshRange(pos_type & first, pos_type & last) const {
133 first = refresh_.first;
134 last = refresh_.last;
137 void needsRefresh(pos_type pos) {
138 if (needs_refresh_ && pos != -1) {
139 if (pos < refresh_.first)
140 refresh_.first = pos;
141 if (pos > refresh_.last)
143 } else if (pos != -1) {
144 refresh_.first = pos;
147 needs_refresh_ = pos != -1;
150 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
151 needs_refresh_ = true;
154 current_change_number_ = change_number;
158 /// store the ranges as map of FontSpan and spell result pairs
159 typedef map<FontSpan, SpellChecker::Result> Ranges;
160 typedef Ranges::const_iterator RangesIterator;
165 SpellChecker::ChangeNumber current_change_number_;
167 void eraseCoveredRanges(FontSpan const fp)
170 RangesIterator et = ranges_.end();
171 RangesIterator it = ranges_.begin();
172 for (; it != et; ++it) {
173 FontSpan fc = it->first;
174 // 1. first of new range inside current range or
175 // 2. last of new range inside current range or
176 // 3. first of current range inside new range or
177 // 4. last of current range inside new range or
178 if ((fc.first <= fp.first && fp.first <= fc.last) ||
179 (fc.first <= fp.last && fp.last <= fc.last) ||
180 (fp.first <= fc.first && fc.first <= fp.last) ||
181 (fp.first <= fc.last && fc.last <= fp.last))
185 result[fc] = it->second;
190 void correctRangesAfterPos(pos_type pos, int offset)
193 RangesIterator et = ranges_.end();
194 RangesIterator it = ranges_.begin();
195 for (; it != et; ++it) {
196 FontSpan m = it->first;
200 } else if (m.last > pos) {
203 result[m] = it->second;
210 /////////////////////////////////////////////////////////////////////
212 // Paragraph::Private
214 /////////////////////////////////////////////////////////////////////
216 class Paragraph::Private
220 Private(Paragraph * owner, Layout const & layout);
221 /// "Copy constructor"
222 Private(Private const &, Paragraph * owner);
223 /// Copy constructor from \p beg to \p end
224 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
227 void insertChar(pos_type pos, char_type c, Change const & change);
229 /// Output the surrogate pair formed by \p c and \p next to \p os.
230 /// \return the number of characters written.
231 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
232 OutputParams const &);
234 /// Output a space in appropriate formatting (or a surrogate pair
235 /// if the next character is a combining character).
236 /// \return whether a surrogate pair was output.
237 bool simpleTeXBlanks(OutputParams const &,
238 odocstream &, TexRow & texrow,
240 unsigned int & column,
242 Layout const & style);
244 /// Output consecutive unicode chars, belonging to the same script as
245 /// specified by the latex macro \p ltx, to \p os starting from \p i.
246 /// \return the number of characters written.
247 int writeScriptChars(odocstream & os, docstring const & ltx,
248 Change const &, Encoding const &, pos_type & i);
250 /// This could go to ParagraphParameters if we want to.
251 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
252 OutputParams const &) const;
254 /// This could go to ParagraphParameters if we want to.
255 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
256 OutputParams const &) const;
259 void latexInset(BufferParams const &,
261 TexRow & texrow, OutputParams &,
264 Font const & outerfont,
266 Change & running_change,
267 Layout const & style,
269 unsigned int & column);
272 void latexSpecialChar(
274 OutputParams const & runparams,
275 Font const & running_font,
276 Change const & running_change,
277 Layout const & style,
279 unsigned int & column);
286 unsigned int & column);
288 bool latexSpecialTypewriter(
292 unsigned int & column);
294 bool latexSpecialPhrase(
297 unsigned int & column,
298 OutputParams const & runparams);
301 void validate(LaTeXFeatures & features) const;
303 /// Checks if the paragraph contains only text and no inset or font change.
304 bool onlyText(Buffer const & buf, Font const & outerfont,
305 pos_type initial) const;
307 /// match a string against a particular point in the paragraph
308 bool isTextAt(string const & str, pos_type pos) const;
310 /// a vector of inset positions
311 typedef vector<pos_type> Positions;
312 typedef Positions::const_iterator PositionsIterator;
314 Language * getSpellLanguage(pos_type const from) const;
316 Language * locateSpellRange(pos_type & from, pos_type & to,
317 Positions & softbreaks) const;
319 bool hasSpellerChange() const {
320 SpellChecker::ChangeNumber speller_change_number = 0;
321 if (theSpellChecker())
322 speller_change_number = theSpellChecker()->changeNumber();
323 return speller_change_number > speller_state_.currentChangeNumber();
326 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
328 pos_type textsize = owner_->size();
329 // check for sane arguments
330 if (to < from || from >= textsize)
332 FontSpan fp = FontSpan(from, to);
333 // don't mark end of paragraph
334 if (fp.last >= textsize)
335 fp.last = textsize - 1;
336 speller_state_.setRange(fp, state);
339 void requestSpellCheck(pos_type pos) {
340 speller_state_.needsRefresh(pos);
343 void readySpellCheck() {
344 speller_state_.needsRefresh(-1);
347 bool needsSpellCheck() const
349 return speller_state_.needsRefresh();
352 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
354 speller_state_.refreshRange(first, last);
356 last = owner_->size();
359 pos_type endpos = last;
360 owner_->locateWord(first, endpos, WHOLE_WORD);
363 owner_->locateWord(last, endpos, WHOLE_WORD);
368 void markMisspelledWords(pos_type const & first, pos_type const & last,
369 SpellChecker::Result result,
370 docstring const & word,
371 Positions const & softbreaks);
373 InsetCode ownerCode() const
375 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
378 /// Which Paragraph owns us?
382 Inset const * inset_owner_;
391 ParagraphParameters params_;
393 /// for recording and looking up changes
397 InsetList insetlist_;
400 pos_type begin_of_body_;
402 typedef docstring TextContainer;
406 typedef set<docstring> Words;
407 typedef map<Language, Words> LangWordsMap;
411 Layout const * layout_;
413 SpellCheckerState speller_state_;
419 struct special_phrase {
425 special_phrase const special_phrases[] = {
426 { "LyX", from_ascii("\\LyX{}"), false },
427 { "TeX", from_ascii("\\TeX{}"), true },
428 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
429 { "LaTeX", from_ascii("\\LaTeX{}"), true },
432 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
437 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
438 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
444 // Initialization of the counter for the paragraph id's,
446 // FIXME: There should be a more intelligent way to generate and use the
447 // paragraph ids per buffer instead a global static counter for all InsetText
448 // in the running program.
449 static int paragraph_id = -1;
451 Paragraph::Private::Private(Private const & p, Paragraph * owner)
452 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
453 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
454 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
455 layout_(p.layout_), speller_state_(p.speller_state_)
457 id_ = ++paragraph_id;
458 requestSpellCheck(p.text_.size());
462 Paragraph::Private::Private(Private const & p, Paragraph * owner,
463 pos_type beg, pos_type end)
464 : owner_(owner), inset_owner_(p.inset_owner_),
465 params_(p.params_), changes_(p.changes_),
466 insetlist_(p.insetlist_, beg, end),
467 begin_of_body_(p.begin_of_body_), words_(p.words_),
468 layout_(p.layout_), speller_state_(p.speller_state_)
470 id_ = ++paragraph_id;
471 if (beg >= pos_type(p.text_.size()))
473 text_ = p.text_.substr(beg, end - beg);
475 FontList::const_iterator fcit = fontlist_.begin();
476 FontList::const_iterator fend = fontlist_.end();
477 for (; fcit != fend; ++fcit) {
478 if (fcit->pos() < beg)
480 if (fcit->pos() >= end) {
481 // Add last entry in the fontlist_.
482 fontlist_.set(text_.size() - 1, fcit->font());
485 // Add a new entry in the fontlist_.
486 fontlist_.set(fcit->pos() - beg, fcit->font());
488 requestSpellCheck(p.text_.size());
492 void Paragraph::addChangesToToc(DocIterator const & cdit,
493 Buffer const & buf) const
495 d->changes_.addToToc(cdit, buf);
499 bool Paragraph::isDeleted(pos_type start, pos_type end) const
501 LASSERT(start >= 0 && start <= size(), /**/);
502 LASSERT(end > start && end <= size() + 1, /**/);
504 return d->changes_.isDeleted(start, end);
508 bool Paragraph::isChanged(pos_type start, pos_type end) const
510 LASSERT(start >= 0 && start <= size(), /**/);
511 LASSERT(end > start && end <= size() + 1, /**/);
513 return d->changes_.isChanged(start, end);
517 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
519 // keep the logic here in sync with the logic of eraseChars()
523 Change const change = d->changes_.lookup(size());
524 return change.inserted() && change.currentAuthor();
528 void Paragraph::setChange(Change const & change)
530 // beware of the imaginary end-of-par character!
531 d->changes_.set(change, 0, size() + 1);
534 * Propagate the change recursively - but not in case of DELETED!
536 * Imagine that your co-author makes changes in an existing inset. He
537 * sends your document to you and you come to the conclusion that the
538 * inset should go completely. If you erase it, LyX must not delete all
539 * text within the inset. Otherwise, the change tracked insertions of
540 * your co-author get lost and there is no way to restore them later.
542 * Conclusion: An inset's content should remain untouched if you delete it
545 if (!change.deleted()) {
546 for (pos_type pos = 0; pos < size(); ++pos) {
547 if (Inset * inset = getInset(pos))
548 inset->setChange(change);
554 void Paragraph::setChange(pos_type pos, Change const & change)
556 LASSERT(pos >= 0 && pos <= size(), /**/);
557 d->changes_.set(change, pos);
559 // see comment in setChange(Change const &) above
560 if (!change.deleted() && pos < size())
561 if (Inset * inset = getInset(pos))
562 inset->setChange(change);
566 Change const & Paragraph::lookupChange(pos_type pos) const
568 LASSERT(pos >= 0 && pos <= size(), /**/);
569 return d->changes_.lookup(pos);
573 void Paragraph::acceptChanges(pos_type start, pos_type end)
575 LASSERT(start >= 0 && start <= size(), /**/);
576 LASSERT(end > start && end <= size() + 1, /**/);
578 for (pos_type pos = start; pos < end; ++pos) {
579 switch (lookupChange(pos).type) {
580 case Change::UNCHANGED:
581 // accept changes in nested inset
582 if (Inset * inset = getInset(pos))
583 inset->acceptChanges();
586 case Change::INSERTED:
587 d->changes_.set(Change(Change::UNCHANGED), pos);
588 // also accept changes in nested inset
589 if (Inset * inset = getInset(pos))
590 inset->acceptChanges();
593 case Change::DELETED:
594 // Suppress access to non-existent
595 // "end-of-paragraph char"
597 eraseChar(pos, false);
608 void Paragraph::rejectChanges(pos_type start, pos_type end)
610 LASSERT(start >= 0 && start <= size(), /**/);
611 LASSERT(end > start && end <= size() + 1, /**/);
613 for (pos_type pos = start; pos < end; ++pos) {
614 switch (lookupChange(pos).type) {
615 case Change::UNCHANGED:
616 // reject changes in nested inset
617 if (Inset * inset = getInset(pos))
618 inset->rejectChanges();
621 case Change::INSERTED:
622 // Suppress access to non-existent
623 // "end-of-paragraph char"
625 eraseChar(pos, false);
631 case Change::DELETED:
632 d->changes_.set(Change(Change::UNCHANGED), pos);
634 // Do NOT reject changes within a deleted inset!
635 // There may be insertions of a co-author inside of it!
643 void Paragraph::Private::insertChar(pos_type pos, char_type c,
644 Change const & change)
646 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
649 changes_.insert(change, pos);
651 // This is actually very common when parsing buffers (and
652 // maybe inserting ascii text)
653 if (pos == pos_type(text_.size())) {
654 // when appending characters, no need to update tables
656 // but we want spell checking
657 requestSpellCheck(pos);
661 text_.insert(text_.begin() + pos, c);
663 // Update the font table.
664 fontlist_.increasePosAfterPos(pos);
667 insetlist_.increasePosAfterPos(pos);
669 // Update list of misspelled positions
670 speller_state_.increasePosAfterPos(pos);
674 bool Paragraph::insertInset(pos_type pos, Inset * inset,
675 Change const & change)
677 LASSERT(inset, /**/);
678 LASSERT(pos >= 0 && pos <= size(), /**/);
680 // Paragraph::insertInset() can be used in cut/copy/paste operation where
681 // d->inset_owner_ is not set yet.
682 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
685 d->insertChar(pos, META_INSET, change);
686 LASSERT(d->text_[pos] == META_INSET, /**/);
688 // Add a new entry in the insetlist_.
689 d->insetlist_.insert(inset, pos);
691 // Some insets require run of spell checker
692 requestSpellCheck(pos);
697 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
699 LASSERT(pos >= 0 && pos <= size(), return false);
701 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
704 Change change = d->changes_.lookup(pos);
706 // set the character to DELETED if
707 // a) it was previously unchanged or
708 // b) it was inserted by a co-author
710 if (!change.changed() ||
711 (change.inserted() && !change.currentAuthor())) {
712 setChange(pos, Change(Change::DELETED));
716 if (change.deleted())
720 // Don't physically access the imaginary end-of-paragraph character.
721 // eraseChar() can only mark it as DELETED. A physical deletion of
722 // end-of-par must be handled externally.
728 d->changes_.erase(pos);
730 // if it is an inset, delete the inset entry
731 if (d->text_[pos] == META_INSET)
732 d->insetlist_.erase(pos);
734 d->text_.erase(d->text_.begin() + pos);
736 // Update the fontlist_
737 d->fontlist_.erase(pos);
739 // Update the insetlist_
740 d->insetlist_.decreasePosAfterPos(pos);
742 // Update list of misspelled positions
743 d->speller_state_.decreasePosAfterPos(pos);
749 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
751 LASSERT(start >= 0 && start <= size(), /**/);
752 LASSERT(end >= start && end <= size() + 1, /**/);
755 for (pos_type count = end - start; count; --count) {
756 if (!eraseChar(i, trackChanges))
763 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
764 char_type next, OutputParams const & runparams)
766 // Writing next here may circumvent a possible font change between
767 // c and next. Since next is only output if it forms a surrogate pair
768 // with c we can ignore this:
769 // A font change inside a surrogate pair does not make sense and is
770 // hopefully impossible to input.
771 // FIXME: change tracking
772 // Is this correct WRT change tracking?
773 Encoding const & encoding = *(runparams.encoding);
774 docstring const latex1 = encoding.latexChar(next);
775 docstring const latex2 = encoding.latexChar(c);
776 if (docstring(1, next) == latex1) {
777 // the encoding supports the combination
778 os << latex2 << latex1;
779 return latex1.length() + latex2.length();
780 } else if (runparams.local_font &&
781 runparams.local_font->language()->lang() == "polutonikogreek") {
782 // polutonikogreek only works without the brackets
783 os << latex1 << latex2;
784 return latex1.length() + latex2.length();
786 os << latex1 << '{' << latex2 << '}';
787 return latex1.length() + latex2.length() + 2;
791 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
792 odocstream & os, TexRow & texrow,
794 unsigned int & column,
796 Layout const & style)
798 if (style.pass_thru || runparams.pass_thru)
801 if (i + 1 < int(text_.size())) {
802 char_type next = text_[i + 1];
803 if (Encodings::isCombiningChar(next)) {
804 // This space has an accent, so we must always output it.
805 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
810 if (runparams.linelen > 0
811 && column > runparams.linelen
813 && text_[i - 1] != ' '
814 && (i + 1 < int(text_.size()))
815 // same in FreeSpacing mode
816 && !owner_->isFreeSpacing()
817 // In typewriter mode, we want to avoid
818 // ! . ? : at the end of a line
819 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
820 && (text_[i - 1] == '.'
821 || text_[i - 1] == '?'
822 || text_[i - 1] == ':'
823 || text_[i - 1] == '!'))) {
826 texrow.start(owner_->id(), i + 1);
828 } else if (style.free_spacing) {
837 int Paragraph::Private::writeScriptChars(odocstream & os,
838 docstring const & ltx,
839 Change const & runningChange,
840 Encoding const & encoding,
843 // FIXME: modifying i here is not very nice...
845 // We only arrive here when a proper language for character text_[i] has
846 // not been specified (i.e., it could not be translated in the current
847 // latex encoding) or its latex translation has been forced, and it
848 // belongs to a known script.
849 // Parameter ltx contains the latex translation of text_[i] as specified
850 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
851 // The latex macro name "textXXX" specifies the script to which text_[i]
852 // belongs and we use it in order to check whether characters from the
853 // same script immediately follow, such that we can collect them in a
854 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
855 // for the first char but only "<spec>" for all subsequent chars.
856 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
857 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
858 string script = to_ascii(ltx.substr(1, brace1 - 1));
861 bool closing_brace = true;
862 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
863 // Correct encoding is being used, so we can avoid \textgreek.
866 closing_brace = false;
868 os << ltx.substr(pos, length);
869 int size = text_.size();
870 while (i + 1 < size) {
871 char_type const next = text_[i + 1];
872 // Stop here if next character belongs to another script
873 // or there is a change in change tracking status.
874 if (!Encodings::isKnownScriptChar(next, script) ||
875 runningChange != owner_->lookupChange(i + 1))
879 FontList::const_iterator cit = fontlist_.begin();
880 FontList::const_iterator end = fontlist_.end();
881 for (; cit != end; ++cit) {
882 if (cit->pos() >= i && !found) {
883 prev_font = cit->font();
886 if (cit->pos() >= i + 1)
889 // Stop here if there is a font attribute or encoding change.
890 if (found && cit != end && prev_font != cit->font())
892 docstring const latex = encoding.latexChar(next);
893 docstring::size_type const b1 =
894 latex.find_first_of(from_ascii("{"));
895 docstring::size_type const b2 =
896 latex.find_last_of(from_ascii("}"));
897 int const len = b2 - b1 - 1;
898 os << latex.substr(b1 + 1, len);
910 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
912 pos_type const len = str.length();
914 // is the paragraph large enough?
915 if (pos + len > int(text_.size()))
918 // does the wanted text start at point?
919 for (string::size_type i = 0; i < str.length(); ++i) {
920 // Caution: direct comparison of characters works only
921 // because str is pure ASCII.
922 if (str[i] != text_[pos + i])
926 return fontlist_.hasChangeInRange(pos, len);
930 void Paragraph::Private::latexInset(BufferParams const & bparams,
933 OutputParams & runparams,
936 Font const & outerfont,
938 Change & running_change,
939 Layout const & style,
941 unsigned int & column)
943 Inset * inset = owner_->getInset(i);
944 LASSERT(inset, /**/);
946 if (style.pass_thru) {
947 inset->plaintext(os, runparams);
951 // FIXME: move this to InsetNewline::latex
952 if (inset->lyxCode() == NEWLINE_CODE) {
953 // newlines are handled differently here than
954 // the default in simpleTeXSpecialChars().
955 if (!style.newline_allowed) {
959 column += running_font.latexWriteEndChanges(
960 os, bparams, runparams,
965 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
968 basefont = owner_->getLayoutFont(bparams, outerfont);
969 running_font = basefont;
971 if (runparams.moving_arg)
976 texrow.start(owner_->id(), i + 1);
980 if (owner_->isDeleted(i)) {
981 if( ++runparams.inDeletedInset == 1)
982 runparams.changeOfDeletedInset = owner_->lookupChange(i);
985 if (inset->canTrackChanges()) {
986 column += Changes::latexMarkChange(os, bparams, running_change,
987 Change(Change::UNCHANGED), runparams);
988 running_change = Change(Change::UNCHANGED);
992 odocstream::pos_type const len = os.tellp();
994 if (inset->forceLTR()
995 && running_font.isRightToLeft()
996 // ERT is an exception, it should be output with no
997 // decorations at all
998 && inset->lyxCode() != ERT_CODE) {
999 if (running_font.language()->lang() == "farsi")
1006 // FIXME: Bug: we can have an empty font change here!
1007 // if there has just been a font change, we are going to close it
1008 // right now, which means stupid latex code like \textsf{}. AFAIK,
1009 // this does not harm dvi output. A minor bug, thus (JMarc)
1011 // Some insets cannot be inside a font change command.
1012 // However, even such insets *can* be placed in \L or \R
1013 // or their equivalents (for RTL language switches), so we don't
1014 // close the language in those cases.
1015 // ArabTeX, though, cannot handle this special behavior, it seems.
1016 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1017 || running_font.language()->lang() == "arabic_arabtex";
1018 if (open_font && inset->noFontChange()) {
1019 bool closeLanguage = arabtex
1020 || basefont.isRightToLeft() == running_font.isRightToLeft();
1021 unsigned int count = running_font.latexWriteEndChanges(os,
1022 bparams, runparams, basefont, basefont, closeLanguage);
1024 // if any font properties were closed, update the running_font,
1025 // making sure, however, to leave the language as it was
1027 // FIXME: probably a better way to keep track of the old
1028 // language, than copying the entire font?
1029 Font const copy_font(running_font);
1030 basefont = owner_->getLayoutFont(bparams, outerfont);
1031 running_font = basefont;
1033 running_font.setLanguage(copy_font.language());
1034 // leave font open if language is still open
1035 open_font = (running_font.language() == basefont.language());
1037 runparams.local_font = &basefont;
1044 tmp = inset->latex(os, runparams);
1045 } catch (EncodingException & e) {
1046 // add location information and throw again.
1053 if (running_font.language()->lang() == "farsi")
1060 texrow.newlines(tmp);
1061 texrow.start(owner_->id(), i + 1);
1064 column += os.tellp() - len;
1067 if (owner_->isDeleted(i))
1068 --runparams.inDeletedInset;
1072 void Paragraph::Private::latexSpecialChar(
1074 OutputParams const & runparams,
1075 Font const & running_font,
1076 Change const & running_change,
1077 Layout const & style,
1079 unsigned int & column)
1081 char_type const c = text_[i];
1083 if (style.pass_thru || runparams.pass_thru) {
1085 // FIXME UNICODE: This can fail if c cannot
1086 // be encoded in the current encoding.
1091 // If T1 font encoding is used, use the special
1092 // characters it provides.
1093 // NOTE: some languages reset the font encoding
1095 if (!running_font.language()->internalFontEncoding()
1096 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1099 // \tt font needs special treatment
1100 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1101 && latexSpecialTypewriter(c, os, i, column))
1104 // Otherwise, we use what LaTeX provides us.
1107 os << "\\textbackslash{}";
1111 os << "\\textless{}";
1115 os << "\\textgreater{}";
1119 os << "\\textbar{}";
1126 os << "\\char`\\\"{}";
1131 case '%': case '#': case '{':
1139 os << "\\textasciitilde{}";
1144 os << "\\textasciicircum{}";
1151 // avoid being mistaken for optional arguments
1159 // Blanks are printed before font switching.
1160 // Sure? I am not! (try nice-latex)
1161 // I am sure it's correct. LyX might be smarter
1162 // in the future, but for now, nothing wrong is
1168 if (latexSpecialPhrase(os, i, column, runparams))
1174 Encoding const & encoding = *(runparams.encoding);
1175 if (i + 1 < int(text_.size())) {
1176 char_type next = text_[i + 1];
1177 if (Encodings::isCombiningChar(next)) {
1178 column += latexSurrogatePair(os, c, next, runparams) - 1;
1184 docstring const latex = encoding.latexChar(c);
1185 if (Encodings::isKnownScriptChar(c, script)
1186 && prefixIs(latex, from_ascii("\\" + script)))
1187 column += writeScriptChars(os, latex,
1188 running_change, encoding, i) - 1;
1189 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1190 // Prevent eating of a following
1191 // space or command corruption by
1192 // following characters
1193 column += latex.length() + 1;
1194 os << latex << "{}";
1196 column += latex.length() - 1;
1204 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1205 pos_type i, unsigned int & column)
1211 // In T1 encoding, these characters exist
1212 // but we should avoid ligatures
1213 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1215 os << "\\textcompwordmark{}";
1222 // soul.sty breaks with \char`\"
1223 os << "\\textquotedbl{}";
1232 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1233 pos_type i, unsigned int & column)
1237 // within \ttfamily, "--" is merged to "-" (no endash)
1238 // so we avoid this rather irritating ligature
1239 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1246 // everything else has to be checked separately
1247 // (depending on the encoding)
1254 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1255 unsigned int & column, OutputParams const & runparams)
1257 // FIXME: if we have "LaTeX" with a font
1258 // change in the middle (before the 'T', then
1259 // the "TeX" part is still special cased.
1260 // Really we should only operate this on
1261 // "words" for some definition of word
1263 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1264 if (!isTextAt(special_phrases[pnr].phrase, i))
1266 if (runparams.moving_arg)
1268 os << special_phrases[pnr].macro;
1269 i += special_phrases[pnr].phrase.length() - 1;
1270 column += special_phrases[pnr].macro.length() - 1;
1277 void Paragraph::Private::validate(LaTeXFeatures & features) const
1279 if (layout_->inpreamble && inset_owner_) {
1280 Buffer const & buf = inset_owner_->buffer();
1281 BufferParams const & bp = buf.params();
1284 odocstringstream ods;
1285 // we have to provide all the optional arguments here, even though
1286 // the last one is the only one we care about.
1287 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1288 docstring const d = ods.str();
1290 // this will have "{" at the beginning, but not at the end
1291 string const content = to_utf8(d);
1292 string const cmd = layout_->latexname();
1293 features.addPreambleSnippet("\\" + cmd + content + "}");
1297 if (features.runparams().flavor == OutputParams::HTML
1298 && layout_->htmltitle()) {
1299 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1302 // check the params.
1303 if (!params_.spacing().isDefault())
1304 features.require("setspace");
1307 features.useLayout(layout_->name());
1310 fontlist_.validate(features);
1312 // then the indentation
1313 if (!params_.leftIndent().zero())
1314 features.require("ParagraphLeftIndent");
1317 InsetList::const_iterator icit = insetlist_.begin();
1318 InsetList::const_iterator iend = insetlist_.end();
1319 for (; icit != iend; ++icit) {
1321 icit->inset->validate(features);
1322 if (layout_->needprotect &&
1323 icit->inset->lyxCode() == FOOT_CODE)
1324 features.require("NeedLyXFootnoteCode");
1328 // then the contents
1329 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1330 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1331 if (!special_phrases[pnr].builtin
1332 && isTextAt(special_phrases[pnr].phrase, i)) {
1333 features.require(special_phrases[pnr].phrase);
1337 Encodings::validate(text_[i], features);
1341 /////////////////////////////////////////////////////////////////////
1345 /////////////////////////////////////////////////////////////////////
1348 Layout const emptyParagraphLayout;
1351 Paragraph::Paragraph()
1352 : d(new Paragraph::Private(this, emptyParagraphLayout))
1359 Paragraph::Paragraph(Paragraph const & par)
1360 : itemdepth(par.itemdepth),
1361 d(new Paragraph::Private(*par.d, this))
1367 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1368 : itemdepth(par.itemdepth),
1369 d(new Paragraph::Private(*par.d, this, beg, end))
1375 Paragraph & Paragraph::operator=(Paragraph const & par)
1377 // needed as we will destroy the private part before copying it
1379 itemdepth = par.itemdepth;
1383 d = new Private(*par.d, this);
1390 Paragraph::~Paragraph()
1399 // this shall be called just before every "os << ..." action.
1400 void flushString(ostream & os, docstring & s)
1409 void Paragraph::write(ostream & os, BufferParams const & bparams,
1410 depth_type & dth) const
1412 // The beginning or end of a deeper (i.e. nested) area?
1413 if (dth != d->params_.depth()) {
1414 if (d->params_.depth() > dth) {
1415 while (d->params_.depth() > dth) {
1416 os << "\n\\begin_deeper";
1420 while (d->params_.depth() < dth) {
1421 os << "\n\\end_deeper";
1427 // First write the layout
1428 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1430 d->params_.write(os);
1432 Font font1(inherit_font, bparams.language);
1434 Change running_change = Change(Change::UNCHANGED);
1436 // this string is used as a buffer to avoid repetitive calls
1437 // to to_utf8(), which turn out to be expensive (JMarc)
1438 docstring write_buffer;
1441 for (pos_type i = 0; i <= size(); ++i) {
1443 Change const change = lookupChange(i);
1444 if (change != running_change)
1445 flushString(os, write_buffer);
1446 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1447 running_change = change;
1452 // Write font changes
1453 Font font2 = getFontSettings(bparams, i);
1454 if (font2 != font1) {
1455 flushString(os, write_buffer);
1456 font2.lyxWriteChanges(font1, os);
1461 char_type const c = d->text_[i];
1464 if (Inset const * inset = getInset(i)) {
1465 flushString(os, write_buffer);
1466 if (inset->directWrite()) {
1467 // international char, let it write
1468 // code directly so it's shorter in
1474 os << "\\begin_inset ";
1476 os << "\n\\end_inset\n\n";
1482 flushString(os, write_buffer);
1483 os << "\n\\backslash\n";
1487 flushString(os, write_buffer);
1488 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1495 if ((column > 70 && c == ' ')
1497 flushString(os, write_buffer);
1501 // this check is to amend a bug. LyX sometimes
1502 // inserts '\0' this could cause problems.
1504 write_buffer.push_back(c);
1506 LYXERR0("NUL char in structure.");
1512 flushString(os, write_buffer);
1513 os << "\n\\end_layout\n";
1517 void Paragraph::validate(LaTeXFeatures & features) const
1519 d->validate(features);
1523 void Paragraph::insert(pos_type start, docstring const & str,
1524 Font const & font, Change const & change)
1526 for (size_t i = 0, n = str.size(); i != n ; ++i)
1527 insertChar(start + i, str[i], font, change);
1531 void Paragraph::appendChar(char_type c, Font const & font,
1532 Change const & change)
1535 d->changes_.insert(change, d->text_.size());
1536 // when appending characters, no need to update tables
1537 d->text_.push_back(c);
1538 setFont(d->text_.size() - 1, font);
1542 void Paragraph::appendString(docstring const & s, Font const & font,
1543 Change const & change)
1545 pos_type end = s.size();
1546 size_t oldsize = d->text_.size();
1547 size_t newsize = oldsize + end;
1548 size_t capacity = d->text_.capacity();
1549 if (newsize >= capacity)
1550 d->text_.reserve(max(capacity + 100, newsize));
1552 // when appending characters, no need to update tables
1555 // FIXME: Optimize this!
1556 for (size_t i = oldsize; i != newsize; ++i) {
1558 d->changes_.insert(change, i);
1560 d->fontlist_.set(oldsize, font);
1561 d->fontlist_.set(newsize - 1, font);
1565 void Paragraph::insertChar(pos_type pos, char_type c,
1568 d->insertChar(pos, c, Change(trackChanges ?
1569 Change::INSERTED : Change::UNCHANGED));
1573 void Paragraph::insertChar(pos_type pos, char_type c,
1574 Font const & font, bool trackChanges)
1576 d->insertChar(pos, c, Change(trackChanges ?
1577 Change::INSERTED : Change::UNCHANGED));
1582 void Paragraph::insertChar(pos_type pos, char_type c,
1583 Font const & font, Change const & change)
1585 d->insertChar(pos, c, change);
1590 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1591 Font const & font, Change const & change)
1593 bool const success = insertInset(pos, inset, change);
1594 // Set the font/language of the inset...
1600 void Paragraph::resetFonts(Font const & font)
1602 d->fontlist_.clear();
1603 d->fontlist_.set(0, font);
1604 d->fontlist_.set(d->text_.size() - 1, font);
1607 // Gets uninstantiated font setting at position.
1608 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1612 LYXERR0("pos: " << pos << " size: " << size());
1613 LASSERT(pos <= size(), /**/);
1616 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1617 if (cit != d->fontlist_.end())
1620 if (pos == size() && !empty())
1621 return getFontSettings(bparams, pos - 1);
1623 // Optimisation: avoid a full font instantiation if there is no
1624 // language change from previous call.
1625 static Font previous_font;
1626 static Language const * previous_lang = 0;
1627 Language const * lang = getParLanguage(bparams);
1628 if (lang != previous_lang) {
1629 previous_lang = lang;
1630 previous_font = Font(inherit_font, lang);
1632 return previous_font;
1636 FontSpan Paragraph::fontSpan(pos_type pos) const
1638 LASSERT(pos <= size(), /**/);
1641 FontList::const_iterator cit = d->fontlist_.begin();
1642 FontList::const_iterator end = d->fontlist_.end();
1643 for (; cit != end; ++cit) {
1644 if (cit->pos() >= pos) {
1645 if (pos >= beginOfBody())
1646 return FontSpan(max(start, beginOfBody()),
1649 return FontSpan(start,
1650 min(beginOfBody() - 1,
1653 start = cit->pos() + 1;
1656 // This should not happen, but if so, we take no chances.
1657 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1658 return FontSpan(pos, pos);
1662 // Gets uninstantiated font setting at position 0
1663 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1665 if (!empty() && !d->fontlist_.empty())
1666 return d->fontlist_.begin()->font();
1668 // Optimisation: avoid a full font instantiation if there is no
1669 // language change from previous call.
1670 static Font previous_font;
1671 static Language const * previous_lang = 0;
1672 if (bparams.language != previous_lang) {
1673 previous_lang = bparams.language;
1674 previous_font = Font(inherit_font, bparams.language);
1677 return previous_font;
1681 // Gets the fully instantiated font at a given position in a paragraph
1682 // This is basically the same function as Text::GetFont() in text2.cpp.
1683 // The difference is that this one is used for generating the LaTeX file,
1684 // and thus cosmetic "improvements" are disallowed: This has to deliver
1685 // the true picture of the buffer. (Asger)
1686 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1687 Font const & outerfont) const
1689 LASSERT(pos >= 0, /**/);
1691 Font font = getFontSettings(bparams, pos);
1693 pos_type const body_pos = beginOfBody();
1694 FontInfo & fi = font.fontInfo();
1696 fi.realize(d->layout_->labelfont);
1698 fi.realize(d->layout_->font);
1700 fi.realize(outerfont.fontInfo());
1701 fi.realize(bparams.getFont().fontInfo());
1707 Font const Paragraph::getLabelFont
1708 (BufferParams const & bparams, Font const & outerfont) const
1710 FontInfo tmpfont = d->layout_->labelfont;
1711 tmpfont.realize(outerfont.fontInfo());
1712 tmpfont.realize(bparams.getFont().fontInfo());
1713 return Font(tmpfont, getParLanguage(bparams));
1717 Font const Paragraph::getLayoutFont
1718 (BufferParams const & bparams, Font const & outerfont) const
1720 FontInfo tmpfont = d->layout_->font;
1721 tmpfont.realize(outerfont.fontInfo());
1722 tmpfont.realize(bparams.getFont().fontInfo());
1723 return Font(tmpfont, getParLanguage(bparams));
1727 /// Returns the height of the highest font in range
1728 FontSize Paragraph::highestFontInRange
1729 (pos_type startpos, pos_type endpos, FontSize def_size) const
1731 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1735 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1737 char_type c = d->text_[pos];
1738 if (!lyxrc.rtl_support)
1768 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1774 void Paragraph::setFont(pos_type pos, Font const & font)
1776 LASSERT(pos <= size(), /**/);
1778 // First, reduce font against layout/label font
1779 // Update: The setCharFont() routine in text2.cpp already
1780 // reduces font, so we don't need to do that here. (Asger)
1782 d->fontlist_.set(pos, font);
1786 void Paragraph::makeSameLayout(Paragraph const & par)
1788 d->layout_ = par.d->layout_;
1789 d->params_ = par.d->params_;
1793 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1795 if (isFreeSpacing())
1801 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1802 if (eraseChar(pos, trackChanges))
1808 return count > 0 || pos > 0;
1812 bool Paragraph::hasSameLayout(Paragraph const & par) const
1814 return par.d->layout_ == d->layout_
1815 && d->params_.sameLayout(par.d->params_);
1819 depth_type Paragraph::getDepth() const
1821 return d->params_.depth();
1825 depth_type Paragraph::getMaxDepthAfter() const
1827 if (d->layout_->isEnvironment())
1828 return d->params_.depth() + 1;
1830 return d->params_.depth();
1834 char Paragraph::getAlign() const
1836 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1837 return d->layout_->align;
1839 return d->params_.align();
1843 docstring const & Paragraph::labelString() const
1845 return d->params_.labelString();
1849 // the next two functions are for the manual labels
1850 docstring const Paragraph::getLabelWidthString() const
1852 if (d->layout_->margintype == MARGIN_MANUAL
1853 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1854 return d->params_.labelWidthString();
1856 return _("Senseless with this layout!");
1860 void Paragraph::setLabelWidthString(docstring const & s)
1862 d->params_.labelWidthString(s);
1866 docstring Paragraph::expandLabel(Layout const & layout,
1867 BufferParams const & bparams) const
1869 return expandParagraphLabel(layout, bparams, true);
1873 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1874 BufferParams const & bparams) const
1876 return expandParagraphLabel(layout, bparams, false);
1880 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1881 BufferParams const & bparams, bool process_appendix) const
1883 DocumentClass const & tclass = bparams.documentClass();
1884 string const & lang = getParLanguage(bparams)->code();
1885 bool const in_appendix = process_appendix && d->params_.appendix();
1886 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1888 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1889 && !layout.counter.empty())
1890 return tclass.counters().theCounter(layout.counter, lang);
1892 // handle 'inherited level parts' in 'fmt',
1893 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1894 size_t const i = fmt.find('@', 0);
1895 if (i != docstring::npos) {
1896 size_t const j = fmt.find('@', i + 1);
1897 if (j != docstring::npos) {
1898 docstring parent(fmt, i + 1, j - i - 1);
1899 docstring label = from_ascii("??");
1900 if (tclass.hasLayout(parent))
1901 docstring label = expandParagraphLabel(tclass[parent], bparams,
1903 fmt = docstring(fmt, 0, i) + label
1904 + docstring(fmt, j + 1, docstring::npos);
1908 return tclass.counters().counterLabel(fmt, lang);
1912 void Paragraph::applyLayout(Layout const & new_layout)
1914 d->layout_ = &new_layout;
1915 LyXAlignment const oldAlign = d->params_.align();
1917 if (!(oldAlign & d->layout_->alignpossible)) {
1918 frontend::Alert::warning(_("Alignment not permitted"),
1919 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1920 d->params_.align(LYX_ALIGN_LAYOUT);
1925 pos_type Paragraph::beginOfBody() const
1927 return d->begin_of_body_;
1931 void Paragraph::setBeginOfBody()
1933 if (d->layout_->labeltype != LABEL_MANUAL) {
1934 d->begin_of_body_ = 0;
1938 // Unroll the first two cycles of the loop
1939 // and remember the previous character to
1940 // remove unnecessary getChar() calls
1942 pos_type end = size();
1943 if (i < end && !isNewline(i)) {
1945 char_type previous_char = 0;
1948 previous_char = d->text_[i];
1949 if (!isNewline(i)) {
1951 while (i < end && previous_char != ' ') {
1956 previous_char = temp;
1962 d->begin_of_body_ = i;
1966 bool Paragraph::allowParagraphCustomization() const
1968 return inInset().allowParagraphCustomization();
1972 bool Paragraph::usePlainLayout() const
1974 return inInset().usePlainLayout();
1980 // paragraphs inside floats need different alignment tags to avoid
1983 bool noTrivlistCentering(InsetCode code)
1985 return code == FLOAT_CODE
1986 || code == WRAP_CODE
1987 || code == CELL_CODE;
1991 string correction(string const & orig)
1993 if (orig == "flushleft")
1994 return "raggedright";
1995 if (orig == "flushright")
1996 return "raggedleft";
1997 if (orig == "center")
2003 string const corrected_env(string const & suffix, string const & env,
2004 InsetCode code, bool const lastpar)
2006 string output = suffix + "{";
2007 if (noTrivlistCentering(code)) {
2009 // the last paragraph in non-trivlist-aligned
2010 // context is special (to avoid unwanted whitespace)
2011 if (suffix == "\\begin")
2012 return "\\" + correction(env) + "{}";
2015 output += correction(env);
2019 if (suffix == "\\begin")
2025 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2027 if (!contains(str, "\n"))
2028 column += str.size();
2032 column = rsplit(str, tmp, '\n').size();
2039 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2040 odocstream & os, TexRow & texrow,
2041 OutputParams const & runparams) const
2045 if (params_.noindent()) {
2046 os << "\\noindent ";
2050 LyXAlignment const curAlign = params_.align();
2052 if (curAlign == layout_->align)
2056 case LYX_ALIGN_NONE:
2057 case LYX_ALIGN_BLOCK:
2058 case LYX_ALIGN_LAYOUT:
2059 case LYX_ALIGN_SPECIAL:
2060 case LYX_ALIGN_DECIMAL:
2062 case LYX_ALIGN_LEFT:
2063 case LYX_ALIGN_RIGHT:
2064 case LYX_ALIGN_CENTER:
2065 if (runparams.moving_arg) {
2072 string const begin_tag = "\\begin";
2073 InsetCode code = ownerCode();
2074 bool const lastpar = runparams.isLastPar;
2077 case LYX_ALIGN_NONE:
2078 case LYX_ALIGN_BLOCK:
2079 case LYX_ALIGN_LAYOUT:
2080 case LYX_ALIGN_SPECIAL:
2081 case LYX_ALIGN_DECIMAL:
2083 case LYX_ALIGN_LEFT: {
2085 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2086 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2088 output = corrected_env(begin_tag, "flushright", code, lastpar);
2089 os << from_ascii(output);
2090 adjust_row_column(output, texrow, column);
2092 } case LYX_ALIGN_RIGHT: {
2094 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2095 output = corrected_env(begin_tag, "flushright", code, lastpar);
2097 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2098 os << from_ascii(output);
2099 adjust_row_column(output, texrow, column);
2101 } case LYX_ALIGN_CENTER: {
2103 output = corrected_env(begin_tag, "center", code, lastpar);
2104 os << from_ascii(output);
2105 adjust_row_column(output, texrow, column);
2114 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2115 odocstream & os, TexRow & texrow,
2116 OutputParams const & runparams) const
2120 LyXAlignment const curAlign = params_.align();
2122 if (curAlign == layout_->align)
2126 case LYX_ALIGN_NONE:
2127 case LYX_ALIGN_BLOCK:
2128 case LYX_ALIGN_LAYOUT:
2129 case LYX_ALIGN_SPECIAL:
2130 case LYX_ALIGN_DECIMAL:
2132 case LYX_ALIGN_LEFT:
2133 case LYX_ALIGN_RIGHT:
2134 case LYX_ALIGN_CENTER:
2135 if (runparams.moving_arg) {
2142 string const end_tag = "\n\\par\\end";
2143 InsetCode code = ownerCode();
2144 bool const lastpar = runparams.isLastPar;
2147 case LYX_ALIGN_NONE:
2148 case LYX_ALIGN_BLOCK:
2149 case LYX_ALIGN_LAYOUT:
2150 case LYX_ALIGN_SPECIAL:
2151 case LYX_ALIGN_DECIMAL:
2153 case LYX_ALIGN_LEFT: {
2155 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2156 output = corrected_env(end_tag, "flushleft", code, lastpar);
2158 output = corrected_env(end_tag, "flushright", code, lastpar);
2159 os << from_ascii(output);
2160 adjust_row_column(output, texrow, column);
2162 } case LYX_ALIGN_RIGHT: {
2164 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2165 output = corrected_env(end_tag, "flushright", code, lastpar);
2167 output = corrected_env(end_tag, "flushleft", code, lastpar);
2168 os << from_ascii(output);
2169 adjust_row_column(output, texrow, column);
2171 } case LYX_ALIGN_CENTER: {
2173 output = corrected_env(end_tag, "center", code, lastpar);
2174 os << from_ascii(output);
2175 adjust_row_column(output, texrow, column);
2184 // This one spits out the text of the paragraph
2185 void Paragraph::latex(BufferParams const & bparams,
2186 Font const & outerfont,
2187 odocstream & os, TexRow & texrow,
2188 OutputParams const & runparams,
2189 int start_pos, int end_pos, bool force) const
2191 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2193 // FIXME This check should not be needed. Perhaps issue an
2194 // error if it triggers.
2195 Layout const & style = inInset().forcePlainLayout() ?
2196 bparams.documentClass().plainLayout() : *d->layout_;
2198 if (!force && style.inpreamble)
2201 bool const allowcust = allowParagraphCustomization();
2203 // Current base font for all inherited font changes, without any
2204 // change caused by an individual character, except for the language:
2205 // It is set to the language of the first character.
2206 // As long as we are in the label, this font is the base font of the
2207 // label. Before the first body character it is set to the base font
2211 // Maybe we have to create a optional argument.
2212 pos_type body_pos = beginOfBody();
2213 unsigned int column = 0;
2216 // the optional argument is kept in curly brackets in
2217 // case it contains a ']'
2220 basefont = getLabelFont(bparams, outerfont);
2222 basefont = getLayoutFont(bparams, outerfont);
2225 // Which font is currently active?
2226 Font running_font(basefont);
2227 // Do we have an open font change?
2228 bool open_font = false;
2230 Change runningChange = Change(Change::UNCHANGED);
2232 Encoding const * const prev_encoding = runparams.encoding;
2234 texrow.start(id(), 0);
2236 // if the paragraph is empty, the loop will not be entered at all
2238 if (style.isCommand()) {
2243 column += d->startTeXParParams(bparams, os, texrow,
2247 for (pos_type i = 0; i < size(); ++i) {
2248 // First char in paragraph or after label?
2249 if (i == body_pos) {
2252 column += running_font.latexWriteEndChanges(
2253 os, bparams, runparams,
2254 basefont, basefont);
2257 basefont = getLayoutFont(bparams, outerfont);
2258 running_font = basefont;
2260 column += Changes::latexMarkChange(os, bparams,
2261 runningChange, Change(Change::UNCHANGED),
2263 runningChange = Change(Change::UNCHANGED);
2268 if (style.isCommand()) {
2274 column += d->startTeXParParams(bparams, os,
2279 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2282 if (bparams.outputChanges && runningChange != change) {
2284 column += running_font.latexWriteEndChanges(
2285 os, bparams, runparams, basefont, basefont);
2288 basefont = getLayoutFont(bparams, outerfont);
2289 running_font = basefont;
2291 column += Changes::latexMarkChange(os, bparams, runningChange,
2293 runningChange = change;
2296 // do not output text which is marked deleted
2297 // if change tracking output is disabled
2298 if (!bparams.outputChanges && change.deleted()) {
2304 // Fully instantiated font
2305 Font const font = getFont(bparams, i, outerfont);
2307 Font const last_font = running_font;
2309 // Do we need to close the previous font?
2311 (font != running_font ||
2312 font.language() != running_font.language()))
2314 column += running_font.latexWriteEndChanges(
2315 os, bparams, runparams, basefont,
2316 (i == body_pos-1) ? basefont : font);
2317 running_font = basefont;
2321 // close babel's font environment before opening CJK.
2322 if (!running_font.language()->babel().empty() &&
2323 font.language()->encoding()->package() == Encoding::CJK) {
2324 string end_tag = subst(lyxrc.language_command_end,
2326 running_font.language()->babel());
2327 os << from_ascii(end_tag);
2328 column += end_tag.length();
2331 // Switch file encoding if necessary (and allowed)
2332 if (!runparams.pass_thru && !style.pass_thru &&
2333 runparams.encoding->package() != Encoding::none &&
2334 font.language()->encoding()->package() != Encoding::none) {
2335 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2336 runparams, *(font.language()->encoding()));
2337 if (enc_switch.first) {
2338 column += enc_switch.second;
2339 runparams.encoding = font.language()->encoding();
2343 char_type const c = d->text_[i];
2345 // Do we need to change font?
2346 if ((font != running_font ||
2347 font.language() != running_font.language()) &&
2350 odocstringstream ods;
2351 column += font.latexWriteStartChanges(ods, bparams,
2352 runparams, basefont,
2354 running_font = font;
2356 docstring fontchange = ods.str();
2357 // check whether the fontchange ends with a \\textcolor
2358 // modifier and the text starts with a space (bug 4473)
2359 docstring const last_modifier = rsplit(fontchange, '\\');
2360 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2361 os << fontchange << from_ascii("{}");
2362 // check if the fontchange ends with a trailing blank
2363 // (like "\small " (see bug 3382)
2364 else if (suffixIs(fontchange, ' ') && c == ' ')
2365 os << fontchange.substr(0, fontchange.size() - 1)
2366 << from_ascii("{}");
2371 // FIXME: think about end_pos implementation...
2372 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2373 // FIXME: integrate this case in latexSpecialChar
2374 // Do not print the separation of the optional argument
2375 // if style.pass_thru is false. This works because
2376 // latexSpecialChar ignores spaces if
2377 // style.pass_thru is false.
2378 if (i != body_pos - 1) {
2379 if (d->simpleTeXBlanks(
2380 runparams, os, texrow,
2381 i, column, font, style)) {
2382 // A surrogate pair was output. We
2383 // must not call latexSpecialChar
2384 // in this iteration, since it would output
2385 // the combining character again.
2392 OutputParams rp = runparams;
2393 rp.free_spacing = style.free_spacing;
2394 rp.local_font = &font;
2395 rp.intitle = style.intitle;
2397 // Two major modes: LaTeX or plain
2398 // Handle here those cases common to both modes
2399 // and then split to handle the two modes separately.
2400 if (c == META_INSET) {
2401 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2402 d->latexInset(bparams, os,
2403 texrow, rp, running_font,
2404 basefont, outerfont, open_font,
2405 runningChange, style, i, column);
2408 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2410 d->latexSpecialChar(os, rp, running_font, runningChange,
2412 } catch (EncodingException & e) {
2413 if (runparams.dryrun) {
2414 os << "<" << _("LyX Warning: ")
2415 << _("uncodable character") << " '";
2419 // add location information and throw again.
2428 // Set the encoding to that returned from latexSpecialChar (see
2429 // comment for encoding member in OutputParams.h)
2430 runparams.encoding = rp.encoding;
2433 // If we have an open font definition, we have to close it
2435 #ifdef FIXED_LANGUAGE_END_DETECTION
2437 running_font.latexWriteEndChanges(os, bparams,
2438 runparams, basefont,
2439 next_->getFont(bparams, 0, outerfont));
2441 running_font.latexWriteEndChanges(os, bparams,
2442 runparams, basefont, basefont);
2445 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2446 //FIXME: there as we start another \selectlanguage with the next paragraph if
2447 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2448 running_font.latexWriteEndChanges(os, bparams, runparams,
2449 basefont, basefont);
2453 column += Changes::latexMarkChange(os, bparams, runningChange,
2454 Change(Change::UNCHANGED), runparams);
2456 // Needed if there is an optional argument but no contents.
2457 if (body_pos > 0 && body_pos == size()) {
2461 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2462 && runparams.encoding != prev_encoding) {
2463 runparams.encoding = prev_encoding;
2464 if (!bparams.useXetex)
2465 os << setEncoding(prev_encoding->iconvName());
2468 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2472 bool Paragraph::emptyTag() const
2474 for (pos_type i = 0; i < size(); ++i) {
2475 if (Inset const * inset = getInset(i)) {
2476 InsetCode lyx_code = inset->lyxCode();
2477 // FIXME testing like that is wrong. What is
2479 if (lyx_code != TOC_CODE &&
2480 lyx_code != INCLUDE_CODE &&
2481 lyx_code != GRAPHICS_CODE &&
2482 lyx_code != ERT_CODE &&
2483 lyx_code != LISTINGS_CODE &&
2484 lyx_code != FLOAT_CODE &&
2485 lyx_code != TABULAR_CODE) {
2489 char_type c = d->text_[i];
2490 if (c != ' ' && c != '\t')
2498 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2501 for (pos_type i = 0; i < size(); ++i) {
2502 if (Inset const * inset = getInset(i)) {
2503 InsetCode lyx_code = inset->lyxCode();
2504 if (lyx_code == LABEL_CODE) {
2505 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2506 docstring const & id = il->getParam("name");
2507 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2515 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2519 for (i = 0; i < size(); ++i) {
2520 if (Inset const * inset = getInset(i)) {
2521 inset->docbook(os, runparams);
2523 char_type c = d->text_[i];
2526 os << sgml::escapeChar(c);
2533 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2537 for (i = 0; i < size(); ++i) {
2538 if (Inset const * inset = getInset(i)) {
2539 inset->xhtml(xs, runparams);
2541 char_type c = d->text_[i];
2551 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2554 pos_type size = text_.size();
2555 for (pos_type i = initial; i < size; ++i) {
2556 Font font = owner_->getFont(buf.params(), i, outerfont);
2557 if (text_[i] == META_INSET)
2559 if (i != initial && font != font_old)
2568 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2570 OutputParams const & runparams,
2571 Font const & outerfont,
2572 pos_type initial) const
2574 bool emph_flag = false;
2576 Layout const & style = *d->layout_;
2578 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2580 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2583 // parsing main loop
2584 for (pos_type i = initial; i < size(); ++i) {
2585 Font font = getFont(buf.params(), i, outerfont);
2587 // handle <emphasis> tag
2588 if (font_old.emph() != font.fontInfo().emph()) {
2589 if (font.fontInfo().emph() == FONT_ON) {
2592 } else if (i != initial) {
2593 os << "</emphasis>";
2598 if (Inset const * inset = getInset(i)) {
2599 inset->docbook(os, runparams);
2601 char_type c = d->text_[i];
2603 if (style.pass_thru)
2606 os << sgml::escapeChar(c);
2608 font_old = font.fontInfo();
2612 os << "</emphasis>";
2615 if (style.free_spacing)
2617 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2622 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2624 OutputParams const & runparams,
2625 Font const & outerfont,
2626 pos_type initial) const
2630 bool emph_flag = false;
2631 bool bold_flag = false;
2634 Layout const & style = *d->layout_;
2636 if (!runparams.for_toc && runparams.html_make_pars) {
2637 // generate a magic label for this paragraph
2638 string const attr = "id='" + magicLabel() + "'";
2639 xs << html::CompTag("a", attr);
2643 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2645 // parsing main loop
2646 for (pos_type i = initial; i < size(); ++i) {
2647 // let's not show deleted material in the output
2651 Font font = getFont(buf.params(), i, outerfont);
2654 if (font_old.emph() != font.fontInfo().emph()) {
2655 if (font.fontInfo().emph() == FONT_ON) {
2656 xs << html::StartTag("em");
2658 } else if (emph_flag && i != initial) {
2659 xs << html::EndTag("em");
2664 if (font_old.series() != font.fontInfo().series()) {
2665 if (font.fontInfo().series() == BOLD_SERIES) {
2666 xs << html::StartTag("strong");
2668 } else if (bold_flag && i != initial) {
2669 xs << html::EndTag("strong");
2674 // Other such tags? What about the other text ranges?
2676 Inset const * inset = getInset(i);
2678 InsetCommand const * ic = inset->asInsetCommand();
2679 InsetLayout const & il = inset->getLayout();
2680 InsetMath const * im = inset->asInsetMath();
2681 if (!runparams.for_toc
2682 || im || il.isInToc() || (ic && ic->isInToc())) {
2683 OutputParams np = runparams;
2684 if (!il.htmlisblock())
2685 np.html_in_par = true;
2686 retval += inset->xhtml(xs, np);
2689 char_type c = d->text_[i];
2691 if (style.pass_thru)
2693 else if (c == '-') {
2696 if (j < size() && d->text_[j] == '-') {
2698 if (j < size() && d->text_[j] == '-') {
2699 str += from_ascii("—");
2702 str += from_ascii("–");
2708 // We don't want to escape the entities. Note that
2709 // it is safe to do this, since str can otherwise
2710 // only be "-". E.g., it can't be "<".
2711 xs << XHTMLStream::NextRaw() << str;
2715 font_old = font.fontInfo();
2723 bool Paragraph::isHfill(pos_type pos) const
2725 Inset const * inset = getInset(pos);
2726 return inset && (inset->lyxCode() == SPACE_CODE &&
2727 inset->isStretchableSpace());
2731 bool Paragraph::isNewline(pos_type pos) const
2733 Inset const * inset = getInset(pos);
2734 return inset && inset->lyxCode() == NEWLINE_CODE;
2738 bool Paragraph::isLineSeparator(pos_type pos) const
2740 char_type const c = d->text_[pos];
2741 if (isLineSeparatorChar(c))
2743 Inset const * inset = getInset(pos);
2744 return inset && inset->isLineSeparator();
2748 bool Paragraph::isWordSeparator(pos_type pos) const
2750 if (Inset const * inset = getInset(pos))
2751 return !inset->isLetter();
2752 char_type const c = d->text_[pos];
2753 // We want to pass the ' and escape chars to the spellchecker
2754 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2755 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2760 bool Paragraph::isChar(pos_type pos) const
2762 if (Inset const * inset = getInset(pos))
2763 return inset->isChar();
2764 char_type const c = d->text_[pos];
2765 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2769 bool Paragraph::isSpace(pos_type pos) const
2771 if (Inset const * inset = getInset(pos))
2772 return inset->isSpace();
2773 char_type const c = d->text_[pos];
2774 return lyx::isSpace(c);
2779 Paragraph::getParLanguage(BufferParams const & bparams) const
2782 return getFirstFontSettings(bparams).language();
2783 // FIXME: we should check the prev par as well (Lgb)
2784 return bparams.language;
2788 bool Paragraph::isRTL(BufferParams const & bparams) const
2790 return lyxrc.rtl_support
2791 && getParLanguage(bparams)->rightToLeft()
2792 && !inInset().getLayout().forceLTR();
2796 void Paragraph::changeLanguage(BufferParams const & bparams,
2797 Language const * from, Language const * to)
2799 // change language including dummy font change at the end
2800 for (pos_type i = 0; i <= size(); ++i) {
2801 Font font = getFontSettings(bparams, i);
2802 if (font.language() == from) {
2803 font.setLanguage(to);
2807 d->requestSpellCheck(size());
2811 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2813 Language const * doc_language = bparams.language;
2814 FontList::const_iterator cit = d->fontlist_.begin();
2815 FontList::const_iterator end = d->fontlist_.end();
2817 for (; cit != end; ++cit)
2818 if (cit->font().language() != ignore_language &&
2819 cit->font().language() != latex_language &&
2820 cit->font().language() != doc_language)
2826 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2828 FontList::const_iterator cit = d->fontlist_.begin();
2829 FontList::const_iterator end = d->fontlist_.end();
2831 for (; cit != end; ++cit) {
2832 Language const * lang = cit->font().language();
2833 if (lang != ignore_language &&
2834 lang != latex_language)
2835 languages.insert(lang);
2840 docstring Paragraph::asString(int options) const
2842 return asString(0, size(), options);
2846 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2848 odocstringstream os;
2851 && options & AS_STR_LABEL
2852 && !d->params_.labelString().empty())
2853 os << d->params_.labelString() << ' ';
2855 for (pos_type i = beg; i < end; ++i) {
2856 char_type const c = d->text_[i];
2857 if (isPrintable(c) || c == '\t'
2858 || (c == '\n' && (options & AS_STR_NEWLINES)))
2860 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2861 getInset(i)->tocString(os);
2862 if (getInset(i)->asInsetMath())
2871 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2873 odocstringstream os;
2876 && options & AS_STR_LABEL
2877 && !d->params_.labelString().empty())
2878 os << d->params_.labelString() << ' ';
2880 for (pos_type i = beg; i < end; ++i) {
2881 char_type const c = d->text_[i];
2882 if (isPrintable(c) || c == '\t'
2883 || (c == '\n' && (options & AS_STR_NEWLINES)))
2885 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2886 getInset(i)->plaintext(os, runparams);
2894 void Paragraph::setInsetOwner(Inset const * inset)
2896 d->inset_owner_ = inset;
2900 int Paragraph::id() const
2906 void Paragraph::setId(int id)
2912 Layout const & Paragraph::layout() const
2918 void Paragraph::setLayout(Layout const & layout)
2920 d->layout_ = &layout;
2924 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2926 setLayout(tc.defaultLayout());
2930 void Paragraph::setPlainLayout(DocumentClass const & tc)
2932 setLayout(tc.plainLayout());
2936 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2938 if (usePlainLayout())
2939 setPlainLayout(tclass);
2941 setDefaultLayout(tclass);
2945 Inset const & Paragraph::inInset() const
2947 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2948 _("Memory problem"), _("Paragraph not properly initialized")));
2949 return *d->inset_owner_;
2953 ParagraphParameters & Paragraph::params()
2959 ParagraphParameters const & Paragraph::params() const
2965 bool Paragraph::isFreeSpacing() const
2967 if (d->layout_->free_spacing)
2969 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2973 bool Paragraph::allowEmpty() const
2975 if (d->layout_->keepempty)
2977 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2981 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2983 if (!Encodings::isArabicChar(c))
2986 char_type prev_char = ' ';
2987 char_type next_char = ' ';
2989 for (pos_type i = pos - 1; i >= 0; --i) {
2990 char_type const par_char = d->text_[i];
2991 if (!Encodings::isArabicComposeChar(par_char)) {
2992 prev_char = par_char;
2997 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
2998 char_type const par_char = d->text_[i];
2999 if (!Encodings::isArabicComposeChar(par_char)) {
3000 next_char = par_char;
3005 if (Encodings::isArabicChar(next_char)) {
3006 if (Encodings::isArabicChar(prev_char) &&
3007 !Encodings::isArabicSpecialChar(prev_char))
3008 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3010 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3012 if (Encodings::isArabicChar(prev_char) &&
3013 !Encodings::isArabicSpecialChar(prev_char))
3014 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3016 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3021 int Paragraph::checkBiblio(Buffer const & buffer)
3024 // This is getting more and more a mess. ...We really should clean
3025 // up this bibitem issue for 1.6. See also bug 2743.
3027 // Add bibitem insets if necessary
3028 if (d->layout_->labeltype != LABEL_BIBLIO)
3031 bool hasbibitem = !d->insetlist_.empty()
3032 // Insist on it being in pos 0
3033 && d->text_[0] == META_INSET
3034 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3036 bool track_changes = buffer.params().trackChanges;
3041 // remove a bibitem in pos != 0
3042 // restore it later in pos 0 if necessary
3043 // (e.g. if a user inserts contents _before_ the item)
3044 // we're assuming there's only one of these, which there
3046 int erasedInsetPosition = -1;
3047 InsetList::iterator it = d->insetlist_.begin();
3048 InsetList::iterator end = d->insetlist_.end();
3049 for (; it != end; ++it)
3050 if (it->inset->lyxCode() == BIBITEM_CODE
3052 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3053 oldkey = olditem->getParam("key");
3054 oldlabel = olditem->getParam("label");
3055 erasedInsetPosition = it->pos;
3056 eraseChar(erasedInsetPosition, track_changes);
3060 // There was an InsetBibitem at the beginning, and we didn't
3061 // have to erase one.
3062 if (hasbibitem && erasedInsetPosition < 0)
3065 // There was an InsetBibitem at the beginning and we did have to
3066 // erase one. So we give its properties to the beginning inset.
3068 InsetBibitem * inset =
3069 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3070 if (!oldkey.empty())
3071 inset->setParam("key", oldkey);
3072 inset->setParam("label", oldlabel);
3073 return -erasedInsetPosition;
3076 // There was no inset at the beginning, so we need to create one with
3077 // the key and label of the one we erased.
3078 InsetBibitem * inset =
3079 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3080 // restore values of previously deleted item in this par.
3081 if (!oldkey.empty())
3082 inset->setParam("key", oldkey);
3083 inset->setParam("label", oldlabel);
3084 insertInset(0, static_cast<Inset *>(inset),
3085 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3091 void Paragraph::checkAuthors(AuthorList const & authorList)
3093 d->changes_.checkAuthors(authorList);
3097 bool Paragraph::isChanged(pos_type pos) const
3099 return lookupChange(pos).changed();
3103 bool Paragraph::isInserted(pos_type pos) const
3105 return lookupChange(pos).inserted();
3109 bool Paragraph::isDeleted(pos_type pos) const
3111 return lookupChange(pos).deleted();
3115 InsetList const & Paragraph::insetList() const
3117 return d->insetlist_;
3121 void Paragraph::setBuffer(Buffer & b)
3123 d->insetlist_.setBuffer(b);
3127 Inset * Paragraph::releaseInset(pos_type pos)
3129 Inset * inset = d->insetlist_.release(pos);
3130 /// does not honour change tracking!
3131 eraseChar(pos, false);
3136 Inset * Paragraph::getInset(pos_type pos)
3138 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3139 ? d->insetlist_.get(pos) : 0;
3143 Inset const * Paragraph::getInset(pos_type pos) const
3145 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3146 ? d->insetlist_.get(pos) : 0;
3150 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3151 pos_type & right, TextCase action)
3153 // process sequences of modified characters; in change
3154 // tracking mode, this approach results in much better
3155 // usability than changing case on a char-by-char basis
3158 bool const trackChanges = bparams.trackChanges;
3160 bool capitalize = true;
3162 for (; pos < right; ++pos) {
3163 char_type oldChar = d->text_[pos];
3164 char_type newChar = oldChar;
3166 // ignore insets and don't play with deleted text!
3167 if (oldChar != META_INSET && !isDeleted(pos)) {
3169 case text_lowercase:
3170 newChar = lowercase(oldChar);
3172 case text_capitalization:
3174 newChar = uppercase(oldChar);
3178 case text_uppercase:
3179 newChar = uppercase(oldChar);
3184 if (isWordSeparator(pos) || isDeleted(pos)) {
3185 // permit capitalization again
3189 if (oldChar != newChar) {
3191 if (pos != right - 1)
3193 // step behind the changing area
3197 int erasePos = pos - changes.size();
3198 for (size_t i = 0; i < changes.size(); i++) {
3199 insertChar(pos, changes[i],
3200 getFontSettings(bparams,
3203 if (!eraseChar(erasePos, trackChanges)) {
3206 ++right; // expand selection
3214 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3215 pos_type pos, bool del) const
3217 int const strsize = str.length();
3219 pos_type const parsize = d->text_.size();
3220 for (i = 0; pos + i < parsize; ++i) {
3223 if (cs && str[i] != d->text_[pos + i])
3225 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3227 if (!del && isDeleted(pos + i))
3234 // if necessary, check whether string matches word
3236 if (pos > 0 && !isWordSeparator(pos - 1))
3238 if (pos + strsize < parsize
3239 && !isWordSeparator(pos + strsize))
3247 char_type Paragraph::getChar(pos_type pos) const
3249 return d->text_[pos];
3253 pos_type Paragraph::size() const
3255 return d->text_.size();
3259 bool Paragraph::empty() const
3261 return d->text_.empty();
3265 bool Paragraph::isInset(pos_type pos) const
3267 return d->text_[pos] == META_INSET;
3271 bool Paragraph::isSeparator(pos_type pos) const
3273 //FIXME: Are we sure this can be the only separator?
3274 return d->text_[pos] == ' ';
3278 void Paragraph::deregisterWords()
3280 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3281 Private::LangWordsMap::const_iterator ite = d->words_.end();
3282 for (; itl != ite; ++itl) {
3283 WordList * wl = theWordList(itl->first);
3284 Private::Words::const_iterator it = (itl->second).begin();
3285 Private::Words::const_iterator et = (itl->second).end();
3286 for (; it != et; ++it)
3293 void Paragraph::locateWord(pos_type & from, pos_type & to,
3294 word_location const loc) const
3297 case WHOLE_WORD_STRICT:
3298 if (from == 0 || from == size()
3299 || isWordSeparator(from)
3300 || isWordSeparator(from - 1)) {
3304 // no break here, we go to the next
3307 // If we are already at the beginning of a word, do nothing
3308 if (!from || isWordSeparator(from - 1))
3310 // no break here, we go to the next
3313 // always move the cursor to the beginning of previous word
3314 while (from && !isWordSeparator(from - 1))
3318 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3321 // no need to move the 'from' cursor
3325 while (to < size() && !isWordSeparator(to))
3330 void Paragraph::collectWords()
3332 // This is the value that needs to be exposed in the preferences
3333 // to resolve bug #6760.
3334 static int minlength = 6;
3335 pos_type n = size();
3336 for (pos_type pos = 0; pos < n; ++pos) {
3337 if (isWordSeparator(pos))
3339 pos_type from = pos;
3340 locateWord(from, pos, WHOLE_WORD);
3341 if (pos - from >= minlength) {
3342 docstring word = asString(from, pos, AS_STR_NONE);
3343 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3344 if (cit == d->fontlist_.end())
3346 Language const * lang = cit->font().language();
3347 d->words_[*lang].insert(word);
3353 void Paragraph::registerWords()
3355 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3356 Private::LangWordsMap::const_iterator ite = d->words_.end();
3357 for (; itl != ite; ++itl) {
3358 WordList * wl = theWordList(itl->first);
3359 Private::Words::const_iterator it = (itl->second).begin();
3360 Private::Words::const_iterator et = (itl->second).end();
3361 for (; it != et; ++it)
3367 void Paragraph::updateWords()
3375 Language * Paragraph::Private::locateSpellRange(
3376 pos_type & from, pos_type & to,
3377 Positions & softbreaks) const
3379 // skip leading white space
3380 while (from < to && owner_->isWordSeparator(from))
3382 // don't check empty range
3385 // get current language
3386 Language * lang = getSpellLanguage(from);
3387 pos_type last = from;
3388 bool samelang = true;
3389 bool sameinset = true;
3390 while (last < to && samelang && sameinset) {
3391 // hop to end of word
3392 while (last < to && !owner_->isWordSeparator(last)) {
3393 if (owner_->getInset(last)) {
3394 softbreaks.insert(softbreaks.end(), last);
3398 // hop to next word while checking for insets
3399 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3400 if (Inset const * inset = owner_->getInset(last))
3401 sameinset = inset->isChar() && inset->isLetter();
3405 if (sameinset && last < to) {
3406 // now check for language change
3407 samelang = lang == getSpellLanguage(last);
3410 // if language change detected backstep is needed
3418 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3421 const_cast<Language *>(owner_->getFontSettings(
3422 inset_owner_->buffer().params(), from).language());
3423 if (lang == inset_owner_->buffer().params().language
3424 && !lyxrc.spellchecker_alt_lang.empty()) {
3426 string const lang_variety =
3427 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3428 lang->setCode(lang_code);
3429 lang->setVariety(lang_variety);
3435 void Paragraph::requestSpellCheck(pos_type pos)
3437 d->requestSpellCheck(pos == -1 ? size() : pos);
3441 bool Paragraph::needsSpellCheck() const
3443 SpellChecker::ChangeNumber speller_change_number = 0;
3444 if (theSpellChecker())
3445 speller_change_number = theSpellChecker()->changeNumber();
3446 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3447 d->speller_state_.needsCompleteRefresh(speller_change_number);
3449 return d->needsSpellCheck();
3453 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3454 WordLangTuple & wl, docstring_list & suggestions,
3455 bool do_suggestion, bool check_learned) const
3457 SpellChecker::Result result = SpellChecker::WORD_OK;
3458 SpellChecker * speller = theSpellChecker();
3462 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3465 locateWord(from, to, WHOLE_WORD);
3466 if (from == to || from >= pos_type(d->text_.size()))
3469 docstring word = asString(from, to, AS_STR_INSETS);
3470 Language * lang = d->getSpellLanguage(from);
3472 wl = WordLangTuple(word, lang);
3477 if (needsSpellCheck() || check_learned) {
3478 // Ignore words with digits
3479 // FIXME: make this customizable
3480 // (note that some checkers ignore words with digits by default)
3481 if (!hasDigit(word))
3482 result = speller->check(wl);
3483 d->setMisspelled(from, to, result);
3485 result = d->speller_state_.getState(from);
3488 bool const misspelled_ = SpellChecker::misspelled(result) ;
3489 if (misspelled_ && do_suggestion)
3490 speller->suggest(wl, suggestions);
3491 else if (misspelled_)
3492 LYXERR(Debug::GUI, "misspelled word: \"" <<
3494 from << ".." << to << "]");
3496 suggestions.clear();
3502 void Paragraph::Private::markMisspelledWords(
3503 pos_type const & first, pos_type const & last,
3504 SpellChecker::Result result,
3505 docstring const & word,
3506 Positions const & softbreaks)
3508 pos_type snext = first;
3509 if (SpellChecker::misspelled(result)) {
3510 SpellChecker * speller = theSpellChecker();
3511 // locate and enumerate the error positions
3512 int nerrors = speller->numMisspelledWords();
3514 PositionsIterator it = softbreaks.begin();
3515 PositionsIterator et = softbreaks.end();
3516 for (int index = 0; index < nerrors; ++index) {
3519 speller->misspelledWord(index, wstart, wlen);
3521 docstring const misspelled = word.substr(wstart, wlen);
3522 wstart += first + numbreaks;
3523 if (snext < wstart) {
3524 while (it != et && *it < wstart) {
3529 setMisspelled(snext,
3530 wstart - 1, SpellChecker::WORD_OK);
3532 snext = wstart + wlen;
3533 while (it != et && *it < snext) {
3538 setMisspelled(wstart, snext, result);
3539 LYXERR(Debug::GUI, "misspelled word: \"" <<
3540 misspelled << "\" [" <<
3541 wstart << ".." << (snext-1) << "]");
3546 if (snext <= last) {
3547 setMisspelled(snext, last, SpellChecker::WORD_OK);
3552 void Paragraph::spellCheck() const
3554 SpellChecker * speller = theSpellChecker();
3555 if (!speller || !size() ||!needsSpellCheck())
3559 d->rangeOfSpellCheck(start, endpos);
3560 if (speller->canCheckParagraph()) {
3561 // loop until we leave the range argument
3562 for (pos_type first = start; first < endpos; ) {
3563 pos_type last = endpos;
3564 Private::Positions softbreaks;
3565 Language * lang = d->locateSpellRange(first, last, softbreaks);
3566 if (first >= endpos)
3568 // start the spell checker on the unit of meaning
3569 docstring word = asString(first, last, AS_STR_INSETS);
3570 WordLangTuple wl = WordLangTuple(word, lang);
3571 SpellChecker::Result result = word.size() ?
3572 speller->check(wl) : SpellChecker::WORD_OK;
3573 d->markMisspelledWords(first, last, result, word, softbreaks);
3577 static docstring_list suggestions;
3578 pos_type to = endpos;
3579 while (start < endpos) {
3581 spellCheck(start, to, wl, suggestions, false);
3585 d->readySpellCheck();
3589 bool Paragraph::isMisspelled(pos_type pos) const
3591 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3595 string Paragraph::magicLabel() const
3598 ss << "magicparlabel-" << id();