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"
28 #include "BufferEncodings.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"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.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;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
79 /////////////////////////////////////////////////////////////////////
83 /////////////////////////////////////////////////////////////////////
85 class SpellResultRange {
87 SpellResultRange(FontSpan range, SpellChecker::Result result)
88 : range_(range), result_(result)
91 FontSpan const & range() const { return range_; }
93 void range(FontSpan const & r) { range_ = r; }
95 SpellChecker::Result result() const { return result_; }
97 void result(SpellChecker::Result r) { result_ = r; }
99 bool inside(pos_type pos) const { return range_.inside(pos); }
101 bool covered(FontSpan const & r) const
103 // 1. first of new range inside current range or
104 // 2. last of new range inside current range or
105 // 3. first of current range inside new range or
106 // 4. last of current range inside new range
107 return range_.inside(r.first) || range_.inside(r.last) ||
108 r.inside(range_.first) || r.inside(range_.last);
111 void shift(pos_type pos, int offset)
113 if (range_.first > pos) {
114 range_.first += offset;
115 range_.last += offset;
116 } else if (range_.last >= pos) {
117 range_.last += offset;
122 SpellChecker::Result result_ ;
126 /////////////////////////////////////////////////////////////////////
130 /////////////////////////////////////////////////////////////////////
132 class SpellCheckerState {
136 needs_refresh_ = true;
137 current_change_number_ = 0;
140 void setRange(FontSpan const & fp, SpellChecker::Result state)
143 RangesIterator et = ranges_.end();
144 RangesIterator it = ranges_.begin();
145 for (; it != et; ++it) {
146 if (!it->covered(fp))
147 result.push_back(SpellResultRange(it->range(), it->result()));
148 else if (state == SpellChecker::WORD_OK) {
149 // trim or split the current misspelled range
150 // store misspelled ranges only
151 FontSpan range = it->range();
152 if (fp.first > range.first) {
153 // misspelled area in front of WORD_OK
154 range.last = fp.first - 1;
155 result.push_back(SpellResultRange(range, it->result()));
158 if (fp.last < range.last) {
159 // misspelled area after WORD_OK range
160 range.first = fp.last + 1;
161 result.push_back(SpellResultRange(range, it->result()));
166 if (state != SpellChecker::WORD_OK)
167 ranges_.push_back(SpellResultRange(fp, state));
170 void increasePosAfterPos(pos_type pos)
172 correctRangesAfterPos(pos, 1);
176 void decreasePosAfterPos(pos_type pos)
178 correctRangesAfterPos(pos, -1);
182 void refreshLast(pos_type pos)
184 if (pos < refresh_.last)
188 SpellChecker::Result getState(pos_type pos) const
190 SpellChecker::Result result = SpellChecker::WORD_OK;
191 RangesIterator et = ranges_.end();
192 RangesIterator it = ranges_.begin();
193 for (; it != et; ++it) {
194 if(it->inside(pos)) {
201 FontSpan const & getRange(pos_type pos) const
203 /// empty span to indicate mismatch
204 static FontSpan empty_;
205 RangesIterator et = ranges_.end();
206 RangesIterator it = ranges_.begin();
207 for (; it != et; ++it) {
208 if(it->inside(pos)) {
215 bool needsRefresh() const
217 return needs_refresh_;
220 SpellChecker::ChangeNumber currentChangeNumber() const
222 return current_change_number_;
225 void refreshRange(pos_type & first, pos_type & last) const
227 first = refresh_.first;
228 last = refresh_.last;
231 void needsRefresh(pos_type pos)
233 if (needs_refresh_ && pos != -1) {
234 if (pos < refresh_.first)
235 refresh_.first = pos;
236 if (pos > refresh_.last)
238 } else if (pos != -1) {
239 // init request check for neighbour positions too
240 refresh_.first = pos > 0 ? pos - 1 : 0;
241 // no need for special end of paragraph check
242 refresh_.last = pos + 1;
244 needs_refresh_ = pos != -1;
247 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
249 needs_refresh_ = true;
252 current_change_number_ = change_number;
255 typedef vector<SpellResultRange> Ranges;
256 typedef Ranges::const_iterator RangesIterator;
258 /// the area of the paragraph with pending spell check
261 /// spell state cache version number
262 SpellChecker::ChangeNumber current_change_number_;
265 void correctRangesAfterPos(pos_type pos, int offset)
267 RangesIterator et = ranges_.end();
268 Ranges::iterator it = ranges_.begin();
269 for (; it != et; ++it) {
270 it->shift(pos, offset);
276 /////////////////////////////////////////////////////////////////////
278 // Paragraph::Private
280 /////////////////////////////////////////////////////////////////////
282 class Paragraph::Private
286 Private(Paragraph * owner, Layout const & layout);
287 /// "Copy constructor"
288 Private(Private const &, Paragraph * owner);
289 /// Copy constructor from \p beg to \p end
290 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
293 void insertChar(pos_type pos, char_type c, Change const & change);
295 /// Output the surrogate pair formed by \p c and \p next to \p os.
296 /// \return the number of characters written.
297 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
298 OutputParams const &);
300 /// Output a space in appropriate formatting (or a surrogate pair
301 /// if the next character is a combining character).
302 /// \return whether a surrogate pair was output.
303 bool simpleTeXBlanks(OutputParams const &,
306 unsigned int & column,
308 Layout const & style);
310 /// Output consecutive unicode chars, belonging to the same script as
311 /// specified by the latex macro \p ltx, to \p os starting from \p i.
312 /// \return the number of characters written.
313 int writeScriptChars(otexstream & os, docstring const & ltx,
314 Change const &, Encoding const &, pos_type & i);
316 /// This could go to ParagraphParameters if we want to.
317 int startTeXParParams(BufferParams const &, otexstream &,
318 OutputParams const &) const;
320 /// This could go to ParagraphParameters if we want to.
321 bool endTeXParParams(BufferParams const &, otexstream &,
322 OutputParams const &) const;
325 void latexInset(BufferParams const &,
330 Font const & outerfont,
332 Change & running_change,
333 Layout const & style,
335 unsigned int & column);
338 void latexSpecialChar(
340 BufferParams const & bparams,
341 OutputParams const & runparams,
342 Font const & running_font,
343 Change const & running_change,
344 Layout const & style,
347 unsigned int & column);
354 unsigned int & column);
360 unsigned int & column);
362 bool latexSpecialTypewriter(
366 unsigned int & column);
368 bool latexSpecialPhrase(
372 unsigned int & column,
373 OutputParams const & runparams);
376 void validate(LaTeXFeatures & features) const;
378 /// Checks if the paragraph contains only text and no inset or font change.
379 bool onlyText(Buffer const & buf, Font const & outerfont,
380 pos_type initial) const;
382 /// match a string against a particular point in the paragraph
383 bool isTextAt(string const & str, pos_type pos) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD);
445 owner_->locateWord(last, endpos, WHOLE_WORD);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 int skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<Language, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
514 struct special_phrase {
520 special_phrase const special_phrases[] = {
521 { "LyX", from_ascii("\\LyX{}"), false },
522 { "TeX", from_ascii("\\TeX{}"), true },
523 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
524 { "LaTeX", from_ascii("\\LaTeX{}"), true },
527 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
532 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
533 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
539 // Initialization of the counter for the paragraph id's,
541 // FIXME: There should be a more intelligent way to generate and use the
542 // paragraph ids per buffer instead a global static counter for all InsetText
543 // in the running program.
544 static int paragraph_id = -1;
546 Paragraph::Private::Private(Private const & p, Paragraph * owner)
547 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
548 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
549 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
552 id_ = ++paragraph_id;
553 requestSpellCheck(p.text_.size());
557 Paragraph::Private::Private(Private const & p, Paragraph * owner,
558 pos_type beg, pos_type end)
559 : owner_(owner), inset_owner_(p.inset_owner_),
560 params_(p.params_), changes_(p.changes_),
561 insetlist_(p.insetlist_, beg, end),
562 begin_of_body_(p.begin_of_body_), words_(p.words_),
565 id_ = ++paragraph_id;
566 if (beg >= pos_type(p.text_.size()))
568 text_ = p.text_.substr(beg, end - beg);
570 FontList::const_iterator fcit = fontlist_.begin();
571 FontList::const_iterator fend = fontlist_.end();
572 for (; fcit != fend; ++fcit) {
573 if (fcit->pos() < beg)
575 if (fcit->pos() >= end) {
576 // Add last entry in the fontlist_.
577 fontlist_.set(text_.size() - 1, fcit->font());
580 // Add a new entry in the fontlist_.
581 fontlist_.set(fcit->pos() - beg, fcit->font());
583 requestSpellCheck(p.text_.size());
587 void Paragraph::addChangesToToc(DocIterator const & cdit,
588 Buffer const & buf, bool output_active) const
590 d->changes_.addToToc(cdit, buf, output_active);
594 bool Paragraph::isDeleted(pos_type start, pos_type end) const
596 LASSERT(start >= 0 && start <= size(), return false);
597 LASSERT(end > start && end <= size() + 1, return false);
599 return d->changes_.isDeleted(start, end);
603 bool Paragraph::isChanged(pos_type start, pos_type end) const
605 LASSERT(start >= 0 && start <= size(), return false);
606 LASSERT(end > start && end <= size() + 1, return false);
608 return d->changes_.isChanged(start, end);
612 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
614 // keep the logic here in sync with the logic of eraseChars()
618 Change const change = d->changes_.lookup(size());
619 return change.inserted() && change.currentAuthor();
623 void Paragraph::setChange(Change const & change)
625 // beware of the imaginary end-of-par character!
626 d->changes_.set(change, 0, size() + 1);
629 * Propagate the change recursively - but not in case of DELETED!
631 * Imagine that your co-author makes changes in an existing inset. He
632 * sends your document to you and you come to the conclusion that the
633 * inset should go completely. If you erase it, LyX must not delete all
634 * text within the inset. Otherwise, the change tracked insertions of
635 * your co-author get lost and there is no way to restore them later.
637 * Conclusion: An inset's content should remain untouched if you delete it
640 if (!change.deleted()) {
641 for (pos_type pos = 0; pos < size(); ++pos) {
642 if (Inset * inset = getInset(pos))
643 inset->setChange(change);
649 void Paragraph::setChange(pos_type pos, Change const & change)
651 LASSERT(pos >= 0 && pos <= size(), return);
652 d->changes_.set(change, pos);
654 // see comment in setChange(Change const &) above
655 if (!change.deleted() && pos < size())
656 if (Inset * inset = getInset(pos))
657 inset->setChange(change);
661 Change const & Paragraph::lookupChange(pos_type pos) const
663 LBUFERR(pos >= 0 && pos <= size());
664 return d->changes_.lookup(pos);
668 void Paragraph::acceptChanges(pos_type start, pos_type end)
670 LASSERT(start >= 0 && start <= size(), return);
671 LASSERT(end > start && end <= size() + 1, return);
673 for (pos_type pos = start; pos < end; ++pos) {
674 switch (lookupChange(pos).type) {
675 case Change::UNCHANGED:
676 // accept changes in nested inset
677 if (Inset * inset = getInset(pos))
678 inset->acceptChanges();
681 case Change::INSERTED:
682 d->changes_.set(Change(Change::UNCHANGED), pos);
683 // also accept changes in nested inset
684 if (Inset * inset = getInset(pos))
685 inset->acceptChanges();
688 case Change::DELETED:
689 // Suppress access to non-existent
690 // "end-of-paragraph char"
692 eraseChar(pos, false);
703 void Paragraph::rejectChanges(pos_type start, pos_type end)
705 LASSERT(start >= 0 && start <= size(), return);
706 LASSERT(end > start && end <= size() + 1, return);
708 for (pos_type pos = start; pos < end; ++pos) {
709 switch (lookupChange(pos).type) {
710 case Change::UNCHANGED:
711 // reject changes in nested inset
712 if (Inset * inset = getInset(pos))
713 inset->rejectChanges();
716 case Change::INSERTED:
717 // Suppress access to non-existent
718 // "end-of-paragraph char"
720 eraseChar(pos, false);
726 case Change::DELETED:
727 d->changes_.set(Change(Change::UNCHANGED), pos);
729 // Do NOT reject changes within a deleted inset!
730 // There may be insertions of a co-author inside of it!
738 void Paragraph::Private::insertChar(pos_type pos, char_type c,
739 Change const & change)
741 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
744 changes_.insert(change, pos);
746 // This is actually very common when parsing buffers (and
747 // maybe inserting ascii text)
748 if (pos == pos_type(text_.size())) {
749 // when appending characters, no need to update tables
751 // but we want spell checking
752 requestSpellCheck(pos);
756 text_.insert(text_.begin() + pos, c);
758 // Update the font table.
759 fontlist_.increasePosAfterPos(pos);
762 insetlist_.increasePosAfterPos(pos);
764 // Update list of misspelled positions
765 speller_state_.increasePosAfterPos(pos);
769 bool Paragraph::insertInset(pos_type pos, Inset * inset,
770 Font const & font, Change const & change)
772 LASSERT(inset, return false);
773 LASSERT(pos >= 0 && pos <= size(), return false);
775 // Paragraph::insertInset() can be used in cut/copy/paste operation where
776 // d->inset_owner_ is not set yet.
777 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
780 d->insertChar(pos, META_INSET, change);
781 LASSERT(d->text_[pos] == META_INSET, return false);
783 // Add a new entry in the insetlist_.
784 d->insetlist_.insert(inset, pos);
786 // Some insets require run of spell checker
787 requestSpellCheck(pos);
793 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
795 LASSERT(pos >= 0 && pos <= size(), return false);
797 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
800 Change change = d->changes_.lookup(pos);
802 // set the character to DELETED if
803 // a) it was previously unchanged or
804 // b) it was inserted by a co-author
806 if (!change.changed() ||
807 (change.inserted() && !change.currentAuthor())) {
808 setChange(pos, Change(Change::DELETED));
809 // request run of spell checker
810 requestSpellCheck(pos);
814 if (change.deleted())
818 // Don't physically access the imaginary end-of-paragraph character.
819 // eraseChar() can only mark it as DELETED. A physical deletion of
820 // end-of-par must be handled externally.
826 d->changes_.erase(pos);
828 // if it is an inset, delete the inset entry
829 if (d->text_[pos] == META_INSET)
830 d->insetlist_.erase(pos);
832 d->text_.erase(d->text_.begin() + pos);
834 // Update the fontlist_
835 d->fontlist_.erase(pos);
837 // Update the insetlist_
838 d->insetlist_.decreasePosAfterPos(pos);
840 // Update list of misspelled positions
841 d->speller_state_.decreasePosAfterPos(pos);
842 d->speller_state_.refreshLast(size());
848 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
850 LASSERT(start >= 0 && start <= size(), return 0);
851 LASSERT(end >= start && end <= size() + 1, return 0);
854 for (pos_type count = end - start; count; --count) {
855 if (!eraseChar(i, trackChanges))
862 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
863 char_type next, OutputParams const & runparams)
865 // Writing next here may circumvent a possible font change between
866 // c and next. Since next is only output if it forms a surrogate pair
867 // with c we can ignore this:
868 // A font change inside a surrogate pair does not make sense and is
869 // hopefully impossible to input.
870 // FIXME: change tracking
871 // Is this correct WRT change tracking?
872 Encoding const & encoding = *(runparams.encoding);
873 docstring latex1 = encoding.latexChar(next).first;
874 if (runparams.inIPA) {
875 string const tipashortcut = Encodings::TIPAShortcut(next);
876 if (!tipashortcut.empty()) {
877 latex1 = from_ascii(tipashortcut);
880 docstring const latex2 = encoding.latexChar(c).first;
881 if (docstring(1, next) == latex1) {
882 // the encoding supports the combination
883 os << latex2 << latex1;
884 return latex1.length() + latex2.length();
885 } else if (runparams.local_font &&
886 runparams.local_font->language()->lang() == "polutonikogreek") {
887 // polutonikogreek only works without the brackets
888 os << latex1 << latex2;
889 return latex1.length() + latex2.length();
891 os << latex1 << '{' << latex2 << '}';
892 return latex1.length() + latex2.length() + 2;
896 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
899 unsigned int & column,
901 Layout const & style)
903 if (style.pass_thru || runparams.pass_thru)
906 if (i + 1 < int(text_.size())) {
907 char_type next = text_[i + 1];
908 if (Encodings::isCombiningChar(next)) {
909 // This space has an accent, so we must always output it.
910 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
915 if (runparams.linelen > 0
916 && column > runparams.linelen
918 && text_[i - 1] != ' '
919 && (i + 1 < int(text_.size()))
920 // same in FreeSpacing mode
921 && !owner_->isFreeSpacing()
922 // In typewriter mode, we want to avoid
923 // ! . ? : at the end of a line
924 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
925 && (text_[i - 1] == '.'
926 || text_[i - 1] == '?'
927 || text_[i - 1] == ':'
928 || text_[i - 1] == '!'))) {
930 os.texrow().start(owner_->id(), i + 1);
932 } else if (style.free_spacing) {
941 int Paragraph::Private::writeScriptChars(otexstream & os,
942 docstring const & ltx,
943 Change const & runningChange,
944 Encoding const & encoding,
947 // FIXME: modifying i here is not very nice...
949 // We only arrive here when a proper language for character text_[i] has
950 // not been specified (i.e., it could not be translated in the current
951 // latex encoding) or its latex translation has been forced, and it
952 // belongs to a known script.
953 // Parameter ltx contains the latex translation of text_[i] as specified
954 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
955 // The latex macro name "textXXX" specifies the script to which text_[i]
956 // belongs and we use it in order to check whether characters from the
957 // same script immediately follow, such that we can collect them in a
958 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
959 // for the first char but only "<spec>" for all subsequent chars.
960 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
961 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
962 string script = to_ascii(ltx.substr(1, brace1 - 1));
965 bool closing_brace = true;
966 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
967 // Correct encoding is being used, so we can avoid \textgreek.
970 closing_brace = false;
972 os << ltx.substr(pos, length);
973 int size = text_.size();
974 while (i + 1 < size) {
975 char_type const next = text_[i + 1];
976 // Stop here if next character belongs to another script
977 // or there is a change in change tracking status.
978 if (!Encodings::isKnownScriptChar(next, script) ||
979 runningChange != owner_->lookupChange(i + 1))
983 FontList::const_iterator cit = fontlist_.begin();
984 FontList::const_iterator end = fontlist_.end();
985 for (; cit != end; ++cit) {
986 if (cit->pos() >= i && !found) {
987 prev_font = cit->font();
990 if (cit->pos() >= i + 1)
993 // Stop here if there is a font attribute or encoding change.
994 if (found && cit != end && prev_font != cit->font())
996 docstring const latex = encoding.latexChar(next).first;
997 docstring::size_type const b1 =
998 latex.find_first_of(from_ascii("{"));
999 docstring::size_type const b2 =
1000 latex.find_last_of(from_ascii("}"));
1001 int const len = b2 - b1 - 1;
1002 os << latex.substr(b1 + 1, len);
1006 if (closing_brace) {
1014 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1016 pos_type const len = str.length();
1018 // is the paragraph large enough?
1019 if (pos + len > int(text_.size()))
1022 // does the wanted text start at point?
1023 for (string::size_type i = 0; i < str.length(); ++i) {
1024 // Caution: direct comparison of characters works only
1025 // because str is pure ASCII.
1026 if (str[i] != text_[pos + i])
1030 return fontlist_.hasChangeInRange(pos, len);
1034 void Paragraph::Private::latexInset(BufferParams const & bparams,
1036 OutputParams & runparams,
1037 Font & running_font,
1039 Font const & outerfont,
1041 Change & running_change,
1042 Layout const & style,
1044 unsigned int & column)
1046 Inset * inset = owner_->getInset(i);
1049 if (style.pass_thru) {
1050 odocstringstream ods;
1051 inset->plaintext(ods, runparams);
1056 // FIXME: move this to InsetNewline::latex
1057 if (inset->lyxCode() == NEWLINE_CODE) {
1058 // newlines are handled differently here than
1059 // the default in simpleTeXSpecialChars().
1060 if (!style.newline_allowed) {
1064 column += running_font.latexWriteEndChanges(
1065 os, bparams, runparams,
1066 basefont, basefont);
1070 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1073 basefont = owner_->getLayoutFont(bparams, outerfont);
1074 running_font = basefont;
1076 if (runparams.moving_arg)
1080 os.texrow().start(owner_->id(), i + 1);
1084 if (owner_->isDeleted(i)) {
1085 if( ++runparams.inDeletedInset == 1)
1086 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1089 if (inset->canTrackChanges()) {
1090 column += Changes::latexMarkChange(os, bparams, running_change,
1091 Change(Change::UNCHANGED), runparams);
1092 running_change = Change(Change::UNCHANGED);
1096 odocstream::pos_type const len = os.os().tellp();
1098 if (inset->forceLTR()
1099 && !runparams.use_polyglossia
1100 && running_font.isRightToLeft()
1101 // ERT is an exception, it should be output with no
1102 // decorations at all
1103 && inset->lyxCode() != ERT_CODE) {
1104 if (running_font.language()->lang() == "farsi")
1111 // FIXME: Bug: we can have an empty font change here!
1112 // if there has just been a font change, we are going to close it
1113 // right now, which means stupid latex code like \textsf{}. AFAIK,
1114 // this does not harm dvi output. A minor bug, thus (JMarc)
1116 // Some insets cannot be inside a font change command.
1117 // However, even such insets *can* be placed in \L or \R
1118 // or their equivalents (for RTL language switches), so we don't
1119 // close the language in those cases.
1120 // ArabTeX, though, cannot handle this special behavior, it seems.
1121 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1122 || running_font.language()->lang() == "arabic_arabtex";
1123 if (open_font && !inset->inheritFont()) {
1124 bool closeLanguage = arabtex
1125 || basefont.isRightToLeft() == running_font.isRightToLeft();
1126 unsigned int count = running_font.latexWriteEndChanges(os,
1127 bparams, runparams, basefont, basefont, closeLanguage);
1129 // if any font properties were closed, update the running_font,
1130 // making sure, however, to leave the language as it was
1132 // FIXME: probably a better way to keep track of the old
1133 // language, than copying the entire font?
1134 Font const copy_font(running_font);
1135 basefont = owner_->getLayoutFont(bparams, outerfont);
1136 running_font = basefont;
1138 running_font.setLanguage(copy_font.language());
1139 // leave font open if language is still open
1140 open_font = (running_font.language() == basefont.language());
1142 runparams.local_font = &basefont;
1146 int prev_rows = os.texrow().rows();
1149 runparams.lastid = id_;
1150 runparams.lastpos = i;
1151 inset->latex(os, runparams);
1152 } catch (EncodingException & e) {
1153 // add location information and throw again.
1160 if (running_font.language()->lang() == "farsi")
1166 if (os.texrow().rows() > prev_rows) {
1167 os.texrow().start(owner_->id(), i + 1);
1170 column += (unsigned int)(os.os().tellp() - len);
1173 if (owner_->isDeleted(i))
1174 --runparams.inDeletedInset;
1178 void Paragraph::Private::latexSpecialChar(otexstream & os,
1179 BufferParams const & bparams,
1180 OutputParams const & runparams,
1181 Font const & running_font,
1182 Change const & running_change,
1183 Layout const & style,
1186 unsigned int & column)
1188 // With polyglossia, brackets and stuff need not be reversed
1189 // in RTL scripts (see bug #8251)
1190 char_type const c = (runparams.use_polyglossia) ?
1191 owner_->getUChar(bparams, i) : text_[i];
1193 if (style.pass_thru || runparams.pass_thru) {
1195 Encoding const * const enc = runparams.encoding;
1196 if (enc && !enc->encodable(c))
1197 throw EncodingException(c);
1203 // TIPA uses its own T3 encoding
1204 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1206 // If T1 font encoding is used, use the special
1207 // characters it provides.
1208 // NOTE: some languages reset the font encoding
1210 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1211 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1214 // \tt font needs special treatment
1215 if (!runparams.inIPA
1216 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1217 && latexSpecialTypewriter(c, os, i, column))
1220 // Otherwise, we use what LaTeX provides us.
1223 os << "\\textbackslash{}";
1227 os << "\\textless{}";
1231 os << "\\textgreater{}";
1235 os << "\\textbar{}";
1242 os << "\\char`\\\"{}";
1247 case '%': case '#': case '{':
1255 os << "\\textasciitilde{}";
1260 os << "\\textasciicircum{}";
1267 // avoid being mistaken for optional arguments
1275 // Blanks are printed before font switching.
1276 // Sure? I am not! (try nice-latex)
1277 // I am sure it's correct. LyX might be smarter
1278 // in the future, but for now, nothing wrong is
1284 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1290 Encoding const & encoding = *(runparams.encoding);
1291 char_type next = '\0';
1292 if (i + 1 < int(text_.size())) {
1293 next = text_[i + 1];
1294 if (Encodings::isCombiningChar(next)) {
1295 column += latexSurrogatePair(os, c, next, runparams) - 1;
1301 pair<docstring, bool> latex = encoding.latexChar(c);
1302 docstring nextlatex;
1303 bool nexttipas = false;
1304 string nexttipashortcut;
1305 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1306 nextlatex = encoding.latexChar(next).first;
1307 if (runparams.inIPA) {
1308 nexttipashortcut = Encodings::TIPAShortcut(next);
1309 nexttipas = !nexttipashortcut.empty();
1313 if (runparams.inIPA) {
1314 string const tipashortcut = Encodings::TIPAShortcut(c);
1315 if (!tipashortcut.empty()) {
1316 latex.first = from_ascii(tipashortcut);
1317 latex.second = false;
1321 if (Encodings::isKnownScriptChar(c, script)
1322 && prefixIs(latex.first, from_ascii("\\" + script)))
1323 column += writeScriptChars(os, latex.first,
1324 running_change, encoding, i) - 1;
1325 else if (latex.second
1326 && ((!prefixIs(nextlatex, '\\')
1327 && !prefixIs(nextlatex, '{')
1328 && !prefixIs(nextlatex, '}'))
1330 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1332 // Prevent eating of a following
1333 // space or command corruption by
1334 // following characters
1335 if (next == ' ' || next == '\0') {
1336 column += latex.first.length() + 1;
1337 os << latex.first << "{}";
1339 column += latex.first.length();
1340 os << latex.first << " ";
1343 column += latex.first.length() - 1;
1351 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1352 pos_type i, unsigned int & column)
1358 // In T1 encoding, these characters exist
1359 // but we should avoid ligatures
1360 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1362 os << "\\textcompwordmark{}";
1369 // soul.sty breaks with \char`\"
1370 os << "\\textquotedbl{}";
1379 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1380 pos_type /*i*/, unsigned int & column)
1390 os << "\\textvertline{}";
1399 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1400 pos_type i, unsigned int & column)
1404 // within \ttfamily, "--" is merged to "-" (no endash)
1405 // so we avoid this rather irritating ligature
1406 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1413 // everything else has to be checked separately
1414 // (depending on the encoding)
1422 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1423 /// do not apply the macro transformation.
1424 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1425 unsigned int & column, OutputParams const & runparams)
1427 // FIXME: if we have "LaTeX" with a font
1428 // change in the middle (before the 'T', then
1429 // the "TeX" part is still special cased.
1430 // Really we should only operate this on
1431 // "words" for some definition of word
1433 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1434 if (!isTextAt(special_phrases[pnr].phrase, i)
1435 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1437 if (runparams.moving_arg)
1439 os << special_phrases[pnr].macro;
1440 i += special_phrases[pnr].phrase.length() - 1;
1441 column += special_phrases[pnr].macro.length() - 1;
1448 void Paragraph::Private::validate(LaTeXFeatures & features) const
1450 if (layout_->inpreamble && inset_owner_) {
1451 bool const is_command = layout_->latextype == LATEX_COMMAND;
1452 Buffer const & buf = inset_owner_->buffer();
1453 BufferParams const & bp = buf.params();
1456 // Using a string stream here circumvents the encoding
1457 // switching machinery of odocstream. Therefore the
1458 // output is wrong if this paragraph contains content
1459 // that needs to switch encoding.
1460 odocstringstream ods;
1461 otexstream os(ods, texrow);
1463 os << '\\' << from_ascii(layout_->latexname());
1464 // we have to provide all the optional arguments here, even though
1465 // the last one is the only one we care about.
1466 // Separate handling of optional argument inset.
1467 if (!layout_->latexargs().empty()) {
1468 OutputParams rp = features.runparams();
1469 rp.local_font = &owner_->getFirstFontSettings(bp);
1470 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1472 os << from_ascii(layout_->latexparam());
1474 docstring::size_type const length = ods.str().length();
1475 // this will output "{" at the beginning, but not at the end
1476 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1477 if (ods.str().length() > length) {
1480 if (!layout_->postcommandargs().empty()) {
1481 OutputParams rp = features.runparams();
1482 rp.local_font = &owner_->getFirstFontSettings(bp);
1483 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1486 string const snippet = to_utf8(ods.str());
1487 features.addPreambleSnippet(snippet);
1491 if (features.runparams().flavor == OutputParams::HTML
1492 && layout_->htmltitle()) {
1493 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1496 // check the params.
1497 if (!params_.spacing().isDefault())
1498 features.require("setspace");
1501 features.useLayout(layout_->name());
1504 fontlist_.validate(features);
1506 // then the indentation
1507 if (!params_.leftIndent().zero())
1508 features.require("ParagraphLeftIndent");
1511 InsetList::const_iterator icit = insetlist_.begin();
1512 InsetList::const_iterator iend = insetlist_.end();
1513 for (; icit != iend; ++icit) {
1515 icit->inset->validate(features);
1516 if (layout_->needprotect &&
1517 icit->inset->lyxCode() == FOOT_CODE)
1518 features.require("NeedLyXFootnoteCode");
1522 // then the contents
1523 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1524 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1525 if (!special_phrases[pnr].builtin
1526 && isTextAt(special_phrases[pnr].phrase, i)) {
1527 features.require(special_phrases[pnr].phrase);
1531 BufferEncodings::validate(text_[i], features);
1535 /////////////////////////////////////////////////////////////////////
1539 /////////////////////////////////////////////////////////////////////
1542 Layout const emptyParagraphLayout;
1545 Paragraph::Paragraph()
1546 : d(new Paragraph::Private(this, emptyParagraphLayout))
1553 Paragraph::Paragraph(Paragraph const & par)
1554 : itemdepth(par.itemdepth),
1555 d(new Paragraph::Private(*par.d, this))
1561 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1562 : itemdepth(par.itemdepth),
1563 d(new Paragraph::Private(*par.d, this, beg, end))
1569 Paragraph & Paragraph::operator=(Paragraph const & par)
1571 // needed as we will destroy the private part before copying it
1573 itemdepth = par.itemdepth;
1577 d = new Private(*par.d, this);
1584 Paragraph::~Paragraph()
1593 // this shall be called just before every "os << ..." action.
1594 void flushString(ostream & os, docstring & s)
1603 void Paragraph::write(ostream & os, BufferParams const & bparams,
1604 depth_type & dth) const
1606 // The beginning or end of a deeper (i.e. nested) area?
1607 if (dth != d->params_.depth()) {
1608 if (d->params_.depth() > dth) {
1609 while (d->params_.depth() > dth) {
1610 os << "\n\\begin_deeper";
1614 while (d->params_.depth() < dth) {
1615 os << "\n\\end_deeper";
1621 // First write the layout
1622 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1624 d->params_.write(os);
1626 Font font1(inherit_font, bparams.language);
1628 Change running_change = Change(Change::UNCHANGED);
1630 // this string is used as a buffer to avoid repetitive calls
1631 // to to_utf8(), which turn out to be expensive (JMarc)
1632 docstring write_buffer;
1635 for (pos_type i = 0; i <= size(); ++i) {
1637 Change const change = lookupChange(i);
1638 if (change != running_change)
1639 flushString(os, write_buffer);
1640 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1641 running_change = change;
1646 // Write font changes
1647 Font font2 = getFontSettings(bparams, i);
1648 if (font2 != font1) {
1649 flushString(os, write_buffer);
1650 font2.lyxWriteChanges(font1, os);
1655 char_type const c = d->text_[i];
1658 if (Inset const * inset = getInset(i)) {
1659 flushString(os, write_buffer);
1660 if (inset->directWrite()) {
1661 // international char, let it write
1662 // code directly so it's shorter in
1668 os << "\\begin_inset ";
1670 os << "\n\\end_inset\n\n";
1676 flushString(os, write_buffer);
1677 os << "\n\\backslash\n";
1681 flushString(os, write_buffer);
1682 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1689 if ((column > 70 && c == ' ')
1691 flushString(os, write_buffer);
1695 // this check is to amend a bug. LyX sometimes
1696 // inserts '\0' this could cause problems.
1698 write_buffer.push_back(c);
1700 LYXERR0("NUL char in structure.");
1706 flushString(os, write_buffer);
1707 os << "\n\\end_layout\n";
1711 void Paragraph::validate(LaTeXFeatures & features) const
1713 d->validate(features);
1717 void Paragraph::insert(pos_type start, docstring const & str,
1718 Font const & font, Change const & change)
1720 for (size_t i = 0, n = str.size(); i != n ; ++i)
1721 insertChar(start + i, str[i], font, change);
1725 void Paragraph::appendChar(char_type c, Font const & font,
1726 Change const & change)
1729 d->changes_.insert(change, d->text_.size());
1730 // when appending characters, no need to update tables
1731 d->text_.push_back(c);
1732 setFont(d->text_.size() - 1, font);
1733 d->requestSpellCheck(d->text_.size() - 1);
1737 void Paragraph::appendString(docstring const & s, Font const & font,
1738 Change const & change)
1740 pos_type end = s.size();
1741 size_t oldsize = d->text_.size();
1742 size_t newsize = oldsize + end;
1743 size_t capacity = d->text_.capacity();
1744 if (newsize >= capacity)
1745 d->text_.reserve(max(capacity + 100, newsize));
1747 // when appending characters, no need to update tables
1750 // FIXME: Optimize this!
1751 for (size_t i = oldsize; i != newsize; ++i) {
1753 d->changes_.insert(change, i);
1754 d->requestSpellCheck(i);
1756 d->fontlist_.set(oldsize, font);
1757 d->fontlist_.set(newsize - 1, font);
1761 void Paragraph::insertChar(pos_type pos, char_type c,
1764 d->insertChar(pos, c, Change(trackChanges ?
1765 Change::INSERTED : Change::UNCHANGED));
1769 void Paragraph::insertChar(pos_type pos, char_type c,
1770 Font const & font, bool trackChanges)
1772 d->insertChar(pos, c, Change(trackChanges ?
1773 Change::INSERTED : Change::UNCHANGED));
1778 void Paragraph::insertChar(pos_type pos, char_type c,
1779 Font const & font, Change const & change)
1781 d->insertChar(pos, c, change);
1786 void Paragraph::resetFonts(Font const & font)
1788 d->fontlist_.clear();
1789 d->fontlist_.set(0, font);
1790 d->fontlist_.set(d->text_.size() - 1, font);
1793 // Gets uninstantiated font setting at position.
1794 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1798 LYXERR0("pos: " << pos << " size: " << size());
1802 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1803 if (cit != d->fontlist_.end())
1806 if (pos == size() && !empty())
1807 return getFontSettings(bparams, pos - 1);
1809 // Optimisation: avoid a full font instantiation if there is no
1810 // language change from previous call.
1811 static Font previous_font;
1812 static Language const * previous_lang = 0;
1813 Language const * lang = getParLanguage(bparams);
1814 if (lang != previous_lang) {
1815 previous_lang = lang;
1816 previous_font = Font(inherit_font, lang);
1818 return previous_font;
1822 FontSpan Paragraph::fontSpan(pos_type pos) const
1824 LBUFERR(pos < size());
1827 FontList::const_iterator cit = d->fontlist_.begin();
1828 FontList::const_iterator end = d->fontlist_.end();
1829 for (; cit != end; ++cit) {
1830 if (cit->pos() >= pos) {
1831 if (pos >= beginOfBody())
1832 return FontSpan(max(start, beginOfBody()),
1835 return FontSpan(start,
1836 min(beginOfBody() - 1,
1839 start = cit->pos() + 1;
1842 // This should not happen, but if so, we take no chances.
1843 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1844 LASSERT(false, return FontSpan(pos, pos));
1848 // Gets uninstantiated font setting at position 0
1849 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1851 if (!empty() && !d->fontlist_.empty())
1852 return d->fontlist_.begin()->font();
1854 // Optimisation: avoid a full font instantiation if there is no
1855 // language change from previous call.
1856 static Font previous_font;
1857 static Language const * previous_lang = 0;
1858 if (bparams.language != previous_lang) {
1859 previous_lang = bparams.language;
1860 previous_font = Font(inherit_font, bparams.language);
1863 return previous_font;
1867 // Gets the fully instantiated font at a given position in a paragraph
1868 // This is basically the same function as Text::GetFont() in text2.cpp.
1869 // The difference is that this one is used for generating the LaTeX file,
1870 // and thus cosmetic "improvements" are disallowed: This has to deliver
1871 // the true picture of the buffer. (Asger)
1872 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1873 Font const & outerfont) const
1877 Font font = getFontSettings(bparams, pos);
1879 pos_type const body_pos = beginOfBody();
1880 FontInfo & fi = font.fontInfo();
1882 fi.realize(d->layout_->labelfont);
1884 fi.realize(d->layout_->font);
1886 fi.realize(outerfont.fontInfo());
1887 fi.realize(bparams.getFont().fontInfo());
1893 Font const Paragraph::getLabelFont
1894 (BufferParams const & bparams, Font const & outerfont) const
1896 FontInfo tmpfont = d->layout_->labelfont;
1897 tmpfont.realize(outerfont.fontInfo());
1898 tmpfont.realize(bparams.getFont().fontInfo());
1899 return Font(tmpfont, getParLanguage(bparams));
1903 Font const Paragraph::getLayoutFont
1904 (BufferParams const & bparams, Font const & outerfont) const
1906 FontInfo tmpfont = d->layout_->font;
1907 tmpfont.realize(outerfont.fontInfo());
1908 tmpfont.realize(bparams.getFont().fontInfo());
1909 return Font(tmpfont, getParLanguage(bparams));
1913 /// Returns the height of the highest font in range
1914 FontSize Paragraph::highestFontInRange
1915 (pos_type startpos, pos_type endpos, FontSize def_size) const
1917 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1921 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1923 char_type c = d->text_[pos];
1924 if (!lyxrc.rtl_support || !getFontSettings(bparams, pos).isRightToLeft())
1927 // FIXME: The arabic special casing is due to the difference of arabic
1928 // round brackets input introduced in r18599. Check if this should be
1929 // unified with Hebrew or at least if all bracket types should be
1930 // handled the same (file format change in either case).
1931 string const & lang = getFontSettings(bparams, pos).language()->lang();
1932 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1937 uc = arabic ? c : ')';
1940 uc = arabic ? c : '(';
1966 void Paragraph::setFont(pos_type pos, Font const & font)
1968 LASSERT(pos <= size(), return);
1970 // First, reduce font against layout/label font
1971 // Update: The setCharFont() routine in text2.cpp already
1972 // reduces font, so we don't need to do that here. (Asger)
1974 d->fontlist_.set(pos, font);
1978 void Paragraph::makeSameLayout(Paragraph const & par)
1980 d->layout_ = par.d->layout_;
1981 d->params_ = par.d->params_;
1985 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1987 if (isFreeSpacing())
1993 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1994 if (eraseChar(pos, trackChanges))
2000 return count > 0 || pos > 0;
2004 bool Paragraph::hasSameLayout(Paragraph const & par) const
2006 return par.d->layout_ == d->layout_
2007 && d->params_.sameLayout(par.d->params_);
2011 depth_type Paragraph::getDepth() const
2013 return d->params_.depth();
2017 depth_type Paragraph::getMaxDepthAfter() const
2019 if (d->layout_->isEnvironment())
2020 return d->params_.depth() + 1;
2022 return d->params_.depth();
2026 char Paragraph::getAlign() const
2028 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2029 return d->layout_->align;
2031 return d->params_.align();
2035 docstring const & Paragraph::labelString() const
2037 return d->params_.labelString();
2041 // the next two functions are for the manual labels
2042 docstring const Paragraph::getLabelWidthString() const
2044 if (d->layout_->margintype == MARGIN_MANUAL
2045 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2046 return d->params_.labelWidthString();
2048 return _("Senseless with this layout!");
2052 void Paragraph::setLabelWidthString(docstring const & s)
2054 d->params_.labelWidthString(s);
2058 docstring Paragraph::expandLabel(Layout const & layout,
2059 BufferParams const & bparams) const
2061 return expandParagraphLabel(layout, bparams, true);
2065 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2066 BufferParams const & bparams) const
2068 return expandParagraphLabel(layout, bparams, false);
2072 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2073 BufferParams const & bparams, bool process_appendix) const
2075 DocumentClass const & tclass = bparams.documentClass();
2076 string const & lang = getParLanguage(bparams)->code();
2077 bool const in_appendix = process_appendix && d->params_.appendix();
2078 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2080 if (fmt.empty() && !layout.counter.empty())
2081 return tclass.counters().theCounter(layout.counter, lang);
2083 // handle 'inherited level parts' in 'fmt',
2084 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2085 size_t const i = fmt.find('@', 0);
2086 if (i != docstring::npos) {
2087 size_t const j = fmt.find('@', i + 1);
2088 if (j != docstring::npos) {
2089 docstring parent(fmt, i + 1, j - i - 1);
2090 docstring label = from_ascii("??");
2091 if (tclass.hasLayout(parent))
2092 docstring label = expandParagraphLabel(tclass[parent], bparams,
2094 fmt = docstring(fmt, 0, i) + label
2095 + docstring(fmt, j + 1, docstring::npos);
2099 return tclass.counters().counterLabel(fmt, lang);
2103 void Paragraph::applyLayout(Layout const & new_layout)
2105 d->layout_ = &new_layout;
2106 LyXAlignment const oldAlign = d->params_.align();
2108 if (!(oldAlign & d->layout_->alignpossible)) {
2109 frontend::Alert::warning(_("Alignment not permitted"),
2110 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2111 d->params_.align(LYX_ALIGN_LAYOUT);
2116 pos_type Paragraph::beginOfBody() const
2118 return d->begin_of_body_;
2122 void Paragraph::setBeginOfBody()
2124 if (d->layout_->labeltype != LABEL_MANUAL) {
2125 d->begin_of_body_ = 0;
2129 // Unroll the first two cycles of the loop
2130 // and remember the previous character to
2131 // remove unnecessary getChar() calls
2133 pos_type end = size();
2134 if (i < end && !isNewline(i)) {
2136 char_type previous_char = 0;
2139 previous_char = d->text_[i];
2140 if (!isNewline(i)) {
2142 while (i < end && previous_char != ' ') {
2147 previous_char = temp;
2153 d->begin_of_body_ = i;
2157 bool Paragraph::allowParagraphCustomization() const
2159 return inInset().allowParagraphCustomization();
2163 bool Paragraph::usePlainLayout() const
2165 return inInset().usePlainLayout();
2169 bool Paragraph::isPassThru() const
2171 return inInset().isPassThru() || d->layout_->pass_thru;
2176 // paragraphs inside floats need different alignment tags to avoid
2179 bool noTrivlistCentering(InsetCode code)
2181 return code == FLOAT_CODE
2182 || code == WRAP_CODE
2183 || code == CELL_CODE;
2187 string correction(string const & orig)
2189 if (orig == "flushleft")
2190 return "raggedright";
2191 if (orig == "flushright")
2192 return "raggedleft";
2193 if (orig == "center")
2199 string const corrected_env(string const & suffix, string const & env,
2200 InsetCode code, bool const lastpar)
2202 string output = suffix + "{";
2203 if (noTrivlistCentering(code)) {
2205 // the last paragraph in non-trivlist-aligned
2206 // context is special (to avoid unwanted whitespace)
2207 if (suffix == "\\begin")
2208 return "\\" + correction(env) + "{}";
2211 output += correction(env);
2215 if (suffix == "\\begin")
2221 void adjust_column(string const & str, int & column)
2223 if (!contains(str, "\n"))
2224 column += str.size();
2227 column = rsplit(str, tmp, '\n').size();
2234 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2235 otexstream & os, OutputParams const & runparams) const
2239 if (params_.noindent() && !layout_->pass_thru) {
2240 os << "\\noindent ";
2244 LyXAlignment const curAlign = params_.align();
2246 if (curAlign == layout_->align)
2250 case LYX_ALIGN_NONE:
2251 case LYX_ALIGN_BLOCK:
2252 case LYX_ALIGN_LAYOUT:
2253 case LYX_ALIGN_SPECIAL:
2254 case LYX_ALIGN_DECIMAL:
2256 case LYX_ALIGN_LEFT:
2257 case LYX_ALIGN_RIGHT:
2258 case LYX_ALIGN_CENTER:
2259 if (runparams.moving_arg) {
2266 string const begin_tag = "\\begin";
2267 InsetCode code = ownerCode();
2268 bool const lastpar = runparams.isLastPar;
2271 case LYX_ALIGN_NONE:
2272 case LYX_ALIGN_BLOCK:
2273 case LYX_ALIGN_LAYOUT:
2274 case LYX_ALIGN_SPECIAL:
2275 case LYX_ALIGN_DECIMAL:
2277 case LYX_ALIGN_LEFT: {
2279 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2280 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2282 output = corrected_env(begin_tag, "flushright", code, lastpar);
2283 os << from_ascii(output);
2284 adjust_column(output, column);
2286 } case LYX_ALIGN_RIGHT: {
2288 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2289 output = corrected_env(begin_tag, "flushright", code, lastpar);
2291 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2292 os << from_ascii(output);
2293 adjust_column(output, column);
2295 } case LYX_ALIGN_CENTER: {
2297 output = corrected_env(begin_tag, "center", code, lastpar);
2298 os << from_ascii(output);
2299 adjust_column(output, column);
2308 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2309 otexstream & os, OutputParams const & runparams) const
2311 LyXAlignment const curAlign = params_.align();
2313 if (curAlign == layout_->align)
2317 case LYX_ALIGN_NONE:
2318 case LYX_ALIGN_BLOCK:
2319 case LYX_ALIGN_LAYOUT:
2320 case LYX_ALIGN_SPECIAL:
2321 case LYX_ALIGN_DECIMAL:
2323 case LYX_ALIGN_LEFT:
2324 case LYX_ALIGN_RIGHT:
2325 case LYX_ALIGN_CENTER:
2326 if (runparams.moving_arg)
2332 string const end_tag = "\n\\par\\end";
2333 InsetCode code = ownerCode();
2334 bool const lastpar = runparams.isLastPar;
2337 case LYX_ALIGN_NONE:
2338 case LYX_ALIGN_BLOCK:
2339 case LYX_ALIGN_LAYOUT:
2340 case LYX_ALIGN_SPECIAL:
2341 case LYX_ALIGN_DECIMAL:
2343 case LYX_ALIGN_LEFT: {
2344 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2345 output = corrected_env(end_tag, "flushleft", code, lastpar);
2347 output = corrected_env(end_tag, "flushright", code, lastpar);
2348 os << from_ascii(output);
2350 } case LYX_ALIGN_RIGHT: {
2351 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2352 output = corrected_env(end_tag, "flushright", code, lastpar);
2354 output = corrected_env(end_tag, "flushleft", code, lastpar);
2355 os << from_ascii(output);
2357 } case LYX_ALIGN_CENTER: {
2358 output = corrected_env(end_tag, "center", code, lastpar);
2359 os << from_ascii(output);
2364 return !output.empty() || lastpar;
2368 // This one spits out the text of the paragraph
2369 void Paragraph::latex(BufferParams const & bparams,
2370 Font const & outerfont,
2372 OutputParams const & runparams,
2373 int start_pos, int end_pos, bool force) const
2375 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2377 // FIXME This check should not be needed. Perhaps issue an
2378 // error if it triggers.
2379 Layout const & style = inInset().forcePlainLayout() ?
2380 bparams.documentClass().plainLayout() : *d->layout_;
2382 if (!force && style.inpreamble)
2385 bool const allowcust = allowParagraphCustomization();
2387 // Current base font for all inherited font changes, without any
2388 // change caused by an individual character, except for the language:
2389 // It is set to the language of the first character.
2390 // As long as we are in the label, this font is the base font of the
2391 // label. Before the first body character it is set to the base font
2395 // Maybe we have to create a optional argument.
2396 pos_type body_pos = beginOfBody();
2397 unsigned int column = 0;
2400 // the optional argument is kept in curly brackets in
2401 // case it contains a ']'
2402 // This is not strictly needed, but if this is changed it
2403 // would be a file format change, and tex2lyx would need
2404 // to be adjusted, since it unconditionally removes the
2405 // braces when it parses \item.
2408 basefont = getLabelFont(bparams, outerfont);
2410 basefont = getLayoutFont(bparams, outerfont);
2413 // Which font is currently active?
2414 Font running_font(basefont);
2415 // Do we have an open font change?
2416 bool open_font = false;
2418 Change runningChange = Change(Change::UNCHANGED);
2420 Encoding const * const prev_encoding = runparams.encoding;
2422 os.texrow().start(id(), 0);
2424 // if the paragraph is empty, the loop will not be entered at all
2426 if (style.isCommand()) {
2430 if (!style.leftdelim().empty()) {
2431 os << style.leftdelim();
2432 column += style.leftdelim().size();
2435 column += d->startTeXParParams(bparams, os, runparams);
2438 for (pos_type i = 0; i < size(); ++i) {
2439 // First char in paragraph or after label?
2440 if (i == body_pos) {
2443 column += running_font.latexWriteEndChanges(
2444 os, bparams, runparams,
2445 basefont, basefont);
2448 basefont = getLayoutFont(bparams, outerfont);
2449 running_font = basefont;
2451 column += Changes::latexMarkChange(os, bparams,
2452 runningChange, Change(Change::UNCHANGED),
2454 runningChange = Change(Change::UNCHANGED);
2459 if (style.isCommand()) {
2464 if (!style.leftdelim().empty()) {
2465 os << style.leftdelim();
2466 column += style.leftdelim().size();
2470 column += d->startTeXParParams(bparams, os,
2474 Change const & change = runparams.inDeletedInset
2475 ? runparams.changeOfDeletedInset : lookupChange(i);
2477 if (bparams.outputChanges && runningChange != change) {
2479 column += running_font.latexWriteEndChanges(
2480 os, bparams, runparams, basefont, basefont);
2483 basefont = getLayoutFont(bparams, outerfont);
2484 running_font = basefont;
2486 column += Changes::latexMarkChange(os, bparams, runningChange,
2488 runningChange = change;
2491 // do not output text which is marked deleted
2492 // if change tracking output is disabled
2493 if (!bparams.outputChanges && change.deleted()) {
2499 // Fully instantiated font
2500 Font const font = getFont(bparams, i, outerfont);
2502 Font const last_font = running_font;
2504 // Do we need to close the previous font?
2506 (font != running_font ||
2507 font.language() != running_font.language()))
2509 column += running_font.latexWriteEndChanges(
2510 os, bparams, runparams, basefont,
2511 (i == body_pos-1) ? basefont : font);
2512 running_font = basefont;
2516 string const running_lang = runparams.use_polyglossia ?
2517 running_font.language()->polyglossia() : running_font.language()->babel();
2518 // close babel's font environment before opening CJK.
2519 string const lang_end_command = runparams.use_polyglossia ?
2520 "\\end{$$lang}" : lyxrc.language_command_end;
2521 if (!running_lang.empty() &&
2522 font.language()->encoding()->package() == Encoding::CJK) {
2523 string end_tag = subst(lang_end_command,
2526 os << from_ascii(end_tag);
2527 column += end_tag.length();
2530 // Switch file encoding if necessary (and allowed)
2531 if (!runparams.pass_thru && !style.pass_thru &&
2532 runparams.encoding->package() != Encoding::none &&
2533 font.language()->encoding()->package() != Encoding::none) {
2534 pair<bool, int> const enc_switch =
2535 switchEncoding(os.os(), bparams, runparams,
2536 *(font.language()->encoding()));
2537 if (enc_switch.first) {
2538 column += enc_switch.second;
2539 runparams.encoding = font.language()->encoding();
2543 char_type const c = d->text_[i];
2545 // Do we need to change font?
2546 if ((font != running_font ||
2547 font.language() != running_font.language()) &&
2550 odocstringstream ods;
2551 column += font.latexWriteStartChanges(ods, bparams,
2552 runparams, basefont,
2554 running_font = font;
2556 docstring fontchange = ods.str();
2557 // check whether the fontchange ends with a \\textcolor
2558 // modifier and the text starts with a space (bug 4473)
2559 docstring const last_modifier = rsplit(fontchange, '\\');
2560 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2561 os << fontchange << from_ascii("{}");
2562 // check if the fontchange ends with a trailing blank
2563 // (like "\small " (see bug 3382)
2564 else if (suffixIs(fontchange, ' ') && c == ' ')
2565 os << fontchange.substr(0, fontchange.size() - 1)
2566 << from_ascii("{}");
2571 // FIXME: think about end_pos implementation...
2572 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2573 // FIXME: integrate this case in latexSpecialChar
2574 // Do not print the separation of the optional argument
2575 // if style.pass_thru is false. This works because
2576 // latexSpecialChar ignores spaces if
2577 // style.pass_thru is false.
2578 if (i != body_pos - 1) {
2579 if (d->simpleTeXBlanks(runparams, os,
2580 i, column, font, style)) {
2581 // A surrogate pair was output. We
2582 // must not call latexSpecialChar
2583 // in this iteration, since it would output
2584 // the combining character again.
2591 OutputParams rp = runparams;
2592 rp.free_spacing = style.free_spacing;
2593 rp.local_font = &font;
2594 rp.intitle = style.intitle;
2596 // Two major modes: LaTeX or plain
2597 // Handle here those cases common to both modes
2598 // and then split to handle the two modes separately.
2599 if (c == META_INSET) {
2600 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2601 d->latexInset(bparams, os, rp, running_font,
2602 basefont, outerfont, open_font,
2603 runningChange, style, i, column);
2606 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2608 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2609 style, i, end_pos, column);
2610 } catch (EncodingException & e) {
2611 if (runparams.dryrun) {
2612 os << "<" << _("LyX Warning: ")
2613 << _("uncodable character") << " '";
2617 // add location information and throw again.
2626 // Set the encoding to that returned from latexSpecialChar (see
2627 // comment for encoding member in OutputParams.h)
2628 runparams.encoding = rp.encoding;
2631 // If we have an open font definition, we have to close it
2633 #ifdef FIXED_LANGUAGE_END_DETECTION
2635 running_font.latexWriteEndChanges(os, bparams,
2636 runparams, basefont,
2637 next_->getFont(bparams, 0, outerfont));
2639 running_font.latexWriteEndChanges(os, bparams,
2640 runparams, basefont, basefont);
2643 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2644 //FIXME: there as we start another \selectlanguage with the next paragraph if
2645 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2646 running_font.latexWriteEndChanges(os, bparams, runparams,
2647 basefont, basefont);
2651 column += Changes::latexMarkChange(os, bparams, runningChange,
2652 Change(Change::UNCHANGED), runparams);
2654 // Needed if there is an optional argument but no contents.
2655 if (body_pos > 0 && body_pos == size()) {
2659 if (!style.rightdelim().empty()) {
2660 os << style.rightdelim();
2661 column += style.rightdelim().size();
2664 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2665 && runparams.encoding != prev_encoding) {
2666 runparams.encoding = prev_encoding;
2667 if (!runparams.isFullUnicode())
2668 os << setEncoding(prev_encoding->iconvName());
2671 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2675 bool Paragraph::emptyTag() const
2677 for (pos_type i = 0; i < size(); ++i) {
2678 if (Inset const * inset = getInset(i)) {
2679 InsetCode lyx_code = inset->lyxCode();
2680 // FIXME testing like that is wrong. What is
2682 if (lyx_code != TOC_CODE &&
2683 lyx_code != INCLUDE_CODE &&
2684 lyx_code != GRAPHICS_CODE &&
2685 lyx_code != ERT_CODE &&
2686 lyx_code != LISTINGS_CODE &&
2687 lyx_code != FLOAT_CODE &&
2688 lyx_code != TABULAR_CODE) {
2692 char_type c = d->text_[i];
2693 if (c != ' ' && c != '\t')
2701 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2704 for (pos_type i = 0; i < size(); ++i) {
2705 if (Inset const * inset = getInset(i)) {
2706 InsetCode lyx_code = inset->lyxCode();
2707 if (lyx_code == LABEL_CODE) {
2708 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2709 docstring const & id = il->getParam("name");
2710 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2718 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2722 for (i = 0; i < size(); ++i) {
2723 if (Inset const * inset = getInset(i)) {
2724 inset->docbook(os, runparams);
2726 char_type c = d->text_[i];
2729 os << sgml::escapeChar(c);
2736 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2740 for (i = 0; i < size(); ++i) {
2741 if (Inset const * inset = getInset(i)) {
2742 inset->xhtml(xs, runparams);
2744 char_type c = d->text_[i];
2754 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2757 pos_type size = text_.size();
2758 for (pos_type i = initial; i < size; ++i) {
2759 Font font = owner_->getFont(buf.params(), i, outerfont);
2760 if (text_[i] == META_INSET)
2762 if (i != initial && font != font_old)
2771 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2773 OutputParams const & runparams,
2774 Font const & outerfont,
2775 pos_type initial) const
2777 bool emph_flag = false;
2779 Layout const & style = *d->layout_;
2781 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2783 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2786 // parsing main loop
2787 for (pos_type i = initial; i < size(); ++i) {
2788 Font font = getFont(buf.params(), i, outerfont);
2790 // handle <emphasis> tag
2791 if (font_old.emph() != font.fontInfo().emph()) {
2792 if (font.fontInfo().emph() == FONT_ON) {
2795 } else if (i != initial) {
2796 os << "</emphasis>";
2801 if (Inset const * inset = getInset(i)) {
2802 inset->docbook(os, runparams);
2804 char_type c = d->text_[i];
2806 if (style.pass_thru)
2809 os << sgml::escapeChar(c);
2811 font_old = font.fontInfo();
2815 os << "</emphasis>";
2818 if (style.free_spacing)
2820 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2826 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2827 vector<html::EndFontTag> & tagsToClose,
2828 bool & flag, FontState curstate, html::FontTypes type)
2830 if (curstate == FONT_ON) {
2831 tagsToOpen.push_back(html::FontTag(type));
2834 tagsToClose.push_back(html::EndFontTag(type));
2841 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2843 OutputParams const & runparams,
2844 Font const & outerfont,
2845 pos_type initial) const
2849 // track whether we have opened these tags
2850 bool emph_flag = false;
2851 bool bold_flag = false;
2852 bool noun_flag = false;
2853 bool ubar_flag = false;
2854 bool dbar_flag = false;
2855 bool sout_flag = false;
2856 bool wave_flag = false;
2858 bool shap_flag = false;
2860 bool faml_flag = false;
2862 bool size_flag = false;
2864 Layout const & style = *d->layout_;
2866 xs.startParagraph(allowEmpty());
2869 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2871 FontShape curr_fs = INHERIT_SHAPE;
2872 FontFamily curr_fam = INHERIT_FAMILY;
2873 FontSize curr_size = FONT_SIZE_INHERIT;
2875 string const default_family =
2876 buf.masterBuffer()->params().fonts_default_family;
2878 vector<html::FontTag> tagsToOpen;
2879 vector<html::EndFontTag> tagsToClose;
2881 // parsing main loop
2882 for (pos_type i = initial; i < size(); ++i) {
2883 // let's not show deleted material in the output
2887 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2890 FontState curstate = font.fontInfo().emph();
2891 if (font_old.emph() != curstate)
2892 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2895 curstate = font.fontInfo().noun();
2896 if (font_old.noun() != curstate)
2897 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2900 curstate = font.fontInfo().underbar();
2901 if (font_old.underbar() != curstate)
2902 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2905 curstate = font.fontInfo().strikeout();
2906 if (font_old.strikeout() != curstate)
2907 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2910 curstate = font.fontInfo().uuline();
2911 if (font_old.uuline() != curstate)
2912 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2915 curstate = font.fontInfo().uwave();
2916 if (font_old.uwave() != curstate)
2917 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2920 // a little hackish, but allows us to reuse what we have.
2921 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2922 if (font_old.series() != font.fontInfo().series())
2923 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2926 curr_fs = font.fontInfo().shape();
2927 FontShape old_fs = font_old.shape();
2928 if (old_fs != curr_fs) {
2932 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2935 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2937 case SMALLCAPS_SHAPE:
2938 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2944 // the other tags are for internal use
2952 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2956 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2959 case SMALLCAPS_SHAPE:
2960 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2967 // the other tags are for internal use
2974 curr_fam = font.fontInfo().family();
2975 FontFamily old_fam = font_old.family();
2976 if (old_fam != curr_fam) {
2980 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2983 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2985 case TYPEWRITER_FAMILY:
2986 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2988 case INHERIT_FAMILY:
2991 // the other tags are for internal use
2999 // we will treat a "default" font family as roman, since we have
3000 // no other idea what to do.
3001 if (default_family != "rmdefault" && default_family != "default") {
3002 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3007 if (default_family != "sfdefault") {
3008 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3012 case TYPEWRITER_FAMILY:
3013 if (default_family != "ttdefault") {
3014 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3018 case INHERIT_FAMILY:
3021 // the other tags are for internal use
3028 curr_size = font.fontInfo().size();
3029 FontSize old_size = font_old.size();
3030 if (old_size != curr_size) {
3033 case FONT_SIZE_TINY:
3034 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3036 case FONT_SIZE_SCRIPT:
3037 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3039 case FONT_SIZE_FOOTNOTE:
3040 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3042 case FONT_SIZE_SMALL:
3043 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3045 case FONT_SIZE_LARGE:
3046 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3048 case FONT_SIZE_LARGER:
3049 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3051 case FONT_SIZE_LARGEST:
3052 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3054 case FONT_SIZE_HUGE:
3055 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3057 case FONT_SIZE_HUGER:
3058 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3060 case FONT_SIZE_INCREASE:
3061 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3063 case FONT_SIZE_DECREASE:
3064 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3066 case FONT_SIZE_INHERIT:
3067 case FONT_SIZE_NORMAL:
3070 // the other tags are for internal use
3076 switch (curr_size) {
3077 case FONT_SIZE_TINY:
3078 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3081 case FONT_SIZE_SCRIPT:
3082 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3085 case FONT_SIZE_FOOTNOTE:
3086 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3089 case FONT_SIZE_SMALL:
3090 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3093 case FONT_SIZE_LARGE:
3094 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3097 case FONT_SIZE_LARGER:
3098 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3101 case FONT_SIZE_LARGEST:
3102 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3105 case FONT_SIZE_HUGE:
3106 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3109 case FONT_SIZE_HUGER:
3110 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3113 case FONT_SIZE_INCREASE:
3114 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3117 case FONT_SIZE_DECREASE:
3118 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3121 case FONT_SIZE_NORMAL:
3122 case FONT_SIZE_INHERIT:
3125 // the other tags are for internal use
3132 // Other such tags? What about the other text ranges?
3134 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3135 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3136 for (; cit != cen; ++cit)
3139 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3140 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3141 for (; sit != sen; ++sit)
3144 tagsToClose.clear();
3147 Inset const * inset = getInset(i);
3149 if (!runparams.for_toc || inset->isInToc()) {
3150 OutputParams np = runparams;
3151 np.local_font = &font;
3152 if (!inset->getLayout().htmlisblock())
3153 np.html_in_par = true;
3154 retval += inset->xhtml(xs, np);
3157 char_type c = getUChar(buf.masterBuffer()->params(), i);
3159 if (style.pass_thru || runparams.pass_thru)
3161 else if (c == '-') {
3164 if (j < size() && d->text_[j] == '-') {
3166 if (j < size() && d->text_[j] == '-') {
3167 str += from_ascii("—");
3170 str += from_ascii("–");
3176 // We don't want to escape the entities. Note that
3177 // it is safe to do this, since str can otherwise
3178 // only be "-". E.g., it can't be "<".
3179 xs << XHTMLStream::ESCAPE_NONE << str;
3183 font_old = font.fontInfo();
3192 bool Paragraph::isHfill(pos_type pos) const
3194 Inset const * inset = getInset(pos);
3195 return inset && (inset->lyxCode() == SPACE_CODE &&
3196 inset->isStretchableSpace());
3200 bool Paragraph::isNewline(pos_type pos) const
3202 Inset const * inset = getInset(pos);
3203 return inset && inset->lyxCode() == NEWLINE_CODE;
3207 bool Paragraph::isLineSeparator(pos_type pos) const
3209 char_type const c = d->text_[pos];
3210 if (isLineSeparatorChar(c))
3212 Inset const * inset = getInset(pos);
3213 return inset && inset->isLineSeparator();
3217 bool Paragraph::isWordSeparator(pos_type pos) const
3221 if (Inset const * inset = getInset(pos))
3222 return !inset->isLetter();
3223 // if we have a hard hyphen (no en- or emdash) or apostrophe
3224 // we pass this to the spell checker
3225 // FIXME: this method is subject to change, visit
3226 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3227 // to get an impression how complex this is.
3228 if (isHardHyphenOrApostrophe(pos))
3230 char_type const c = d->text_[pos];
3231 // We want to pass the escape chars to the spellchecker
3232 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3233 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3237 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3239 pos_type const psize = size();
3242 char_type const c = d->text_[pos];
3243 if (c != '-' && c != '\'')
3245 int nextpos = pos + 1;
3246 int prevpos = pos > 0 ? pos - 1 : 0;
3247 if ((nextpos == psize || isSpace(nextpos))
3248 && (pos == 0 || isSpace(prevpos)))
3251 || ((nextpos == psize || d->text_[nextpos] != '-')
3252 && (pos == 0 || d->text_[prevpos] != '-'));
3256 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
3259 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
3263 bool Paragraph::isChar(pos_type pos) const
3265 if (Inset const * inset = getInset(pos))
3266 return inset->isChar();
3267 char_type const c = d->text_[pos];
3268 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3272 bool Paragraph::isSpace(pos_type pos) const
3274 if (Inset const * inset = getInset(pos))
3275 return inset->isSpace();
3276 char_type const c = d->text_[pos];
3277 return lyx::isSpace(c);
3282 Paragraph::getParLanguage(BufferParams const & bparams) const
3285 return getFirstFontSettings(bparams).language();
3286 // FIXME: we should check the prev par as well (Lgb)
3287 return bparams.language;
3291 bool Paragraph::isRTL(BufferParams const & bparams) const
3293 return lyxrc.rtl_support
3294 && getParLanguage(bparams)->rightToLeft()
3295 && !inInset().getLayout().forceLTR();
3299 void Paragraph::changeLanguage(BufferParams const & bparams,
3300 Language const * from, Language const * to)
3302 // change language including dummy font change at the end
3303 for (pos_type i = 0; i <= size(); ++i) {
3304 Font font = getFontSettings(bparams, i);
3305 if (font.language() == from) {
3306 font.setLanguage(to);
3308 d->requestSpellCheck(i);
3314 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3316 Language const * doc_language = bparams.language;
3317 FontList::const_iterator cit = d->fontlist_.begin();
3318 FontList::const_iterator end = d->fontlist_.end();
3320 for (; cit != end; ++cit)
3321 if (cit->font().language() != ignore_language &&
3322 cit->font().language() != latex_language &&
3323 cit->font().language() != doc_language)
3329 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3331 FontList::const_iterator cit = d->fontlist_.begin();
3332 FontList::const_iterator end = d->fontlist_.end();
3334 for (; cit != end; ++cit) {
3335 Language const * lang = cit->font().language();
3336 if (lang != ignore_language &&
3337 lang != latex_language)
3338 languages.insert(lang);
3343 docstring Paragraph::asString(int options) const
3345 return asString(0, size(), options);
3349 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
3351 odocstringstream os;
3354 && options & AS_STR_LABEL
3355 && !d->params_.labelString().empty())
3356 os << d->params_.labelString() << ' ';
3358 for (pos_type i = beg; i < end; ++i) {
3359 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3361 char_type const c = d->text_[i];
3362 if (isPrintable(c) || c == '\t'
3363 || (c == '\n' && (options & AS_STR_NEWLINES)))
3365 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3366 getInset(i)->toString(os);
3367 if (getInset(i)->asInsetMath())
3376 void Paragraph::forToc(docstring & os, size_t maxlen) const
3378 if (!d->params_.labelString().empty())
3379 os += d->params_.labelString() + ' ';
3380 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3383 char_type const c = d->text_[i];
3386 else if (c == '\t' || c == '\n')
3388 else if (c == META_INSET)
3389 getInset(i)->forToc(os, maxlen);
3394 docstring Paragraph::stringify(pos_type beg, pos_type end, int options,
3395 OutputParams const & runparams) const
3397 odocstringstream os;
3400 && options & AS_STR_LABEL
3401 && !d->params_.labelString().empty())
3402 os << d->params_.labelString() << ' ';
3404 OutputParams op = runparams;
3405 op.for_search = true;
3407 for (pos_type i = beg; i < end; ++i) {
3408 char_type const c = d->text_[i];
3409 if (isPrintable(c) || c == '\t'
3410 || (c == '\n' && (options & AS_STR_NEWLINES)))
3412 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3413 getInset(i)->plaintext(os, op);
3421 void Paragraph::setInsetOwner(Inset const * inset)
3423 d->inset_owner_ = inset;
3427 int Paragraph::id() const
3433 void Paragraph::setId(int id)
3439 Layout const & Paragraph::layout() const
3445 void Paragraph::setLayout(Layout const & layout)
3447 d->layout_ = &layout;
3451 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3453 setLayout(tc.defaultLayout());
3457 void Paragraph::setPlainLayout(DocumentClass const & tc)
3459 setLayout(tc.plainLayout());
3463 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3465 if (usePlainLayout())
3466 setPlainLayout(tclass);
3468 setDefaultLayout(tclass);
3472 Inset const & Paragraph::inInset() const
3474 LBUFERR(d->inset_owner_);
3475 return *d->inset_owner_;
3479 ParagraphParameters & Paragraph::params()
3485 ParagraphParameters const & Paragraph::params() const
3491 bool Paragraph::isFreeSpacing() const
3493 if (d->layout_->free_spacing)
3495 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3499 bool Paragraph::allowEmpty() const
3501 if (d->layout_->keepempty)
3503 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3507 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3509 if (!Encodings::isArabicChar(c))
3512 char_type prev_char = ' ';
3513 char_type next_char = ' ';
3515 for (pos_type i = pos - 1; i >= 0; --i) {
3516 char_type const par_char = d->text_[i];
3517 if (!Encodings::isArabicComposeChar(par_char)) {
3518 prev_char = par_char;
3523 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3524 char_type const par_char = d->text_[i];
3525 if (!Encodings::isArabicComposeChar(par_char)) {
3526 next_char = par_char;
3531 if (Encodings::isArabicChar(next_char)) {
3532 if (Encodings::isArabicChar(prev_char) &&
3533 !Encodings::isArabicSpecialChar(prev_char))
3534 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3536 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3538 if (Encodings::isArabicChar(prev_char) &&
3539 !Encodings::isArabicSpecialChar(prev_char))
3540 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3542 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3547 bool Paragraph::brokenBiblio() const
3549 // there is a problem if there is no bibitem at position 0 or
3550 // if there is another bibitem in the paragraph.
3551 return d->layout_->labeltype == LABEL_BIBLIO
3552 && (d->insetlist_.find(BIBITEM_CODE) != 0
3553 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3557 int Paragraph::fixBiblio(Buffer const & buffer)
3559 // FIXME: What about the case where paragraph is not BIBLIO
3560 // but there is an InsetBibitem?
3561 // FIXME: when there was already an inset at 0, the return value is 1,
3562 // which does not tell whether another inset has been remove; the
3563 // cursor cannot be correctly updated.
3565 if (d->layout_->labeltype != LABEL_BIBLIO)
3568 bool const track_changes = buffer.params().trackChanges;
3569 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3570 bool const hasbibitem0 = bibitem_pos == 0;
3573 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3574 // There was an InsetBibitem at pos 0, and no other one => OK
3575 if (bibitem_pos == -1)
3577 // there is a bibitem at the 0 position, but since
3578 // there is a second one, we copy the second on the
3579 // first. We're assuming there are at most two of
3580 // these, which there should be.
3581 // FIXME: why does it make sense to do that rather
3582 // than keep the first? (JMarc)
3583 Inset * inset = d->insetlist_.release(bibitem_pos);
3584 eraseChar(bibitem_pos, track_changes);
3585 d->insetlist_.begin()->inset = inset;
3586 return -bibitem_pos;
3589 // We need to create an inset at the beginning
3591 if (bibitem_pos > 0) {
3592 // there was one somewhere in the paragraph, let's move it
3593 inset = d->insetlist_.release(bibitem_pos);
3594 eraseChar(bibitem_pos, track_changes);
3597 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3598 InsetCommandParams(BIBITEM_CODE));
3600 Font font(inherit_font, buffer.params().language);
3601 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3602 : Change::UNCHANGED));
3608 void Paragraph::checkAuthors(AuthorList const & authorList)
3610 d->changes_.checkAuthors(authorList);
3614 bool Paragraph::isChanged(pos_type pos) const
3616 return lookupChange(pos).changed();
3620 bool Paragraph::isInserted(pos_type pos) const
3622 return lookupChange(pos).inserted();
3626 bool Paragraph::isDeleted(pos_type pos) const
3628 return lookupChange(pos).deleted();
3632 InsetList const & Paragraph::insetList() const
3634 return d->insetlist_;
3638 void Paragraph::setBuffer(Buffer & b)
3640 d->insetlist_.setBuffer(b);
3644 Inset * Paragraph::releaseInset(pos_type pos)
3646 Inset * inset = d->insetlist_.release(pos);
3647 /// does not honour change tracking!
3648 eraseChar(pos, false);
3653 Inset * Paragraph::getInset(pos_type pos)
3655 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3656 ? d->insetlist_.get(pos) : 0;
3660 Inset const * Paragraph::getInset(pos_type pos) const
3662 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3663 ? d->insetlist_.get(pos) : 0;
3667 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3668 pos_type & right, TextCase action)
3670 // process sequences of modified characters; in change
3671 // tracking mode, this approach results in much better
3672 // usability than changing case on a char-by-char basis
3675 bool const trackChanges = bparams.trackChanges;
3677 bool capitalize = true;
3679 for (; pos < right; ++pos) {
3680 char_type oldChar = d->text_[pos];
3681 char_type newChar = oldChar;
3683 // ignore insets and don't play with deleted text!
3684 if (oldChar != META_INSET && !isDeleted(pos)) {
3686 case text_lowercase:
3687 newChar = lowercase(oldChar);
3689 case text_capitalization:
3691 newChar = uppercase(oldChar);
3695 case text_uppercase:
3696 newChar = uppercase(oldChar);
3701 if (isWordSeparator(pos) || isDeleted(pos)) {
3702 // permit capitalization again
3706 if (oldChar != newChar) {
3708 if (pos != right - 1)
3710 // step behind the changing area
3714 int erasePos = pos - changes.size();
3715 for (size_t i = 0; i < changes.size(); i++) {
3716 insertChar(pos, changes[i],
3717 getFontSettings(bparams,
3720 if (!eraseChar(erasePos, trackChanges)) {
3723 ++right; // expand selection
3731 int Paragraph::find(docstring const & str, bool cs, bool mw,
3732 pos_type start_pos, bool del) const
3734 pos_type pos = start_pos;
3735 int const strsize = str.length();
3737 pos_type const parsize = d->text_.size();
3738 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3739 // Ignore "invisible" letters such as ligature breaks
3740 // and hyphenation chars while searching
3741 while (pos < parsize - 1 && isInset(pos)) {
3742 odocstringstream os;
3743 getInset(pos)->toString(os);
3744 if (!getInset(pos)->isLetter() || !os.str().empty())
3748 if (cs && str[i] != d->text_[pos])
3750 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3752 if (!del && isDeleted(pos))
3759 // if necessary, check whether string matches word
3761 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3764 && !isWordSeparator(pos))
3768 return pos - start_pos;
3772 char_type Paragraph::getChar(pos_type pos) const
3774 return d->text_[pos];
3778 pos_type Paragraph::size() const
3780 return d->text_.size();
3784 bool Paragraph::empty() const
3786 return d->text_.empty();
3790 bool Paragraph::isInset(pos_type pos) const
3792 return d->text_[pos] == META_INSET;
3796 bool Paragraph::isSeparator(pos_type pos) const
3798 //FIXME: Are we sure this can be the only separator?
3799 return d->text_[pos] == ' ';
3803 void Paragraph::deregisterWords()
3805 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3806 Private::LangWordsMap::const_iterator ite = d->words_.end();
3807 for (; itl != ite; ++itl) {
3808 WordList * wl = theWordList(itl->first);
3809 Private::Words::const_iterator it = (itl->second).begin();
3810 Private::Words::const_iterator et = (itl->second).end();
3811 for (; it != et; ++it)
3818 void Paragraph::locateWord(pos_type & from, pos_type & to,
3819 word_location const loc) const
3822 case WHOLE_WORD_STRICT:
3823 if (from == 0 || from == size()
3824 || isWordSeparator(from)
3825 || isWordSeparator(from - 1)) {
3829 // no break here, we go to the next
3832 // If we are already at the beginning of a word, do nothing
3833 if (!from || isWordSeparator(from - 1))
3835 // no break here, we go to the next
3838 // always move the cursor to the beginning of previous word
3839 while (from && !isWordSeparator(from - 1))
3843 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3846 // no need to move the 'from' cursor
3850 while (to < size() && !isWordSeparator(to))
3855 void Paragraph::collectWords()
3857 pos_type n = size();
3858 for (pos_type pos = 0; pos < n; ++pos) {
3859 if (isWordSeparator(pos))
3861 pos_type from = pos;
3862 locateWord(from, pos, WHOLE_WORD);
3863 if ((pos - from) >= (int)lyxrc.completion_minlength) {
3864 docstring word = asString(from, pos, AS_STR_NONE);
3865 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3866 if (cit == d->fontlist_.end())
3868 Language const * lang = cit->font().language();
3869 d->words_[*lang].insert(word);
3875 void Paragraph::registerWords()
3877 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3878 Private::LangWordsMap::const_iterator ite = d->words_.end();
3879 for (; itl != ite; ++itl) {
3880 WordList * wl = theWordList(itl->first);
3881 Private::Words::const_iterator it = (itl->second).begin();
3882 Private::Words::const_iterator et = (itl->second).end();
3883 for (; it != et; ++it)
3889 void Paragraph::updateWords()
3897 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3899 SkipPositionsIterator begin = skips.begin();
3900 SkipPositions::iterator end = skips.end();
3901 if (pos > 0 && begin < end) {
3903 if (end->last == pos - 1) {
3908 skips.insert(end, FontSpan(pos, pos));
3912 Language * Paragraph::Private::locateSpellRange(
3913 pos_type & from, pos_type & to,
3914 SkipPositions & skips) const
3916 // skip leading white space
3917 while (from < to && owner_->isWordSeparator(from))
3919 // don't check empty range
3922 // get current language
3923 Language * lang = getSpellLanguage(from);
3924 pos_type last = from;
3925 bool samelang = true;
3926 bool sameinset = true;
3927 while (last < to && samelang && sameinset) {
3928 // hop to end of word
3929 while (last < to && !owner_->isWordSeparator(last)) {
3930 if (owner_->getInset(last)) {
3931 appendSkipPosition(skips, last);
3932 } else if (owner_->isDeleted(last)) {
3933 appendSkipPosition(skips, last);
3937 // hop to next word while checking for insets
3938 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3939 if (Inset const * inset = owner_->getInset(last))
3940 sameinset = inset->isChar() && inset->isLetter();
3941 if (sameinset && owner_->isDeleted(last)) {
3942 appendSkipPosition(skips, last);
3947 if (sameinset && last < to) {
3948 // now check for language change
3949 samelang = lang == getSpellLanguage(last);
3952 // if language change detected backstep is needed
3960 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3963 const_cast<Language *>(owner_->getFontSettings(
3964 inset_owner_->buffer().params(), from).language());
3965 if (lang == inset_owner_->buffer().params().language
3966 && !lyxrc.spellchecker_alt_lang.empty()) {
3968 string const lang_variety =
3969 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3970 lang->setCode(lang_code);
3971 lang->setVariety(lang_variety);
3977 void Paragraph::requestSpellCheck(pos_type pos)
3979 d->requestSpellCheck(pos);
3983 bool Paragraph::needsSpellCheck() const
3985 SpellChecker::ChangeNumber speller_change_number = 0;
3986 if (theSpellChecker())
3987 speller_change_number = theSpellChecker()->changeNumber();
3988 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3989 d->speller_state_.needsCompleteRefresh(speller_change_number);
3991 return d->needsSpellCheck();
3995 bool Paragraph::Private::ignoreWord(docstring const & word) const
3997 // Ignore words with digits
3998 // FIXME: make this customizable
3999 // (note that some checkers ignore words with digits by default)
4000 docstring::const_iterator cit = word.begin();
4001 docstring::const_iterator const end = word.end();
4002 for (; cit != end; ++cit) {
4003 if (isNumber((*cit)))
4010 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4011 WordLangTuple & wl, docstring_list & suggestions,
4012 bool do_suggestion, bool check_learned) const
4014 SpellChecker::Result result = SpellChecker::WORD_OK;
4015 SpellChecker * speller = theSpellChecker();
4019 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4022 locateWord(from, to, WHOLE_WORD);
4023 if (from == to || from >= size())
4026 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4027 Language * lang = d->getSpellLanguage(from);
4029 wl = WordLangTuple(word, lang);
4034 if (needsSpellCheck() || check_learned) {
4036 if (!d->ignoreWord(word)) {
4037 bool const trailing_dot = to < size() && d->text_[to] == '.';
4038 result = speller->check(wl);
4039 if (SpellChecker::misspelled(result) && trailing_dot) {
4040 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4041 result = speller->check(wl);
4042 if (!SpellChecker::misspelled(result)) {
4043 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4045 from << ".." << to << "]");
4047 // spell check with dot appended failed too
4048 // restore original word/lang value
4049 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4050 wl = WordLangTuple(word, lang);
4054 if (!SpellChecker::misspelled(result)) {
4055 // area up to the begin of the next word is not misspelled
4056 while (end < size() && isWordSeparator(end))
4059 d->setMisspelled(from, end, result);
4061 result = d->speller_state_.getState(from);
4065 suggestions.clear();
4067 if (SpellChecker::misspelled(result)) {
4068 LYXERR(Debug::GUI, "misspelled word: \"" <<
4070 from << ".." << to << "]");
4072 speller->suggest(wl, suggestions);
4078 void Paragraph::Private::markMisspelledWords(
4079 pos_type const & first, pos_type const & last,
4080 SpellChecker::Result result,
4081 docstring const & word,
4082 SkipPositions const & skips)
4084 if (!SpellChecker::misspelled(result)) {
4085 setMisspelled(first, last, SpellChecker::WORD_OK);
4089 SpellChecker * speller = theSpellChecker();
4090 // locate and enumerate the error positions
4091 int nerrors = speller->numMisspelledWords();
4093 SkipPositionsIterator it = skips.begin();
4094 SkipPositionsIterator et = skips.end();
4095 for (int index = 0; index < nerrors; ++index) {
4098 speller->misspelledWord(index, wstart, wlen);
4099 /// should not happen if speller supports range checks
4100 if (!wlen) continue;
4101 docstring const misspelled = word.substr(wstart, wlen);
4102 wstart += first + numskipped;
4103 if (snext < wstart) {
4104 /// mark the range of correct spelling
4105 numskipped += countSkips(it, et, wstart);
4106 setMisspelled(snext,
4107 wstart - 1, SpellChecker::WORD_OK);
4109 snext = wstart + wlen;
4110 numskipped += countSkips(it, et, snext);
4111 /// mark the range of misspelling
4112 setMisspelled(wstart, snext, result);
4113 LYXERR(Debug::GUI, "misspelled word: \"" <<
4114 misspelled << "\" [" <<
4115 wstart << ".." << (snext-1) << "]");
4118 if (snext <= last) {
4119 /// mark the range of correct spelling at end
4120 setMisspelled(snext, last, SpellChecker::WORD_OK);
4125 void Paragraph::spellCheck() const
4127 SpellChecker * speller = theSpellChecker();
4128 if (!speller || empty() ||!needsSpellCheck())
4132 d->rangeOfSpellCheck(start, endpos);
4133 if (speller->canCheckParagraph()) {
4134 // loop until we leave the range
4135 for (pos_type first = start; first < endpos; ) {
4136 pos_type last = endpos;
4137 Private::SkipPositions skips;
4138 Language * lang = d->locateSpellRange(first, last, skips);
4139 if (first >= endpos)
4141 // start the spell checker on the unit of meaning
4142 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4143 WordLangTuple wl = WordLangTuple(word, lang);
4144 SpellChecker::Result result = word.size() ?
4145 speller->check(wl) : SpellChecker::WORD_OK;
4146 d->markMisspelledWords(first, last, result, word, skips);
4150 static docstring_list suggestions;
4151 pos_type to = endpos;
4152 while (start < endpos) {
4154 spellCheck(start, to, wl, suggestions, false);
4158 d->readySpellCheck();
4162 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4164 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4165 if (result || pos <= 0 || pos > size())
4167 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4168 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4173 string Paragraph::magicLabel() const
4176 ss << "magicparlabel-" << id();