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 "mathed/InsetMathHull.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
71 using namespace lyx::support;
77 /// Inset identifier (above 0x10ffff, for ucs-4)
78 char_type const META_INSET = 0x200001;
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 class SpellResultRange {
91 SpellResultRange(FontSpan range, SpellChecker::Result result)
92 : range_(range), result_(result)
95 FontSpan const & range() const { return range_; }
97 void range(FontSpan const & r) { range_ = r; }
99 SpellChecker::Result result() const { return result_; }
101 void result(SpellChecker::Result r) { result_ = r; }
103 bool contains(pos_type pos) const { return range_.contains(pos); }
105 bool covered(FontSpan const & r) const
107 // 1. first of new range inside current range or
108 // 2. last of new range inside current range or
109 // 3. first of current range inside new range or
110 // 4. last of current range inside new range
111 //FIXME: is this the same as !range_.intersect(r).empty() ?
112 return range_.contains(r.first) || range_.contains(r.last) ||
113 r.contains(range_.first) || r.contains(range_.last);
116 void shift(pos_type pos, int offset)
118 if (range_.first > pos) {
119 range_.first += offset;
120 range_.last += offset;
121 } else if (range_.last >= pos) {
122 range_.last += offset;
127 SpellChecker::Result result_ ;
131 /////////////////////////////////////////////////////////////////////
135 /////////////////////////////////////////////////////////////////////
137 class SpellCheckerState {
141 needs_refresh_ = true;
142 current_change_number_ = 0;
145 void setRange(FontSpan const & fp, SpellChecker::Result state)
148 RangesIterator et = ranges_.end();
149 RangesIterator it = ranges_.begin();
150 for (; it != et; ++it) {
151 if (!it->covered(fp))
152 result.push_back(SpellResultRange(it->range(), it->result()));
153 else if (state == SpellChecker::WORD_OK) {
154 // trim or split the current misspelled range
155 // store misspelled ranges only
156 FontSpan range = it->range();
157 if (fp.first > range.first) {
158 // misspelled area in front of WORD_OK
159 range.last = fp.first - 1;
160 result.push_back(SpellResultRange(range, it->result()));
163 if (fp.last < range.last) {
164 // misspelled area after WORD_OK range
165 range.first = fp.last + 1;
166 result.push_back(SpellResultRange(range, it->result()));
171 if (state != SpellChecker::WORD_OK)
172 ranges_.push_back(SpellResultRange(fp, state));
175 void increasePosAfterPos(pos_type pos)
177 correctRangesAfterPos(pos, 1);
181 void decreasePosAfterPos(pos_type pos)
183 correctRangesAfterPos(pos, -1);
187 void refreshLast(pos_type pos)
189 if (pos < refresh_.last)
193 SpellChecker::Result getState(pos_type pos) const
195 SpellChecker::Result result = SpellChecker::WORD_OK;
196 RangesIterator et = ranges_.end();
197 RangesIterator it = ranges_.begin();
198 for (; it != et; ++it) {
199 if(it->contains(pos)) {
206 FontSpan const & getRange(pos_type pos) const
208 /// empty span to indicate mismatch
209 static FontSpan empty_;
210 RangesIterator et = ranges_.end();
211 RangesIterator it = ranges_.begin();
212 for (; it != et; ++it) {
213 if(it->contains(pos)) {
220 bool needsRefresh() const
222 return needs_refresh_;
225 SpellChecker::ChangeNumber currentChangeNumber() const
227 return current_change_number_;
230 void refreshRange(pos_type & first, pos_type & last) const
232 first = refresh_.first;
233 last = refresh_.last;
236 void needsRefresh(pos_type pos)
238 if (needs_refresh_ && pos != -1) {
239 if (pos < refresh_.first)
240 refresh_.first = pos;
241 if (pos > refresh_.last)
243 } else if (pos != -1) {
244 // init request check for neighbour positions too
245 refresh_.first = pos > 0 ? pos - 1 : 0;
246 // no need for special end of paragraph check
247 refresh_.last = pos + 1;
249 needs_refresh_ = pos != -1;
252 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
254 needs_refresh_ = true;
257 current_change_number_ = change_number;
260 typedef vector<SpellResultRange> Ranges;
261 typedef Ranges::const_iterator RangesIterator;
263 /// the area of the paragraph with pending spell check
266 /// spell state cache version number
267 SpellChecker::ChangeNumber current_change_number_;
270 void correctRangesAfterPos(pos_type pos, int offset)
272 RangesIterator et = ranges_.end();
273 Ranges::iterator it = ranges_.begin();
274 for (; it != et; ++it) {
275 it->shift(pos, offset);
281 /////////////////////////////////////////////////////////////////////
283 // Paragraph::Private
285 /////////////////////////////////////////////////////////////////////
287 class Paragraph::Private
289 // Enforce our own "copy" constructor
290 Private(Private const &) = delete;
291 Private & operator=(Private const &) = delete;
292 // Unique ID generator
293 static int make_id();
296 Private(Paragraph * owner, Layout const & layout);
297 /// "Copy constructor"
298 Private(Private const &, Paragraph * owner);
299 /// Copy constructor from \p beg to \p end
300 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
303 void insertChar(pos_type pos, char_type c, Change const & change);
305 /// Output the surrogate pair formed by \p c and \p next to \p os.
306 /// \return the number of characters written.
307 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
308 OutputParams const &);
310 /// Output a space in appropriate formatting (or a surrogate pair
311 /// if the next character is a combining character).
312 /// \return whether a surrogate pair was output.
313 bool simpleTeXBlanks(OutputParams const &,
316 unsigned int & column,
318 Layout const & style);
320 /// Output consecutive unicode chars, belonging to the same script as
321 /// specified by the latex macro \p ltx, to \p os starting from \p i.
322 /// \return the number of characters written.
323 int writeScriptChars(otexstream & os, docstring const & ltx,
324 Change const &, Encoding const &, pos_type & i);
326 /// This could go to ParagraphParameters if we want to.
327 int startTeXParParams(BufferParams const &, otexstream &,
328 OutputParams const &) const;
330 /// This could go to ParagraphParameters if we want to.
331 bool endTeXParParams(BufferParams const &, otexstream &,
332 OutputParams const &) const;
335 void latexInset(BufferParams const &,
340 Font const & outerfont,
342 Change & running_change,
343 Layout const & style,
345 unsigned int & column);
348 void latexSpecialChar(
350 BufferParams const & bparams,
351 OutputParams const & runparams,
352 Font const & running_font,
353 Change const & running_change,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column);
370 unsigned int & column);
373 void validate(LaTeXFeatures & features) const;
375 /// Checks if the paragraph contains only text and no inset or font change.
376 bool onlyText(Buffer const & buf, Font const & outerfont,
377 pos_type initial) const;
379 /// a vector of speller skip positions
380 typedef vector<FontSpan> SkipPositions;
381 typedef SkipPositions::const_iterator SkipPositionsIterator;
383 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
385 Language * getSpellLanguage(pos_type const from) const;
387 Language * locateSpellRange(pos_type & from, pos_type & to,
388 SkipPositions & skips) const;
390 bool hasSpellerChange() const
392 SpellChecker::ChangeNumber speller_change_number = 0;
393 if (theSpellChecker())
394 speller_change_number = theSpellChecker()->changeNumber();
395 return speller_change_number > speller_state_.currentChangeNumber();
398 bool ignoreWord(docstring const & word) const ;
400 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
402 pos_type textsize = owner_->size();
403 // check for sane arguments
404 if (to <= from || from >= textsize)
406 FontSpan fp = FontSpan(from, to - 1);
407 speller_state_.setRange(fp, state);
410 void requestSpellCheck(pos_type pos)
413 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
415 speller_state_.needsRefresh(pos);
418 void readySpellCheck()
420 speller_state_.needsRefresh(-1);
423 bool needsSpellCheck() const
425 return speller_state_.needsRefresh();
428 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
430 speller_state_.refreshRange(first, last);
432 last = owner_->size();
435 pos_type endpos = last;
436 owner_->locateWord(first, endpos, WHOLE_WORD);
439 owner_->locateWord(last, endpos, WHOLE_WORD);
444 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
448 while (it != et && it->first < start) {
449 int skip = it->last - it->first + 1;
457 void markMisspelledWords(pos_type const & first, pos_type const & last,
458 SpellChecker::Result result,
459 docstring const & word,
460 SkipPositions const & skips);
462 InsetCode ownerCode() const
464 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
467 /// Which Paragraph owns us?
471 Inset const * inset_owner_;
480 ParagraphParameters params_;
482 /// for recording and looking up changes
486 InsetList insetlist_;
489 pos_type begin_of_body_;
491 typedef docstring TextContainer;
495 typedef set<docstring> Words;
496 typedef map<string, Words> LangWordsMap;
500 Layout const * layout_;
502 SpellCheckerState speller_state_;
506 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
507 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
514 int Paragraph::Private::make_id()
516 // The id is unique per session across buffers because it is used in
517 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
520 static atomic_uint next_id(0);
525 Paragraph::Private::Private(Private const & p, Paragraph * owner)
526 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
528 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
529 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
532 requestSpellCheck(p.text_.size());
536 Paragraph::Private::Private(Private const & p, Paragraph * owner,
537 pos_type beg, pos_type end)
538 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
539 params_(p.params_), changes_(p.changes_),
540 insetlist_(p.insetlist_, beg, end),
541 begin_of_body_(p.begin_of_body_), words_(p.words_),
544 if (beg >= pos_type(p.text_.size()))
546 text_ = p.text_.substr(beg, end - beg);
548 FontList::const_iterator fcit = fontlist_.begin();
549 FontList::const_iterator fend = fontlist_.end();
550 for (; fcit != fend; ++fcit) {
551 if (fcit->pos() < beg)
553 if (fcit->pos() >= end) {
554 // Add last entry in the fontlist_.
555 fontlist_.set(text_.size() - 1, fcit->font());
558 // Add a new entry in the fontlist_.
559 fontlist_.set(fcit->pos() - beg, fcit->font());
561 requestSpellCheck(p.text_.size());
565 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
566 bool output_active, TocBackend & backend) const
568 d->changes_.addToToc(cdit, buf, output_active, backend);
572 void Paragraph::addChangesToBuffer(Buffer const & buf) const
574 d->changes_.updateBuffer(buf);
578 bool Paragraph::isChangeUpdateRequired() const
580 return d->changes_.isUpdateRequired();
584 bool Paragraph::isDeleted(pos_type start, pos_type end) const
586 LASSERT(start >= 0 && start <= size(), return false);
587 LASSERT(end > start && end <= size() + 1, return false);
589 return d->changes_.isDeleted(start, end);
593 bool Paragraph::isChanged(pos_type start, pos_type end) const
595 LASSERT(start >= 0 && start <= size(), return false);
596 LASSERT(end > start && end <= size() + 1, return false);
598 return d->changes_.isChanged(start, end);
602 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
604 // keep the logic here in sync with the logic of eraseChars()
608 Change const & change = d->changes_.lookup(size());
609 return change.inserted() && change.currentAuthor();
613 void Paragraph::setChange(Change const & change)
615 // beware of the imaginary end-of-par character!
616 d->changes_.set(change, 0, size() + 1);
619 * Propagate the change recursively - but not in case of DELETED!
621 * Imagine that your co-author makes changes in an existing inset. He
622 * sends your document to you and you come to the conclusion that the
623 * inset should go completely. If you erase it, LyX must not delete all
624 * text within the inset. Otherwise, the change tracked insertions of
625 * your co-author get lost and there is no way to restore them later.
627 * Conclusion: An inset's content should remain untouched if you delete it
630 if (!change.deleted()) {
631 for (pos_type pos = 0; pos < size(); ++pos) {
632 if (Inset * inset = getInset(pos))
633 inset->setChange(change);
639 void Paragraph::setChange(pos_type pos, Change const & change)
641 LASSERT(pos >= 0 && pos <= size(), return);
642 d->changes_.set(change, pos);
644 // see comment in setChange(Change const &) above
645 if (!change.deleted() && pos < size())
646 if (Inset * inset = getInset(pos))
647 inset->setChange(change);
651 Change const & Paragraph::lookupChange(pos_type pos) const
653 LBUFERR(pos >= 0 && pos <= size());
654 return d->changes_.lookup(pos);
658 void Paragraph::acceptChanges(pos_type start, pos_type end)
660 LASSERT(start >= 0 && start <= size(), return);
661 LASSERT(end > start && end <= size() + 1, return);
663 for (pos_type pos = start; pos < end; ++pos) {
664 switch (lookupChange(pos).type) {
665 case Change::UNCHANGED:
666 // accept changes in nested inset
667 if (Inset * inset = getInset(pos))
668 inset->acceptChanges();
671 case Change::INSERTED:
672 d->changes_.set(Change(Change::UNCHANGED), pos);
673 // also accept changes in nested inset
674 if (Inset * inset = getInset(pos))
675 inset->acceptChanges();
678 case Change::DELETED:
679 // Suppress access to non-existent
680 // "end-of-paragraph char"
682 eraseChar(pos, false);
693 void Paragraph::rejectChanges(pos_type start, pos_type end)
695 LASSERT(start >= 0 && start <= size(), return);
696 LASSERT(end > start && end <= size() + 1, return);
698 for (pos_type pos = start; pos < end; ++pos) {
699 switch (lookupChange(pos).type) {
700 case Change::UNCHANGED:
701 // reject changes in nested inset
702 if (Inset * inset = getInset(pos))
703 inset->rejectChanges();
706 case Change::INSERTED:
707 // Suppress access to non-existent
708 // "end-of-paragraph char"
710 eraseChar(pos, false);
716 case Change::DELETED:
717 d->changes_.set(Change(Change::UNCHANGED), pos);
719 // Do NOT reject changes within a deleted inset!
720 // There may be insertions of a co-author inside of it!
728 void Paragraph::Private::insertChar(pos_type pos, char_type c,
729 Change const & change)
731 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
734 changes_.insert(change, pos);
736 // This is actually very common when parsing buffers (and
737 // maybe inserting ascii text)
738 if (pos == pos_type(text_.size())) {
739 // when appending characters, no need to update tables
741 // but we want spell checking
742 requestSpellCheck(pos);
746 text_.insert(text_.begin() + pos, c);
748 // Update the font table.
749 fontlist_.increasePosAfterPos(pos);
752 insetlist_.increasePosAfterPos(pos);
754 // Update list of misspelled positions
755 speller_state_.increasePosAfterPos(pos);
759 bool Paragraph::insertInset(pos_type pos, Inset * inset,
760 Font const & font, Change const & change)
762 LASSERT(inset, return false);
763 LASSERT(pos >= 0 && pos <= size(), return false);
765 // Paragraph::insertInset() can be used in cut/copy/paste operation where
766 // d->inset_owner_ is not set yet.
767 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
770 d->insertChar(pos, META_INSET, change);
771 LASSERT(d->text_[pos] == META_INSET, return false);
773 // Add a new entry in the insetlist_.
774 d->insetlist_.insert(inset, pos);
776 // Some insets require run of spell checker
777 requestSpellCheck(pos);
783 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
785 LASSERT(pos >= 0 && pos <= size(), return false);
787 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
790 Change change = d->changes_.lookup(pos);
792 // set the character to DELETED if
793 // a) it was previously unchanged or
794 // b) it was inserted by a co-author
796 if (!change.changed() ||
797 (change.inserted() && !change.currentAuthor())) {
798 setChange(pos, Change(Change::DELETED));
799 // request run of spell checker
800 requestSpellCheck(pos);
804 if (change.deleted())
808 // Don't physically access the imaginary end-of-paragraph character.
809 // eraseChar() can only mark it as DELETED. A physical deletion of
810 // end-of-par must be handled externally.
816 d->changes_.erase(pos);
818 // if it is an inset, delete the inset entry
819 if (d->text_[pos] == META_INSET)
820 d->insetlist_.erase(pos);
822 d->text_.erase(d->text_.begin() + pos);
824 // Update the fontlist_
825 d->fontlist_.erase(pos);
827 // Update the insetlist_
828 d->insetlist_.decreasePosAfterPos(pos);
830 // Update list of misspelled positions
831 d->speller_state_.decreasePosAfterPos(pos);
832 d->speller_state_.refreshLast(size());
838 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
840 LASSERT(start >= 0 && start <= size(), return 0);
841 LASSERT(end >= start && end <= size() + 1, return 0);
844 for (pos_type count = end - start; count; --count) {
845 if (!eraseChar(i, trackChanges))
852 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
853 char_type next, OutputParams const & runparams)
855 // Writing next here may circumvent a possible font change between
856 // c and next. Since next is only output if it forms a surrogate pair
857 // with c we can ignore this:
858 // A font change inside a surrogate pair does not make sense and is
859 // hopefully impossible to input.
860 // FIXME: change tracking
861 // Is this correct WRT change tracking?
862 Encoding const & encoding = *(runparams.encoding);
863 docstring latex1 = encoding.latexChar(next).first;
864 if (runparams.inIPA) {
865 string const tipashortcut = Encodings::TIPAShortcut(next);
866 if (!tipashortcut.empty()) {
867 latex1 = from_ascii(tipashortcut);
870 docstring const latex2 = encoding.latexChar(c).first;
871 if (docstring(1, next) == latex1) {
872 // the encoding supports the combination
873 os << latex2 << latex1;
874 return latex1.length() + latex2.length();
875 } else if (runparams.local_font &&
876 runparams.local_font->language()->lang() == "polutonikogreek") {
877 // polutonikogreek only works without the brackets
878 os << latex1 << latex2;
879 return latex1.length() + latex2.length();
881 os << latex1 << '{' << latex2 << '}';
882 return latex1.length() + latex2.length() + 2;
886 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
889 unsigned int & column,
891 Layout const & style)
893 if (style.pass_thru || runparams.pass_thru)
896 if (i + 1 < int(text_.size())) {
897 char_type next = text_[i + 1];
898 if (Encodings::isCombiningChar(next)) {
899 // This space has an accent, so we must always output it.
900 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
905 if (runparams.linelen > 0
906 && column > runparams.linelen
908 && text_[i - 1] != ' '
909 && (i + 1 < int(text_.size()))
910 // same in FreeSpacing mode
911 && !owner_->isFreeSpacing()
912 // In typewriter mode, we want to avoid
913 // ! . ? : at the end of a line
914 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
915 && (text_[i - 1] == '.'
916 || text_[i - 1] == '?'
917 || text_[i - 1] == ':'
918 || text_[i - 1] == '!'))) {
920 os.texrow().start(owner_->id(), i + 1);
922 } else if (style.free_spacing) {
931 int Paragraph::Private::writeScriptChars(otexstream & os,
932 docstring const & ltx,
933 Change const & runningChange,
934 Encoding const & encoding,
937 // FIXME: modifying i here is not very nice...
939 // We only arrive here when character text_[i] could not be translated
940 // into the current latex encoding (or its latex translation has been forced,)
941 // and it belongs to a known script.
942 // TODO: We need \textcyr and \textgreek wrappers also for characters
943 // that can be encoded in the "LaTeX encoding" but not in the
944 // current *font encoding*.
945 // (See #9681 for details and test)
946 // Parameter ltx contains the latex translation of text_[i] as specified
947 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
948 // The latex macro name "textXXX" specifies the script to which text_[i]
949 // belongs and we use it in order to check whether characters from the
950 // same script immediately follow, such that we can collect them in a
951 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
952 // for the first char but only "<spec>" for all subsequent chars.
953 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
954 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
955 string script = to_ascii(ltx.substr(1, brace1 - 1));
958 bool closing_brace = true;
959 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
960 // Correct encoding is being used, so we can avoid \textgreek.
961 // TODO: wrong test: we need to check the *font encoding*
962 // (i.e. the active language and its FontEncoding tag)
963 // instead of the LaTeX *input encoding*!
964 // See #9637 for details and test-cases.
967 closing_brace = false;
969 os << ltx.substr(pos, length);
970 int size = text_.size();
971 while (i + 1 < size) {
972 char_type const next = text_[i + 1];
973 // Stop here if next character belongs to another script
974 // or there is a change in change tracking status.
975 if (!Encodings::isKnownScriptChar(next, script) ||
976 runningChange != owner_->lookupChange(i + 1))
980 FontList::const_iterator cit = fontlist_.begin();
981 FontList::const_iterator end = fontlist_.end();
982 for (; cit != end; ++cit) {
983 if (cit->pos() >= i && !found) {
984 prev_font = cit->font();
987 if (cit->pos() >= i + 1)
990 // Stop here if there is a font attribute or encoding change.
991 if (found && cit != end && prev_font != cit->font())
993 docstring const latex = encoding.latexChar(next).first;
994 docstring::size_type const b1 =
995 latex.find_first_of(from_ascii("{"));
996 docstring::size_type const b2 =
997 latex.find_last_of(from_ascii("}"));
998 int const len = b2 - b1 - 1;
999 os << latex.substr(b1 + 1, len);
1003 if (closing_brace) {
1011 void Paragraph::Private::latexInset(BufferParams const & bparams,
1013 OutputParams & runparams,
1014 Font & running_font,
1016 Font const & outerfont,
1018 Change & running_change,
1019 Layout const & style,
1021 unsigned int & column)
1023 Inset * inset = owner_->getInset(i);
1026 if (style.pass_thru) {
1027 odocstringstream ods;
1028 inset->plaintext(ods, runparams);
1033 // FIXME: move this to InsetNewline::latex
1034 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1035 // newlines are handled differently here than
1036 // the default in simpleTeXSpecialChars().
1037 if (!style.newline_allowed) {
1041 column += running_font.latexWriteEndChanges(
1042 os, bparams, runparams,
1043 basefont, basefont);
1047 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1050 basefont = owner_->getLayoutFont(bparams, outerfont);
1051 running_font = basefont;
1053 if (runparams.moving_arg)
1057 os.texrow().start(owner_->id(), i + 1);
1061 if (owner_->isDeleted(i)) {
1062 if( ++runparams.inDeletedInset == 1)
1063 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1066 if (inset->canTrackChanges()) {
1067 column += Changes::latexMarkChange(os, bparams, running_change,
1068 Change(Change::UNCHANGED), runparams);
1069 running_change = Change(Change::UNCHANGED);
1073 odocstream::pos_type const len = os.os().tellp();
1075 if (inset->forceLTR()
1076 && !runparams.use_polyglossia
1077 && running_font.isRightToLeft()
1078 // ERT is an exception, it should be output with no
1079 // decorations at all
1080 && inset->lyxCode() != ERT_CODE) {
1081 if (running_font.language()->lang() == "farsi")
1082 os << "\\beginL" << termcmd;
1088 // FIXME: Bug: we can have an empty font change here!
1089 // if there has just been a font change, we are going to close it
1090 // right now, which means stupid latex code like \textsf{}. AFAIK,
1091 // this does not harm dvi output. A minor bug, thus (JMarc)
1093 // Some insets cannot be inside a font change command.
1094 // However, even such insets *can* be placed in \L or \R
1095 // or their equivalents (for RTL language switches), so we don't
1096 // close the language in those cases.
1097 // ArabTeX, though, cannot handle this special behavior, it seems.
1098 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1099 || running_font.language()->lang() == "arabic_arabtex";
1100 if (open_font && !inset->inheritFont()) {
1101 bool closeLanguage = arabtex
1102 || basefont.isRightToLeft() == running_font.isRightToLeft();
1103 unsigned int count = running_font.latexWriteEndChanges(os,
1104 bparams, runparams, basefont, basefont, closeLanguage);
1106 // if any font properties were closed, update the running_font,
1107 // making sure, however, to leave the language as it was
1109 // FIXME: probably a better way to keep track of the old
1110 // language, than copying the entire font?
1111 Font const copy_font(running_font);
1112 basefont = owner_->getLayoutFont(bparams, outerfont);
1113 running_font = basefont;
1115 running_font.setLanguage(copy_font.language());
1116 // leave font open if language is still open
1117 open_font = (running_font.language() == basefont.language());
1119 runparams.local_font = &basefont;
1123 size_t const previous_row_count = os.texrow().rows();
1126 runparams.lastid = id_;
1127 runparams.lastpos = i;
1128 inset->latex(os, runparams);
1129 } catch (EncodingException & e) {
1130 // add location information and throw again.
1137 if (running_font.language()->lang() == "farsi")
1138 os << "\\endL" << termcmd;
1143 if (os.texrow().rows() > previous_row_count) {
1144 os.texrow().start(owner_->id(), i + 1);
1147 column += (unsigned int)(os.os().tellp() - len);
1150 if (owner_->isDeleted(i))
1151 --runparams.inDeletedInset;
1155 void Paragraph::Private::latexSpecialChar(otexstream & os,
1156 BufferParams const & bparams,
1157 OutputParams const & runparams,
1158 Font const & running_font,
1159 Change const & running_change,
1160 Layout const & style,
1163 unsigned int & column)
1165 // With polyglossia, brackets and stuff need not be reversed
1166 // in RTL scripts (see bug #8251)
1167 char_type const c = (runparams.use_polyglossia) ?
1168 owner_->getUChar(bparams, i) : text_[i];
1170 if (style.pass_thru || runparams.pass_thru
1171 || contains(style.pass_thru_chars, c)
1172 || contains(runparams.pass_thru_chars, c)) {
1174 Encoding const * const enc = runparams.encoding;
1175 if (enc && !enc->encodable(c))
1176 throw EncodingException(c);
1182 // TIPA uses its own T3 encoding
1183 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1185 // If T1 font encoding is used, use the special
1186 // characters it provides.
1187 // NOTE: Some languages reset the font encoding internally to a
1188 // non-standard font encoding. If we are using such a language,
1189 // we do not output special T1 chars.
1190 // NOTE: XeTeX and LuaTeX use OT1 (pre 2017) or TU (as of 2017) encoding
1191 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1192 && !runparams.isFullUnicode() && bparams.font_encoding() == "T1"
1193 && latexSpecialT1(c, os, i, column))
1196 // Otherwise, we use what LaTeX provides us.
1199 os << "\\textbackslash" << termcmd;
1203 os << "\\textless" << termcmd;
1207 os << "\\textgreater" << termcmd;
1211 os << "\\textbar" << termcmd;
1216 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1217 (end_pos == -1 || i + 1 < end_pos) &&
1218 text_[i+1] == '-') {
1219 // Prevent "--" becoming an endash and "---" becoming
1221 // Within \ttfamily, "--" is merged to "-" (no endash)
1222 // so we avoid this rather irritating ligature as well
1228 os << "\\char34" << termcmd;
1233 case '%': case '#': case '{':
1241 os << "\\textasciitilde" << termcmd;
1246 os << "\\textasciicircum" << termcmd;
1253 // avoid being mistaken for optional arguments
1261 // Blanks are printed before font switching.
1262 // Sure? I am not! (try nice-latex)
1263 // I am sure it's correct. LyX might be smarter
1264 // in the future, but for now, nothing wrong is
1272 Encoding const & encoding = *(runparams.encoding);
1273 char_type next = '\0';
1274 if (i + 1 < int(text_.size())) {
1275 next = text_[i + 1];
1276 if (Encodings::isCombiningChar(next)) {
1277 column += latexSurrogatePair(os, c, next, runparams) - 1;
1283 pair<docstring, bool> latex = encoding.latexChar(c);
1284 docstring nextlatex;
1285 bool nexttipas = false;
1286 string nexttipashortcut;
1287 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1288 nextlatex = encoding.latexChar(next).first;
1289 if (runparams.inIPA) {
1290 nexttipashortcut = Encodings::TIPAShortcut(next);
1291 nexttipas = !nexttipashortcut.empty();
1295 if (runparams.inIPA) {
1296 string const tipashortcut = Encodings::TIPAShortcut(c);
1297 if (!tipashortcut.empty()) {
1298 latex.first = from_ascii(tipashortcut);
1299 latex.second = false;
1303 if (Encodings::isKnownScriptChar(c, script)
1304 && prefixIs(latex.first, from_ascii("\\" + script)))
1305 column += writeScriptChars(os, latex.first,
1306 running_change, encoding, i) - 1;
1307 else if (latex.second
1308 && ((!prefixIs(nextlatex, '\\')
1309 && !prefixIs(nextlatex, '{')
1310 && !prefixIs(nextlatex, '}'))
1312 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1314 // Prevent eating of a following
1315 // space or command corruption by
1316 // following characters
1317 if (next == ' ' || next == '\0') {
1318 column += latex.first.length() + 1;
1319 os << latex.first << "{}";
1321 column += latex.first.length();
1322 os << latex.first << " ";
1325 column += latex.first.length() - 1;
1333 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1334 pos_type i, unsigned int & column)
1340 // In T1 encoding, these characters exist
1341 // but we should avoid ligatures
1342 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1344 os << "\\textcompwordmark" << termcmd;
1351 // soul.sty breaks with \char`\"
1352 os << "\\textquotedbl" << termcmd;
1361 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1362 pos_type /*i*/, unsigned int & column)
1372 os << "\\textvertline" << termcmd;
1381 void Paragraph::Private::validate(LaTeXFeatures & features) const
1383 if (layout_->inpreamble && inset_owner_) {
1384 bool const is_command = layout_->latextype == LATEX_COMMAND;
1385 Buffer const & buf = inset_owner_->buffer();
1386 BufferParams const & bp = features.runparams().is_child
1387 ? buf.masterParams() : buf.params();
1389 // Using a string stream here circumvents the encoding
1390 // switching machinery of odocstream. Therefore the
1391 // output is wrong if this paragraph contains content
1392 // that needs to switch encoding.
1393 otexstringstream os;
1395 os << '\\' << from_ascii(layout_->latexname());
1396 // we have to provide all the optional arguments here, even though
1397 // the last one is the only one we care about.
1398 // Separate handling of optional argument inset.
1399 if (!layout_->latexargs().empty()) {
1400 OutputParams rp = features.runparams();
1401 rp.local_font = &owner_->getFirstFontSettings(bp);
1402 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1404 os << from_ascii(layout_->latexparam());
1406 size_t const length = os.length();
1407 // this will output "{" at the beginning, but not at the end
1408 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1409 if (os.length() > length) {
1412 if (!layout_->postcommandargs().empty()) {
1413 OutputParams rp = features.runparams();
1414 rp.local_font = &owner_->getFirstFontSettings(bp);
1415 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1418 features.addPreambleSnippet(os.release(), true);
1422 if (features.runparams().flavor == OutputParams::HTML
1423 && layout_->htmltitle()) {
1424 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1427 // check the params.
1428 if (!params_.spacing().isDefault())
1429 features.require("setspace");
1432 features.useLayout(layout_->name());
1435 fontlist_.validate(features);
1437 // then the indentation
1438 if (!params_.leftIndent().zero())
1439 features.require("ParagraphLeftIndent");
1442 InsetList::const_iterator icit = insetlist_.begin();
1443 InsetList::const_iterator iend = insetlist_.end();
1444 for (; icit != iend; ++icit) {
1446 features.inDeletedInset(owner_->isDeleted(icit->pos));
1447 icit->inset->validate(features);
1448 features.inDeletedInset(false);
1449 if (layout_->needprotect &&
1450 icit->inset->lyxCode() == FOOT_CODE)
1451 features.require("NeedLyXFootnoteCode");
1455 // then the contents
1456 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1457 BufferEncodings::validate(text_[i], features);
1461 /////////////////////////////////////////////////////////////////////
1465 /////////////////////////////////////////////////////////////////////
1468 Layout const emptyParagraphLayout;
1471 Paragraph::Paragraph()
1472 : d(new Paragraph::Private(this, emptyParagraphLayout))
1479 Paragraph::Paragraph(Paragraph const & par)
1480 : itemdepth(par.itemdepth),
1481 d(new Paragraph::Private(*par.d, this))
1487 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1488 : itemdepth(par.itemdepth),
1489 d(new Paragraph::Private(*par.d, this, beg, end))
1495 Paragraph & Paragraph::operator=(Paragraph const & par)
1497 // needed as we will destroy the private part before copying it
1499 itemdepth = par.itemdepth;
1503 d = new Private(*par.d, this);
1510 Paragraph::~Paragraph()
1519 // this shall be called just before every "os << ..." action.
1520 void flushString(ostream & os, docstring & s)
1529 void Paragraph::write(ostream & os, BufferParams const & bparams,
1530 depth_type & dth) const
1532 // The beginning or end of a deeper (i.e. nested) area?
1533 if (dth != d->params_.depth()) {
1534 if (d->params_.depth() > dth) {
1535 while (d->params_.depth() > dth) {
1536 os << "\n\\begin_deeper";
1540 while (d->params_.depth() < dth) {
1541 os << "\n\\end_deeper";
1547 // First write the layout
1548 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1550 d->params_.write(os);
1552 Font font1(inherit_font, bparams.language);
1554 Change running_change = Change(Change::UNCHANGED);
1556 // this string is used as a buffer to avoid repetitive calls
1557 // to to_utf8(), which turn out to be expensive (JMarc)
1558 docstring write_buffer;
1561 for (pos_type i = 0; i <= size(); ++i) {
1563 Change const & change = lookupChange(i);
1564 if (change != running_change)
1565 flushString(os, write_buffer);
1566 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1567 running_change = change;
1572 // Write font changes
1573 Font font2 = getFontSettings(bparams, i);
1574 if (font2 != font1) {
1575 flushString(os, write_buffer);
1576 font2.lyxWriteChanges(font1, os);
1581 char_type const c = d->text_[i];
1584 if (Inset const * inset = getInset(i)) {
1585 flushString(os, write_buffer);
1586 if (inset->directWrite()) {
1587 // international char, let it write
1588 // code directly so it's shorter in
1594 os << "\\begin_inset ";
1596 os << "\n\\end_inset\n\n";
1599 // FIXME This can be removed again once the mystery
1600 // crash has been resolved.
1605 flushString(os, write_buffer);
1606 os << "\n\\backslash\n";
1610 flushString(os, write_buffer);
1611 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1618 if ((column > 70 && c == ' ')
1620 flushString(os, write_buffer);
1624 // this check is to amend a bug. LyX sometimes
1625 // inserts '\0' this could cause problems.
1627 write_buffer.push_back(c);
1629 LYXERR0("NUL char in structure.");
1635 flushString(os, write_buffer);
1636 os << "\n\\end_layout\n";
1637 // FIXME This can be removed again once the mystery
1638 // crash has been resolved.
1643 void Paragraph::validate(LaTeXFeatures & features) const
1645 d->validate(features);
1649 void Paragraph::insert(pos_type start, docstring const & str,
1650 Font const & font, Change const & change)
1652 for (size_t i = 0, n = str.size(); i != n ; ++i)
1653 insertChar(start + i, str[i], font, change);
1657 void Paragraph::appendChar(char_type c, Font const & font,
1658 Change const & change)
1661 d->changes_.insert(change, d->text_.size());
1662 // when appending characters, no need to update tables
1663 d->text_.push_back(c);
1664 setFont(d->text_.size() - 1, font);
1665 d->requestSpellCheck(d->text_.size() - 1);
1669 void Paragraph::appendString(docstring const & s, Font const & font,
1670 Change const & change)
1672 pos_type end = s.size();
1673 size_t oldsize = d->text_.size();
1674 size_t newsize = oldsize + end;
1675 size_t capacity = d->text_.capacity();
1676 if (newsize >= capacity)
1677 d->text_.reserve(max(capacity + 100, newsize));
1679 // when appending characters, no need to update tables
1682 // FIXME: Optimize this!
1683 for (size_t i = oldsize; i != newsize; ++i) {
1685 d->changes_.insert(change, i);
1686 d->requestSpellCheck(i);
1688 d->fontlist_.set(oldsize, font);
1689 d->fontlist_.set(newsize - 1, font);
1693 void Paragraph::insertChar(pos_type pos, char_type c,
1696 d->insertChar(pos, c, Change(trackChanges ?
1697 Change::INSERTED : Change::UNCHANGED));
1701 void Paragraph::insertChar(pos_type pos, char_type c,
1702 Font const & font, bool trackChanges)
1704 d->insertChar(pos, c, Change(trackChanges ?
1705 Change::INSERTED : Change::UNCHANGED));
1710 void Paragraph::insertChar(pos_type pos, char_type c,
1711 Font const & font, Change const & change)
1713 d->insertChar(pos, c, change);
1718 void Paragraph::resetFonts(Font const & font)
1720 d->fontlist_.clear();
1721 d->fontlist_.set(0, font);
1722 d->fontlist_.set(d->text_.size() - 1, font);
1725 // Gets uninstantiated font setting at position.
1726 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1730 LYXERR0("pos: " << pos << " size: " << size());
1734 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1735 if (cit != d->fontlist_.end())
1738 if (pos == size() && !empty())
1739 return getFontSettings(bparams, pos - 1);
1741 // Optimisation: avoid a full font instantiation if there is no
1742 // language change from previous call.
1743 static Font previous_font;
1744 static Language const * previous_lang = 0;
1745 Language const * lang = getParLanguage(bparams);
1746 if (lang != previous_lang) {
1747 previous_lang = lang;
1748 previous_font = Font(inherit_font, lang);
1750 return previous_font;
1754 FontSpan Paragraph::fontSpan(pos_type pos) const
1756 LBUFERR(pos <= size());
1759 return FontSpan(pos, pos);
1762 FontList::const_iterator cit = d->fontlist_.begin();
1763 FontList::const_iterator end = d->fontlist_.end();
1764 for (; cit != end; ++cit) {
1765 if (cit->pos() >= pos) {
1766 if (pos >= beginOfBody())
1767 return FontSpan(max(start, beginOfBody()),
1770 return FontSpan(start,
1771 min(beginOfBody() - 1,
1774 start = cit->pos() + 1;
1777 // This should not happen, but if so, we take no chances.
1778 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1779 LASSERT(false, return FontSpan(pos, pos));
1783 // Gets uninstantiated font setting at position 0
1784 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1786 if (!empty() && !d->fontlist_.empty())
1787 return d->fontlist_.begin()->font();
1789 // Optimisation: avoid a full font instantiation if there is no
1790 // language change from previous call.
1791 static Font previous_font;
1792 static Language const * previous_lang = 0;
1793 if (bparams.language != previous_lang) {
1794 previous_lang = bparams.language;
1795 previous_font = Font(inherit_font, bparams.language);
1798 return previous_font;
1802 // Gets the fully instantiated font at a given position in a paragraph
1803 // This is basically the same function as Text::GetFont() in text2.cpp.
1804 // The difference is that this one is used for generating the LaTeX file,
1805 // and thus cosmetic "improvements" are disallowed: This has to deliver
1806 // the true picture of the buffer. (Asger)
1807 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1808 Font const & outerfont) const
1812 Font font = getFontSettings(bparams, pos);
1814 pos_type const body_pos = beginOfBody();
1815 FontInfo & fi = font.fontInfo();
1817 fi.realize(d->layout_->labelfont);
1819 fi.realize(d->layout_->font);
1821 fi.realize(outerfont.fontInfo());
1822 fi.realize(bparams.getFont().fontInfo());
1828 Font const Paragraph::getLabelFont
1829 (BufferParams const & bparams, Font const & outerfont) const
1831 FontInfo tmpfont = d->layout_->labelfont;
1832 tmpfont.realize(outerfont.fontInfo());
1833 tmpfont.realize(bparams.getFont().fontInfo());
1834 return Font(tmpfont, getParLanguage(bparams));
1838 Font const Paragraph::getLayoutFont
1839 (BufferParams const & bparams, Font const & outerfont) const
1841 FontInfo tmpfont = d->layout_->font;
1842 tmpfont.realize(outerfont.fontInfo());
1843 tmpfont.realize(bparams.getFont().fontInfo());
1844 return Font(tmpfont, getParLanguage(bparams));
1848 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1850 char_type c = d->text_[pos];
1851 if (!getFontSettings(bparams, pos).isRightToLeft())
1854 // FIXME: The arabic special casing is due to the difference of arabic
1855 // round brackets input introduced in r18599. Check if this should be
1856 // unified with Hebrew or at least if all bracket types should be
1857 // handled the same (file format change in either case).
1858 string const & lang = getFontSettings(bparams, pos).language()->lang();
1859 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1864 uc = arabic ? c : ')';
1867 uc = arabic ? c : '(';
1893 void Paragraph::setFont(pos_type pos, Font const & font)
1895 LASSERT(pos <= size(), return);
1897 // First, reduce font against layout/label font
1898 // Update: The setCharFont() routine in text2.cpp already
1899 // reduces font, so we don't need to do that here. (Asger)
1901 d->fontlist_.set(pos, font);
1905 void Paragraph::makeSameLayout(Paragraph const & par)
1907 d->layout_ = par.d->layout_;
1908 d->params_ = par.d->params_;
1912 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1914 if (isFreeSpacing())
1920 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1921 if (eraseChar(pos, trackChanges))
1927 return count > 0 || pos > 0;
1931 bool Paragraph::hasSameLayout(Paragraph const & par) const
1933 return par.d->layout_ == d->layout_
1934 && d->params_.sameLayout(par.d->params_);
1938 depth_type Paragraph::getDepth() const
1940 return d->params_.depth();
1944 depth_type Paragraph::getMaxDepthAfter() const
1946 if (d->layout_->isEnvironment())
1947 return d->params_.depth() + 1;
1949 return d->params_.depth();
1953 LyXAlignment Paragraph::getAlign() const
1955 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1956 return d->layout_->align;
1958 return d->params_.align();
1962 docstring const & Paragraph::labelString() const
1964 return d->params_.labelString();
1968 // the next two functions are for the manual labels
1969 docstring const Paragraph::getLabelWidthString() const
1971 if (d->layout_->margintype == MARGIN_MANUAL
1972 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1973 return d->params_.labelWidthString();
1975 return _("Senseless with this layout!");
1979 void Paragraph::setLabelWidthString(docstring const & s)
1981 d->params_.labelWidthString(s);
1985 docstring Paragraph::expandLabel(Layout const & layout,
1986 BufferParams const & bparams) const
1988 return expandParagraphLabel(layout, bparams, true);
1992 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1993 BufferParams const & bparams) const
1995 return expandParagraphLabel(layout, bparams, false);
1999 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2000 BufferParams const & bparams, bool process_appendix) const
2002 DocumentClass const & tclass = bparams.documentClass();
2003 string const & lang = getParLanguage(bparams)->code();
2004 bool const in_appendix = process_appendix && d->params_.appendix();
2005 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2007 if (fmt.empty() && !layout.counter.empty())
2008 return tclass.counters().theCounter(layout.counter, lang);
2010 // handle 'inherited level parts' in 'fmt',
2011 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2012 size_t const i = fmt.find('@', 0);
2013 if (i != docstring::npos) {
2014 size_t const j = fmt.find('@', i + 1);
2015 if (j != docstring::npos) {
2016 docstring parent(fmt, i + 1, j - i - 1);
2017 docstring label = from_ascii("??");
2018 if (tclass.hasLayout(parent))
2019 label = expandParagraphLabel(tclass[parent], bparams,
2021 fmt = docstring(fmt, 0, i) + label
2022 + docstring(fmt, j + 1, docstring::npos);
2026 return tclass.counters().counterLabel(fmt, lang);
2030 void Paragraph::applyLayout(Layout const & new_layout)
2032 d->layout_ = &new_layout;
2033 LyXAlignment const oldAlign = d->params_.align();
2035 if (!(oldAlign & d->layout_->alignpossible)) {
2036 frontend::Alert::warning(_("Alignment not permitted"),
2037 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2038 d->params_.align(LYX_ALIGN_LAYOUT);
2043 pos_type Paragraph::beginOfBody() const
2045 return d->begin_of_body_;
2049 void Paragraph::setBeginOfBody()
2051 if (d->layout_->labeltype != LABEL_MANUAL) {
2052 d->begin_of_body_ = 0;
2056 // Unroll the first two cycles of the loop
2057 // and remember the previous character to
2058 // remove unnecessary getChar() calls
2060 pos_type end = size();
2061 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2064 char_type previous_char = d->text_[i];
2065 if (!(isNewline(i) || isEnvSeparator(i))) {
2067 while (i < end && previous_char != ' ') {
2068 char_type temp = d->text_[i];
2069 if (isNewline(i) || isEnvSeparator(i))
2072 previous_char = temp;
2078 d->begin_of_body_ = i;
2082 bool Paragraph::allowParagraphCustomization() const
2084 return inInset().allowParagraphCustomization();
2088 bool Paragraph::usePlainLayout() const
2090 return inInset().usePlainLayout();
2094 bool Paragraph::isPassThru() const
2096 return inInset().isPassThru() || d->layout_->pass_thru;
2101 // paragraphs inside floats need different alignment tags to avoid
2104 bool noTrivlistCentering(InsetCode code)
2106 return code == FLOAT_CODE
2107 || code == WRAP_CODE
2108 || code == CELL_CODE;
2112 string correction(string const & orig)
2114 if (orig == "flushleft")
2115 return "raggedright";
2116 if (orig == "flushright")
2117 return "raggedleft";
2118 if (orig == "center")
2124 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2125 InsetCode code, bool const lastpar, int & col)
2127 string macro = suffix + "{";
2128 if (noTrivlistCentering(code)) {
2130 // the last paragraph in non-trivlist-aligned
2131 // context is special (to avoid unwanted whitespace)
2132 if (suffix == "\\begin") {
2133 macro = "\\" + correction(env) + "{}";
2134 os << from_ascii(macro);
2135 col += macro.size();
2140 macro += correction(env);
2144 if (suffix == "\\par\\end") {
2148 os << from_ascii(macro);
2149 col += macro.size();
2150 if (suffix == "\\begin") {
2160 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2161 otexstream & os, OutputParams const & runparams) const
2166 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2167 (layout_->toggle_indent != ITOGGLE_NEVER) :
2168 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2170 if (canindent && params_.noindent() && !layout_->pass_thru) {
2171 os << "\\noindent ";
2175 LyXAlignment const curAlign = params_.align();
2177 if (curAlign == layout_->align)
2181 case LYX_ALIGN_NONE:
2182 case LYX_ALIGN_BLOCK:
2183 case LYX_ALIGN_LAYOUT:
2184 case LYX_ALIGN_SPECIAL:
2185 case LYX_ALIGN_DECIMAL:
2187 case LYX_ALIGN_LEFT:
2188 case LYX_ALIGN_RIGHT:
2189 case LYX_ALIGN_CENTER:
2190 if (runparams.moving_arg) {
2197 string const begin_tag = "\\begin";
2198 InsetCode code = ownerCode();
2199 bool const lastpar = runparams.isLastPar;
2202 case LYX_ALIGN_NONE:
2203 case LYX_ALIGN_BLOCK:
2204 case LYX_ALIGN_LAYOUT:
2205 case LYX_ALIGN_SPECIAL:
2206 case LYX_ALIGN_DECIMAL:
2208 case LYX_ALIGN_LEFT: {
2209 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2210 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2212 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2214 } case LYX_ALIGN_RIGHT: {
2215 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2216 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2218 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2220 } case LYX_ALIGN_CENTER: {
2221 corrected_env(os, begin_tag, "center", code, lastpar, column);
2230 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2231 otexstream & os, OutputParams const & runparams) const
2233 LyXAlignment const curAlign = params_.align();
2235 if (curAlign == layout_->align)
2239 case LYX_ALIGN_NONE:
2240 case LYX_ALIGN_BLOCK:
2241 case LYX_ALIGN_LAYOUT:
2242 case LYX_ALIGN_SPECIAL:
2243 case LYX_ALIGN_DECIMAL:
2245 case LYX_ALIGN_LEFT:
2246 case LYX_ALIGN_RIGHT:
2247 case LYX_ALIGN_CENTER:
2248 if (runparams.moving_arg)
2253 bool output = false;
2255 string const end_tag = "\\par\\end";
2256 InsetCode code = ownerCode();
2257 bool const lastpar = runparams.isLastPar;
2260 case LYX_ALIGN_NONE:
2261 case LYX_ALIGN_BLOCK:
2262 case LYX_ALIGN_LAYOUT:
2263 case LYX_ALIGN_SPECIAL:
2264 case LYX_ALIGN_DECIMAL:
2266 case LYX_ALIGN_LEFT: {
2267 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2268 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2270 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2272 } case LYX_ALIGN_RIGHT: {
2273 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2274 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2276 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2278 } case LYX_ALIGN_CENTER: {
2279 corrected_env(os, end_tag, "center", code, lastpar, col);
2284 return output || lastpar;
2288 // This one spits out the text of the paragraph
2289 void Paragraph::latex(BufferParams const & bparams,
2290 Font const & outerfont,
2292 OutputParams const & runparams,
2293 int start_pos, int end_pos, bool force) const
2295 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2297 // FIXME This check should not be needed. Perhaps issue an
2298 // error if it triggers.
2299 Layout const & style = inInset().forcePlainLayout() ?
2300 bparams.documentClass().plainLayout() : *d->layout_;
2302 if (!force && style.inpreamble)
2305 bool const allowcust = allowParagraphCustomization();
2307 // Current base font for all inherited font changes, without any
2308 // change caused by an individual character, except for the language:
2309 // It is set to the language of the first character.
2310 // As long as we are in the label, this font is the base font of the
2311 // label. Before the first body character it is set to the base font
2315 // Maybe we have to create a optional argument.
2316 pos_type body_pos = beginOfBody();
2317 unsigned int column = 0;
2320 // the optional argument is kept in curly brackets in
2321 // case it contains a ']'
2322 // This is not strictly needed, but if this is changed it
2323 // would be a file format change, and tex2lyx would need
2324 // to be adjusted, since it unconditionally removes the
2325 // braces when it parses \item.
2328 basefont = getLabelFont(bparams, outerfont);
2330 basefont = getLayoutFont(bparams, outerfont);
2333 // Which font is currently active?
2334 Font running_font(basefont);
2335 // Do we have an open font change?
2336 bool open_font = false;
2338 Change runningChange = Change(Change::UNCHANGED);
2340 Encoding const * const prev_encoding = runparams.encoding;
2342 os.texrow().start(id(), 0);
2344 // if the paragraph is empty, the loop will not be entered at all
2346 if (style.isCommand()) {
2350 if (!style.leftdelim().empty()) {
2351 os << style.leftdelim();
2352 column += style.leftdelim().size();
2355 column += d->startTeXParParams(bparams, os, runparams);
2358 for (pos_type i = 0; i < size(); ++i) {
2359 // First char in paragraph or after label?
2360 if (i == body_pos) {
2363 column += running_font.latexWriteEndChanges(
2364 os, bparams, runparams,
2365 basefont, basefont);
2368 basefont = getLayoutFont(bparams, outerfont);
2369 running_font = basefont;
2371 column += Changes::latexMarkChange(os, bparams,
2372 runningChange, Change(Change::UNCHANGED),
2374 runningChange = Change(Change::UNCHANGED);
2379 if (style.isCommand()) {
2384 if (!style.leftdelim().empty()) {
2385 os << style.leftdelim();
2386 column += style.leftdelim().size();
2390 column += d->startTeXParParams(bparams, os,
2394 runparams.wasDisplayMath = runparams.inDisplayMath;
2395 runparams.inDisplayMath = false;
2396 bool deleted_display_math = false;
2398 // Check whether a display math inset follows
2399 if (d->text_[i] == META_INSET
2400 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2401 InsetMath const * im = getInset(i)->asInsetMath();
2402 if (im && im->asHullInset()
2403 && im->asHullInset()->outerDisplay()) {
2404 runparams.inDisplayMath = true;
2405 // runparams.inDeletedInset will be set by
2406 // latexInset later, but we need this info
2407 // before it is called. On the other hand, we
2408 // cannot set it here because it is a counter.
2409 deleted_display_math = isDeleted(i);
2413 Change const & change = runparams.inDeletedInset
2414 ? runparams.changeOfDeletedInset : lookupChange(i);
2416 if (bparams.output_changes && runningChange != change) {
2418 column += running_font.latexWriteEndChanges(
2419 os, bparams, runparams, basefont, basefont);
2422 basefont = getLayoutFont(bparams, outerfont);
2423 running_font = basefont;
2424 column += Changes::latexMarkChange(os, bparams, runningChange,
2426 runningChange = change;
2429 // do not output text which is marked deleted
2430 // if change tracking output is disabled
2431 if (!bparams.output_changes && change.deleted()) {
2437 // Fully instantiated font
2438 Font const current_font = getFont(bparams, i, outerfont);
2440 Font const last_font = running_font;
2442 // Do we need to close the previous font?
2444 (current_font != running_font ||
2445 current_font.language() != running_font.language()))
2447 column += running_font.latexWriteEndChanges(
2448 os, bparams, runparams, basefont,
2449 (i == body_pos-1) ? basefont : current_font);
2450 running_font = basefont;
2454 string const running_lang = runparams.use_polyglossia ?
2455 running_font.language()->polyglossia() : running_font.language()->babel();
2456 // close babel's font environment before opening CJK.
2457 string const lang_end_command = runparams.use_polyglossia ?
2458 "\\end{$$lang}" : lyxrc.language_command_end;
2459 if (!running_lang.empty() &&
2460 current_font.language()->encoding()->package() == Encoding::CJK) {
2461 string end_tag = subst(lang_end_command,
2464 os << from_ascii(end_tag);
2465 column += end_tag.length();
2466 if (runparams.use_polyglossia)
2467 popPolyglossiaLang();
2470 // Switch file encoding if necessary (and allowed)
2471 if (!runparams.pass_thru && !style.pass_thru &&
2472 runparams.encoding->package() != Encoding::none &&
2473 current_font.language()->encoding()->package() != Encoding::none) {
2474 pair<bool, int> const enc_switch =
2475 switchEncoding(os.os(), bparams, runparams,
2476 *(current_font.language()->encoding()));
2477 if (enc_switch.first) {
2478 column += enc_switch.second;
2479 runparams.encoding = current_font.language()->encoding();
2483 char_type const c = d->text_[i];
2485 // A display math inset inside an ulem command will be output
2486 // as a box of width \columnwidth, so we have to either disable
2487 // indentation if the inset starts a paragraph, or start a new
2488 // line to accommodate such box. This has to be done before
2489 // writing any font changing commands.
2490 if (runparams.inDisplayMath && !deleted_display_math
2491 && runparams.inulemcmd) {
2492 if (os.afterParbreak())
2498 // Do we need to change font?
2499 if ((current_font != running_font ||
2500 current_font.language() != running_font.language()) &&
2503 odocstringstream ods;
2504 column += current_font.latexWriteStartChanges(ods, bparams,
2505 runparams, basefont,
2507 // Check again for display math in ulem commands as a
2508 // font change may also occur just before a math inset.
2509 if (runparams.inDisplayMath && !deleted_display_math
2510 && runparams.inulemcmd) {
2511 if (os.afterParbreak())
2516 running_font = current_font;
2518 docstring fontchange = ods.str();
2519 // check whether the fontchange ends with a \\textcolor
2520 // modifier and the text starts with a space (bug 4473)
2521 docstring const last_modifier = rsplit(fontchange, '\\');
2522 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2523 os << fontchange << from_ascii("{}");
2524 // check if the fontchange ends with a trailing blank
2525 // (like "\small " (see bug 3382)
2526 else if (suffixIs(fontchange, ' ') && c == ' ')
2527 os << fontchange.substr(0, fontchange.size() - 1)
2528 << from_ascii("{}");
2533 // FIXME: think about end_pos implementation...
2534 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2535 // FIXME: integrate this case in latexSpecialChar
2536 // Do not print the separation of the optional argument
2537 // if style.pass_thru is false. This works because
2538 // latexSpecialChar ignores spaces if
2539 // style.pass_thru is false.
2540 if (i != body_pos - 1) {
2541 if (d->simpleTeXBlanks(runparams, os,
2542 i, column, current_font, style)) {
2543 // A surrogate pair was output. We
2544 // must not call latexSpecialChar
2545 // in this iteration, since it would output
2546 // the combining character again.
2553 OutputParams rp = runparams;
2554 rp.free_spacing = style.free_spacing;
2555 rp.local_font = ¤t_font;
2556 rp.intitle = style.intitle;
2558 // Two major modes: LaTeX or plain
2559 // Handle here those cases common to both modes
2560 // and then split to handle the two modes separately.
2561 if (c == META_INSET) {
2562 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2563 d->latexInset(bparams, os, rp, running_font,
2564 basefont, outerfont, open_font,
2565 runningChange, style, i, column);
2567 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2569 d->latexSpecialChar(os, bparams, rp,
2570 running_font, runningChange,
2571 style, i, end_pos, column);
2572 } catch (EncodingException & e) {
2573 if (runparams.dryrun) {
2574 os << "<" << _("LyX Warning: ")
2575 << _("uncodable character") << " '";
2579 // add location information and throw again.
2587 // Set the encoding to that returned from latexSpecialChar (see
2588 // comment for encoding member in OutputParams.h)
2589 runparams.encoding = rp.encoding;
2591 // Also carry on the info on a closed ulem command for insets
2592 // such as Note that do not produce any output, so that no
2593 // command is ever executed but its opening was recorded.
2594 runparams.inulemcmd = rp.inulemcmd;
2597 // If we have an open font definition, we have to close it
2599 #ifdef FIXED_LANGUAGE_END_DETECTION
2601 running_font.latexWriteEndChanges(os, bparams,
2602 runparams, basefont,
2603 next_->getFont(bparams, 0, outerfont));
2605 running_font.latexWriteEndChanges(os, bparams,
2606 runparams, basefont, basefont);
2609 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2610 //FIXME: there as we start another \selectlanguage with the next paragraph if
2611 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2612 running_font.latexWriteEndChanges(os, bparams, runparams,
2613 basefont, basefont);
2617 column += Changes::latexMarkChange(os, bparams, runningChange,
2618 Change(Change::UNCHANGED), runparams);
2620 // Needed if there is an optional argument but no contents.
2621 if (body_pos > 0 && body_pos == size()) {
2625 if (!style.rightdelim().empty()) {
2626 os << style.rightdelim();
2627 column += style.rightdelim().size();
2630 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2631 && runparams.encoding != prev_encoding) {
2632 runparams.encoding = prev_encoding;
2633 os << setEncoding(prev_encoding->iconvName());
2636 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2640 bool Paragraph::emptyTag() const
2642 for (pos_type i = 0; i < size(); ++i) {
2643 if (Inset const * inset = getInset(i)) {
2644 InsetCode lyx_code = inset->lyxCode();
2645 // FIXME testing like that is wrong. What is
2647 if (lyx_code != TOC_CODE &&
2648 lyx_code != INCLUDE_CODE &&
2649 lyx_code != GRAPHICS_CODE &&
2650 lyx_code != ERT_CODE &&
2651 lyx_code != LISTINGS_CODE &&
2652 lyx_code != FLOAT_CODE &&
2653 lyx_code != TABULAR_CODE) {
2657 char_type c = d->text_[i];
2658 if (c != ' ' && c != '\t')
2666 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2669 for (pos_type i = 0; i < size(); ++i) {
2670 if (Inset const * inset = getInset(i)) {
2671 InsetCode lyx_code = inset->lyxCode();
2672 if (lyx_code == LABEL_CODE) {
2673 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2674 docstring const & id = il->getParam("name");
2675 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2683 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2687 for (i = 0; i < size(); ++i) {
2688 if (Inset const * inset = getInset(i)) {
2689 inset->docbook(os, runparams);
2691 char_type c = d->text_[i];
2694 os << sgml::escapeChar(c);
2701 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2705 for (i = 0; i < size(); ++i) {
2706 if (Inset const * inset = getInset(i)) {
2707 inset->xhtml(xs, runparams);
2709 char_type c = d->text_[i];
2719 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2722 pos_type size = text_.size();
2723 for (pos_type i = initial; i < size; ++i) {
2724 Font font = owner_->getFont(buf.params(), i, outerfont);
2725 if (text_[i] == META_INSET)
2727 if (i != initial && font != font_old)
2736 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2738 OutputParams const & runparams,
2739 Font const & outerfont,
2740 pos_type initial) const
2742 bool emph_flag = false;
2744 Layout const & style = *d->layout_;
2746 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2748 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2751 // parsing main loop
2752 for (pos_type i = initial; i < size(); ++i) {
2753 Font font = getFont(buf.params(), i, outerfont);
2755 // handle <emphasis> tag
2756 if (font_old.emph() != font.fontInfo().emph()) {
2757 if (font.fontInfo().emph() == FONT_ON) {
2760 } else if (i != initial) {
2761 os << "</emphasis>";
2766 if (Inset const * inset = getInset(i)) {
2767 inset->docbook(os, runparams);
2769 char_type c = d->text_[i];
2771 if (style.pass_thru)
2774 os << sgml::escapeChar(c);
2776 font_old = font.fontInfo();
2780 os << "</emphasis>";
2783 if (style.free_spacing)
2785 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2791 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2792 vector<html::EndFontTag> & tagsToClose,
2793 bool & flag, FontState curstate, html::FontTypes type)
2795 if (curstate == FONT_ON) {
2796 tagsToOpen.push_back(html::FontTag(type));
2799 tagsToClose.push_back(html::EndFontTag(type));
2806 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2808 OutputParams const & runparams,
2809 Font const & outerfont,
2810 bool start_paragraph, bool close_paragraph,
2811 pos_type initial) const
2815 // track whether we have opened these tags
2816 bool emph_flag = false;
2817 bool bold_flag = false;
2818 bool noun_flag = false;
2819 bool ubar_flag = false;
2820 bool dbar_flag = false;
2821 bool sout_flag = false;
2822 bool wave_flag = false;
2824 bool shap_flag = false;
2826 bool faml_flag = false;
2828 bool size_flag = false;
2830 Layout const & style = *d->layout_;
2832 if (start_paragraph)
2833 xs.startDivision(allowEmpty());
2836 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2838 FontShape curr_fs = INHERIT_SHAPE;
2839 FontFamily curr_fam = INHERIT_FAMILY;
2840 FontSize curr_size = FONT_SIZE_INHERIT;
2842 string const default_family =
2843 buf.masterBuffer()->params().fonts_default_family;
2845 vector<html::FontTag> tagsToOpen;
2846 vector<html::EndFontTag> tagsToClose;
2848 // parsing main loop
2849 for (pos_type i = initial; i < size(); ++i) {
2850 // let's not show deleted material in the output
2854 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2857 FontState curstate = font.fontInfo().emph();
2858 if (font_old.emph() != curstate)
2859 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2862 curstate = font.fontInfo().noun();
2863 if (font_old.noun() != curstate)
2864 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2867 curstate = font.fontInfo().underbar();
2868 if (font_old.underbar() != curstate)
2869 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2872 curstate = font.fontInfo().strikeout();
2873 if (font_old.strikeout() != curstate)
2874 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2877 curstate = font.fontInfo().uuline();
2878 if (font_old.uuline() != curstate)
2879 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2882 curstate = font.fontInfo().uwave();
2883 if (font_old.uwave() != curstate)
2884 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2887 // a little hackish, but allows us to reuse what we have.
2888 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2889 if (font_old.series() != font.fontInfo().series())
2890 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2893 curr_fs = font.fontInfo().shape();
2894 FontShape old_fs = font_old.shape();
2895 if (old_fs != curr_fs) {
2899 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2902 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2904 case SMALLCAPS_SHAPE:
2905 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2911 // the other tags are for internal use
2919 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2923 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2926 case SMALLCAPS_SHAPE:
2927 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2934 // the other tags are for internal use
2941 curr_fam = font.fontInfo().family();
2942 FontFamily old_fam = font_old.family();
2943 if (old_fam != curr_fam) {
2947 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2950 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2952 case TYPEWRITER_FAMILY:
2953 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2955 case INHERIT_FAMILY:
2958 // the other tags are for internal use
2966 // we will treat a "default" font family as roman, since we have
2967 // no other idea what to do.
2968 if (default_family != "rmdefault" && default_family != "default") {
2969 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
2974 if (default_family != "sfdefault") {
2975 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
2979 case TYPEWRITER_FAMILY:
2980 if (default_family != "ttdefault") {
2981 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
2985 case INHERIT_FAMILY:
2988 // the other tags are for internal use
2995 curr_size = font.fontInfo().size();
2996 FontSize old_size = font_old.size();
2997 if (old_size != curr_size) {
3000 case FONT_SIZE_TINY:
3001 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3003 case FONT_SIZE_SCRIPT:
3004 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3006 case FONT_SIZE_FOOTNOTE:
3007 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3009 case FONT_SIZE_SMALL:
3010 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3012 case FONT_SIZE_LARGE:
3013 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3015 case FONT_SIZE_LARGER:
3016 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3018 case FONT_SIZE_LARGEST:
3019 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3021 case FONT_SIZE_HUGE:
3022 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3024 case FONT_SIZE_HUGER:
3025 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3027 case FONT_SIZE_INCREASE:
3028 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3030 case FONT_SIZE_DECREASE:
3031 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3033 case FONT_SIZE_INHERIT:
3034 case FONT_SIZE_NORMAL:
3037 // the other tags are for internal use
3043 switch (curr_size) {
3044 case FONT_SIZE_TINY:
3045 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3048 case FONT_SIZE_SCRIPT:
3049 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3052 case FONT_SIZE_FOOTNOTE:
3053 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3056 case FONT_SIZE_SMALL:
3057 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3060 case FONT_SIZE_LARGE:
3061 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3064 case FONT_SIZE_LARGER:
3065 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3068 case FONT_SIZE_LARGEST:
3069 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3072 case FONT_SIZE_HUGE:
3073 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3076 case FONT_SIZE_HUGER:
3077 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3080 case FONT_SIZE_INCREASE:
3081 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3084 case FONT_SIZE_DECREASE:
3085 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3088 case FONT_SIZE_NORMAL:
3089 case FONT_SIZE_INHERIT:
3092 // the other tags are for internal use
3099 // Other such tags? What about the other text ranges?
3101 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3102 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3103 for (; cit != cen; ++cit)
3106 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3107 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3108 for (; sit != sen; ++sit)
3111 tagsToClose.clear();
3114 Inset const * inset = getInset(i);
3116 if (!runparams.for_toc || inset->isInToc()) {
3117 OutputParams np = runparams;
3118 np.local_font = &font;
3119 // If the paragraph has size 1, then we are in the "special
3120 // case" where we do not output the containing paragraph info
3121 if (!inset->getLayout().htmlisblock() && size() != 1)
3122 np.html_in_par = true;
3123 retval += inset->xhtml(xs, np);
3126 char_type c = getUChar(buf.masterBuffer()->params(), i);
3129 font_old = font.fontInfo();
3133 // I'm worried about what happens if a branch, say, is itself
3134 // wrapped in some font stuff. I think that will not work.
3136 if (close_paragraph)
3143 bool Paragraph::isHfill(pos_type pos) const
3145 Inset const * inset = getInset(pos);
3146 return inset && inset->isHfill();
3150 bool Paragraph::isNewline(pos_type pos) const
3152 // U+2028 LINE SEPARATOR
3153 // U+2029 PARAGRAPH SEPARATOR
3154 char_type const c = d->text_[pos];
3155 if (c == 0x2028 || c == 0x2029)
3157 Inset const * inset = getInset(pos);
3158 return inset && inset->lyxCode() == NEWLINE_CODE;
3162 bool Paragraph::isEnvSeparator(pos_type pos) const
3164 Inset const * inset = getInset(pos);
3165 return inset && inset->lyxCode() == SEPARATOR_CODE;
3169 bool Paragraph::isLineSeparator(pos_type pos) const
3171 char_type const c = d->text_[pos];
3172 if (isLineSeparatorChar(c))
3174 Inset const * inset = getInset(pos);
3175 return inset && inset->isLineSeparator();
3179 bool Paragraph::isWordSeparator(pos_type pos) const
3183 if (Inset const * inset = getInset(pos))
3184 return !inset->isLetter();
3185 // if we have a hard hyphen (no en- or emdash) or apostrophe
3186 // we pass this to the spell checker
3187 // FIXME: this method is subject to change, visit
3188 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3189 // to get an impression how complex this is.
3190 if (isHardHyphenOrApostrophe(pos))
3192 char_type const c = d->text_[pos];
3193 // We want to pass the escape chars to the spellchecker
3194 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3195 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3199 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3201 pos_type const psize = size();
3204 char_type const c = d->text_[pos];
3205 if (c != '-' && c != '\'')
3207 int nextpos = pos + 1;
3208 int prevpos = pos > 0 ? pos - 1 : 0;
3209 if ((nextpos == psize || isSpace(nextpos))
3210 && (pos == 0 || isSpace(prevpos)))
3216 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3218 return d->speller_state_.getRange(pos);
3222 bool Paragraph::isChar(pos_type pos) const
3224 if (Inset const * inset = getInset(pos))
3225 return inset->isChar();
3226 char_type const c = d->text_[pos];
3227 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3231 bool Paragraph::isSpace(pos_type pos) const
3233 if (Inset const * inset = getInset(pos))
3234 return inset->isSpace();
3235 char_type const c = d->text_[pos];
3236 return lyx::isSpace(c);
3241 Paragraph::getParLanguage(BufferParams const & bparams) const
3244 return getFirstFontSettings(bparams).language();
3245 // FIXME: we should check the prev par as well (Lgb)
3246 return bparams.language;
3250 bool Paragraph::isRTL(BufferParams const & bparams) const
3252 return getParLanguage(bparams)->rightToLeft()
3253 && !inInset().getLayout().forceLTR();
3257 void Paragraph::changeLanguage(BufferParams const & bparams,
3258 Language const * from, Language const * to)
3260 // change language including dummy font change at the end
3261 for (pos_type i = 0; i <= size(); ++i) {
3262 Font font = getFontSettings(bparams, i);
3263 if (font.language() == from) {
3264 font.setLanguage(to);
3266 d->requestSpellCheck(i);
3272 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3274 Language const * doc_language = bparams.language;
3275 FontList::const_iterator cit = d->fontlist_.begin();
3276 FontList::const_iterator end = d->fontlist_.end();
3278 for (; cit != end; ++cit)
3279 if (cit->font().language() != ignore_language &&
3280 cit->font().language() != latex_language &&
3281 cit->font().language() != doc_language)
3287 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3289 FontList::const_iterator cit = d->fontlist_.begin();
3290 FontList::const_iterator end = d->fontlist_.end();
3292 for (; cit != end; ++cit) {
3293 Language const * lang = cit->font().language();
3294 if (lang != ignore_language &&
3295 lang != latex_language)
3296 languages.insert(lang);
3301 docstring Paragraph::asString(int options) const
3303 return asString(0, size(), options);
3307 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3309 odocstringstream os;
3312 && options & AS_STR_LABEL
3313 && !d->params_.labelString().empty())
3314 os << d->params_.labelString() << ' ';
3316 for (pos_type i = beg; i < end; ++i) {
3317 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3319 char_type const c = d->text_[i];
3320 if (isPrintable(c) || c == '\t'
3321 || (c == '\n' && (options & AS_STR_NEWLINES)))
3323 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3324 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3325 LASSERT(runparams != 0, return docstring());
3326 getInset(i)->plaintext(os, *runparams);
3328 getInset(i)->toString(os);
3337 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3338 bool const shorten, bool const label) const
3340 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3341 if (label && !labelString().empty())
3342 os += labelString() + ' ';
3343 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3346 char_type const c = d->text_[i];
3349 else if (c == META_INSET)
3350 getInset(i)->forOutliner(os, tmplen, false);
3353 Text::shortenForOutliner(os, maxlen);
3357 void Paragraph::setInsetOwner(Inset const * inset)
3359 d->inset_owner_ = inset;
3363 int Paragraph::id() const
3369 void Paragraph::setId(int id)
3375 Layout const & Paragraph::layout() const
3381 void Paragraph::setLayout(Layout const & layout)
3383 d->layout_ = &layout;
3387 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3389 setLayout(tc.defaultLayout());
3393 void Paragraph::setPlainLayout(DocumentClass const & tc)
3395 setLayout(tc.plainLayout());
3399 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3401 if (usePlainLayout())
3402 setPlainLayout(tclass);
3404 setDefaultLayout(tclass);
3408 Inset const & Paragraph::inInset() const
3410 LBUFERR(d->inset_owner_);
3411 return *d->inset_owner_;
3415 ParagraphParameters & Paragraph::params()
3421 ParagraphParameters const & Paragraph::params() const
3427 bool Paragraph::isFreeSpacing() const
3429 if (d->layout_->free_spacing)
3431 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3435 bool Paragraph::allowEmpty() const
3437 if (d->layout_->keepempty)
3439 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3443 bool Paragraph::brokenBiblio() const
3445 // there is a problem if there is no bibitem at position 0 or
3446 // if there is another bibitem in the paragraph.
3447 return d->layout_->labeltype == LABEL_BIBLIO
3448 && (d->insetlist_.find(BIBITEM_CODE) != 0
3449 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3453 int Paragraph::fixBiblio(Buffer const & buffer)
3455 // FIXME: What about the case where paragraph is not BIBLIO
3456 // but there is an InsetBibitem?
3457 // FIXME: when there was already an inset at 0, the return value is 1,
3458 // which does not tell whether another inset has been remove; the
3459 // cursor cannot be correctly updated.
3461 if (d->layout_->labeltype != LABEL_BIBLIO)
3464 bool const track_changes = buffer.params().track_changes;
3465 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3466 bool const hasbibitem0 = bibitem_pos == 0;
3469 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3470 // There was an InsetBibitem at pos 0, and no other one => OK
3471 if (bibitem_pos == -1)
3473 // there is a bibitem at the 0 position, but since
3474 // there is a second one, we copy the second on the
3475 // first. We're assuming there are at most two of
3476 // these, which there should be.
3477 // FIXME: why does it make sense to do that rather
3478 // than keep the first? (JMarc)
3479 Inset * inset = releaseInset(bibitem_pos);
3480 d->insetlist_.begin()->inset = inset;
3481 return -bibitem_pos;
3484 // We need to create an inset at the beginning
3486 if (bibitem_pos > 0) {
3487 // there was one somewhere in the paragraph, let's move it
3488 inset = d->insetlist_.release(bibitem_pos);
3489 eraseChar(bibitem_pos, track_changes);
3492 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3493 InsetCommandParams(BIBITEM_CODE));
3495 Font font(inherit_font, buffer.params().language);
3496 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3497 : Change::UNCHANGED));
3503 void Paragraph::checkAuthors(AuthorList const & authorList)
3505 d->changes_.checkAuthors(authorList);
3509 bool Paragraph::isChanged(pos_type pos) const
3511 return lookupChange(pos).changed();
3515 bool Paragraph::isInserted(pos_type pos) const
3517 return lookupChange(pos).inserted();
3521 bool Paragraph::isDeleted(pos_type pos) const
3523 return lookupChange(pos).deleted();
3527 InsetList const & Paragraph::insetList() const
3529 return d->insetlist_;
3533 void Paragraph::setBuffer(Buffer & b)
3535 d->insetlist_.setBuffer(b);
3539 void Paragraph::resetBuffer()
3541 d->insetlist_.resetBuffer();
3545 Inset * Paragraph::releaseInset(pos_type pos)
3547 Inset * inset = d->insetlist_.release(pos);
3548 /// does not honour change tracking!
3549 eraseChar(pos, false);
3554 Inset * Paragraph::getInset(pos_type pos)
3556 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3557 ? d->insetlist_.get(pos) : 0;
3561 Inset const * Paragraph::getInset(pos_type pos) const
3563 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3564 ? d->insetlist_.get(pos) : 0;
3568 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3569 pos_type & right, TextCase action)
3571 // process sequences of modified characters; in change
3572 // tracking mode, this approach results in much better
3573 // usability than changing case on a char-by-char basis
3574 // We also need to track the current font, since font
3575 // changes within sequences can occur.
3576 vector<pair<char_type, Font> > changes;
3578 bool const trackChanges = bparams.track_changes;
3580 bool capitalize = true;
3582 for (; pos < right; ++pos) {
3583 char_type oldChar = d->text_[pos];
3584 char_type newChar = oldChar;
3586 // ignore insets and don't play with deleted text!
3587 if (oldChar != META_INSET && !isDeleted(pos)) {
3589 case text_lowercase:
3590 newChar = lowercase(oldChar);
3592 case text_capitalization:
3594 newChar = uppercase(oldChar);
3598 case text_uppercase:
3599 newChar = uppercase(oldChar);
3604 if (isWordSeparator(pos) || isDeleted(pos)) {
3605 // permit capitalization again
3609 if (oldChar != newChar) {
3610 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3611 if (pos != right - 1)
3613 // step behind the changing area
3617 int erasePos = pos - changes.size();
3618 for (size_t i = 0; i < changes.size(); i++) {
3619 insertChar(pos, changes[i].first,
3622 if (!eraseChar(erasePos, trackChanges)) {
3625 ++right; // expand selection
3633 int Paragraph::find(docstring const & str, bool cs, bool mw,
3634 pos_type start_pos, bool del) const
3636 pos_type pos = start_pos;
3637 int const strsize = str.length();
3639 pos_type const parsize = d->text_.size();
3640 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3641 // Ignore "invisible" letters such as ligature breaks
3642 // and hyphenation chars while searching
3643 while (pos < parsize - 1 && isInset(pos)) {
3644 odocstringstream os;
3645 getInset(pos)->toString(os);
3646 if (!getInset(pos)->isLetter() || !os.str().empty())
3650 if (cs && str[i] != d->text_[pos])
3652 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3654 if (!del && isDeleted(pos))
3661 // if necessary, check whether string matches word
3663 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3666 && !isWordSeparator(pos))
3670 return pos - start_pos;
3674 char_type Paragraph::getChar(pos_type pos) const
3676 return d->text_[pos];
3680 pos_type Paragraph::size() const
3682 return d->text_.size();
3686 bool Paragraph::empty() const
3688 return d->text_.empty();
3692 bool Paragraph::isInset(pos_type pos) const
3694 return d->text_[pos] == META_INSET;
3698 bool Paragraph::isSeparator(pos_type pos) const
3700 //FIXME: Are we sure this can be the only separator?
3701 return d->text_[pos] == ' ';
3705 void Paragraph::deregisterWords()
3707 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3708 Private::LangWordsMap::const_iterator ite = d->words_.end();
3709 for (; itl != ite; ++itl) {
3710 WordList & wl = theWordList(itl->first);
3711 Private::Words::const_iterator it = (itl->second).begin();
3712 Private::Words::const_iterator et = (itl->second).end();
3713 for (; it != et; ++it)
3720 void Paragraph::locateWord(pos_type & from, pos_type & to,
3721 word_location const loc) const
3724 case WHOLE_WORD_STRICT:
3725 if (from == 0 || from == size()
3726 || isWordSeparator(from)
3727 || isWordSeparator(from - 1)) {
3731 // no break here, we go to the next
3734 // If we are already at the beginning of a word, do nothing
3735 if (!from || isWordSeparator(from - 1))
3737 // no break here, we go to the next
3740 // always move the cursor to the beginning of previous word
3741 while (from && !isWordSeparator(from - 1))
3745 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3748 // no need to move the 'from' cursor
3752 while (to < size() && !isWordSeparator(to))
3757 void Paragraph::collectWords()
3759 for (pos_type pos = 0; pos < size(); ++pos) {
3760 if (isWordSeparator(pos))
3762 pos_type from = pos;
3763 locateWord(from, pos, WHOLE_WORD);
3764 // Work around MSVC warning: The statement
3765 // if (pos < from + lyxrc.completion_minlength)
3766 // triggers a signed vs. unsigned warning.
3767 // I don't know why this happens, it could be a MSVC bug, or
3768 // related to LLP64 (windows) vs. LP64 (unix) programming
3769 // model, or the C++ standard might be ambigous in the section
3770 // defining the "usual arithmetic conversions". However, using
3771 // a temporary variable is safe and works on all compilers.
3772 pos_type const endpos = from + lyxrc.completion_minlength;
3775 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3776 if (cit == d->fontlist_.end())
3778 Language const * lang = cit->font().language();
3779 docstring const word = asString(from, pos, AS_STR_NONE);
3780 d->words_[lang->lang()].insert(word);
3785 void Paragraph::registerWords()
3787 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3788 Private::LangWordsMap::const_iterator ite = d->words_.end();
3789 for (; itl != ite; ++itl) {
3790 WordList & wl = theWordList(itl->first);
3791 Private::Words::const_iterator it = (itl->second).begin();
3792 Private::Words::const_iterator et = (itl->second).end();
3793 for (; it != et; ++it)
3799 void Paragraph::updateWords()
3807 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3809 SkipPositionsIterator begin = skips.begin();
3810 SkipPositions::iterator end = skips.end();
3811 if (pos > 0 && begin < end) {
3813 if (end->last == pos - 1) {
3818 skips.insert(end, FontSpan(pos, pos));
3822 Language * Paragraph::Private::locateSpellRange(
3823 pos_type & from, pos_type & to,
3824 SkipPositions & skips) const
3826 // skip leading white space
3827 while (from < to && owner_->isWordSeparator(from))
3829 // don't check empty range
3832 // get current language
3833 Language * lang = getSpellLanguage(from);
3834 pos_type last = from;
3835 bool samelang = true;
3836 bool sameinset = true;
3837 while (last < to && samelang && sameinset) {
3838 // hop to end of word
3839 while (last < to && !owner_->isWordSeparator(last)) {
3840 if (owner_->getInset(last)) {
3841 appendSkipPosition(skips, last);
3842 } else if (owner_->isDeleted(last)) {
3843 appendSkipPosition(skips, last);
3847 // hop to next word while checking for insets
3848 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3849 if (Inset const * inset = owner_->getInset(last))
3850 sameinset = inset->isChar() && inset->isLetter();
3851 if (sameinset && owner_->isDeleted(last)) {
3852 appendSkipPosition(skips, last);
3857 if (sameinset && last < to) {
3858 // now check for language change
3859 samelang = lang == getSpellLanguage(last);
3862 // if language change detected backstep is needed
3870 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3873 const_cast<Language *>(owner_->getFontSettings(
3874 inset_owner_->buffer().params(), from).language());
3875 if (lang == inset_owner_->buffer().params().language
3876 && !lyxrc.spellchecker_alt_lang.empty()) {
3878 string const lang_variety =
3879 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3880 lang->setCode(lang_code);
3881 lang->setVariety(lang_variety);
3887 void Paragraph::requestSpellCheck(pos_type pos)
3889 d->requestSpellCheck(pos);
3893 bool Paragraph::needsSpellCheck() const
3895 SpellChecker::ChangeNumber speller_change_number = 0;
3896 if (theSpellChecker())
3897 speller_change_number = theSpellChecker()->changeNumber();
3898 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3899 d->speller_state_.needsCompleteRefresh(speller_change_number);
3901 return d->needsSpellCheck();
3905 bool Paragraph::Private::ignoreWord(docstring const & word) const
3907 // Ignore words with digits
3908 // FIXME: make this customizable
3909 // (note that some checkers ignore words with digits by default)
3910 docstring::const_iterator cit = word.begin();
3911 docstring::const_iterator const end = word.end();
3912 for (; cit != end; ++cit) {
3913 if (isNumber((*cit)))
3920 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3921 WordLangTuple & wl, docstring_list & suggestions,
3922 bool do_suggestion, bool check_learned) const
3924 SpellChecker::Result result = SpellChecker::WORD_OK;
3925 SpellChecker * speller = theSpellChecker();
3929 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3932 locateWord(from, to, WHOLE_WORD);
3933 if (from == to || from >= size())
3936 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3937 Language * lang = d->getSpellLanguage(from);
3939 wl = WordLangTuple(word, lang);
3944 if (needsSpellCheck() || check_learned) {
3946 if (!d->ignoreWord(word)) {
3947 bool const trailing_dot = to < size() && d->text_[to] == '.';
3948 result = speller->check(wl);
3949 if (SpellChecker::misspelled(result) && trailing_dot) {
3950 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3951 result = speller->check(wl);
3952 if (!SpellChecker::misspelled(result)) {
3953 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3955 from << ".." << to << "]");
3957 // spell check with dot appended failed too
3958 // restore original word/lang value
3959 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3960 wl = WordLangTuple(word, lang);
3964 if (!SpellChecker::misspelled(result)) {
3965 // area up to the begin of the next word is not misspelled
3966 while (end < size() && isWordSeparator(end))
3969 d->setMisspelled(from, end, result);
3971 result = d->speller_state_.getState(from);
3975 suggestions.clear();
3977 if (SpellChecker::misspelled(result)) {
3978 LYXERR(Debug::GUI, "misspelled word: \"" <<
3980 from << ".." << to << "]");
3982 speller->suggest(wl, suggestions);
3988 void Paragraph::Private::markMisspelledWords(
3989 pos_type const & first, pos_type const & last,
3990 SpellChecker::Result result,
3991 docstring const & word,
3992 SkipPositions const & skips)
3994 if (!SpellChecker::misspelled(result)) {
3995 setMisspelled(first, last, SpellChecker::WORD_OK);
3999 SpellChecker * speller = theSpellChecker();
4000 // locate and enumerate the error positions
4001 int nerrors = speller->numMisspelledWords();
4003 SkipPositionsIterator it = skips.begin();
4004 SkipPositionsIterator et = skips.end();
4005 for (int index = 0; index < nerrors; ++index) {
4008 speller->misspelledWord(index, wstart, wlen);
4009 /// should not happen if speller supports range checks
4010 if (!wlen) continue;
4011 docstring const misspelled = word.substr(wstart, wlen);
4012 wstart += first + numskipped;
4013 if (snext < wstart) {
4014 /// mark the range of correct spelling
4015 numskipped += countSkips(it, et, wstart);
4016 setMisspelled(snext,
4017 wstart - 1, SpellChecker::WORD_OK);
4019 snext = wstart + wlen;
4020 numskipped += countSkips(it, et, snext);
4021 /// mark the range of misspelling
4022 setMisspelled(wstart, snext, result);
4023 LYXERR(Debug::GUI, "misspelled word: \"" <<
4024 misspelled << "\" [" <<
4025 wstart << ".." << (snext-1) << "]");
4028 if (snext <= last) {
4029 /// mark the range of correct spelling at end
4030 setMisspelled(snext, last, SpellChecker::WORD_OK);
4035 void Paragraph::spellCheck() const
4037 SpellChecker * speller = theSpellChecker();
4038 if (!speller || empty() ||!needsSpellCheck())
4042 d->rangeOfSpellCheck(start, endpos);
4043 if (speller->canCheckParagraph()) {
4044 // loop until we leave the range
4045 for (pos_type first = start; first < endpos; ) {
4046 pos_type last = endpos;
4047 Private::SkipPositions skips;
4048 Language * lang = d->locateSpellRange(first, last, skips);
4049 if (first >= endpos)
4051 // start the spell checker on the unit of meaning
4052 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4053 WordLangTuple wl = WordLangTuple(word, lang);
4054 SpellChecker::Result result = word.size() ?
4055 speller->check(wl) : SpellChecker::WORD_OK;
4056 d->markMisspelledWords(first, last, result, word, skips);
4060 static docstring_list suggestions;
4061 pos_type to = endpos;
4062 while (start < endpos) {
4064 spellCheck(start, to, wl, suggestions, false);
4068 d->readySpellCheck();
4072 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4074 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4075 if (result || pos <= 0 || pos > size())
4077 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4078 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4083 string Paragraph::magicLabel() const
4086 ss << "magicparlabel-" << id();