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 SpellResultRange {
85 SpellResultRange(FontSpan range, SpellChecker::Result result)
86 : range_(range), result_(result)
89 FontSpan const & range() const { return range_; }
91 void range(FontSpan const & r) { range_ = r; }
93 SpellChecker::Result result() const { return result_; }
95 void result(SpellChecker::Result r) { result_ = r; }
97 bool inside(pos_type pos) const { return range_.inside(pos); }
99 bool covered(FontSpan const & r) const
101 // 1. first of new range inside current range or
102 // 2. last of new range inside current range or
103 // 3. first of current range inside new range or
104 // 4. last of current range inside new range
105 return range_.inside(r.first) || range_.inside(r.last) ||
106 r.inside(range_.first) || r.inside(range_.last);
109 void shift(pos_type pos, int offset)
111 if (range_.first > pos) {
112 range_.first += offset;
113 range_.last += offset;
114 } else if (range_.last > pos) {
115 range_.last += offset;
120 SpellChecker::Result result_ ;
124 /////////////////////////////////////////////////////////////////////
128 /////////////////////////////////////////////////////////////////////
130 class SpellCheckerState {
132 SpellCheckerState() {
133 needs_refresh_ = true;
134 current_change_number_ = 0;
137 void setRange(FontSpan const fp, SpellChecker::Result state)
139 eraseCoveredRanges(fp);
140 if (state != SpellChecker::WORD_OK)
141 ranges_.push_back(SpellResultRange(fp, state));
144 void increasePosAfterPos(pos_type pos)
146 correctRangesAfterPos(pos, 1);
150 void decreasePosAfterPos(pos_type pos)
152 correctRangesAfterPos(pos, -1);
156 void refreshLast(pos_type pos)
158 if (pos < refresh_.last)
162 SpellChecker::Result getState(pos_type pos) const
164 SpellChecker::Result result = SpellChecker::WORD_OK;
165 RangesIterator et = ranges_.end();
166 RangesIterator it = ranges_.begin();
167 for (; it != et; ++it) {
168 if(it->inside(pos)) {
175 bool needsRefresh() const {
176 return needs_refresh_;
179 SpellChecker::ChangeNumber currentChangeNumber() const {
180 return current_change_number_;
183 void refreshRange(pos_type & first, pos_type & last) const {
184 first = refresh_.first;
185 last = refresh_.last;
188 void needsRefresh(pos_type pos) {
189 if (needs_refresh_ && pos != -1) {
190 if (pos < refresh_.first)
191 refresh_.first = pos;
192 if (pos > refresh_.last)
194 } else if (pos != -1) {
195 refresh_.first = pos;
198 needs_refresh_ = pos != -1;
201 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
202 needs_refresh_ = true;
205 current_change_number_ = change_number;
209 typedef vector<SpellResultRange> Ranges;
210 typedef Ranges::const_iterator RangesIterator;
212 /// the area of the paragraph with pending spell check
215 /// spell state cache version number
216 SpellChecker::ChangeNumber current_change_number_;
219 void eraseCoveredRanges(FontSpan const fp)
222 RangesIterator et = ranges_.end();
223 RangesIterator it = ranges_.begin();
224 for (; it != et; ++it) {
225 if (!it->covered(fp))
226 result.push_back(SpellResultRange(it->range(), it->result()));
231 void correctRangesAfterPos(pos_type pos, int offset)
233 RangesIterator et = ranges_.end();
234 Ranges::iterator it = ranges_.begin();
235 for (; it != et; ++it) {
236 it->shift(pos, offset);
242 /////////////////////////////////////////////////////////////////////
244 // Paragraph::Private
246 /////////////////////////////////////////////////////////////////////
248 class Paragraph::Private
252 Private(Paragraph * owner, Layout const & layout);
253 /// "Copy constructor"
254 Private(Private const &, Paragraph * owner);
255 /// Copy constructor from \p beg to \p end
256 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
259 void insertChar(pos_type pos, char_type c, Change const & change);
261 /// Output the surrogate pair formed by \p c and \p next to \p os.
262 /// \return the number of characters written.
263 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
264 OutputParams const &);
266 /// Output a space in appropriate formatting (or a surrogate pair
267 /// if the next character is a combining character).
268 /// \return whether a surrogate pair was output.
269 bool simpleTeXBlanks(OutputParams const &,
270 odocstream &, TexRow & texrow,
272 unsigned int & column,
274 Layout const & style);
276 /// Output consecutive unicode chars, belonging to the same script as
277 /// specified by the latex macro \p ltx, to \p os starting from \p i.
278 /// \return the number of characters written.
279 int writeScriptChars(odocstream & os, docstring const & ltx,
280 Change const &, Encoding const &, pos_type & i);
282 /// This could go to ParagraphParameters if we want to.
283 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
284 OutputParams const &) const;
286 /// This could go to ParagraphParameters if we want to.
287 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
288 OutputParams const &) const;
291 void latexInset(BufferParams const &,
293 TexRow & texrow, OutputParams &,
296 Font const & outerfont,
298 Change & running_change,
299 Layout const & style,
301 unsigned int & column);
304 void latexSpecialChar(
306 OutputParams const & runparams,
307 Font const & running_font,
308 Change const & running_change,
309 Layout const & style,
311 unsigned int & column);
318 unsigned int & column);
320 bool latexSpecialTypewriter(
324 unsigned int & column);
326 bool latexSpecialPhrase(
329 unsigned int & column,
330 OutputParams const & runparams);
333 void validate(LaTeXFeatures & features) const;
335 /// Checks if the paragraph contains only text and no inset or font change.
336 bool onlyText(Buffer const & buf, Font const & outerfont,
337 pos_type initial) const;
339 /// match a string against a particular point in the paragraph
340 bool isTextAt(string const & str, pos_type pos) const;
342 /// a vector of speller skip positions
343 typedef vector<FontSpan> SkipPositions;
344 typedef SkipPositions::const_iterator SkipPositionsIterator;
346 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
348 Language * getSpellLanguage(pos_type const from) const;
350 Language * locateSpellRange(pos_type & from, pos_type & to,
351 SkipPositions & skips) const;
353 bool hasSpellerChange() const {
354 SpellChecker::ChangeNumber speller_change_number = 0;
355 if (theSpellChecker())
356 speller_change_number = theSpellChecker()->changeNumber();
357 return speller_change_number > speller_state_.currentChangeNumber();
360 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
362 pos_type textsize = owner_->size();
363 // check for sane arguments
364 if (to < from || from >= textsize)
366 FontSpan fp = FontSpan(from, to);
367 // don't mark end of paragraph
368 if (fp.last >= textsize)
369 fp.last = textsize - 1;
370 speller_state_.setRange(fp, state);
373 void requestSpellCheck(pos_type pos) {
374 speller_state_.needsRefresh(pos);
377 void readySpellCheck() {
378 speller_state_.needsRefresh(-1);
381 bool needsSpellCheck() const
383 return speller_state_.needsRefresh();
386 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
388 speller_state_.refreshRange(first, last);
390 last = owner_->size();
393 pos_type endpos = last;
394 owner_->locateWord(first, endpos, WHOLE_WORD);
397 owner_->locateWord(last, endpos, WHOLE_WORD);
402 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
406 while (it != et && it->first < start) {
407 int skip = it->last - it->first + 1;
415 void markMisspelledWords(pos_type const & first, pos_type const & last,
416 SpellChecker::Result result,
417 docstring const & word,
418 SkipPositions const & skips);
420 InsetCode ownerCode() const
422 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
425 /// Which Paragraph owns us?
429 Inset const * inset_owner_;
438 ParagraphParameters params_;
440 /// for recording and looking up changes
444 InsetList insetlist_;
447 pos_type begin_of_body_;
449 typedef docstring TextContainer;
453 typedef set<docstring> Words;
454 typedef map<Language, Words> LangWordsMap;
458 Layout const * layout_;
460 SpellCheckerState speller_state_;
466 struct special_phrase {
472 special_phrase const special_phrases[] = {
473 { "LyX", from_ascii("\\LyX{}"), false },
474 { "TeX", from_ascii("\\TeX{}"), true },
475 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
476 { "LaTeX", from_ascii("\\LaTeX{}"), true },
479 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
484 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
485 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
491 // Initialization of the counter for the paragraph id's,
493 // FIXME: There should be a more intelligent way to generate and use the
494 // paragraph ids per buffer instead a global static counter for all InsetText
495 // in the running program.
496 static int paragraph_id = -1;
498 Paragraph::Private::Private(Private const & p, Paragraph * owner)
499 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
500 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
501 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
504 id_ = ++paragraph_id;
505 requestSpellCheck(p.text_.size());
509 Paragraph::Private::Private(Private const & p, Paragraph * owner,
510 pos_type beg, pos_type end)
511 : owner_(owner), inset_owner_(p.inset_owner_),
512 params_(p.params_), changes_(p.changes_),
513 insetlist_(p.insetlist_, beg, end),
514 begin_of_body_(p.begin_of_body_), words_(p.words_),
517 id_ = ++paragraph_id;
518 if (beg >= pos_type(p.text_.size()))
520 text_ = p.text_.substr(beg, end - beg);
522 FontList::const_iterator fcit = fontlist_.begin();
523 FontList::const_iterator fend = fontlist_.end();
524 for (; fcit != fend; ++fcit) {
525 if (fcit->pos() < beg)
527 if (fcit->pos() >= end) {
528 // Add last entry in the fontlist_.
529 fontlist_.set(text_.size() - 1, fcit->font());
532 // Add a new entry in the fontlist_.
533 fontlist_.set(fcit->pos() - beg, fcit->font());
535 requestSpellCheck(p.text_.size());
539 void Paragraph::addChangesToToc(DocIterator const & cdit,
540 Buffer const & buf) const
542 d->changes_.addToToc(cdit, buf);
546 bool Paragraph::isDeleted(pos_type start, pos_type end) const
548 LASSERT(start >= 0 && start <= size(), /**/);
549 LASSERT(end > start && end <= size() + 1, /**/);
551 return d->changes_.isDeleted(start, end);
555 bool Paragraph::isChanged(pos_type start, pos_type end) const
557 LASSERT(start >= 0 && start <= size(), /**/);
558 LASSERT(end > start && end <= size() + 1, /**/);
560 return d->changes_.isChanged(start, end);
564 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
566 // keep the logic here in sync with the logic of eraseChars()
570 Change const change = d->changes_.lookup(size());
571 return change.inserted() && change.currentAuthor();
575 void Paragraph::setChange(Change const & change)
577 // beware of the imaginary end-of-par character!
578 d->changes_.set(change, 0, size() + 1);
581 * Propagate the change recursively - but not in case of DELETED!
583 * Imagine that your co-author makes changes in an existing inset. He
584 * sends your document to you and you come to the conclusion that the
585 * inset should go completely. If you erase it, LyX must not delete all
586 * text within the inset. Otherwise, the change tracked insertions of
587 * your co-author get lost and there is no way to restore them later.
589 * Conclusion: An inset's content should remain untouched if you delete it
592 if (!change.deleted()) {
593 for (pos_type pos = 0; pos < size(); ++pos) {
594 if (Inset * inset = getInset(pos))
595 inset->setChange(change);
601 void Paragraph::setChange(pos_type pos, Change const & change)
603 LASSERT(pos >= 0 && pos <= size(), /**/);
604 d->changes_.set(change, pos);
606 // see comment in setChange(Change const &) above
607 if (!change.deleted() && pos < size())
608 if (Inset * inset = getInset(pos))
609 inset->setChange(change);
613 Change const & Paragraph::lookupChange(pos_type pos) const
615 LASSERT(pos >= 0 && pos <= size(), /**/);
616 return d->changes_.lookup(pos);
620 void Paragraph::acceptChanges(pos_type start, pos_type end)
622 LASSERT(start >= 0 && start <= size(), /**/);
623 LASSERT(end > start && end <= size() + 1, /**/);
625 for (pos_type pos = start; pos < end; ++pos) {
626 switch (lookupChange(pos).type) {
627 case Change::UNCHANGED:
628 // accept changes in nested inset
629 if (Inset * inset = getInset(pos))
630 inset->acceptChanges();
633 case Change::INSERTED:
634 d->changes_.set(Change(Change::UNCHANGED), pos);
635 // also accept changes in nested inset
636 if (Inset * inset = getInset(pos))
637 inset->acceptChanges();
640 case Change::DELETED:
641 // Suppress access to non-existent
642 // "end-of-paragraph char"
644 eraseChar(pos, false);
655 void Paragraph::rejectChanges(pos_type start, pos_type end)
657 LASSERT(start >= 0 && start <= size(), /**/);
658 LASSERT(end > start && end <= size() + 1, /**/);
660 for (pos_type pos = start; pos < end; ++pos) {
661 switch (lookupChange(pos).type) {
662 case Change::UNCHANGED:
663 // reject changes in nested inset
664 if (Inset * inset = getInset(pos))
665 inset->rejectChanges();
668 case Change::INSERTED:
669 // Suppress access to non-existent
670 // "end-of-paragraph char"
672 eraseChar(pos, false);
678 case Change::DELETED:
679 d->changes_.set(Change(Change::UNCHANGED), pos);
681 // Do NOT reject changes within a deleted inset!
682 // There may be insertions of a co-author inside of it!
690 void Paragraph::Private::insertChar(pos_type pos, char_type c,
691 Change const & change)
693 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
696 changes_.insert(change, pos);
698 // This is actually very common when parsing buffers (and
699 // maybe inserting ascii text)
700 if (pos == pos_type(text_.size())) {
701 // when appending characters, no need to update tables
703 // but we want spell checking
704 requestSpellCheck(pos);
708 text_.insert(text_.begin() + pos, c);
710 // Update the font table.
711 fontlist_.increasePosAfterPos(pos);
714 insetlist_.increasePosAfterPos(pos);
716 // Update list of misspelled positions
717 speller_state_.increasePosAfterPos(pos);
721 bool Paragraph::insertInset(pos_type pos, Inset * inset,
722 Change const & change)
724 LASSERT(inset, /**/);
725 LASSERT(pos >= 0 && pos <= size(), /**/);
727 // Paragraph::insertInset() can be used in cut/copy/paste operation where
728 // d->inset_owner_ is not set yet.
729 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
732 d->insertChar(pos, META_INSET, change);
733 LASSERT(d->text_[pos] == META_INSET, /**/);
735 // Add a new entry in the insetlist_.
736 d->insetlist_.insert(inset, pos);
738 // Some insets require run of spell checker
739 requestSpellCheck(pos);
744 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
746 LASSERT(pos >= 0 && pos <= size(), return false);
748 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
751 Change change = d->changes_.lookup(pos);
753 // set the character to DELETED if
754 // a) it was previously unchanged or
755 // b) it was inserted by a co-author
757 if (!change.changed() ||
758 (change.inserted() && !change.currentAuthor())) {
759 setChange(pos, Change(Change::DELETED));
760 // request run of spell checker
761 requestSpellCheck(pos);
765 if (change.deleted())
769 // Don't physically access the imaginary end-of-paragraph character.
770 // eraseChar() can only mark it as DELETED. A physical deletion of
771 // end-of-par must be handled externally.
777 d->changes_.erase(pos);
779 // if it is an inset, delete the inset entry
780 if (d->text_[pos] == META_INSET)
781 d->insetlist_.erase(pos);
783 d->text_.erase(d->text_.begin() + pos);
785 // Update the fontlist_
786 d->fontlist_.erase(pos);
788 // Update the insetlist_
789 d->insetlist_.decreasePosAfterPos(pos);
791 // Update list of misspelled positions
792 d->speller_state_.decreasePosAfterPos(pos);
793 d->speller_state_.refreshLast(size());
799 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
801 LASSERT(start >= 0 && start <= size(), /**/);
802 LASSERT(end >= start && end <= size() + 1, /**/);
805 for (pos_type count = end - start; count; --count) {
806 if (!eraseChar(i, trackChanges))
813 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
814 char_type next, OutputParams const & runparams)
816 // Writing next here may circumvent a possible font change between
817 // c and next. Since next is only output if it forms a surrogate pair
818 // with c we can ignore this:
819 // A font change inside a surrogate pair does not make sense and is
820 // hopefully impossible to input.
821 // FIXME: change tracking
822 // Is this correct WRT change tracking?
823 Encoding const & encoding = *(runparams.encoding);
824 docstring const latex1 = encoding.latexChar(next);
825 docstring const latex2 = encoding.latexChar(c);
826 if (docstring(1, next) == latex1) {
827 // the encoding supports the combination
828 os << latex2 << latex1;
829 return latex1.length() + latex2.length();
830 } else if (runparams.local_font &&
831 runparams.local_font->language()->lang() == "polutonikogreek") {
832 // polutonikogreek only works without the brackets
833 os << latex1 << latex2;
834 return latex1.length() + latex2.length();
836 os << latex1 << '{' << latex2 << '}';
837 return latex1.length() + latex2.length() + 2;
841 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
842 odocstream & os, TexRow & texrow,
844 unsigned int & column,
846 Layout const & style)
848 if (style.pass_thru || runparams.pass_thru)
851 if (i + 1 < int(text_.size())) {
852 char_type next = text_[i + 1];
853 if (Encodings::isCombiningChar(next)) {
854 // This space has an accent, so we must always output it.
855 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
860 if (runparams.linelen > 0
861 && column > runparams.linelen
863 && text_[i - 1] != ' '
864 && (i + 1 < int(text_.size()))
865 // same in FreeSpacing mode
866 && !owner_->isFreeSpacing()
867 // In typewriter mode, we want to avoid
868 // ! . ? : at the end of a line
869 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
870 && (text_[i - 1] == '.'
871 || text_[i - 1] == '?'
872 || text_[i - 1] == ':'
873 || text_[i - 1] == '!'))) {
876 texrow.start(owner_->id(), i + 1);
878 } else if (style.free_spacing) {
887 int Paragraph::Private::writeScriptChars(odocstream & os,
888 docstring const & ltx,
889 Change const & runningChange,
890 Encoding const & encoding,
893 // FIXME: modifying i here is not very nice...
895 // We only arrive here when a proper language for character text_[i] has
896 // not been specified (i.e., it could not be translated in the current
897 // latex encoding) or its latex translation has been forced, and it
898 // belongs to a known script.
899 // Parameter ltx contains the latex translation of text_[i] as specified
900 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
901 // The latex macro name "textXXX" specifies the script to which text_[i]
902 // belongs and we use it in order to check whether characters from the
903 // same script immediately follow, such that we can collect them in a
904 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
905 // for the first char but only "<spec>" for all subsequent chars.
906 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
907 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
908 string script = to_ascii(ltx.substr(1, brace1 - 1));
911 bool closing_brace = true;
912 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
913 // Correct encoding is being used, so we can avoid \textgreek.
916 closing_brace = false;
918 os << ltx.substr(pos, length);
919 int size = text_.size();
920 while (i + 1 < size) {
921 char_type const next = text_[i + 1];
922 // Stop here if next character belongs to another script
923 // or there is a change in change tracking status.
924 if (!Encodings::isKnownScriptChar(next, script) ||
925 runningChange != owner_->lookupChange(i + 1))
929 FontList::const_iterator cit = fontlist_.begin();
930 FontList::const_iterator end = fontlist_.end();
931 for (; cit != end; ++cit) {
932 if (cit->pos() >= i && !found) {
933 prev_font = cit->font();
936 if (cit->pos() >= i + 1)
939 // Stop here if there is a font attribute or encoding change.
940 if (found && cit != end && prev_font != cit->font())
942 docstring const latex = encoding.latexChar(next);
943 docstring::size_type const b1 =
944 latex.find_first_of(from_ascii("{"));
945 docstring::size_type const b2 =
946 latex.find_last_of(from_ascii("}"));
947 int const len = b2 - b1 - 1;
948 os << latex.substr(b1 + 1, len);
960 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
962 pos_type const len = str.length();
964 // is the paragraph large enough?
965 if (pos + len > int(text_.size()))
968 // does the wanted text start at point?
969 for (string::size_type i = 0; i < str.length(); ++i) {
970 // Caution: direct comparison of characters works only
971 // because str is pure ASCII.
972 if (str[i] != text_[pos + i])
976 return fontlist_.hasChangeInRange(pos, len);
980 void Paragraph::Private::latexInset(BufferParams const & bparams,
983 OutputParams & runparams,
986 Font const & outerfont,
988 Change & running_change,
989 Layout const & style,
991 unsigned int & column)
993 Inset * inset = owner_->getInset(i);
994 LASSERT(inset, /**/);
996 if (style.pass_thru) {
997 inset->plaintext(os, runparams);
1001 // FIXME: move this to InsetNewline::latex
1002 if (inset->lyxCode() == NEWLINE_CODE) {
1003 // newlines are handled differently here than
1004 // the default in simpleTeXSpecialChars().
1005 if (!style.newline_allowed) {
1009 column += running_font.latexWriteEndChanges(
1010 os, bparams, runparams,
1011 basefont, basefont);
1015 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1018 basefont = owner_->getLayoutFont(bparams, outerfont);
1019 running_font = basefont;
1021 if (runparams.moving_arg)
1026 texrow.start(owner_->id(), i + 1);
1030 if (owner_->isDeleted(i)) {
1031 if( ++runparams.inDeletedInset == 1)
1032 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1035 if (inset->canTrackChanges()) {
1036 column += Changes::latexMarkChange(os, bparams, running_change,
1037 Change(Change::UNCHANGED), runparams);
1038 running_change = Change(Change::UNCHANGED);
1042 odocstream::pos_type const len = os.tellp();
1044 if (inset->forceLTR()
1045 && running_font.isRightToLeft()
1046 // ERT is an exception, it should be output with no
1047 // decorations at all
1048 && inset->lyxCode() != ERT_CODE) {
1049 if (running_font.language()->lang() == "farsi")
1056 // FIXME: Bug: we can have an empty font change here!
1057 // if there has just been a font change, we are going to close it
1058 // right now, which means stupid latex code like \textsf{}. AFAIK,
1059 // this does not harm dvi output. A minor bug, thus (JMarc)
1061 // Some insets cannot be inside a font change command.
1062 // However, even such insets *can* be placed in \L or \R
1063 // or their equivalents (for RTL language switches), so we don't
1064 // close the language in those cases.
1065 // ArabTeX, though, cannot handle this special behavior, it seems.
1066 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1067 || running_font.language()->lang() == "arabic_arabtex";
1068 if (open_font && inset->noFontChange()) {
1069 bool closeLanguage = arabtex
1070 || basefont.isRightToLeft() == running_font.isRightToLeft();
1071 unsigned int count = running_font.latexWriteEndChanges(os,
1072 bparams, runparams, basefont, basefont, closeLanguage);
1074 // if any font properties were closed, update the running_font,
1075 // making sure, however, to leave the language as it was
1077 // FIXME: probably a better way to keep track of the old
1078 // language, than copying the entire font?
1079 Font const copy_font(running_font);
1080 basefont = owner_->getLayoutFont(bparams, outerfont);
1081 running_font = basefont;
1083 running_font.setLanguage(copy_font.language());
1084 // leave font open if language is still open
1085 open_font = (running_font.language() == basefont.language());
1087 runparams.local_font = &basefont;
1094 tmp = inset->latex(os, runparams);
1095 } catch (EncodingException & e) {
1096 // add location information and throw again.
1103 if (running_font.language()->lang() == "farsi")
1110 texrow.newlines(tmp);
1111 texrow.start(owner_->id(), i + 1);
1114 column += os.tellp() - len;
1117 if (owner_->isDeleted(i))
1118 --runparams.inDeletedInset;
1122 void Paragraph::Private::latexSpecialChar(
1124 OutputParams const & runparams,
1125 Font const & running_font,
1126 Change const & running_change,
1127 Layout const & style,
1129 unsigned int & column)
1131 char_type const c = text_[i];
1133 if (style.pass_thru || runparams.pass_thru) {
1135 // FIXME UNICODE: This can fail if c cannot
1136 // be encoded in the current encoding.
1141 // If T1 font encoding is used, use the special
1142 // characters it provides.
1143 // NOTE: some languages reset the font encoding
1145 if (!running_font.language()->internalFontEncoding()
1146 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1149 // \tt font needs special treatment
1150 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1151 && latexSpecialTypewriter(c, os, i, column))
1154 // Otherwise, we use what LaTeX provides us.
1157 os << "\\textbackslash{}";
1161 os << "\\textless{}";
1165 os << "\\textgreater{}";
1169 os << "\\textbar{}";
1176 os << "\\char`\\\"{}";
1181 case '%': case '#': case '{':
1189 os << "\\textasciitilde{}";
1194 os << "\\textasciicircum{}";
1201 // avoid being mistaken for optional arguments
1209 // Blanks are printed before font switching.
1210 // Sure? I am not! (try nice-latex)
1211 // I am sure it's correct. LyX might be smarter
1212 // in the future, but for now, nothing wrong is
1218 if (latexSpecialPhrase(os, i, column, runparams))
1224 Encoding const & encoding = *(runparams.encoding);
1225 if (i + 1 < int(text_.size())) {
1226 char_type next = text_[i + 1];
1227 if (Encodings::isCombiningChar(next)) {
1228 column += latexSurrogatePair(os, c, next, runparams) - 1;
1234 docstring const latex = encoding.latexChar(c);
1235 if (Encodings::isKnownScriptChar(c, script)
1236 && prefixIs(latex, from_ascii("\\" + script)))
1237 column += writeScriptChars(os, latex,
1238 running_change, encoding, i) - 1;
1239 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1240 // Prevent eating of a following
1241 // space or command corruption by
1242 // following characters
1243 column += latex.length() + 1;
1244 os << latex << "{}";
1246 column += latex.length() - 1;
1254 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1255 pos_type i, unsigned int & column)
1261 // In T1 encoding, these characters exist
1262 // but we should avoid ligatures
1263 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1265 os << "\\textcompwordmark{}";
1272 // soul.sty breaks with \char`\"
1273 os << "\\textquotedbl{}";
1282 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1283 pos_type i, unsigned int & column)
1287 // within \ttfamily, "--" is merged to "-" (no endash)
1288 // so we avoid this rather irritating ligature
1289 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1296 // everything else has to be checked separately
1297 // (depending on the encoding)
1304 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1305 unsigned int & column, OutputParams const & runparams)
1307 // FIXME: if we have "LaTeX" with a font
1308 // change in the middle (before the 'T', then
1309 // the "TeX" part is still special cased.
1310 // Really we should only operate this on
1311 // "words" for some definition of word
1313 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1314 if (!isTextAt(special_phrases[pnr].phrase, i))
1316 if (runparams.moving_arg)
1318 os << special_phrases[pnr].macro;
1319 i += special_phrases[pnr].phrase.length() - 1;
1320 column += special_phrases[pnr].macro.length() - 1;
1327 void Paragraph::Private::validate(LaTeXFeatures & features) const
1329 if (layout_->inpreamble && inset_owner_) {
1330 Buffer const & buf = inset_owner_->buffer();
1331 BufferParams const & bp = buf.params();
1334 odocstringstream ods;
1335 // we have to provide all the optional arguments here, even though
1336 // the last one is the only one we care about.
1337 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1338 docstring const d = ods.str();
1340 // this will have "{" at the beginning, but not at the end
1341 string const content = to_utf8(d);
1342 string const cmd = layout_->latexname();
1343 features.addPreambleSnippet("\\" + cmd + content + "}");
1347 if (features.runparams().flavor == OutputParams::HTML
1348 && layout_->htmltitle()) {
1349 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1352 // check the params.
1353 if (!params_.spacing().isDefault())
1354 features.require("setspace");
1357 features.useLayout(layout_->name());
1360 fontlist_.validate(features);
1362 // then the indentation
1363 if (!params_.leftIndent().zero())
1364 features.require("ParagraphLeftIndent");
1367 InsetList::const_iterator icit = insetlist_.begin();
1368 InsetList::const_iterator iend = insetlist_.end();
1369 for (; icit != iend; ++icit) {
1371 icit->inset->validate(features);
1372 if (layout_->needprotect &&
1373 icit->inset->lyxCode() == FOOT_CODE)
1374 features.require("NeedLyXFootnoteCode");
1378 // then the contents
1379 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1380 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1381 if (!special_phrases[pnr].builtin
1382 && isTextAt(special_phrases[pnr].phrase, i)) {
1383 features.require(special_phrases[pnr].phrase);
1387 Encodings::validate(text_[i], features);
1391 /////////////////////////////////////////////////////////////////////
1395 /////////////////////////////////////////////////////////////////////
1398 Layout const emptyParagraphLayout;
1401 Paragraph::Paragraph()
1402 : d(new Paragraph::Private(this, emptyParagraphLayout))
1409 Paragraph::Paragraph(Paragraph const & par)
1410 : itemdepth(par.itemdepth),
1411 d(new Paragraph::Private(*par.d, this))
1417 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1418 : itemdepth(par.itemdepth),
1419 d(new Paragraph::Private(*par.d, this, beg, end))
1425 Paragraph & Paragraph::operator=(Paragraph const & par)
1427 // needed as we will destroy the private part before copying it
1429 itemdepth = par.itemdepth;
1433 d = new Private(*par.d, this);
1440 Paragraph::~Paragraph()
1449 // this shall be called just before every "os << ..." action.
1450 void flushString(ostream & os, docstring & s)
1459 void Paragraph::write(ostream & os, BufferParams const & bparams,
1460 depth_type & dth) const
1462 // The beginning or end of a deeper (i.e. nested) area?
1463 if (dth != d->params_.depth()) {
1464 if (d->params_.depth() > dth) {
1465 while (d->params_.depth() > dth) {
1466 os << "\n\\begin_deeper";
1470 while (d->params_.depth() < dth) {
1471 os << "\n\\end_deeper";
1477 // First write the layout
1478 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1480 d->params_.write(os);
1482 Font font1(inherit_font, bparams.language);
1484 Change running_change = Change(Change::UNCHANGED);
1486 // this string is used as a buffer to avoid repetitive calls
1487 // to to_utf8(), which turn out to be expensive (JMarc)
1488 docstring write_buffer;
1491 for (pos_type i = 0; i <= size(); ++i) {
1493 Change const change = lookupChange(i);
1494 if (change != running_change)
1495 flushString(os, write_buffer);
1496 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1497 running_change = change;
1502 // Write font changes
1503 Font font2 = getFontSettings(bparams, i);
1504 if (font2 != font1) {
1505 flushString(os, write_buffer);
1506 font2.lyxWriteChanges(font1, os);
1511 char_type const c = d->text_[i];
1514 if (Inset const * inset = getInset(i)) {
1515 flushString(os, write_buffer);
1516 if (inset->directWrite()) {
1517 // international char, let it write
1518 // code directly so it's shorter in
1524 os << "\\begin_inset ";
1526 os << "\n\\end_inset\n\n";
1532 flushString(os, write_buffer);
1533 os << "\n\\backslash\n";
1537 flushString(os, write_buffer);
1538 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1545 if ((column > 70 && c == ' ')
1547 flushString(os, write_buffer);
1551 // this check is to amend a bug. LyX sometimes
1552 // inserts '\0' this could cause problems.
1554 write_buffer.push_back(c);
1556 LYXERR0("NUL char in structure.");
1562 flushString(os, write_buffer);
1563 os << "\n\\end_layout\n";
1567 void Paragraph::validate(LaTeXFeatures & features) const
1569 d->validate(features);
1573 void Paragraph::insert(pos_type start, docstring const & str,
1574 Font const & font, Change const & change)
1576 for (size_t i = 0, n = str.size(); i != n ; ++i)
1577 insertChar(start + i, str[i], font, change);
1581 void Paragraph::appendChar(char_type c, Font const & font,
1582 Change const & change)
1585 d->changes_.insert(change, d->text_.size());
1586 // when appending characters, no need to update tables
1587 d->text_.push_back(c);
1588 setFont(d->text_.size() - 1, font);
1592 void Paragraph::appendString(docstring const & s, Font const & font,
1593 Change const & change)
1595 pos_type end = s.size();
1596 size_t oldsize = d->text_.size();
1597 size_t newsize = oldsize + end;
1598 size_t capacity = d->text_.capacity();
1599 if (newsize >= capacity)
1600 d->text_.reserve(max(capacity + 100, newsize));
1602 // when appending characters, no need to update tables
1605 // FIXME: Optimize this!
1606 for (size_t i = oldsize; i != newsize; ++i) {
1608 d->changes_.insert(change, i);
1610 d->fontlist_.set(oldsize, font);
1611 d->fontlist_.set(newsize - 1, font);
1615 void Paragraph::insertChar(pos_type pos, char_type c,
1618 d->insertChar(pos, c, Change(trackChanges ?
1619 Change::INSERTED : Change::UNCHANGED));
1623 void Paragraph::insertChar(pos_type pos, char_type c,
1624 Font const & font, bool trackChanges)
1626 d->insertChar(pos, c, Change(trackChanges ?
1627 Change::INSERTED : Change::UNCHANGED));
1632 void Paragraph::insertChar(pos_type pos, char_type c,
1633 Font const & font, Change const & change)
1635 d->insertChar(pos, c, change);
1640 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1641 Font const & font, Change const & change)
1643 bool const success = insertInset(pos, inset, change);
1644 // Set the font/language of the inset...
1650 void Paragraph::resetFonts(Font const & font)
1652 d->fontlist_.clear();
1653 d->fontlist_.set(0, font);
1654 d->fontlist_.set(d->text_.size() - 1, font);
1657 // Gets uninstantiated font setting at position.
1658 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1662 LYXERR0("pos: " << pos << " size: " << size());
1663 LASSERT(pos <= size(), /**/);
1666 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1667 if (cit != d->fontlist_.end())
1670 if (pos == size() && !empty())
1671 return getFontSettings(bparams, pos - 1);
1673 // Optimisation: avoid a full font instantiation if there is no
1674 // language change from previous call.
1675 static Font previous_font;
1676 static Language const * previous_lang = 0;
1677 Language const * lang = getParLanguage(bparams);
1678 if (lang != previous_lang) {
1679 previous_lang = lang;
1680 previous_font = Font(inherit_font, lang);
1682 return previous_font;
1686 FontSpan Paragraph::fontSpan(pos_type pos) const
1688 LASSERT(pos <= size(), /**/);
1691 FontList::const_iterator cit = d->fontlist_.begin();
1692 FontList::const_iterator end = d->fontlist_.end();
1693 for (; cit != end; ++cit) {
1694 if (cit->pos() >= pos) {
1695 if (pos >= beginOfBody())
1696 return FontSpan(max(start, beginOfBody()),
1699 return FontSpan(start,
1700 min(beginOfBody() - 1,
1703 start = cit->pos() + 1;
1706 // This should not happen, but if so, we take no chances.
1707 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1708 return FontSpan(pos, pos);
1712 // Gets uninstantiated font setting at position 0
1713 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1715 if (!empty() && !d->fontlist_.empty())
1716 return d->fontlist_.begin()->font();
1718 // Optimisation: avoid a full font instantiation if there is no
1719 // language change from previous call.
1720 static Font previous_font;
1721 static Language const * previous_lang = 0;
1722 if (bparams.language != previous_lang) {
1723 previous_lang = bparams.language;
1724 previous_font = Font(inherit_font, bparams.language);
1727 return previous_font;
1731 // Gets the fully instantiated font at a given position in a paragraph
1732 // This is basically the same function as Text::GetFont() in text2.cpp.
1733 // The difference is that this one is used for generating the LaTeX file,
1734 // and thus cosmetic "improvements" are disallowed: This has to deliver
1735 // the true picture of the buffer. (Asger)
1736 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1737 Font const & outerfont) const
1739 LASSERT(pos >= 0, /**/);
1741 Font font = getFontSettings(bparams, pos);
1743 pos_type const body_pos = beginOfBody();
1744 FontInfo & fi = font.fontInfo();
1746 fi.realize(d->layout_->labelfont);
1748 fi.realize(d->layout_->font);
1750 fi.realize(outerfont.fontInfo());
1751 fi.realize(bparams.getFont().fontInfo());
1757 Font const Paragraph::getLabelFont
1758 (BufferParams const & bparams, Font const & outerfont) const
1760 FontInfo tmpfont = d->layout_->labelfont;
1761 tmpfont.realize(outerfont.fontInfo());
1762 tmpfont.realize(bparams.getFont().fontInfo());
1763 return Font(tmpfont, getParLanguage(bparams));
1767 Font const Paragraph::getLayoutFont
1768 (BufferParams const & bparams, Font const & outerfont) const
1770 FontInfo tmpfont = d->layout_->font;
1771 tmpfont.realize(outerfont.fontInfo());
1772 tmpfont.realize(bparams.getFont().fontInfo());
1773 return Font(tmpfont, getParLanguage(bparams));
1777 /// Returns the height of the highest font in range
1778 FontSize Paragraph::highestFontInRange
1779 (pos_type startpos, pos_type endpos, FontSize def_size) const
1781 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1785 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1787 char_type c = d->text_[pos];
1788 if (!lyxrc.rtl_support)
1818 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1824 void Paragraph::setFont(pos_type pos, Font const & font)
1826 LASSERT(pos <= size(), /**/);
1828 // First, reduce font against layout/label font
1829 // Update: The setCharFont() routine in text2.cpp already
1830 // reduces font, so we don't need to do that here. (Asger)
1832 d->fontlist_.set(pos, font);
1836 void Paragraph::makeSameLayout(Paragraph const & par)
1838 d->layout_ = par.d->layout_;
1839 d->params_ = par.d->params_;
1843 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1845 if (isFreeSpacing())
1851 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1852 if (eraseChar(pos, trackChanges))
1858 return count > 0 || pos > 0;
1862 bool Paragraph::hasSameLayout(Paragraph const & par) const
1864 return par.d->layout_ == d->layout_
1865 && d->params_.sameLayout(par.d->params_);
1869 depth_type Paragraph::getDepth() const
1871 return d->params_.depth();
1875 depth_type Paragraph::getMaxDepthAfter() const
1877 if (d->layout_->isEnvironment())
1878 return d->params_.depth() + 1;
1880 return d->params_.depth();
1884 char Paragraph::getAlign() const
1886 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1887 return d->layout_->align;
1889 return d->params_.align();
1893 docstring const & Paragraph::labelString() const
1895 return d->params_.labelString();
1899 // the next two functions are for the manual labels
1900 docstring const Paragraph::getLabelWidthString() const
1902 if (d->layout_->margintype == MARGIN_MANUAL
1903 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1904 return d->params_.labelWidthString();
1906 return _("Senseless with this layout!");
1910 void Paragraph::setLabelWidthString(docstring const & s)
1912 d->params_.labelWidthString(s);
1916 docstring Paragraph::expandLabel(Layout const & layout,
1917 BufferParams const & bparams) const
1919 return expandParagraphLabel(layout, bparams, true);
1923 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1924 BufferParams const & bparams) const
1926 return expandParagraphLabel(layout, bparams, false);
1930 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1931 BufferParams const & bparams, bool process_appendix) const
1933 DocumentClass const & tclass = bparams.documentClass();
1934 string const & lang = getParLanguage(bparams)->code();
1935 bool const in_appendix = process_appendix && d->params_.appendix();
1936 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1938 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1939 && !layout.counter.empty())
1940 return tclass.counters().theCounter(layout.counter, lang);
1942 // handle 'inherited level parts' in 'fmt',
1943 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1944 size_t const i = fmt.find('@', 0);
1945 if (i != docstring::npos) {
1946 size_t const j = fmt.find('@', i + 1);
1947 if (j != docstring::npos) {
1948 docstring parent(fmt, i + 1, j - i - 1);
1949 docstring label = from_ascii("??");
1950 if (tclass.hasLayout(parent))
1951 docstring label = expandParagraphLabel(tclass[parent], bparams,
1953 fmt = docstring(fmt, 0, i) + label
1954 + docstring(fmt, j + 1, docstring::npos);
1958 return tclass.counters().counterLabel(fmt, lang);
1962 void Paragraph::applyLayout(Layout const & new_layout)
1964 d->layout_ = &new_layout;
1965 LyXAlignment const oldAlign = d->params_.align();
1967 if (!(oldAlign & d->layout_->alignpossible)) {
1968 frontend::Alert::warning(_("Alignment not permitted"),
1969 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1970 d->params_.align(LYX_ALIGN_LAYOUT);
1975 pos_type Paragraph::beginOfBody() const
1977 return d->begin_of_body_;
1981 void Paragraph::setBeginOfBody()
1983 if (d->layout_->labeltype != LABEL_MANUAL) {
1984 d->begin_of_body_ = 0;
1988 // Unroll the first two cycles of the loop
1989 // and remember the previous character to
1990 // remove unnecessary getChar() calls
1992 pos_type end = size();
1993 if (i < end && !isNewline(i)) {
1995 char_type previous_char = 0;
1998 previous_char = d->text_[i];
1999 if (!isNewline(i)) {
2001 while (i < end && previous_char != ' ') {
2006 previous_char = temp;
2012 d->begin_of_body_ = i;
2016 bool Paragraph::allowParagraphCustomization() const
2018 return inInset().allowParagraphCustomization();
2022 bool Paragraph::usePlainLayout() const
2024 return inInset().usePlainLayout();
2030 // paragraphs inside floats need different alignment tags to avoid
2033 bool noTrivlistCentering(InsetCode code)
2035 return code == FLOAT_CODE
2036 || code == WRAP_CODE
2037 || code == CELL_CODE;
2041 string correction(string const & orig)
2043 if (orig == "flushleft")
2044 return "raggedright";
2045 if (orig == "flushright")
2046 return "raggedleft";
2047 if (orig == "center")
2053 string const corrected_env(string const & suffix, string const & env,
2054 InsetCode code, bool const lastpar)
2056 string output = suffix + "{";
2057 if (noTrivlistCentering(code)) {
2059 // the last paragraph in non-trivlist-aligned
2060 // context is special (to avoid unwanted whitespace)
2061 if (suffix == "\\begin")
2062 return "\\" + correction(env) + "{}";
2065 output += correction(env);
2069 if (suffix == "\\begin")
2075 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2077 if (!contains(str, "\n"))
2078 column += str.size();
2082 column = rsplit(str, tmp, '\n').size();
2089 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2090 odocstream & os, TexRow & texrow,
2091 OutputParams const & runparams) const
2095 if (params_.noindent()) {
2096 os << "\\noindent ";
2100 LyXAlignment const curAlign = params_.align();
2102 if (curAlign == layout_->align)
2106 case LYX_ALIGN_NONE:
2107 case LYX_ALIGN_BLOCK:
2108 case LYX_ALIGN_LAYOUT:
2109 case LYX_ALIGN_SPECIAL:
2110 case LYX_ALIGN_DECIMAL:
2112 case LYX_ALIGN_LEFT:
2113 case LYX_ALIGN_RIGHT:
2114 case LYX_ALIGN_CENTER:
2115 if (runparams.moving_arg) {
2122 string const begin_tag = "\\begin";
2123 InsetCode code = ownerCode();
2124 bool const lastpar = runparams.isLastPar;
2127 case LYX_ALIGN_NONE:
2128 case LYX_ALIGN_BLOCK:
2129 case LYX_ALIGN_LAYOUT:
2130 case LYX_ALIGN_SPECIAL:
2131 case LYX_ALIGN_DECIMAL:
2133 case LYX_ALIGN_LEFT: {
2135 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2136 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2138 output = corrected_env(begin_tag, "flushright", code, lastpar);
2139 os << from_ascii(output);
2140 adjust_row_column(output, texrow, column);
2142 } case LYX_ALIGN_RIGHT: {
2144 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2145 output = corrected_env(begin_tag, "flushright", code, lastpar);
2147 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2148 os << from_ascii(output);
2149 adjust_row_column(output, texrow, column);
2151 } case LYX_ALIGN_CENTER: {
2153 output = corrected_env(begin_tag, "center", code, lastpar);
2154 os << from_ascii(output);
2155 adjust_row_column(output, texrow, column);
2164 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2165 odocstream & os, TexRow & texrow,
2166 OutputParams const & runparams) const
2170 LyXAlignment const curAlign = params_.align();
2172 if (curAlign == layout_->align)
2176 case LYX_ALIGN_NONE:
2177 case LYX_ALIGN_BLOCK:
2178 case LYX_ALIGN_LAYOUT:
2179 case LYX_ALIGN_SPECIAL:
2180 case LYX_ALIGN_DECIMAL:
2182 case LYX_ALIGN_LEFT:
2183 case LYX_ALIGN_RIGHT:
2184 case LYX_ALIGN_CENTER:
2185 if (runparams.moving_arg) {
2192 string const end_tag = "\n\\par\\end";
2193 InsetCode code = ownerCode();
2194 bool const lastpar = runparams.isLastPar;
2197 case LYX_ALIGN_NONE:
2198 case LYX_ALIGN_BLOCK:
2199 case LYX_ALIGN_LAYOUT:
2200 case LYX_ALIGN_SPECIAL:
2201 case LYX_ALIGN_DECIMAL:
2203 case LYX_ALIGN_LEFT: {
2205 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2206 output = corrected_env(end_tag, "flushleft", code, lastpar);
2208 output = corrected_env(end_tag, "flushright", code, lastpar);
2209 os << from_ascii(output);
2210 adjust_row_column(output, texrow, column);
2212 } case LYX_ALIGN_RIGHT: {
2214 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2215 output = corrected_env(end_tag, "flushright", code, lastpar);
2217 output = corrected_env(end_tag, "flushleft", code, lastpar);
2218 os << from_ascii(output);
2219 adjust_row_column(output, texrow, column);
2221 } case LYX_ALIGN_CENTER: {
2223 output = corrected_env(end_tag, "center", code, lastpar);
2224 os << from_ascii(output);
2225 adjust_row_column(output, texrow, column);
2234 // This one spits out the text of the paragraph
2235 void Paragraph::latex(BufferParams const & bparams,
2236 Font const & outerfont,
2237 odocstream & os, TexRow & texrow,
2238 OutputParams const & runparams,
2239 int start_pos, int end_pos, bool force) const
2241 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2243 // FIXME This check should not be needed. Perhaps issue an
2244 // error if it triggers.
2245 Layout const & style = inInset().forcePlainLayout() ?
2246 bparams.documentClass().plainLayout() : *d->layout_;
2248 if (!force && style.inpreamble)
2251 bool const allowcust = allowParagraphCustomization();
2253 // Current base font for all inherited font changes, without any
2254 // change caused by an individual character, except for the language:
2255 // It is set to the language of the first character.
2256 // As long as we are in the label, this font is the base font of the
2257 // label. Before the first body character it is set to the base font
2261 // Maybe we have to create a optional argument.
2262 pos_type body_pos = beginOfBody();
2263 unsigned int column = 0;
2266 // the optional argument is kept in curly brackets in
2267 // case it contains a ']'
2270 basefont = getLabelFont(bparams, outerfont);
2272 basefont = getLayoutFont(bparams, outerfont);
2275 // Which font is currently active?
2276 Font running_font(basefont);
2277 // Do we have an open font change?
2278 bool open_font = false;
2280 Change runningChange = Change(Change::UNCHANGED);
2282 Encoding const * const prev_encoding = runparams.encoding;
2284 texrow.start(id(), 0);
2286 // if the paragraph is empty, the loop will not be entered at all
2288 if (style.isCommand()) {
2293 column += d->startTeXParParams(bparams, os, texrow,
2297 for (pos_type i = 0; i < size(); ++i) {
2298 // First char in paragraph or after label?
2299 if (i == body_pos) {
2302 column += running_font.latexWriteEndChanges(
2303 os, bparams, runparams,
2304 basefont, basefont);
2307 basefont = getLayoutFont(bparams, outerfont);
2308 running_font = basefont;
2310 column += Changes::latexMarkChange(os, bparams,
2311 runningChange, Change(Change::UNCHANGED),
2313 runningChange = Change(Change::UNCHANGED);
2318 if (style.isCommand()) {
2324 column += d->startTeXParParams(bparams, os,
2329 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2332 if (bparams.outputChanges && runningChange != change) {
2334 column += running_font.latexWriteEndChanges(
2335 os, bparams, runparams, basefont, basefont);
2338 basefont = getLayoutFont(bparams, outerfont);
2339 running_font = basefont;
2341 column += Changes::latexMarkChange(os, bparams, runningChange,
2343 runningChange = change;
2346 // do not output text which is marked deleted
2347 // if change tracking output is disabled
2348 if (!bparams.outputChanges && change.deleted()) {
2354 // Fully instantiated font
2355 Font const font = getFont(bparams, i, outerfont);
2357 Font const last_font = running_font;
2359 // Do we need to close the previous font?
2361 (font != running_font ||
2362 font.language() != running_font.language()))
2364 column += running_font.latexWriteEndChanges(
2365 os, bparams, runparams, basefont,
2366 (i == body_pos-1) ? basefont : font);
2367 running_font = basefont;
2371 // close babel's font environment before opening CJK.
2372 if (!running_font.language()->babel().empty() &&
2373 font.language()->encoding()->package() == Encoding::CJK) {
2374 string end_tag = subst(lyxrc.language_command_end,
2376 running_font.language()->babel());
2377 os << from_ascii(end_tag);
2378 column += end_tag.length();
2381 // Switch file encoding if necessary (and allowed)
2382 if (!runparams.pass_thru && !style.pass_thru &&
2383 runparams.encoding->package() != Encoding::none &&
2384 font.language()->encoding()->package() != Encoding::none) {
2385 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2386 runparams, *(font.language()->encoding()));
2387 if (enc_switch.first) {
2388 column += enc_switch.second;
2389 runparams.encoding = font.language()->encoding();
2393 char_type const c = d->text_[i];
2395 // Do we need to change font?
2396 if ((font != running_font ||
2397 font.language() != running_font.language()) &&
2400 odocstringstream ods;
2401 column += font.latexWriteStartChanges(ods, bparams,
2402 runparams, basefont,
2404 running_font = font;
2406 docstring fontchange = ods.str();
2407 // check whether the fontchange ends with a \\textcolor
2408 // modifier and the text starts with a space (bug 4473)
2409 docstring const last_modifier = rsplit(fontchange, '\\');
2410 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2411 os << fontchange << from_ascii("{}");
2412 // check if the fontchange ends with a trailing blank
2413 // (like "\small " (see bug 3382)
2414 else if (suffixIs(fontchange, ' ') && c == ' ')
2415 os << fontchange.substr(0, fontchange.size() - 1)
2416 << from_ascii("{}");
2421 // FIXME: think about end_pos implementation...
2422 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2423 // FIXME: integrate this case in latexSpecialChar
2424 // Do not print the separation of the optional argument
2425 // if style.pass_thru is false. This works because
2426 // latexSpecialChar ignores spaces if
2427 // style.pass_thru is false.
2428 if (i != body_pos - 1) {
2429 if (d->simpleTeXBlanks(
2430 runparams, os, texrow,
2431 i, column, font, style)) {
2432 // A surrogate pair was output. We
2433 // must not call latexSpecialChar
2434 // in this iteration, since it would output
2435 // the combining character again.
2442 OutputParams rp = runparams;
2443 rp.free_spacing = style.free_spacing;
2444 rp.local_font = &font;
2445 rp.intitle = style.intitle;
2447 // Two major modes: LaTeX or plain
2448 // Handle here those cases common to both modes
2449 // and then split to handle the two modes separately.
2450 if (c == META_INSET) {
2451 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2452 d->latexInset(bparams, os,
2453 texrow, rp, running_font,
2454 basefont, outerfont, open_font,
2455 runningChange, style, i, column);
2458 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2460 d->latexSpecialChar(os, rp, running_font, runningChange,
2462 } catch (EncodingException & e) {
2463 if (runparams.dryrun) {
2464 os << "<" << _("LyX Warning: ")
2465 << _("uncodable character") << " '";
2469 // add location information and throw again.
2478 // Set the encoding to that returned from latexSpecialChar (see
2479 // comment for encoding member in OutputParams.h)
2480 runparams.encoding = rp.encoding;
2483 // If we have an open font definition, we have to close it
2485 #ifdef FIXED_LANGUAGE_END_DETECTION
2487 running_font.latexWriteEndChanges(os, bparams,
2488 runparams, basefont,
2489 next_->getFont(bparams, 0, outerfont));
2491 running_font.latexWriteEndChanges(os, bparams,
2492 runparams, basefont, basefont);
2495 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2496 //FIXME: there as we start another \selectlanguage with the next paragraph if
2497 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2498 running_font.latexWriteEndChanges(os, bparams, runparams,
2499 basefont, basefont);
2503 column += Changes::latexMarkChange(os, bparams, runningChange,
2504 Change(Change::UNCHANGED), runparams);
2506 // Needed if there is an optional argument but no contents.
2507 if (body_pos > 0 && body_pos == size()) {
2511 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2512 && runparams.encoding != prev_encoding) {
2513 runparams.encoding = prev_encoding;
2514 if (!bparams.useXetex)
2515 os << setEncoding(prev_encoding->iconvName());
2518 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2522 bool Paragraph::emptyTag() const
2524 for (pos_type i = 0; i < size(); ++i) {
2525 if (Inset const * inset = getInset(i)) {
2526 InsetCode lyx_code = inset->lyxCode();
2527 // FIXME testing like that is wrong. What is
2529 if (lyx_code != TOC_CODE &&
2530 lyx_code != INCLUDE_CODE &&
2531 lyx_code != GRAPHICS_CODE &&
2532 lyx_code != ERT_CODE &&
2533 lyx_code != LISTINGS_CODE &&
2534 lyx_code != FLOAT_CODE &&
2535 lyx_code != TABULAR_CODE) {
2539 char_type c = d->text_[i];
2540 if (c != ' ' && c != '\t')
2548 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2551 for (pos_type i = 0; i < size(); ++i) {
2552 if (Inset const * inset = getInset(i)) {
2553 InsetCode lyx_code = inset->lyxCode();
2554 if (lyx_code == LABEL_CODE) {
2555 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2556 docstring const & id = il->getParam("name");
2557 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2565 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2569 for (i = 0; i < size(); ++i) {
2570 if (Inset const * inset = getInset(i)) {
2571 inset->docbook(os, runparams);
2573 char_type c = d->text_[i];
2576 os << sgml::escapeChar(c);
2583 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2587 for (i = 0; i < size(); ++i) {
2588 if (Inset const * inset = getInset(i)) {
2589 inset->xhtml(xs, runparams);
2591 char_type c = d->text_[i];
2601 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2604 pos_type size = text_.size();
2605 for (pos_type i = initial; i < size; ++i) {
2606 Font font = owner_->getFont(buf.params(), i, outerfont);
2607 if (text_[i] == META_INSET)
2609 if (i != initial && font != font_old)
2618 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2620 OutputParams const & runparams,
2621 Font const & outerfont,
2622 pos_type initial) const
2624 bool emph_flag = false;
2626 Layout const & style = *d->layout_;
2628 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2630 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2633 // parsing main loop
2634 for (pos_type i = initial; i < size(); ++i) {
2635 Font font = getFont(buf.params(), i, outerfont);
2637 // handle <emphasis> tag
2638 if (font_old.emph() != font.fontInfo().emph()) {
2639 if (font.fontInfo().emph() == FONT_ON) {
2642 } else if (i != initial) {
2643 os << "</emphasis>";
2648 if (Inset const * inset = getInset(i)) {
2649 inset->docbook(os, runparams);
2651 char_type c = d->text_[i];
2653 if (style.pass_thru)
2656 os << sgml::escapeChar(c);
2658 font_old = font.fontInfo();
2662 os << "</emphasis>";
2665 if (style.free_spacing)
2667 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2672 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2674 OutputParams const & runparams,
2675 Font const & outerfont,
2676 pos_type initial) const
2680 bool emph_flag = false;
2681 bool bold_flag = false;
2684 Layout const & style = *d->layout_;
2686 if (!runparams.for_toc && runparams.html_make_pars) {
2687 // generate a magic label for this paragraph
2688 string const attr = "id='" + magicLabel() + "'";
2689 xs << html::CompTag("a", attr);
2693 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2695 // parsing main loop
2696 for (pos_type i = initial; i < size(); ++i) {
2697 // let's not show deleted material in the output
2701 Font font = getFont(buf.params(), i, outerfont);
2704 if (font_old.emph() != font.fontInfo().emph()) {
2705 if (font.fontInfo().emph() == FONT_ON) {
2706 xs << html::StartTag("em");
2708 } else if (emph_flag && i != initial) {
2709 xs << html::EndTag("em");
2714 if (font_old.series() != font.fontInfo().series()) {
2715 if (font.fontInfo().series() == BOLD_SERIES) {
2716 xs << html::StartTag("strong");
2718 } else if (bold_flag && i != initial) {
2719 xs << html::EndTag("strong");
2724 // Other such tags? What about the other text ranges?
2726 Inset const * inset = getInset(i);
2728 if (!runparams.for_toc || inset->isInToc()) {
2729 OutputParams np = runparams;
2730 if (!inset->getLayout().htmlisblock())
2731 np.html_in_par = true;
2732 retval += inset->xhtml(xs, np);
2735 char_type c = d->text_[i];
2737 if (style.pass_thru)
2739 else if (c == '-') {
2742 if (j < size() && d->text_[j] == '-') {
2744 if (j < size() && d->text_[j] == '-') {
2745 str += from_ascii("—");
2748 str += from_ascii("–");
2754 // We don't want to escape the entities. Note that
2755 // it is safe to do this, since str can otherwise
2756 // only be "-". E.g., it can't be "<".
2757 xs << XHTMLStream::NextRaw() << str;
2761 font_old = font.fontInfo();
2769 bool Paragraph::isHfill(pos_type pos) const
2771 Inset const * inset = getInset(pos);
2772 return inset && (inset->lyxCode() == SPACE_CODE &&
2773 inset->isStretchableSpace());
2777 bool Paragraph::isNewline(pos_type pos) const
2779 Inset const * inset = getInset(pos);
2780 return inset && inset->lyxCode() == NEWLINE_CODE;
2784 bool Paragraph::isLineSeparator(pos_type pos) const
2786 char_type const c = d->text_[pos];
2787 if (isLineSeparatorChar(c))
2789 Inset const * inset = getInset(pos);
2790 return inset && inset->isLineSeparator();
2794 bool Paragraph::isWordSeparator(pos_type pos) const
2796 if (Inset const * inset = getInset(pos))
2797 return !inset->isLetter();
2798 char_type const c = d->text_[pos];
2799 // We want to pass the ' and escape chars to the spellchecker
2800 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2801 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2806 bool Paragraph::isChar(pos_type pos) const
2808 if (Inset const * inset = getInset(pos))
2809 return inset->isChar();
2810 char_type const c = d->text_[pos];
2811 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2815 bool Paragraph::isSpace(pos_type pos) const
2817 if (Inset const * inset = getInset(pos))
2818 return inset->isSpace();
2819 char_type const c = d->text_[pos];
2820 return lyx::isSpace(c);
2825 Paragraph::getParLanguage(BufferParams const & bparams) const
2828 return getFirstFontSettings(bparams).language();
2829 // FIXME: we should check the prev par as well (Lgb)
2830 return bparams.language;
2834 bool Paragraph::isRTL(BufferParams const & bparams) const
2836 return lyxrc.rtl_support
2837 && getParLanguage(bparams)->rightToLeft()
2838 && !inInset().getLayout().forceLTR();
2842 void Paragraph::changeLanguage(BufferParams const & bparams,
2843 Language const * from, Language const * to)
2845 // change language including dummy font change at the end
2846 for (pos_type i = 0; i <= size(); ++i) {
2847 Font font = getFontSettings(bparams, i);
2848 if (font.language() == from) {
2849 font.setLanguage(to);
2853 d->requestSpellCheck(size());
2857 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2859 Language const * doc_language = bparams.language;
2860 FontList::const_iterator cit = d->fontlist_.begin();
2861 FontList::const_iterator end = d->fontlist_.end();
2863 for (; cit != end; ++cit)
2864 if (cit->font().language() != ignore_language &&
2865 cit->font().language() != latex_language &&
2866 cit->font().language() != doc_language)
2872 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2874 FontList::const_iterator cit = d->fontlist_.begin();
2875 FontList::const_iterator end = d->fontlist_.end();
2877 for (; cit != end; ++cit) {
2878 Language const * lang = cit->font().language();
2879 if (lang != ignore_language &&
2880 lang != latex_language)
2881 languages.insert(lang);
2886 docstring Paragraph::asString(int options) const
2888 return asString(0, size(), options);
2892 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2894 odocstringstream os;
2897 && options & AS_STR_LABEL
2898 && !d->params_.labelString().empty())
2899 os << d->params_.labelString() << ' ';
2901 for (pos_type i = beg; i < end; ++i) {
2902 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2904 char_type const c = d->text_[i];
2905 if (isPrintable(c) || c == '\t'
2906 || (c == '\n' && (options & AS_STR_NEWLINES)))
2908 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2909 getInset(i)->tocString(os);
2910 if (getInset(i)->asInsetMath())
2919 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2921 odocstringstream os;
2924 && options & AS_STR_LABEL
2925 && !d->params_.labelString().empty())
2926 os << d->params_.labelString() << ' ';
2928 for (pos_type i = beg; i < end; ++i) {
2929 char_type const c = d->text_[i];
2930 if (isPrintable(c) || c == '\t'
2931 || (c == '\n' && (options & AS_STR_NEWLINES)))
2933 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2934 getInset(i)->plaintext(os, runparams);
2942 void Paragraph::setInsetOwner(Inset const * inset)
2944 d->inset_owner_ = inset;
2948 int Paragraph::id() const
2954 void Paragraph::setId(int id)
2960 Layout const & Paragraph::layout() const
2966 void Paragraph::setLayout(Layout const & layout)
2968 d->layout_ = &layout;
2972 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2974 setLayout(tc.defaultLayout());
2978 void Paragraph::setPlainLayout(DocumentClass const & tc)
2980 setLayout(tc.plainLayout());
2984 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2986 if (usePlainLayout())
2987 setPlainLayout(tclass);
2989 setDefaultLayout(tclass);
2993 Inset const & Paragraph::inInset() const
2995 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2996 _("Memory problem"), _("Paragraph not properly initialized")));
2997 return *d->inset_owner_;
3001 ParagraphParameters & Paragraph::params()
3007 ParagraphParameters const & Paragraph::params() const
3013 bool Paragraph::isFreeSpacing() const
3015 if (d->layout_->free_spacing)
3017 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3021 bool Paragraph::allowEmpty() const
3023 if (d->layout_->keepempty)
3025 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3029 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3031 if (!Encodings::isArabicChar(c))
3034 char_type prev_char = ' ';
3035 char_type next_char = ' ';
3037 for (pos_type i = pos - 1; i >= 0; --i) {
3038 char_type const par_char = d->text_[i];
3039 if (!Encodings::isArabicComposeChar(par_char)) {
3040 prev_char = par_char;
3045 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3046 char_type const par_char = d->text_[i];
3047 if (!Encodings::isArabicComposeChar(par_char)) {
3048 next_char = par_char;
3053 if (Encodings::isArabicChar(next_char)) {
3054 if (Encodings::isArabicChar(prev_char) &&
3055 !Encodings::isArabicSpecialChar(prev_char))
3056 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3058 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3060 if (Encodings::isArabicChar(prev_char) &&
3061 !Encodings::isArabicSpecialChar(prev_char))
3062 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3064 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3069 int Paragraph::checkBiblio(Buffer const & buffer)
3072 // This is getting more and more a mess. ...We really should clean
3073 // up this bibitem issue for 1.6. See also bug 2743.
3075 // Add bibitem insets if necessary
3076 if (d->layout_->labeltype != LABEL_BIBLIO)
3079 bool hasbibitem = !d->insetlist_.empty()
3080 // Insist on it being in pos 0
3081 && d->text_[0] == META_INSET
3082 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3084 bool track_changes = buffer.params().trackChanges;
3089 // remove a bibitem in pos != 0
3090 // restore it later in pos 0 if necessary
3091 // (e.g. if a user inserts contents _before_ the item)
3092 // we're assuming there's only one of these, which there
3094 int erasedInsetPosition = -1;
3095 InsetList::iterator it = d->insetlist_.begin();
3096 InsetList::iterator end = d->insetlist_.end();
3097 for (; it != end; ++it)
3098 if (it->inset->lyxCode() == BIBITEM_CODE
3100 InsetCommand * olditem = it->inset->asInsetCommand();
3101 oldkey = olditem->getParam("key");
3102 oldlabel = olditem->getParam("label");
3103 erasedInsetPosition = it->pos;
3104 eraseChar(erasedInsetPosition, track_changes);
3108 // There was an InsetBibitem at the beginning, and we didn't
3109 // have to erase one.
3110 if (hasbibitem && erasedInsetPosition < 0)
3113 // There was an InsetBibitem at the beginning and we did have to
3114 // erase one. So we give its properties to the beginning inset.
3116 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3117 if (!oldkey.empty())
3118 inset->setParam("key", oldkey);
3119 inset->setParam("label", oldlabel);
3120 return -erasedInsetPosition;
3123 // There was no inset at the beginning, so we need to create one with
3124 // the key and label of the one we erased.
3125 InsetBibitem * inset =
3126 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3127 // restore values of previously deleted item in this par.
3128 if (!oldkey.empty())
3129 inset->setParam("key", oldkey);
3130 inset->setParam("label", oldlabel);
3131 insertInset(0, inset,
3132 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3138 void Paragraph::checkAuthors(AuthorList const & authorList)
3140 d->changes_.checkAuthors(authorList);
3144 bool Paragraph::isChanged(pos_type pos) const
3146 return lookupChange(pos).changed();
3150 bool Paragraph::isInserted(pos_type pos) const
3152 return lookupChange(pos).inserted();
3156 bool Paragraph::isDeleted(pos_type pos) const
3158 return lookupChange(pos).deleted();
3162 InsetList const & Paragraph::insetList() const
3164 return d->insetlist_;
3168 void Paragraph::setBuffer(Buffer & b)
3170 d->insetlist_.setBuffer(b);
3174 Inset * Paragraph::releaseInset(pos_type pos)
3176 Inset * inset = d->insetlist_.release(pos);
3177 /// does not honour change tracking!
3178 eraseChar(pos, false);
3183 Inset * Paragraph::getInset(pos_type pos)
3185 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3186 ? d->insetlist_.get(pos) : 0;
3190 Inset const * Paragraph::getInset(pos_type pos) const
3192 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3193 ? d->insetlist_.get(pos) : 0;
3197 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3198 pos_type & right, TextCase action)
3200 // process sequences of modified characters; in change
3201 // tracking mode, this approach results in much better
3202 // usability than changing case on a char-by-char basis
3205 bool const trackChanges = bparams.trackChanges;
3207 bool capitalize = true;
3209 for (; pos < right; ++pos) {
3210 char_type oldChar = d->text_[pos];
3211 char_type newChar = oldChar;
3213 // ignore insets and don't play with deleted text!
3214 if (oldChar != META_INSET && !isDeleted(pos)) {
3216 case text_lowercase:
3217 newChar = lowercase(oldChar);
3219 case text_capitalization:
3221 newChar = uppercase(oldChar);
3225 case text_uppercase:
3226 newChar = uppercase(oldChar);
3231 if (isWordSeparator(pos) || isDeleted(pos)) {
3232 // permit capitalization again
3236 if (oldChar != newChar) {
3238 if (pos != right - 1)
3240 // step behind the changing area
3244 int erasePos = pos - changes.size();
3245 for (size_t i = 0; i < changes.size(); i++) {
3246 insertChar(pos, changes[i],
3247 getFontSettings(bparams,
3250 if (!eraseChar(erasePos, trackChanges)) {
3253 ++right; // expand selection
3261 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3262 pos_type pos, bool del) const
3264 int const strsize = str.length();
3266 pos_type const parsize = d->text_.size();
3267 for (i = 0; pos + i < parsize; ++i) {
3270 if (cs && str[i] != d->text_[pos + i])
3272 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3274 if (!del && isDeleted(pos + i))
3281 // if necessary, check whether string matches word
3283 if (pos > 0 && !isWordSeparator(pos - 1))
3285 if (pos + strsize < parsize
3286 && !isWordSeparator(pos + strsize))
3294 char_type Paragraph::getChar(pos_type pos) const
3296 return d->text_[pos];
3300 pos_type Paragraph::size() const
3302 return d->text_.size();
3306 bool Paragraph::empty() const
3308 return d->text_.empty();
3312 bool Paragraph::isInset(pos_type pos) const
3314 return d->text_[pos] == META_INSET;
3318 bool Paragraph::isSeparator(pos_type pos) const
3320 //FIXME: Are we sure this can be the only separator?
3321 return d->text_[pos] == ' ';
3325 void Paragraph::deregisterWords()
3327 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3328 Private::LangWordsMap::const_iterator ite = d->words_.end();
3329 for (; itl != ite; ++itl) {
3330 WordList * wl = theWordList(itl->first);
3331 Private::Words::const_iterator it = (itl->second).begin();
3332 Private::Words::const_iterator et = (itl->second).end();
3333 for (; it != et; ++it)
3340 void Paragraph::locateWord(pos_type & from, pos_type & to,
3341 word_location const loc) const
3344 case WHOLE_WORD_STRICT:
3345 if (from == 0 || from == size()
3346 || isWordSeparator(from)
3347 || isWordSeparator(from - 1)) {
3351 // no break here, we go to the next
3354 // If we are already at the beginning of a word, do nothing
3355 if (!from || isWordSeparator(from - 1))
3357 // no break here, we go to the next
3360 // always move the cursor to the beginning of previous word
3361 while (from && !isWordSeparator(from - 1))
3365 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3368 // no need to move the 'from' cursor
3372 while (to < size() && !isWordSeparator(to))
3377 void Paragraph::collectWords()
3379 // This is the value that needs to be exposed in the preferences
3380 // to resolve bug #6760.
3381 static int minlength = 6;
3382 pos_type n = size();
3383 for (pos_type pos = 0; pos < n; ++pos) {
3384 if (isWordSeparator(pos))
3386 pos_type from = pos;
3387 locateWord(from, pos, WHOLE_WORD);
3388 if (pos - from >= minlength) {
3389 docstring word = asString(from, pos, AS_STR_NONE);
3390 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3391 if (cit == d->fontlist_.end())
3393 Language const * lang = cit->font().language();
3394 d->words_[*lang].insert(word);
3400 void Paragraph::registerWords()
3402 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3403 Private::LangWordsMap::const_iterator ite = d->words_.end();
3404 for (; itl != ite; ++itl) {
3405 WordList * wl = theWordList(itl->first);
3406 Private::Words::const_iterator it = (itl->second).begin();
3407 Private::Words::const_iterator et = (itl->second).end();
3408 for (; it != et; ++it)
3414 void Paragraph::updateWords()
3422 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3424 SkipPositionsIterator begin = skips.begin();
3425 SkipPositions::iterator end = skips.end();
3426 if (pos > 0 && begin < end) {
3428 if (end->last == pos - 1) {
3433 skips.insert(end, FontSpan(pos, pos));
3437 Language * Paragraph::Private::locateSpellRange(
3438 pos_type & from, pos_type & to,
3439 SkipPositions & skips) const
3441 // skip leading white space
3442 while (from < to && owner_->isWordSeparator(from))
3444 // don't check empty range
3447 // get current language
3448 Language * lang = getSpellLanguage(from);
3449 pos_type last = from;
3450 bool samelang = true;
3451 bool sameinset = true;
3452 while (last < to && samelang && sameinset) {
3453 // hop to end of word
3454 while (last < to && !owner_->isWordSeparator(last)) {
3455 if (owner_->getInset(last)) {
3456 appendSkipPosition(skips, last);
3457 } else if (owner_->isDeleted(last)) {
3458 appendSkipPosition(skips, last);
3462 // hop to next word while checking for insets
3463 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3464 if (Inset const * inset = owner_->getInset(last))
3465 sameinset = inset->isChar() && inset->isLetter();
3466 if (sameinset && owner_->isDeleted(last)) {
3467 appendSkipPosition(skips, last);
3472 if (sameinset && last < to) {
3473 // now check for language change
3474 samelang = lang == getSpellLanguage(last);
3477 // if language change detected backstep is needed
3485 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3488 const_cast<Language *>(owner_->getFontSettings(
3489 inset_owner_->buffer().params(), from).language());
3490 if (lang == inset_owner_->buffer().params().language
3491 && !lyxrc.spellchecker_alt_lang.empty()) {
3493 string const lang_variety =
3494 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3495 lang->setCode(lang_code);
3496 lang->setVariety(lang_variety);
3502 void Paragraph::requestSpellCheck(pos_type pos)
3504 d->requestSpellCheck(pos == -1 ? size() : pos);
3508 bool Paragraph::needsSpellCheck() const
3510 SpellChecker::ChangeNumber speller_change_number = 0;
3511 if (theSpellChecker())
3512 speller_change_number = theSpellChecker()->changeNumber();
3513 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3514 d->speller_state_.needsCompleteRefresh(speller_change_number);
3516 return d->needsSpellCheck();
3520 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3521 WordLangTuple & wl, docstring_list & suggestions,
3522 bool do_suggestion, bool check_learned) const
3524 SpellChecker::Result result = SpellChecker::WORD_OK;
3525 SpellChecker * speller = theSpellChecker();
3529 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3532 locateWord(from, to, WHOLE_WORD);
3533 if (from == to || from >= size())
3536 docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3537 Language * lang = d->getSpellLanguage(from);
3539 wl = WordLangTuple(word, lang);
3544 if (needsSpellCheck() || check_learned) {
3545 // Ignore words with digits
3546 // FIXME: make this customizable
3547 // (note that some checkers ignore words with digits by default)
3548 if (!hasDigit(word)) {
3549 bool const trailing_dot = to < size() && d->text_[to] == '.';
3550 result = speller->check(wl);
3551 if (SpellChecker::misspelled(result) && trailing_dot) {
3552 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3553 result = speller->check(wl);
3554 if (!SpellChecker::misspelled(result)) {
3555 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3557 from << ".." << to << "]");
3561 d->setMisspelled(from, to, result);
3563 result = d->speller_state_.getState(from);
3566 bool const misspelled_ = SpellChecker::misspelled(result) ;
3567 if (misspelled_ && do_suggestion)
3568 speller->suggest(wl, suggestions);
3569 else if (misspelled_)
3570 LYXERR(Debug::GUI, "misspelled word: \"" <<
3572 from << ".." << to << "]");
3574 suggestions.clear();
3580 void Paragraph::Private::markMisspelledWords(
3581 pos_type const & first, pos_type const & last,
3582 SpellChecker::Result result,
3583 docstring const & word,
3584 SkipPositions const & skips)
3586 if (!SpellChecker::misspelled(result)) {
3587 setMisspelled(first, last, SpellChecker::WORD_OK);
3591 SpellChecker * speller = theSpellChecker();
3592 // locate and enumerate the error positions
3593 int nerrors = speller->numMisspelledWords();
3595 SkipPositionsIterator it = skips.begin();
3596 SkipPositionsIterator et = skips.end();
3597 for (int index = 0; index < nerrors; ++index) {
3600 speller->misspelledWord(index, wstart, wlen);
3601 /// should not happen if speller supports range checks
3602 if (!wlen) continue;
3603 docstring const misspelled = word.substr(wstart, wlen);
3604 wstart += first + numskipped;
3605 if (snext < wstart) {
3606 /// mark the range of correct spelling
3607 numskipped += countSkips(it, et, wstart);
3608 setMisspelled(snext,
3609 wstart - 1, SpellChecker::WORD_OK);
3611 snext = wstart + wlen;
3612 numskipped += countSkips(it, et, snext);
3613 /// mark the range of misspelling
3614 setMisspelled(wstart, snext, result);
3615 LYXERR(Debug::GUI, "misspelled word: \"" <<
3616 misspelled << "\" [" <<
3617 wstart << ".." << (snext-1) << "]");
3620 if (snext <= last) {
3621 /// mark the range of correct spelling at end
3622 setMisspelled(snext, last, SpellChecker::WORD_OK);
3627 void Paragraph::spellCheck() const
3629 SpellChecker * speller = theSpellChecker();
3630 if (!speller || !size() ||!needsSpellCheck())
3634 d->rangeOfSpellCheck(start, endpos);
3635 if (speller->canCheckParagraph()) {
3636 // loop until we leave the range
3637 for (pos_type first = start; first < endpos; ) {
3638 pos_type last = endpos;
3639 Private::SkipPositions skips;
3640 Language * lang = d->locateSpellRange(first, last, skips);
3641 if (first >= endpos)
3643 // start the spell checker on the unit of meaning
3644 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3645 WordLangTuple wl = WordLangTuple(word, lang);
3646 SpellChecker::Result result = word.size() ?
3647 speller->check(wl) : SpellChecker::WORD_OK;
3648 d->markMisspelledWords(first, last, result, word, skips);
3652 static docstring_list suggestions;
3653 pos_type to = endpos;
3654 while (start < endpos) {
3656 spellCheck(start, to, wl, suggestions, false);
3660 d->readySpellCheck();
3664 bool Paragraph::isMisspelled(pos_type pos) const
3666 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3670 string Paragraph::magicLabel() const
3673 ss << "magicparlabel-" << id();