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 "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
56 #include "support/debug.h"
57 #include "support/docstring_list.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
69 using namespace lyx::support;
75 /// Inset identifier (above 0x10ffff, for ucs-4)
76 char_type const META_INSET = 0x200001;
81 /////////////////////////////////////////////////////////////////////
85 /////////////////////////////////////////////////////////////////////
87 class SpellResultRange {
89 SpellResultRange(FontSpan range, SpellChecker::Result result)
90 : range_(range), result_(result)
93 FontSpan const & range() const { return range_; }
95 void range(FontSpan const & r) { range_ = r; }
97 SpellChecker::Result result() const { return result_; }
99 void result(SpellChecker::Result r) { result_ = r; }
101 bool contains(pos_type pos) const { return range_.contains(pos); }
103 bool covered(FontSpan const & r) const
105 // 1. first of new range inside current range or
106 // 2. last of new range inside current range or
107 // 3. first of current range inside new range or
108 // 4. last of current range inside new range
109 //FIXME: is this the same as !range_.intersect(r).empty() ?
110 return range_.contains(r.first) || range_.contains(r.last) ||
111 r.contains(range_.first) || r.contains(range_.last);
114 void shift(pos_type pos, int offset)
116 if (range_.first > pos) {
117 range_.first += offset;
118 range_.last += offset;
119 } else if (range_.last >= pos) {
120 range_.last += offset;
125 SpellChecker::Result result_ ;
129 /////////////////////////////////////////////////////////////////////
133 /////////////////////////////////////////////////////////////////////
135 class SpellCheckerState {
139 needs_refresh_ = true;
140 current_change_number_ = 0;
143 void setRange(FontSpan const & fp, SpellChecker::Result state)
146 RangesIterator et = ranges_.end();
147 RangesIterator it = ranges_.begin();
148 for (; it != et; ++it) {
149 if (!it->covered(fp))
150 result.push_back(SpellResultRange(it->range(), it->result()));
151 else if (state == SpellChecker::WORD_OK) {
152 // trim or split the current misspelled range
153 // store misspelled ranges only
154 FontSpan range = it->range();
155 if (fp.first > range.first) {
156 // misspelled area in front of WORD_OK
157 range.last = fp.first - 1;
158 result.push_back(SpellResultRange(range, it->result()));
161 if (fp.last < range.last) {
162 // misspelled area after WORD_OK range
163 range.first = fp.last + 1;
164 result.push_back(SpellResultRange(range, it->result()));
169 if (state != SpellChecker::WORD_OK)
170 ranges_.push_back(SpellResultRange(fp, state));
173 void increasePosAfterPos(pos_type pos)
175 correctRangesAfterPos(pos, 1);
179 void decreasePosAfterPos(pos_type pos)
181 correctRangesAfterPos(pos, -1);
185 void refreshLast(pos_type pos)
187 if (pos < refresh_.last)
191 SpellChecker::Result getState(pos_type pos) const
193 SpellChecker::Result result = SpellChecker::WORD_OK;
194 RangesIterator et = ranges_.end();
195 RangesIterator it = ranges_.begin();
196 for (; it != et; ++it) {
197 if(it->contains(pos)) {
204 FontSpan const & getRange(pos_type pos) const
206 /// empty span to indicate mismatch
207 static FontSpan empty_;
208 RangesIterator et = ranges_.end();
209 RangesIterator it = ranges_.begin();
210 for (; it != et; ++it) {
211 if(it->contains(pos)) {
218 bool needsRefresh() const
220 return needs_refresh_;
223 SpellChecker::ChangeNumber currentChangeNumber() const
225 return current_change_number_;
228 void refreshRange(pos_type & first, pos_type & last) const
230 first = refresh_.first;
231 last = refresh_.last;
234 void needsRefresh(pos_type pos)
236 if (needs_refresh_ && pos != -1) {
237 if (pos < refresh_.first)
238 refresh_.first = pos;
239 if (pos > refresh_.last)
241 } else if (pos != -1) {
242 // init request check for neighbour positions too
243 refresh_.first = pos > 0 ? pos - 1 : 0;
244 // no need for special end of paragraph check
245 refresh_.last = pos + 1;
247 needs_refresh_ = pos != -1;
250 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
252 needs_refresh_ = true;
255 current_change_number_ = change_number;
258 typedef vector<SpellResultRange> Ranges;
259 typedef Ranges::const_iterator RangesIterator;
261 /// the area of the paragraph with pending spell check
264 /// spell state cache version number
265 SpellChecker::ChangeNumber current_change_number_;
268 void correctRangesAfterPos(pos_type pos, int offset)
270 RangesIterator et = ranges_.end();
271 Ranges::iterator it = ranges_.begin();
272 for (; it != et; ++it) {
273 it->shift(pos, offset);
279 /////////////////////////////////////////////////////////////////////
281 // Paragraph::Private
283 /////////////////////////////////////////////////////////////////////
285 class Paragraph::Private
287 // Enforce our own "copy" constructor
288 Private(Private const &) = delete;
289 Private & operator=(Private const &) = delete;
290 // Unique ID generator
291 static int make_id();
294 Private(Paragraph * owner, Layout const & layout);
295 /// "Copy constructor"
296 Private(Private const &, Paragraph * owner);
297 /// Copy constructor from \p beg to \p end
298 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
301 void insertChar(pos_type pos, char_type c, Change const & change);
303 /// Output the surrogate pair formed by \p c and \p next to \p os.
304 /// \return the number of characters written.
305 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
306 OutputParams const &);
308 /// Output a space in appropriate formatting (or a surrogate pair
309 /// if the next character is a combining character).
310 /// \return whether a surrogate pair was output.
311 bool simpleTeXBlanks(OutputParams const &,
314 unsigned int & column,
316 Layout const & style);
318 /// Output consecutive unicode chars, belonging to the same script as
319 /// specified by the latex macro \p ltx, to \p os starting from \p i.
320 /// \return the number of characters written.
321 int writeScriptChars(otexstream & os, docstring const & ltx,
322 Change const &, Encoding const &, pos_type & i);
324 /// This could go to ParagraphParameters if we want to.
325 int startTeXParParams(BufferParams const &, otexstream &,
326 OutputParams const &) const;
328 /// This could go to ParagraphParameters if we want to.
329 bool endTeXParParams(BufferParams const &, otexstream &,
330 OutputParams const &) const;
333 void latexInset(BufferParams const &,
338 Font const & outerfont,
340 Change & running_change,
341 Layout const & style,
343 unsigned int & column);
346 void latexSpecialChar(
348 BufferParams const & bparams,
349 OutputParams const & runparams,
350 Font const & running_font,
351 Change const & running_change,
352 Layout const & style,
355 unsigned int & column);
362 unsigned int & column);
368 unsigned int & column);
371 void validate(LaTeXFeatures & features) const;
373 /// Checks if the paragraph contains only text and no inset or font change.
374 bool onlyText(Buffer const & buf, Font const & outerfont,
375 pos_type initial) const;
377 /// a vector of speller skip positions
378 typedef vector<FontSpan> SkipPositions;
379 typedef SkipPositions::const_iterator SkipPositionsIterator;
381 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
383 Language * getSpellLanguage(pos_type const from) const;
385 Language * locateSpellRange(pos_type & from, pos_type & to,
386 SkipPositions & skips) const;
388 bool hasSpellerChange() const
390 SpellChecker::ChangeNumber speller_change_number = 0;
391 if (theSpellChecker())
392 speller_change_number = theSpellChecker()->changeNumber();
393 return speller_change_number > speller_state_.currentChangeNumber();
396 bool ignoreWord(docstring const & word) const ;
398 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
400 pos_type textsize = owner_->size();
401 // check for sane arguments
402 if (to <= from || from >= textsize)
404 FontSpan fp = FontSpan(from, to - 1);
405 speller_state_.setRange(fp, state);
408 void requestSpellCheck(pos_type pos)
411 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
413 speller_state_.needsRefresh(pos);
416 void readySpellCheck()
418 speller_state_.needsRefresh(-1);
421 bool needsSpellCheck() const
423 return speller_state_.needsRefresh();
426 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
428 speller_state_.refreshRange(first, last);
430 last = owner_->size();
433 pos_type endpos = last;
434 owner_->locateWord(first, endpos, WHOLE_WORD);
437 owner_->locateWord(last, endpos, WHOLE_WORD);
442 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
446 while (it != et && it->first < start) {
447 int skip = it->last - it->first + 1;
455 void markMisspelledWords(pos_type const & first, pos_type const & last,
456 SpellChecker::Result result,
457 docstring const & word,
458 SkipPositions const & skips);
460 InsetCode ownerCode() const
462 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
465 /// Which Paragraph owns us?
469 Inset const * inset_owner_;
478 ParagraphParameters params_;
480 /// for recording and looking up changes
484 InsetList insetlist_;
487 pos_type begin_of_body_;
489 typedef docstring TextContainer;
493 typedef set<docstring> Words;
494 typedef map<string, Words> LangWordsMap;
498 Layout const * layout_;
500 SpellCheckerState speller_state_;
504 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
505 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
512 int Paragraph::Private::make_id()
514 // The id is unique per session across buffers because it is used in
515 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
518 static atomic_uint next_id(0);
523 Paragraph::Private::Private(Private const & p, Paragraph * owner)
524 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
526 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
527 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
530 requestSpellCheck(p.text_.size());
534 Paragraph::Private::Private(Private const & p, Paragraph * owner,
535 pos_type beg, pos_type end)
536 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
537 params_(p.params_), changes_(p.changes_),
538 insetlist_(p.insetlist_, beg, end),
539 begin_of_body_(p.begin_of_body_), words_(p.words_),
542 if (beg >= pos_type(p.text_.size()))
544 text_ = p.text_.substr(beg, end - beg);
546 FontList::const_iterator fcit = fontlist_.begin();
547 FontList::const_iterator fend = fontlist_.end();
548 for (; fcit != fend; ++fcit) {
549 if (fcit->pos() < beg)
551 if (fcit->pos() >= end) {
552 // Add last entry in the fontlist_.
553 fontlist_.set(text_.size() - 1, fcit->font());
556 // Add a new entry in the fontlist_.
557 fontlist_.set(fcit->pos() - beg, fcit->font());
559 requestSpellCheck(p.text_.size());
563 void Paragraph::addChangesToToc(DocIterator const & cdit,
564 Buffer const & buf, bool output_active) const
566 d->changes_.addToToc(cdit, buf, output_active);
570 void Paragraph::addChangesToBuffer(Buffer const & buf) const
572 d->changes_.updateBuffer(buf);
576 bool Paragraph::isChangeUpdateRequired() const
578 return d->changes_.isUpdateRequired();
582 bool Paragraph::isDeleted(pos_type start, pos_type end) const
584 LASSERT(start >= 0 && start <= size(), return false);
585 LASSERT(end > start && end <= size() + 1, return false);
587 return d->changes_.isDeleted(start, end);
591 bool Paragraph::isChanged(pos_type start, pos_type end) const
593 LASSERT(start >= 0 && start <= size(), return false);
594 LASSERT(end > start && end <= size() + 1, return false);
596 return d->changes_.isChanged(start, end);
600 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
602 // keep the logic here in sync with the logic of eraseChars()
606 Change const & change = d->changes_.lookup(size());
607 return change.inserted() && change.currentAuthor();
611 void Paragraph::setChange(Change const & change)
613 // beware of the imaginary end-of-par character!
614 d->changes_.set(change, 0, size() + 1);
617 * Propagate the change recursively - but not in case of DELETED!
619 * Imagine that your co-author makes changes in an existing inset. He
620 * sends your document to you and you come to the conclusion that the
621 * inset should go completely. If you erase it, LyX must not delete all
622 * text within the inset. Otherwise, the change tracked insertions of
623 * your co-author get lost and there is no way to restore them later.
625 * Conclusion: An inset's content should remain untouched if you delete it
628 if (!change.deleted()) {
629 for (pos_type pos = 0; pos < size(); ++pos) {
630 if (Inset * inset = getInset(pos))
631 inset->setChange(change);
637 void Paragraph::setChange(pos_type pos, Change const & change)
639 LASSERT(pos >= 0 && pos <= size(), return);
640 d->changes_.set(change, pos);
642 // see comment in setChange(Change const &) above
643 if (!change.deleted() && pos < size())
644 if (Inset * inset = getInset(pos))
645 inset->setChange(change);
649 Change const & Paragraph::lookupChange(pos_type pos) const
651 LBUFERR(pos >= 0 && pos <= size());
652 return d->changes_.lookup(pos);
656 void Paragraph::acceptChanges(pos_type start, pos_type end)
658 LASSERT(start >= 0 && start <= size(), return);
659 LASSERT(end > start && end <= size() + 1, return);
661 for (pos_type pos = start; pos < end; ++pos) {
662 switch (lookupChange(pos).type) {
663 case Change::UNCHANGED:
664 // accept changes in nested inset
665 if (Inset * inset = getInset(pos))
666 inset->acceptChanges();
669 case Change::INSERTED:
670 d->changes_.set(Change(Change::UNCHANGED), pos);
671 // also accept changes in nested inset
672 if (Inset * inset = getInset(pos))
673 inset->acceptChanges();
676 case Change::DELETED:
677 // Suppress access to non-existent
678 // "end-of-paragraph char"
680 eraseChar(pos, false);
691 void Paragraph::rejectChanges(pos_type start, pos_type end)
693 LASSERT(start >= 0 && start <= size(), return);
694 LASSERT(end > start && end <= size() + 1, return);
696 for (pos_type pos = start; pos < end; ++pos) {
697 switch (lookupChange(pos).type) {
698 case Change::UNCHANGED:
699 // reject changes in nested inset
700 if (Inset * inset = getInset(pos))
701 inset->rejectChanges();
704 case Change::INSERTED:
705 // Suppress access to non-existent
706 // "end-of-paragraph char"
708 eraseChar(pos, false);
714 case Change::DELETED:
715 d->changes_.set(Change(Change::UNCHANGED), pos);
717 // Do NOT reject changes within a deleted inset!
718 // There may be insertions of a co-author inside of it!
726 void Paragraph::Private::insertChar(pos_type pos, char_type c,
727 Change const & change)
729 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
732 changes_.insert(change, pos);
734 // This is actually very common when parsing buffers (and
735 // maybe inserting ascii text)
736 if (pos == pos_type(text_.size())) {
737 // when appending characters, no need to update tables
739 // but we want spell checking
740 requestSpellCheck(pos);
744 text_.insert(text_.begin() + pos, c);
746 // Update the font table.
747 fontlist_.increasePosAfterPos(pos);
750 insetlist_.increasePosAfterPos(pos);
752 // Update list of misspelled positions
753 speller_state_.increasePosAfterPos(pos);
757 bool Paragraph::insertInset(pos_type pos, Inset * inset,
758 Font const & font, Change const & change)
760 LASSERT(inset, return false);
761 LASSERT(pos >= 0 && pos <= size(), return false);
763 // Paragraph::insertInset() can be used in cut/copy/paste operation where
764 // d->inset_owner_ is not set yet.
765 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
768 d->insertChar(pos, META_INSET, change);
769 LASSERT(d->text_[pos] == META_INSET, return false);
771 // Add a new entry in the insetlist_.
772 d->insetlist_.insert(inset, pos);
774 // Some insets require run of spell checker
775 requestSpellCheck(pos);
781 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
783 LASSERT(pos >= 0 && pos <= size(), return false);
785 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
788 Change change = d->changes_.lookup(pos);
790 // set the character to DELETED if
791 // a) it was previously unchanged or
792 // b) it was inserted by a co-author
794 if (!change.changed() ||
795 (change.inserted() && !change.currentAuthor())) {
796 setChange(pos, Change(Change::DELETED));
797 // request run of spell checker
798 requestSpellCheck(pos);
802 if (change.deleted())
806 // Don't physically access the imaginary end-of-paragraph character.
807 // eraseChar() can only mark it as DELETED. A physical deletion of
808 // end-of-par must be handled externally.
814 d->changes_.erase(pos);
816 // if it is an inset, delete the inset entry
817 if (d->text_[pos] == META_INSET)
818 d->insetlist_.erase(pos);
820 d->text_.erase(d->text_.begin() + pos);
822 // Update the fontlist_
823 d->fontlist_.erase(pos);
825 // Update the insetlist_
826 d->insetlist_.decreasePosAfterPos(pos);
828 // Update list of misspelled positions
829 d->speller_state_.decreasePosAfterPos(pos);
830 d->speller_state_.refreshLast(size());
836 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
838 LASSERT(start >= 0 && start <= size(), return 0);
839 LASSERT(end >= start && end <= size() + 1, return 0);
842 for (pos_type count = end - start; count; --count) {
843 if (!eraseChar(i, trackChanges))
850 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
851 char_type next, OutputParams const & runparams)
853 // Writing next here may circumvent a possible font change between
854 // c and next. Since next is only output if it forms a surrogate pair
855 // with c we can ignore this:
856 // A font change inside a surrogate pair does not make sense and is
857 // hopefully impossible to input.
858 // FIXME: change tracking
859 // Is this correct WRT change tracking?
860 Encoding const & encoding = *(runparams.encoding);
861 docstring latex1 = encoding.latexChar(next).first;
862 if (runparams.inIPA) {
863 string const tipashortcut = Encodings::TIPAShortcut(next);
864 if (!tipashortcut.empty()) {
865 latex1 = from_ascii(tipashortcut);
868 docstring const latex2 = encoding.latexChar(c).first;
869 if (docstring(1, next) == latex1) {
870 // the encoding supports the combination
871 os << latex2 << latex1;
872 return latex1.length() + latex2.length();
873 } else if (runparams.local_font &&
874 runparams.local_font->language()->lang() == "polutonikogreek") {
875 // polutonikogreek only works without the brackets
876 os << latex1 << latex2;
877 return latex1.length() + latex2.length();
879 os << latex1 << '{' << latex2 << '}';
880 return latex1.length() + latex2.length() + 2;
884 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
887 unsigned int & column,
889 Layout const & style)
891 if (style.pass_thru || runparams.pass_thru)
894 if (i + 1 < int(text_.size())) {
895 char_type next = text_[i + 1];
896 if (Encodings::isCombiningChar(next)) {
897 // This space has an accent, so we must always output it.
898 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
903 if (runparams.linelen > 0
904 && column > runparams.linelen
906 && text_[i - 1] != ' '
907 && (i + 1 < int(text_.size()))
908 // same in FreeSpacing mode
909 && !owner_->isFreeSpacing()
910 // In typewriter mode, we want to avoid
911 // ! . ? : at the end of a line
912 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
913 && (text_[i - 1] == '.'
914 || text_[i - 1] == '?'
915 || text_[i - 1] == ':'
916 || text_[i - 1] == '!'))) {
918 os.texrow().start(owner_->id(), i + 1);
920 } else if (style.free_spacing) {
929 int Paragraph::Private::writeScriptChars(otexstream & os,
930 docstring const & ltx,
931 Change const & runningChange,
932 Encoding const & encoding,
935 // FIXME: modifying i here is not very nice...
937 // We only arrive here when character text_[i] could not be translated
938 // into the current latex encoding (or its latex translation has been forced,)
939 // and it belongs to a known script.
940 // TODO: We need \textcyr and \textgreek wrappers also for characters
941 // that can be encoded in the "LaTeX encoding" but not in the
942 // current *font encoding*.
943 // (See #9681 for details and test)
944 // Parameter ltx contains the latex translation of text_[i] as specified
945 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
946 // The latex macro name "textXXX" specifies the script to which text_[i]
947 // belongs and we use it in order to check whether characters from the
948 // same script immediately follow, such that we can collect them in a
949 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
950 // for the first char but only "<spec>" for all subsequent chars.
951 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
952 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
953 string script = to_ascii(ltx.substr(1, brace1 - 1));
956 bool closing_brace = true;
957 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
958 // Correct encoding is being used, so we can avoid \textgreek.
959 // TODO: wrong test: we need to check the *font encoding*
960 // (i.e. the active language and its FontEncoding tag)
961 // instead of the LaTeX *input encoding*!
962 // See #9637 for details and test-cases.
965 closing_brace = false;
967 os << ltx.substr(pos, length);
968 int size = text_.size();
969 while (i + 1 < size) {
970 char_type const next = text_[i + 1];
971 // Stop here if next character belongs to another script
972 // or there is a change in change tracking status.
973 if (!Encodings::isKnownScriptChar(next, script) ||
974 runningChange != owner_->lookupChange(i + 1))
978 FontList::const_iterator cit = fontlist_.begin();
979 FontList::const_iterator end = fontlist_.end();
980 for (; cit != end; ++cit) {
981 if (cit->pos() >= i && !found) {
982 prev_font = cit->font();
985 if (cit->pos() >= i + 1)
988 // Stop here if there is a font attribute or encoding change.
989 if (found && cit != end && prev_font != cit->font())
991 docstring const latex = encoding.latexChar(next).first;
992 docstring::size_type const b1 =
993 latex.find_first_of(from_ascii("{"));
994 docstring::size_type const b2 =
995 latex.find_last_of(from_ascii("}"));
996 int const len = b2 - b1 - 1;
997 os << latex.substr(b1 + 1, len);
1001 if (closing_brace) {
1009 void Paragraph::Private::latexInset(BufferParams const & bparams,
1011 OutputParams & runparams,
1012 Font & running_font,
1014 Font const & outerfont,
1016 Change & running_change,
1017 Layout const & style,
1019 unsigned int & column)
1021 Inset * inset = owner_->getInset(i);
1024 if (style.pass_thru) {
1025 odocstringstream ods;
1026 inset->plaintext(ods, runparams);
1031 // FIXME: move this to InsetNewline::latex
1032 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1033 // newlines are handled differently here than
1034 // the default in simpleTeXSpecialChars().
1035 if (!style.newline_allowed) {
1039 column += running_font.latexWriteEndChanges(
1040 os, bparams, runparams,
1041 basefont, basefont);
1045 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1048 basefont = owner_->getLayoutFont(bparams, outerfont);
1049 running_font = basefont;
1051 if (runparams.moving_arg)
1055 os.texrow().start(owner_->id(), i + 1);
1059 if (owner_->isDeleted(i)) {
1060 if( ++runparams.inDeletedInset == 1)
1061 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1064 if (inset->canTrackChanges()) {
1065 column += Changes::latexMarkChange(os, bparams, running_change,
1066 Change(Change::UNCHANGED), runparams);
1067 running_change = Change(Change::UNCHANGED);
1071 odocstream::pos_type const len = os.os().tellp();
1073 if (inset->forceLTR()
1074 && !runparams.use_polyglossia
1075 && running_font.isRightToLeft()
1076 // ERT is an exception, it should be output with no
1077 // decorations at all
1078 && inset->lyxCode() != ERT_CODE) {
1079 if (running_font.language()->lang() == "farsi")
1086 // FIXME: Bug: we can have an empty font change here!
1087 // if there has just been a font change, we are going to close it
1088 // right now, which means stupid latex code like \textsf{}. AFAIK,
1089 // this does not harm dvi output. A minor bug, thus (JMarc)
1091 // Some insets cannot be inside a font change command.
1092 // However, even such insets *can* be placed in \L or \R
1093 // or their equivalents (for RTL language switches), so we don't
1094 // close the language in those cases.
1095 // ArabTeX, though, cannot handle this special behavior, it seems.
1096 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1097 || running_font.language()->lang() == "arabic_arabtex";
1098 if (open_font && !inset->inheritFont()) {
1099 bool closeLanguage = arabtex
1100 || basefont.isRightToLeft() == running_font.isRightToLeft();
1101 unsigned int count = running_font.latexWriteEndChanges(os,
1102 bparams, runparams, basefont, basefont, closeLanguage);
1104 // if any font properties were closed, update the running_font,
1105 // making sure, however, to leave the language as it was
1107 // FIXME: probably a better way to keep track of the old
1108 // language, than copying the entire font?
1109 Font const copy_font(running_font);
1110 basefont = owner_->getLayoutFont(bparams, outerfont);
1111 running_font = basefont;
1113 running_font.setLanguage(copy_font.language());
1114 // leave font open if language is still open
1115 open_font = (running_font.language() == basefont.language());
1117 runparams.local_font = &basefont;
1121 int prev_rows = os.texrow().rows();
1124 runparams.lastid = id_;
1125 runparams.lastpos = i;
1126 inset->latex(os, runparams);
1127 } catch (EncodingException & e) {
1128 // add location information and throw again.
1135 if (running_font.language()->lang() == "farsi")
1141 if (os.texrow().rows() > prev_rows) {
1142 os.texrow().start(owner_->id(), i + 1);
1145 column += (unsigned int)(os.os().tellp() - len);
1148 if (owner_->isDeleted(i))
1149 --runparams.inDeletedInset;
1153 void Paragraph::Private::latexSpecialChar(otexstream & os,
1154 BufferParams const & bparams,
1155 OutputParams const & runparams,
1156 Font const & running_font,
1157 Change const & running_change,
1158 Layout const & style,
1161 unsigned int & column)
1163 // With polyglossia, brackets and stuff need not be reversed
1164 // in RTL scripts (see bug #8251)
1165 char_type const c = (runparams.use_polyglossia) ?
1166 owner_->getUChar(bparams, i) : text_[i];
1168 if (style.pass_thru || runparams.pass_thru
1169 || contains(style.pass_thru_chars, c)
1170 || contains(runparams.pass_thru_chars, c)) {
1172 Encoding const * const enc = runparams.encoding;
1173 if (enc && !enc->encodable(c))
1174 throw EncodingException(c);
1180 // TIPA uses its own T3 encoding
1181 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1183 // If T1 font encoding is used, use the special
1184 // characters it provides.
1185 // NOTE: Some languages reset the font encoding internally to a
1186 // non-standard font encoding. If we are using such a language,
1187 // we do not output special T1 chars.
1188 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1189 && bparams.font_encoding() == "T1" && latexSpecialT1(c, os, i, column))
1192 // Otherwise, we use what LaTeX provides us.
1195 os << "\\textbackslash{}";
1199 os << "\\textless{}";
1203 os << "\\textgreater{}";
1207 os << "\\textbar{}";
1212 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1213 (end_pos == -1 || i + 1 < end_pos) &&
1214 text_[i+1] == '-') {
1215 // Prevent "--" becoming an endash and "---" becoming
1217 // Within \ttfamily, "--" is merged to "-" (no endash)
1218 // so we avoid this rather irritating ligature as well
1224 os << "\\char`\\\"{}";
1229 case '%': case '#': case '{':
1237 os << "\\textasciitilde{}";
1242 os << "\\textasciicircum{}";
1249 // avoid being mistaken for optional arguments
1257 // Blanks are printed before font switching.
1258 // Sure? I am not! (try nice-latex)
1259 // I am sure it's correct. LyX might be smarter
1260 // in the future, but for now, nothing wrong is
1268 Encoding const & encoding = *(runparams.encoding);
1269 char_type next = '\0';
1270 if (i + 1 < int(text_.size())) {
1271 next = text_[i + 1];
1272 if (Encodings::isCombiningChar(next)) {
1273 column += latexSurrogatePair(os, c, next, runparams) - 1;
1279 pair<docstring, bool> latex = encoding.latexChar(c);
1280 docstring nextlatex;
1281 bool nexttipas = false;
1282 string nexttipashortcut;
1283 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1284 nextlatex = encoding.latexChar(next).first;
1285 if (runparams.inIPA) {
1286 nexttipashortcut = Encodings::TIPAShortcut(next);
1287 nexttipas = !nexttipashortcut.empty();
1291 if (runparams.inIPA) {
1292 string const tipashortcut = Encodings::TIPAShortcut(c);
1293 if (!tipashortcut.empty()) {
1294 latex.first = from_ascii(tipashortcut);
1295 latex.second = false;
1299 if (Encodings::isKnownScriptChar(c, script)
1300 && prefixIs(latex.first, from_ascii("\\" + script)))
1301 column += writeScriptChars(os, latex.first,
1302 running_change, encoding, i) - 1;
1303 else if (latex.second
1304 && ((!prefixIs(nextlatex, '\\')
1305 && !prefixIs(nextlatex, '{')
1306 && !prefixIs(nextlatex, '}'))
1308 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1310 // Prevent eating of a following
1311 // space or command corruption by
1312 // following characters
1313 if (next == ' ' || next == '\0') {
1314 column += latex.first.length() + 1;
1315 os << latex.first << "{}";
1317 column += latex.first.length();
1318 os << latex.first << " ";
1321 column += latex.first.length() - 1;
1329 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1330 pos_type i, unsigned int & column)
1336 // In T1 encoding, these characters exist
1337 // but we should avoid ligatures
1338 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1340 os << "\\textcompwordmark{}";
1347 // soul.sty breaks with \char`\"
1348 os << "\\textquotedbl{}";
1357 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1358 pos_type /*i*/, unsigned int & column)
1368 os << "\\textvertline{}";
1377 void Paragraph::Private::validate(LaTeXFeatures & features) const
1379 if (layout_->inpreamble && inset_owner_) {
1380 bool const is_command = layout_->latextype == LATEX_COMMAND;
1381 Buffer const & buf = inset_owner_->buffer();
1382 BufferParams const & bp = features.runparams().is_child
1383 ? buf.masterParams() : buf.params();
1385 // Using a string stream here circumvents the encoding
1386 // switching machinery of odocstream. Therefore the
1387 // output is wrong if this paragraph contains content
1388 // that needs to switch encoding.
1389 odocstringstream ods;
1392 os << '\\' << from_ascii(layout_->latexname());
1393 // we have to provide all the optional arguments here, even though
1394 // the last one is the only one we care about.
1395 // Separate handling of optional argument inset.
1396 if (!layout_->latexargs().empty()) {
1397 OutputParams rp = features.runparams();
1398 rp.local_font = &owner_->getFirstFontSettings(bp);
1399 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1401 os << from_ascii(layout_->latexparam());
1403 docstring::size_type const length = ods.str().length();
1404 // this will output "{" at the beginning, but not at the end
1405 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1406 if (ods.str().length() > length) {
1409 if (!layout_->postcommandargs().empty()) {
1410 OutputParams rp = features.runparams();
1411 rp.local_font = &owner_->getFirstFontSettings(bp);
1412 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1415 string const snippet = to_utf8(ods.str());
1416 features.addPreambleSnippet(snippet, true);
1420 if (features.runparams().flavor == OutputParams::HTML
1421 && layout_->htmltitle()) {
1422 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1425 // check the params.
1426 if (!params_.spacing().isDefault())
1427 features.require("setspace");
1430 features.useLayout(layout_->name());
1433 fontlist_.validate(features);
1435 // then the indentation
1436 if (!params_.leftIndent().zero())
1437 features.require("ParagraphLeftIndent");
1440 InsetList::const_iterator icit = insetlist_.begin();
1441 InsetList::const_iterator iend = insetlist_.end();
1442 for (; icit != iend; ++icit) {
1444 icit->inset->validate(features);
1445 if (layout_->needprotect &&
1446 icit->inset->lyxCode() == FOOT_CODE)
1447 features.require("NeedLyXFootnoteCode");
1451 // then the contents
1452 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1453 BufferEncodings::validate(text_[i], features);
1457 /////////////////////////////////////////////////////////////////////
1461 /////////////////////////////////////////////////////////////////////
1464 Layout const emptyParagraphLayout;
1467 Paragraph::Paragraph()
1468 : d(new Paragraph::Private(this, emptyParagraphLayout))
1475 Paragraph::Paragraph(Paragraph const & par)
1476 : itemdepth(par.itemdepth),
1477 d(new Paragraph::Private(*par.d, this))
1483 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1484 : itemdepth(par.itemdepth),
1485 d(new Paragraph::Private(*par.d, this, beg, end))
1491 Paragraph & Paragraph::operator=(Paragraph const & par)
1493 // needed as we will destroy the private part before copying it
1495 itemdepth = par.itemdepth;
1499 d = new Private(*par.d, this);
1506 Paragraph::~Paragraph()
1515 // this shall be called just before every "os << ..." action.
1516 void flushString(ostream & os, docstring & s)
1525 void Paragraph::write(ostream & os, BufferParams const & bparams,
1526 depth_type & dth) const
1528 // The beginning or end of a deeper (i.e. nested) area?
1529 if (dth != d->params_.depth()) {
1530 if (d->params_.depth() > dth) {
1531 while (d->params_.depth() > dth) {
1532 os << "\n\\begin_deeper";
1536 while (d->params_.depth() < dth) {
1537 os << "\n\\end_deeper";
1543 // First write the layout
1544 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1546 d->params_.write(os);
1548 Font font1(inherit_font, bparams.language);
1550 Change running_change = Change(Change::UNCHANGED);
1552 // this string is used as a buffer to avoid repetitive calls
1553 // to to_utf8(), which turn out to be expensive (JMarc)
1554 docstring write_buffer;
1557 for (pos_type i = 0; i <= size(); ++i) {
1559 Change const & change = lookupChange(i);
1560 if (change != running_change)
1561 flushString(os, write_buffer);
1562 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1563 running_change = change;
1568 // Write font changes
1569 Font font2 = getFontSettings(bparams, i);
1570 if (font2 != font1) {
1571 flushString(os, write_buffer);
1572 font2.lyxWriteChanges(font1, os);
1577 char_type const c = d->text_[i];
1580 if (Inset const * inset = getInset(i)) {
1581 flushString(os, write_buffer);
1582 if (inset->directWrite()) {
1583 // international char, let it write
1584 // code directly so it's shorter in
1590 os << "\\begin_inset ";
1592 os << "\n\\end_inset\n\n";
1595 // FIXME This can be removed again once the mystery
1596 // crash has been resolved.
1601 flushString(os, write_buffer);
1602 os << "\n\\backslash\n";
1606 flushString(os, write_buffer);
1607 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1614 if ((column > 70 && c == ' ')
1616 flushString(os, write_buffer);
1620 // this check is to amend a bug. LyX sometimes
1621 // inserts '\0' this could cause problems.
1623 write_buffer.push_back(c);
1625 LYXERR0("NUL char in structure.");
1631 flushString(os, write_buffer);
1632 os << "\n\\end_layout\n";
1633 // FIXME This can be removed again once the mystery
1634 // crash has been resolved.
1639 void Paragraph::validate(LaTeXFeatures & features) const
1641 d->validate(features);
1645 void Paragraph::insert(pos_type start, docstring const & str,
1646 Font const & font, Change const & change)
1648 for (size_t i = 0, n = str.size(); i != n ; ++i)
1649 insertChar(start + i, str[i], font, change);
1653 void Paragraph::appendChar(char_type c, Font const & font,
1654 Change const & change)
1657 d->changes_.insert(change, d->text_.size());
1658 // when appending characters, no need to update tables
1659 d->text_.push_back(c);
1660 setFont(d->text_.size() - 1, font);
1661 d->requestSpellCheck(d->text_.size() - 1);
1665 void Paragraph::appendString(docstring const & s, Font const & font,
1666 Change const & change)
1668 pos_type end = s.size();
1669 size_t oldsize = d->text_.size();
1670 size_t newsize = oldsize + end;
1671 size_t capacity = d->text_.capacity();
1672 if (newsize >= capacity)
1673 d->text_.reserve(max(capacity + 100, newsize));
1675 // when appending characters, no need to update tables
1678 // FIXME: Optimize this!
1679 for (size_t i = oldsize; i != newsize; ++i) {
1681 d->changes_.insert(change, i);
1682 d->requestSpellCheck(i);
1684 d->fontlist_.set(oldsize, font);
1685 d->fontlist_.set(newsize - 1, font);
1689 void Paragraph::insertChar(pos_type pos, char_type c,
1692 d->insertChar(pos, c, Change(trackChanges ?
1693 Change::INSERTED : Change::UNCHANGED));
1697 void Paragraph::insertChar(pos_type pos, char_type c,
1698 Font const & font, bool trackChanges)
1700 d->insertChar(pos, c, Change(trackChanges ?
1701 Change::INSERTED : Change::UNCHANGED));
1706 void Paragraph::insertChar(pos_type pos, char_type c,
1707 Font const & font, Change const & change)
1709 d->insertChar(pos, c, change);
1714 void Paragraph::resetFonts(Font const & font)
1716 d->fontlist_.clear();
1717 d->fontlist_.set(0, font);
1718 d->fontlist_.set(d->text_.size() - 1, font);
1721 // Gets uninstantiated font setting at position.
1722 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1726 LYXERR0("pos: " << pos << " size: " << size());
1730 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1731 if (cit != d->fontlist_.end())
1734 if (pos == size() && !empty())
1735 return getFontSettings(bparams, pos - 1);
1737 // Optimisation: avoid a full font instantiation if there is no
1738 // language change from previous call.
1739 static Font previous_font;
1740 static Language const * previous_lang = 0;
1741 Language const * lang = getParLanguage(bparams);
1742 if (lang != previous_lang) {
1743 previous_lang = lang;
1744 previous_font = Font(inherit_font, lang);
1746 return previous_font;
1750 FontSpan Paragraph::fontSpan(pos_type pos) const
1752 LBUFERR(pos <= size());
1755 return FontSpan(pos, pos);
1758 FontList::const_iterator cit = d->fontlist_.begin();
1759 FontList::const_iterator end = d->fontlist_.end();
1760 for (; cit != end; ++cit) {
1761 if (cit->pos() >= pos) {
1762 if (pos >= beginOfBody())
1763 return FontSpan(max(start, beginOfBody()),
1766 return FontSpan(start,
1767 min(beginOfBody() - 1,
1770 start = cit->pos() + 1;
1773 // This should not happen, but if so, we take no chances.
1774 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1775 LASSERT(false, return FontSpan(pos, pos));
1779 // Gets uninstantiated font setting at position 0
1780 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1782 if (!empty() && !d->fontlist_.empty())
1783 return d->fontlist_.begin()->font();
1785 // Optimisation: avoid a full font instantiation if there is no
1786 // language change from previous call.
1787 static Font previous_font;
1788 static Language const * previous_lang = 0;
1789 if (bparams.language != previous_lang) {
1790 previous_lang = bparams.language;
1791 previous_font = Font(inherit_font, bparams.language);
1794 return previous_font;
1798 // Gets the fully instantiated font at a given position in a paragraph
1799 // This is basically the same function as Text::GetFont() in text2.cpp.
1800 // The difference is that this one is used for generating the LaTeX file,
1801 // and thus cosmetic "improvements" are disallowed: This has to deliver
1802 // the true picture of the buffer. (Asger)
1803 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1804 Font const & outerfont) const
1808 Font font = getFontSettings(bparams, pos);
1810 pos_type const body_pos = beginOfBody();
1811 FontInfo & fi = font.fontInfo();
1813 fi.realize(d->layout_->labelfont);
1815 fi.realize(d->layout_->font);
1817 fi.realize(outerfont.fontInfo());
1818 fi.realize(bparams.getFont().fontInfo());
1824 Font const Paragraph::getLabelFont
1825 (BufferParams const & bparams, Font const & outerfont) const
1827 FontInfo tmpfont = d->layout_->labelfont;
1828 tmpfont.realize(outerfont.fontInfo());
1829 tmpfont.realize(bparams.getFont().fontInfo());
1830 return Font(tmpfont, getParLanguage(bparams));
1834 Font const Paragraph::getLayoutFont
1835 (BufferParams const & bparams, Font const & outerfont) const
1837 FontInfo tmpfont = d->layout_->font;
1838 tmpfont.realize(outerfont.fontInfo());
1839 tmpfont.realize(bparams.getFont().fontInfo());
1840 return Font(tmpfont, getParLanguage(bparams));
1844 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1846 char_type c = d->text_[pos];
1847 if (!getFontSettings(bparams, pos).isRightToLeft())
1850 // FIXME: The arabic special casing is due to the difference of arabic
1851 // round brackets input introduced in r18599. Check if this should be
1852 // unified with Hebrew or at least if all bracket types should be
1853 // handled the same (file format change in either case).
1854 string const & lang = getFontSettings(bparams, pos).language()->lang();
1855 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1860 uc = arabic ? c : ')';
1863 uc = arabic ? c : '(';
1889 void Paragraph::setFont(pos_type pos, Font const & font)
1891 LASSERT(pos <= size(), return);
1893 // First, reduce font against layout/label font
1894 // Update: The setCharFont() routine in text2.cpp already
1895 // reduces font, so we don't need to do that here. (Asger)
1897 d->fontlist_.set(pos, font);
1901 void Paragraph::makeSameLayout(Paragraph const & par)
1903 d->layout_ = par.d->layout_;
1904 d->params_ = par.d->params_;
1908 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1910 if (isFreeSpacing())
1916 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1917 if (eraseChar(pos, trackChanges))
1923 return count > 0 || pos > 0;
1927 bool Paragraph::hasSameLayout(Paragraph const & par) const
1929 return par.d->layout_ == d->layout_
1930 && d->params_.sameLayout(par.d->params_);
1934 depth_type Paragraph::getDepth() const
1936 return d->params_.depth();
1940 depth_type Paragraph::getMaxDepthAfter() const
1942 if (d->layout_->isEnvironment())
1943 return d->params_.depth() + 1;
1945 return d->params_.depth();
1949 char Paragraph::getAlign() const
1951 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1952 return d->layout_->align;
1954 return d->params_.align();
1958 docstring const & Paragraph::labelString() const
1960 return d->params_.labelString();
1964 // the next two functions are for the manual labels
1965 docstring const Paragraph::getLabelWidthString() const
1967 if (d->layout_->margintype == MARGIN_MANUAL
1968 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1969 return d->params_.labelWidthString();
1971 return _("Senseless with this layout!");
1975 void Paragraph::setLabelWidthString(docstring const & s)
1977 d->params_.labelWidthString(s);
1981 docstring Paragraph::expandLabel(Layout const & layout,
1982 BufferParams const & bparams) const
1984 return expandParagraphLabel(layout, bparams, true);
1988 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1989 BufferParams const & bparams) const
1991 return expandParagraphLabel(layout, bparams, false);
1995 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1996 BufferParams const & bparams, bool process_appendix) const
1998 DocumentClass const & tclass = bparams.documentClass();
1999 string const & lang = getParLanguage(bparams)->code();
2000 bool const in_appendix = process_appendix && d->params_.appendix();
2001 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2003 if (fmt.empty() && !layout.counter.empty())
2004 return tclass.counters().theCounter(layout.counter, lang);
2006 // handle 'inherited level parts' in 'fmt',
2007 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2008 size_t const i = fmt.find('@', 0);
2009 if (i != docstring::npos) {
2010 size_t const j = fmt.find('@', i + 1);
2011 if (j != docstring::npos) {
2012 docstring parent(fmt, i + 1, j - i - 1);
2013 docstring label = from_ascii("??");
2014 if (tclass.hasLayout(parent))
2015 label = expandParagraphLabel(tclass[parent], bparams,
2017 fmt = docstring(fmt, 0, i) + label
2018 + docstring(fmt, j + 1, docstring::npos);
2022 return tclass.counters().counterLabel(fmt, lang);
2026 void Paragraph::applyLayout(Layout const & new_layout)
2028 d->layout_ = &new_layout;
2029 LyXAlignment const oldAlign = d->params_.align();
2031 if (!(oldAlign & d->layout_->alignpossible)) {
2032 frontend::Alert::warning(_("Alignment not permitted"),
2033 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2034 d->params_.align(LYX_ALIGN_LAYOUT);
2039 pos_type Paragraph::beginOfBody() const
2041 return d->begin_of_body_;
2045 void Paragraph::setBeginOfBody()
2047 if (d->layout_->labeltype != LABEL_MANUAL) {
2048 d->begin_of_body_ = 0;
2052 // Unroll the first two cycles of the loop
2053 // and remember the previous character to
2054 // remove unnecessary getChar() calls
2056 pos_type end = size();
2057 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2060 char_type previous_char = d->text_[i];
2061 if (!(isNewline(i) || isEnvSeparator(i))) {
2063 while (i < end && previous_char != ' ') {
2064 char_type temp = d->text_[i];
2065 if (isNewline(i) || isEnvSeparator(i))
2068 previous_char = temp;
2074 d->begin_of_body_ = i;
2078 bool Paragraph::allowParagraphCustomization() const
2080 return inInset().allowParagraphCustomization();
2084 bool Paragraph::usePlainLayout() const
2086 return inInset().usePlainLayout();
2090 bool Paragraph::isPassThru() const
2092 return inInset().isPassThru() || d->layout_->pass_thru;
2097 // paragraphs inside floats need different alignment tags to avoid
2100 bool noTrivlistCentering(InsetCode code)
2102 return code == FLOAT_CODE
2103 || code == WRAP_CODE
2104 || code == CELL_CODE;
2108 string correction(string const & orig)
2110 if (orig == "flushleft")
2111 return "raggedright";
2112 if (orig == "flushright")
2113 return "raggedleft";
2114 if (orig == "center")
2120 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2121 InsetCode code, bool const lastpar, int & col)
2123 string macro = suffix + "{";
2124 if (noTrivlistCentering(code)) {
2126 // the last paragraph in non-trivlist-aligned
2127 // context is special (to avoid unwanted whitespace)
2128 if (suffix == "\\begin") {
2129 macro = "\\" + correction(env) + "{}";
2130 os << from_ascii(macro);
2131 col += macro.size();
2136 macro += correction(env);
2140 if (suffix == "\\par\\end") {
2144 os << from_ascii(macro);
2145 col += macro.size();
2146 if (suffix == "\\begin") {
2156 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2157 otexstream & os, OutputParams const & runparams) const
2162 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2163 (layout_->toggle_indent != ITOGGLE_NEVER) :
2164 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2166 if (canindent && params_.noindent() && !layout_->pass_thru) {
2167 os << "\\noindent ";
2171 LyXAlignment const curAlign = params_.align();
2173 if (curAlign == layout_->align)
2177 case LYX_ALIGN_NONE:
2178 case LYX_ALIGN_BLOCK:
2179 case LYX_ALIGN_LAYOUT:
2180 case LYX_ALIGN_SPECIAL:
2181 case LYX_ALIGN_DECIMAL:
2183 case LYX_ALIGN_LEFT:
2184 case LYX_ALIGN_RIGHT:
2185 case LYX_ALIGN_CENTER:
2186 if (runparams.moving_arg) {
2193 string const begin_tag = "\\begin";
2194 InsetCode code = ownerCode();
2195 bool const lastpar = runparams.isLastPar;
2198 case LYX_ALIGN_NONE:
2199 case LYX_ALIGN_BLOCK:
2200 case LYX_ALIGN_LAYOUT:
2201 case LYX_ALIGN_SPECIAL:
2202 case LYX_ALIGN_DECIMAL:
2204 case LYX_ALIGN_LEFT: {
2205 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2206 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2208 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2210 } case LYX_ALIGN_RIGHT: {
2211 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2212 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2214 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2216 } case LYX_ALIGN_CENTER: {
2217 corrected_env(os, begin_tag, "center", code, lastpar, column);
2226 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2227 otexstream & os, OutputParams const & runparams) const
2229 LyXAlignment const curAlign = params_.align();
2231 if (curAlign == layout_->align)
2235 case LYX_ALIGN_NONE:
2236 case LYX_ALIGN_BLOCK:
2237 case LYX_ALIGN_LAYOUT:
2238 case LYX_ALIGN_SPECIAL:
2239 case LYX_ALIGN_DECIMAL:
2241 case LYX_ALIGN_LEFT:
2242 case LYX_ALIGN_RIGHT:
2243 case LYX_ALIGN_CENTER:
2244 if (runparams.moving_arg)
2249 bool output = false;
2251 string const end_tag = "\\par\\end";
2252 InsetCode code = ownerCode();
2253 bool const lastpar = runparams.isLastPar;
2256 case LYX_ALIGN_NONE:
2257 case LYX_ALIGN_BLOCK:
2258 case LYX_ALIGN_LAYOUT:
2259 case LYX_ALIGN_SPECIAL:
2260 case LYX_ALIGN_DECIMAL:
2262 case LYX_ALIGN_LEFT: {
2263 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2264 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2266 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2268 } case LYX_ALIGN_RIGHT: {
2269 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2270 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2272 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2274 } case LYX_ALIGN_CENTER: {
2275 corrected_env(os, end_tag, "center", code, lastpar, col);
2280 return output || lastpar;
2284 // This one spits out the text of the paragraph
2285 void Paragraph::latex(BufferParams const & bparams,
2286 Font const & outerfont,
2288 OutputParams const & runparams,
2289 int start_pos, int end_pos, bool force) const
2291 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2293 // FIXME This check should not be needed. Perhaps issue an
2294 // error if it triggers.
2295 Layout const & style = inInset().forcePlainLayout() ?
2296 bparams.documentClass().plainLayout() : *d->layout_;
2298 if (!force && style.inpreamble)
2301 bool const allowcust = allowParagraphCustomization();
2303 // Current base font for all inherited font changes, without any
2304 // change caused by an individual character, except for the language:
2305 // It is set to the language of the first character.
2306 // As long as we are in the label, this font is the base font of the
2307 // label. Before the first body character it is set to the base font
2311 // Maybe we have to create a optional argument.
2312 pos_type body_pos = beginOfBody();
2313 unsigned int column = 0;
2316 // the optional argument is kept in curly brackets in
2317 // case it contains a ']'
2318 // This is not strictly needed, but if this is changed it
2319 // would be a file format change, and tex2lyx would need
2320 // to be adjusted, since it unconditionally removes the
2321 // braces when it parses \item.
2324 basefont = getLabelFont(bparams, outerfont);
2326 basefont = getLayoutFont(bparams, outerfont);
2329 // Which font is currently active?
2330 Font running_font(basefont);
2331 // Do we have an open font change?
2332 bool open_font = false;
2334 Change runningChange = Change(Change::UNCHANGED);
2336 Encoding const * const prev_encoding = runparams.encoding;
2338 os.texrow().start(id(), 0);
2340 // if the paragraph is empty, the loop will not be entered at all
2342 if (style.isCommand()) {
2346 if (!style.leftdelim().empty()) {
2347 os << style.leftdelim();
2348 column += style.leftdelim().size();
2351 column += d->startTeXParParams(bparams, os, runparams);
2354 for (pos_type i = 0; i < size(); ++i) {
2355 // First char in paragraph or after label?
2356 if (i == body_pos) {
2359 column += running_font.latexWriteEndChanges(
2360 os, bparams, runparams,
2361 basefont, basefont);
2364 basefont = getLayoutFont(bparams, outerfont);
2365 running_font = basefont;
2367 column += Changes::latexMarkChange(os, bparams,
2368 runningChange, Change(Change::UNCHANGED),
2370 runningChange = Change(Change::UNCHANGED);
2375 if (style.isCommand()) {
2380 if (!style.leftdelim().empty()) {
2381 os << style.leftdelim();
2382 column += style.leftdelim().size();
2386 column += d->startTeXParParams(bparams, os,
2390 Change const & change = runparams.inDeletedInset
2391 ? runparams.changeOfDeletedInset : lookupChange(i);
2393 if (bparams.output_changes && runningChange != change) {
2395 column += running_font.latexWriteEndChanges(
2396 os, bparams, runparams, basefont, basefont);
2399 basefont = getLayoutFont(bparams, outerfont);
2400 running_font = basefont;
2402 column += Changes::latexMarkChange(os, bparams, runningChange,
2404 runningChange = change;
2407 // do not output text which is marked deleted
2408 // if change tracking output is disabled
2409 if (!bparams.output_changes && change.deleted()) {
2415 // Fully instantiated font
2416 Font const current_font = getFont(bparams, i, outerfont);
2418 Font const last_font = running_font;
2420 // Do we need to close the previous font?
2422 (current_font != running_font ||
2423 current_font.language() != running_font.language()))
2425 column += running_font.latexWriteEndChanges(
2426 os, bparams, runparams, basefont,
2427 (i == body_pos-1) ? basefont : current_font);
2428 running_font = basefont;
2432 string const running_lang = runparams.use_polyglossia ?
2433 running_font.language()->polyglossia() : running_font.language()->babel();
2434 // close babel's font environment before opening CJK.
2435 string const lang_end_command = runparams.use_polyglossia ?
2436 "\\end{$$lang}" : lyxrc.language_command_end;
2437 if (!running_lang.empty() &&
2438 current_font.language()->encoding()->package() == Encoding::CJK) {
2439 string end_tag = subst(lang_end_command,
2442 os << from_ascii(end_tag);
2443 column += end_tag.length();
2444 if (runparams.use_polyglossia)
2445 popPolyglossiaLang();
2448 // Switch file encoding if necessary (and allowed)
2449 if (!runparams.pass_thru && !style.pass_thru &&
2450 runparams.encoding->package() != Encoding::none &&
2451 current_font.language()->encoding()->package() != Encoding::none) {
2452 pair<bool, int> const enc_switch =
2453 switchEncoding(os.os(), bparams, runparams,
2454 *(current_font.language()->encoding()));
2455 if (enc_switch.first) {
2456 column += enc_switch.second;
2457 runparams.encoding = current_font.language()->encoding();
2461 char_type const c = d->text_[i];
2463 // Do we need to change font?
2464 if ((current_font != running_font ||
2465 current_font.language() != running_font.language()) &&
2468 odocstringstream ods;
2469 column += current_font.latexWriteStartChanges(ods, bparams,
2470 runparams, basefont,
2472 running_font = current_font;
2474 docstring fontchange = ods.str();
2475 // check whether the fontchange ends with a \\textcolor
2476 // modifier and the text starts with a space (bug 4473)
2477 docstring const last_modifier = rsplit(fontchange, '\\');
2478 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2479 os << fontchange << from_ascii("{}");
2480 // check if the fontchange ends with a trailing blank
2481 // (like "\small " (see bug 3382)
2482 else if (suffixIs(fontchange, ' ') && c == ' ')
2483 os << fontchange.substr(0, fontchange.size() - 1)
2484 << from_ascii("{}");
2489 // FIXME: think about end_pos implementation...
2490 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2491 // FIXME: integrate this case in latexSpecialChar
2492 // Do not print the separation of the optional argument
2493 // if style.pass_thru is false. This works because
2494 // latexSpecialChar ignores spaces if
2495 // style.pass_thru is false.
2496 if (i != body_pos - 1) {
2497 if (d->simpleTeXBlanks(runparams, os,
2498 i, column, current_font, style)) {
2499 // A surrogate pair was output. We
2500 // must not call latexSpecialChar
2501 // in this iteration, since it would output
2502 // the combining character again.
2509 OutputParams rp = runparams;
2510 rp.free_spacing = style.free_spacing;
2511 rp.local_font = ¤t_font;
2512 rp.intitle = style.intitle;
2514 // Two major modes: LaTeX or plain
2515 // Handle here those cases common to both modes
2516 // and then split to handle the two modes separately.
2517 if (c == META_INSET) {
2518 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2519 d->latexInset(bparams, os, rp, running_font,
2520 basefont, outerfont, open_font,
2521 runningChange, style, i, column);
2524 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2526 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2527 style, i, end_pos, column);
2528 } catch (EncodingException & e) {
2529 if (runparams.dryrun) {
2530 os << "<" << _("LyX Warning: ")
2531 << _("uncodable character") << " '";
2535 // add location information and throw again.
2544 // Set the encoding to that returned from latexSpecialChar (see
2545 // comment for encoding member in OutputParams.h)
2546 runparams.encoding = rp.encoding;
2549 // If we have an open font definition, we have to close it
2551 #ifdef FIXED_LANGUAGE_END_DETECTION
2553 running_font.latexWriteEndChanges(os, bparams,
2554 runparams, basefont,
2555 next_->getFont(bparams, 0, outerfont));
2557 running_font.latexWriteEndChanges(os, bparams,
2558 runparams, basefont, basefont);
2561 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2562 //FIXME: there as we start another \selectlanguage with the next paragraph if
2563 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2564 running_font.latexWriteEndChanges(os, bparams, runparams,
2565 basefont, basefont);
2569 column += Changes::latexMarkChange(os, bparams, runningChange,
2570 Change(Change::UNCHANGED), runparams);
2572 // Needed if there is an optional argument but no contents.
2573 if (body_pos > 0 && body_pos == size()) {
2577 if (!style.rightdelim().empty()) {
2578 os << style.rightdelim();
2579 column += style.rightdelim().size();
2582 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2583 && runparams.encoding != prev_encoding) {
2584 runparams.encoding = prev_encoding;
2585 os << setEncoding(prev_encoding->iconvName());
2588 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2592 bool Paragraph::emptyTag() const
2594 for (pos_type i = 0; i < size(); ++i) {
2595 if (Inset const * inset = getInset(i)) {
2596 InsetCode lyx_code = inset->lyxCode();
2597 // FIXME testing like that is wrong. What is
2599 if (lyx_code != TOC_CODE &&
2600 lyx_code != INCLUDE_CODE &&
2601 lyx_code != GRAPHICS_CODE &&
2602 lyx_code != ERT_CODE &&
2603 lyx_code != LISTINGS_CODE &&
2604 lyx_code != FLOAT_CODE &&
2605 lyx_code != TABULAR_CODE) {
2609 char_type c = d->text_[i];
2610 if (c != ' ' && c != '\t')
2618 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2621 for (pos_type i = 0; i < size(); ++i) {
2622 if (Inset const * inset = getInset(i)) {
2623 InsetCode lyx_code = inset->lyxCode();
2624 if (lyx_code == LABEL_CODE) {
2625 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2626 docstring const & id = il->getParam("name");
2627 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2635 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2639 for (i = 0; i < size(); ++i) {
2640 if (Inset const * inset = getInset(i)) {
2641 inset->docbook(os, runparams);
2643 char_type c = d->text_[i];
2646 os << sgml::escapeChar(c);
2653 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2657 for (i = 0; i < size(); ++i) {
2658 if (Inset const * inset = getInset(i)) {
2659 inset->xhtml(xs, runparams);
2661 char_type c = d->text_[i];
2671 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2674 pos_type size = text_.size();
2675 for (pos_type i = initial; i < size; ++i) {
2676 Font font = owner_->getFont(buf.params(), i, outerfont);
2677 if (text_[i] == META_INSET)
2679 if (i != initial && font != font_old)
2688 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2690 OutputParams const & runparams,
2691 Font const & outerfont,
2692 pos_type initial) const
2694 bool emph_flag = false;
2696 Layout const & style = *d->layout_;
2698 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2700 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2703 // parsing main loop
2704 for (pos_type i = initial; i < size(); ++i) {
2705 Font font = getFont(buf.params(), i, outerfont);
2707 // handle <emphasis> tag
2708 if (font_old.emph() != font.fontInfo().emph()) {
2709 if (font.fontInfo().emph() == FONT_ON) {
2712 } else if (i != initial) {
2713 os << "</emphasis>";
2718 if (Inset const * inset = getInset(i)) {
2719 inset->docbook(os, runparams);
2721 char_type c = d->text_[i];
2723 if (style.pass_thru)
2726 os << sgml::escapeChar(c);
2728 font_old = font.fontInfo();
2732 os << "</emphasis>";
2735 if (style.free_spacing)
2737 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2743 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2744 vector<html::EndFontTag> & tagsToClose,
2745 bool & flag, FontState curstate, html::FontTypes type)
2747 if (curstate == FONT_ON) {
2748 tagsToOpen.push_back(html::FontTag(type));
2751 tagsToClose.push_back(html::EndFontTag(type));
2758 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2760 OutputParams const & runparams,
2761 Font const & outerfont,
2762 bool start_paragraph, bool close_paragraph,
2763 pos_type initial) const
2767 // track whether we have opened these tags
2768 bool emph_flag = false;
2769 bool bold_flag = false;
2770 bool noun_flag = false;
2771 bool ubar_flag = false;
2772 bool dbar_flag = false;
2773 bool sout_flag = false;
2774 bool wave_flag = false;
2776 bool shap_flag = false;
2778 bool faml_flag = false;
2780 bool size_flag = false;
2782 Layout const & style = *d->layout_;
2784 if (start_paragraph)
2785 xs.startDivision(allowEmpty());
2788 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2790 FontShape curr_fs = INHERIT_SHAPE;
2791 FontFamily curr_fam = INHERIT_FAMILY;
2792 FontSize curr_size = FONT_SIZE_INHERIT;
2794 string const default_family =
2795 buf.masterBuffer()->params().fonts_default_family;
2797 vector<html::FontTag> tagsToOpen;
2798 vector<html::EndFontTag> tagsToClose;
2800 // parsing main loop
2801 for (pos_type i = initial; i < size(); ++i) {
2802 // let's not show deleted material in the output
2806 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2809 FontState curstate = font.fontInfo().emph();
2810 if (font_old.emph() != curstate)
2811 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2814 curstate = font.fontInfo().noun();
2815 if (font_old.noun() != curstate)
2816 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2819 curstate = font.fontInfo().underbar();
2820 if (font_old.underbar() != curstate)
2821 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2824 curstate = font.fontInfo().strikeout();
2825 if (font_old.strikeout() != curstate)
2826 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2829 curstate = font.fontInfo().uuline();
2830 if (font_old.uuline() != curstate)
2831 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2834 curstate = font.fontInfo().uwave();
2835 if (font_old.uwave() != curstate)
2836 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2839 // a little hackish, but allows us to reuse what we have.
2840 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2841 if (font_old.series() != font.fontInfo().series())
2842 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2845 curr_fs = font.fontInfo().shape();
2846 FontShape old_fs = font_old.shape();
2847 if (old_fs != curr_fs) {
2851 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2854 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2856 case SMALLCAPS_SHAPE:
2857 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2863 // the other tags are for internal use
2871 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2875 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2878 case SMALLCAPS_SHAPE:
2879 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2886 // the other tags are for internal use
2893 curr_fam = font.fontInfo().family();
2894 FontFamily old_fam = font_old.family();
2895 if (old_fam != curr_fam) {
2899 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2902 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2904 case TYPEWRITER_FAMILY:
2905 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2907 case INHERIT_FAMILY:
2910 // the other tags are for internal use
2918 // we will treat a "default" font family as roman, since we have
2919 // no other idea what to do.
2920 if (default_family != "rmdefault" && default_family != "default") {
2921 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
2926 if (default_family != "sfdefault") {
2927 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
2931 case TYPEWRITER_FAMILY:
2932 if (default_family != "ttdefault") {
2933 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
2937 case INHERIT_FAMILY:
2940 // the other tags are for internal use
2947 curr_size = font.fontInfo().size();
2948 FontSize old_size = font_old.size();
2949 if (old_size != curr_size) {
2952 case FONT_SIZE_TINY:
2953 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
2955 case FONT_SIZE_SCRIPT:
2956 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
2958 case FONT_SIZE_FOOTNOTE:
2959 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
2961 case FONT_SIZE_SMALL:
2962 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
2964 case FONT_SIZE_LARGE:
2965 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
2967 case FONT_SIZE_LARGER:
2968 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
2970 case FONT_SIZE_LARGEST:
2971 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
2973 case FONT_SIZE_HUGE:
2974 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
2976 case FONT_SIZE_HUGER:
2977 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
2979 case FONT_SIZE_INCREASE:
2980 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
2982 case FONT_SIZE_DECREASE:
2983 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
2985 case FONT_SIZE_INHERIT:
2986 case FONT_SIZE_NORMAL:
2989 // the other tags are for internal use
2995 switch (curr_size) {
2996 case FONT_SIZE_TINY:
2997 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3000 case FONT_SIZE_SCRIPT:
3001 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3004 case FONT_SIZE_FOOTNOTE:
3005 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3008 case FONT_SIZE_SMALL:
3009 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3012 case FONT_SIZE_LARGE:
3013 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3016 case FONT_SIZE_LARGER:
3017 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3020 case FONT_SIZE_LARGEST:
3021 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3024 case FONT_SIZE_HUGE:
3025 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3028 case FONT_SIZE_HUGER:
3029 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3032 case FONT_SIZE_INCREASE:
3033 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3036 case FONT_SIZE_DECREASE:
3037 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3040 case FONT_SIZE_NORMAL:
3041 case FONT_SIZE_INHERIT:
3044 // the other tags are for internal use
3051 // Other such tags? What about the other text ranges?
3053 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3054 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3055 for (; cit != cen; ++cit)
3058 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3059 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3060 for (; sit != sen; ++sit)
3063 tagsToClose.clear();
3066 Inset const * inset = getInset(i);
3068 if (!runparams.for_toc || inset->isInToc()) {
3069 OutputParams np = runparams;
3070 np.local_font = &font;
3071 // If the paragraph has size 1, then we are in the "special
3072 // case" where we do not output the containing paragraph info
3073 if (!inset->getLayout().htmlisblock() && size() != 1)
3074 np.html_in_par = true;
3075 retval += inset->xhtml(xs, np);
3078 char_type c = getUChar(buf.masterBuffer()->params(), i);
3081 font_old = font.fontInfo();
3085 // I'm worried about what happens if a branch, say, is itself
3086 // wrapped in some font stuff. I think that will not work.
3088 if (close_paragraph)
3095 bool Paragraph::isHfill(pos_type pos) const
3097 Inset const * inset = getInset(pos);
3098 return inset && inset->isHfill();
3102 bool Paragraph::isNewline(pos_type pos) const
3104 Inset const * inset = getInset(pos);
3105 return inset && inset->lyxCode() == NEWLINE_CODE;
3109 bool Paragraph::isEnvSeparator(pos_type pos) const
3111 Inset const * inset = getInset(pos);
3112 return inset && inset->lyxCode() == SEPARATOR_CODE;
3116 bool Paragraph::isLineSeparator(pos_type pos) const
3118 char_type const c = d->text_[pos];
3119 if (isLineSeparatorChar(c))
3121 Inset const * inset = getInset(pos);
3122 return inset && inset->isLineSeparator();
3126 bool Paragraph::isWordSeparator(pos_type pos) const
3130 if (Inset const * inset = getInset(pos))
3131 return !inset->isLetter();
3132 // if we have a hard hyphen (no en- or emdash) or apostrophe
3133 // we pass this to the spell checker
3134 // FIXME: this method is subject to change, visit
3135 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3136 // to get an impression how complex this is.
3137 if (isHardHyphenOrApostrophe(pos))
3139 char_type const c = d->text_[pos];
3140 // We want to pass the escape chars to the spellchecker
3141 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3142 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3146 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3148 pos_type const psize = size();
3151 char_type const c = d->text_[pos];
3152 if (c != '-' && c != '\'')
3154 int nextpos = pos + 1;
3155 int prevpos = pos > 0 ? pos - 1 : 0;
3156 if ((nextpos == psize || isSpace(nextpos))
3157 && (pos == 0 || isSpace(prevpos)))
3163 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3165 return d->speller_state_.getRange(pos);
3169 bool Paragraph::isChar(pos_type pos) const
3171 if (Inset const * inset = getInset(pos))
3172 return inset->isChar();
3173 char_type const c = d->text_[pos];
3174 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3178 bool Paragraph::isSpace(pos_type pos) const
3180 if (Inset const * inset = getInset(pos))
3181 return inset->isSpace();
3182 char_type const c = d->text_[pos];
3183 return lyx::isSpace(c);
3188 Paragraph::getParLanguage(BufferParams const & bparams) const
3191 return getFirstFontSettings(bparams).language();
3192 // FIXME: we should check the prev par as well (Lgb)
3193 return bparams.language;
3197 bool Paragraph::isRTL(BufferParams const & bparams) const
3199 return getParLanguage(bparams)->rightToLeft()
3200 && !inInset().getLayout().forceLTR();
3204 void Paragraph::changeLanguage(BufferParams const & bparams,
3205 Language const * from, Language const * to)
3207 // change language including dummy font change at the end
3208 for (pos_type i = 0; i <= size(); ++i) {
3209 Font font = getFontSettings(bparams, i);
3210 if (font.language() == from) {
3211 font.setLanguage(to);
3213 d->requestSpellCheck(i);
3219 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3221 Language const * doc_language = bparams.language;
3222 FontList::const_iterator cit = d->fontlist_.begin();
3223 FontList::const_iterator end = d->fontlist_.end();
3225 for (; cit != end; ++cit)
3226 if (cit->font().language() != ignore_language &&
3227 cit->font().language() != latex_language &&
3228 cit->font().language() != doc_language)
3234 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3236 FontList::const_iterator cit = d->fontlist_.begin();
3237 FontList::const_iterator end = d->fontlist_.end();
3239 for (; cit != end; ++cit) {
3240 Language const * lang = cit->font().language();
3241 if (lang != ignore_language &&
3242 lang != latex_language)
3243 languages.insert(lang);
3248 docstring Paragraph::asString(int options) const
3250 return asString(0, size(), options);
3254 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3256 odocstringstream os;
3259 && options & AS_STR_LABEL
3260 && !d->params_.labelString().empty())
3261 os << d->params_.labelString() << ' ';
3263 for (pos_type i = beg; i < end; ++i) {
3264 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3266 char_type const c = d->text_[i];
3267 if (isPrintable(c) || c == '\t'
3268 || (c == '\n' && (options & AS_STR_NEWLINES)))
3270 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3271 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3272 LASSERT(runparams != 0, return docstring());
3273 getInset(i)->plaintext(os, *runparams);
3275 getInset(i)->toString(os);
3284 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3285 bool const shorten) const
3287 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3288 if (!d->params_.labelString().empty())
3289 os += d->params_.labelString() + ' ';
3290 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3293 char_type const c = d->text_[i];
3296 else if (c == META_INSET)
3297 getInset(i)->forOutliner(os, tmplen, false);
3300 Text::shortenForOutliner(os, maxlen);
3304 void Paragraph::setInsetOwner(Inset const * inset)
3306 d->inset_owner_ = inset;
3310 int Paragraph::id() const
3316 void Paragraph::setId(int id)
3322 Layout const & Paragraph::layout() const
3328 void Paragraph::setLayout(Layout const & layout)
3330 d->layout_ = &layout;
3334 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3336 setLayout(tc.defaultLayout());
3340 void Paragraph::setPlainLayout(DocumentClass const & tc)
3342 setLayout(tc.plainLayout());
3346 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3348 if (usePlainLayout())
3349 setPlainLayout(tclass);
3351 setDefaultLayout(tclass);
3355 Inset const & Paragraph::inInset() const
3357 LBUFERR(d->inset_owner_);
3358 return *d->inset_owner_;
3362 ParagraphParameters & Paragraph::params()
3368 ParagraphParameters const & Paragraph::params() const
3374 bool Paragraph::isFreeSpacing() const
3376 if (d->layout_->free_spacing)
3378 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3382 bool Paragraph::allowEmpty() const
3384 if (d->layout_->keepempty)
3386 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3390 bool Paragraph::brokenBiblio() const
3392 // there is a problem if there is no bibitem at position 0 or
3393 // if there is another bibitem in the paragraph.
3394 return d->layout_->labeltype == LABEL_BIBLIO
3395 && (d->insetlist_.find(BIBITEM_CODE) != 0
3396 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3400 int Paragraph::fixBiblio(Buffer const & buffer)
3402 // FIXME: What about the case where paragraph is not BIBLIO
3403 // but there is an InsetBibitem?
3404 // FIXME: when there was already an inset at 0, the return value is 1,
3405 // which does not tell whether another inset has been remove; the
3406 // cursor cannot be correctly updated.
3408 if (d->layout_->labeltype != LABEL_BIBLIO)
3411 bool const track_changes = buffer.params().track_changes;
3412 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3413 bool const hasbibitem0 = bibitem_pos == 0;
3416 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3417 // There was an InsetBibitem at pos 0, and no other one => OK
3418 if (bibitem_pos == -1)
3420 // there is a bibitem at the 0 position, but since
3421 // there is a second one, we copy the second on the
3422 // first. We're assuming there are at most two of
3423 // these, which there should be.
3424 // FIXME: why does it make sense to do that rather
3425 // than keep the first? (JMarc)
3426 Inset * inset = releaseInset(bibitem_pos);
3427 d->insetlist_.begin()->inset = inset;
3428 return -bibitem_pos;
3431 // We need to create an inset at the beginning
3433 if (bibitem_pos > 0) {
3434 // there was one somewhere in the paragraph, let's move it
3435 inset = d->insetlist_.release(bibitem_pos);
3436 eraseChar(bibitem_pos, track_changes);
3439 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3440 InsetCommandParams(BIBITEM_CODE));
3442 Font font(inherit_font, buffer.params().language);
3443 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3444 : Change::UNCHANGED));
3450 void Paragraph::checkAuthors(AuthorList const & authorList)
3452 d->changes_.checkAuthors(authorList);
3456 bool Paragraph::isChanged(pos_type pos) const
3458 return lookupChange(pos).changed();
3462 bool Paragraph::isInserted(pos_type pos) const
3464 return lookupChange(pos).inserted();
3468 bool Paragraph::isDeleted(pos_type pos) const
3470 return lookupChange(pos).deleted();
3474 InsetList const & Paragraph::insetList() const
3476 return d->insetlist_;
3480 void Paragraph::setBuffer(Buffer & b)
3482 d->insetlist_.setBuffer(b);
3486 Inset * Paragraph::releaseInset(pos_type pos)
3488 Inset * inset = d->insetlist_.release(pos);
3489 /// does not honour change tracking!
3490 eraseChar(pos, false);
3495 Inset * Paragraph::getInset(pos_type pos)
3497 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3498 ? d->insetlist_.get(pos) : 0;
3502 Inset const * Paragraph::getInset(pos_type pos) const
3504 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3505 ? d->insetlist_.get(pos) : 0;
3509 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3510 pos_type & right, TextCase action)
3512 // process sequences of modified characters; in change
3513 // tracking mode, this approach results in much better
3514 // usability than changing case on a char-by-char basis
3515 // We also need to track the current font, since font
3516 // changes within sequences can occur.
3517 vector<pair<char_type, Font> > changes;
3519 bool const trackChanges = bparams.track_changes;
3521 bool capitalize = true;
3523 for (; pos < right; ++pos) {
3524 char_type oldChar = d->text_[pos];
3525 char_type newChar = oldChar;
3527 // ignore insets and don't play with deleted text!
3528 if (oldChar != META_INSET && !isDeleted(pos)) {
3530 case text_lowercase:
3531 newChar = lowercase(oldChar);
3533 case text_capitalization:
3535 newChar = uppercase(oldChar);
3539 case text_uppercase:
3540 newChar = uppercase(oldChar);
3545 if (isWordSeparator(pos) || isDeleted(pos)) {
3546 // permit capitalization again
3550 if (oldChar != newChar) {
3551 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3552 if (pos != right - 1)
3554 // step behind the changing area
3558 int erasePos = pos - changes.size();
3559 for (size_t i = 0; i < changes.size(); i++) {
3560 insertChar(pos, changes[i].first,
3563 if (!eraseChar(erasePos, trackChanges)) {
3566 ++right; // expand selection
3574 int Paragraph::find(docstring const & str, bool cs, bool mw,
3575 pos_type start_pos, bool del) const
3577 pos_type pos = start_pos;
3578 int const strsize = str.length();
3580 pos_type const parsize = d->text_.size();
3581 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3582 // Ignore "invisible" letters such as ligature breaks
3583 // and hyphenation chars while searching
3584 while (pos < parsize - 1 && isInset(pos)) {
3585 odocstringstream os;
3586 getInset(pos)->toString(os);
3587 if (!getInset(pos)->isLetter() || !os.str().empty())
3591 if (cs && str[i] != d->text_[pos])
3593 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3595 if (!del && isDeleted(pos))
3602 // if necessary, check whether string matches word
3604 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3607 && !isWordSeparator(pos))
3611 return pos - start_pos;
3615 char_type Paragraph::getChar(pos_type pos) const
3617 return d->text_[pos];
3621 pos_type Paragraph::size() const
3623 return d->text_.size();
3627 bool Paragraph::empty() const
3629 return d->text_.empty();
3633 bool Paragraph::isInset(pos_type pos) const
3635 return d->text_[pos] == META_INSET;
3639 bool Paragraph::isSeparator(pos_type pos) const
3641 //FIXME: Are we sure this can be the only separator?
3642 return d->text_[pos] == ' ';
3646 void Paragraph::deregisterWords()
3648 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3649 Private::LangWordsMap::const_iterator ite = d->words_.end();
3650 for (; itl != ite; ++itl) {
3651 WordList * wl = theWordList(itl->first);
3652 Private::Words::const_iterator it = (itl->second).begin();
3653 Private::Words::const_iterator et = (itl->second).end();
3654 for (; it != et; ++it)
3661 void Paragraph::locateWord(pos_type & from, pos_type & to,
3662 word_location const loc) const
3665 case WHOLE_WORD_STRICT:
3666 if (from == 0 || from == size()
3667 || isWordSeparator(from)
3668 || isWordSeparator(from - 1)) {
3672 // no break here, we go to the next
3675 // If we are already at the beginning of a word, do nothing
3676 if (!from || isWordSeparator(from - 1))
3678 // no break here, we go to the next
3681 // always move the cursor to the beginning of previous word
3682 while (from && !isWordSeparator(from - 1))
3686 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3689 // no need to move the 'from' cursor
3693 while (to < size() && !isWordSeparator(to))
3698 void Paragraph::collectWords()
3700 for (pos_type pos = 0; pos < size(); ++pos) {
3701 if (isWordSeparator(pos))
3703 pos_type from = pos;
3704 locateWord(from, pos, WHOLE_WORD);
3705 // Work around MSVC warning: The statement
3706 // if (pos < from + lyxrc.completion_minlength)
3707 // triggers a signed vs. unsigned warning.
3708 // I don't know why this happens, it could be a MSVC bug, or
3709 // related to LLP64 (windows) vs. LP64 (unix) programming
3710 // model, or the C++ standard might be ambigous in the section
3711 // defining the "usual arithmetic conversions". However, using
3712 // a temporary variable is safe and works on all compilers.
3713 pos_type const endpos = from + lyxrc.completion_minlength;
3716 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3717 if (cit == d->fontlist_.end())
3719 Language const * lang = cit->font().language();
3720 docstring const word = asString(from, pos, AS_STR_NONE);
3721 d->words_[lang->lang()].insert(word);
3726 void Paragraph::registerWords()
3728 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3729 Private::LangWordsMap::const_iterator ite = d->words_.end();
3730 for (; itl != ite; ++itl) {
3731 WordList * wl = theWordList(itl->first);
3732 Private::Words::const_iterator it = (itl->second).begin();
3733 Private::Words::const_iterator et = (itl->second).end();
3734 for (; it != et; ++it)
3740 void Paragraph::updateWords()
3748 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3750 SkipPositionsIterator begin = skips.begin();
3751 SkipPositions::iterator end = skips.end();
3752 if (pos > 0 && begin < end) {
3754 if (end->last == pos - 1) {
3759 skips.insert(end, FontSpan(pos, pos));
3763 Language * Paragraph::Private::locateSpellRange(
3764 pos_type & from, pos_type & to,
3765 SkipPositions & skips) const
3767 // skip leading white space
3768 while (from < to && owner_->isWordSeparator(from))
3770 // don't check empty range
3773 // get current language
3774 Language * lang = getSpellLanguage(from);
3775 pos_type last = from;
3776 bool samelang = true;
3777 bool sameinset = true;
3778 while (last < to && samelang && sameinset) {
3779 // hop to end of word
3780 while (last < to && !owner_->isWordSeparator(last)) {
3781 if (owner_->getInset(last)) {
3782 appendSkipPosition(skips, last);
3783 } else if (owner_->isDeleted(last)) {
3784 appendSkipPosition(skips, last);
3788 // hop to next word while checking for insets
3789 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3790 if (Inset const * inset = owner_->getInset(last))
3791 sameinset = inset->isChar() && inset->isLetter();
3792 if (sameinset && owner_->isDeleted(last)) {
3793 appendSkipPosition(skips, last);
3798 if (sameinset && last < to) {
3799 // now check for language change
3800 samelang = lang == getSpellLanguage(last);
3803 // if language change detected backstep is needed
3811 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3814 const_cast<Language *>(owner_->getFontSettings(
3815 inset_owner_->buffer().params(), from).language());
3816 if (lang == inset_owner_->buffer().params().language
3817 && !lyxrc.spellchecker_alt_lang.empty()) {
3819 string const lang_variety =
3820 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3821 lang->setCode(lang_code);
3822 lang->setVariety(lang_variety);
3828 void Paragraph::requestSpellCheck(pos_type pos)
3830 d->requestSpellCheck(pos);
3834 bool Paragraph::needsSpellCheck() const
3836 SpellChecker::ChangeNumber speller_change_number = 0;
3837 if (theSpellChecker())
3838 speller_change_number = theSpellChecker()->changeNumber();
3839 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3840 d->speller_state_.needsCompleteRefresh(speller_change_number);
3842 return d->needsSpellCheck();
3846 bool Paragraph::Private::ignoreWord(docstring const & word) const
3848 // Ignore words with digits
3849 // FIXME: make this customizable
3850 // (note that some checkers ignore words with digits by default)
3851 docstring::const_iterator cit = word.begin();
3852 docstring::const_iterator const end = word.end();
3853 for (; cit != end; ++cit) {
3854 if (isNumber((*cit)))
3861 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3862 WordLangTuple & wl, docstring_list & suggestions,
3863 bool do_suggestion, bool check_learned) const
3865 SpellChecker::Result result = SpellChecker::WORD_OK;
3866 SpellChecker * speller = theSpellChecker();
3870 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3873 locateWord(from, to, WHOLE_WORD);
3874 if (from == to || from >= size())
3877 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3878 Language * lang = d->getSpellLanguage(from);
3880 wl = WordLangTuple(word, lang);
3885 if (needsSpellCheck() || check_learned) {
3887 if (!d->ignoreWord(word)) {
3888 bool const trailing_dot = to < size() && d->text_[to] == '.';
3889 result = speller->check(wl);
3890 if (SpellChecker::misspelled(result) && trailing_dot) {
3891 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3892 result = speller->check(wl);
3893 if (!SpellChecker::misspelled(result)) {
3894 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3896 from << ".." << to << "]");
3898 // spell check with dot appended failed too
3899 // restore original word/lang value
3900 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3901 wl = WordLangTuple(word, lang);
3905 if (!SpellChecker::misspelled(result)) {
3906 // area up to the begin of the next word is not misspelled
3907 while (end < size() && isWordSeparator(end))
3910 d->setMisspelled(from, end, result);
3912 result = d->speller_state_.getState(from);
3916 suggestions.clear();
3918 if (SpellChecker::misspelled(result)) {
3919 LYXERR(Debug::GUI, "misspelled word: \"" <<
3921 from << ".." << to << "]");
3923 speller->suggest(wl, suggestions);
3929 void Paragraph::Private::markMisspelledWords(
3930 pos_type const & first, pos_type const & last,
3931 SpellChecker::Result result,
3932 docstring const & word,
3933 SkipPositions const & skips)
3935 if (!SpellChecker::misspelled(result)) {
3936 setMisspelled(first, last, SpellChecker::WORD_OK);
3940 SpellChecker * speller = theSpellChecker();
3941 // locate and enumerate the error positions
3942 int nerrors = speller->numMisspelledWords();
3944 SkipPositionsIterator it = skips.begin();
3945 SkipPositionsIterator et = skips.end();
3946 for (int index = 0; index < nerrors; ++index) {
3949 speller->misspelledWord(index, wstart, wlen);
3950 /// should not happen if speller supports range checks
3951 if (!wlen) continue;
3952 docstring const misspelled = word.substr(wstart, wlen);
3953 wstart += first + numskipped;
3954 if (snext < wstart) {
3955 /// mark the range of correct spelling
3956 numskipped += countSkips(it, et, wstart);
3957 setMisspelled(snext,
3958 wstart - 1, SpellChecker::WORD_OK);
3960 snext = wstart + wlen;
3961 numskipped += countSkips(it, et, snext);
3962 /// mark the range of misspelling
3963 setMisspelled(wstart, snext, result);
3964 LYXERR(Debug::GUI, "misspelled word: \"" <<
3965 misspelled << "\" [" <<
3966 wstart << ".." << (snext-1) << "]");
3969 if (snext <= last) {
3970 /// mark the range of correct spelling at end
3971 setMisspelled(snext, last, SpellChecker::WORD_OK);
3976 void Paragraph::spellCheck() const
3978 SpellChecker * speller = theSpellChecker();
3979 if (!speller || empty() ||!needsSpellCheck())
3983 d->rangeOfSpellCheck(start, endpos);
3984 if (speller->canCheckParagraph()) {
3985 // loop until we leave the range
3986 for (pos_type first = start; first < endpos; ) {
3987 pos_type last = endpos;
3988 Private::SkipPositions skips;
3989 Language * lang = d->locateSpellRange(first, last, skips);
3990 if (first >= endpos)
3992 // start the spell checker on the unit of meaning
3993 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3994 WordLangTuple wl = WordLangTuple(word, lang);
3995 SpellChecker::Result result = word.size() ?
3996 speller->check(wl) : SpellChecker::WORD_OK;
3997 d->markMisspelledWords(first, last, result, word, skips);
4001 static docstring_list suggestions;
4002 pos_type to = endpos;
4003 while (start < endpos) {
4005 spellCheck(start, to, wl, suggestions, false);
4009 d->readySpellCheck();
4013 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4015 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4016 if (result || pos <= 0 || pos > size())
4018 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4019 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4024 string Paragraph::magicLabel() const
4027 ss << "magicparlabel-" << id();