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
287 Private(Paragraph * owner, Layout const & layout);
288 /// "Copy constructor"
289 Private(Private const &, Paragraph * owner);
290 /// Copy constructor from \p beg to \p end
291 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
294 void insertChar(pos_type pos, char_type c, Change const & change);
296 /// Output the surrogate pair formed by \p c and \p next to \p os.
297 /// \return the number of characters written.
298 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
299 OutputParams const &);
301 /// Output a space in appropriate formatting (or a surrogate pair
302 /// if the next character is a combining character).
303 /// \return whether a surrogate pair was output.
304 bool simpleTeXBlanks(OutputParams const &,
307 unsigned int & column,
309 Layout const & style);
311 /// Output consecutive unicode chars, belonging to the same script as
312 /// specified by the latex macro \p ltx, to \p os starting from \p i.
313 /// \return the number of characters written.
314 int writeScriptChars(otexstream & os, docstring const & ltx,
315 Change const &, Encoding const &, pos_type & i);
317 /// This could go to ParagraphParameters if we want to.
318 int startTeXParParams(BufferParams const &, otexstream &,
319 OutputParams const &) const;
321 /// This could go to ParagraphParameters if we want to.
322 bool endTeXParParams(BufferParams const &, otexstream &,
323 OutputParams const &) const;
326 void latexInset(BufferParams const &,
331 Font const & outerfont,
333 Change & running_change,
334 Layout const & style,
336 unsigned int & column);
339 void latexSpecialChar(
341 BufferParams const & bparams,
342 OutputParams const & runparams,
343 Font const & running_font,
344 Change const & running_change,
345 Layout const & style,
348 unsigned int & column);
355 unsigned int & column);
361 unsigned int & column);
363 bool latexSpecialTypewriter(
367 unsigned int & column);
369 bool latexSpecialPhrase(
373 unsigned int & column,
374 OutputParams const & runparams);
377 void validate(LaTeXFeatures & features) const;
379 /// Checks if the paragraph contains only text and no inset or font change.
380 bool onlyText(Buffer const & buf, Font const & outerfont,
381 pos_type initial) const;
383 /// match a string against a particular point in the paragraph
384 bool isTextAt(string const & str, pos_type pos) const;
386 /// a vector of speller skip positions
387 typedef vector<FontSpan> SkipPositions;
388 typedef SkipPositions::const_iterator SkipPositionsIterator;
390 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
392 Language * getSpellLanguage(pos_type const from) const;
394 Language * locateSpellRange(pos_type & from, pos_type & to,
395 SkipPositions & skips) const;
397 bool hasSpellerChange() const
399 SpellChecker::ChangeNumber speller_change_number = 0;
400 if (theSpellChecker())
401 speller_change_number = theSpellChecker()->changeNumber();
402 return speller_change_number > speller_state_.currentChangeNumber();
405 bool ignoreWord(docstring const & word) const ;
407 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
409 pos_type textsize = owner_->size();
410 // check for sane arguments
411 if (to <= from || from >= textsize)
413 FontSpan fp = FontSpan(from, to - 1);
414 speller_state_.setRange(fp, state);
417 void requestSpellCheck(pos_type pos)
420 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
422 speller_state_.needsRefresh(pos);
425 void readySpellCheck()
427 speller_state_.needsRefresh(-1);
430 bool needsSpellCheck() const
432 return speller_state_.needsRefresh();
435 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
437 speller_state_.refreshRange(first, last);
439 last = owner_->size();
442 pos_type endpos = last;
443 owner_->locateWord(first, endpos, WHOLE_WORD);
446 owner_->locateWord(last, endpos, WHOLE_WORD);
451 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
455 while (it != et && it->first < start) {
456 int skip = it->last - it->first + 1;
464 void markMisspelledWords(pos_type const & first, pos_type const & last,
465 SpellChecker::Result result,
466 docstring const & word,
467 SkipPositions const & skips);
469 InsetCode ownerCode() const
471 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
474 /// Which Paragraph owns us?
478 Inset const * inset_owner_;
487 ParagraphParameters params_;
489 /// for recording and looking up changes
493 InsetList insetlist_;
496 pos_type begin_of_body_;
498 typedef docstring TextContainer;
502 typedef set<docstring> Words;
503 typedef map<string, Words> LangWordsMap;
507 Layout const * layout_;
509 SpellCheckerState speller_state_;
515 struct special_phrase {
521 special_phrase const special_phrases[] = {
522 { "LyX", from_ascii("\\LyX{}"), false },
523 { "TeX", from_ascii("\\TeX{}"), true },
524 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
525 { "LaTeX", from_ascii("\\LaTeX{}"), true },
528 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
533 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
534 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
540 // Initialization of the counter for the paragraph id's,
542 // FIXME: There should be a more intelligent way to generate and use the
543 // paragraph ids per buffer instead a global static counter for all InsetText
544 // in the running program.
545 static int paragraph_id = -1;
547 Paragraph::Private::Private(Private const & p, Paragraph * owner)
548 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
549 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
550 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
553 id_ = ++paragraph_id;
554 requestSpellCheck(p.text_.size());
558 Paragraph::Private::Private(Private const & p, Paragraph * owner,
559 pos_type beg, pos_type end)
560 : owner_(owner), inset_owner_(p.inset_owner_),
561 params_(p.params_), changes_(p.changes_),
562 insetlist_(p.insetlist_, beg, end),
563 begin_of_body_(p.begin_of_body_), words_(p.words_),
566 id_ = ++paragraph_id;
567 if (beg >= pos_type(p.text_.size()))
569 text_ = p.text_.substr(beg, end - beg);
571 FontList::const_iterator fcit = fontlist_.begin();
572 FontList::const_iterator fend = fontlist_.end();
573 for (; fcit != fend; ++fcit) {
574 if (fcit->pos() < beg)
576 if (fcit->pos() >= end) {
577 // Add last entry in the fontlist_.
578 fontlist_.set(text_.size() - 1, fcit->font());
581 // Add a new entry in the fontlist_.
582 fontlist_.set(fcit->pos() - beg, fcit->font());
584 requestSpellCheck(p.text_.size());
588 void Paragraph::addChangesToToc(DocIterator const & cdit,
589 Buffer const & buf, bool output_active) const
591 d->changes_.addToToc(cdit, buf, output_active);
595 bool Paragraph::isDeleted(pos_type start, pos_type end) const
597 LASSERT(start >= 0 && start <= size(), return false);
598 LASSERT(end > start && end <= size() + 1, return false);
600 return d->changes_.isDeleted(start, end);
604 bool Paragraph::isChanged(pos_type start, pos_type end) const
606 LASSERT(start >= 0 && start <= size(), return false);
607 LASSERT(end > start && end <= size() + 1, return false);
609 return d->changes_.isChanged(start, end);
613 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
615 // keep the logic here in sync with the logic of eraseChars()
619 Change const change = d->changes_.lookup(size());
620 return change.inserted() && change.currentAuthor();
624 void Paragraph::setChange(Change const & change)
626 // beware of the imaginary end-of-par character!
627 d->changes_.set(change, 0, size() + 1);
630 * Propagate the change recursively - but not in case of DELETED!
632 * Imagine that your co-author makes changes in an existing inset. He
633 * sends your document to you and you come to the conclusion that the
634 * inset should go completely. If you erase it, LyX must not delete all
635 * text within the inset. Otherwise, the change tracked insertions of
636 * your co-author get lost and there is no way to restore them later.
638 * Conclusion: An inset's content should remain untouched if you delete it
641 if (!change.deleted()) {
642 for (pos_type pos = 0; pos < size(); ++pos) {
643 if (Inset * inset = getInset(pos))
644 inset->setChange(change);
650 void Paragraph::setChange(pos_type pos, Change const & change)
652 LASSERT(pos >= 0 && pos <= size(), return);
653 d->changes_.set(change, pos);
655 // see comment in setChange(Change const &) above
656 if (!change.deleted() && pos < size())
657 if (Inset * inset = getInset(pos))
658 inset->setChange(change);
662 Change const & Paragraph::lookupChange(pos_type pos) const
664 LBUFERR(pos >= 0 && pos <= size());
665 return d->changes_.lookup(pos);
669 void Paragraph::acceptChanges(pos_type start, pos_type end)
671 LASSERT(start >= 0 && start <= size(), return);
672 LASSERT(end > start && end <= size() + 1, return);
674 for (pos_type pos = start; pos < end; ++pos) {
675 switch (lookupChange(pos).type) {
676 case Change::UNCHANGED:
677 // accept changes in nested inset
678 if (Inset * inset = getInset(pos))
679 inset->acceptChanges();
682 case Change::INSERTED:
683 d->changes_.set(Change(Change::UNCHANGED), pos);
684 // also accept changes in nested inset
685 if (Inset * inset = getInset(pos))
686 inset->acceptChanges();
689 case Change::DELETED:
690 // Suppress access to non-existent
691 // "end-of-paragraph char"
693 eraseChar(pos, false);
704 void Paragraph::rejectChanges(pos_type start, pos_type end)
706 LASSERT(start >= 0 && start <= size(), return);
707 LASSERT(end > start && end <= size() + 1, return);
709 for (pos_type pos = start; pos < end; ++pos) {
710 switch (lookupChange(pos).type) {
711 case Change::UNCHANGED:
712 // reject changes in nested inset
713 if (Inset * inset = getInset(pos))
714 inset->rejectChanges();
717 case Change::INSERTED:
718 // Suppress access to non-existent
719 // "end-of-paragraph char"
721 eraseChar(pos, false);
727 case Change::DELETED:
728 d->changes_.set(Change(Change::UNCHANGED), pos);
730 // Do NOT reject changes within a deleted inset!
731 // There may be insertions of a co-author inside of it!
739 void Paragraph::Private::insertChar(pos_type pos, char_type c,
740 Change const & change)
742 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
745 changes_.insert(change, pos);
747 // This is actually very common when parsing buffers (and
748 // maybe inserting ascii text)
749 if (pos == pos_type(text_.size())) {
750 // when appending characters, no need to update tables
752 // but we want spell checking
753 requestSpellCheck(pos);
757 text_.insert(text_.begin() + pos, c);
759 // Update the font table.
760 fontlist_.increasePosAfterPos(pos);
763 insetlist_.increasePosAfterPos(pos);
765 // Update list of misspelled positions
766 speller_state_.increasePosAfterPos(pos);
770 bool Paragraph::insertInset(pos_type pos, Inset * inset,
771 Font const & font, Change const & change)
773 LASSERT(inset, return false);
774 LASSERT(pos >= 0 && pos <= size(), return false);
776 // Paragraph::insertInset() can be used in cut/copy/paste operation where
777 // d->inset_owner_ is not set yet.
778 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
781 d->insertChar(pos, META_INSET, change);
782 LASSERT(d->text_[pos] == META_INSET, return false);
784 // Add a new entry in the insetlist_.
785 d->insetlist_.insert(inset, pos);
787 // Some insets require run of spell checker
788 requestSpellCheck(pos);
794 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
796 LASSERT(pos >= 0 && pos <= size(), return false);
798 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
801 Change change = d->changes_.lookup(pos);
803 // set the character to DELETED if
804 // a) it was previously unchanged or
805 // b) it was inserted by a co-author
807 if (!change.changed() ||
808 (change.inserted() && !change.currentAuthor())) {
809 setChange(pos, Change(Change::DELETED));
810 // request run of spell checker
811 requestSpellCheck(pos);
815 if (change.deleted())
819 // Don't physically access the imaginary end-of-paragraph character.
820 // eraseChar() can only mark it as DELETED. A physical deletion of
821 // end-of-par must be handled externally.
827 d->changes_.erase(pos);
829 // if it is an inset, delete the inset entry
830 if (d->text_[pos] == META_INSET)
831 d->insetlist_.erase(pos);
833 d->text_.erase(d->text_.begin() + pos);
835 // Update the fontlist_
836 d->fontlist_.erase(pos);
838 // Update the insetlist_
839 d->insetlist_.decreasePosAfterPos(pos);
841 // Update list of misspelled positions
842 d->speller_state_.decreasePosAfterPos(pos);
843 d->speller_state_.refreshLast(size());
849 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
851 LASSERT(start >= 0 && start <= size(), return 0);
852 LASSERT(end >= start && end <= size() + 1, return 0);
855 for (pos_type count = end - start; count; --count) {
856 if (!eraseChar(i, trackChanges))
863 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
864 char_type next, OutputParams const & runparams)
866 // Writing next here may circumvent a possible font change between
867 // c and next. Since next is only output if it forms a surrogate pair
868 // with c we can ignore this:
869 // A font change inside a surrogate pair does not make sense and is
870 // hopefully impossible to input.
871 // FIXME: change tracking
872 // Is this correct WRT change tracking?
873 Encoding const & encoding = *(runparams.encoding);
874 docstring latex1 = encoding.latexChar(next).first;
875 if (runparams.inIPA) {
876 string const tipashortcut = Encodings::TIPAShortcut(next);
877 if (!tipashortcut.empty()) {
878 latex1 = from_ascii(tipashortcut);
881 docstring const latex2 = encoding.latexChar(c).first;
882 if (docstring(1, next) == latex1) {
883 // the encoding supports the combination
884 os << latex2 << latex1;
885 return latex1.length() + latex2.length();
886 } else if (runparams.local_font &&
887 runparams.local_font->language()->lang() == "polutonikogreek") {
888 // polutonikogreek only works without the brackets
889 os << latex1 << latex2;
890 return latex1.length() + latex2.length();
892 os << latex1 << '{' << latex2 << '}';
893 return latex1.length() + latex2.length() + 2;
897 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
900 unsigned int & column,
902 Layout const & style)
904 if (style.pass_thru || runparams.pass_thru)
907 if (i + 1 < int(text_.size())) {
908 char_type next = text_[i + 1];
909 if (Encodings::isCombiningChar(next)) {
910 // This space has an accent, so we must always output it.
911 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
916 if (runparams.linelen > 0
917 && column > runparams.linelen
919 && text_[i - 1] != ' '
920 && (i + 1 < int(text_.size()))
921 // same in FreeSpacing mode
922 && !owner_->isFreeSpacing()
923 // In typewriter mode, we want to avoid
924 // ! . ? : at the end of a line
925 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
926 && (text_[i - 1] == '.'
927 || text_[i - 1] == '?'
928 || text_[i - 1] == ':'
929 || text_[i - 1] == '!'))) {
931 os.texrow().start(owner_->id(), i + 1);
933 } else if (style.free_spacing) {
942 int Paragraph::Private::writeScriptChars(otexstream & os,
943 docstring const & ltx,
944 Change const & runningChange,
945 Encoding const & encoding,
948 // FIXME: modifying i here is not very nice...
950 // We only arrive here when a proper language for character text_[i] has
951 // not been specified (i.e., it could not be translated in the current
952 // latex encoding) or its latex translation has been forced, and it
953 // belongs to a known script.
954 // Parameter ltx contains the latex translation of text_[i] as specified
955 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
956 // The latex macro name "textXXX" specifies the script to which text_[i]
957 // belongs and we use it in order to check whether characters from the
958 // same script immediately follow, such that we can collect them in a
959 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
960 // for the first char but only "<spec>" for all subsequent chars.
961 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
962 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
963 string script = to_ascii(ltx.substr(1, brace1 - 1));
966 bool closing_brace = true;
967 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
968 // Correct encoding is being used, so we can avoid \textgreek.
971 closing_brace = false;
973 os << ltx.substr(pos, length);
974 int size = text_.size();
975 while (i + 1 < size) {
976 char_type const next = text_[i + 1];
977 // Stop here if next character belongs to another script
978 // or there is a change in change tracking status.
979 if (!Encodings::isKnownScriptChar(next, script) ||
980 runningChange != owner_->lookupChange(i + 1))
984 FontList::const_iterator cit = fontlist_.begin();
985 FontList::const_iterator end = fontlist_.end();
986 for (; cit != end; ++cit) {
987 if (cit->pos() >= i && !found) {
988 prev_font = cit->font();
991 if (cit->pos() >= i + 1)
994 // Stop here if there is a font attribute or encoding change.
995 if (found && cit != end && prev_font != cit->font())
997 docstring const latex = encoding.latexChar(next).first;
998 docstring::size_type const b1 =
999 latex.find_first_of(from_ascii("{"));
1000 docstring::size_type const b2 =
1001 latex.find_last_of(from_ascii("}"));
1002 int const len = b2 - b1 - 1;
1003 os << latex.substr(b1 + 1, len);
1007 if (closing_brace) {
1015 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1017 pos_type const len = str.length();
1019 // is the paragraph large enough?
1020 if (pos + len > int(text_.size()))
1023 // does the wanted text start at point?
1024 for (string::size_type i = 0; i < str.length(); ++i) {
1025 // Caution: direct comparison of characters works only
1026 // because str is pure ASCII.
1027 if (str[i] != text_[pos + i])
1031 return fontlist_.hasChangeInRange(pos, len);
1035 void Paragraph::Private::latexInset(BufferParams const & bparams,
1037 OutputParams & runparams,
1038 Font & running_font,
1040 Font const & outerfont,
1042 Change & running_change,
1043 Layout const & style,
1045 unsigned int & column)
1047 Inset * inset = owner_->getInset(i);
1050 if (style.pass_thru) {
1051 odocstringstream ods;
1052 inset->plaintext(ods, runparams);
1057 // FIXME: move this to InsetNewline::latex
1058 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1059 // newlines are handled differently here than
1060 // the default in simpleTeXSpecialChars().
1061 if (!style.newline_allowed) {
1065 column += running_font.latexWriteEndChanges(
1066 os, bparams, runparams,
1067 basefont, basefont);
1071 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1074 basefont = owner_->getLayoutFont(bparams, outerfont);
1075 running_font = basefont;
1077 if (runparams.moving_arg)
1081 os.texrow().start(owner_->id(), i + 1);
1085 if (owner_->isDeleted(i)) {
1086 if( ++runparams.inDeletedInset == 1)
1087 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1090 if (inset->canTrackChanges()) {
1091 column += Changes::latexMarkChange(os, bparams, running_change,
1092 Change(Change::UNCHANGED), runparams);
1093 running_change = Change(Change::UNCHANGED);
1097 odocstream::pos_type const len = os.os().tellp();
1099 if (inset->forceLTR()
1100 && !runparams.use_polyglossia
1101 && running_font.isRightToLeft()
1102 // ERT is an exception, it should be output with no
1103 // decorations at all
1104 && inset->lyxCode() != ERT_CODE) {
1105 if (running_font.language()->lang() == "farsi")
1112 // FIXME: Bug: we can have an empty font change here!
1113 // if there has just been a font change, we are going to close it
1114 // right now, which means stupid latex code like \textsf{}. AFAIK,
1115 // this does not harm dvi output. A minor bug, thus (JMarc)
1117 // Some insets cannot be inside a font change command.
1118 // However, even such insets *can* be placed in \L or \R
1119 // or their equivalents (for RTL language switches), so we don't
1120 // close the language in those cases.
1121 // ArabTeX, though, cannot handle this special behavior, it seems.
1122 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1123 || running_font.language()->lang() == "arabic_arabtex";
1124 if (open_font && !inset->inheritFont()) {
1125 bool closeLanguage = arabtex
1126 || basefont.isRightToLeft() == running_font.isRightToLeft();
1127 unsigned int count = running_font.latexWriteEndChanges(os,
1128 bparams, runparams, basefont, basefont, closeLanguage);
1130 // if any font properties were closed, update the running_font,
1131 // making sure, however, to leave the language as it was
1133 // FIXME: probably a better way to keep track of the old
1134 // language, than copying the entire font?
1135 Font const copy_font(running_font);
1136 basefont = owner_->getLayoutFont(bparams, outerfont);
1137 running_font = basefont;
1139 running_font.setLanguage(copy_font.language());
1140 // leave font open if language is still open
1141 open_font = (running_font.language() == basefont.language());
1143 runparams.local_font = &basefont;
1147 int prev_rows = os.texrow().rows();
1150 runparams.lastid = id_;
1151 runparams.lastpos = i;
1152 inset->latex(os, runparams);
1153 } catch (EncodingException & e) {
1154 // add location information and throw again.
1161 if (running_font.language()->lang() == "farsi")
1167 if (os.texrow().rows() > prev_rows) {
1168 os.texrow().start(owner_->id(), i + 1);
1171 column += (unsigned int)(os.os().tellp() - len);
1174 if (owner_->isDeleted(i))
1175 --runparams.inDeletedInset;
1179 void Paragraph::Private::latexSpecialChar(otexstream & os,
1180 BufferParams const & bparams,
1181 OutputParams const & runparams,
1182 Font const & running_font,
1183 Change const & running_change,
1184 Layout const & style,
1187 unsigned int & column)
1189 // With polyglossia, brackets and stuff need not be reversed
1190 // in RTL scripts (see bug #8251)
1191 char_type const c = (runparams.use_polyglossia) ?
1192 owner_->getUChar(bparams, i) : text_[i];
1194 if (style.pass_thru || runparams.pass_thru) {
1196 Encoding const * const enc = runparams.encoding;
1197 if (enc && !enc->encodable(c))
1198 throw EncodingException(c);
1204 // TIPA uses its own T3 encoding
1205 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1207 // If T1 font encoding is used, use the special
1208 // characters it provides.
1209 // NOTE: some languages reset the font encoding
1211 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1212 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1215 // \tt font needs special treatment
1216 if (!runparams.inIPA
1217 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1218 && latexSpecialTypewriter(c, os, i, column))
1221 // Otherwise, we use what LaTeX provides us.
1224 os << "\\textbackslash{}";
1228 os << "\\textless{}";
1232 os << "\\textgreater{}";
1236 os << "\\textbar{}";
1243 os << "\\char`\\\"{}";
1248 case '%': case '#': case '{':
1256 os << "\\textasciitilde{}";
1261 os << "\\textasciicircum{}";
1268 // avoid being mistaken for optional arguments
1276 // Blanks are printed before font switching.
1277 // Sure? I am not! (try nice-latex)
1278 // I am sure it's correct. LyX might be smarter
1279 // in the future, but for now, nothing wrong is
1285 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1291 Encoding const & encoding = *(runparams.encoding);
1292 char_type next = '\0';
1293 if (i + 1 < int(text_.size())) {
1294 next = text_[i + 1];
1295 if (Encodings::isCombiningChar(next)) {
1296 column += latexSurrogatePair(os, c, next, runparams) - 1;
1302 pair<docstring, bool> latex = encoding.latexChar(c);
1303 docstring nextlatex;
1304 bool nexttipas = false;
1305 string nexttipashortcut;
1306 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1307 nextlatex = encoding.latexChar(next).first;
1308 if (runparams.inIPA) {
1309 nexttipashortcut = Encodings::TIPAShortcut(next);
1310 nexttipas = !nexttipashortcut.empty();
1314 if (runparams.inIPA) {
1315 string const tipashortcut = Encodings::TIPAShortcut(c);
1316 if (!tipashortcut.empty()) {
1317 latex.first = from_ascii(tipashortcut);
1318 latex.second = false;
1322 if (Encodings::isKnownScriptChar(c, script)
1323 && prefixIs(latex.first, from_ascii("\\" + script)))
1324 column += writeScriptChars(os, latex.first,
1325 running_change, encoding, i) - 1;
1326 else if (latex.second
1327 && ((!prefixIs(nextlatex, '\\')
1328 && !prefixIs(nextlatex, '{')
1329 && !prefixIs(nextlatex, '}'))
1331 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1333 // Prevent eating of a following
1334 // space or command corruption by
1335 // following characters
1336 if (next == ' ' || next == '\0') {
1337 column += latex.first.length() + 1;
1338 os << latex.first << "{}";
1340 column += latex.first.length();
1341 os << latex.first << " ";
1344 column += latex.first.length() - 1;
1352 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1353 pos_type i, unsigned int & column)
1359 // In T1 encoding, these characters exist
1360 // but we should avoid ligatures
1361 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1363 os << "\\textcompwordmark{}";
1370 // soul.sty breaks with \char`\"
1371 os << "\\textquotedbl{}";
1380 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1381 pos_type /*i*/, unsigned int & column)
1391 os << "\\textvertline{}";
1400 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1401 pos_type i, unsigned int & column)
1405 // within \ttfamily, "--" is merged to "-" (no endash)
1406 // so we avoid this rather irritating ligature
1407 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1414 // everything else has to be checked separately
1415 // (depending on the encoding)
1423 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1424 /// do not apply the macro transformation.
1425 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1426 unsigned int & column, OutputParams const & runparams)
1428 // FIXME: if we have "LaTeX" with a font
1429 // change in the middle (before the 'T', then
1430 // the "TeX" part is still special cased.
1431 // Really we should only operate this on
1432 // "words" for some definition of word
1434 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1435 if (!isTextAt(special_phrases[pnr].phrase, i)
1436 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1438 if (runparams.moving_arg)
1440 os << special_phrases[pnr].macro;
1441 i += special_phrases[pnr].phrase.length() - 1;
1442 column += special_phrases[pnr].macro.length() - 1;
1449 void Paragraph::Private::validate(LaTeXFeatures & features) const
1451 if (layout_->inpreamble && inset_owner_) {
1452 bool const is_command = layout_->latextype == LATEX_COMMAND;
1453 Buffer const & buf = inset_owner_->buffer();
1454 BufferParams const & bp = features.runparams().is_child
1455 ? buf.masterParams() : buf.params();
1458 // Using a string stream here circumvents the encoding
1459 // switching machinery of odocstream. Therefore the
1460 // output is wrong if this paragraph contains content
1461 // that needs to switch encoding.
1462 odocstringstream ods;
1463 otexstream os(ods, texrow);
1465 os << '\\' << from_ascii(layout_->latexname());
1466 // we have to provide all the optional arguments here, even though
1467 // the last one is the only one we care about.
1468 // Separate handling of optional argument inset.
1469 if (!layout_->latexargs().empty()) {
1470 OutputParams rp = features.runparams();
1471 rp.local_font = &owner_->getFirstFontSettings(bp);
1472 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1474 os << from_ascii(layout_->latexparam());
1476 docstring::size_type const length = ods.str().length();
1477 // this will output "{" at the beginning, but not at the end
1478 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1479 if (ods.str().length() > length) {
1482 if (!layout_->postcommandargs().empty()) {
1483 OutputParams rp = features.runparams();
1484 rp.local_font = &owner_->getFirstFontSettings(bp);
1485 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1488 string const snippet = to_utf8(ods.str());
1489 features.addPreambleSnippet(snippet);
1493 if (features.runparams().flavor == OutputParams::HTML
1494 && layout_->htmltitle()) {
1495 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1498 // check the params.
1499 if (!params_.spacing().isDefault())
1500 features.require("setspace");
1503 features.useLayout(layout_->name());
1506 fontlist_.validate(features);
1508 // then the indentation
1509 if (!params_.leftIndent().zero())
1510 features.require("ParagraphLeftIndent");
1513 InsetList::const_iterator icit = insetlist_.begin();
1514 InsetList::const_iterator iend = insetlist_.end();
1515 for (; icit != iend; ++icit) {
1517 icit->inset->validate(features);
1518 if (layout_->needprotect &&
1519 icit->inset->lyxCode() == FOOT_CODE)
1520 features.require("NeedLyXFootnoteCode");
1524 // then the contents
1525 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1526 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1527 if (!special_phrases[pnr].builtin
1528 && isTextAt(special_phrases[pnr].phrase, i)) {
1529 features.require(special_phrases[pnr].phrase);
1533 BufferEncodings::validate(text_[i], features);
1537 /////////////////////////////////////////////////////////////////////
1541 /////////////////////////////////////////////////////////////////////
1544 Layout const emptyParagraphLayout;
1547 Paragraph::Paragraph()
1548 : d(new Paragraph::Private(this, emptyParagraphLayout))
1555 Paragraph::Paragraph(Paragraph const & par)
1556 : itemdepth(par.itemdepth),
1557 d(new Paragraph::Private(*par.d, this))
1563 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1564 : itemdepth(par.itemdepth),
1565 d(new Paragraph::Private(*par.d, this, beg, end))
1571 Paragraph & Paragraph::operator=(Paragraph const & par)
1573 // needed as we will destroy the private part before copying it
1575 itemdepth = par.itemdepth;
1579 d = new Private(*par.d, this);
1586 Paragraph::~Paragraph()
1595 // this shall be called just before every "os << ..." action.
1596 void flushString(ostream & os, docstring & s)
1605 void Paragraph::write(ostream & os, BufferParams const & bparams,
1606 depth_type & dth) const
1608 // The beginning or end of a deeper (i.e. nested) area?
1609 if (dth != d->params_.depth()) {
1610 if (d->params_.depth() > dth) {
1611 while (d->params_.depth() > dth) {
1612 os << "\n\\begin_deeper";
1616 while (d->params_.depth() < dth) {
1617 os << "\n\\end_deeper";
1623 // First write the layout
1624 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1626 d->params_.write(os);
1628 Font font1(inherit_font, bparams.language);
1630 Change running_change = Change(Change::UNCHANGED);
1632 // this string is used as a buffer to avoid repetitive calls
1633 // to to_utf8(), which turn out to be expensive (JMarc)
1634 docstring write_buffer;
1637 for (pos_type i = 0; i <= size(); ++i) {
1639 Change const change = lookupChange(i);
1640 if (change != running_change)
1641 flushString(os, write_buffer);
1642 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1643 running_change = change;
1648 // Write font changes
1649 Font font2 = getFontSettings(bparams, i);
1650 if (font2 != font1) {
1651 flushString(os, write_buffer);
1652 font2.lyxWriteChanges(font1, os);
1657 char_type const c = d->text_[i];
1660 if (Inset const * inset = getInset(i)) {
1661 flushString(os, write_buffer);
1662 if (inset->directWrite()) {
1663 // international char, let it write
1664 // code directly so it's shorter in
1670 os << "\\begin_inset ";
1672 os << "\n\\end_inset\n\n";
1675 // FIXME This can be removed again once the mystery
1676 // crash has been resolved.
1681 flushString(os, write_buffer);
1682 os << "\n\\backslash\n";
1686 flushString(os, write_buffer);
1687 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1694 if ((column > 70 && c == ' ')
1696 flushString(os, write_buffer);
1700 // this check is to amend a bug. LyX sometimes
1701 // inserts '\0' this could cause problems.
1703 write_buffer.push_back(c);
1705 LYXERR0("NUL char in structure.");
1711 flushString(os, write_buffer);
1712 os << "\n\\end_layout\n";
1713 // FIXME This can be removed again once the mystery
1714 // crash has been resolved.
1719 void Paragraph::validate(LaTeXFeatures & features) const
1721 d->validate(features);
1725 void Paragraph::insert(pos_type start, docstring const & str,
1726 Font const & font, Change const & change)
1728 for (size_t i = 0, n = str.size(); i != n ; ++i)
1729 insertChar(start + i, str[i], font, change);
1733 void Paragraph::appendChar(char_type c, Font const & font,
1734 Change const & change)
1737 d->changes_.insert(change, d->text_.size());
1738 // when appending characters, no need to update tables
1739 d->text_.push_back(c);
1740 setFont(d->text_.size() - 1, font);
1741 d->requestSpellCheck(d->text_.size() - 1);
1745 void Paragraph::appendString(docstring const & s, Font const & font,
1746 Change const & change)
1748 pos_type end = s.size();
1749 size_t oldsize = d->text_.size();
1750 size_t newsize = oldsize + end;
1751 size_t capacity = d->text_.capacity();
1752 if (newsize >= capacity)
1753 d->text_.reserve(max(capacity + 100, newsize));
1755 // when appending characters, no need to update tables
1758 // FIXME: Optimize this!
1759 for (size_t i = oldsize; i != newsize; ++i) {
1761 d->changes_.insert(change, i);
1762 d->requestSpellCheck(i);
1764 d->fontlist_.set(oldsize, font);
1765 d->fontlist_.set(newsize - 1, font);
1769 void Paragraph::insertChar(pos_type pos, char_type c,
1772 d->insertChar(pos, c, Change(trackChanges ?
1773 Change::INSERTED : Change::UNCHANGED));
1777 void Paragraph::insertChar(pos_type pos, char_type c,
1778 Font const & font, bool trackChanges)
1780 d->insertChar(pos, c, Change(trackChanges ?
1781 Change::INSERTED : Change::UNCHANGED));
1786 void Paragraph::insertChar(pos_type pos, char_type c,
1787 Font const & font, Change const & change)
1789 d->insertChar(pos, c, change);
1794 void Paragraph::resetFonts(Font const & font)
1796 d->fontlist_.clear();
1797 d->fontlist_.set(0, font);
1798 d->fontlist_.set(d->text_.size() - 1, font);
1801 // Gets uninstantiated font setting at position.
1802 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1806 LYXERR0("pos: " << pos << " size: " << size());
1810 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1811 if (cit != d->fontlist_.end())
1814 if (pos == size() && !empty())
1815 return getFontSettings(bparams, pos - 1);
1817 // Optimisation: avoid a full font instantiation if there is no
1818 // language change from previous call.
1819 static Font previous_font;
1820 static Language const * previous_lang = 0;
1821 Language const * lang = getParLanguage(bparams);
1822 if (lang != previous_lang) {
1823 previous_lang = lang;
1824 previous_font = Font(inherit_font, lang);
1826 return previous_font;
1830 FontSpan Paragraph::fontSpan(pos_type pos) const
1832 LBUFERR(pos < size());
1835 FontList::const_iterator cit = d->fontlist_.begin();
1836 FontList::const_iterator end = d->fontlist_.end();
1837 for (; cit != end; ++cit) {
1838 if (cit->pos() >= pos) {
1839 if (pos >= beginOfBody())
1840 return FontSpan(max(start, beginOfBody()),
1843 return FontSpan(start,
1844 min(beginOfBody() - 1,
1847 start = cit->pos() + 1;
1850 // This should not happen, but if so, we take no chances.
1851 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1852 LASSERT(false, return FontSpan(pos, pos));
1856 // Gets uninstantiated font setting at position 0
1857 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1859 if (!empty() && !d->fontlist_.empty())
1860 return d->fontlist_.begin()->font();
1862 // Optimisation: avoid a full font instantiation if there is no
1863 // language change from previous call.
1864 static Font previous_font;
1865 static Language const * previous_lang = 0;
1866 if (bparams.language != previous_lang) {
1867 previous_lang = bparams.language;
1868 previous_font = Font(inherit_font, bparams.language);
1871 return previous_font;
1875 // Gets the fully instantiated font at a given position in a paragraph
1876 // This is basically the same function as Text::GetFont() in text2.cpp.
1877 // The difference is that this one is used for generating the LaTeX file,
1878 // and thus cosmetic "improvements" are disallowed: This has to deliver
1879 // the true picture of the buffer. (Asger)
1880 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1881 Font const & outerfont) const
1885 Font font = getFontSettings(bparams, pos);
1887 pos_type const body_pos = beginOfBody();
1888 FontInfo & fi = font.fontInfo();
1890 fi.realize(d->layout_->labelfont);
1892 fi.realize(d->layout_->font);
1894 fi.realize(outerfont.fontInfo());
1895 fi.realize(bparams.getFont().fontInfo());
1901 Font const Paragraph::getLabelFont
1902 (BufferParams const & bparams, Font const & outerfont) const
1904 FontInfo tmpfont = d->layout_->labelfont;
1905 tmpfont.realize(outerfont.fontInfo());
1906 tmpfont.realize(bparams.getFont().fontInfo());
1907 return Font(tmpfont, getParLanguage(bparams));
1911 Font const Paragraph::getLayoutFont
1912 (BufferParams const & bparams, Font const & outerfont) const
1914 FontInfo tmpfont = d->layout_->font;
1915 tmpfont.realize(outerfont.fontInfo());
1916 tmpfont.realize(bparams.getFont().fontInfo());
1917 return Font(tmpfont, getParLanguage(bparams));
1921 /// Returns the height of the highest font in range
1922 FontSize Paragraph::highestFontInRange
1923 (pos_type startpos, pos_type endpos, FontSize def_size) const
1925 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1929 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1931 char_type c = d->text_[pos];
1932 if (!getFontSettings(bparams, pos).isRightToLeft())
1935 // FIXME: The arabic special casing is due to the difference of arabic
1936 // round brackets input introduced in r18599. Check if this should be
1937 // unified with Hebrew or at least if all bracket types should be
1938 // handled the same (file format change in either case).
1939 string const & lang = getFontSettings(bparams, pos).language()->lang();
1940 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1945 uc = arabic ? c : ')';
1948 uc = arabic ? c : '(';
1974 void Paragraph::setFont(pos_type pos, Font const & font)
1976 LASSERT(pos <= size(), return);
1978 // First, reduce font against layout/label font
1979 // Update: The setCharFont() routine in text2.cpp already
1980 // reduces font, so we don't need to do that here. (Asger)
1982 d->fontlist_.set(pos, font);
1986 void Paragraph::makeSameLayout(Paragraph const & par)
1988 d->layout_ = par.d->layout_;
1989 d->params_ = par.d->params_;
1993 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1995 if (isFreeSpacing())
2001 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2002 if (eraseChar(pos, trackChanges))
2008 return count > 0 || pos > 0;
2012 bool Paragraph::hasSameLayout(Paragraph const & par) const
2014 return par.d->layout_ == d->layout_
2015 && d->params_.sameLayout(par.d->params_);
2019 depth_type Paragraph::getDepth() const
2021 return d->params_.depth();
2025 depth_type Paragraph::getMaxDepthAfter() const
2027 if (d->layout_->isEnvironment())
2028 return d->params_.depth() + 1;
2030 return d->params_.depth();
2034 char Paragraph::getAlign() const
2036 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2037 return d->layout_->align;
2039 return d->params_.align();
2043 docstring const & Paragraph::labelString() const
2045 return d->params_.labelString();
2049 // the next two functions are for the manual labels
2050 docstring const Paragraph::getLabelWidthString() const
2052 if (d->layout_->margintype == MARGIN_MANUAL
2053 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2054 return d->params_.labelWidthString();
2056 return _("Senseless with this layout!");
2060 void Paragraph::setLabelWidthString(docstring const & s)
2062 d->params_.labelWidthString(s);
2066 docstring Paragraph::expandLabel(Layout const & layout,
2067 BufferParams const & bparams) const
2069 return expandParagraphLabel(layout, bparams, true);
2073 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2074 BufferParams const & bparams) const
2076 return expandParagraphLabel(layout, bparams, false);
2080 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2081 BufferParams const & bparams, bool process_appendix) const
2083 DocumentClass const & tclass = bparams.documentClass();
2084 string const & lang = getParLanguage(bparams)->code();
2085 bool const in_appendix = process_appendix && d->params_.appendix();
2086 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2088 if (fmt.empty() && !layout.counter.empty())
2089 return tclass.counters().theCounter(layout.counter, lang);
2091 // handle 'inherited level parts' in 'fmt',
2092 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2093 size_t const i = fmt.find('@', 0);
2094 if (i != docstring::npos) {
2095 size_t const j = fmt.find('@', i + 1);
2096 if (j != docstring::npos) {
2097 docstring parent(fmt, i + 1, j - i - 1);
2098 docstring label = from_ascii("??");
2099 if (tclass.hasLayout(parent))
2100 docstring label = expandParagraphLabel(tclass[parent], bparams,
2102 fmt = docstring(fmt, 0, i) + label
2103 + docstring(fmt, j + 1, docstring::npos);
2107 return tclass.counters().counterLabel(fmt, lang);
2111 void Paragraph::applyLayout(Layout const & new_layout)
2113 d->layout_ = &new_layout;
2114 LyXAlignment const oldAlign = d->params_.align();
2116 if (!(oldAlign & d->layout_->alignpossible)) {
2117 frontend::Alert::warning(_("Alignment not permitted"),
2118 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2119 d->params_.align(LYX_ALIGN_LAYOUT);
2124 pos_type Paragraph::beginOfBody() const
2126 return d->begin_of_body_;
2130 void Paragraph::setBeginOfBody()
2132 if (d->layout_->labeltype != LABEL_MANUAL) {
2133 d->begin_of_body_ = 0;
2137 // Unroll the first two cycles of the loop
2138 // and remember the previous character to
2139 // remove unnecessary getChar() calls
2141 pos_type end = size();
2142 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2144 char_type previous_char = 0;
2147 previous_char = d->text_[i];
2148 if (!(isNewline(i) || isEnvSeparator(i))) {
2150 while (i < end && previous_char != ' ') {
2152 if (isNewline(i) || isEnvSeparator(i))
2155 previous_char = temp;
2161 d->begin_of_body_ = i;
2165 bool Paragraph::allowParagraphCustomization() const
2167 return inInset().allowParagraphCustomization();
2171 bool Paragraph::usePlainLayout() const
2173 return inInset().usePlainLayout();
2177 bool Paragraph::isPassThru() const
2179 return inInset().isPassThru() || d->layout_->pass_thru;
2184 // paragraphs inside floats need different alignment tags to avoid
2187 bool noTrivlistCentering(InsetCode code)
2189 return code == FLOAT_CODE
2190 || code == WRAP_CODE
2191 || code == CELL_CODE;
2195 string correction(string const & orig)
2197 if (orig == "flushleft")
2198 return "raggedright";
2199 if (orig == "flushright")
2200 return "raggedleft";
2201 if (orig == "center")
2207 string const corrected_env(string const & suffix, string const & env,
2208 InsetCode code, bool const lastpar)
2210 string output = suffix + "{";
2211 if (noTrivlistCentering(code)) {
2213 // the last paragraph in non-trivlist-aligned
2214 // context is special (to avoid unwanted whitespace)
2215 if (suffix == "\\begin")
2216 return "\\" + correction(env) + "{}";
2219 output += correction(env);
2223 if (suffix == "\\begin")
2229 void adjust_column(string const & str, int & column)
2231 if (!contains(str, "\n"))
2232 column += str.size();
2235 column = rsplit(str, tmp, '\n').size();
2242 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2243 otexstream & os, OutputParams const & runparams) const
2247 if (params_.noindent() && !layout_->pass_thru
2248 && (layout_->toggle_indent != ITOGGLE_NEVER)) {
2249 os << "\\noindent ";
2253 LyXAlignment const curAlign = params_.align();
2255 if (curAlign == layout_->align)
2259 case LYX_ALIGN_NONE:
2260 case LYX_ALIGN_BLOCK:
2261 case LYX_ALIGN_LAYOUT:
2262 case LYX_ALIGN_SPECIAL:
2263 case LYX_ALIGN_DECIMAL:
2265 case LYX_ALIGN_LEFT:
2266 case LYX_ALIGN_RIGHT:
2267 case LYX_ALIGN_CENTER:
2268 if (runparams.moving_arg) {
2275 string const begin_tag = "\\begin";
2276 InsetCode code = ownerCode();
2277 bool const lastpar = runparams.isLastPar;
2280 case LYX_ALIGN_NONE:
2281 case LYX_ALIGN_BLOCK:
2282 case LYX_ALIGN_LAYOUT:
2283 case LYX_ALIGN_SPECIAL:
2284 case LYX_ALIGN_DECIMAL:
2286 case LYX_ALIGN_LEFT: {
2288 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2289 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2291 output = corrected_env(begin_tag, "flushright", code, lastpar);
2292 os << from_ascii(output);
2293 adjust_column(output, column);
2295 } case LYX_ALIGN_RIGHT: {
2297 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2298 output = corrected_env(begin_tag, "flushright", code, lastpar);
2300 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2301 os << from_ascii(output);
2302 adjust_column(output, column);
2304 } case LYX_ALIGN_CENTER: {
2306 output = corrected_env(begin_tag, "center", code, lastpar);
2307 os << from_ascii(output);
2308 adjust_column(output, column);
2317 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2318 otexstream & os, OutputParams const & runparams) const
2320 LyXAlignment const curAlign = params_.align();
2322 if (curAlign == layout_->align)
2326 case LYX_ALIGN_NONE:
2327 case LYX_ALIGN_BLOCK:
2328 case LYX_ALIGN_LAYOUT:
2329 case LYX_ALIGN_SPECIAL:
2330 case LYX_ALIGN_DECIMAL:
2332 case LYX_ALIGN_LEFT:
2333 case LYX_ALIGN_RIGHT:
2334 case LYX_ALIGN_CENTER:
2335 if (runparams.moving_arg)
2341 string const end_tag = "\n\\par\\end";
2342 InsetCode code = ownerCode();
2343 bool const lastpar = runparams.isLastPar;
2346 case LYX_ALIGN_NONE:
2347 case LYX_ALIGN_BLOCK:
2348 case LYX_ALIGN_LAYOUT:
2349 case LYX_ALIGN_SPECIAL:
2350 case LYX_ALIGN_DECIMAL:
2352 case LYX_ALIGN_LEFT: {
2353 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2354 output = corrected_env(end_tag, "flushleft", code, lastpar);
2356 output = corrected_env(end_tag, "flushright", code, lastpar);
2357 os << from_ascii(output);
2359 } case LYX_ALIGN_RIGHT: {
2360 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2361 output = corrected_env(end_tag, "flushright", code, lastpar);
2363 output = corrected_env(end_tag, "flushleft", code, lastpar);
2364 os << from_ascii(output);
2366 } case LYX_ALIGN_CENTER: {
2367 output = corrected_env(end_tag, "center", code, lastpar);
2368 os << from_ascii(output);
2373 return !output.empty() || lastpar;
2377 // This one spits out the text of the paragraph
2378 void Paragraph::latex(BufferParams const & bparams,
2379 Font const & outerfont,
2381 OutputParams const & runparams,
2382 int start_pos, int end_pos, bool force) const
2384 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2386 // FIXME This check should not be needed. Perhaps issue an
2387 // error if it triggers.
2388 Layout const & style = inInset().forcePlainLayout() ?
2389 bparams.documentClass().plainLayout() : *d->layout_;
2391 if (!force && style.inpreamble)
2394 bool const allowcust = allowParagraphCustomization();
2396 // Current base font for all inherited font changes, without any
2397 // change caused by an individual character, except for the language:
2398 // It is set to the language of the first character.
2399 // As long as we are in the label, this font is the base font of the
2400 // label. Before the first body character it is set to the base font
2404 // Maybe we have to create a optional argument.
2405 pos_type body_pos = beginOfBody();
2406 unsigned int column = 0;
2409 // the optional argument is kept in curly brackets in
2410 // case it contains a ']'
2411 // This is not strictly needed, but if this is changed it
2412 // would be a file format change, and tex2lyx would need
2413 // to be adjusted, since it unconditionally removes the
2414 // braces when it parses \item.
2417 basefont = getLabelFont(bparams, outerfont);
2419 basefont = getLayoutFont(bparams, outerfont);
2422 // Which font is currently active?
2423 Font running_font(basefont);
2424 // Do we have an open font change?
2425 bool open_font = false;
2427 Change runningChange = Change(Change::UNCHANGED);
2429 Encoding const * const prev_encoding = runparams.encoding;
2431 os.texrow().start(id(), 0);
2433 // if the paragraph is empty, the loop will not be entered at all
2435 if (style.isCommand()) {
2439 if (!style.leftdelim().empty()) {
2440 os << style.leftdelim();
2441 column += style.leftdelim().size();
2444 column += d->startTeXParParams(bparams, os, runparams);
2447 for (pos_type i = 0; i < size(); ++i) {
2448 // First char in paragraph or after label?
2449 if (i == body_pos) {
2452 column += running_font.latexWriteEndChanges(
2453 os, bparams, runparams,
2454 basefont, basefont);
2457 basefont = getLayoutFont(bparams, outerfont);
2458 running_font = basefont;
2460 column += Changes::latexMarkChange(os, bparams,
2461 runningChange, Change(Change::UNCHANGED),
2463 runningChange = Change(Change::UNCHANGED);
2468 if (style.isCommand()) {
2473 if (!style.leftdelim().empty()) {
2474 os << style.leftdelim();
2475 column += style.leftdelim().size();
2479 column += d->startTeXParParams(bparams, os,
2483 Change const & change = runparams.inDeletedInset
2484 ? runparams.changeOfDeletedInset : lookupChange(i);
2486 if (bparams.output_changes && runningChange != change) {
2488 column += running_font.latexWriteEndChanges(
2489 os, bparams, runparams, basefont, basefont);
2492 basefont = getLayoutFont(bparams, outerfont);
2493 running_font = basefont;
2495 column += Changes::latexMarkChange(os, bparams, runningChange,
2497 runningChange = change;
2500 // do not output text which is marked deleted
2501 // if change tracking output is disabled
2502 if (!bparams.output_changes && change.deleted()) {
2508 // Fully instantiated font
2509 Font const font = getFont(bparams, i, outerfont);
2511 Font const last_font = running_font;
2513 // Do we need to close the previous font?
2515 (font != running_font ||
2516 font.language() != running_font.language()))
2518 column += running_font.latexWriteEndChanges(
2519 os, bparams, runparams, basefont,
2520 (i == body_pos-1) ? basefont : font);
2521 running_font = basefont;
2525 string const running_lang = runparams.use_polyglossia ?
2526 running_font.language()->polyglossia() : running_font.language()->babel();
2527 // close babel's font environment before opening CJK.
2528 string const lang_end_command = runparams.use_polyglossia ?
2529 "\\end{$$lang}" : lyxrc.language_command_end;
2530 if (!running_lang.empty() &&
2531 font.language()->encoding()->package() == Encoding::CJK) {
2532 string end_tag = subst(lang_end_command,
2535 os << from_ascii(end_tag);
2536 column += end_tag.length();
2539 // Switch file encoding if necessary (and allowed)
2540 if (!runparams.pass_thru && !style.pass_thru &&
2541 runparams.encoding->package() != Encoding::none &&
2542 font.language()->encoding()->package() != Encoding::none) {
2543 pair<bool, int> const enc_switch =
2544 switchEncoding(os.os(), bparams, runparams,
2545 *(font.language()->encoding()));
2546 if (enc_switch.first) {
2547 column += enc_switch.second;
2548 runparams.encoding = font.language()->encoding();
2552 char_type const c = d->text_[i];
2554 // Do we need to change font?
2555 if ((font != running_font ||
2556 font.language() != running_font.language()) &&
2559 odocstringstream ods;
2560 column += font.latexWriteStartChanges(ods, bparams,
2561 runparams, basefont,
2563 running_font = font;
2565 docstring fontchange = ods.str();
2566 // check whether the fontchange ends with a \\textcolor
2567 // modifier and the text starts with a space (bug 4473)
2568 docstring const last_modifier = rsplit(fontchange, '\\');
2569 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2570 os << fontchange << from_ascii("{}");
2571 // check if the fontchange ends with a trailing blank
2572 // (like "\small " (see bug 3382)
2573 else if (suffixIs(fontchange, ' ') && c == ' ')
2574 os << fontchange.substr(0, fontchange.size() - 1)
2575 << from_ascii("{}");
2580 // FIXME: think about end_pos implementation...
2581 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2582 // FIXME: integrate this case in latexSpecialChar
2583 // Do not print the separation of the optional argument
2584 // if style.pass_thru is false. This works because
2585 // latexSpecialChar ignores spaces if
2586 // style.pass_thru is false.
2587 if (i != body_pos - 1) {
2588 if (d->simpleTeXBlanks(runparams, os,
2589 i, column, font, style)) {
2590 // A surrogate pair was output. We
2591 // must not call latexSpecialChar
2592 // in this iteration, since it would output
2593 // the combining character again.
2600 OutputParams rp = runparams;
2601 rp.free_spacing = style.free_spacing;
2602 rp.local_font = &font;
2603 rp.intitle = style.intitle;
2605 // Two major modes: LaTeX or plain
2606 // Handle here those cases common to both modes
2607 // and then split to handle the two modes separately.
2608 if (c == META_INSET) {
2609 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2610 d->latexInset(bparams, os, rp, running_font,
2611 basefont, outerfont, open_font,
2612 runningChange, style, i, column);
2615 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2617 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2618 style, i, end_pos, column);
2619 } catch (EncodingException & e) {
2620 if (runparams.dryrun) {
2621 os << "<" << _("LyX Warning: ")
2622 << _("uncodable character") << " '";
2626 // add location information and throw again.
2635 // Set the encoding to that returned from latexSpecialChar (see
2636 // comment for encoding member in OutputParams.h)
2637 runparams.encoding = rp.encoding;
2640 // If we have an open font definition, we have to close it
2642 #ifdef FIXED_LANGUAGE_END_DETECTION
2644 running_font.latexWriteEndChanges(os, bparams,
2645 runparams, basefont,
2646 next_->getFont(bparams, 0, outerfont));
2648 running_font.latexWriteEndChanges(os, bparams,
2649 runparams, basefont, basefont);
2652 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2653 //FIXME: there as we start another \selectlanguage with the next paragraph if
2654 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2655 running_font.latexWriteEndChanges(os, bparams, runparams,
2656 basefont, basefont);
2660 column += Changes::latexMarkChange(os, bparams, runningChange,
2661 Change(Change::UNCHANGED), runparams);
2663 // Needed if there is an optional argument but no contents.
2664 if (body_pos > 0 && body_pos == size()) {
2668 if (!style.rightdelim().empty()) {
2669 os << style.rightdelim();
2670 column += style.rightdelim().size();
2673 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2674 && runparams.encoding != prev_encoding) {
2675 runparams.encoding = prev_encoding;
2676 if (!runparams.isFullUnicode())
2677 os << setEncoding(prev_encoding->iconvName());
2680 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2684 bool Paragraph::emptyTag() const
2686 for (pos_type i = 0; i < size(); ++i) {
2687 if (Inset const * inset = getInset(i)) {
2688 InsetCode lyx_code = inset->lyxCode();
2689 // FIXME testing like that is wrong. What is
2691 if (lyx_code != TOC_CODE &&
2692 lyx_code != INCLUDE_CODE &&
2693 lyx_code != GRAPHICS_CODE &&
2694 lyx_code != ERT_CODE &&
2695 lyx_code != LISTINGS_CODE &&
2696 lyx_code != FLOAT_CODE &&
2697 lyx_code != TABULAR_CODE) {
2701 char_type c = d->text_[i];
2702 if (c != ' ' && c != '\t')
2710 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2713 for (pos_type i = 0; i < size(); ++i) {
2714 if (Inset const * inset = getInset(i)) {
2715 InsetCode lyx_code = inset->lyxCode();
2716 if (lyx_code == LABEL_CODE) {
2717 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2718 docstring const & id = il->getParam("name");
2719 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2727 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2731 for (i = 0; i < size(); ++i) {
2732 if (Inset const * inset = getInset(i)) {
2733 inset->docbook(os, runparams);
2735 char_type c = d->text_[i];
2738 os << sgml::escapeChar(c);
2745 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2749 for (i = 0; i < size(); ++i) {
2750 if (Inset const * inset = getInset(i)) {
2751 inset->xhtml(xs, runparams);
2753 char_type c = d->text_[i];
2763 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2766 pos_type size = text_.size();
2767 for (pos_type i = initial; i < size; ++i) {
2768 Font font = owner_->getFont(buf.params(), i, outerfont);
2769 if (text_[i] == META_INSET)
2771 if (i != initial && font != font_old)
2780 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2782 OutputParams const & runparams,
2783 Font const & outerfont,
2784 pos_type initial) const
2786 bool emph_flag = false;
2788 Layout const & style = *d->layout_;
2790 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2792 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2795 // parsing main loop
2796 for (pos_type i = initial; i < size(); ++i) {
2797 Font font = getFont(buf.params(), i, outerfont);
2799 // handle <emphasis> tag
2800 if (font_old.emph() != font.fontInfo().emph()) {
2801 if (font.fontInfo().emph() == FONT_ON) {
2804 } else if (i != initial) {
2805 os << "</emphasis>";
2810 if (Inset const * inset = getInset(i)) {
2811 inset->docbook(os, runparams);
2813 char_type c = d->text_[i];
2815 if (style.pass_thru)
2818 os << sgml::escapeChar(c);
2820 font_old = font.fontInfo();
2824 os << "</emphasis>";
2827 if (style.free_spacing)
2829 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2835 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2836 vector<html::EndFontTag> & tagsToClose,
2837 bool & flag, FontState curstate, html::FontTypes type)
2839 if (curstate == FONT_ON) {
2840 tagsToOpen.push_back(html::FontTag(type));
2843 tagsToClose.push_back(html::EndFontTag(type));
2850 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2852 OutputParams const & runparams,
2853 Font const & outerfont,
2854 pos_type initial) const
2858 // track whether we have opened these tags
2859 bool emph_flag = false;
2860 bool bold_flag = false;
2861 bool noun_flag = false;
2862 bool ubar_flag = false;
2863 bool dbar_flag = false;
2864 bool sout_flag = false;
2865 bool wave_flag = false;
2867 bool shap_flag = false;
2869 bool faml_flag = false;
2871 bool size_flag = false;
2873 Layout const & style = *d->layout_;
2875 xs.startParagraph(allowEmpty());
2878 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2880 FontShape curr_fs = INHERIT_SHAPE;
2881 FontFamily curr_fam = INHERIT_FAMILY;
2882 FontSize curr_size = FONT_SIZE_INHERIT;
2884 string const default_family =
2885 buf.masterBuffer()->params().fonts_default_family;
2887 vector<html::FontTag> tagsToOpen;
2888 vector<html::EndFontTag> tagsToClose;
2890 // parsing main loop
2891 for (pos_type i = initial; i < size(); ++i) {
2892 // let's not show deleted material in the output
2896 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2899 FontState curstate = font.fontInfo().emph();
2900 if (font_old.emph() != curstate)
2901 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2904 curstate = font.fontInfo().noun();
2905 if (font_old.noun() != curstate)
2906 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2909 curstate = font.fontInfo().underbar();
2910 if (font_old.underbar() != curstate)
2911 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2914 curstate = font.fontInfo().strikeout();
2915 if (font_old.strikeout() != curstate)
2916 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2919 curstate = font.fontInfo().uuline();
2920 if (font_old.uuline() != curstate)
2921 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2924 curstate = font.fontInfo().uwave();
2925 if (font_old.uwave() != curstate)
2926 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2929 // a little hackish, but allows us to reuse what we have.
2930 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2931 if (font_old.series() != font.fontInfo().series())
2932 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2935 curr_fs = font.fontInfo().shape();
2936 FontShape old_fs = font_old.shape();
2937 if (old_fs != curr_fs) {
2941 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2944 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2946 case SMALLCAPS_SHAPE:
2947 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2953 // the other tags are for internal use
2961 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2965 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2968 case SMALLCAPS_SHAPE:
2969 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2976 // the other tags are for internal use
2983 curr_fam = font.fontInfo().family();
2984 FontFamily old_fam = font_old.family();
2985 if (old_fam != curr_fam) {
2989 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2992 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2994 case TYPEWRITER_FAMILY:
2995 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2997 case INHERIT_FAMILY:
3000 // the other tags are for internal use
3008 // we will treat a "default" font family as roman, since we have
3009 // no other idea what to do.
3010 if (default_family != "rmdefault" && default_family != "default") {
3011 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3016 if (default_family != "sfdefault") {
3017 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3021 case TYPEWRITER_FAMILY:
3022 if (default_family != "ttdefault") {
3023 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3027 case INHERIT_FAMILY:
3030 // the other tags are for internal use
3037 curr_size = font.fontInfo().size();
3038 FontSize old_size = font_old.size();
3039 if (old_size != curr_size) {
3042 case FONT_SIZE_TINY:
3043 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3045 case FONT_SIZE_SCRIPT:
3046 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3048 case FONT_SIZE_FOOTNOTE:
3049 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3051 case FONT_SIZE_SMALL:
3052 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3054 case FONT_SIZE_LARGE:
3055 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3057 case FONT_SIZE_LARGER:
3058 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3060 case FONT_SIZE_LARGEST:
3061 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3063 case FONT_SIZE_HUGE:
3064 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3066 case FONT_SIZE_HUGER:
3067 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3069 case FONT_SIZE_INCREASE:
3070 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3072 case FONT_SIZE_DECREASE:
3073 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3075 case FONT_SIZE_INHERIT:
3076 case FONT_SIZE_NORMAL:
3079 // the other tags are for internal use
3085 switch (curr_size) {
3086 case FONT_SIZE_TINY:
3087 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3090 case FONT_SIZE_SCRIPT:
3091 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3094 case FONT_SIZE_FOOTNOTE:
3095 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3098 case FONT_SIZE_SMALL:
3099 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3102 case FONT_SIZE_LARGE:
3103 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3106 case FONT_SIZE_LARGER:
3107 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3110 case FONT_SIZE_LARGEST:
3111 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3114 case FONT_SIZE_HUGE:
3115 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3118 case FONT_SIZE_HUGER:
3119 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3122 case FONT_SIZE_INCREASE:
3123 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3126 case FONT_SIZE_DECREASE:
3127 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3130 case FONT_SIZE_NORMAL:
3131 case FONT_SIZE_INHERIT:
3134 // the other tags are for internal use
3141 // Other such tags? What about the other text ranges?
3143 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3144 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3145 for (; cit != cen; ++cit)
3148 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3149 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3150 for (; sit != sen; ++sit)
3153 tagsToClose.clear();
3156 Inset const * inset = getInset(i);
3158 if (!runparams.for_toc || inset->isInToc()) {
3159 OutputParams np = runparams;
3160 np.local_font = &font;
3161 if (!inset->getLayout().htmlisblock())
3162 np.html_in_par = true;
3163 retval += inset->xhtml(xs, np);
3166 char_type c = getUChar(buf.masterBuffer()->params(), i);
3168 if (style.pass_thru || runparams.pass_thru)
3170 else if (c == '-') {
3173 if (j < size() && d->text_[j] == '-') {
3175 if (j < size() && d->text_[j] == '-') {
3176 str += from_ascii("—");
3179 str += from_ascii("–");
3185 // We don't want to escape the entities. Note that
3186 // it is safe to do this, since str can otherwise
3187 // only be "-". E.g., it can't be "<".
3188 xs << XHTMLStream::ESCAPE_NONE << str;
3192 font_old = font.fontInfo();
3201 bool Paragraph::isHfill(pos_type pos) const
3203 Inset const * inset = getInset(pos);
3204 return inset && inset->isHfill();
3208 bool Paragraph::isNewline(pos_type pos) const
3210 Inset const * inset = getInset(pos);
3211 return inset && inset->lyxCode() == NEWLINE_CODE;
3215 bool Paragraph::isEnvSeparator(pos_type pos) const
3217 Inset const * inset = getInset(pos);
3218 return inset && inset->lyxCode() == SEPARATOR_CODE;
3222 bool Paragraph::isLineSeparator(pos_type pos) const
3224 char_type const c = d->text_[pos];
3225 if (isLineSeparatorChar(c))
3227 Inset const * inset = getInset(pos);
3228 return inset && inset->isLineSeparator();
3232 bool Paragraph::isWordSeparator(pos_type pos) const
3236 if (Inset const * inset = getInset(pos))
3237 return !inset->isLetter();
3238 // if we have a hard hyphen (no en- or emdash) or apostrophe
3239 // we pass this to the spell checker
3240 // FIXME: this method is subject to change, visit
3241 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3242 // to get an impression how complex this is.
3243 if (isHardHyphenOrApostrophe(pos))
3245 char_type const c = d->text_[pos];
3246 // We want to pass the escape chars to the spellchecker
3247 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3248 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3252 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3254 pos_type const psize = size();
3257 char_type const c = d->text_[pos];
3258 if (c != '-' && c != '\'')
3260 int nextpos = pos + 1;
3261 int prevpos = pos > 0 ? pos - 1 : 0;
3262 if ((nextpos == psize || isSpace(nextpos))
3263 && (pos == 0 || isSpace(prevpos)))
3266 || ((nextpos == psize || d->text_[nextpos] != '-')
3267 && (pos == 0 || d->text_[prevpos] != '-'));
3271 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
3274 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
3278 bool Paragraph::isChar(pos_type pos) const
3280 if (Inset const * inset = getInset(pos))
3281 return inset->isChar();
3282 char_type const c = d->text_[pos];
3283 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3287 bool Paragraph::isSpace(pos_type pos) const
3289 if (Inset const * inset = getInset(pos))
3290 return inset->isSpace();
3291 char_type const c = d->text_[pos];
3292 return lyx::isSpace(c);
3297 Paragraph::getParLanguage(BufferParams const & bparams) const
3300 return getFirstFontSettings(bparams).language();
3301 // FIXME: we should check the prev par as well (Lgb)
3302 return bparams.language;
3306 bool Paragraph::isRTL(BufferParams const & bparams) const
3308 return getParLanguage(bparams)->rightToLeft()
3309 && !inInset().getLayout().forceLTR();
3313 void Paragraph::changeLanguage(BufferParams const & bparams,
3314 Language const * from, Language const * to)
3316 // change language including dummy font change at the end
3317 for (pos_type i = 0; i <= size(); ++i) {
3318 Font font = getFontSettings(bparams, i);
3319 if (font.language() == from) {
3320 font.setLanguage(to);
3322 d->requestSpellCheck(i);
3328 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3330 Language const * doc_language = bparams.language;
3331 FontList::const_iterator cit = d->fontlist_.begin();
3332 FontList::const_iterator end = d->fontlist_.end();
3334 for (; cit != end; ++cit)
3335 if (cit->font().language() != ignore_language &&
3336 cit->font().language() != latex_language &&
3337 cit->font().language() != doc_language)
3343 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3345 FontList::const_iterator cit = d->fontlist_.begin();
3346 FontList::const_iterator end = d->fontlist_.end();
3348 for (; cit != end; ++cit) {
3349 Language const * lang = cit->font().language();
3350 if (lang != ignore_language &&
3351 lang != latex_language)
3352 languages.insert(lang);
3357 docstring Paragraph::asString(int options) const
3359 return asString(0, size(), options);
3363 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3365 odocstringstream os;
3368 && options & AS_STR_LABEL
3369 && !d->params_.labelString().empty())
3370 os << d->params_.labelString() << ' ';
3372 for (pos_type i = beg; i < end; ++i) {
3373 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3375 char_type const c = d->text_[i];
3376 if (isPrintable(c) || c == '\t'
3377 || (c == '\n' && (options & AS_STR_NEWLINES)))
3379 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3380 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3381 LASSERT(runparams != 0, return docstring());
3382 getInset(i)->plaintext(os, *runparams);
3384 getInset(i)->toString(os);
3385 if (getInset(i)->asInsetMath())
3395 void Paragraph::forOutliner(docstring & os, size_t maxlen) const
3397 if (!d->params_.labelString().empty())
3398 os += d->params_.labelString() + ' ';
3399 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3402 char_type const c = d->text_[i];
3405 else if (c == '\t' || c == '\n')
3407 else if (c == META_INSET)
3408 getInset(i)->forOutliner(os, maxlen);
3413 void Paragraph::setInsetOwner(Inset const * inset)
3415 d->inset_owner_ = inset;
3419 int Paragraph::id() const
3425 void Paragraph::setId(int id)
3431 Layout const & Paragraph::layout() const
3437 void Paragraph::setLayout(Layout const & layout)
3439 d->layout_ = &layout;
3443 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3445 setLayout(tc.defaultLayout());
3449 void Paragraph::setPlainLayout(DocumentClass const & tc)
3451 setLayout(tc.plainLayout());
3455 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3457 if (usePlainLayout())
3458 setPlainLayout(tclass);
3460 setDefaultLayout(tclass);
3464 Inset const & Paragraph::inInset() const
3466 LBUFERR(d->inset_owner_);
3467 return *d->inset_owner_;
3471 ParagraphParameters & Paragraph::params()
3477 ParagraphParameters const & Paragraph::params() const
3483 bool Paragraph::isFreeSpacing() const
3485 if (d->layout_->free_spacing)
3487 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3491 bool Paragraph::allowEmpty() const
3493 if (d->layout_->keepempty)
3495 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3499 bool Paragraph::brokenBiblio() const
3501 // there is a problem if there is no bibitem at position 0 or
3502 // if there is another bibitem in the paragraph.
3503 return d->layout_->labeltype == LABEL_BIBLIO
3504 && (d->insetlist_.find(BIBITEM_CODE) != 0
3505 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3509 int Paragraph::fixBiblio(Buffer const & buffer)
3511 // FIXME: What about the case where paragraph is not BIBLIO
3512 // but there is an InsetBibitem?
3513 // FIXME: when there was already an inset at 0, the return value is 1,
3514 // which does not tell whether another inset has been remove; the
3515 // cursor cannot be correctly updated.
3517 if (d->layout_->labeltype != LABEL_BIBLIO)
3520 bool const track_changes = buffer.params().track_changes;
3521 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3522 bool const hasbibitem0 = bibitem_pos == 0;
3525 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3526 // There was an InsetBibitem at pos 0, and no other one => OK
3527 if (bibitem_pos == -1)
3529 // there is a bibitem at the 0 position, but since
3530 // there is a second one, we copy the second on the
3531 // first. We're assuming there are at most two of
3532 // these, which there should be.
3533 // FIXME: why does it make sense to do that rather
3534 // than keep the first? (JMarc)
3535 Inset * inset = releaseInset(bibitem_pos);
3536 d->insetlist_.begin()->inset = inset;
3537 return -bibitem_pos;
3540 // We need to create an inset at the beginning
3542 if (bibitem_pos > 0) {
3543 // there was one somewhere in the paragraph, let's move it
3544 inset = d->insetlist_.release(bibitem_pos);
3545 eraseChar(bibitem_pos, track_changes);
3548 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3549 InsetCommandParams(BIBITEM_CODE));
3551 Font font(inherit_font, buffer.params().language);
3552 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3553 : Change::UNCHANGED));
3559 void Paragraph::checkAuthors(AuthorList const & authorList)
3561 d->changes_.checkAuthors(authorList);
3565 bool Paragraph::isChanged(pos_type pos) const
3567 return lookupChange(pos).changed();
3571 bool Paragraph::isInserted(pos_type pos) const
3573 return lookupChange(pos).inserted();
3577 bool Paragraph::isDeleted(pos_type pos) const
3579 return lookupChange(pos).deleted();
3583 InsetList const & Paragraph::insetList() const
3585 return d->insetlist_;
3589 void Paragraph::setBuffer(Buffer & b)
3591 d->insetlist_.setBuffer(b);
3595 Inset * Paragraph::releaseInset(pos_type pos)
3597 Inset * inset = d->insetlist_.release(pos);
3598 /// does not honour change tracking!
3599 eraseChar(pos, false);
3604 Inset * Paragraph::getInset(pos_type pos)
3606 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3607 ? d->insetlist_.get(pos) : 0;
3611 Inset const * Paragraph::getInset(pos_type pos) const
3613 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3614 ? d->insetlist_.get(pos) : 0;
3618 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3619 pos_type & right, TextCase action)
3621 // process sequences of modified characters; in change
3622 // tracking mode, this approach results in much better
3623 // usability than changing case on a char-by-char basis
3624 // We also need to track the current font, since font
3625 // changes within sequences can occur.
3626 vector<pair<char_type, Font> > changes;
3628 bool const trackChanges = bparams.track_changes;
3630 bool capitalize = true;
3632 for (; pos < right; ++pos) {
3633 char_type oldChar = d->text_[pos];
3634 char_type newChar = oldChar;
3636 // ignore insets and don't play with deleted text!
3637 if (oldChar != META_INSET && !isDeleted(pos)) {
3639 case text_lowercase:
3640 newChar = lowercase(oldChar);
3642 case text_capitalization:
3644 newChar = uppercase(oldChar);
3648 case text_uppercase:
3649 newChar = uppercase(oldChar);
3654 if (isWordSeparator(pos) || isDeleted(pos)) {
3655 // permit capitalization again
3659 if (oldChar != newChar) {
3660 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3661 if (pos != right - 1)
3663 // step behind the changing area
3667 int erasePos = pos - changes.size();
3668 for (size_t i = 0; i < changes.size(); i++) {
3669 insertChar(pos, changes[i].first,
3672 if (!eraseChar(erasePos, trackChanges)) {
3675 ++right; // expand selection
3683 int Paragraph::find(docstring const & str, bool cs, bool mw,
3684 pos_type start_pos, bool del) const
3686 pos_type pos = start_pos;
3687 int const strsize = str.length();
3689 pos_type const parsize = d->text_.size();
3690 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3691 // Ignore "invisible" letters such as ligature breaks
3692 // and hyphenation chars while searching
3693 while (pos < parsize - 1 && isInset(pos)) {
3694 odocstringstream os;
3695 getInset(pos)->toString(os);
3696 if (!getInset(pos)->isLetter() || !os.str().empty())
3700 if (cs && str[i] != d->text_[pos])
3702 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3704 if (!del && isDeleted(pos))
3711 // if necessary, check whether string matches word
3713 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3716 && !isWordSeparator(pos))
3720 return pos - start_pos;
3724 char_type Paragraph::getChar(pos_type pos) const
3726 return d->text_[pos];
3730 pos_type Paragraph::size() const
3732 return d->text_.size();
3736 bool Paragraph::empty() const
3738 return d->text_.empty();
3742 bool Paragraph::isInset(pos_type pos) const
3744 return d->text_[pos] == META_INSET;
3748 bool Paragraph::isSeparator(pos_type pos) const
3750 //FIXME: Are we sure this can be the only separator?
3751 return d->text_[pos] == ' ';
3755 void Paragraph::deregisterWords()
3757 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3758 Private::LangWordsMap::const_iterator ite = d->words_.end();
3759 for (; itl != ite; ++itl) {
3760 WordList * wl = theWordList(itl->first);
3761 Private::Words::const_iterator it = (itl->second).begin();
3762 Private::Words::const_iterator et = (itl->second).end();
3763 for (; it != et; ++it)
3770 void Paragraph::locateWord(pos_type & from, pos_type & to,
3771 word_location const loc) const
3774 case WHOLE_WORD_STRICT:
3775 if (from == 0 || from == size()
3776 || isWordSeparator(from)
3777 || isWordSeparator(from - 1)) {
3781 // no break here, we go to the next
3784 // If we are already at the beginning of a word, do nothing
3785 if (!from || isWordSeparator(from - 1))
3787 // no break here, we go to the next
3790 // always move the cursor to the beginning of previous word
3791 while (from && !isWordSeparator(from - 1))
3795 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3798 // no need to move the 'from' cursor
3802 while (to < size() && !isWordSeparator(to))
3807 void Paragraph::collectWords()
3809 for (pos_type pos = 0; pos < size(); ++pos) {
3810 if (isWordSeparator(pos))
3812 pos_type from = pos;
3813 locateWord(from, pos, WHOLE_WORD);
3814 // Work around MSVC warning: The statement
3815 // if (pos < from + lyxrc.completion_minlength)
3816 // triggers a signed vs. unsigned warning.
3817 // I don't know why this happens, it could be a MSVC bug, or
3818 // related to LLP64 (windows) vs. LP64 (unix) programming
3819 // model, or the C++ standard might be ambigous in the section
3820 // defining the "usual arithmetic conversions". However, using
3821 // a temporary variable is safe and works on all compilers.
3822 pos_type const endpos = from + lyxrc.completion_minlength;
3825 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3826 if (cit == d->fontlist_.end())
3828 Language const * lang = cit->font().language();
3829 docstring const word = asString(from, pos, AS_STR_NONE);
3830 d->words_[lang->lang()].insert(word);
3835 void Paragraph::registerWords()
3837 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3838 Private::LangWordsMap::const_iterator ite = d->words_.end();
3839 for (; itl != ite; ++itl) {
3840 WordList * wl = theWordList(itl->first);
3841 Private::Words::const_iterator it = (itl->second).begin();
3842 Private::Words::const_iterator et = (itl->second).end();
3843 for (; it != et; ++it)
3849 void Paragraph::updateWords()
3857 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3859 SkipPositionsIterator begin = skips.begin();
3860 SkipPositions::iterator end = skips.end();
3861 if (pos > 0 && begin < end) {
3863 if (end->last == pos - 1) {
3868 skips.insert(end, FontSpan(pos, pos));
3872 Language * Paragraph::Private::locateSpellRange(
3873 pos_type & from, pos_type & to,
3874 SkipPositions & skips) const
3876 // skip leading white space
3877 while (from < to && owner_->isWordSeparator(from))
3879 // don't check empty range
3882 // get current language
3883 Language * lang = getSpellLanguage(from);
3884 pos_type last = from;
3885 bool samelang = true;
3886 bool sameinset = true;
3887 while (last < to && samelang && sameinset) {
3888 // hop to end of word
3889 while (last < to && !owner_->isWordSeparator(last)) {
3890 if (owner_->getInset(last)) {
3891 appendSkipPosition(skips, last);
3892 } else if (owner_->isDeleted(last)) {
3893 appendSkipPosition(skips, last);
3897 // hop to next word while checking for insets
3898 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3899 if (Inset const * inset = owner_->getInset(last))
3900 sameinset = inset->isChar() && inset->isLetter();
3901 if (sameinset && owner_->isDeleted(last)) {
3902 appendSkipPosition(skips, last);
3907 if (sameinset && last < to) {
3908 // now check for language change
3909 samelang = lang == getSpellLanguage(last);
3912 // if language change detected backstep is needed
3920 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3923 const_cast<Language *>(owner_->getFontSettings(
3924 inset_owner_->buffer().params(), from).language());
3925 if (lang == inset_owner_->buffer().params().language
3926 && !lyxrc.spellchecker_alt_lang.empty()) {
3928 string const lang_variety =
3929 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3930 lang->setCode(lang_code);
3931 lang->setVariety(lang_variety);
3937 void Paragraph::requestSpellCheck(pos_type pos)
3939 d->requestSpellCheck(pos);
3943 bool Paragraph::needsSpellCheck() const
3945 SpellChecker::ChangeNumber speller_change_number = 0;
3946 if (theSpellChecker())
3947 speller_change_number = theSpellChecker()->changeNumber();
3948 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3949 d->speller_state_.needsCompleteRefresh(speller_change_number);
3951 return d->needsSpellCheck();
3955 bool Paragraph::Private::ignoreWord(docstring const & word) const
3957 // Ignore words with digits
3958 // FIXME: make this customizable
3959 // (note that some checkers ignore words with digits by default)
3960 docstring::const_iterator cit = word.begin();
3961 docstring::const_iterator const end = word.end();
3962 for (; cit != end; ++cit) {
3963 if (isNumber((*cit)))
3970 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3971 WordLangTuple & wl, docstring_list & suggestions,
3972 bool do_suggestion, bool check_learned) const
3974 SpellChecker::Result result = SpellChecker::WORD_OK;
3975 SpellChecker * speller = theSpellChecker();
3979 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3982 locateWord(from, to, WHOLE_WORD);
3983 if (from == to || from >= size())
3986 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3987 Language * lang = d->getSpellLanguage(from);
3989 wl = WordLangTuple(word, lang);
3994 if (needsSpellCheck() || check_learned) {
3996 if (!d->ignoreWord(word)) {
3997 bool const trailing_dot = to < size() && d->text_[to] == '.';
3998 result = speller->check(wl);
3999 if (SpellChecker::misspelled(result) && trailing_dot) {
4000 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4001 result = speller->check(wl);
4002 if (!SpellChecker::misspelled(result)) {
4003 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4005 from << ".." << to << "]");
4007 // spell check with dot appended failed too
4008 // restore original word/lang value
4009 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4010 wl = WordLangTuple(word, lang);
4014 if (!SpellChecker::misspelled(result)) {
4015 // area up to the begin of the next word is not misspelled
4016 while (end < size() && isWordSeparator(end))
4019 d->setMisspelled(from, end, result);
4021 result = d->speller_state_.getState(from);
4025 suggestions.clear();
4027 if (SpellChecker::misspelled(result)) {
4028 LYXERR(Debug::GUI, "misspelled word: \"" <<
4030 from << ".." << to << "]");
4032 speller->suggest(wl, suggestions);
4038 void Paragraph::Private::markMisspelledWords(
4039 pos_type const & first, pos_type const & last,
4040 SpellChecker::Result result,
4041 docstring const & word,
4042 SkipPositions const & skips)
4044 if (!SpellChecker::misspelled(result)) {
4045 setMisspelled(first, last, SpellChecker::WORD_OK);
4049 SpellChecker * speller = theSpellChecker();
4050 // locate and enumerate the error positions
4051 int nerrors = speller->numMisspelledWords();
4053 SkipPositionsIterator it = skips.begin();
4054 SkipPositionsIterator et = skips.end();
4055 for (int index = 0; index < nerrors; ++index) {
4058 speller->misspelledWord(index, wstart, wlen);
4059 /// should not happen if speller supports range checks
4060 if (!wlen) continue;
4061 docstring const misspelled = word.substr(wstart, wlen);
4062 wstart += first + numskipped;
4063 if (snext < wstart) {
4064 /// mark the range of correct spelling
4065 numskipped += countSkips(it, et, wstart);
4066 setMisspelled(snext,
4067 wstart - 1, SpellChecker::WORD_OK);
4069 snext = wstart + wlen;
4070 numskipped += countSkips(it, et, snext);
4071 /// mark the range of misspelling
4072 setMisspelled(wstart, snext, result);
4073 LYXERR(Debug::GUI, "misspelled word: \"" <<
4074 misspelled << "\" [" <<
4075 wstart << ".." << (snext-1) << "]");
4078 if (snext <= last) {
4079 /// mark the range of correct spelling at end
4080 setMisspelled(snext, last, SpellChecker::WORD_OK);
4085 void Paragraph::spellCheck() const
4087 SpellChecker * speller = theSpellChecker();
4088 if (!speller || empty() ||!needsSpellCheck())
4092 d->rangeOfSpellCheck(start, endpos);
4093 if (speller->canCheckParagraph()) {
4094 // loop until we leave the range
4095 for (pos_type first = start; first < endpos; ) {
4096 pos_type last = endpos;
4097 Private::SkipPositions skips;
4098 Language * lang = d->locateSpellRange(first, last, skips);
4099 if (first >= endpos)
4101 // start the spell checker on the unit of meaning
4102 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4103 WordLangTuple wl = WordLangTuple(word, lang);
4104 SpellChecker::Result result = word.size() ?
4105 speller->check(wl) : SpellChecker::WORD_OK;
4106 d->markMisspelledWords(first, last, result, word, skips);
4110 static docstring_list suggestions;
4111 pos_type to = endpos;
4112 while (start < endpos) {
4114 spellCheck(start, to, wl, suggestions, false);
4118 d->readySpellCheck();
4122 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4124 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4125 if (result || pos <= 0 || pos > size())
4127 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4128 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4133 string Paragraph::magicLabel() const
4136 ss << "magicparlabel-" << id();