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 contains(pos_type pos) const { return range_.contains(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 //FIXME: is this the same as !range_.intersect(r).empty() ?
108 return range_.contains(r.first) || range_.contains(r.last) ||
109 r.contains(range_.first) || r.contains(range_.last);
112 void shift(pos_type pos, int offset)
114 if (range_.first > pos) {
115 range_.first += offset;
116 range_.last += offset;
117 } else if (range_.last >= pos) {
118 range_.last += offset;
123 SpellChecker::Result result_ ;
127 /////////////////////////////////////////////////////////////////////
131 /////////////////////////////////////////////////////////////////////
133 class SpellCheckerState {
137 needs_refresh_ = true;
138 current_change_number_ = 0;
141 void setRange(FontSpan const & fp, SpellChecker::Result state)
144 RangesIterator et = ranges_.end();
145 RangesIterator it = ranges_.begin();
146 for (; it != et; ++it) {
147 if (!it->covered(fp))
148 result.push_back(SpellResultRange(it->range(), it->result()));
149 else if (state == SpellChecker::WORD_OK) {
150 // trim or split the current misspelled range
151 // store misspelled ranges only
152 FontSpan range = it->range();
153 if (fp.first > range.first) {
154 // misspelled area in front of WORD_OK
155 range.last = fp.first - 1;
156 result.push_back(SpellResultRange(range, it->result()));
159 if (fp.last < range.last) {
160 // misspelled area after WORD_OK range
161 range.first = fp.last + 1;
162 result.push_back(SpellResultRange(range, it->result()));
167 if (state != SpellChecker::WORD_OK)
168 ranges_.push_back(SpellResultRange(fp, state));
171 void increasePosAfterPos(pos_type pos)
173 correctRangesAfterPos(pos, 1);
177 void decreasePosAfterPos(pos_type pos)
179 correctRangesAfterPos(pos, -1);
183 void refreshLast(pos_type pos)
185 if (pos < refresh_.last)
189 SpellChecker::Result getState(pos_type pos) const
191 SpellChecker::Result result = SpellChecker::WORD_OK;
192 RangesIterator et = ranges_.end();
193 RangesIterator it = ranges_.begin();
194 for (; it != et; ++it) {
195 if(it->contains(pos)) {
202 FontSpan const & getRange(pos_type pos) const
204 /// empty span to indicate mismatch
205 static FontSpan empty_;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 bool needsRefresh() const
218 return needs_refresh_;
221 SpellChecker::ChangeNumber currentChangeNumber() const
223 return current_change_number_;
226 void refreshRange(pos_type & first, pos_type & last) const
228 first = refresh_.first;
229 last = refresh_.last;
232 void needsRefresh(pos_type pos)
234 if (needs_refresh_ && pos != -1) {
235 if (pos < refresh_.first)
236 refresh_.first = pos;
237 if (pos > refresh_.last)
239 } else if (pos != -1) {
240 // init request check for neighbour positions too
241 refresh_.first = pos > 0 ? pos - 1 : 0;
242 // no need for special end of paragraph check
243 refresh_.last = pos + 1;
245 needs_refresh_ = pos != -1;
248 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
250 needs_refresh_ = true;
253 current_change_number_ = change_number;
256 typedef vector<SpellResultRange> Ranges;
257 typedef Ranges::const_iterator RangesIterator;
259 /// the area of the paragraph with pending spell check
262 /// spell state cache version number
263 SpellChecker::ChangeNumber current_change_number_;
266 void correctRangesAfterPos(pos_type pos, int offset)
268 RangesIterator et = ranges_.end();
269 Ranges::iterator it = ranges_.begin();
270 for (; it != et; ++it) {
271 it->shift(pos, offset);
277 /////////////////////////////////////////////////////////////////////
279 // Paragraph::Private
281 /////////////////////////////////////////////////////////////////////
283 class Paragraph::Private
285 // Enforce our own "copy" constructor by declaring the standard one and
286 // the assignment operator private without implementing them.
287 Private(Private const &);
288 Private & operator=(Private const &);
291 Private(Paragraph * owner, Layout const & layout);
292 /// "Copy constructor"
293 Private(Private const &, Paragraph * owner);
294 /// Copy constructor from \p beg to \p end
295 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
298 void insertChar(pos_type pos, char_type c, Change const & change);
300 /// Output the surrogate pair formed by \p c and \p next to \p os.
301 /// \return the number of characters written.
302 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
303 OutputParams const &);
305 /// Output a space in appropriate formatting (or a surrogate pair
306 /// if the next character is a combining character).
307 /// \return whether a surrogate pair was output.
308 bool simpleTeXBlanks(OutputParams const &,
311 unsigned int & column,
313 Layout const & style);
315 /// Output consecutive unicode chars, belonging to the same script as
316 /// specified by the latex macro \p ltx, to \p os starting from \p i.
317 /// \return the number of characters written.
318 int writeScriptChars(otexstream & os, docstring const & ltx,
319 Change const &, Encoding const &, pos_type & i);
321 /// This could go to ParagraphParameters if we want to.
322 int startTeXParParams(BufferParams const &, otexstream &,
323 OutputParams const &) const;
325 /// This could go to ParagraphParameters if we want to.
326 bool endTeXParParams(BufferParams const &, otexstream &,
327 OutputParams const &) const;
330 void latexInset(BufferParams const &,
335 Font const & outerfont,
337 Change & running_change,
338 Layout const & style,
340 unsigned int & column);
343 void latexSpecialChar(
345 BufferParams const & bparams,
346 OutputParams const & runparams,
347 Font const & running_font,
348 Change const & running_change,
349 Layout const & style,
352 unsigned int & column);
359 unsigned int & column);
365 unsigned int & column);
367 bool latexSpecialTypewriter(
371 unsigned int & column);
373 bool latexSpecialPhrase(
377 unsigned int & column,
378 OutputParams const & runparams);
381 void validate(LaTeXFeatures & features) const;
383 /// Checks if the paragraph contains only text and no inset or font change.
384 bool onlyText(Buffer const & buf, Font const & outerfont,
385 pos_type initial) const;
387 /// match a string against a particular point in the paragraph
388 bool isTextAt(string const & str, pos_type pos) const;
390 /// a vector of speller skip positions
391 typedef vector<FontSpan> SkipPositions;
392 typedef SkipPositions::const_iterator SkipPositionsIterator;
394 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
396 Language * getSpellLanguage(pos_type const from) const;
398 Language * locateSpellRange(pos_type & from, pos_type & to,
399 SkipPositions & skips) const;
401 bool hasSpellerChange() const
403 SpellChecker::ChangeNumber speller_change_number = 0;
404 if (theSpellChecker())
405 speller_change_number = theSpellChecker()->changeNumber();
406 return speller_change_number > speller_state_.currentChangeNumber();
409 bool ignoreWord(docstring const & word) const ;
411 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
413 pos_type textsize = owner_->size();
414 // check for sane arguments
415 if (to <= from || from >= textsize)
417 FontSpan fp = FontSpan(from, to - 1);
418 speller_state_.setRange(fp, state);
421 void requestSpellCheck(pos_type pos)
424 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
426 speller_state_.needsRefresh(pos);
429 void readySpellCheck()
431 speller_state_.needsRefresh(-1);
434 bool needsSpellCheck() const
436 return speller_state_.needsRefresh();
439 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
441 speller_state_.refreshRange(first, last);
443 last = owner_->size();
446 pos_type endpos = last;
447 owner_->locateWord(first, endpos, WHOLE_WORD);
450 owner_->locateWord(last, endpos, WHOLE_WORD);
455 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
459 while (it != et && it->first < start) {
460 int skip = it->last - it->first + 1;
468 void markMisspelledWords(pos_type const & first, pos_type const & last,
469 SpellChecker::Result result,
470 docstring const & word,
471 SkipPositions const & skips);
473 InsetCode ownerCode() const
475 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
478 /// Which Paragraph owns us?
482 Inset const * inset_owner_;
491 ParagraphParameters params_;
493 /// for recording and looking up changes
497 InsetList insetlist_;
500 pos_type begin_of_body_;
502 typedef docstring TextContainer;
506 typedef set<docstring> Words;
507 typedef map<string, Words> LangWordsMap;
511 Layout const * layout_;
513 SpellCheckerState speller_state_;
519 struct special_phrase {
525 special_phrase const special_phrases[] = {
526 { "LyX", from_ascii("\\LyX{}"), false },
527 { "TeX", from_ascii("\\TeX{}"), true },
528 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
529 { "LaTeX", from_ascii("\\LaTeX{}"), true },
532 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
537 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
538 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
544 // Initialization of the counter for the paragraph id's,
546 // FIXME: There should be a more intelligent way to generate and use the
547 // paragraph ids per buffer instead a global static counter for all InsetText
548 // in the running program.
549 static int paragraph_id = -1;
551 Paragraph::Private::Private(Private const & p, Paragraph * owner)
552 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
553 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
554 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
557 id_ = ++paragraph_id;
558 requestSpellCheck(p.text_.size());
562 Paragraph::Private::Private(Private const & p, Paragraph * owner,
563 pos_type beg, pos_type end)
564 : owner_(owner), inset_owner_(p.inset_owner_),
565 params_(p.params_), changes_(p.changes_),
566 insetlist_(p.insetlist_, beg, end),
567 begin_of_body_(p.begin_of_body_), words_(p.words_),
570 id_ = ++paragraph_id;
571 if (beg >= pos_type(p.text_.size()))
573 text_ = p.text_.substr(beg, end - beg);
575 FontList::const_iterator fcit = fontlist_.begin();
576 FontList::const_iterator fend = fontlist_.end();
577 for (; fcit != fend; ++fcit) {
578 if (fcit->pos() < beg)
580 if (fcit->pos() >= end) {
581 // Add last entry in the fontlist_.
582 fontlist_.set(text_.size() - 1, fcit->font());
585 // Add a new entry in the fontlist_.
586 fontlist_.set(fcit->pos() - beg, fcit->font());
588 requestSpellCheck(p.text_.size());
592 void Paragraph::addChangesToToc(DocIterator const & cdit,
593 Buffer const & buf, bool output_active) const
595 d->changes_.addToToc(cdit, buf, output_active);
599 bool Paragraph::isDeleted(pos_type start, pos_type end) const
601 LASSERT(start >= 0 && start <= size(), return false);
602 LASSERT(end > start && end <= size() + 1, return false);
604 return d->changes_.isDeleted(start, end);
608 bool Paragraph::isChanged(pos_type start, pos_type end) const
610 LASSERT(start >= 0 && start <= size(), return false);
611 LASSERT(end > start && end <= size() + 1, return false);
613 return d->changes_.isChanged(start, end);
617 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
619 // keep the logic here in sync with the logic of eraseChars()
623 Change const change = d->changes_.lookup(size());
624 return change.inserted() && change.currentAuthor();
628 void Paragraph::setChange(Change const & change)
630 // beware of the imaginary end-of-par character!
631 d->changes_.set(change, 0, size() + 1);
634 * Propagate the change recursively - but not in case of DELETED!
636 * Imagine that your co-author makes changes in an existing inset. He
637 * sends your document to you and you come to the conclusion that the
638 * inset should go completely. If you erase it, LyX must not delete all
639 * text within the inset. Otherwise, the change tracked insertions of
640 * your co-author get lost and there is no way to restore them later.
642 * Conclusion: An inset's content should remain untouched if you delete it
645 if (!change.deleted()) {
646 for (pos_type pos = 0; pos < size(); ++pos) {
647 if (Inset * inset = getInset(pos))
648 inset->setChange(change);
654 void Paragraph::setChange(pos_type pos, Change const & change)
656 LASSERT(pos >= 0 && pos <= size(), return);
657 d->changes_.set(change, pos);
659 // see comment in setChange(Change const &) above
660 if (!change.deleted() && pos < size())
661 if (Inset * inset = getInset(pos))
662 inset->setChange(change);
666 Change const & Paragraph::lookupChange(pos_type pos) const
668 LBUFERR(pos >= 0 && pos <= size());
669 return d->changes_.lookup(pos);
673 void Paragraph::acceptChanges(pos_type start, pos_type end)
675 LASSERT(start >= 0 && start <= size(), return);
676 LASSERT(end > start && end <= size() + 1, return);
678 for (pos_type pos = start; pos < end; ++pos) {
679 switch (lookupChange(pos).type) {
680 case Change::UNCHANGED:
681 // accept changes in nested inset
682 if (Inset * inset = getInset(pos))
683 inset->acceptChanges();
686 case Change::INSERTED:
687 d->changes_.set(Change(Change::UNCHANGED), pos);
688 // also accept changes in nested inset
689 if (Inset * inset = getInset(pos))
690 inset->acceptChanges();
693 case Change::DELETED:
694 // Suppress access to non-existent
695 // "end-of-paragraph char"
697 eraseChar(pos, false);
708 void Paragraph::rejectChanges(pos_type start, pos_type end)
710 LASSERT(start >= 0 && start <= size(), return);
711 LASSERT(end > start && end <= size() + 1, return);
713 for (pos_type pos = start; pos < end; ++pos) {
714 switch (lookupChange(pos).type) {
715 case Change::UNCHANGED:
716 // reject changes in nested inset
717 if (Inset * inset = getInset(pos))
718 inset->rejectChanges();
721 case Change::INSERTED:
722 // Suppress access to non-existent
723 // "end-of-paragraph char"
725 eraseChar(pos, false);
731 case Change::DELETED:
732 d->changes_.set(Change(Change::UNCHANGED), pos);
734 // Do NOT reject changes within a deleted inset!
735 // There may be insertions of a co-author inside of it!
743 void Paragraph::Private::insertChar(pos_type pos, char_type c,
744 Change const & change)
746 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
749 changes_.insert(change, pos);
751 // This is actually very common when parsing buffers (and
752 // maybe inserting ascii text)
753 if (pos == pos_type(text_.size())) {
754 // when appending characters, no need to update tables
756 // but we want spell checking
757 requestSpellCheck(pos);
761 text_.insert(text_.begin() + pos, c);
763 // Update the font table.
764 fontlist_.increasePosAfterPos(pos);
767 insetlist_.increasePosAfterPos(pos);
769 // Update list of misspelled positions
770 speller_state_.increasePosAfterPos(pos);
774 bool Paragraph::insertInset(pos_type pos, Inset * inset,
775 Font const & font, Change const & change)
777 LASSERT(inset, return false);
778 LASSERT(pos >= 0 && pos <= size(), return false);
780 // Paragraph::insertInset() can be used in cut/copy/paste operation where
781 // d->inset_owner_ is not set yet.
782 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
785 d->insertChar(pos, META_INSET, change);
786 LASSERT(d->text_[pos] == META_INSET, return false);
788 // Add a new entry in the insetlist_.
789 d->insetlist_.insert(inset, pos);
791 // Some insets require run of spell checker
792 requestSpellCheck(pos);
798 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
800 LASSERT(pos >= 0 && pos <= size(), return false);
802 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
805 Change change = d->changes_.lookup(pos);
807 // set the character to DELETED if
808 // a) it was previously unchanged or
809 // b) it was inserted by a co-author
811 if (!change.changed() ||
812 (change.inserted() && !change.currentAuthor())) {
813 setChange(pos, Change(Change::DELETED));
814 // request run of spell checker
815 requestSpellCheck(pos);
819 if (change.deleted())
823 // Don't physically access the imaginary end-of-paragraph character.
824 // eraseChar() can only mark it as DELETED. A physical deletion of
825 // end-of-par must be handled externally.
831 d->changes_.erase(pos);
833 // if it is an inset, delete the inset entry
834 if (d->text_[pos] == META_INSET)
835 d->insetlist_.erase(pos);
837 d->text_.erase(d->text_.begin() + pos);
839 // Update the fontlist_
840 d->fontlist_.erase(pos);
842 // Update the insetlist_
843 d->insetlist_.decreasePosAfterPos(pos);
845 // Update list of misspelled positions
846 d->speller_state_.decreasePosAfterPos(pos);
847 d->speller_state_.refreshLast(size());
853 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
855 LASSERT(start >= 0 && start <= size(), return 0);
856 LASSERT(end >= start && end <= size() + 1, return 0);
859 for (pos_type count = end - start; count; --count) {
860 if (!eraseChar(i, trackChanges))
867 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
868 char_type next, OutputParams const & runparams)
870 // Writing next here may circumvent a possible font change between
871 // c and next. Since next is only output if it forms a surrogate pair
872 // with c we can ignore this:
873 // A font change inside a surrogate pair does not make sense and is
874 // hopefully impossible to input.
875 // FIXME: change tracking
876 // Is this correct WRT change tracking?
877 Encoding const & encoding = *(runparams.encoding);
878 docstring latex1 = encoding.latexChar(next).first;
879 if (runparams.inIPA) {
880 string const tipashortcut = Encodings::TIPAShortcut(next);
881 if (!tipashortcut.empty()) {
882 latex1 = from_ascii(tipashortcut);
885 docstring const latex2 = encoding.latexChar(c).first;
886 if (docstring(1, next) == latex1) {
887 // the encoding supports the combination
888 os << latex2 << latex1;
889 return latex1.length() + latex2.length();
890 } else if (runparams.local_font &&
891 runparams.local_font->language()->lang() == "polutonikogreek") {
892 // polutonikogreek only works without the brackets
893 os << latex1 << latex2;
894 return latex1.length() + latex2.length();
896 os << latex1 << '{' << latex2 << '}';
897 return latex1.length() + latex2.length() + 2;
901 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
904 unsigned int & column,
906 Layout const & style)
908 if (style.pass_thru || runparams.pass_thru)
911 if (i + 1 < int(text_.size())) {
912 char_type next = text_[i + 1];
913 if (Encodings::isCombiningChar(next)) {
914 // This space has an accent, so we must always output it.
915 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
920 if (runparams.linelen > 0
921 && column > runparams.linelen
923 && text_[i - 1] != ' '
924 && (i + 1 < int(text_.size()))
925 // same in FreeSpacing mode
926 && !owner_->isFreeSpacing()
927 // In typewriter mode, we want to avoid
928 // ! . ? : at the end of a line
929 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
930 && (text_[i - 1] == '.'
931 || text_[i - 1] == '?'
932 || text_[i - 1] == ':'
933 || text_[i - 1] == '!'))) {
935 os.texrow().start(owner_->id(), i + 1);
937 } else if (style.free_spacing) {
946 int Paragraph::Private::writeScriptChars(otexstream & os,
947 docstring const & ltx,
948 Change const & runningChange,
949 Encoding const & encoding,
952 // FIXME: modifying i here is not very nice...
954 // We only arrive here when a proper language for character text_[i] has
955 // not been specified (i.e., it could not be translated in the current
956 // latex encoding) or its latex translation has been forced, and it
957 // belongs to a known script.
958 // Parameter ltx contains the latex translation of text_[i] as specified
959 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
960 // The latex macro name "textXXX" specifies the script to which text_[i]
961 // belongs and we use it in order to check whether characters from the
962 // same script immediately follow, such that we can collect them in a
963 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
964 // for the first char but only "<spec>" for all subsequent chars.
965 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
966 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
967 string script = to_ascii(ltx.substr(1, brace1 - 1));
970 bool closing_brace = true;
971 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
972 // Correct encoding is being used, so we can avoid \textgreek.
975 closing_brace = false;
977 os << ltx.substr(pos, length);
978 int size = text_.size();
979 while (i + 1 < size) {
980 char_type const next = text_[i + 1];
981 // Stop here if next character belongs to another script
982 // or there is a change in change tracking status.
983 if (!Encodings::isKnownScriptChar(next, script) ||
984 runningChange != owner_->lookupChange(i + 1))
988 FontList::const_iterator cit = fontlist_.begin();
989 FontList::const_iterator end = fontlist_.end();
990 for (; cit != end; ++cit) {
991 if (cit->pos() >= i && !found) {
992 prev_font = cit->font();
995 if (cit->pos() >= i + 1)
998 // Stop here if there is a font attribute or encoding change.
999 if (found && cit != end && prev_font != cit->font())
1001 docstring const latex = encoding.latexChar(next).first;
1002 docstring::size_type const b1 =
1003 latex.find_first_of(from_ascii("{"));
1004 docstring::size_type const b2 =
1005 latex.find_last_of(from_ascii("}"));
1006 int const len = b2 - b1 - 1;
1007 os << latex.substr(b1 + 1, len);
1011 if (closing_brace) {
1019 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1021 pos_type const len = str.length();
1023 // is the paragraph large enough?
1024 if (pos + len > int(text_.size()))
1027 // does the wanted text start at point?
1028 for (string::size_type i = 0; i < str.length(); ++i) {
1029 // Caution: direct comparison of characters works only
1030 // because str is pure ASCII.
1031 if (str[i] != text_[pos + i])
1035 return fontlist_.hasChangeInRange(pos, len);
1039 void Paragraph::Private::latexInset(BufferParams const & bparams,
1041 OutputParams & runparams,
1042 Font & running_font,
1044 Font const & outerfont,
1046 Change & running_change,
1047 Layout const & style,
1049 unsigned int & column)
1051 Inset * inset = owner_->getInset(i);
1054 if (style.pass_thru) {
1055 odocstringstream ods;
1056 inset->plaintext(ods, runparams);
1061 // FIXME: move this to InsetNewline::latex
1062 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1063 // newlines are handled differently here than
1064 // the default in simpleTeXSpecialChars().
1065 if (!style.newline_allowed) {
1069 column += running_font.latexWriteEndChanges(
1070 os, bparams, runparams,
1071 basefont, basefont);
1075 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1078 basefont = owner_->getLayoutFont(bparams, outerfont);
1079 running_font = basefont;
1081 if (runparams.moving_arg)
1085 os.texrow().start(owner_->id(), i + 1);
1089 if (owner_->isDeleted(i)) {
1090 if( ++runparams.inDeletedInset == 1)
1091 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1094 if (inset->canTrackChanges()) {
1095 column += Changes::latexMarkChange(os, bparams, running_change,
1096 Change(Change::UNCHANGED), runparams);
1097 running_change = Change(Change::UNCHANGED);
1101 odocstream::pos_type const len = os.os().tellp();
1103 if (inset->forceLTR()
1104 && !runparams.use_polyglossia
1105 && running_font.isRightToLeft()
1106 // ERT is an exception, it should be output with no
1107 // decorations at all
1108 && inset->lyxCode() != ERT_CODE) {
1109 if (running_font.language()->lang() == "farsi")
1116 // FIXME: Bug: we can have an empty font change here!
1117 // if there has just been a font change, we are going to close it
1118 // right now, which means stupid latex code like \textsf{}. AFAIK,
1119 // this does not harm dvi output. A minor bug, thus (JMarc)
1121 // Some insets cannot be inside a font change command.
1122 // However, even such insets *can* be placed in \L or \R
1123 // or their equivalents (for RTL language switches), so we don't
1124 // close the language in those cases.
1125 // ArabTeX, though, cannot handle this special behavior, it seems.
1126 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1127 || running_font.language()->lang() == "arabic_arabtex";
1128 if (open_font && !inset->inheritFont()) {
1129 bool closeLanguage = arabtex
1130 || basefont.isRightToLeft() == running_font.isRightToLeft();
1131 unsigned int count = running_font.latexWriteEndChanges(os,
1132 bparams, runparams, basefont, basefont, closeLanguage);
1134 // if any font properties were closed, update the running_font,
1135 // making sure, however, to leave the language as it was
1137 // FIXME: probably a better way to keep track of the old
1138 // language, than copying the entire font?
1139 Font const copy_font(running_font);
1140 basefont = owner_->getLayoutFont(bparams, outerfont);
1141 running_font = basefont;
1143 running_font.setLanguage(copy_font.language());
1144 // leave font open if language is still open
1145 open_font = (running_font.language() == basefont.language());
1147 runparams.local_font = &basefont;
1151 int prev_rows = os.texrow().rows();
1154 runparams.lastid = id_;
1155 runparams.lastpos = i;
1156 inset->latex(os, runparams);
1157 } catch (EncodingException & e) {
1158 // add location information and throw again.
1165 if (running_font.language()->lang() == "farsi")
1171 if (os.texrow().rows() > prev_rows) {
1172 os.texrow().start(owner_->id(), i + 1);
1175 column += (unsigned int)(os.os().tellp() - len);
1178 if (owner_->isDeleted(i))
1179 --runparams.inDeletedInset;
1183 void Paragraph::Private::latexSpecialChar(otexstream & os,
1184 BufferParams const & bparams,
1185 OutputParams const & runparams,
1186 Font const & running_font,
1187 Change const & running_change,
1188 Layout const & style,
1191 unsigned int & column)
1193 // With polyglossia, brackets and stuff need not be reversed
1194 // in RTL scripts (see bug #8251)
1195 char_type const c = (runparams.use_polyglossia) ?
1196 owner_->getUChar(bparams, i) : text_[i];
1198 if (style.pass_thru || runparams.pass_thru) {
1200 Encoding const * const enc = runparams.encoding;
1201 if (enc && !enc->encodable(c))
1202 throw EncodingException(c);
1208 // TIPA uses its own T3 encoding
1209 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1211 // If T1 font encoding is used, use the special
1212 // characters it provides.
1213 // NOTE: some languages reset the font encoding
1215 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1216 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1219 // \tt font needs special treatment
1220 if (!runparams.inIPA
1221 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1222 && latexSpecialTypewriter(c, os, i, column))
1225 // Otherwise, we use what LaTeX provides us.
1228 os << "\\textbackslash{}";
1232 os << "\\textless{}";
1236 os << "\\textgreater{}";
1240 os << "\\textbar{}";
1247 os << "\\char`\\\"{}";
1252 case '%': case '#': case '{':
1260 os << "\\textasciitilde{}";
1265 os << "\\textasciicircum{}";
1272 // avoid being mistaken for optional arguments
1280 // Blanks are printed before font switching.
1281 // Sure? I am not! (try nice-latex)
1282 // I am sure it's correct. LyX might be smarter
1283 // in the future, but for now, nothing wrong is
1289 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1295 Encoding const & encoding = *(runparams.encoding);
1296 char_type next = '\0';
1297 if (i + 1 < int(text_.size())) {
1298 next = text_[i + 1];
1299 if (Encodings::isCombiningChar(next)) {
1300 column += latexSurrogatePair(os, c, next, runparams) - 1;
1306 pair<docstring, bool> latex = encoding.latexChar(c);
1307 docstring nextlatex;
1308 bool nexttipas = false;
1309 string nexttipashortcut;
1310 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1311 nextlatex = encoding.latexChar(next).first;
1312 if (runparams.inIPA) {
1313 nexttipashortcut = Encodings::TIPAShortcut(next);
1314 nexttipas = !nexttipashortcut.empty();
1318 if (runparams.inIPA) {
1319 string const tipashortcut = Encodings::TIPAShortcut(c);
1320 if (!tipashortcut.empty()) {
1321 latex.first = from_ascii(tipashortcut);
1322 latex.second = false;
1326 if (Encodings::isKnownScriptChar(c, script)
1327 && prefixIs(latex.first, from_ascii("\\" + script)))
1328 column += writeScriptChars(os, latex.first,
1329 running_change, encoding, i) - 1;
1330 else if (latex.second
1331 && ((!prefixIs(nextlatex, '\\')
1332 && !prefixIs(nextlatex, '{')
1333 && !prefixIs(nextlatex, '}'))
1335 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1337 // Prevent eating of a following
1338 // space or command corruption by
1339 // following characters
1340 if (next == ' ' || next == '\0') {
1341 column += latex.first.length() + 1;
1342 os << latex.first << "{}";
1344 column += latex.first.length();
1345 os << latex.first << " ";
1348 column += latex.first.length() - 1;
1356 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1357 pos_type i, unsigned int & column)
1363 // In T1 encoding, these characters exist
1364 // but we should avoid ligatures
1365 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1367 os << "\\textcompwordmark{}";
1374 // soul.sty breaks with \char`\"
1375 os << "\\textquotedbl{}";
1384 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1385 pos_type /*i*/, unsigned int & column)
1395 os << "\\textvertline{}";
1404 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1405 pos_type i, unsigned int & column)
1409 // within \ttfamily, "--" is merged to "-" (no endash)
1410 // so we avoid this rather irritating ligature
1411 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1418 // everything else has to be checked separately
1419 // (depending on the encoding)
1427 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1428 /// do not apply the macro transformation.
1429 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1430 unsigned int & column, OutputParams const & runparams)
1432 // FIXME: if we have "LaTeX" with a font
1433 // change in the middle (before the 'T', then
1434 // the "TeX" part is still special cased.
1435 // Really we should only operate this on
1436 // "words" for some definition of word
1438 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1439 if (!isTextAt(special_phrases[pnr].phrase, i)
1440 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1442 if (runparams.moving_arg)
1444 os << special_phrases[pnr].macro;
1445 i += special_phrases[pnr].phrase.length() - 1;
1446 column += special_phrases[pnr].macro.length() - 1;
1453 void Paragraph::Private::validate(LaTeXFeatures & features) const
1455 if (layout_->inpreamble && inset_owner_) {
1456 bool const is_command = layout_->latextype == LATEX_COMMAND;
1457 Buffer const & buf = inset_owner_->buffer();
1458 BufferParams const & bp = features.runparams().is_child
1459 ? buf.masterParams() : buf.params();
1462 // Using a string stream here circumvents the encoding
1463 // switching machinery of odocstream. Therefore the
1464 // output is wrong if this paragraph contains content
1465 // that needs to switch encoding.
1466 odocstringstream ods;
1467 otexstream os(ods, texrow);
1469 os << '\\' << from_ascii(layout_->latexname());
1470 // we have to provide all the optional arguments here, even though
1471 // the last one is the only one we care about.
1472 // Separate handling of optional argument inset.
1473 if (!layout_->latexargs().empty()) {
1474 OutputParams rp = features.runparams();
1475 rp.local_font = &owner_->getFirstFontSettings(bp);
1476 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1478 os << from_ascii(layout_->latexparam());
1480 docstring::size_type const length = ods.str().length();
1481 // this will output "{" at the beginning, but not at the end
1482 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1483 if (ods.str().length() > length) {
1486 if (!layout_->postcommandargs().empty()) {
1487 OutputParams rp = features.runparams();
1488 rp.local_font = &owner_->getFirstFontSettings(bp);
1489 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1492 string const snippet = to_utf8(ods.str());
1493 features.addPreambleSnippet(snippet);
1497 if (features.runparams().flavor == OutputParams::HTML
1498 && layout_->htmltitle()) {
1499 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1502 // check the params.
1503 if (!params_.spacing().isDefault())
1504 features.require("setspace");
1507 features.useLayout(layout_->name());
1510 fontlist_.validate(features);
1512 // then the indentation
1513 if (!params_.leftIndent().zero())
1514 features.require("ParagraphLeftIndent");
1517 InsetList::const_iterator icit = insetlist_.begin();
1518 InsetList::const_iterator iend = insetlist_.end();
1519 for (; icit != iend; ++icit) {
1521 icit->inset->validate(features);
1522 if (layout_->needprotect &&
1523 icit->inset->lyxCode() == FOOT_CODE)
1524 features.require("footmisc");
1528 // then the contents
1529 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1530 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1531 if (!special_phrases[pnr].builtin
1532 && isTextAt(special_phrases[pnr].phrase, i)) {
1533 features.require(special_phrases[pnr].phrase);
1537 BufferEncodings::validate(text_[i], features);
1541 /////////////////////////////////////////////////////////////////////
1545 /////////////////////////////////////////////////////////////////////
1548 Layout const emptyParagraphLayout;
1551 Paragraph::Paragraph()
1552 : d(new Paragraph::Private(this, emptyParagraphLayout))
1559 Paragraph::Paragraph(Paragraph const & par)
1560 : itemdepth(par.itemdepth),
1561 d(new Paragraph::Private(*par.d, this))
1567 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1568 : itemdepth(par.itemdepth),
1569 d(new Paragraph::Private(*par.d, this, beg, end))
1575 Paragraph & Paragraph::operator=(Paragraph const & par)
1577 // needed as we will destroy the private part before copying it
1579 itemdepth = par.itemdepth;
1583 d = new Private(*par.d, this);
1590 Paragraph::~Paragraph()
1599 // this shall be called just before every "os << ..." action.
1600 void flushString(ostream & os, docstring & s)
1609 void Paragraph::write(ostream & os, BufferParams const & bparams,
1610 depth_type & dth) const
1612 // The beginning or end of a deeper (i.e. nested) area?
1613 if (dth != d->params_.depth()) {
1614 if (d->params_.depth() > dth) {
1615 while (d->params_.depth() > dth) {
1616 os << "\n\\begin_deeper";
1620 while (d->params_.depth() < dth) {
1621 os << "\n\\end_deeper";
1627 // First write the layout
1628 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1630 d->params_.write(os);
1632 Font font1(inherit_font, bparams.language);
1634 Change running_change = Change(Change::UNCHANGED);
1636 // this string is used as a buffer to avoid repetitive calls
1637 // to to_utf8(), which turn out to be expensive (JMarc)
1638 docstring write_buffer;
1641 for (pos_type i = 0; i <= size(); ++i) {
1643 Change const change = lookupChange(i);
1644 if (change != running_change)
1645 flushString(os, write_buffer);
1646 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1647 running_change = change;
1652 // Write font changes
1653 Font font2 = getFontSettings(bparams, i);
1654 if (font2 != font1) {
1655 flushString(os, write_buffer);
1656 font2.lyxWriteChanges(font1, os);
1661 char_type const c = d->text_[i];
1664 if (Inset const * inset = getInset(i)) {
1665 flushString(os, write_buffer);
1666 if (inset->directWrite()) {
1667 // international char, let it write
1668 // code directly so it's shorter in
1674 os << "\\begin_inset ";
1676 os << "\n\\end_inset\n\n";
1679 // FIXME This can be removed again once the mystery
1680 // crash has been resolved.
1685 flushString(os, write_buffer);
1686 os << "\n\\backslash\n";
1690 flushString(os, write_buffer);
1691 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1698 if ((column > 70 && c == ' ')
1700 flushString(os, write_buffer);
1704 // this check is to amend a bug. LyX sometimes
1705 // inserts '\0' this could cause problems.
1707 write_buffer.push_back(c);
1709 LYXERR0("NUL char in structure.");
1715 flushString(os, write_buffer);
1716 os << "\n\\end_layout\n";
1717 // FIXME This can be removed again once the mystery
1718 // crash has been resolved.
1723 void Paragraph::validate(LaTeXFeatures & features) const
1725 d->validate(features);
1729 void Paragraph::insert(pos_type start, docstring const & str,
1730 Font const & font, Change const & change)
1732 for (size_t i = 0, n = str.size(); i != n ; ++i)
1733 insertChar(start + i, str[i], font, change);
1737 void Paragraph::appendChar(char_type c, Font const & font,
1738 Change const & change)
1741 d->changes_.insert(change, d->text_.size());
1742 // when appending characters, no need to update tables
1743 d->text_.push_back(c);
1744 setFont(d->text_.size() - 1, font);
1745 d->requestSpellCheck(d->text_.size() - 1);
1749 void Paragraph::appendString(docstring const & s, Font const & font,
1750 Change const & change)
1752 pos_type end = s.size();
1753 size_t oldsize = d->text_.size();
1754 size_t newsize = oldsize + end;
1755 size_t capacity = d->text_.capacity();
1756 if (newsize >= capacity)
1757 d->text_.reserve(max(capacity + 100, newsize));
1759 // when appending characters, no need to update tables
1762 // FIXME: Optimize this!
1763 for (size_t i = oldsize; i != newsize; ++i) {
1765 d->changes_.insert(change, i);
1766 d->requestSpellCheck(i);
1768 d->fontlist_.set(oldsize, font);
1769 d->fontlist_.set(newsize - 1, font);
1773 void Paragraph::insertChar(pos_type pos, char_type c,
1776 d->insertChar(pos, c, Change(trackChanges ?
1777 Change::INSERTED : Change::UNCHANGED));
1781 void Paragraph::insertChar(pos_type pos, char_type c,
1782 Font const & font, bool trackChanges)
1784 d->insertChar(pos, c, Change(trackChanges ?
1785 Change::INSERTED : Change::UNCHANGED));
1790 void Paragraph::insertChar(pos_type pos, char_type c,
1791 Font const & font, Change const & change)
1793 d->insertChar(pos, c, change);
1798 void Paragraph::resetFonts(Font const & font)
1800 d->fontlist_.clear();
1801 d->fontlist_.set(0, font);
1802 d->fontlist_.set(d->text_.size() - 1, font);
1805 // Gets uninstantiated font setting at position.
1806 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1810 LYXERR0("pos: " << pos << " size: " << size());
1814 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1815 if (cit != d->fontlist_.end())
1818 if (pos == size() && !empty())
1819 return getFontSettings(bparams, pos - 1);
1821 // Optimisation: avoid a full font instantiation if there is no
1822 // language change from previous call.
1823 static Font previous_font;
1824 static Language const * previous_lang = 0;
1825 Language const * lang = getParLanguage(bparams);
1826 if (lang != previous_lang) {
1827 previous_lang = lang;
1828 previous_font = Font(inherit_font, lang);
1830 return previous_font;
1834 FontSpan Paragraph::fontSpan(pos_type pos) const
1836 LBUFERR(pos < size());
1839 FontList::const_iterator cit = d->fontlist_.begin();
1840 FontList::const_iterator end = d->fontlist_.end();
1841 for (; cit != end; ++cit) {
1842 if (cit->pos() >= pos) {
1843 if (pos >= beginOfBody())
1844 return FontSpan(max(start, beginOfBody()),
1847 return FontSpan(start,
1848 min(beginOfBody() - 1,
1851 start = cit->pos() + 1;
1854 // This should not happen, but if so, we take no chances.
1855 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1856 LASSERT(false, return FontSpan(pos, pos));
1860 // Gets uninstantiated font setting at position 0
1861 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1863 if (!empty() && !d->fontlist_.empty())
1864 return d->fontlist_.begin()->font();
1866 // Optimisation: avoid a full font instantiation if there is no
1867 // language change from previous call.
1868 static Font previous_font;
1869 static Language const * previous_lang = 0;
1870 if (bparams.language != previous_lang) {
1871 previous_lang = bparams.language;
1872 previous_font = Font(inherit_font, bparams.language);
1875 return previous_font;
1879 // Gets the fully instantiated font at a given position in a paragraph
1880 // This is basically the same function as Text::GetFont() in text2.cpp.
1881 // The difference is that this one is used for generating the LaTeX file,
1882 // and thus cosmetic "improvements" are disallowed: This has to deliver
1883 // the true picture of the buffer. (Asger)
1884 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1885 Font const & outerfont) const
1889 Font font = getFontSettings(bparams, pos);
1891 pos_type const body_pos = beginOfBody();
1892 FontInfo & fi = font.fontInfo();
1894 fi.realize(d->layout_->labelfont);
1896 fi.realize(d->layout_->font);
1898 fi.realize(outerfont.fontInfo());
1899 fi.realize(bparams.getFont().fontInfo());
1905 Font const Paragraph::getLabelFont
1906 (BufferParams const & bparams, Font const & outerfont) const
1908 FontInfo tmpfont = d->layout_->labelfont;
1909 tmpfont.realize(outerfont.fontInfo());
1910 tmpfont.realize(bparams.getFont().fontInfo());
1911 return Font(tmpfont, getParLanguage(bparams));
1915 Font const Paragraph::getLayoutFont
1916 (BufferParams const & bparams, Font const & outerfont) const
1918 FontInfo tmpfont = d->layout_->font;
1919 tmpfont.realize(outerfont.fontInfo());
1920 tmpfont.realize(bparams.getFont().fontInfo());
1921 return Font(tmpfont, getParLanguage(bparams));
1925 /// Returns the height of the highest font in range
1926 FontSize Paragraph::highestFontInRange
1927 (pos_type startpos, pos_type endpos, FontSize def_size) const
1929 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1933 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1935 char_type c = d->text_[pos];
1936 if (!getFontSettings(bparams, pos).isRightToLeft())
1939 // FIXME: The arabic special casing is due to the difference of arabic
1940 // round brackets input introduced in r18599. Check if this should be
1941 // unified with Hebrew or at least if all bracket types should be
1942 // handled the same (file format change in either case).
1943 string const & lang = getFontSettings(bparams, pos).language()->lang();
1944 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1949 uc = arabic ? c : ')';
1952 uc = arabic ? c : '(';
1978 void Paragraph::setFont(pos_type pos, Font const & font)
1980 LASSERT(pos <= size(), return);
1982 // First, reduce font against layout/label font
1983 // Update: The setCharFont() routine in text2.cpp already
1984 // reduces font, so we don't need to do that here. (Asger)
1986 d->fontlist_.set(pos, font);
1990 void Paragraph::makeSameLayout(Paragraph const & par)
1992 d->layout_ = par.d->layout_;
1993 d->params_ = par.d->params_;
1997 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1999 if (isFreeSpacing())
2005 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2006 if (eraseChar(pos, trackChanges))
2012 return count > 0 || pos > 0;
2016 bool Paragraph::hasSameLayout(Paragraph const & par) const
2018 return par.d->layout_ == d->layout_
2019 && d->params_.sameLayout(par.d->params_);
2023 depth_type Paragraph::getDepth() const
2025 return d->params_.depth();
2029 depth_type Paragraph::getMaxDepthAfter() const
2031 if (d->layout_->isEnvironment())
2032 return d->params_.depth() + 1;
2034 return d->params_.depth();
2038 char Paragraph::getAlign() const
2040 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2041 return d->layout_->align;
2043 return d->params_.align();
2047 docstring const & Paragraph::labelString() const
2049 return d->params_.labelString();
2053 // the next two functions are for the manual labels
2054 docstring const Paragraph::getLabelWidthString() const
2056 if (d->layout_->margintype == MARGIN_MANUAL
2057 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2058 return d->params_.labelWidthString();
2060 return _("Senseless with this layout!");
2064 void Paragraph::setLabelWidthString(docstring const & s)
2066 d->params_.labelWidthString(s);
2070 docstring Paragraph::expandLabel(Layout const & layout,
2071 BufferParams const & bparams) const
2073 return expandParagraphLabel(layout, bparams, true);
2077 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2078 BufferParams const & bparams) const
2080 return expandParagraphLabel(layout, bparams, false);
2084 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2085 BufferParams const & bparams, bool process_appendix) const
2087 DocumentClass const & tclass = bparams.documentClass();
2088 string const & lang = getParLanguage(bparams)->code();
2089 bool const in_appendix = process_appendix && d->params_.appendix();
2090 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2092 if (fmt.empty() && !layout.counter.empty())
2093 return tclass.counters().theCounter(layout.counter, lang);
2095 // handle 'inherited level parts' in 'fmt',
2096 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2097 size_t const i = fmt.find('@', 0);
2098 if (i != docstring::npos) {
2099 size_t const j = fmt.find('@', i + 1);
2100 if (j != docstring::npos) {
2101 docstring parent(fmt, i + 1, j - i - 1);
2102 docstring label = from_ascii("??");
2103 if (tclass.hasLayout(parent))
2104 docstring label = expandParagraphLabel(tclass[parent], bparams,
2106 fmt = docstring(fmt, 0, i) + label
2107 + docstring(fmt, j + 1, docstring::npos);
2111 return tclass.counters().counterLabel(fmt, lang);
2115 void Paragraph::applyLayout(Layout const & new_layout)
2117 d->layout_ = &new_layout;
2118 LyXAlignment const oldAlign = d->params_.align();
2120 if (!(oldAlign & d->layout_->alignpossible)) {
2121 frontend::Alert::warning(_("Alignment not permitted"),
2122 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2123 d->params_.align(LYX_ALIGN_LAYOUT);
2128 pos_type Paragraph::beginOfBody() const
2130 return d->begin_of_body_;
2134 void Paragraph::setBeginOfBody()
2136 if (d->layout_->labeltype != LABEL_MANUAL) {
2137 d->begin_of_body_ = 0;
2141 // Unroll the first two cycles of the loop
2142 // and remember the previous character to
2143 // remove unnecessary getChar() calls
2145 pos_type end = size();
2146 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2148 char_type previous_char = 0;
2151 previous_char = d->text_[i];
2152 if (!(isNewline(i) || isEnvSeparator(i))) {
2154 while (i < end && previous_char != ' ') {
2156 if (isNewline(i) || isEnvSeparator(i))
2159 previous_char = temp;
2165 d->begin_of_body_ = i;
2169 bool Paragraph::allowParagraphCustomization() const
2171 return inInset().allowParagraphCustomization();
2175 bool Paragraph::usePlainLayout() const
2177 return inInset().usePlainLayout();
2181 bool Paragraph::isPassThru() const
2183 return inInset().isPassThru() || d->layout_->pass_thru;
2188 // paragraphs inside floats need different alignment tags to avoid
2191 bool noTrivlistCentering(InsetCode code)
2193 return code == FLOAT_CODE
2194 || code == WRAP_CODE
2195 || code == CELL_CODE;
2199 string correction(string const & orig)
2201 if (orig == "flushleft")
2202 return "raggedright";
2203 if (orig == "flushright")
2204 return "raggedleft";
2205 if (orig == "center")
2211 string const corrected_env(string const & suffix, string const & env,
2212 InsetCode code, bool const lastpar)
2214 string output = suffix + "{";
2215 if (noTrivlistCentering(code)) {
2217 // the last paragraph in non-trivlist-aligned
2218 // context is special (to avoid unwanted whitespace)
2219 if (suffix == "\\begin")
2220 return "\\" + correction(env) + "{}";
2223 output += correction(env);
2227 if (suffix == "\\begin")
2233 void adjust_column(string const & str, int & column)
2235 if (!contains(str, "\n"))
2236 column += str.size();
2239 column = rsplit(str, tmp, '\n').size();
2246 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2247 otexstream & os, OutputParams const & runparams) const
2251 if (params_.noindent() && !layout_->pass_thru
2252 && (layout_->toggle_indent != ITOGGLE_NEVER)) {
2253 os << "\\noindent ";
2257 LyXAlignment const curAlign = params_.align();
2259 if (curAlign == layout_->align)
2263 case LYX_ALIGN_NONE:
2264 case LYX_ALIGN_BLOCK:
2265 case LYX_ALIGN_LAYOUT:
2266 case LYX_ALIGN_SPECIAL:
2267 case LYX_ALIGN_DECIMAL:
2269 case LYX_ALIGN_LEFT:
2270 case LYX_ALIGN_RIGHT:
2271 case LYX_ALIGN_CENTER:
2272 if (runparams.moving_arg) {
2279 string const begin_tag = "\\begin";
2280 InsetCode code = ownerCode();
2281 bool const lastpar = runparams.isLastPar;
2284 case LYX_ALIGN_NONE:
2285 case LYX_ALIGN_BLOCK:
2286 case LYX_ALIGN_LAYOUT:
2287 case LYX_ALIGN_SPECIAL:
2288 case LYX_ALIGN_DECIMAL:
2290 case LYX_ALIGN_LEFT: {
2292 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2293 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2295 output = corrected_env(begin_tag, "flushright", code, lastpar);
2296 os << from_ascii(output);
2297 adjust_column(output, column);
2299 } case LYX_ALIGN_RIGHT: {
2301 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2302 output = corrected_env(begin_tag, "flushright", code, lastpar);
2304 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2305 os << from_ascii(output);
2306 adjust_column(output, column);
2308 } case LYX_ALIGN_CENTER: {
2310 output = corrected_env(begin_tag, "center", code, lastpar);
2311 os << from_ascii(output);
2312 adjust_column(output, column);
2321 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2322 otexstream & os, OutputParams const & runparams) const
2324 LyXAlignment const curAlign = params_.align();
2326 if (curAlign == layout_->align)
2330 case LYX_ALIGN_NONE:
2331 case LYX_ALIGN_BLOCK:
2332 case LYX_ALIGN_LAYOUT:
2333 case LYX_ALIGN_SPECIAL:
2334 case LYX_ALIGN_DECIMAL:
2336 case LYX_ALIGN_LEFT:
2337 case LYX_ALIGN_RIGHT:
2338 case LYX_ALIGN_CENTER:
2339 if (runparams.moving_arg)
2345 string const end_tag = "\n\\par\\end";
2346 InsetCode code = ownerCode();
2347 bool const lastpar = runparams.isLastPar;
2350 case LYX_ALIGN_NONE:
2351 case LYX_ALIGN_BLOCK:
2352 case LYX_ALIGN_LAYOUT:
2353 case LYX_ALIGN_SPECIAL:
2354 case LYX_ALIGN_DECIMAL:
2356 case LYX_ALIGN_LEFT: {
2357 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2358 output = corrected_env(end_tag, "flushleft", code, lastpar);
2360 output = corrected_env(end_tag, "flushright", code, lastpar);
2361 os << from_ascii(output);
2363 } case LYX_ALIGN_RIGHT: {
2364 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2365 output = corrected_env(end_tag, "flushright", code, lastpar);
2367 output = corrected_env(end_tag, "flushleft", code, lastpar);
2368 os << from_ascii(output);
2370 } case LYX_ALIGN_CENTER: {
2371 output = corrected_env(end_tag, "center", code, lastpar);
2372 os << from_ascii(output);
2377 return !output.empty() || lastpar;
2381 // This one spits out the text of the paragraph
2382 void Paragraph::latex(BufferParams const & bparams,
2383 Font const & outerfont,
2385 OutputParams const & runparams,
2386 int start_pos, int end_pos, bool force) const
2388 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2390 // FIXME This check should not be needed. Perhaps issue an
2391 // error if it triggers.
2392 Layout const & style = inInset().forcePlainLayout() ?
2393 bparams.documentClass().plainLayout() : *d->layout_;
2395 if (!force && style.inpreamble)
2398 bool const allowcust = allowParagraphCustomization();
2400 // Current base font for all inherited font changes, without any
2401 // change caused by an individual character, except for the language:
2402 // It is set to the language of the first character.
2403 // As long as we are in the label, this font is the base font of the
2404 // label. Before the first body character it is set to the base font
2408 // Maybe we have to create a optional argument.
2409 pos_type body_pos = beginOfBody();
2410 unsigned int column = 0;
2413 // the optional argument is kept in curly brackets in
2414 // case it contains a ']'
2415 // This is not strictly needed, but if this is changed it
2416 // would be a file format change, and tex2lyx would need
2417 // to be adjusted, since it unconditionally removes the
2418 // braces when it parses \item.
2421 basefont = getLabelFont(bparams, outerfont);
2423 basefont = getLayoutFont(bparams, outerfont);
2426 // Which font is currently active?
2427 Font running_font(basefont);
2428 // Do we have an open font change?
2429 bool open_font = false;
2431 Change runningChange = Change(Change::UNCHANGED);
2433 Encoding const * const prev_encoding = runparams.encoding;
2435 os.texrow().start(id(), 0);
2437 // if the paragraph is empty, the loop will not be entered at all
2439 if (style.isCommand()) {
2443 if (!style.leftdelim().empty()) {
2444 os << style.leftdelim();
2445 column += style.leftdelim().size();
2448 column += d->startTeXParParams(bparams, os, runparams);
2451 for (pos_type i = 0; i < size(); ++i) {
2452 // First char in paragraph or after label?
2453 if (i == body_pos) {
2456 column += running_font.latexWriteEndChanges(
2457 os, bparams, runparams,
2458 basefont, basefont);
2461 basefont = getLayoutFont(bparams, outerfont);
2462 running_font = basefont;
2464 column += Changes::latexMarkChange(os, bparams,
2465 runningChange, Change(Change::UNCHANGED),
2467 runningChange = Change(Change::UNCHANGED);
2472 if (style.isCommand()) {
2477 if (!style.leftdelim().empty()) {
2478 os << style.leftdelim();
2479 column += style.leftdelim().size();
2483 column += d->startTeXParParams(bparams, os,
2487 Change const & change = runparams.inDeletedInset
2488 ? runparams.changeOfDeletedInset : lookupChange(i);
2490 if (bparams.output_changes && runningChange != change) {
2492 column += running_font.latexWriteEndChanges(
2493 os, bparams, runparams, basefont, basefont);
2496 basefont = getLayoutFont(bparams, outerfont);
2497 running_font = basefont;
2499 column += Changes::latexMarkChange(os, bparams, runningChange,
2501 runningChange = change;
2504 // do not output text which is marked deleted
2505 // if change tracking output is disabled
2506 if (!bparams.output_changes && change.deleted()) {
2512 // Fully instantiated font
2513 Font const font = getFont(bparams, i, outerfont);
2515 Font const last_font = running_font;
2517 // Do we need to close the previous font?
2519 (font != running_font ||
2520 font.language() != running_font.language()))
2522 column += running_font.latexWriteEndChanges(
2523 os, bparams, runparams, basefont,
2524 (i == body_pos-1) ? basefont : font);
2525 running_font = basefont;
2529 string const running_lang = runparams.use_polyglossia ?
2530 running_font.language()->polyglossia() : running_font.language()->babel();
2531 // close babel's font environment before opening CJK.
2532 string const lang_end_command = runparams.use_polyglossia ?
2533 "\\end{$$lang}" : lyxrc.language_command_end;
2534 if (!running_lang.empty() &&
2535 font.language()->encoding()->package() == Encoding::CJK) {
2536 string end_tag = subst(lang_end_command,
2539 os << from_ascii(end_tag);
2540 column += end_tag.length();
2543 // Switch file encoding if necessary (and allowed)
2544 if (!runparams.pass_thru && !style.pass_thru &&
2545 runparams.encoding->package() != Encoding::none &&
2546 font.language()->encoding()->package() != Encoding::none) {
2547 pair<bool, int> const enc_switch =
2548 switchEncoding(os.os(), bparams, runparams,
2549 *(font.language()->encoding()));
2550 if (enc_switch.first) {
2551 column += enc_switch.second;
2552 runparams.encoding = font.language()->encoding();
2556 char_type const c = d->text_[i];
2558 // Do we need to change font?
2559 if ((font != running_font ||
2560 font.language() != running_font.language()) &&
2563 odocstringstream ods;
2564 column += font.latexWriteStartChanges(ods, bparams,
2565 runparams, basefont,
2567 running_font = font;
2569 docstring fontchange = ods.str();
2570 // check whether the fontchange ends with a \\textcolor
2571 // modifier and the text starts with a space (bug 4473)
2572 docstring const last_modifier = rsplit(fontchange, '\\');
2573 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2574 os << fontchange << from_ascii("{}");
2575 // check if the fontchange ends with a trailing blank
2576 // (like "\small " (see bug 3382)
2577 else if (suffixIs(fontchange, ' ') && c == ' ')
2578 os << fontchange.substr(0, fontchange.size() - 1)
2579 << from_ascii("{}");
2584 // FIXME: think about end_pos implementation...
2585 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2586 // FIXME: integrate this case in latexSpecialChar
2587 // Do not print the separation of the optional argument
2588 // if style.pass_thru is false. This works because
2589 // latexSpecialChar ignores spaces if
2590 // style.pass_thru is false.
2591 if (i != body_pos - 1) {
2592 if (d->simpleTeXBlanks(runparams, os,
2593 i, column, font, style)) {
2594 // A surrogate pair was output. We
2595 // must not call latexSpecialChar
2596 // in this iteration, since it would output
2597 // the combining character again.
2604 OutputParams rp = runparams;
2605 rp.free_spacing = style.free_spacing;
2606 rp.local_font = &font;
2607 rp.intitle = style.intitle;
2609 // Two major modes: LaTeX or plain
2610 // Handle here those cases common to both modes
2611 // and then split to handle the two modes separately.
2612 if (c == META_INSET) {
2613 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2614 d->latexInset(bparams, os, rp, running_font,
2615 basefont, outerfont, open_font,
2616 runningChange, style, i, column);
2619 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2621 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2622 style, i, end_pos, column);
2623 } catch (EncodingException & e) {
2624 if (runparams.dryrun) {
2625 os << "<" << _("LyX Warning: ")
2626 << _("uncodable character") << " '";
2630 // add location information and throw again.
2639 // Set the encoding to that returned from latexSpecialChar (see
2640 // comment for encoding member in OutputParams.h)
2641 runparams.encoding = rp.encoding;
2644 // If we have an open font definition, we have to close it
2646 #ifdef FIXED_LANGUAGE_END_DETECTION
2648 running_font.latexWriteEndChanges(os, bparams,
2649 runparams, basefont,
2650 next_->getFont(bparams, 0, outerfont));
2652 running_font.latexWriteEndChanges(os, bparams,
2653 runparams, basefont, basefont);
2656 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2657 //FIXME: there as we start another \selectlanguage with the next paragraph if
2658 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2659 running_font.latexWriteEndChanges(os, bparams, runparams,
2660 basefont, basefont);
2664 column += Changes::latexMarkChange(os, bparams, runningChange,
2665 Change(Change::UNCHANGED), runparams);
2667 // Needed if there is an optional argument but no contents.
2668 if (body_pos > 0 && body_pos == size()) {
2672 if (!style.rightdelim().empty()) {
2673 os << style.rightdelim();
2674 column += style.rightdelim().size();
2677 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2678 && runparams.encoding != prev_encoding) {
2679 runparams.encoding = prev_encoding;
2680 if (!runparams.isFullUnicode())
2681 os << setEncoding(prev_encoding->iconvName());
2684 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2688 bool Paragraph::emptyTag() const
2690 for (pos_type i = 0; i < size(); ++i) {
2691 if (Inset const * inset = getInset(i)) {
2692 InsetCode lyx_code = inset->lyxCode();
2693 // FIXME testing like that is wrong. What is
2695 if (lyx_code != TOC_CODE &&
2696 lyx_code != INCLUDE_CODE &&
2697 lyx_code != GRAPHICS_CODE &&
2698 lyx_code != ERT_CODE &&
2699 lyx_code != LISTINGS_CODE &&
2700 lyx_code != FLOAT_CODE &&
2701 lyx_code != TABULAR_CODE) {
2705 char_type c = d->text_[i];
2706 if (c != ' ' && c != '\t')
2714 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2717 for (pos_type i = 0; i < size(); ++i) {
2718 if (Inset const * inset = getInset(i)) {
2719 InsetCode lyx_code = inset->lyxCode();
2720 if (lyx_code == LABEL_CODE) {
2721 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2722 docstring const & id = il->getParam("name");
2723 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2731 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2735 for (i = 0; i < size(); ++i) {
2736 if (Inset const * inset = getInset(i)) {
2737 inset->docbook(os, runparams);
2739 char_type c = d->text_[i];
2742 os << sgml::escapeChar(c);
2749 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2753 for (i = 0; i < size(); ++i) {
2754 if (Inset const * inset = getInset(i)) {
2755 inset->xhtml(xs, runparams);
2757 char_type c = d->text_[i];
2767 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2770 pos_type size = text_.size();
2771 for (pos_type i = initial; i < size; ++i) {
2772 Font font = owner_->getFont(buf.params(), i, outerfont);
2773 if (text_[i] == META_INSET)
2775 if (i != initial && font != font_old)
2784 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2786 OutputParams const & runparams,
2787 Font const & outerfont,
2788 pos_type initial) const
2790 bool emph_flag = false;
2792 Layout const & style = *d->layout_;
2794 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2796 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2799 // parsing main loop
2800 for (pos_type i = initial; i < size(); ++i) {
2801 Font font = getFont(buf.params(), i, outerfont);
2803 // handle <emphasis> tag
2804 if (font_old.emph() != font.fontInfo().emph()) {
2805 if (font.fontInfo().emph() == FONT_ON) {
2808 } else if (i != initial) {
2809 os << "</emphasis>";
2814 if (Inset const * inset = getInset(i)) {
2815 inset->docbook(os, runparams);
2817 char_type c = d->text_[i];
2819 if (style.pass_thru)
2822 os << sgml::escapeChar(c);
2824 font_old = font.fontInfo();
2828 os << "</emphasis>";
2831 if (style.free_spacing)
2833 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2839 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2840 vector<html::EndFontTag> & tagsToClose,
2841 bool & flag, FontState curstate, html::FontTypes type)
2843 if (curstate == FONT_ON) {
2844 tagsToOpen.push_back(html::FontTag(type));
2847 tagsToClose.push_back(html::EndFontTag(type));
2854 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2856 OutputParams const & runparams,
2857 Font const & outerfont,
2858 pos_type initial) const
2862 // track whether we have opened these tags
2863 bool emph_flag = false;
2864 bool bold_flag = false;
2865 bool noun_flag = false;
2866 bool ubar_flag = false;
2867 bool dbar_flag = false;
2868 bool sout_flag = false;
2869 bool wave_flag = false;
2871 bool shap_flag = false;
2873 bool faml_flag = false;
2875 bool size_flag = false;
2877 Layout const & style = *d->layout_;
2879 xs.startParagraph(allowEmpty());
2882 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2884 FontShape curr_fs = INHERIT_SHAPE;
2885 FontFamily curr_fam = INHERIT_FAMILY;
2886 FontSize curr_size = FONT_SIZE_INHERIT;
2888 string const default_family =
2889 buf.masterBuffer()->params().fonts_default_family;
2891 vector<html::FontTag> tagsToOpen;
2892 vector<html::EndFontTag> tagsToClose;
2894 // parsing main loop
2895 for (pos_type i = initial; i < size(); ++i) {
2896 // let's not show deleted material in the output
2900 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2903 FontState curstate = font.fontInfo().emph();
2904 if (font_old.emph() != curstate)
2905 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2908 curstate = font.fontInfo().noun();
2909 if (font_old.noun() != curstate)
2910 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2913 curstate = font.fontInfo().underbar();
2914 if (font_old.underbar() != curstate)
2915 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2918 curstate = font.fontInfo().strikeout();
2919 if (font_old.strikeout() != curstate)
2920 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2923 curstate = font.fontInfo().uuline();
2924 if (font_old.uuline() != curstate)
2925 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2928 curstate = font.fontInfo().uwave();
2929 if (font_old.uwave() != curstate)
2930 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2933 // a little hackish, but allows us to reuse what we have.
2934 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2935 if (font_old.series() != font.fontInfo().series())
2936 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2939 curr_fs = font.fontInfo().shape();
2940 FontShape old_fs = font_old.shape();
2941 if (old_fs != curr_fs) {
2945 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2948 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2950 case SMALLCAPS_SHAPE:
2951 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2957 // the other tags are for internal use
2965 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2969 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2972 case SMALLCAPS_SHAPE:
2973 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2980 // the other tags are for internal use
2987 curr_fam = font.fontInfo().family();
2988 FontFamily old_fam = font_old.family();
2989 if (old_fam != curr_fam) {
2993 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2996 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2998 case TYPEWRITER_FAMILY:
2999 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3001 case INHERIT_FAMILY:
3004 // the other tags are for internal use
3012 // we will treat a "default" font family as roman, since we have
3013 // no other idea what to do.
3014 if (default_family != "rmdefault" && default_family != "default") {
3015 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3020 if (default_family != "sfdefault") {
3021 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3025 case TYPEWRITER_FAMILY:
3026 if (default_family != "ttdefault") {
3027 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3031 case INHERIT_FAMILY:
3034 // the other tags are for internal use
3041 curr_size = font.fontInfo().size();
3042 FontSize old_size = font_old.size();
3043 if (old_size != curr_size) {
3046 case FONT_SIZE_TINY:
3047 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3049 case FONT_SIZE_SCRIPT:
3050 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3052 case FONT_SIZE_FOOTNOTE:
3053 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3055 case FONT_SIZE_SMALL:
3056 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3058 case FONT_SIZE_LARGE:
3059 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3061 case FONT_SIZE_LARGER:
3062 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3064 case FONT_SIZE_LARGEST:
3065 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3067 case FONT_SIZE_HUGE:
3068 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3070 case FONT_SIZE_HUGER:
3071 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3073 case FONT_SIZE_INCREASE:
3074 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3076 case FONT_SIZE_DECREASE:
3077 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3079 case FONT_SIZE_INHERIT:
3080 case FONT_SIZE_NORMAL:
3083 // the other tags are for internal use
3089 switch (curr_size) {
3090 case FONT_SIZE_TINY:
3091 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3094 case FONT_SIZE_SCRIPT:
3095 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3098 case FONT_SIZE_FOOTNOTE:
3099 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3102 case FONT_SIZE_SMALL:
3103 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3106 case FONT_SIZE_LARGE:
3107 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3110 case FONT_SIZE_LARGER:
3111 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3114 case FONT_SIZE_LARGEST:
3115 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3118 case FONT_SIZE_HUGE:
3119 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3122 case FONT_SIZE_HUGER:
3123 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3126 case FONT_SIZE_INCREASE:
3127 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3130 case FONT_SIZE_DECREASE:
3131 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3134 case FONT_SIZE_NORMAL:
3135 case FONT_SIZE_INHERIT:
3138 // the other tags are for internal use
3145 // Other such tags? What about the other text ranges?
3147 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3148 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3149 for (; cit != cen; ++cit)
3152 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3153 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3154 for (; sit != sen; ++sit)
3157 tagsToClose.clear();
3160 Inset const * inset = getInset(i);
3162 if (!runparams.for_toc || inset->isInToc()) {
3163 OutputParams np = runparams;
3164 np.local_font = &font;
3165 if (!inset->getLayout().htmlisblock())
3166 np.html_in_par = true;
3167 retval += inset->xhtml(xs, np);
3170 char_type c = getUChar(buf.masterBuffer()->params(), i);
3172 if (style.pass_thru || runparams.pass_thru)
3174 else if (c == '-') {
3177 if (j < size() && d->text_[j] == '-') {
3179 if (j < size() && d->text_[j] == '-') {
3180 str += from_ascii("—");
3183 str += from_ascii("–");
3189 // We don't want to escape the entities. Note that
3190 // it is safe to do this, since str can otherwise
3191 // only be "-". E.g., it can't be "<".
3192 xs << XHTMLStream::ESCAPE_NONE << str;
3196 font_old = font.fontInfo();
3205 bool Paragraph::isHfill(pos_type pos) const
3207 Inset const * inset = getInset(pos);
3208 return inset && inset->isHfill();
3212 bool Paragraph::isNewline(pos_type pos) const
3214 Inset const * inset = getInset(pos);
3215 return inset && inset->lyxCode() == NEWLINE_CODE;
3219 bool Paragraph::isEnvSeparator(pos_type pos) const
3221 Inset const * inset = getInset(pos);
3222 return inset && inset->lyxCode() == SEPARATOR_CODE;
3226 bool Paragraph::isLineSeparator(pos_type pos) const
3228 char_type const c = d->text_[pos];
3229 if (isLineSeparatorChar(c))
3231 Inset const * inset = getInset(pos);
3232 return inset && inset->isLineSeparator();
3236 bool Paragraph::isWordSeparator(pos_type pos) const
3240 if (Inset const * inset = getInset(pos))
3241 return !inset->isLetter();
3242 // if we have a hard hyphen (no en- or emdash) or apostrophe
3243 // we pass this to the spell checker
3244 // FIXME: this method is subject to change, visit
3245 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3246 // to get an impression how complex this is.
3247 if (isHardHyphenOrApostrophe(pos))
3249 char_type const c = d->text_[pos];
3250 // We want to pass the escape chars to the spellchecker
3251 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3252 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3256 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3258 pos_type const psize = size();
3261 char_type const c = d->text_[pos];
3262 if (c != '-' && c != '\'')
3264 int nextpos = pos + 1;
3265 int prevpos = pos > 0 ? pos - 1 : 0;
3266 if ((nextpos == psize || isSpace(nextpos))
3267 && (pos == 0 || isSpace(prevpos)))
3270 || ((nextpos == psize || d->text_[nextpos] != '-')
3271 && (pos == 0 || d->text_[prevpos] != '-'));
3275 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
3278 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
3282 bool Paragraph::isChar(pos_type pos) const
3284 if (Inset const * inset = getInset(pos))
3285 return inset->isChar();
3286 char_type const c = d->text_[pos];
3287 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3291 bool Paragraph::isSpace(pos_type pos) const
3293 if (Inset const * inset = getInset(pos))
3294 return inset->isSpace();
3295 char_type const c = d->text_[pos];
3296 return lyx::isSpace(c);
3301 Paragraph::getParLanguage(BufferParams const & bparams) const
3304 return getFirstFontSettings(bparams).language();
3305 // FIXME: we should check the prev par as well (Lgb)
3306 return bparams.language;
3310 bool Paragraph::isRTL(BufferParams const & bparams) const
3312 return getParLanguage(bparams)->rightToLeft()
3313 && !inInset().getLayout().forceLTR();
3317 void Paragraph::changeLanguage(BufferParams const & bparams,
3318 Language const * from, Language const * to)
3320 // change language including dummy font change at the end
3321 for (pos_type i = 0; i <= size(); ++i) {
3322 Font font = getFontSettings(bparams, i);
3323 if (font.language() == from) {
3324 font.setLanguage(to);
3326 d->requestSpellCheck(i);
3332 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3334 Language const * doc_language = bparams.language;
3335 FontList::const_iterator cit = d->fontlist_.begin();
3336 FontList::const_iterator end = d->fontlist_.end();
3338 for (; cit != end; ++cit)
3339 if (cit->font().language() != ignore_language &&
3340 cit->font().language() != latex_language &&
3341 cit->font().language() != doc_language)
3347 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3349 FontList::const_iterator cit = d->fontlist_.begin();
3350 FontList::const_iterator end = d->fontlist_.end();
3352 for (; cit != end; ++cit) {
3353 Language const * lang = cit->font().language();
3354 if (lang != ignore_language &&
3355 lang != latex_language)
3356 languages.insert(lang);
3361 docstring Paragraph::asString(int options) const
3363 return asString(0, size(), options);
3367 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3369 odocstringstream os;
3372 && options & AS_STR_LABEL
3373 && !d->params_.labelString().empty())
3374 os << d->params_.labelString() << ' ';
3376 for (pos_type i = beg; i < end; ++i) {
3377 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3379 char_type const c = d->text_[i];
3380 if (isPrintable(c) || c == '\t'
3381 || (c == '\n' && (options & AS_STR_NEWLINES)))
3383 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3384 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3385 LASSERT(runparams != 0, return docstring());
3386 getInset(i)->plaintext(os, *runparams);
3388 getInset(i)->toString(os);
3397 void Paragraph::forOutliner(docstring & os, size_t maxlen) const
3399 if (!d->params_.labelString().empty())
3400 os += d->params_.labelString() + ' ';
3401 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3404 char_type const c = d->text_[i];
3407 else if (c == '\t' || c == '\n')
3409 else if (c == META_INSET)
3410 getInset(i)->forOutliner(os, maxlen);
3415 void Paragraph::setInsetOwner(Inset const * inset)
3417 d->inset_owner_ = inset;
3421 int Paragraph::id() const
3427 void Paragraph::setId(int id)
3433 Layout const & Paragraph::layout() const
3439 void Paragraph::setLayout(Layout const & layout)
3441 d->layout_ = &layout;
3445 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3447 setLayout(tc.defaultLayout());
3451 void Paragraph::setPlainLayout(DocumentClass const & tc)
3453 setLayout(tc.plainLayout());
3457 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3459 if (usePlainLayout())
3460 setPlainLayout(tclass);
3462 setDefaultLayout(tclass);
3466 Inset const & Paragraph::inInset() const
3468 LBUFERR(d->inset_owner_);
3469 return *d->inset_owner_;
3473 ParagraphParameters & Paragraph::params()
3479 ParagraphParameters const & Paragraph::params() const
3485 bool Paragraph::isFreeSpacing() const
3487 if (d->layout_->free_spacing)
3489 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3493 bool Paragraph::allowEmpty() const
3495 if (d->layout_->keepempty)
3497 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3501 bool Paragraph::brokenBiblio() const
3503 // there is a problem if there is no bibitem at position 0 or
3504 // if there is another bibitem in the paragraph.
3505 return d->layout_->labeltype == LABEL_BIBLIO
3506 && (d->insetlist_.find(BIBITEM_CODE) != 0
3507 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3511 int Paragraph::fixBiblio(Buffer const & buffer)
3513 // FIXME: What about the case where paragraph is not BIBLIO
3514 // but there is an InsetBibitem?
3515 // FIXME: when there was already an inset at 0, the return value is 1,
3516 // which does not tell whether another inset has been remove; the
3517 // cursor cannot be correctly updated.
3519 if (d->layout_->labeltype != LABEL_BIBLIO)
3522 bool const track_changes = buffer.params().track_changes;
3523 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3524 bool const hasbibitem0 = bibitem_pos == 0;
3527 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3528 // There was an InsetBibitem at pos 0, and no other one => OK
3529 if (bibitem_pos == -1)
3531 // there is a bibitem at the 0 position, but since
3532 // there is a second one, we copy the second on the
3533 // first. We're assuming there are at most two of
3534 // these, which there should be.
3535 // FIXME: why does it make sense to do that rather
3536 // than keep the first? (JMarc)
3537 Inset * inset = releaseInset(bibitem_pos);
3538 d->insetlist_.begin()->inset = inset;
3539 return -bibitem_pos;
3542 // We need to create an inset at the beginning
3544 if (bibitem_pos > 0) {
3545 // there was one somewhere in the paragraph, let's move it
3546 inset = d->insetlist_.release(bibitem_pos);
3547 eraseChar(bibitem_pos, track_changes);
3550 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3551 InsetCommandParams(BIBITEM_CODE));
3553 Font font(inherit_font, buffer.params().language);
3554 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3555 : Change::UNCHANGED));
3561 void Paragraph::checkAuthors(AuthorList const & authorList)
3563 d->changes_.checkAuthors(authorList);
3567 bool Paragraph::isChanged(pos_type pos) const
3569 return lookupChange(pos).changed();
3573 bool Paragraph::isInserted(pos_type pos) const
3575 return lookupChange(pos).inserted();
3579 bool Paragraph::isDeleted(pos_type pos) const
3581 return lookupChange(pos).deleted();
3585 InsetList const & Paragraph::insetList() const
3587 return d->insetlist_;
3591 void Paragraph::setBuffer(Buffer & b)
3593 d->insetlist_.setBuffer(b);
3597 Inset * Paragraph::releaseInset(pos_type pos)
3599 Inset * inset = d->insetlist_.release(pos);
3600 /// does not honour change tracking!
3601 eraseChar(pos, false);
3606 Inset * Paragraph::getInset(pos_type pos)
3608 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3609 ? d->insetlist_.get(pos) : 0;
3613 Inset const * Paragraph::getInset(pos_type pos) const
3615 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3616 ? d->insetlist_.get(pos) : 0;
3620 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3621 pos_type & right, TextCase action)
3623 // process sequences of modified characters; in change
3624 // tracking mode, this approach results in much better
3625 // usability than changing case on a char-by-char basis
3626 // We also need to track the current font, since font
3627 // changes within sequences can occur.
3628 vector<pair<char_type, Font> > changes;
3630 bool const trackChanges = bparams.track_changes;
3632 bool capitalize = true;
3634 for (; pos < right; ++pos) {
3635 char_type oldChar = d->text_[pos];
3636 char_type newChar = oldChar;
3638 // ignore insets and don't play with deleted text!
3639 if (oldChar != META_INSET && !isDeleted(pos)) {
3641 case text_lowercase:
3642 newChar = lowercase(oldChar);
3644 case text_capitalization:
3646 newChar = uppercase(oldChar);
3650 case text_uppercase:
3651 newChar = uppercase(oldChar);
3656 if (isWordSeparator(pos) || isDeleted(pos)) {
3657 // permit capitalization again
3661 if (oldChar != newChar) {
3662 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3663 if (pos != right - 1)
3665 // step behind the changing area
3669 int erasePos = pos - changes.size();
3670 for (size_t i = 0; i < changes.size(); i++) {
3671 insertChar(pos, changes[i].first,
3674 if (!eraseChar(erasePos, trackChanges)) {
3677 ++right; // expand selection
3685 int Paragraph::find(docstring const & str, bool cs, bool mw,
3686 pos_type start_pos, bool del) const
3688 pos_type pos = start_pos;
3689 int const strsize = str.length();
3691 pos_type const parsize = d->text_.size();
3692 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3693 // Ignore "invisible" letters such as ligature breaks
3694 // and hyphenation chars while searching
3695 while (pos < parsize - 1 && isInset(pos)) {
3696 odocstringstream os;
3697 getInset(pos)->toString(os);
3698 if (!getInset(pos)->isLetter() || !os.str().empty())
3702 if (cs && str[i] != d->text_[pos])
3704 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3706 if (!del && isDeleted(pos))
3713 // if necessary, check whether string matches word
3715 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3718 && !isWordSeparator(pos))
3722 return pos - start_pos;
3726 char_type Paragraph::getChar(pos_type pos) const
3728 return d->text_[pos];
3732 pos_type Paragraph::size() const
3734 return d->text_.size();
3738 bool Paragraph::empty() const
3740 return d->text_.empty();
3744 bool Paragraph::isInset(pos_type pos) const
3746 return d->text_[pos] == META_INSET;
3750 bool Paragraph::isSeparator(pos_type pos) const
3752 //FIXME: Are we sure this can be the only separator?
3753 return d->text_[pos] == ' ';
3757 void Paragraph::deregisterWords()
3759 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3760 Private::LangWordsMap::const_iterator ite = d->words_.end();
3761 for (; itl != ite; ++itl) {
3762 WordList * wl = theWordList(itl->first);
3763 Private::Words::const_iterator it = (itl->second).begin();
3764 Private::Words::const_iterator et = (itl->second).end();
3765 for (; it != et; ++it)
3772 void Paragraph::locateWord(pos_type & from, pos_type & to,
3773 word_location const loc) const
3776 case WHOLE_WORD_STRICT:
3777 if (from == 0 || from == size()
3778 || isWordSeparator(from)
3779 || isWordSeparator(from - 1)) {
3783 // no break here, we go to the next
3786 // If we are already at the beginning of a word, do nothing
3787 if (!from || isWordSeparator(from - 1))
3789 // no break here, we go to the next
3792 // always move the cursor to the beginning of previous word
3793 while (from && !isWordSeparator(from - 1))
3797 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3800 // no need to move the 'from' cursor
3804 while (to < size() && !isWordSeparator(to))
3809 void Paragraph::collectWords()
3811 for (pos_type pos = 0; pos < size(); ++pos) {
3812 if (isWordSeparator(pos))
3814 pos_type from = pos;
3815 locateWord(from, pos, WHOLE_WORD);
3816 // Work around MSVC warning: The statement
3817 // if (pos < from + lyxrc.completion_minlength)
3818 // triggers a signed vs. unsigned warning.
3819 // I don't know why this happens, it could be a MSVC bug, or
3820 // related to LLP64 (windows) vs. LP64 (unix) programming
3821 // model, or the C++ standard might be ambigous in the section
3822 // defining the "usual arithmetic conversions". However, using
3823 // a temporary variable is safe and works on all compilers.
3824 pos_type const endpos = from + lyxrc.completion_minlength;
3827 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3828 if (cit == d->fontlist_.end())
3830 Language const * lang = cit->font().language();
3831 docstring const word = asString(from, pos, AS_STR_NONE);
3832 d->words_[lang->lang()].insert(word);
3837 void Paragraph::registerWords()
3839 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3840 Private::LangWordsMap::const_iterator ite = d->words_.end();
3841 for (; itl != ite; ++itl) {
3842 WordList * wl = theWordList(itl->first);
3843 Private::Words::const_iterator it = (itl->second).begin();
3844 Private::Words::const_iterator et = (itl->second).end();
3845 for (; it != et; ++it)
3851 void Paragraph::updateWords()
3859 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3861 SkipPositionsIterator begin = skips.begin();
3862 SkipPositions::iterator end = skips.end();
3863 if (pos > 0 && begin < end) {
3865 if (end->last == pos - 1) {
3870 skips.insert(end, FontSpan(pos, pos));
3874 Language * Paragraph::Private::locateSpellRange(
3875 pos_type & from, pos_type & to,
3876 SkipPositions & skips) const
3878 // skip leading white space
3879 while (from < to && owner_->isWordSeparator(from))
3881 // don't check empty range
3884 // get current language
3885 Language * lang = getSpellLanguage(from);
3886 pos_type last = from;
3887 bool samelang = true;
3888 bool sameinset = true;
3889 while (last < to && samelang && sameinset) {
3890 // hop to end of word
3891 while (last < to && !owner_->isWordSeparator(last)) {
3892 if (owner_->getInset(last)) {
3893 appendSkipPosition(skips, last);
3894 } else if (owner_->isDeleted(last)) {
3895 appendSkipPosition(skips, last);
3899 // hop to next word while checking for insets
3900 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3901 if (Inset const * inset = owner_->getInset(last))
3902 sameinset = inset->isChar() && inset->isLetter();
3903 if (sameinset && owner_->isDeleted(last)) {
3904 appendSkipPosition(skips, last);
3909 if (sameinset && last < to) {
3910 // now check for language change
3911 samelang = lang == getSpellLanguage(last);
3914 // if language change detected backstep is needed
3922 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3925 const_cast<Language *>(owner_->getFontSettings(
3926 inset_owner_->buffer().params(), from).language());
3927 if (lang == inset_owner_->buffer().params().language
3928 && !lyxrc.spellchecker_alt_lang.empty()) {
3930 string const lang_variety =
3931 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3932 lang->setCode(lang_code);
3933 lang->setVariety(lang_variety);
3939 void Paragraph::requestSpellCheck(pos_type pos)
3941 d->requestSpellCheck(pos);
3945 bool Paragraph::needsSpellCheck() const
3947 SpellChecker::ChangeNumber speller_change_number = 0;
3948 if (theSpellChecker())
3949 speller_change_number = theSpellChecker()->changeNumber();
3950 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3951 d->speller_state_.needsCompleteRefresh(speller_change_number);
3953 return d->needsSpellCheck();
3957 bool Paragraph::Private::ignoreWord(docstring const & word) const
3959 // Ignore words with digits
3960 // FIXME: make this customizable
3961 // (note that some checkers ignore words with digits by default)
3962 docstring::const_iterator cit = word.begin();
3963 docstring::const_iterator const end = word.end();
3964 for (; cit != end; ++cit) {
3965 if (isNumber((*cit)))
3972 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3973 WordLangTuple & wl, docstring_list & suggestions,
3974 bool do_suggestion, bool check_learned) const
3976 SpellChecker::Result result = SpellChecker::WORD_OK;
3977 SpellChecker * speller = theSpellChecker();
3981 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3984 locateWord(from, to, WHOLE_WORD);
3985 if (from == to || from >= size())
3988 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3989 Language * lang = d->getSpellLanguage(from);
3991 wl = WordLangTuple(word, lang);
3996 if (needsSpellCheck() || check_learned) {
3998 if (!d->ignoreWord(word)) {
3999 bool const trailing_dot = to < size() && d->text_[to] == '.';
4000 result = speller->check(wl);
4001 if (SpellChecker::misspelled(result) && trailing_dot) {
4002 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4003 result = speller->check(wl);
4004 if (!SpellChecker::misspelled(result)) {
4005 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4007 from << ".." << to << "]");
4009 // spell check with dot appended failed too
4010 // restore original word/lang value
4011 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4012 wl = WordLangTuple(word, lang);
4016 if (!SpellChecker::misspelled(result)) {
4017 // area up to the begin of the next word is not misspelled
4018 while (end < size() && isWordSeparator(end))
4021 d->setMisspelled(from, end, result);
4023 result = d->speller_state_.getState(from);
4027 suggestions.clear();
4029 if (SpellChecker::misspelled(result)) {
4030 LYXERR(Debug::GUI, "misspelled word: \"" <<
4032 from << ".." << to << "]");
4034 speller->suggest(wl, suggestions);
4040 void Paragraph::Private::markMisspelledWords(
4041 pos_type const & first, pos_type const & last,
4042 SpellChecker::Result result,
4043 docstring const & word,
4044 SkipPositions const & skips)
4046 if (!SpellChecker::misspelled(result)) {
4047 setMisspelled(first, last, SpellChecker::WORD_OK);
4051 SpellChecker * speller = theSpellChecker();
4052 // locate and enumerate the error positions
4053 int nerrors = speller->numMisspelledWords();
4055 SkipPositionsIterator it = skips.begin();
4056 SkipPositionsIterator et = skips.end();
4057 for (int index = 0; index < nerrors; ++index) {
4060 speller->misspelledWord(index, wstart, wlen);
4061 /// should not happen if speller supports range checks
4062 if (!wlen) continue;
4063 docstring const misspelled = word.substr(wstart, wlen);
4064 wstart += first + numskipped;
4065 if (snext < wstart) {
4066 /// mark the range of correct spelling
4067 numskipped += countSkips(it, et, wstart);
4068 setMisspelled(snext,
4069 wstart - 1, SpellChecker::WORD_OK);
4071 snext = wstart + wlen;
4072 numskipped += countSkips(it, et, snext);
4073 /// mark the range of misspelling
4074 setMisspelled(wstart, snext, result);
4075 LYXERR(Debug::GUI, "misspelled word: \"" <<
4076 misspelled << "\" [" <<
4077 wstart << ".." << (snext-1) << "]");
4080 if (snext <= last) {
4081 /// mark the range of correct spelling at end
4082 setMisspelled(snext, last, SpellChecker::WORD_OK);
4087 void Paragraph::spellCheck() const
4089 SpellChecker * speller = theSpellChecker();
4090 if (!speller || empty() ||!needsSpellCheck())
4094 d->rangeOfSpellCheck(start, endpos);
4095 if (speller->canCheckParagraph()) {
4096 // loop until we leave the range
4097 for (pos_type first = start; first < endpos; ) {
4098 pos_type last = endpos;
4099 Private::SkipPositions skips;
4100 Language * lang = d->locateSpellRange(first, last, skips);
4101 if (first >= endpos)
4103 // start the spell checker on the unit of meaning
4104 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4105 WordLangTuple wl = WordLangTuple(word, lang);
4106 SpellChecker::Result result = word.size() ?
4107 speller->check(wl) : SpellChecker::WORD_OK;
4108 d->markMisspelledWords(first, last, result, word, skips);
4112 static docstring_list suggestions;
4113 pos_type to = endpos;
4114 while (start < endpos) {
4116 spellCheck(start, to, wl, suggestions, false);
4120 d->readySpellCheck();
4124 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4126 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4127 if (result || pos <= 0 || pos > size())
4129 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4130 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4135 string Paragraph::magicLabel() const
4138 ss << "magicparlabel-" << id();