3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
79 /////////////////////////////////////////////////////////////////////
83 /////////////////////////////////////////////////////////////////////
85 class SpellResultRange {
87 SpellResultRange(FontSpan range, SpellChecker::Result result)
88 : range_(range), result_(result)
91 FontSpan const & range() const { return range_; }
93 void range(FontSpan const & r) { range_ = r; }
95 SpellChecker::Result result() const { return result_; }
97 void result(SpellChecker::Result r) { result_ = r; }
99 bool contains(pos_type pos) const { return range_.contains(pos); }
101 bool covered(FontSpan const & r) const
103 // 1. first of new range inside current range or
104 // 2. last of new range inside current range or
105 // 3. first of current range inside new range or
106 // 4. last of current range inside new range
107 //FIXME: is this the same as !range_.intersect(r).empty() ?
108 return range_.contains(r.first) || range_.contains(r.last) ||
109 r.contains(range_.first) || r.contains(range_.last);
112 void shift(pos_type pos, int offset)
114 if (range_.first > pos) {
115 range_.first += offset;
116 range_.last += offset;
117 } else if (range_.last >= pos) {
118 range_.last += offset;
123 SpellChecker::Result result_ ;
127 /////////////////////////////////////////////////////////////////////
131 /////////////////////////////////////////////////////////////////////
133 class SpellCheckerState {
137 needs_refresh_ = true;
138 current_change_number_ = 0;
141 void setRange(FontSpan const & fp, SpellChecker::Result state)
144 RangesIterator et = ranges_.end();
145 RangesIterator it = ranges_.begin();
146 for (; it != et; ++it) {
147 if (!it->covered(fp))
148 result.push_back(SpellResultRange(it->range(), it->result()));
149 else if (state == SpellChecker::WORD_OK) {
150 // trim or split the current misspelled range
151 // store misspelled ranges only
152 FontSpan range = it->range();
153 if (fp.first > range.first) {
154 // misspelled area in front of WORD_OK
155 range.last = fp.first - 1;
156 result.push_back(SpellResultRange(range, it->result()));
159 if (fp.last < range.last) {
160 // misspelled area after WORD_OK range
161 range.first = fp.last + 1;
162 result.push_back(SpellResultRange(range, it->result()));
167 if (state != SpellChecker::WORD_OK)
168 ranges_.push_back(SpellResultRange(fp, state));
171 void increasePosAfterPos(pos_type pos)
173 correctRangesAfterPos(pos, 1);
177 void decreasePosAfterPos(pos_type pos)
179 correctRangesAfterPos(pos, -1);
183 void refreshLast(pos_type pos)
185 if (pos < refresh_.last)
189 SpellChecker::Result getState(pos_type pos) const
191 SpellChecker::Result result = SpellChecker::WORD_OK;
192 RangesIterator et = ranges_.end();
193 RangesIterator it = ranges_.begin();
194 for (; it != et; ++it) {
195 if(it->contains(pos)) {
202 FontSpan const & getRange(pos_type pos) const
204 /// empty span to indicate mismatch
205 static FontSpan empty_;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 bool needsRefresh() const
218 return needs_refresh_;
221 SpellChecker::ChangeNumber currentChangeNumber() const
223 return current_change_number_;
226 void refreshRange(pos_type & first, pos_type & last) const
228 first = refresh_.first;
229 last = refresh_.last;
232 void needsRefresh(pos_type pos)
234 if (needs_refresh_ && pos != -1) {
235 if (pos < refresh_.first)
236 refresh_.first = pos;
237 if (pos > refresh_.last)
239 } else if (pos != -1) {
240 // init request check for neighbour positions too
241 refresh_.first = pos > 0 ? pos - 1 : 0;
242 // no need for special end of paragraph check
243 refresh_.last = pos + 1;
245 needs_refresh_ = pos != -1;
248 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
250 needs_refresh_ = true;
253 current_change_number_ = change_number;
256 typedef vector<SpellResultRange> Ranges;
257 typedef Ranges::const_iterator RangesIterator;
259 /// the area of the paragraph with pending spell check
262 /// spell state cache version number
263 SpellChecker::ChangeNumber current_change_number_;
266 void correctRangesAfterPos(pos_type pos, int offset)
268 RangesIterator et = ranges_.end();
269 Ranges::iterator it = ranges_.begin();
270 for (; it != et; ++it) {
271 it->shift(pos, offset);
277 /////////////////////////////////////////////////////////////////////
279 // Paragraph::Private
281 /////////////////////////////////////////////////////////////////////
283 class Paragraph::Private
285 // Enforce our own "copy" constructor by declaring the standard one and
286 // the assignment operator private without implementing them.
287 Private(Private const &);
288 Private & operator=(Private const &);
291 Private(Paragraph * owner, Layout const & layout);
292 /// "Copy constructor"
293 Private(Private const &, Paragraph * owner);
294 /// Copy constructor from \p beg to \p end
295 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
298 void insertChar(pos_type pos, char_type c, Change const & change);
300 /// Output the surrogate pair formed by \p c and \p next to \p os.
301 /// \return the number of characters written.
302 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
303 OutputParams const &);
305 /// Output a space in appropriate formatting (or a surrogate pair
306 /// if the next character is a combining character).
307 /// \return whether a surrogate pair was output.
308 bool simpleTeXBlanks(OutputParams const &,
311 unsigned int & column,
313 Layout const & style);
315 /// Output consecutive unicode chars, belonging to the same script as
316 /// specified by the latex macro \p ltx, to \p os starting from \p i.
317 /// \return the number of characters written.
318 int writeScriptChars(otexstream & os, docstring const & ltx,
319 Change const &, Encoding const &, pos_type & i);
321 /// This could go to ParagraphParameters if we want to.
322 int startTeXParParams(BufferParams const &, otexstream &,
323 OutputParams const &) const;
325 /// This could go to ParagraphParameters if we want to.
326 bool endTeXParParams(BufferParams const &, otexstream &,
327 OutputParams const &) const;
330 void latexInset(BufferParams const &,
335 Font const & outerfont,
337 Change & running_change,
338 Layout const & style,
340 unsigned int & column);
343 void latexSpecialChar(
345 BufferParams const & bparams,
346 OutputParams const & runparams,
347 Font const & running_font,
348 Change const & running_change,
349 Layout const & style,
352 unsigned int & column);
359 unsigned int & column);
365 unsigned int & column);
367 bool latexSpecialPhrase(
371 unsigned int & column,
372 OutputParams const & runparams);
375 void validate(LaTeXFeatures & features) const;
377 /// Checks if the paragraph contains only text and no inset or font change.
378 bool onlyText(Buffer const & buf, Font const & outerfont,
379 pos_type initial) const;
381 /// match a string against a particular point in the paragraph
382 bool isTextAt(string const & str, pos_type pos) const;
384 /// a vector of speller skip positions
385 typedef vector<FontSpan> SkipPositions;
386 typedef SkipPositions::const_iterator SkipPositionsIterator;
388 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
390 Language * getSpellLanguage(pos_type const from) const;
392 Language * locateSpellRange(pos_type & from, pos_type & to,
393 SkipPositions & skips) const;
395 bool hasSpellerChange() const
397 SpellChecker::ChangeNumber speller_change_number = 0;
398 if (theSpellChecker())
399 speller_change_number = theSpellChecker()->changeNumber();
400 return speller_change_number > speller_state_.currentChangeNumber();
403 bool ignoreWord(docstring const & word) const ;
405 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
407 pos_type textsize = owner_->size();
408 // check for sane arguments
409 if (to <= from || from >= textsize)
411 FontSpan fp = FontSpan(from, to - 1);
412 speller_state_.setRange(fp, state);
415 void requestSpellCheck(pos_type pos)
418 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
420 speller_state_.needsRefresh(pos);
423 void readySpellCheck()
425 speller_state_.needsRefresh(-1);
428 bool needsSpellCheck() const
430 return speller_state_.needsRefresh();
433 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
435 speller_state_.refreshRange(first, last);
437 last = owner_->size();
440 pos_type endpos = last;
441 owner_->locateWord(first, endpos, WHOLE_WORD);
444 owner_->locateWord(last, endpos, WHOLE_WORD);
449 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
453 while (it != et && it->first < start) {
454 int skip = it->last - it->first + 1;
462 void markMisspelledWords(pos_type const & first, pos_type const & last,
463 SpellChecker::Result result,
464 docstring const & word,
465 SkipPositions const & skips);
467 InsetCode ownerCode() const
469 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
472 /// Which Paragraph owns us?
476 Inset const * inset_owner_;
485 ParagraphParameters params_;
487 /// for recording and looking up changes
491 InsetList insetlist_;
494 pos_type begin_of_body_;
496 typedef docstring TextContainer;
500 typedef set<docstring> Words;
501 typedef map<string, Words> LangWordsMap;
505 Layout const * layout_;
507 SpellCheckerState speller_state_;
513 struct special_phrase {
519 special_phrase const special_phrases[] = {
520 { "LyX", from_ascii("\\LyX{}"), false },
521 { "TeX", from_ascii("\\TeX{}"), true },
522 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
523 { "LaTeX", from_ascii("\\LaTeX{}"), true },
526 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
531 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
532 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
538 // Initialization of the counter for the paragraph id's,
540 // FIXME: There should be a more intelligent way to generate and use the
541 // paragraph ids per buffer instead a global static counter for all InsetText
542 // in the running program.
543 static int paragraph_id = -1;
545 Paragraph::Private::Private(Private const & p, Paragraph * owner)
546 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
547 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
548 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
551 id_ = ++paragraph_id;
552 requestSpellCheck(p.text_.size());
556 Paragraph::Private::Private(Private const & p, Paragraph * owner,
557 pos_type beg, pos_type end)
558 : owner_(owner), inset_owner_(p.inset_owner_),
559 params_(p.params_), changes_(p.changes_),
560 insetlist_(p.insetlist_, beg, end),
561 begin_of_body_(p.begin_of_body_), words_(p.words_),
564 id_ = ++paragraph_id;
565 if (beg >= pos_type(p.text_.size()))
567 text_ = p.text_.substr(beg, end - beg);
569 FontList::const_iterator fcit = fontlist_.begin();
570 FontList::const_iterator fend = fontlist_.end();
571 for (; fcit != fend; ++fcit) {
572 if (fcit->pos() < beg)
574 if (fcit->pos() >= end) {
575 // Add last entry in the fontlist_.
576 fontlist_.set(text_.size() - 1, fcit->font());
579 // Add a new entry in the fontlist_.
580 fontlist_.set(fcit->pos() - beg, fcit->font());
582 requestSpellCheck(p.text_.size());
586 void Paragraph::addChangesToToc(DocIterator const & cdit,
587 Buffer const & buf, bool output_active) const
589 d->changes_.addToToc(cdit, buf, output_active);
593 bool Paragraph::isDeleted(pos_type start, pos_type end) const
595 LASSERT(start >= 0 && start <= size(), return false);
596 LASSERT(end > start && end <= size() + 1, return false);
598 return d->changes_.isDeleted(start, end);
602 bool Paragraph::isChanged(pos_type start, pos_type end) const
604 LASSERT(start >= 0 && start <= size(), return false);
605 LASSERT(end > start && end <= size() + 1, return false);
607 return d->changes_.isChanged(start, end);
611 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
613 // keep the logic here in sync with the logic of eraseChars()
617 Change const & change = d->changes_.lookup(size());
618 return change.inserted() && change.currentAuthor();
622 void Paragraph::setChange(Change const & change)
624 // beware of the imaginary end-of-par character!
625 d->changes_.set(change, 0, size() + 1);
628 * Propagate the change recursively - but not in case of DELETED!
630 * Imagine that your co-author makes changes in an existing inset. He
631 * sends your document to you and you come to the conclusion that the
632 * inset should go completely. If you erase it, LyX must not delete all
633 * text within the inset. Otherwise, the change tracked insertions of
634 * your co-author get lost and there is no way to restore them later.
636 * Conclusion: An inset's content should remain untouched if you delete it
639 if (!change.deleted()) {
640 for (pos_type pos = 0; pos < size(); ++pos) {
641 if (Inset * inset = getInset(pos))
642 inset->setChange(change);
648 void Paragraph::setChange(pos_type pos, Change const & change)
650 LASSERT(pos >= 0 && pos <= size(), return);
651 d->changes_.set(change, pos);
653 // see comment in setChange(Change const &) above
654 if (!change.deleted() && pos < size())
655 if (Inset * inset = getInset(pos))
656 inset->setChange(change);
660 Change const & Paragraph::lookupChange(pos_type pos) const
662 LBUFERR(pos >= 0 && pos <= size());
663 return d->changes_.lookup(pos);
667 void Paragraph::acceptChanges(pos_type start, pos_type end)
669 LASSERT(start >= 0 && start <= size(), return);
670 LASSERT(end > start && end <= size() + 1, return);
672 for (pos_type pos = start; pos < end; ++pos) {
673 switch (lookupChange(pos).type) {
674 case Change::UNCHANGED:
675 // accept changes in nested inset
676 if (Inset * inset = getInset(pos))
677 inset->acceptChanges();
680 case Change::INSERTED:
681 d->changes_.set(Change(Change::UNCHANGED), pos);
682 // also accept changes in nested inset
683 if (Inset * inset = getInset(pos))
684 inset->acceptChanges();
687 case Change::DELETED:
688 // Suppress access to non-existent
689 // "end-of-paragraph char"
691 eraseChar(pos, false);
702 void Paragraph::rejectChanges(pos_type start, pos_type end)
704 LASSERT(start >= 0 && start <= size(), return);
705 LASSERT(end > start && end <= size() + 1, return);
707 for (pos_type pos = start; pos < end; ++pos) {
708 switch (lookupChange(pos).type) {
709 case Change::UNCHANGED:
710 // reject changes in nested inset
711 if (Inset * inset = getInset(pos))
712 inset->rejectChanges();
715 case Change::INSERTED:
716 // Suppress access to non-existent
717 // "end-of-paragraph char"
719 eraseChar(pos, false);
725 case Change::DELETED:
726 d->changes_.set(Change(Change::UNCHANGED), pos);
728 // Do NOT reject changes within a deleted inset!
729 // There may be insertions of a co-author inside of it!
737 void Paragraph::Private::insertChar(pos_type pos, char_type c,
738 Change const & change)
740 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
743 changes_.insert(change, pos);
745 // This is actually very common when parsing buffers (and
746 // maybe inserting ascii text)
747 if (pos == pos_type(text_.size())) {
748 // when appending characters, no need to update tables
750 // but we want spell checking
751 requestSpellCheck(pos);
755 text_.insert(text_.begin() + pos, c);
757 // Update the font table.
758 fontlist_.increasePosAfterPos(pos);
761 insetlist_.increasePosAfterPos(pos);
763 // Update list of misspelled positions
764 speller_state_.increasePosAfterPos(pos);
768 bool Paragraph::insertInset(pos_type pos, Inset * inset,
769 Font const & font, Change const & change)
771 LASSERT(inset, return false);
772 LASSERT(pos >= 0 && pos <= size(), return false);
774 // Paragraph::insertInset() can be used in cut/copy/paste operation where
775 // d->inset_owner_ is not set yet.
776 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
779 d->insertChar(pos, META_INSET, change);
780 LASSERT(d->text_[pos] == META_INSET, return false);
782 // Add a new entry in the insetlist_.
783 d->insetlist_.insert(inset, pos);
785 // Some insets require run of spell checker
786 requestSpellCheck(pos);
792 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
794 LASSERT(pos >= 0 && pos <= size(), return false);
796 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
799 Change change = d->changes_.lookup(pos);
801 // set the character to DELETED if
802 // a) it was previously unchanged or
803 // b) it was inserted by a co-author
805 if (!change.changed() ||
806 (change.inserted() && !change.currentAuthor())) {
807 setChange(pos, Change(Change::DELETED));
808 // request run of spell checker
809 requestSpellCheck(pos);
813 if (change.deleted())
817 // Don't physically access the imaginary end-of-paragraph character.
818 // eraseChar() can only mark it as DELETED. A physical deletion of
819 // end-of-par must be handled externally.
825 d->changes_.erase(pos);
827 // if it is an inset, delete the inset entry
828 if (d->text_[pos] == META_INSET)
829 d->insetlist_.erase(pos);
831 d->text_.erase(d->text_.begin() + pos);
833 // Update the fontlist_
834 d->fontlist_.erase(pos);
836 // Update the insetlist_
837 d->insetlist_.decreasePosAfterPos(pos);
839 // Update list of misspelled positions
840 d->speller_state_.decreasePosAfterPos(pos);
841 d->speller_state_.refreshLast(size());
847 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
849 LASSERT(start >= 0 && start <= size(), return 0);
850 LASSERT(end >= start && end <= size() + 1, return 0);
853 for (pos_type count = end - start; count; --count) {
854 if (!eraseChar(i, trackChanges))
861 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
862 char_type next, OutputParams const & runparams)
864 // Writing next here may circumvent a possible font change between
865 // c and next. Since next is only output if it forms a surrogate pair
866 // with c we can ignore this:
867 // A font change inside a surrogate pair does not make sense and is
868 // hopefully impossible to input.
869 // FIXME: change tracking
870 // Is this correct WRT change tracking?
871 Encoding const & encoding = *(runparams.encoding);
872 docstring latex1 = encoding.latexChar(next).first;
873 if (runparams.inIPA) {
874 string const tipashortcut = Encodings::TIPAShortcut(next);
875 if (!tipashortcut.empty()) {
876 latex1 = from_ascii(tipashortcut);
879 docstring const latex2 = encoding.latexChar(c).first;
880 if (docstring(1, next) == latex1) {
881 // the encoding supports the combination
882 os << latex2 << latex1;
883 return latex1.length() + latex2.length();
884 } else if (runparams.local_font &&
885 runparams.local_font->language()->lang() == "polutonikogreek") {
886 // polutonikogreek only works without the brackets
887 os << latex1 << latex2;
888 return latex1.length() + latex2.length();
890 os << latex1 << '{' << latex2 << '}';
891 return latex1.length() + latex2.length() + 2;
895 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
898 unsigned int & column,
900 Layout const & style)
902 if (style.pass_thru || runparams.pass_thru)
905 if (i + 1 < int(text_.size())) {
906 char_type next = text_[i + 1];
907 if (Encodings::isCombiningChar(next)) {
908 // This space has an accent, so we must always output it.
909 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
914 if (runparams.linelen > 0
915 && column > runparams.linelen
917 && text_[i - 1] != ' '
918 && (i + 1 < int(text_.size()))
919 // same in FreeSpacing mode
920 && !owner_->isFreeSpacing()
921 // In typewriter mode, we want to avoid
922 // ! . ? : at the end of a line
923 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
924 && (text_[i - 1] == '.'
925 || text_[i - 1] == '?'
926 || text_[i - 1] == ':'
927 || text_[i - 1] == '!'))) {
929 os.texrow().start(owner_->id(), i + 1);
931 } else if (style.free_spacing) {
940 int Paragraph::Private::writeScriptChars(otexstream & os,
941 docstring const & ltx,
942 Change const & runningChange,
943 Encoding const & encoding,
946 // FIXME: modifying i here is not very nice...
948 // We only arrive here when a proper language for character text_[i] has
949 // not been specified (i.e., it could not be translated in the current
950 // latex encoding) or its latex translation has been forced, and it
951 // belongs to a known script.
952 // Parameter ltx contains the latex translation of text_[i] as specified
953 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
954 // The latex macro name "textXXX" specifies the script to which text_[i]
955 // belongs and we use it in order to check whether characters from the
956 // same script immediately follow, such that we can collect them in a
957 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
958 // for the first char but only "<spec>" for all subsequent chars.
959 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
960 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
961 string script = to_ascii(ltx.substr(1, brace1 - 1));
964 bool closing_brace = true;
965 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
966 // Correct encoding is being used, so we can avoid \textgreek.
969 closing_brace = false;
971 os << ltx.substr(pos, length);
972 int size = text_.size();
973 while (i + 1 < size) {
974 char_type const next = text_[i + 1];
975 // Stop here if next character belongs to another script
976 // or there is a change in change tracking status.
977 if (!Encodings::isKnownScriptChar(next, script) ||
978 runningChange != owner_->lookupChange(i + 1))
982 FontList::const_iterator cit = fontlist_.begin();
983 FontList::const_iterator end = fontlist_.end();
984 for (; cit != end; ++cit) {
985 if (cit->pos() >= i && !found) {
986 prev_font = cit->font();
989 if (cit->pos() >= i + 1)
992 // Stop here if there is a font attribute or encoding change.
993 if (found && cit != end && prev_font != cit->font())
995 docstring const latex = encoding.latexChar(next).first;
996 docstring::size_type const b1 =
997 latex.find_first_of(from_ascii("{"));
998 docstring::size_type const b2 =
999 latex.find_last_of(from_ascii("}"));
1000 int const len = b2 - b1 - 1;
1001 os << latex.substr(b1 + 1, len);
1005 if (closing_brace) {
1013 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
1015 pos_type const len = str.length();
1017 // is the paragraph large enough?
1018 if (pos + len > int(text_.size()))
1021 // does the wanted text start at point?
1022 for (string::size_type i = 0; i < str.length(); ++i) {
1023 // Caution: direct comparison of characters works only
1024 // because str is pure ASCII.
1025 if (str[i] != text_[pos + i])
1029 return fontlist_.hasChangeInRange(pos, len);
1033 void Paragraph::Private::latexInset(BufferParams const & bparams,
1035 OutputParams & runparams,
1036 Font & running_font,
1038 Font const & outerfont,
1040 Change & running_change,
1041 Layout const & style,
1043 unsigned int & column)
1045 Inset * inset = owner_->getInset(i);
1048 if (style.pass_thru) {
1049 odocstringstream ods;
1050 inset->plaintext(ods, runparams);
1055 // FIXME: move this to InsetNewline::latex
1056 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1057 // newlines are handled differently here than
1058 // the default in simpleTeXSpecialChars().
1059 if (!style.newline_allowed) {
1063 column += running_font.latexWriteEndChanges(
1064 os, bparams, runparams,
1065 basefont, basefont);
1069 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1072 basefont = owner_->getLayoutFont(bparams, outerfont);
1073 running_font = basefont;
1075 if (runparams.moving_arg)
1079 os.texrow().start(owner_->id(), i + 1);
1083 if (owner_->isDeleted(i)) {
1084 if( ++runparams.inDeletedInset == 1)
1085 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1088 if (inset->canTrackChanges()) {
1089 column += Changes::latexMarkChange(os, bparams, running_change,
1090 Change(Change::UNCHANGED), runparams);
1091 running_change = Change(Change::UNCHANGED);
1095 odocstream::pos_type const len = os.os().tellp();
1097 if (inset->forceLTR()
1098 && !runparams.use_polyglossia
1099 && running_font.isRightToLeft()
1100 // ERT is an exception, it should be output with no
1101 // decorations at all
1102 && inset->lyxCode() != ERT_CODE) {
1103 if (running_font.language()->lang() == "farsi")
1110 // FIXME: Bug: we can have an empty font change here!
1111 // if there has just been a font change, we are going to close it
1112 // right now, which means stupid latex code like \textsf{}. AFAIK,
1113 // this does not harm dvi output. A minor bug, thus (JMarc)
1115 // Some insets cannot be inside a font change command.
1116 // However, even such insets *can* be placed in \L or \R
1117 // or their equivalents (for RTL language switches), so we don't
1118 // close the language in those cases.
1119 // ArabTeX, though, cannot handle this special behavior, it seems.
1120 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1121 || running_font.language()->lang() == "arabic_arabtex";
1122 if (open_font && !inset->inheritFont()) {
1123 bool closeLanguage = arabtex
1124 || basefont.isRightToLeft() == running_font.isRightToLeft();
1125 unsigned int count = running_font.latexWriteEndChanges(os,
1126 bparams, runparams, basefont, basefont, closeLanguage);
1128 // if any font properties were closed, update the running_font,
1129 // making sure, however, to leave the language as it was
1131 // FIXME: probably a better way to keep track of the old
1132 // language, than copying the entire font?
1133 Font const copy_font(running_font);
1134 basefont = owner_->getLayoutFont(bparams, outerfont);
1135 running_font = basefont;
1137 running_font.setLanguage(copy_font.language());
1138 // leave font open if language is still open
1139 open_font = (running_font.language() == basefont.language());
1141 runparams.local_font = &basefont;
1145 int prev_rows = os.texrow().rows();
1148 runparams.lastid = id_;
1149 runparams.lastpos = i;
1150 inset->latex(os, runparams);
1151 } catch (EncodingException & e) {
1152 // add location information and throw again.
1159 if (running_font.language()->lang() == "farsi")
1165 if (os.texrow().rows() > prev_rows) {
1166 os.texrow().start(owner_->id(), i + 1);
1169 column += (unsigned int)(os.os().tellp() - len);
1172 if (owner_->isDeleted(i))
1173 --runparams.inDeletedInset;
1177 void Paragraph::Private::latexSpecialChar(otexstream & os,
1178 BufferParams const & bparams,
1179 OutputParams const & runparams,
1180 Font const & running_font,
1181 Change const & running_change,
1182 Layout const & style,
1185 unsigned int & column)
1187 // With polyglossia, brackets and stuff need not be reversed
1188 // in RTL scripts (see bug #8251)
1189 char_type const c = (runparams.use_polyglossia) ?
1190 owner_->getUChar(bparams, i) : text_[i];
1192 if (style.pass_thru || runparams.pass_thru) {
1194 Encoding const * const enc = runparams.encoding;
1195 if (enc && !enc->encodable(c))
1196 throw EncodingException(c);
1202 // TIPA uses its own T3 encoding
1203 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1205 // If T1 font encoding is used, use the special
1206 // characters it provides.
1207 // NOTE: some languages reset the font encoding
1209 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1210 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1213 // Otherwise, we use what LaTeX provides us.
1216 os << "\\textbackslash{}";
1220 os << "\\textless{}";
1224 os << "\\textgreater{}";
1228 os << "\\textbar{}";
1233 if (i + 1 < end_pos && text_[i+1] == '-') {
1234 // Prevent "--" becoming an endash and "---" becoming
1236 // Within \ttfamily, "--" is merged to "-" (no endash)
1237 // so we avoid this rather irritating ligature as well
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{}";
1401 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1402 /// do not apply the macro transformation.
1403 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1404 unsigned int & column, OutputParams const & runparams)
1406 // FIXME: if we have "LaTeX" with a font
1407 // change in the middle (before the 'T', then
1408 // the "TeX" part is still special cased.
1409 // Really we should only operate this on
1410 // "words" for some definition of word
1412 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1413 if (!isTextAt(special_phrases[pnr].phrase, i)
1414 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1416 if (runparams.moving_arg)
1418 os << special_phrases[pnr].macro;
1419 i += special_phrases[pnr].phrase.length() - 1;
1420 column += special_phrases[pnr].macro.length() - 1;
1427 void Paragraph::Private::validate(LaTeXFeatures & features) const
1429 if (layout_->inpreamble && inset_owner_) {
1430 bool const is_command = layout_->latextype == LATEX_COMMAND;
1431 Buffer const & buf = inset_owner_->buffer();
1432 BufferParams const & bp = features.runparams().is_child
1433 ? buf.masterParams() : buf.params();
1436 // Using a string stream here circumvents the encoding
1437 // switching machinery of odocstream. Therefore the
1438 // output is wrong if this paragraph contains content
1439 // that needs to switch encoding.
1440 odocstringstream ods;
1441 otexstream os(ods, texrow);
1443 os << '\\' << from_ascii(layout_->latexname());
1444 // we have to provide all the optional arguments here, even though
1445 // the last one is the only one we care about.
1446 // Separate handling of optional argument inset.
1447 if (!layout_->latexargs().empty()) {
1448 OutputParams rp = features.runparams();
1449 rp.local_font = &owner_->getFirstFontSettings(bp);
1450 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1452 os << from_ascii(layout_->latexparam());
1454 docstring::size_type const length = ods.str().length();
1455 // this will output "{" at the beginning, but not at the end
1456 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1457 if (ods.str().length() > length) {
1460 if (!layout_->postcommandargs().empty()) {
1461 OutputParams rp = features.runparams();
1462 rp.local_font = &owner_->getFirstFontSettings(bp);
1463 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1466 string const snippet = to_utf8(ods.str());
1467 features.addPreambleSnippet(snippet);
1471 if (features.runparams().flavor == OutputParams::HTML
1472 && layout_->htmltitle()) {
1473 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1476 // check the params.
1477 if (!params_.spacing().isDefault())
1478 features.require("setspace");
1481 features.useLayout(layout_->name());
1484 fontlist_.validate(features);
1486 // then the indentation
1487 if (!params_.leftIndent().zero())
1488 features.require("ParagraphLeftIndent");
1491 InsetList::const_iterator icit = insetlist_.begin();
1492 InsetList::const_iterator iend = insetlist_.end();
1493 for (; icit != iend; ++icit) {
1495 icit->inset->validate(features);
1496 if (layout_->needprotect &&
1497 icit->inset->lyxCode() == FOOT_CODE)
1498 features.require("footmisc");
1502 // then the contents
1503 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1504 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1505 if (!special_phrases[pnr].builtin
1506 && isTextAt(special_phrases[pnr].phrase, i)) {
1507 features.require(special_phrases[pnr].phrase);
1511 BufferEncodings::validate(text_[i], features);
1515 /////////////////////////////////////////////////////////////////////
1519 /////////////////////////////////////////////////////////////////////
1522 Layout const emptyParagraphLayout;
1525 Paragraph::Paragraph()
1526 : d(new Paragraph::Private(this, emptyParagraphLayout))
1533 Paragraph::Paragraph(Paragraph const & par)
1534 : itemdepth(par.itemdepth),
1535 d(new Paragraph::Private(*par.d, this))
1541 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1542 : itemdepth(par.itemdepth),
1543 d(new Paragraph::Private(*par.d, this, beg, end))
1549 Paragraph & Paragraph::operator=(Paragraph const & par)
1551 // needed as we will destroy the private part before copying it
1553 itemdepth = par.itemdepth;
1557 d = new Private(*par.d, this);
1564 Paragraph::~Paragraph()
1573 // this shall be called just before every "os << ..." action.
1574 void flushString(ostream & os, docstring & s)
1583 void Paragraph::write(ostream & os, BufferParams const & bparams,
1584 depth_type & dth) const
1586 // The beginning or end of a deeper (i.e. nested) area?
1587 if (dth != d->params_.depth()) {
1588 if (d->params_.depth() > dth) {
1589 while (d->params_.depth() > dth) {
1590 os << "\n\\begin_deeper";
1594 while (d->params_.depth() < dth) {
1595 os << "\n\\end_deeper";
1601 // First write the layout
1602 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1604 d->params_.write(os);
1606 Font font1(inherit_font, bparams.language);
1608 Change running_change = Change(Change::UNCHANGED);
1610 // this string is used as a buffer to avoid repetitive calls
1611 // to to_utf8(), which turn out to be expensive (JMarc)
1612 docstring write_buffer;
1615 for (pos_type i = 0; i <= size(); ++i) {
1617 Change const & change = lookupChange(i);
1618 if (change != running_change)
1619 flushString(os, write_buffer);
1620 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1621 running_change = change;
1626 // Write font changes
1627 Font font2 = getFontSettings(bparams, i);
1628 if (font2 != font1) {
1629 flushString(os, write_buffer);
1630 font2.lyxWriteChanges(font1, os);
1635 char_type const c = d->text_[i];
1638 if (Inset const * inset = getInset(i)) {
1639 flushString(os, write_buffer);
1640 if (inset->directWrite()) {
1641 // international char, let it write
1642 // code directly so it's shorter in
1648 os << "\\begin_inset ";
1650 os << "\n\\end_inset\n\n";
1653 // FIXME This can be removed again once the mystery
1654 // crash has been resolved.
1659 flushString(os, write_buffer);
1660 os << "\n\\backslash\n";
1664 flushString(os, write_buffer);
1665 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1672 if ((column > 70 && c == ' ')
1674 flushString(os, write_buffer);
1678 // this check is to amend a bug. LyX sometimes
1679 // inserts '\0' this could cause problems.
1681 write_buffer.push_back(c);
1683 LYXERR0("NUL char in structure.");
1689 flushString(os, write_buffer);
1690 os << "\n\\end_layout\n";
1691 // FIXME This can be removed again once the mystery
1692 // crash has been resolved.
1697 void Paragraph::validate(LaTeXFeatures & features) const
1699 d->validate(features);
1703 void Paragraph::insert(pos_type start, docstring const & str,
1704 Font const & font, Change const & change)
1706 for (size_t i = 0, n = str.size(); i != n ; ++i)
1707 insertChar(start + i, str[i], font, change);
1711 void Paragraph::appendChar(char_type c, Font const & font,
1712 Change const & change)
1715 d->changes_.insert(change, d->text_.size());
1716 // when appending characters, no need to update tables
1717 d->text_.push_back(c);
1718 setFont(d->text_.size() - 1, font);
1719 d->requestSpellCheck(d->text_.size() - 1);
1723 void Paragraph::appendString(docstring const & s, Font const & font,
1724 Change const & change)
1726 pos_type end = s.size();
1727 size_t oldsize = d->text_.size();
1728 size_t newsize = oldsize + end;
1729 size_t capacity = d->text_.capacity();
1730 if (newsize >= capacity)
1731 d->text_.reserve(max(capacity + 100, newsize));
1733 // when appending characters, no need to update tables
1736 // FIXME: Optimize this!
1737 for (size_t i = oldsize; i != newsize; ++i) {
1739 d->changes_.insert(change, i);
1740 d->requestSpellCheck(i);
1742 d->fontlist_.set(oldsize, font);
1743 d->fontlist_.set(newsize - 1, font);
1747 void Paragraph::insertChar(pos_type pos, char_type c,
1750 d->insertChar(pos, c, Change(trackChanges ?
1751 Change::INSERTED : Change::UNCHANGED));
1755 void Paragraph::insertChar(pos_type pos, char_type c,
1756 Font const & font, bool trackChanges)
1758 d->insertChar(pos, c, Change(trackChanges ?
1759 Change::INSERTED : Change::UNCHANGED));
1764 void Paragraph::insertChar(pos_type pos, char_type c,
1765 Font const & font, Change const & change)
1767 d->insertChar(pos, c, change);
1772 void Paragraph::resetFonts(Font const & font)
1774 d->fontlist_.clear();
1775 d->fontlist_.set(0, font);
1776 d->fontlist_.set(d->text_.size() - 1, font);
1779 // Gets uninstantiated font setting at position.
1780 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1784 LYXERR0("pos: " << pos << " size: " << size());
1788 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1789 if (cit != d->fontlist_.end())
1792 if (pos == size() && !empty())
1793 return getFontSettings(bparams, pos - 1);
1795 // Optimisation: avoid a full font instantiation if there is no
1796 // language change from previous call.
1797 static Font previous_font;
1798 static Language const * previous_lang = 0;
1799 Language const * lang = getParLanguage(bparams);
1800 if (lang != previous_lang) {
1801 previous_lang = lang;
1802 previous_font = Font(inherit_font, lang);
1804 return previous_font;
1808 FontSpan Paragraph::fontSpan(pos_type pos) const
1810 LBUFERR(pos < size());
1813 FontList::const_iterator cit = d->fontlist_.begin();
1814 FontList::const_iterator end = d->fontlist_.end();
1815 for (; cit != end; ++cit) {
1816 if (cit->pos() >= pos) {
1817 if (pos >= beginOfBody())
1818 return FontSpan(max(start, beginOfBody()),
1821 return FontSpan(start,
1822 min(beginOfBody() - 1,
1825 start = cit->pos() + 1;
1828 // This should not happen, but if so, we take no chances.
1829 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1830 LASSERT(false, return FontSpan(pos, pos));
1834 // Gets uninstantiated font setting at position 0
1835 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1837 if (!empty() && !d->fontlist_.empty())
1838 return d->fontlist_.begin()->font();
1840 // Optimisation: avoid a full font instantiation if there is no
1841 // language change from previous call.
1842 static Font previous_font;
1843 static Language const * previous_lang = 0;
1844 if (bparams.language != previous_lang) {
1845 previous_lang = bparams.language;
1846 previous_font = Font(inherit_font, bparams.language);
1849 return previous_font;
1853 // Gets the fully instantiated font at a given position in a paragraph
1854 // This is basically the same function as Text::GetFont() in text2.cpp.
1855 // The difference is that this one is used for generating the LaTeX file,
1856 // and thus cosmetic "improvements" are disallowed: This has to deliver
1857 // the true picture of the buffer. (Asger)
1858 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1859 Font const & outerfont) const
1863 Font font = getFontSettings(bparams, pos);
1865 pos_type const body_pos = beginOfBody();
1866 FontInfo & fi = font.fontInfo();
1868 fi.realize(d->layout_->labelfont);
1870 fi.realize(d->layout_->font);
1872 fi.realize(outerfont.fontInfo());
1873 fi.realize(bparams.getFont().fontInfo());
1879 Font const Paragraph::getLabelFont
1880 (BufferParams const & bparams, Font const & outerfont) const
1882 FontInfo tmpfont = d->layout_->labelfont;
1883 tmpfont.realize(outerfont.fontInfo());
1884 tmpfont.realize(bparams.getFont().fontInfo());
1885 return Font(tmpfont, getParLanguage(bparams));
1889 Font const Paragraph::getLayoutFont
1890 (BufferParams const & bparams, Font const & outerfont) const
1892 FontInfo tmpfont = d->layout_->font;
1893 tmpfont.realize(outerfont.fontInfo());
1894 tmpfont.realize(bparams.getFont().fontInfo());
1895 return Font(tmpfont, getParLanguage(bparams));
1899 /// Returns the height of the highest font in range
1900 FontSize Paragraph::highestFontInRange
1901 (pos_type startpos, pos_type endpos, FontSize def_size) const
1903 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1907 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1909 char_type c = d->text_[pos];
1910 if (!getFontSettings(bparams, pos).isRightToLeft())
1913 // FIXME: The arabic special casing is due to the difference of arabic
1914 // round brackets input introduced in r18599. Check if this should be
1915 // unified with Hebrew or at least if all bracket types should be
1916 // handled the same (file format change in either case).
1917 string const & lang = getFontSettings(bparams, pos).language()->lang();
1918 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1923 uc = arabic ? c : ')';
1926 uc = arabic ? c : '(';
1952 void Paragraph::setFont(pos_type pos, Font const & font)
1954 LASSERT(pos <= size(), return);
1956 // First, reduce font against layout/label font
1957 // Update: The setCharFont() routine in text2.cpp already
1958 // reduces font, so we don't need to do that here. (Asger)
1960 d->fontlist_.set(pos, font);
1964 void Paragraph::makeSameLayout(Paragraph const & par)
1966 d->layout_ = par.d->layout_;
1967 d->params_ = par.d->params_;
1971 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1973 if (isFreeSpacing())
1979 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1980 if (eraseChar(pos, trackChanges))
1986 return count > 0 || pos > 0;
1990 bool Paragraph::hasSameLayout(Paragraph const & par) const
1992 return par.d->layout_ == d->layout_
1993 && d->params_.sameLayout(par.d->params_);
1997 depth_type Paragraph::getDepth() const
1999 return d->params_.depth();
2003 depth_type Paragraph::getMaxDepthAfter() const
2005 if (d->layout_->isEnvironment())
2006 return d->params_.depth() + 1;
2008 return d->params_.depth();
2012 char Paragraph::getAlign() const
2014 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2015 return d->layout_->align;
2017 return d->params_.align();
2021 docstring const & Paragraph::labelString() const
2023 return d->params_.labelString();
2027 // the next two functions are for the manual labels
2028 docstring const Paragraph::getLabelWidthString() const
2030 if (d->layout_->margintype == MARGIN_MANUAL
2031 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2032 return d->params_.labelWidthString();
2034 return _("Senseless with this layout!");
2038 void Paragraph::setLabelWidthString(docstring const & s)
2040 d->params_.labelWidthString(s);
2044 docstring Paragraph::expandLabel(Layout const & layout,
2045 BufferParams const & bparams) const
2047 return expandParagraphLabel(layout, bparams, true);
2051 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2052 BufferParams const & bparams) const
2054 return expandParagraphLabel(layout, bparams, false);
2058 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2059 BufferParams const & bparams, bool process_appendix) const
2061 DocumentClass const & tclass = bparams.documentClass();
2062 string const & lang = getParLanguage(bparams)->code();
2063 bool const in_appendix = process_appendix && d->params_.appendix();
2064 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2066 if (fmt.empty() && !layout.counter.empty())
2067 return tclass.counters().theCounter(layout.counter, lang);
2069 // handle 'inherited level parts' in 'fmt',
2070 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2071 size_t const i = fmt.find('@', 0);
2072 if (i != docstring::npos) {
2073 size_t const j = fmt.find('@', i + 1);
2074 if (j != docstring::npos) {
2075 docstring parent(fmt, i + 1, j - i - 1);
2076 docstring label = from_ascii("??");
2077 if (tclass.hasLayout(parent))
2078 docstring label = expandParagraphLabel(tclass[parent], bparams,
2080 fmt = docstring(fmt, 0, i) + label
2081 + docstring(fmt, j + 1, docstring::npos);
2085 return tclass.counters().counterLabel(fmt, lang);
2089 void Paragraph::applyLayout(Layout const & new_layout)
2091 d->layout_ = &new_layout;
2092 LyXAlignment const oldAlign = d->params_.align();
2094 if (!(oldAlign & d->layout_->alignpossible)) {
2095 frontend::Alert::warning(_("Alignment not permitted"),
2096 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2097 d->params_.align(LYX_ALIGN_LAYOUT);
2102 pos_type Paragraph::beginOfBody() const
2104 return d->begin_of_body_;
2108 void Paragraph::setBeginOfBody()
2110 if (d->layout_->labeltype != LABEL_MANUAL) {
2111 d->begin_of_body_ = 0;
2115 // Unroll the first two cycles of the loop
2116 // and remember the previous character to
2117 // remove unnecessary getChar() calls
2119 pos_type end = size();
2120 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2122 char_type previous_char = 0;
2125 previous_char = d->text_[i];
2126 if (!(isNewline(i) || isEnvSeparator(i))) {
2128 while (i < end && previous_char != ' ') {
2130 if (isNewline(i) || isEnvSeparator(i))
2133 previous_char = temp;
2139 d->begin_of_body_ = i;
2143 bool Paragraph::allowParagraphCustomization() const
2145 return inInset().allowParagraphCustomization();
2149 bool Paragraph::usePlainLayout() const
2151 return inInset().usePlainLayout();
2155 bool Paragraph::isPassThru() const
2157 return inInset().isPassThru() || d->layout_->pass_thru;
2162 // paragraphs inside floats need different alignment tags to avoid
2165 bool noTrivlistCentering(InsetCode code)
2167 return code == FLOAT_CODE
2168 || code == WRAP_CODE
2169 || code == CELL_CODE;
2173 string correction(string const & orig)
2175 if (orig == "flushleft")
2176 return "raggedright";
2177 if (orig == "flushright")
2178 return "raggedleft";
2179 if (orig == "center")
2185 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2186 InsetCode code, bool const lastpar, int & col)
2188 string macro = suffix + "{";
2189 if (noTrivlistCentering(code)) {
2191 // the last paragraph in non-trivlist-aligned
2192 // context is special (to avoid unwanted whitespace)
2193 if (suffix == "\\begin") {
2194 macro = "\\" + correction(env) + "{}";
2195 os << from_ascii(macro);
2196 col += macro.size();
2201 macro += correction(env);
2205 if (suffix == "\\par\\end") {
2209 os << from_ascii(macro);
2210 col += macro.size();
2211 if (suffix == "\\begin") {
2221 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2222 otexstream & os, OutputParams const & runparams) const
2226 if (params_.noindent() && !layout_->pass_thru
2227 && (layout_->toggle_indent != ITOGGLE_NEVER)) {
2228 os << "\\noindent ";
2232 LyXAlignment const curAlign = params_.align();
2234 if (curAlign == layout_->align)
2238 case LYX_ALIGN_NONE:
2239 case LYX_ALIGN_BLOCK:
2240 case LYX_ALIGN_LAYOUT:
2241 case LYX_ALIGN_SPECIAL:
2242 case LYX_ALIGN_DECIMAL:
2244 case LYX_ALIGN_LEFT:
2245 case LYX_ALIGN_RIGHT:
2246 case LYX_ALIGN_CENTER:
2247 if (runparams.moving_arg) {
2254 string const begin_tag = "\\begin";
2255 InsetCode code = ownerCode();
2256 bool const lastpar = runparams.isLastPar;
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 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2267 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2269 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2271 } case LYX_ALIGN_RIGHT: {
2273 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2274 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2276 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2278 } case LYX_ALIGN_CENTER: {
2279 corrected_env(os, begin_tag, "center", code, lastpar, column);
2288 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2289 otexstream & os, OutputParams const & runparams) const
2291 LyXAlignment const curAlign = params_.align();
2293 if (curAlign == layout_->align)
2297 case LYX_ALIGN_NONE:
2298 case LYX_ALIGN_BLOCK:
2299 case LYX_ALIGN_LAYOUT:
2300 case LYX_ALIGN_SPECIAL:
2301 case LYX_ALIGN_DECIMAL:
2303 case LYX_ALIGN_LEFT:
2304 case LYX_ALIGN_RIGHT:
2305 case LYX_ALIGN_CENTER:
2306 if (runparams.moving_arg)
2311 bool output = false;
2313 string const end_tag = "\\par\\end";
2314 InsetCode code = ownerCode();
2315 bool const lastpar = runparams.isLastPar;
2318 case LYX_ALIGN_NONE:
2319 case LYX_ALIGN_BLOCK:
2320 case LYX_ALIGN_LAYOUT:
2321 case LYX_ALIGN_SPECIAL:
2322 case LYX_ALIGN_DECIMAL:
2324 case LYX_ALIGN_LEFT: {
2325 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2326 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2328 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2330 } case LYX_ALIGN_RIGHT: {
2331 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2332 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2334 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2336 } case LYX_ALIGN_CENTER: {
2337 corrected_env(os, end_tag, "center", code, lastpar, col);
2342 return output || lastpar;
2346 // This one spits out the text of the paragraph
2347 void Paragraph::latex(BufferParams const & bparams,
2348 Font const & outerfont,
2350 OutputParams const & runparams,
2351 int start_pos, int end_pos, bool force) const
2353 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2355 // FIXME This check should not be needed. Perhaps issue an
2356 // error if it triggers.
2357 Layout const & style = inInset().forcePlainLayout() ?
2358 bparams.documentClass().plainLayout() : *d->layout_;
2360 if (!force && style.inpreamble)
2363 bool const allowcust = allowParagraphCustomization();
2365 // Current base font for all inherited font changes, without any
2366 // change caused by an individual character, except for the language:
2367 // It is set to the language of the first character.
2368 // As long as we are in the label, this font is the base font of the
2369 // label. Before the first body character it is set to the base font
2373 // Maybe we have to create a optional argument.
2374 pos_type body_pos = beginOfBody();
2375 unsigned int column = 0;
2378 // the optional argument is kept in curly brackets in
2379 // case it contains a ']'
2380 // This is not strictly needed, but if this is changed it
2381 // would be a file format change, and tex2lyx would need
2382 // to be adjusted, since it unconditionally removes the
2383 // braces when it parses \item.
2386 basefont = getLabelFont(bparams, outerfont);
2388 basefont = getLayoutFont(bparams, outerfont);
2391 // Which font is currently active?
2392 Font running_font(basefont);
2393 // Do we have an open font change?
2394 bool open_font = false;
2396 Change runningChange = Change(Change::UNCHANGED);
2398 Encoding const * const prev_encoding = runparams.encoding;
2400 os.texrow().start(id(), 0);
2402 // if the paragraph is empty, the loop will not be entered at all
2404 if (style.isCommand()) {
2408 if (!style.leftdelim().empty()) {
2409 os << style.leftdelim();
2410 column += style.leftdelim().size();
2413 column += d->startTeXParParams(bparams, os, runparams);
2416 for (pos_type i = 0; i < size(); ++i) {
2417 // First char in paragraph or after label?
2418 if (i == body_pos) {
2421 column += running_font.latexWriteEndChanges(
2422 os, bparams, runparams,
2423 basefont, basefont);
2426 basefont = getLayoutFont(bparams, outerfont);
2427 running_font = basefont;
2429 column += Changes::latexMarkChange(os, bparams,
2430 runningChange, Change(Change::UNCHANGED),
2432 runningChange = Change(Change::UNCHANGED);
2437 if (style.isCommand()) {
2442 if (!style.leftdelim().empty()) {
2443 os << style.leftdelim();
2444 column += style.leftdelim().size();
2448 column += d->startTeXParParams(bparams, os,
2452 Change const & change = runparams.inDeletedInset
2453 ? runparams.changeOfDeletedInset : lookupChange(i);
2455 if (bparams.output_changes && runningChange != change) {
2457 column += running_font.latexWriteEndChanges(
2458 os, bparams, runparams, basefont, basefont);
2461 basefont = getLayoutFont(bparams, outerfont);
2462 running_font = basefont;
2464 column += Changes::latexMarkChange(os, bparams, runningChange,
2466 runningChange = change;
2469 // do not output text which is marked deleted
2470 // if change tracking output is disabled
2471 if (!bparams.output_changes && change.deleted()) {
2477 // Fully instantiated font
2478 Font const font = getFont(bparams, i, outerfont);
2480 Font const last_font = running_font;
2482 // Do we need to close the previous font?
2484 (font != running_font ||
2485 font.language() != running_font.language()))
2487 column += running_font.latexWriteEndChanges(
2488 os, bparams, runparams, basefont,
2489 (i == body_pos-1) ? basefont : font);
2490 running_font = basefont;
2494 string const running_lang = runparams.use_polyglossia ?
2495 running_font.language()->polyglossia() : running_font.language()->babel();
2496 // close babel's font environment before opening CJK.
2497 string const lang_end_command = runparams.use_polyglossia ?
2498 "\\end{$$lang}" : lyxrc.language_command_end;
2499 if (!running_lang.empty() &&
2500 font.language()->encoding()->package() == Encoding::CJK) {
2501 string end_tag = subst(lang_end_command,
2504 os << from_ascii(end_tag);
2505 column += end_tag.length();
2508 // Switch file encoding if necessary (and allowed)
2509 if (!runparams.pass_thru && !style.pass_thru &&
2510 runparams.encoding->package() != Encoding::none &&
2511 font.language()->encoding()->package() != Encoding::none) {
2512 pair<bool, int> const enc_switch =
2513 switchEncoding(os.os(), bparams, runparams,
2514 *(font.language()->encoding()));
2515 if (enc_switch.first) {
2516 column += enc_switch.second;
2517 runparams.encoding = font.language()->encoding();
2521 char_type const c = d->text_[i];
2523 // Do we need to change font?
2524 if ((font != running_font ||
2525 font.language() != running_font.language()) &&
2528 odocstringstream ods;
2529 column += font.latexWriteStartChanges(ods, bparams,
2530 runparams, basefont,
2532 running_font = font;
2534 docstring fontchange = ods.str();
2535 // check whether the fontchange ends with a \\textcolor
2536 // modifier and the text starts with a space (bug 4473)
2537 docstring const last_modifier = rsplit(fontchange, '\\');
2538 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2539 os << fontchange << from_ascii("{}");
2540 // check if the fontchange ends with a trailing blank
2541 // (like "\small " (see bug 3382)
2542 else if (suffixIs(fontchange, ' ') && c == ' ')
2543 os << fontchange.substr(0, fontchange.size() - 1)
2544 << from_ascii("{}");
2549 // FIXME: think about end_pos implementation...
2550 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2551 // FIXME: integrate this case in latexSpecialChar
2552 // Do not print the separation of the optional argument
2553 // if style.pass_thru is false. This works because
2554 // latexSpecialChar ignores spaces if
2555 // style.pass_thru is false.
2556 if (i != body_pos - 1) {
2557 if (d->simpleTeXBlanks(runparams, os,
2558 i, column, font, style)) {
2559 // A surrogate pair was output. We
2560 // must not call latexSpecialChar
2561 // in this iteration, since it would output
2562 // the combining character again.
2569 OutputParams rp = runparams;
2570 rp.free_spacing = style.free_spacing;
2571 rp.local_font = &font;
2572 rp.intitle = style.intitle;
2574 // Two major modes: LaTeX or plain
2575 // Handle here those cases common to both modes
2576 // and then split to handle the two modes separately.
2577 if (c == META_INSET) {
2578 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2579 d->latexInset(bparams, os, rp, running_font,
2580 basefont, outerfont, open_font,
2581 runningChange, style, i, column);
2584 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2586 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2587 style, i, end_pos, column);
2588 } catch (EncodingException & e) {
2589 if (runparams.dryrun) {
2590 os << "<" << _("LyX Warning: ")
2591 << _("uncodable character") << " '";
2595 // add location information and throw again.
2604 // Set the encoding to that returned from latexSpecialChar (see
2605 // comment for encoding member in OutputParams.h)
2606 runparams.encoding = rp.encoding;
2609 // If we have an open font definition, we have to close it
2611 #ifdef FIXED_LANGUAGE_END_DETECTION
2613 running_font.latexWriteEndChanges(os, bparams,
2614 runparams, basefont,
2615 next_->getFont(bparams, 0, outerfont));
2617 running_font.latexWriteEndChanges(os, bparams,
2618 runparams, basefont, basefont);
2621 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2622 //FIXME: there as we start another \selectlanguage with the next paragraph if
2623 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2624 running_font.latexWriteEndChanges(os, bparams, runparams,
2625 basefont, basefont);
2629 column += Changes::latexMarkChange(os, bparams, runningChange,
2630 Change(Change::UNCHANGED), runparams);
2632 // Needed if there is an optional argument but no contents.
2633 if (body_pos > 0 && body_pos == size()) {
2637 if (!style.rightdelim().empty()) {
2638 os << style.rightdelim();
2639 column += style.rightdelim().size();
2642 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2643 && runparams.encoding != prev_encoding) {
2644 runparams.encoding = prev_encoding;
2645 if (!runparams.isFullUnicode())
2646 os << setEncoding(prev_encoding->iconvName());
2649 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2653 bool Paragraph::emptyTag() const
2655 for (pos_type i = 0; i < size(); ++i) {
2656 if (Inset const * inset = getInset(i)) {
2657 InsetCode lyx_code = inset->lyxCode();
2658 // FIXME testing like that is wrong. What is
2660 if (lyx_code != TOC_CODE &&
2661 lyx_code != INCLUDE_CODE &&
2662 lyx_code != GRAPHICS_CODE &&
2663 lyx_code != ERT_CODE &&
2664 lyx_code != LISTINGS_CODE &&
2665 lyx_code != FLOAT_CODE &&
2666 lyx_code != TABULAR_CODE) {
2670 char_type c = d->text_[i];
2671 if (c != ' ' && c != '\t')
2679 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2682 for (pos_type i = 0; i < size(); ++i) {
2683 if (Inset const * inset = getInset(i)) {
2684 InsetCode lyx_code = inset->lyxCode();
2685 if (lyx_code == LABEL_CODE) {
2686 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2687 docstring const & id = il->getParam("name");
2688 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2696 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2700 for (i = 0; i < size(); ++i) {
2701 if (Inset const * inset = getInset(i)) {
2702 inset->docbook(os, runparams);
2704 char_type c = d->text_[i];
2707 os << sgml::escapeChar(c);
2714 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2718 for (i = 0; i < size(); ++i) {
2719 if (Inset const * inset = getInset(i)) {
2720 inset->xhtml(xs, runparams);
2722 char_type c = d->text_[i];
2732 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2735 pos_type size = text_.size();
2736 for (pos_type i = initial; i < size; ++i) {
2737 Font font = owner_->getFont(buf.params(), i, outerfont);
2738 if (text_[i] == META_INSET)
2740 if (i != initial && font != font_old)
2749 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2751 OutputParams const & runparams,
2752 Font const & outerfont,
2753 pos_type initial) const
2755 bool emph_flag = false;
2757 Layout const & style = *d->layout_;
2759 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2761 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2764 // parsing main loop
2765 for (pos_type i = initial; i < size(); ++i) {
2766 Font font = getFont(buf.params(), i, outerfont);
2768 // handle <emphasis> tag
2769 if (font_old.emph() != font.fontInfo().emph()) {
2770 if (font.fontInfo().emph() == FONT_ON) {
2773 } else if (i != initial) {
2774 os << "</emphasis>";
2779 if (Inset const * inset = getInset(i)) {
2780 inset->docbook(os, runparams);
2782 char_type c = d->text_[i];
2784 if (style.pass_thru)
2787 os << sgml::escapeChar(c);
2789 font_old = font.fontInfo();
2793 os << "</emphasis>";
2796 if (style.free_spacing)
2798 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2804 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2805 vector<html::EndFontTag> & tagsToClose,
2806 bool & flag, FontState curstate, html::FontTypes type)
2808 if (curstate == FONT_ON) {
2809 tagsToOpen.push_back(html::FontTag(type));
2812 tagsToClose.push_back(html::EndFontTag(type));
2819 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2821 OutputParams const & runparams,
2822 Font const & outerfont,
2823 pos_type initial) const
2827 // track whether we have opened these tags
2828 bool emph_flag = false;
2829 bool bold_flag = false;
2830 bool noun_flag = false;
2831 bool ubar_flag = false;
2832 bool dbar_flag = false;
2833 bool sout_flag = false;
2834 bool wave_flag = false;
2836 bool shap_flag = false;
2838 bool faml_flag = false;
2840 bool size_flag = false;
2842 Layout const & style = *d->layout_;
2844 xs.startParagraph(allowEmpty());
2847 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2849 FontShape curr_fs = INHERIT_SHAPE;
2850 FontFamily curr_fam = INHERIT_FAMILY;
2851 FontSize curr_size = FONT_SIZE_INHERIT;
2853 string const default_family =
2854 buf.masterBuffer()->params().fonts_default_family;
2856 vector<html::FontTag> tagsToOpen;
2857 vector<html::EndFontTag> tagsToClose;
2859 // parsing main loop
2860 for (pos_type i = initial; i < size(); ++i) {
2861 // let's not show deleted material in the output
2865 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2868 FontState curstate = font.fontInfo().emph();
2869 if (font_old.emph() != curstate)
2870 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2873 curstate = font.fontInfo().noun();
2874 if (font_old.noun() != curstate)
2875 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2878 curstate = font.fontInfo().underbar();
2879 if (font_old.underbar() != curstate)
2880 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2883 curstate = font.fontInfo().strikeout();
2884 if (font_old.strikeout() != curstate)
2885 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2888 curstate = font.fontInfo().uuline();
2889 if (font_old.uuline() != curstate)
2890 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2893 curstate = font.fontInfo().uwave();
2894 if (font_old.uwave() != curstate)
2895 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2898 // a little hackish, but allows us to reuse what we have.
2899 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2900 if (font_old.series() != font.fontInfo().series())
2901 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2904 curr_fs = font.fontInfo().shape();
2905 FontShape old_fs = font_old.shape();
2906 if (old_fs != curr_fs) {
2910 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2913 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2915 case SMALLCAPS_SHAPE:
2916 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2922 // the other tags are for internal use
2930 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2934 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2937 case SMALLCAPS_SHAPE:
2938 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2945 // the other tags are for internal use
2952 curr_fam = font.fontInfo().family();
2953 FontFamily old_fam = font_old.family();
2954 if (old_fam != curr_fam) {
2958 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2961 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2963 case TYPEWRITER_FAMILY:
2964 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2966 case INHERIT_FAMILY:
2969 // the other tags are for internal use
2977 // we will treat a "default" font family as roman, since we have
2978 // no other idea what to do.
2979 if (default_family != "rmdefault" && default_family != "default") {
2980 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
2985 if (default_family != "sfdefault") {
2986 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
2990 case TYPEWRITER_FAMILY:
2991 if (default_family != "ttdefault") {
2992 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
2996 case INHERIT_FAMILY:
2999 // the other tags are for internal use
3006 curr_size = font.fontInfo().size();
3007 FontSize old_size = font_old.size();
3008 if (old_size != curr_size) {
3011 case FONT_SIZE_TINY:
3012 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3014 case FONT_SIZE_SCRIPT:
3015 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3017 case FONT_SIZE_FOOTNOTE:
3018 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3020 case FONT_SIZE_SMALL:
3021 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3023 case FONT_SIZE_LARGE:
3024 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3026 case FONT_SIZE_LARGER:
3027 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3029 case FONT_SIZE_LARGEST:
3030 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3032 case FONT_SIZE_HUGE:
3033 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3035 case FONT_SIZE_HUGER:
3036 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3038 case FONT_SIZE_INCREASE:
3039 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3041 case FONT_SIZE_DECREASE:
3042 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3044 case FONT_SIZE_INHERIT:
3045 case FONT_SIZE_NORMAL:
3048 // the other tags are for internal use
3054 switch (curr_size) {
3055 case FONT_SIZE_TINY:
3056 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3059 case FONT_SIZE_SCRIPT:
3060 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3063 case FONT_SIZE_FOOTNOTE:
3064 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3067 case FONT_SIZE_SMALL:
3068 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3071 case FONT_SIZE_LARGE:
3072 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3075 case FONT_SIZE_LARGER:
3076 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3079 case FONT_SIZE_LARGEST:
3080 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3083 case FONT_SIZE_HUGE:
3084 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3087 case FONT_SIZE_HUGER:
3088 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3091 case FONT_SIZE_INCREASE:
3092 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3095 case FONT_SIZE_DECREASE:
3096 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3099 case FONT_SIZE_NORMAL:
3100 case FONT_SIZE_INHERIT:
3103 // the other tags are for internal use
3110 // Other such tags? What about the other text ranges?
3112 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3113 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3114 for (; cit != cen; ++cit)
3117 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3118 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3119 for (; sit != sen; ++sit)
3122 tagsToClose.clear();
3125 Inset const * inset = getInset(i);
3127 if (!runparams.for_toc || inset->isInToc()) {
3128 OutputParams np = runparams;
3129 np.local_font = &font;
3130 if (!inset->getLayout().htmlisblock())
3131 np.html_in_par = true;
3132 retval += inset->xhtml(xs, np);
3135 char_type c = getUChar(buf.masterBuffer()->params(), i);
3138 font_old = font.fontInfo();
3147 bool Paragraph::isHfill(pos_type pos) const
3149 Inset const * inset = getInset(pos);
3150 return inset && inset->isHfill();
3154 bool Paragraph::isNewline(pos_type pos) const
3156 Inset const * inset = getInset(pos);
3157 return inset && inset->lyxCode() == NEWLINE_CODE;
3161 bool Paragraph::isEnvSeparator(pos_type pos) const
3163 Inset const * inset = getInset(pos);
3164 return inset && inset->lyxCode() == SEPARATOR_CODE;
3168 bool Paragraph::isLineSeparator(pos_type pos) const
3170 char_type const c = d->text_[pos];
3171 if (isLineSeparatorChar(c))
3173 Inset const * inset = getInset(pos);
3174 return inset && inset->isLineSeparator();
3178 bool Paragraph::isWordSeparator(pos_type pos) const
3182 if (Inset const * inset = getInset(pos))
3183 return !inset->isLetter();
3184 // if we have a hard hyphen (no en- or emdash) or apostrophe
3185 // we pass this to the spell checker
3186 // FIXME: this method is subject to change, visit
3187 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3188 // to get an impression how complex this is.
3189 if (isHardHyphenOrApostrophe(pos))
3191 char_type const c = d->text_[pos];
3192 // We want to pass the escape chars to the spellchecker
3193 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3194 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3198 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3200 pos_type const psize = size();
3203 char_type const c = d->text_[pos];
3204 if (c != '-' && c != '\'')
3206 int nextpos = pos + 1;
3207 int prevpos = pos > 0 ? pos - 1 : 0;
3208 if ((nextpos == psize || isSpace(nextpos))
3209 && (pos == 0 || isSpace(prevpos)))
3215 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
3218 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
3222 bool Paragraph::isChar(pos_type pos) const
3224 if (Inset const * inset = getInset(pos))
3225 return inset->isChar();
3226 char_type const c = d->text_[pos];
3227 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3231 bool Paragraph::isSpace(pos_type pos) const
3233 if (Inset const * inset = getInset(pos))
3234 return inset->isSpace();
3235 char_type const c = d->text_[pos];
3236 return lyx::isSpace(c);
3241 Paragraph::getParLanguage(BufferParams const & bparams) const
3244 return getFirstFontSettings(bparams).language();
3245 // FIXME: we should check the prev par as well (Lgb)
3246 return bparams.language;
3250 bool Paragraph::isRTL(BufferParams const & bparams) const
3252 return getParLanguage(bparams)->rightToLeft()
3253 && !inInset().getLayout().forceLTR();
3257 void Paragraph::changeLanguage(BufferParams const & bparams,
3258 Language const * from, Language const * to)
3260 // change language including dummy font change at the end
3261 for (pos_type i = 0; i <= size(); ++i) {
3262 Font font = getFontSettings(bparams, i);
3263 if (font.language() == from) {
3264 font.setLanguage(to);
3266 d->requestSpellCheck(i);
3272 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3274 Language const * doc_language = bparams.language;
3275 FontList::const_iterator cit = d->fontlist_.begin();
3276 FontList::const_iterator end = d->fontlist_.end();
3278 for (; cit != end; ++cit)
3279 if (cit->font().language() != ignore_language &&
3280 cit->font().language() != latex_language &&
3281 cit->font().language() != doc_language)
3287 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3289 FontList::const_iterator cit = d->fontlist_.begin();
3290 FontList::const_iterator end = d->fontlist_.end();
3292 for (; cit != end; ++cit) {
3293 Language const * lang = cit->font().language();
3294 if (lang != ignore_language &&
3295 lang != latex_language)
3296 languages.insert(lang);
3301 docstring Paragraph::asString(int options) const
3303 return asString(0, size(), options);
3307 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3309 odocstringstream os;
3312 && options & AS_STR_LABEL
3313 && !d->params_.labelString().empty())
3314 os << d->params_.labelString() << ' ';
3316 for (pos_type i = beg; i < end; ++i) {
3317 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3319 char_type const c = d->text_[i];
3320 if (isPrintable(c) || c == '\t'
3321 || (c == '\n' && (options & AS_STR_NEWLINES)))
3323 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3324 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3325 LASSERT(runparams != 0, return docstring());
3326 getInset(i)->plaintext(os, *runparams);
3328 getInset(i)->toString(os);
3337 void Paragraph::forOutliner(docstring & os, size_t maxlen) const
3339 if (!d->params_.labelString().empty())
3340 os += d->params_.labelString() + ' ';
3341 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3344 char_type const c = d->text_[i];
3347 else if (c == '\t' || c == '\n')
3349 else if (c == META_INSET)
3350 getInset(i)->forOutliner(os, maxlen);
3355 void Paragraph::setInsetOwner(Inset const * inset)
3357 d->inset_owner_ = inset;
3361 int Paragraph::id() const
3367 void Paragraph::setId(int id)
3373 Layout const & Paragraph::layout() const
3379 void Paragraph::setLayout(Layout const & layout)
3381 d->layout_ = &layout;
3385 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3387 setLayout(tc.defaultLayout());
3391 void Paragraph::setPlainLayout(DocumentClass const & tc)
3393 setLayout(tc.plainLayout());
3397 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3399 if (usePlainLayout())
3400 setPlainLayout(tclass);
3402 setDefaultLayout(tclass);
3406 Inset const & Paragraph::inInset() const
3408 LBUFERR(d->inset_owner_);
3409 return *d->inset_owner_;
3413 ParagraphParameters & Paragraph::params()
3419 ParagraphParameters const & Paragraph::params() const
3425 bool Paragraph::isFreeSpacing() const
3427 if (d->layout_->free_spacing)
3429 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3433 bool Paragraph::allowEmpty() const
3435 if (d->layout_->keepempty)
3437 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3441 bool Paragraph::brokenBiblio() const
3443 // there is a problem if there is no bibitem at position 0 or
3444 // if there is another bibitem in the paragraph.
3445 return d->layout_->labeltype == LABEL_BIBLIO
3446 && (d->insetlist_.find(BIBITEM_CODE) != 0
3447 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3451 int Paragraph::fixBiblio(Buffer const & buffer)
3453 // FIXME: What about the case where paragraph is not BIBLIO
3454 // but there is an InsetBibitem?
3455 // FIXME: when there was already an inset at 0, the return value is 1,
3456 // which does not tell whether another inset has been remove; the
3457 // cursor cannot be correctly updated.
3459 if (d->layout_->labeltype != LABEL_BIBLIO)
3462 bool const track_changes = buffer.params().track_changes;
3463 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3464 bool const hasbibitem0 = bibitem_pos == 0;
3467 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3468 // There was an InsetBibitem at pos 0, and no other one => OK
3469 if (bibitem_pos == -1)
3471 // there is a bibitem at the 0 position, but since
3472 // there is a second one, we copy the second on the
3473 // first. We're assuming there are at most two of
3474 // these, which there should be.
3475 // FIXME: why does it make sense to do that rather
3476 // than keep the first? (JMarc)
3477 Inset * inset = releaseInset(bibitem_pos);
3478 d->insetlist_.begin()->inset = inset;
3479 return -bibitem_pos;
3482 // We need to create an inset at the beginning
3484 if (bibitem_pos > 0) {
3485 // there was one somewhere in the paragraph, let's move it
3486 inset = d->insetlist_.release(bibitem_pos);
3487 eraseChar(bibitem_pos, track_changes);
3490 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3491 InsetCommandParams(BIBITEM_CODE));
3493 Font font(inherit_font, buffer.params().language);
3494 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3495 : Change::UNCHANGED));
3501 void Paragraph::checkAuthors(AuthorList const & authorList)
3503 d->changes_.checkAuthors(authorList);
3507 bool Paragraph::isChanged(pos_type pos) const
3509 return lookupChange(pos).changed();
3513 bool Paragraph::isInserted(pos_type pos) const
3515 return lookupChange(pos).inserted();
3519 bool Paragraph::isDeleted(pos_type pos) const
3521 return lookupChange(pos).deleted();
3525 InsetList const & Paragraph::insetList() const
3527 return d->insetlist_;
3531 void Paragraph::setBuffer(Buffer & b)
3533 d->insetlist_.setBuffer(b);
3537 Inset * Paragraph::releaseInset(pos_type pos)
3539 Inset * inset = d->insetlist_.release(pos);
3540 /// does not honour change tracking!
3541 eraseChar(pos, false);
3546 Inset * Paragraph::getInset(pos_type pos)
3548 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3549 ? d->insetlist_.get(pos) : 0;
3553 Inset const * Paragraph::getInset(pos_type pos) const
3555 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3556 ? d->insetlist_.get(pos) : 0;
3560 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3561 pos_type & right, TextCase action)
3563 // process sequences of modified characters; in change
3564 // tracking mode, this approach results in much better
3565 // usability than changing case on a char-by-char basis
3566 // We also need to track the current font, since font
3567 // changes within sequences can occur.
3568 vector<pair<char_type, Font> > changes;
3570 bool const trackChanges = bparams.track_changes;
3572 bool capitalize = true;
3574 for (; pos < right; ++pos) {
3575 char_type oldChar = d->text_[pos];
3576 char_type newChar = oldChar;
3578 // ignore insets and don't play with deleted text!
3579 if (oldChar != META_INSET && !isDeleted(pos)) {
3581 case text_lowercase:
3582 newChar = lowercase(oldChar);
3584 case text_capitalization:
3586 newChar = uppercase(oldChar);
3590 case text_uppercase:
3591 newChar = uppercase(oldChar);
3596 if (isWordSeparator(pos) || isDeleted(pos)) {
3597 // permit capitalization again
3601 if (oldChar != newChar) {
3602 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3603 if (pos != right - 1)
3605 // step behind the changing area
3609 int erasePos = pos - changes.size();
3610 for (size_t i = 0; i < changes.size(); i++) {
3611 insertChar(pos, changes[i].first,
3614 if (!eraseChar(erasePos, trackChanges)) {
3617 ++right; // expand selection
3625 int Paragraph::find(docstring const & str, bool cs, bool mw,
3626 pos_type start_pos, bool del) const
3628 pos_type pos = start_pos;
3629 int const strsize = str.length();
3631 pos_type const parsize = d->text_.size();
3632 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3633 // Ignore "invisible" letters such as ligature breaks
3634 // and hyphenation chars while searching
3635 while (pos < parsize - 1 && isInset(pos)) {
3636 odocstringstream os;
3637 getInset(pos)->toString(os);
3638 if (!getInset(pos)->isLetter() || !os.str().empty())
3642 if (cs && str[i] != d->text_[pos])
3644 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3646 if (!del && isDeleted(pos))
3653 // if necessary, check whether string matches word
3655 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3658 && !isWordSeparator(pos))
3662 return pos - start_pos;
3666 char_type Paragraph::getChar(pos_type pos) const
3668 return d->text_[pos];
3672 pos_type Paragraph::size() const
3674 return d->text_.size();
3678 bool Paragraph::empty() const
3680 return d->text_.empty();
3684 bool Paragraph::isInset(pos_type pos) const
3686 return d->text_[pos] == META_INSET;
3690 bool Paragraph::isSeparator(pos_type pos) const
3692 //FIXME: Are we sure this can be the only separator?
3693 return d->text_[pos] == ' ';
3697 void Paragraph::deregisterWords()
3699 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3700 Private::LangWordsMap::const_iterator ite = d->words_.end();
3701 for (; itl != ite; ++itl) {
3702 WordList * wl = theWordList(itl->first);
3703 Private::Words::const_iterator it = (itl->second).begin();
3704 Private::Words::const_iterator et = (itl->second).end();
3705 for (; it != et; ++it)
3712 void Paragraph::locateWord(pos_type & from, pos_type & to,
3713 word_location const loc) const
3716 case WHOLE_WORD_STRICT:
3717 if (from == 0 || from == size()
3718 || isWordSeparator(from)
3719 || isWordSeparator(from - 1)) {
3723 // no break here, we go to the next
3726 // If we are already at the beginning of a word, do nothing
3727 if (!from || isWordSeparator(from - 1))
3729 // no break here, we go to the next
3732 // always move the cursor to the beginning of previous word
3733 while (from && !isWordSeparator(from - 1))
3737 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3740 // no need to move the 'from' cursor
3744 while (to < size() && !isWordSeparator(to))
3749 void Paragraph::collectWords()
3751 for (pos_type pos = 0; pos < size(); ++pos) {
3752 if (isWordSeparator(pos))
3754 pos_type from = pos;
3755 locateWord(from, pos, WHOLE_WORD);
3756 // Work around MSVC warning: The statement
3757 // if (pos < from + lyxrc.completion_minlength)
3758 // triggers a signed vs. unsigned warning.
3759 // I don't know why this happens, it could be a MSVC bug, or
3760 // related to LLP64 (windows) vs. LP64 (unix) programming
3761 // model, or the C++ standard might be ambigous in the section
3762 // defining the "usual arithmetic conversions". However, using
3763 // a temporary variable is safe and works on all compilers.
3764 pos_type const endpos = from + lyxrc.completion_minlength;
3767 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3768 if (cit == d->fontlist_.end())
3770 Language const * lang = cit->font().language();
3771 docstring const word = asString(from, pos, AS_STR_NONE);
3772 d->words_[lang->lang()].insert(word);
3777 void Paragraph::registerWords()
3779 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3780 Private::LangWordsMap::const_iterator ite = d->words_.end();
3781 for (; itl != ite; ++itl) {
3782 WordList * wl = theWordList(itl->first);
3783 Private::Words::const_iterator it = (itl->second).begin();
3784 Private::Words::const_iterator et = (itl->second).end();
3785 for (; it != et; ++it)
3791 void Paragraph::updateWords()
3799 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3801 SkipPositionsIterator begin = skips.begin();
3802 SkipPositions::iterator end = skips.end();
3803 if (pos > 0 && begin < end) {
3805 if (end->last == pos - 1) {
3810 skips.insert(end, FontSpan(pos, pos));
3814 Language * Paragraph::Private::locateSpellRange(
3815 pos_type & from, pos_type & to,
3816 SkipPositions & skips) const
3818 // skip leading white space
3819 while (from < to && owner_->isWordSeparator(from))
3821 // don't check empty range
3824 // get current language
3825 Language * lang = getSpellLanguage(from);
3826 pos_type last = from;
3827 bool samelang = true;
3828 bool sameinset = true;
3829 while (last < to && samelang && sameinset) {
3830 // hop to end of word
3831 while (last < to && !owner_->isWordSeparator(last)) {
3832 if (owner_->getInset(last)) {
3833 appendSkipPosition(skips, last);
3834 } else if (owner_->isDeleted(last)) {
3835 appendSkipPosition(skips, last);
3839 // hop to next word while checking for insets
3840 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3841 if (Inset const * inset = owner_->getInset(last))
3842 sameinset = inset->isChar() && inset->isLetter();
3843 if (sameinset && owner_->isDeleted(last)) {
3844 appendSkipPosition(skips, last);
3849 if (sameinset && last < to) {
3850 // now check for language change
3851 samelang = lang == getSpellLanguage(last);
3854 // if language change detected backstep is needed
3862 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3865 const_cast<Language *>(owner_->getFontSettings(
3866 inset_owner_->buffer().params(), from).language());
3867 if (lang == inset_owner_->buffer().params().language
3868 && !lyxrc.spellchecker_alt_lang.empty()) {
3870 string const lang_variety =
3871 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3872 lang->setCode(lang_code);
3873 lang->setVariety(lang_variety);
3879 void Paragraph::requestSpellCheck(pos_type pos)
3881 d->requestSpellCheck(pos);
3885 bool Paragraph::needsSpellCheck() const
3887 SpellChecker::ChangeNumber speller_change_number = 0;
3888 if (theSpellChecker())
3889 speller_change_number = theSpellChecker()->changeNumber();
3890 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3891 d->speller_state_.needsCompleteRefresh(speller_change_number);
3893 return d->needsSpellCheck();
3897 bool Paragraph::Private::ignoreWord(docstring const & word) const
3899 // Ignore words with digits
3900 // FIXME: make this customizable
3901 // (note that some checkers ignore words with digits by default)
3902 docstring::const_iterator cit = word.begin();
3903 docstring::const_iterator const end = word.end();
3904 for (; cit != end; ++cit) {
3905 if (isNumber((*cit)))
3912 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3913 WordLangTuple & wl, docstring_list & suggestions,
3914 bool do_suggestion, bool check_learned) const
3916 SpellChecker::Result result = SpellChecker::WORD_OK;
3917 SpellChecker * speller = theSpellChecker();
3921 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3924 locateWord(from, to, WHOLE_WORD);
3925 if (from == to || from >= size())
3928 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3929 Language * lang = d->getSpellLanguage(from);
3931 wl = WordLangTuple(word, lang);
3936 if (needsSpellCheck() || check_learned) {
3938 if (!d->ignoreWord(word)) {
3939 bool const trailing_dot = to < size() && d->text_[to] == '.';
3940 result = speller->check(wl);
3941 if (SpellChecker::misspelled(result) && trailing_dot) {
3942 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3943 result = speller->check(wl);
3944 if (!SpellChecker::misspelled(result)) {
3945 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3947 from << ".." << to << "]");
3949 // spell check with dot appended failed too
3950 // restore original word/lang value
3951 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3952 wl = WordLangTuple(word, lang);
3956 if (!SpellChecker::misspelled(result)) {
3957 // area up to the begin of the next word is not misspelled
3958 while (end < size() && isWordSeparator(end))
3961 d->setMisspelled(from, end, result);
3963 result = d->speller_state_.getState(from);
3967 suggestions.clear();
3969 if (SpellChecker::misspelled(result)) {
3970 LYXERR(Debug::GUI, "misspelled word: \"" <<
3972 from << ".." << to << "]");
3974 speller->suggest(wl, suggestions);
3980 void Paragraph::Private::markMisspelledWords(
3981 pos_type const & first, pos_type const & last,
3982 SpellChecker::Result result,
3983 docstring const & word,
3984 SkipPositions const & skips)
3986 if (!SpellChecker::misspelled(result)) {
3987 setMisspelled(first, last, SpellChecker::WORD_OK);
3991 SpellChecker * speller = theSpellChecker();
3992 // locate and enumerate the error positions
3993 int nerrors = speller->numMisspelledWords();
3995 SkipPositionsIterator it = skips.begin();
3996 SkipPositionsIterator et = skips.end();
3997 for (int index = 0; index < nerrors; ++index) {
4000 speller->misspelledWord(index, wstart, wlen);
4001 /// should not happen if speller supports range checks
4002 if (!wlen) continue;
4003 docstring const misspelled = word.substr(wstart, wlen);
4004 wstart += first + numskipped;
4005 if (snext < wstart) {
4006 /// mark the range of correct spelling
4007 numskipped += countSkips(it, et, wstart);
4008 setMisspelled(snext,
4009 wstart - 1, SpellChecker::WORD_OK);
4011 snext = wstart + wlen;
4012 numskipped += countSkips(it, et, snext);
4013 /// mark the range of misspelling
4014 setMisspelled(wstart, snext, result);
4015 LYXERR(Debug::GUI, "misspelled word: \"" <<
4016 misspelled << "\" [" <<
4017 wstart << ".." << (snext-1) << "]");
4020 if (snext <= last) {
4021 /// mark the range of correct spelling at end
4022 setMisspelled(snext, last, SpellChecker::WORD_OK);
4027 void Paragraph::spellCheck() const
4029 SpellChecker * speller = theSpellChecker();
4030 if (!speller || empty() ||!needsSpellCheck())
4034 d->rangeOfSpellCheck(start, endpos);
4035 if (speller->canCheckParagraph()) {
4036 // loop until we leave the range
4037 for (pos_type first = start; first < endpos; ) {
4038 pos_type last = endpos;
4039 Private::SkipPositions skips;
4040 Language * lang = d->locateSpellRange(first, last, skips);
4041 if (first >= endpos)
4043 // start the spell checker on the unit of meaning
4044 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4045 WordLangTuple wl = WordLangTuple(word, lang);
4046 SpellChecker::Result result = word.size() ?
4047 speller->check(wl) : SpellChecker::WORD_OK;
4048 d->markMisspelledWords(first, last, result, word, skips);
4052 static docstring_list suggestions;
4053 pos_type to = endpos;
4054 while (start < endpos) {
4056 spellCheck(start, to, wl, suggestions, false);
4060 d->readySpellCheck();
4064 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4066 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4067 if (result || pos <= 0 || pos > size())
4069 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4070 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4075 string Paragraph::magicLabel() const
4078 ss << "magicparlabel-" << id();