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 "output_docbook.h"
41 #include "ParagraphParameters.h"
42 #include "SpellChecker.h"
44 #include "texstream.h"
45 #include "TextClass.h"
48 #include "WordLangTuple.h"
51 #include "frontends/alert.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetLabel.h"
55 #include "insets/InsetSpecialChar.h"
56 #include "insets/InsetText.h"
58 #include "mathed/InsetMathHull.h"
60 #include "support/debug.h"
61 #include "support/docstring_list.h"
62 #include "support/ExceptionMessage.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "output_docbook.h"
74 using namespace lyx::support;
76 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
77 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
78 #define THREAD_LOCAL_STATIC static __thread
79 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
80 #define THREAD_LOCAL_STATIC static __declspec(thread)
82 #define THREAD_LOCAL_STATIC thread_local static
87 /////////////////////////////////////////////////////////////////////
91 /////////////////////////////////////////////////////////////////////
93 class SpellResultRange {
95 SpellResultRange(FontSpan range, SpellChecker::Result result)
96 : range_(range), result_(result)
99 FontSpan const & range() const { return range_; }
101 void range(FontSpan const & r) { range_ = r; }
103 SpellChecker::Result result() const { return result_; }
105 void result(SpellChecker::Result r) { result_ = r; }
107 bool contains(pos_type pos) const { return range_.contains(pos); }
109 bool covered(FontSpan const & r) const
111 // 1. first of new range inside current range or
112 // 2. last of new range inside current range or
113 // 3. first of current range inside new range or
114 // 4. last of current range inside new range
115 //FIXME: is this the same as !range_.intersect(r).empty() ?
116 return range_.contains(r.first) || range_.contains(r.last) ||
117 r.contains(range_.first) || r.contains(range_.last);
120 void shift(pos_type pos, int offset)
122 if (range_.first > pos) {
123 range_.first += offset;
124 range_.last += offset;
125 } else if (range_.last >= pos) {
126 range_.last += offset;
131 SpellChecker::Result result_ ;
135 /////////////////////////////////////////////////////////////////////
139 /////////////////////////////////////////////////////////////////////
141 class SpellCheckerState {
145 needs_refresh_ = true;
146 current_change_number_ = 0;
149 void setRange(FontSpan const & fp, SpellChecker::Result state)
152 RangesIterator et = ranges_.end();
153 RangesIterator it = ranges_.begin();
154 for (; it != et; ++it) {
155 if (!it->covered(fp))
156 result.push_back(SpellResultRange(it->range(), it->result()));
157 else if (state == SpellChecker::WORD_OK) {
158 // trim or split the current misspelled range
159 // store misspelled ranges only
160 FontSpan range = it->range();
161 if (fp.first > range.first) {
162 // misspelled area in front of WORD_OK
163 range.last = fp.first - 1;
164 result.push_back(SpellResultRange(range, it->result()));
167 if (fp.last < range.last) {
168 // misspelled area after WORD_OK range
169 range.first = fp.last + 1;
170 result.push_back(SpellResultRange(range, it->result()));
175 if (state != SpellChecker::WORD_OK)
176 ranges_.push_back(SpellResultRange(fp, state));
179 void increasePosAfterPos(pos_type pos)
181 correctRangesAfterPos(pos, 1);
185 void decreasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, -1);
191 void refreshLast(pos_type pos)
193 if (pos < refresh_.last)
197 SpellChecker::Result getState(pos_type pos) const
199 SpellChecker::Result result = SpellChecker::WORD_OK;
200 RangesIterator et = ranges_.end();
201 RangesIterator it = ranges_.begin();
202 for (; it != et; ++it) {
203 if(it->contains(pos)) {
210 FontSpan const & getRange(pos_type pos) const
212 /// empty span to indicate mismatch
213 static FontSpan empty_;
214 RangesIterator et = ranges_.end();
215 RangesIterator it = ranges_.begin();
216 for (; it != et; ++it) {
217 if(it->contains(pos)) {
224 bool needsRefresh() const
226 return needs_refresh_;
229 SpellChecker::ChangeNumber currentChangeNumber() const
231 return current_change_number_;
234 void refreshRange(pos_type & first, pos_type & last) const
236 first = refresh_.first;
237 last = refresh_.last;
240 void needsRefresh(pos_type pos)
242 if (needs_refresh_ && pos != -1) {
243 if (pos < refresh_.first)
244 refresh_.first = pos;
245 if (pos > refresh_.last)
247 } else if (pos != -1) {
248 // init request check for neighbour positions too
249 refresh_.first = pos > 0 ? pos - 1 : 0;
250 // no need for special end of paragraph check
251 refresh_.last = pos + 1;
253 needs_refresh_ = pos != -1;
256 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
258 needs_refresh_ = true;
261 current_change_number_ = change_number;
264 typedef vector<SpellResultRange> Ranges;
265 typedef Ranges::const_iterator RangesIterator;
267 /// the area of the paragraph with pending spell check
269 /// spell state cache version number
270 SpellChecker::ChangeNumber current_change_number_;
274 void correctRangesAfterPos(pos_type pos, int offset)
276 RangesIterator et = ranges_.end();
277 Ranges::iterator it = ranges_.begin();
278 for (; it != et; ++it) {
279 it->shift(pos, offset);
285 /////////////////////////////////////////////////////////////////////
287 // Paragraph::Private
289 /////////////////////////////////////////////////////////////////////
291 class Paragraph::Private
293 // Enforce our own "copy" constructor
294 Private(Private const &) = delete;
295 Private & operator=(Private const &) = delete;
296 // Unique ID generator
297 static int make_id();
300 Private(Paragraph * owner, Layout const & layout);
301 /// "Copy constructor"
302 Private(Private const &, Paragraph * owner);
303 /// Copy constructor from \p beg to \p end
304 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
307 void insertChar(pos_type pos, char_type c, Change const & change);
309 /// Output the surrogate pair formed by \p c and \p next to \p os.
310 /// \return the number of characters written.
311 int latexSurrogatePair(BufferParams const &, otexstream & os,
312 char_type c, char_type next,
313 OutputParams const &);
315 /// Output a space in appropriate formatting (or a surrogate pair
316 /// if the next character is a combining character).
317 /// \return whether a surrogate pair was output.
318 bool simpleTeXBlanks(BufferParams const &,
319 OutputParams const &,
322 unsigned int & column,
324 Layout const & style);
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 string & alien_script,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column);
370 unsigned int & column);
376 unsigned int & column);
379 void validate(LaTeXFeatures & features) const;
381 /// Checks if the paragraph contains only text and no inset or font change.
382 bool onlyText(Buffer const & buf, Font const & outerfont,
383 pos_type initial) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD, true);
445 owner_->locateWord(last, endpos, WHOLE_WORD, true);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 long skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
483 ParagraphParameters params_;
485 /// for recording and looking up changes
489 InsetList insetlist_;
492 pos_type begin_of_body_;
494 typedef docstring TextContainer;
498 typedef set<docstring> Words;
499 typedef map<string, Words> LangWordsMap;
503 Layout const * layout_;
505 SpellCheckerState speller_state_;
511 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
512 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
519 int Paragraph::Private::make_id()
521 // The id is unique per session across buffers because it is used in
522 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
525 static int next_id(0);
530 Paragraph::Private::Private(Private const & p, Paragraph * owner)
531 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
532 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
533 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
534 layout_(p.layout_), id_(make_id())
536 requestSpellCheck(p.text_.size());
540 Paragraph::Private::Private(Private const & p, Paragraph * owner,
541 pos_type beg, pos_type end)
542 : owner_(owner), inset_owner_(p.inset_owner_),
543 params_(p.params_), changes_(p.changes_),
544 insetlist_(p.insetlist_, beg, end),
545 begin_of_body_(p.begin_of_body_), words_(p.words_),
546 layout_(p.layout_), id_(make_id())
548 if (beg >= pos_type(p.text_.size()))
550 text_ = p.text_.substr(beg, end - beg);
552 FontList::const_iterator fcit = fontlist_.begin();
553 FontList::const_iterator fend = fontlist_.end();
554 for (; fcit != fend; ++fcit) {
555 if (fcit->pos() < beg)
557 if (fcit->pos() >= end) {
558 // Add last entry in the fontlist_.
559 fontlist_.set(text_.size() - 1, fcit->font());
562 // Add a new entry in the fontlist_.
563 fontlist_.set(fcit->pos() - beg, fcit->font());
565 requestSpellCheck(p.text_.size());
569 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
570 bool output_active, TocBackend & backend) const
572 d->changes_.addToToc(cdit, buf, output_active, backend);
576 bool Paragraph::isDeleted(pos_type start, pos_type end) const
578 LASSERT(start >= 0 && start <= size(), return false);
579 LASSERT(end > start && end <= size() + 1, return false);
581 return d->changes_.isDeleted(start, end);
585 bool Paragraph::isChanged(pos_type start, pos_type end) const
587 LASSERT(start >= 0 && start <= size(), return false);
588 LASSERT(end > start && end <= size() + 1, return false);
590 return d->changes_.isChanged(start, end);
593 // FIXME: Ideally the diverse isChanged() methods should account for that!
594 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
596 LASSERT(start >= 0 && start <= size(), return false);
597 LASSERT(end > start && end <= size() + 1, return false);
599 for (auto const & icit : d->insetlist_) {
600 if (icit.pos < start)
604 if (icit.inset && icit.inset->isChanged())
610 bool Paragraph::isChanged() const
612 return d->changes_.isChanged();
616 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
618 // keep the logic here in sync with the logic of eraseChars()
622 Change const & change = d->changes_.lookup(size());
623 return change.inserted() && change.currentAuthor();
626 Change Paragraph::parEndChange() const
628 return d->changes_.lookup(size());
632 void Paragraph::setChange(Change const & change)
634 // beware of the imaginary end-of-par character!
635 d->changes_.set(change, 0, size() + 1);
638 * Propagate the change recursively - but not in case of DELETED!
640 * Imagine that your co-author makes changes in an existing inset. He
641 * sends your document to you and you come to the conclusion that the
642 * inset should go completely. If you erase it, LyX must not delete all
643 * text within the inset. Otherwise, the change tracked insertions of
644 * your co-author get lost and there is no way to restore them later.
646 * Conclusion: An inset's content should remain untouched if you delete it
649 if (!change.deleted()) {
650 for (pos_type pos = 0; pos < size(); ++pos) {
651 if (Inset * inset = getInset(pos))
652 inset->setChange(change);
658 void Paragraph::setChange(pos_type pos, Change const & change)
660 LASSERT(pos >= 0 && pos <= size(), return);
661 d->changes_.set(change, pos);
663 // see comment in setChange(Change const &) above
664 if (!change.deleted() && pos < size())
665 if (Inset * inset = getInset(pos))
666 inset->setChange(change);
670 Change const & Paragraph::lookupChange(pos_type pos) const
672 LBUFERR(pos >= 0 && pos <= size());
673 return d->changes_.lookup(pos);
677 void Paragraph::acceptChanges(pos_type start, pos_type end)
679 LASSERT(start >= 0 && start <= size(), return);
680 LASSERT(end > start && end <= size() + 1, return);
682 for (pos_type pos = start; pos < end; ++pos) {
683 switch (lookupChange(pos).type) {
684 case Change::UNCHANGED:
685 // accept changes in nested inset
686 if (Inset * inset = getInset(pos))
687 inset->acceptChanges();
690 case Change::INSERTED:
691 d->changes_.set(Change(Change::UNCHANGED), pos);
692 // also accept changes in nested inset
693 if (Inset * inset = getInset(pos))
694 inset->acceptChanges();
697 case Change::DELETED:
698 // Suppress access to non-existent
699 // "end-of-paragraph char"
701 eraseChar(pos, false);
712 void Paragraph::rejectChanges(pos_type start, pos_type end)
714 LASSERT(start >= 0 && start <= size(), return);
715 LASSERT(end > start && end <= size() + 1, return);
717 for (pos_type pos = start; pos < end; ++pos) {
718 switch (lookupChange(pos).type) {
719 case Change::UNCHANGED:
720 // reject changes in nested inset
721 if (Inset * inset = getInset(pos))
722 inset->rejectChanges();
725 case Change::INSERTED:
726 // Suppress access to non-existent
727 // "end-of-paragraph char"
729 eraseChar(pos, false);
735 case Change::DELETED:
736 d->changes_.set(Change(Change::UNCHANGED), pos);
738 // Do NOT reject changes within a deleted inset!
739 // There may be insertions of a co-author inside of it!
747 void Paragraph::Private::insertChar(pos_type pos, char_type c,
748 Change const & change)
750 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
753 changes_.insert(change, pos);
755 // This is actually very common when parsing buffers (and
756 // maybe inserting ascii text)
757 if (pos == pos_type(text_.size())) {
758 // when appending characters, no need to update tables
760 // but we want spell checking
761 requestSpellCheck(pos);
765 text_.insert(text_.begin() + pos, c);
767 // Update the font table.
768 fontlist_.increasePosAfterPos(pos);
771 insetlist_.increasePosAfterPos(pos);
773 // Update list of misspelled positions
774 speller_state_.increasePosAfterPos(pos);
778 bool Paragraph::insertInset(pos_type pos, Inset * inset,
779 Font const & font, Change const & change)
781 LASSERT(inset, return false);
782 LASSERT(pos >= 0 && pos <= size(), return false);
784 // Paragraph::insertInset() can be used in cut/copy/paste operation where
785 // d->inset_owner_ is not set yet.
786 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
789 d->insertChar(pos, META_INSET, change);
790 LASSERT(d->text_[pos] == META_INSET, return false);
792 // Add a new entry in the insetlist_.
793 d->insetlist_.insert(inset, pos);
795 // Some insets require run of spell checker
796 requestSpellCheck(pos);
802 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
804 LASSERT(pos >= 0 && pos <= size(), return false);
806 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
809 Change change = d->changes_.lookup(pos);
811 // set the character to DELETED if
812 // a) it was previously unchanged or
813 // b) it was inserted by a co-author
815 if (!change.changed() ||
816 (change.inserted() && !change.currentAuthor())) {
817 setChange(pos, Change(Change::DELETED));
818 // request run of spell checker
819 requestSpellCheck(pos);
823 if (change.deleted())
827 // Don't physically access the imaginary end-of-paragraph character.
828 // eraseChar() can only mark it as DELETED. A physical deletion of
829 // end-of-par must be handled externally.
835 d->changes_.erase(pos);
837 // if it is an inset, delete the inset entry
838 if (d->text_[pos] == META_INSET)
839 d->insetlist_.erase(pos);
841 d->text_.erase(d->text_.begin() + pos);
843 // Update the fontlist_
844 d->fontlist_.erase(pos);
846 // Update the insetlist_
847 d->insetlist_.decreasePosAfterPos(pos);
849 // Update list of misspelled positions
850 d->speller_state_.decreasePosAfterPos(pos);
851 d->speller_state_.refreshLast(size());
857 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
859 LASSERT(start >= 0 && start <= size(), return 0);
860 LASSERT(end >= start && end <= size() + 1, return 0);
863 for (pos_type count = end - start; count; --count) {
864 if (!eraseChar(i, trackChanges))
870 // Handle combining characters
871 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
872 otexstream & os, char_type c, char_type next,
873 OutputParams const & runparams)
875 // Writing next here may circumvent a possible font change between
876 // c and next. Since next is only output if it forms a surrogate pair
877 // with c we can ignore this:
878 // A font change inside a surrogate pair does not make sense and is
879 // hopefully impossible to input.
880 // FIXME: change tracking
881 // Is this correct WRT change tracking?
882 Encoding const & encoding = *(runparams.encoding);
883 docstring latex1 = encoding.latexChar(next).first;
884 if (runparams.inIPA) {
885 string const tipashortcut = Encodings::TIPAShortcut(next);
886 if (!tipashortcut.empty()) {
887 latex1 = from_ascii(tipashortcut);
890 docstring latex2 = encoding.latexChar(c).first;
892 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
893 // Encoding supports the combination:
894 // output as is (combining char after base char).
895 os << latex2 << latex1;
896 return latex1.length() + latex2.length();
899 os << latex1 << "{" << latex2 << "}";
900 return latex1.length() + latex2.length() + 2;
904 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
905 OutputParams const & runparams,
908 unsigned int & column,
910 Layout const & style)
912 if (style.pass_thru || runparams.pass_thru)
915 if (i + 1 < int(text_.size())) {
916 char_type next = text_[i + 1];
917 if (Encodings::isCombiningChar(next)) {
918 // This space has an accent, so we must always output it.
919 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
924 if (runparams.linelen > 0
925 && column > runparams.linelen
927 && text_[i - 1] != ' '
928 && (i + 1 < int(text_.size()))
929 // same in FreeSpacing mode
930 && !owner_->isFreeSpacing()
931 // In typewriter mode, we want to avoid
932 // ! . ? : at the end of a line
933 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
934 && (text_[i - 1] == '.'
935 || text_[i - 1] == '?'
936 || text_[i - 1] == ':'
937 || text_[i - 1] == '!'))) {
939 os.texrow().start(owner_->id(), i + 1);
941 } else if (style.free_spacing) {
950 void Paragraph::Private::latexInset(BufferParams const & bparams,
952 OutputParams & runparams,
955 Font const & outerfont,
957 Change & running_change,
958 Layout const & style,
960 unsigned int & column)
962 Inset * inset = owner_->getInset(i);
965 if (style.pass_thru) {
966 odocstringstream ods;
967 inset->plaintext(ods, runparams);
972 // FIXME: move this to InsetNewline::latex
973 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
974 // newlines are handled differently here than
975 // the default in simpleTeXSpecialChars().
976 if (!style.newline_allowed) {
980 bool needPar = false;
981 column += running_font.latexWriteEndChanges(
982 os, bparams, runparams,
983 basefont, basefont, needPar);
987 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
990 basefont = owner_->getLayoutFont(bparams, outerfont);
991 running_font = basefont;
993 if (runparams.moving_arg)
997 os.texrow().start(owner_->id(), i + 1);
1001 if (owner_->isDeleted(i)) {
1002 if( ++runparams.inDeletedInset == 1)
1003 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1006 if (inset->canTrackChanges()) {
1007 column += Changes::latexMarkChange(os, bparams, running_change,
1008 Change(Change::UNCHANGED), runparams);
1009 running_change = Change(Change::UNCHANGED);
1013 odocstream::pos_type const len = os.os().tellp();
1015 if (inset->forceLTR(runparams)
1016 && running_font.isRightToLeft()
1017 // ERT is an exception, it should be output with no
1018 // decorations at all
1019 && inset->lyxCode() != ERT_CODE) {
1020 if (runparams.use_polyglossia) {
1022 } else if (running_font.language()->lang() == "farsi"
1023 || running_font.language()->lang() == "arabic_arabi")
1024 os << "\\textLR{" << termcmd;
1030 // FIXME: Bug: we can have an empty font change here!
1031 // if there has just been a font change, we are going to close it
1032 // right now, which means stupid latex code like \textsf{}. AFAIK,
1033 // this does not harm dvi output. A minor bug, thus (JMarc)
1035 // Some insets cannot be inside a font change command.
1036 // However, even such insets *can* be placed in \L or \R
1037 // or their equivalents (for RTL language switches), so we don't
1038 // close the language in those cases.
1039 // ArabTeX, though, cannot handle this special behavior, it seems.
1040 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1041 || running_font.language()->lang() == "arabic_arabtex";
1042 if (open_font && !inset->inheritFont()) {
1043 bool needPar = false;
1044 bool closeLanguage = arabtex
1045 || basefont.isRightToLeft() == running_font.isRightToLeft();
1046 // We pass non_inherit_inset = true here since size switches
1047 // ought not to be terminated here (#8384).
1048 unsigned int count = running_font.latexWriteEndChanges(os,
1049 bparams, runparams, basefont, basefont,
1050 needPar, closeLanguage, true);
1052 // if any font properties were closed, update the running_font,
1053 // making sure, however, to leave the language as it was
1055 // FIXME: probably a better way to keep track of the old
1056 // language, than copying the entire font?
1057 Font const copy_font(running_font);
1058 basefont = owner_->getLayoutFont(bparams, outerfont);
1059 running_font = basefont;
1061 running_font.setLanguage(copy_font.language());
1062 // For these, we use switches, so no need to close
1063 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1064 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1065 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1066 // leave font open if language or any of the switches is still open
1067 open_font = (running_font.language() == basefont.language()
1068 || running_font.fontInfo().size() == basefont.fontInfo().size()
1069 || running_font.fontInfo().family() == basefont.fontInfo().family()
1070 || running_font.fontInfo().series() == basefont.fontInfo().series());
1072 runparams.local_font = &basefont;
1076 size_t const previous_row_count = os.texrow().rows();
1079 runparams.lastid = id_;
1080 runparams.lastpos = i;
1081 inset->latex(os, runparams);
1082 } catch (EncodingException & e) {
1083 // add location information and throw again.
1092 if (os.texrow().rows() > previous_row_count) {
1093 os.texrow().start(owner_->id(), i + 1);
1096 column += (unsigned int)(os.os().tellp() - len);
1099 if (owner_->isDeleted(i))
1100 --runparams.inDeletedInset;
1104 void Paragraph::Private::latexSpecialChar(otexstream & os,
1105 BufferParams const & bparams,
1106 OutputParams const & runparams,
1107 Font const & running_font,
1108 string & alien_script,
1109 Layout const & style,
1112 unsigned int & column)
1114 char_type const c = owner_->getUChar(bparams, runparams, i);
1116 if (style.pass_thru || runparams.pass_thru
1117 || contains(style.pass_thru_chars, c)
1118 || contains(runparams.pass_thru_chars, c)) {
1120 Encoding const * const enc = runparams.encoding;
1121 if (enc && !enc->encodable(c))
1122 throw EncodingException(c);
1128 // TIPA uses its own T3 encoding
1129 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1131 // If T1 font encoding is used, use the special
1132 // characters it provides.
1133 // NOTE: Some languages reset the font encoding internally to a
1134 // non-standard font encoding. If we are using such a language,
1135 // we do not output special T1 chars.
1136 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1137 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1138 && latexSpecialT1(c, os, i, column))
1140 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1141 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1142 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1145 // Otherwise, we use what LaTeX provides us.
1148 os << "\\textbackslash" << termcmd;
1152 os << "\\textless" << termcmd;
1156 os << "\\textgreater" << termcmd;
1160 os << "\\textbar" << termcmd;
1165 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1166 (end_pos == -1 || i + 1 < end_pos) &&
1167 text_[i+1] == '-') {
1168 // Prevent "--" becoming an en dash and "---" an em dash.
1169 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1175 os << "\\textquotedbl" << termcmd;
1180 case '%': case '#': case '{':
1188 os << "\\textasciitilde" << termcmd;
1193 os << "\\textasciicircum" << termcmd;
1200 // avoid being mistaken for optional arguments
1208 // Blanks are printed before font switching.
1209 // Sure? I am not! (try nice-latex)
1210 // I am sure it's correct. LyX might be smarter
1211 // in the future, but for now, nothing wrong is
1217 // XeTeX's dash behaviour is determined via a global setting
1218 if (bparams.use_dash_ligatures
1219 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1221 // TODO #10961: && not in inset Flex Code
1222 // TODO #10961: && not in layout LyXCode
1223 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1240 Encoding const & encoding = *(runparams.encoding);
1241 char_type next = '\0';
1242 if (i + 1 < int(text_.size())) {
1243 next = text_[i + 1];
1244 if (Encodings::isCombiningChar(next)) {
1245 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1250 pair<docstring, bool> latex = encoding.latexChar(c);
1251 docstring nextlatex;
1252 bool nexttipas = false;
1253 string nexttipashortcut;
1254 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1255 nextlatex = encoding.latexChar(next).first;
1256 if (runparams.inIPA) {
1257 nexttipashortcut = Encodings::TIPAShortcut(next);
1258 nexttipas = !nexttipashortcut.empty();
1262 if (runparams.inIPA) {
1263 string const tipashortcut = Encodings::TIPAShortcut(c);
1264 if (!tipashortcut.empty()) {
1265 latex.first = from_ascii(tipashortcut);
1266 latex.second = false;
1270 // eventually close "script wrapper" command (see `Paragraph::latex`)
1271 if (!alien_script.empty()
1272 && alien_script != Encodings::isKnownScriptChar(next)) {
1273 column += latex.first.length();
1274 alien_script.clear();
1275 os << latex.first << "}";
1279 && ((!prefixIs(nextlatex, '\\')
1280 && !prefixIs(nextlatex, '{')
1281 && !prefixIs(nextlatex, '}'))
1283 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1285 // Prevent eating of a following space or command corruption by
1286 // following characters
1287 if (next == ' ' || next == '\0') {
1288 column += latex.first.length() + 1;
1289 os << latex.first << "{}";
1291 column += latex.first.length();
1292 os << latex.first << " ";
1295 column += latex.first.length() - 1;
1303 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1304 pos_type i, unsigned int & column)
1310 // In T1 encoding, these characters exist
1311 // but we should avoid ligatures
1312 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1314 os << "\\textcompwordmark" << termcmd;
1321 // soul.sty breaks with \char`\"
1322 os << "\\textquotedbl" << termcmd;
1331 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1332 pos_type i, unsigned int & column)
1334 // TU encoding is currently on par with T1.
1335 return latexSpecialT1(c, os, i, column);
1339 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1340 pos_type /*i*/, unsigned int & column)
1350 os << "\\textvertline" << termcmd;
1359 void Paragraph::Private::validate(LaTeXFeatures & features) const
1361 if (layout_->inpreamble && inset_owner_) {
1362 // FIXME: Using a string stream here circumvents the encoding
1363 // switching machinery of odocstream. Therefore the
1364 // output is wrong if this paragraph contains content
1365 // that needs to switch encoding.
1366 Buffer const & buf = inset_owner_->buffer();
1367 otexstringstream os;
1368 os << layout_->preamble();
1369 size_t const length = os.length();
1370 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1371 buf.getParFromID(owner_->id()).pit(), os,
1372 features.runparams(), string(), 0, -1, true);
1373 if (os.length() > length)
1374 features.addPreambleSnippet(os.release(), true);
1377 if (features.runparams().flavor == OutputParams::HTML
1378 && layout_->htmltitle()) {
1379 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1382 // check the params.
1383 if (!params_.spacing().isDefault())
1384 features.require("setspace");
1387 features.useLayout(layout_->name());
1390 fontlist_.validate(features);
1392 // then the indentation
1393 if (!params_.leftIndent().zero())
1394 features.require("ParagraphLeftIndent");
1397 InsetList::const_iterator icit = insetlist_.begin();
1398 InsetList::const_iterator iend = insetlist_.end();
1399 for (; icit != iend; ++icit) {
1401 features.inDeletedInset(owner_->isDeleted(icit->pos));
1402 if (icit->inset->lyxCode() == FOOT_CODE) {
1403 // FIXME: an item inset would make things much easier.
1404 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1405 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1406 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1407 && (icit->pos < begin_of_body_
1408 || (icit->pos == begin_of_body_
1409 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1410 features.saveNoteEnv("description");
1412 icit->inset->validate(features);
1413 features.inDeletedInset(false);
1414 if (layout_->needprotect &&
1415 icit->inset->lyxCode() == FOOT_CODE)
1416 features.require("NeedLyXFootnoteCode");
1420 // then the contents
1421 BufferParams const bp = features.runparams().is_child
1422 ? features.buffer().masterParams() : features.buffer().params();
1423 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1424 char_type c = text_[i];
1425 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1427 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1428 features.require("textquotedblp");
1429 else if (bp.main_font_encoding() != "T1"
1430 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1431 features.require("textquotedbl");
1432 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1433 // features that depend on the font or input encoding
1434 string feats = ci.textpreamble();
1435 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1436 if (fontenc.empty())
1437 fontenc = features.runparams().main_fontenc;
1438 while (!feats.empty()) {
1440 feats = split(feats, feat, ',');
1441 if (contains(feat, "!=")) {
1442 // a feature that is required except for the spcified
1443 // font or input encodings
1445 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1446 // multiple encodings are separated by semicolon
1447 vector<string> context = getVectorFromString(contexts, ";");
1448 // require feature if the context matches neither current font
1449 // nor input encoding
1450 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1451 && std::find(context.begin(), context.end(),
1452 features.runparams().encoding->name()) == context.end())
1453 features.require(realfeature);
1454 } else if (contains(feat, '=')) {
1455 // a feature that is required only for the spcified
1456 // font or input encodings
1458 string const contexts = split(feat, realfeature, '=');
1459 // multiple encodings are separated by semicolon
1460 vector<string> context = getVectorFromString(contexts, ";");
1461 // require feature if the context matches either current font
1462 // or input encoding
1463 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1464 || std::find(context.begin(), context.end(),
1465 features.runparams().encoding->name()) != context.end())
1466 features.require(realfeature);
1469 } else if (!bp.use_dash_ligatures
1470 && (c == 0x2013 || c == 0x2014)
1471 && bp.useNonTeXFonts
1472 && features.runparams().flavor == OutputParams::XETEX)
1473 // XeTeX's dash behaviour is determined via a global setting
1474 features.require("xetexdashbreakstate");
1475 BufferEncodings::validate(c, features);
1479 /////////////////////////////////////////////////////////////////////
1483 /////////////////////////////////////////////////////////////////////
1486 Layout const emptyParagraphLayout;
1489 Paragraph::Paragraph()
1490 : d(new Paragraph::Private(this, emptyParagraphLayout))
1497 Paragraph::Paragraph(Paragraph const & par)
1498 : itemdepth(par.itemdepth),
1499 d(new Paragraph::Private(*par.d, this))
1505 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1506 : itemdepth(par.itemdepth),
1507 d(new Paragraph::Private(*par.d, this, beg, end))
1513 Paragraph & Paragraph::operator=(Paragraph const & par)
1515 // needed as we will destroy the private part before copying it
1517 itemdepth = par.itemdepth;
1521 d = new Private(*par.d, this);
1528 Paragraph::~Paragraph()
1537 // this shall be called just before every "os << ..." action.
1538 void flushString(ostream & os, docstring & s)
1547 void Paragraph::write(ostream & os, BufferParams const & bparams,
1548 depth_type & dth) const
1550 // The beginning or end of a deeper (i.e. nested) area?
1551 if (dth != d->params_.depth()) {
1552 if (d->params_.depth() > dth) {
1553 while (d->params_.depth() > dth) {
1554 os << "\n\\begin_deeper";
1558 while (d->params_.depth() < dth) {
1559 os << "\n\\end_deeper";
1565 // First write the layout
1566 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1568 d->params_.write(os);
1570 Font font1(inherit_font, bparams.language);
1572 Change running_change = Change(Change::UNCHANGED);
1574 // this string is used as a buffer to avoid repetitive calls
1575 // to to_utf8(), which turn out to be expensive (JMarc)
1576 docstring write_buffer;
1579 for (pos_type i = 0; i <= size(); ++i) {
1581 Change const & change = lookupChange(i);
1582 if (change != running_change)
1583 flushString(os, write_buffer);
1584 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1585 running_change = change;
1590 // Write font changes
1591 Font font2 = getFontSettings(bparams, i);
1592 if (font2 != font1) {
1593 flushString(os, write_buffer);
1594 font2.lyxWriteChanges(font1, os);
1599 char_type const c = d->text_[i];
1602 if (Inset const * inset = getInset(i)) {
1603 flushString(os, write_buffer);
1604 if (inset->directWrite()) {
1605 // international char, let it write
1606 // code directly so it's shorter in
1612 os << "\\begin_inset ";
1614 os << "\n\\end_inset\n\n";
1617 // FIXME This can be removed again once the mystery
1618 // crash has been resolved.
1623 flushString(os, write_buffer);
1624 os << "\n\\backslash\n";
1628 flushString(os, write_buffer);
1629 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1636 if ((column > 70 && c == ' ')
1638 flushString(os, write_buffer);
1642 // this check is to amend a bug. LyX sometimes
1643 // inserts '\0' this could cause problems.
1645 write_buffer.push_back(c);
1647 LYXERR0("NUL char in structure.");
1653 flushString(os, write_buffer);
1654 os << "\n\\end_layout\n";
1655 // FIXME This can be removed again once the mystery
1656 // crash has been resolved.
1661 void Paragraph::validate(LaTeXFeatures & features) const
1663 d->validate(features);
1664 bool fragile = features.runparams().moving_arg;
1665 fragile |= layout().needprotect;
1666 if (inInset().getLayout().isNeedProtect())
1668 if (needsCProtection(fragile))
1669 features.require("cprotect");
1673 void Paragraph::insert(pos_type start, docstring const & str,
1674 Font const & font, Change const & change)
1676 for (size_t i = 0, n = str.size(); i != n ; ++i)
1677 insertChar(start + i, str[i], font, change);
1681 void Paragraph::appendChar(char_type c, Font const & font,
1682 Change const & change)
1685 d->changes_.insert(change, d->text_.size());
1686 // when appending characters, no need to update tables
1687 d->text_.push_back(c);
1688 setFont(d->text_.size() - 1, font);
1689 d->requestSpellCheck(d->text_.size() - 1);
1693 void Paragraph::appendString(docstring const & s, Font const & font,
1694 Change const & change)
1696 pos_type end = s.size();
1697 size_t oldsize = d->text_.size();
1698 size_t newsize = oldsize + end;
1699 size_t capacity = d->text_.capacity();
1700 if (newsize >= capacity)
1701 d->text_.reserve(max(capacity + 100, newsize));
1703 // when appending characters, no need to update tables
1706 // FIXME: Optimize this!
1707 for (size_t i = oldsize; i != newsize; ++i) {
1709 d->changes_.insert(change, i);
1710 d->requestSpellCheck(i);
1712 d->fontlist_.set(oldsize, font);
1713 d->fontlist_.set(newsize - 1, font);
1717 void Paragraph::insertChar(pos_type pos, char_type c,
1720 d->insertChar(pos, c, Change(trackChanges ?
1721 Change::INSERTED : Change::UNCHANGED));
1725 void Paragraph::insertChar(pos_type pos, char_type c,
1726 Font const & font, bool trackChanges)
1728 d->insertChar(pos, c, Change(trackChanges ?
1729 Change::INSERTED : Change::UNCHANGED));
1734 void Paragraph::insertChar(pos_type pos, char_type c,
1735 Font const & font, Change const & change)
1737 d->insertChar(pos, c, change);
1742 void Paragraph::resetFonts(Font const & font)
1744 d->fontlist_.clear();
1745 d->fontlist_.set(0, font);
1746 d->fontlist_.set(d->text_.size() - 1, font);
1749 // Gets uninstantiated font setting at position.
1750 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1754 LYXERR0("pos: " << pos << " size: " << size());
1758 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1759 if (cit != d->fontlist_.end())
1762 if (pos == size() && !empty())
1763 return getFontSettings(bparams, pos - 1);
1765 // Optimisation: avoid a full font instantiation if there is no
1766 // language change from previous call.
1767 static Font previous_font;
1768 static Language const * previous_lang = nullptr;
1769 Language const * lang = getParLanguage(bparams);
1770 if (lang != previous_lang) {
1771 previous_lang = lang;
1772 previous_font = Font(inherit_font, lang);
1774 return previous_font;
1778 FontSpan Paragraph::fontSpan(pos_type pos) const
1780 LBUFERR(pos <= size());
1783 return FontSpan(pos, pos);
1786 FontList::const_iterator cit = d->fontlist_.begin();
1787 FontList::const_iterator end = d->fontlist_.end();
1788 for (; cit != end; ++cit) {
1789 if (cit->pos() >= pos) {
1790 if (pos >= beginOfBody())
1791 return FontSpan(max(start, beginOfBody()),
1794 return FontSpan(start,
1795 min(beginOfBody() - 1,
1798 start = cit->pos() + 1;
1801 // This should not happen, but if so, we take no chances.
1802 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1803 LASSERT(false, return FontSpan(pos, pos));
1807 // Gets uninstantiated font setting at position 0
1808 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1810 if (!empty() && !d->fontlist_.empty())
1811 return d->fontlist_.begin()->font();
1813 // Optimisation: avoid a full font instantiation if there is no
1814 // language change from previous call.
1815 static Font previous_font;
1816 static Language const * previous_lang = nullptr;
1817 if (bparams.language != previous_lang) {
1818 previous_lang = bparams.language;
1819 previous_font = Font(inherit_font, bparams.language);
1822 return previous_font;
1826 // Gets the fully instantiated font at a given position in a paragraph
1827 // This is basically the same function as Text::GetFont() in text2.cpp.
1828 // The difference is that this one is used for generating the LaTeX file,
1829 // and thus cosmetic "improvements" are disallowed: This has to deliver
1830 // the true picture of the buffer. (Asger)
1831 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1832 Font const & outerfont) const
1836 Font font = getFontSettings(bparams, pos);
1838 pos_type const body_pos = beginOfBody();
1839 FontInfo & fi = font.fontInfo();
1841 fi.realize(d->layout_->labelfont);
1843 fi.realize(d->layout_->font);
1845 fi.realize(outerfont.fontInfo());
1846 fi.realize(bparams.getFont().fontInfo());
1852 Font const Paragraph::getLabelFont
1853 (BufferParams const & bparams, Font const & outerfont) const
1855 FontInfo tmpfont = d->layout_->labelfont;
1856 tmpfont.realize(outerfont.fontInfo());
1857 tmpfont.realize(bparams.getFont().fontInfo());
1858 return Font(tmpfont, getParLanguage(bparams));
1862 Font const Paragraph::getLayoutFont
1863 (BufferParams const & bparams, Font const & outerfont) const
1865 FontInfo tmpfont = d->layout_->font;
1866 tmpfont.realize(outerfont.fontInfo());
1867 tmpfont.realize(bparams.getFont().fontInfo());
1868 return Font(tmpfont, getParLanguage(bparams));
1872 char_type Paragraph::getUChar(BufferParams const & bparams,
1873 OutputParams const & rp,
1876 char_type c = d->text_[pos];
1878 // Return unchanged character in LTR languages
1879 // or if we use poylglossia/bidi (XeTeX).
1880 if (rp.useBidiPackage()
1881 || !getFontSettings(bparams, pos).isRightToLeft())
1884 // Without polyglossia/bidi, we need to account for some special cases.
1885 // FIXME This needs to be audited!
1887 // * The input is as expected for all delimiters
1888 // => checked for Hebrew!
1889 // * The output matches the display in the LyX workarea
1890 // => checked for Hebrew!
1891 // * The special cases below are really necessary
1892 // => checked for Hebrew!
1893 // * In arabic_arabi, brackets are transformed to Arabic
1894 // Ornate Parentheses. Is this is really wanted?
1896 string const & lang = getFontSettings(bparams, pos).language()->lang();
1899 // 1. In the following languages, parentheses need to be reversed.
1900 // Also with polyglodia/luabidi
1901 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1903 // 2. In the following languages, brackets don't need to be reversed.
1904 bool const reversebrackets = lang != "arabic_arabtex"
1905 && lang != "arabic_arabi"
1908 // Now swap delimiters if needed.
1919 if (reversebrackets)
1923 if (reversebrackets)
1944 void Paragraph::setFont(pos_type pos, Font const & font)
1946 LASSERT(pos <= size(), return);
1948 // First, reduce font against layout/label font
1949 // Update: The setCharFont() routine in text2.cpp already
1950 // reduces font, so we don't need to do that here. (Asger)
1952 d->fontlist_.set(pos, font);
1956 void Paragraph::makeSameLayout(Paragraph const & par)
1958 d->layout_ = par.d->layout_;
1959 d->params_ = par.d->params_;
1963 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1965 if (isFreeSpacing())
1971 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1972 if (eraseChar(pos, trackChanges))
1978 return count > 0 || pos > 0;
1982 bool Paragraph::hasSameLayout(Paragraph const & par) const
1984 return par.d->layout_ == d->layout_
1985 && d->params_.sameLayout(par.d->params_);
1989 depth_type Paragraph::getDepth() const
1991 return d->params_.depth();
1995 depth_type Paragraph::getMaxDepthAfter() const
1997 if (d->layout_->isEnvironment())
1998 return d->params_.depth() + 1;
2000 return d->params_.depth();
2004 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2006 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2007 return getDefaultAlign(bparams);
2009 return d->params_.align();
2013 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2015 LyXAlignment res = layout().align;
2016 if (isRTL(bparams)) {
2018 if (res == LYX_ALIGN_LEFT)
2019 res = LYX_ALIGN_RIGHT;
2020 else if (res == LYX_ALIGN_RIGHT)
2021 res = LYX_ALIGN_LEFT;
2027 docstring const & Paragraph::labelString() const
2029 return d->params_.labelString();
2033 // the next two functions are for the manual labels
2034 docstring const Paragraph::getLabelWidthString() const
2036 if (d->layout_->margintype == MARGIN_MANUAL
2037 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2038 return d->params_.labelWidthString();
2040 return _("Senseless with this layout!");
2044 void Paragraph::setLabelWidthString(docstring const & s)
2046 d->params_.labelWidthString(s);
2050 docstring Paragraph::expandLabel(Layout const & layout,
2051 BufferParams const & bparams) const
2053 return expandParagraphLabel(layout, bparams, true);
2057 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2058 BufferParams const & bparams, bool process_appendix) const
2060 DocumentClass const & tclass = bparams.documentClass();
2061 string const & lang = getParLanguage(bparams)->code();
2062 bool const in_appendix = process_appendix && d->params_.appendix();
2063 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2065 if (fmt.empty() && !layout.counter.empty())
2066 return tclass.counters().theCounter(layout.counter, lang);
2068 // handle 'inherited level parts' in 'fmt',
2069 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2070 size_t const i = fmt.find('@', 0);
2071 if (i != docstring::npos) {
2072 size_t const j = fmt.find('@', i + 1);
2073 if (j != docstring::npos) {
2074 docstring parent(fmt, i + 1, j - i - 1);
2075 docstring label = from_ascii("??");
2076 if (tclass.hasLayout(parent))
2077 label = expandParagraphLabel(tclass[parent], bparams,
2079 fmt = docstring(fmt, 0, i) + label
2080 + docstring(fmt, j + 1, docstring::npos);
2084 return tclass.counters().counterLabel(fmt, lang);
2088 void Paragraph::applyLayout(Layout const & new_layout)
2090 d->layout_ = &new_layout;
2091 LyXAlignment const oldAlign = d->params_.align();
2093 if (!(oldAlign & d->layout_->alignpossible)) {
2094 frontend::Alert::warning(_("Alignment not permitted"),
2095 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2096 d->params_.align(LYX_ALIGN_LAYOUT);
2101 pos_type Paragraph::beginOfBody() const
2103 return d->begin_of_body_;
2107 void Paragraph::setBeginOfBody()
2109 if (d->layout_->labeltype != LABEL_MANUAL) {
2110 d->begin_of_body_ = 0;
2114 // Unroll the first two cycles of the loop
2115 // and remember the previous character to
2116 // remove unnecessary getChar() calls
2118 pos_type end = size();
2119 bool prev_char_deleted = false;
2120 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2123 char_type previous_char = d->text_[i];
2124 if (!(isNewline(i) || isEnvSeparator(i))) {
2126 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2127 char_type temp = d->text_[i];
2128 prev_char_deleted = isDeleted(i);
2129 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2132 previous_char = temp;
2138 d->begin_of_body_ = i;
2142 bool Paragraph::allowParagraphCustomization() const
2144 return inInset().allowParagraphCustomization();
2148 bool Paragraph::usePlainLayout() const
2150 return inInset().usePlainLayout();
2154 bool Paragraph::isPassThru() const
2156 return inInset().isPassThru() || d->layout_->pass_thru;
2161 // paragraphs inside floats need different alignment tags to avoid
2164 bool noTrivlistCentering(InsetCode code)
2166 return code == FLOAT_CODE
2167 || code == WRAP_CODE
2168 || code == CELL_CODE;
2172 string correction(string const & orig)
2174 if (orig == "flushleft")
2175 return "raggedright";
2176 if (orig == "flushright")
2177 return "raggedleft";
2178 if (orig == "center")
2184 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2185 InsetCode code, bool const lastpar, int & col)
2187 string macro = suffix + "{";
2188 if (noTrivlistCentering(code)) {
2190 // the last paragraph in non-trivlist-aligned
2191 // context is special (to avoid unwanted whitespace)
2192 if (suffix == "\\begin") {
2193 macro = "\\" + correction(env) + "{}";
2194 os << from_ascii(macro);
2195 col += macro.size();
2200 macro += correction(env);
2204 if (suffix == "\\par\\end") {
2208 os << from_ascii(macro);
2209 col += macro.size();
2210 if (suffix == "\\begin") {
2220 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2221 otexstream & os, OutputParams const & runparams) const
2226 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2227 (layout_->toggle_indent != ITOGGLE_NEVER) :
2228 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2230 if (canindent && params_.noindent() && !layout_->pass_thru) {
2231 os << "\\noindent ";
2235 LyXAlignment const curAlign = params_.align();
2237 if (curAlign == layout_->align)
2241 case LYX_ALIGN_NONE:
2242 case LYX_ALIGN_BLOCK:
2243 case LYX_ALIGN_LAYOUT:
2244 case LYX_ALIGN_SPECIAL:
2245 case LYX_ALIGN_DECIMAL:
2247 case LYX_ALIGN_LEFT:
2248 case LYX_ALIGN_RIGHT:
2249 case LYX_ALIGN_CENTER:
2250 if (runparams.moving_arg) {
2257 string const begin_tag = "\\begin";
2258 InsetCode code = ownerCode();
2259 bool const lastpar = runparams.isLastPar;
2260 // RTL in classic (PDF)LaTeX (without the Bidi package)
2261 // Luabibdi (used by LuaTeX) behaves like classic
2262 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2263 && !runparams.useBidiPackage();
2266 case LYX_ALIGN_NONE:
2267 case LYX_ALIGN_BLOCK:
2268 case LYX_ALIGN_LAYOUT:
2269 case LYX_ALIGN_SPECIAL:
2270 case LYX_ALIGN_DECIMAL:
2272 case LYX_ALIGN_LEFT: {
2274 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2275 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2277 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2279 } case LYX_ALIGN_RIGHT: {
2281 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2282 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2284 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2286 } case LYX_ALIGN_CENTER: {
2287 corrected_env(os, begin_tag, "center", code, lastpar, column);
2296 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2297 otexstream & os, OutputParams const & runparams) const
2299 LyXAlignment const curAlign = params_.align();
2301 if (curAlign == layout_->align)
2305 case LYX_ALIGN_NONE:
2306 case LYX_ALIGN_BLOCK:
2307 case LYX_ALIGN_LAYOUT:
2308 case LYX_ALIGN_SPECIAL:
2309 case LYX_ALIGN_DECIMAL:
2311 case LYX_ALIGN_LEFT:
2312 case LYX_ALIGN_RIGHT:
2313 case LYX_ALIGN_CENTER:
2314 if (runparams.moving_arg)
2319 bool output = false;
2321 string const end_tag = "\\par\\end";
2322 InsetCode code = ownerCode();
2323 bool const lastpar = runparams.isLastPar;
2324 // RTL in classic (PDF)LaTeX (without the Bidi package)
2325 // Luabibdi (used by LuaTeX) behaves like classic
2326 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2327 && !runparams.useBidiPackage();
2330 case LYX_ALIGN_NONE:
2331 case LYX_ALIGN_BLOCK:
2332 case LYX_ALIGN_LAYOUT:
2333 case LYX_ALIGN_SPECIAL:
2334 case LYX_ALIGN_DECIMAL:
2336 case LYX_ALIGN_LEFT: {
2338 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2339 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2341 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2343 } case LYX_ALIGN_RIGHT: {
2345 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2346 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2348 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2350 } case LYX_ALIGN_CENTER: {
2351 corrected_env(os, end_tag, "center", code, lastpar, col);
2356 return output || lastpar;
2360 // This one spits out the text of the paragraph
2361 void Paragraph::latex(BufferParams const & bparams,
2362 Font const & outerfont,
2364 OutputParams const & runparams,
2365 int start_pos, int end_pos, bool force) const
2367 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2369 // FIXME This check should not be needed. Perhaps issue an
2370 // error if it triggers.
2371 Layout const & style = inInset().forcePlainLayout() ?
2372 bparams.documentClass().plainLayout() : *d->layout_;
2374 if (!force && style.inpreamble)
2377 bool const allowcust = allowParagraphCustomization();
2379 // Current base font for all inherited font changes, without any
2380 // change caused by an individual character, except for the language:
2381 // It is set to the language of the first character.
2382 // As long as we are in the label, this font is the base font of the
2383 // label. Before the first body character it is set to the base font
2387 // If there is an open font-encoding changing command (script wrapper),
2388 // alien_script is set to its name
2389 string alien_script;
2392 // Maybe we have to create a optional argument.
2393 pos_type body_pos = beginOfBody();
2394 unsigned int column = 0;
2396 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2397 Font const real_outerfont = (!inInset().inheritFont()
2398 && runparams.local_font != nullptr)
2399 ? Font(runparams.local_font->fontInfo()) : outerfont;
2402 // the optional argument is kept in curly brackets in
2403 // case it contains a ']'
2404 // This is not strictly needed, but if this is changed it
2405 // would be a file format change, and tex2lyx would need
2406 // to be adjusted, since it unconditionally removes the
2407 // braces when it parses \item.
2410 basefont = getLabelFont(bparams, real_outerfont);
2412 basefont = getLayoutFont(bparams, real_outerfont);
2415 // Which font is currently active?
2416 Font running_font(basefont);
2417 // Do we have an open font change?
2418 bool open_font = false;
2420 Change runningChange = Change(Change::UNCHANGED);
2422 Encoding const * const prev_encoding = runparams.encoding;
2424 os.texrow().start(id(), 0);
2426 // if the paragraph is empty, the loop will not be entered at all
2428 // For InTitle commands, we have already opened a group
2429 // in output_latex::TeXOnePar.
2430 if (style.isCommand() && !style.intitle) {
2434 if (!style.leftdelim().empty()) {
2435 os << style.leftdelim();
2436 column += style.leftdelim().size();
2439 column += d->startTeXParParams(bparams, os, runparams);
2442 // Whether a \par can be issued for insets typeset inline with text.
2443 // Yes if greater than 0. This has to be static.
2444 THREAD_LOCAL_STATIC int parInline = 0;
2446 for (pos_type i = 0; i < size(); ++i) {
2447 // First char in paragraph or after label?
2448 if (i == body_pos) {
2451 bool needPar = false;
2452 column += running_font.latexWriteEndChanges(
2453 os, bparams, runparams,
2454 basefont, basefont, needPar);
2457 basefont = getLayoutFont(bparams, real_outerfont);
2458 running_font = basefont;
2460 column += Changes::latexMarkChange(os, bparams,
2461 runningChange, Change(Change::UNCHANGED),
2463 runningChange = Change(Change::UNCHANGED);
2468 // For InTitle commands, we have already opened a group
2469 // in output_latex::TeXOnePar.
2470 if (style.isCommand() && !style.intitle) {
2475 if (!style.leftdelim().empty()) {
2476 os << style.leftdelim();
2477 column += style.leftdelim().size();
2481 column += d->startTeXParParams(bparams, os,
2485 runparams.wasDisplayMath = runparams.inDisplayMath;
2486 runparams.inDisplayMath = false;
2487 bool deleted_display_math = false;
2488 Change const & change = runparams.inDeletedInset
2489 ? runparams.changeOfDeletedInset : lookupChange(i);
2491 char_type const c = d->text_[i];
2493 // Check whether a display math inset follows
2495 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2497 runparams.ctObject = getInset(i)->CtObject(runparams);
2499 InsetMath const * im = getInset(i)->asInsetMath();
2500 if (im && im->asHullInset()
2501 && im->asHullInset()->outerDisplay()) {
2502 runparams.inDisplayMath = true;
2503 // runparams.inDeletedInset will be set by
2504 // latexInset later, but we need this info
2505 // before it is called. On the other hand, we
2506 // cannot set it here because it is a counter.
2507 deleted_display_math = isDeleted(i);
2509 if (bparams.output_changes && deleted_display_math
2510 && runningChange == change
2511 && change.type == Change::DELETED
2512 && !os.afterParbreak()) {
2513 // A display math in the same paragraph follows.
2514 // We have to close and then reopen \lyxdeleted,
2515 // otherwise the math will be shifted up.
2516 OutputParams rp = runparams;
2518 bool needPar = false;
2519 column += running_font.latexWriteEndChanges(
2520 os, bparams, rp, basefont,
2524 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2525 : getLayoutFont(bparams, real_outerfont);
2526 running_font = basefont;
2527 column += Changes::latexMarkChange(os, bparams,
2528 Change(Change::INSERTED), change, rp);
2532 if (bparams.output_changes && runningChange != change) {
2533 if (!alien_script.empty()) {
2536 alien_script.clear();
2539 bool needPar = false;
2540 column += running_font.latexWriteEndChanges(
2541 os, bparams, runparams,
2542 basefont, basefont, needPar);
2545 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2546 : getLayoutFont(bparams, real_outerfont);
2547 running_font = basefont;
2548 column += Changes::latexMarkChange(os, bparams, runningChange,
2550 runningChange = change;
2553 // do not output text which is marked deleted
2554 // if change tracking output is disabled
2555 if (!bparams.output_changes && change.deleted()) {
2561 // Fully instantiated font
2562 Font const current_font = getFont(bparams, i, outerfont);
2564 Font const last_font = running_font;
2565 bool const in_ct_deletion = (bparams.output_changes
2566 && runningChange == change
2567 && change.type == Change::DELETED
2568 && !os.afterParbreak());
2570 // Do we need to close the previous font?
2572 (current_font != running_font ||
2573 current_font.language() != running_font.language()))
2575 // ensure there is no open script-wrapper
2576 if (!alien_script.empty()) {
2579 alien_script.clear();
2581 bool needPar = false;
2582 if (in_ct_deletion) {
2583 // We have to close and then reopen \lyxdeleted,
2584 // as strikeout needs to be on lowest level.
2588 column += running_font.latexWriteEndChanges(
2589 os, bparams, runparams, basefont,
2590 (i == body_pos-1) ? basefont : current_font,
2592 if (in_ct_deletion) {
2593 // We have to close and then reopen \lyxdeleted,
2594 // as strikeout needs to be on lowest level.
2595 OutputParams rp = runparams;
2596 column += Changes::latexMarkChange(os, bparams,
2597 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2599 running_font = basefont;
2603 // if necessary, close language environment before opening CJK
2604 string const running_lang = running_font.language()->babel();
2605 string const lang_end_command = lyxrc.language_command_end;
2606 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2607 && !running_lang.empty()
2608 && running_lang == openLanguageName()
2609 && current_font.language()->encoding()->package() == Encoding::CJK) {
2610 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2611 os << from_ascii(end_tag);
2612 column += end_tag.length();
2616 // Switch file encoding if necessary (and allowed)
2617 if (!runparams.pass_thru && !style.pass_thru &&
2618 runparams.encoding->package() != Encoding::none &&
2619 current_font.language()->encoding()->package() != Encoding::none) {
2620 pair<bool, int> const enc_switch =
2621 switchEncoding(os.os(), bparams, runparams,
2622 *(current_font.language()->encoding()));
2623 if (enc_switch.first) {
2624 column += enc_switch.second;
2625 runparams.encoding = current_font.language()->encoding();
2629 // A display math inset inside an ulem command will be output
2630 // as a box of width \linewidth, so we have to either disable
2631 // indentation if the inset starts a paragraph, or start a new
2632 // line to accommodate such box. This has to be done before
2633 // writing any font changing commands.
2634 if (runparams.inDisplayMath && !deleted_display_math
2635 && runparams.inulemcmd) {
2636 if (os.afterParbreak())
2642 // Do we need to change font?
2643 if ((current_font != running_font ||
2644 current_font.language() != running_font.language())
2645 && i != body_pos - 1)
2647 if (in_ct_deletion) {
2648 // We have to close and then reopen \lyxdeleted,
2649 // as strikeout needs to be on lowest level.
2650 bool needPar = false;
2651 OutputParams rp = runparams;
2652 column += running_font.latexWriteEndChanges(
2653 os, bparams, rp, basefont,
2658 otexstringstream ots;
2659 bool const non_inherit_inset = (c == META_INSET && getInset(i) && !getInset(i)->inheritFont());
2660 column += current_font.latexWriteStartChanges(ots, bparams,
2661 runparams, basefont,
2662 last_font, non_inherit_inset);
2663 // Check again for display math in ulem commands as a
2664 // font change may also occur just before a math inset.
2665 if (runparams.inDisplayMath && !deleted_display_math
2666 && runparams.inulemcmd) {
2667 if (os.afterParbreak())
2672 running_font = current_font;
2674 docstring fontchange = ots.str();
2676 // check whether the fontchange ends with a \\textcolor
2677 // modifier and the text starts with a space. If so we
2678 // need to add } in order to prevent \\textcolor from gobbling
2679 // the space (bug 4473).
2680 docstring const last_modifier = rsplit(fontchange, '\\');
2681 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2682 os << from_ascii("{}");
2683 else if (ots.terminateCommand())
2685 if (in_ct_deletion) {
2686 // We have to close and then reopen \lyxdeleted,
2687 // as strikeout needs to be on lowest level.
2688 OutputParams rp = runparams;
2689 column += Changes::latexMarkChange(os, bparams,
2690 Change(Change::UNCHANGED), change, rp);
2694 // FIXME: think about end_pos implementation...
2695 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2696 // FIXME: integrate this case in latexSpecialChar
2697 // Do not print the separation of the optional argument
2698 // if style.pass_thru is false. This works because
2699 // latexSpecialChar ignores spaces if
2700 // style.pass_thru is false.
2701 if (i != body_pos - 1) {
2702 if (d->simpleTeXBlanks(bparams, runparams, os,
2703 i, column, current_font, style)) {
2704 // A surrogate pair was output. We
2705 // must not call latexSpecialChar
2706 // in this iteration, since it would output
2707 // the combining character again.
2714 OutputParams rp = runparams;
2715 rp.free_spacing = style.free_spacing;
2716 rp.local_font = ¤t_font;
2717 rp.intitle = style.intitle;
2719 // Two major modes: LaTeX or plain
2720 // Handle here those cases common to both modes
2721 // and then split to handle the two modes separately.
2722 if (c == META_INSET) {
2723 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2724 // Greyedout notes and, in general, all insets
2725 // with InsetLayout::isDisplay() == false,
2726 // are typeset inline with the text. So, we
2727 // can add a \par to the last paragraph of
2728 // such insets only if nothing else follows.
2729 bool incremented = false;
2730 Inset const * inset = getInset(i);
2731 InsetText const * textinset = inset
2732 ? inset->asInsetText()
2734 if (i + 1 == size() && textinset
2735 && !inset->getLayout().isDisplay()) {
2736 ParagraphList const & pars =
2737 textinset->text().paragraphs();
2738 pit_type const pit = pars.size() - 1;
2739 Font const lastfont =
2740 pit < 0 || pars[pit].empty()
2741 ? pars[pit].getLayoutFont(
2744 : pars[pit].getFont(bparams,
2745 pars[pit].size() - 1,
2747 if (lastfont.fontInfo().size() !=
2748 basefont.fontInfo().size()) {
2753 d->latexInset(bparams, os, rp, running_font,
2754 basefont, real_outerfont, open_font,
2755 runningChange, style, i, column);
2759 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2760 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2761 // Close \lyx*deleted and force its
2762 // reopening (if needed)
2765 runningChange = Change(Change::UNCHANGED);
2766 runparams.ctObject = OutputParams::CT_NORMAL;
2769 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2770 if (!bparams.useNonTeXFonts)
2771 script = Encodings::isKnownScriptChar(c);
2772 if (script != alien_script) {
2773 if (!alien_script.empty()) {
2775 alien_script.clear();
2777 string fontenc = running_font.language()->fontenc(bparams);
2779 && !Encodings::fontencSupportsScript(fontenc, script)) {
2780 column += script.length() + 2;
2781 os << "\\" << script << "{";
2782 alien_script = script;
2786 d->latexSpecialChar(os, bparams, rp, running_font,
2787 alien_script, style, i, end_pos, column);
2788 } catch (EncodingException & e) {
2789 if (runparams.dryrun) {
2790 os << "<" << _("LyX Warning: ")
2791 << _("uncodable character") << " '";
2795 // add location information and throw again.
2803 // Set the encoding to that returned from latexSpecialChar (see
2804 // comment for encoding member in OutputParams.h)
2805 runparams.encoding = rp.encoding;
2807 // Also carry on the info on a closed ulem command for insets
2808 // such as Note that do not produce any output, so that no
2809 // command is ever executed but its opening was recorded.
2810 runparams.inulemcmd = rp.inulemcmd;
2812 // These need to be passed upstream as well
2813 runparams.need_maketitle = rp.need_maketitle;
2814 runparams.have_maketitle = rp.have_maketitle;
2816 // And finally, pass the post_macros upstream
2817 runparams.post_macro = rp.post_macro;
2820 // Close wrapper for alien script
2821 if (!alien_script.empty()) {
2823 alien_script.clear();
2826 // If we have an open font definition, we have to close it
2828 // Make sure that \\par is done with the font of the last
2829 // character if this has another size as the default.
2830 // This is necessary because LaTeX (and LyX on the screen)
2831 // calculates the space between the baselines according
2832 // to this font. (Matthias)
2834 // We must not change the font for the last paragraph
2835 // of non-multipar insets, tabular cells or commands,
2836 // since this produces unwanted whitespace.
2838 Font const font = empty()
2839 ? getLayoutFont(bparams, real_outerfont)
2840 : getFont(bparams, size() - 1, real_outerfont);
2842 InsetText const * textinset = inInset().asInsetText();
2844 bool const maintext = textinset
2845 ? textinset->text().isMainText()
2848 size_t const numpars = textinset
2849 ? textinset->text().paragraphs().size()
2852 bool needPar = false;
2854 if (style.resfont.size() != font.fontInfo().size()
2855 && (!runparams.isLastPar || maintext
2856 || (numpars > 1 && d->ownerCode() != CELL_CODE
2857 && (inInset().getLayout().isDisplay()
2859 && !style.isCommand()) {
2862 #ifdef FIXED_LANGUAGE_END_DETECTION
2864 running_font.latexWriteEndChanges(os, bparams,
2865 runparams, basefont,
2866 next_->getFont(bparams, 0, outerfont),
2869 running_font.latexWriteEndChanges(os, bparams,
2870 runparams, basefont, basefont, needPar);
2873 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2874 //FIXME: there as we start another \selectlanguage with the next paragraph if
2875 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2876 running_font.latexWriteEndChanges(os, bparams, runparams,
2877 basefont, basefont, needPar);
2880 // The \par could not be inserted at the same nesting
2881 // level of the font size change, so do it now.
2882 os << "{\\" << font.latexSize() << "\\par}";
2886 column += Changes::latexMarkChange(os, bparams, runningChange,
2887 Change(Change::UNCHANGED), runparams);
2889 // Needed if there is an optional argument but no contents.
2890 if (body_pos > 0 && body_pos == size()) {
2894 if (!style.rightdelim().empty()) {
2895 os << style.rightdelim();
2896 column += style.rightdelim().size();
2899 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2900 && runparams.encoding != prev_encoding) {
2901 runparams.encoding = prev_encoding;
2902 os << setEncoding(prev_encoding->iconvName());
2905 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2909 bool Paragraph::emptyTag() const
2911 for (pos_type i = 0; i < size(); ++i) {
2912 if (Inset const * inset = getInset(i)) {
2913 InsetCode lyx_code = inset->lyxCode();
2914 // FIXME testing like that is wrong. What is
2916 if (lyx_code != TOC_CODE &&
2917 lyx_code != INCLUDE_CODE &&
2918 lyx_code != GRAPHICS_CODE &&
2919 lyx_code != ERT_CODE &&
2920 lyx_code != LISTINGS_CODE &&
2921 lyx_code != FLOAT_CODE &&
2922 lyx_code != TABULAR_CODE) {
2926 char_type c = d->text_[i];
2927 if (c != ' ' && c != '\t')
2935 string Paragraph::getID(Buffer const &, OutputParams const &)
2938 for (pos_type i = 0; i < size(); ++i) {
2939 if (Inset const * inset = getInset(i)) {
2940 InsetCode lyx_code = inset->lyxCode();
2941 if (lyx_code == LABEL_CODE) {
2942 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2943 docstring const & id = il->getParam("name");
2944 return "id='" + to_utf8(xml::cleanID(id)) + "'";
2952 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
2955 for (i = 0; i < size(); ++i) {
2956 if (Inset const * inset = getInset(i)) {
2957 inset->docbook(xs, runparams);
2959 char_type c = d->text_[i];
2969 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
2973 for (i = 0; i < size(); ++i) {
2974 if (Inset const * inset = getInset(i)) {
2975 inset->xhtml(xs, runparams);
2977 char_type c = d->text_[i];
2987 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2990 pos_type size = text_.size();
2991 for (pos_type i = initial; i < size; ++i) {
2992 Font font = owner_->getFont(buf.params(), i, outerfont);
2993 if (text_[i] == META_INSET)
2995 if (i != initial && font != font_old)
3006 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3007 vector<xml::EndFontTag> & tagsToClose,
3008 bool & flag, FontState curstate, xml::FontTypes type)
3010 if (curstate == FONT_ON) {
3011 tagsToOpen.push_back(docbookStartFontTag(type));
3014 tagsToClose.push_back(docbookEndFontTag(type));
3019 class OptionalFontType {
3024 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3025 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3028 OptionalFontType fontShapeToXml(FontShape fs)
3032 return {xml::FT_ITALIC};
3034 return {xml::FT_SLANTED};
3035 case SMALLCAPS_SHAPE:
3036 return {xml::FT_SMALLCAPS};
3041 // the other tags are for internal use
3047 OptionalFontType fontFamilyToXml(FontFamily fm)
3051 return {xml::FT_ROMAN};
3053 return {xml::FT_SANS};
3054 case TYPEWRITER_FAMILY:
3055 return {xml::FT_TYPE};
3056 case INHERIT_FAMILY:
3059 // the other tags are for internal use
3065 OptionalFontType fontSizeToXml(FontSize fs)
3069 return {xml::FT_SIZE_TINY};
3071 return {xml::FT_SIZE_SCRIPT};
3073 return {xml::FT_SIZE_FOOTNOTE};
3075 return {xml::FT_SIZE_SMALL};
3077 return {xml::FT_SIZE_LARGE};
3079 return {xml::FT_SIZE_LARGER};
3081 return {xml::FT_SIZE_LARGEST};
3083 return {xml::FT_SIZE_HUGE};
3085 return {xml::FT_SIZE_HUGER};
3087 return {xml::FT_SIZE_INCREASE};
3089 return {xml::FT_SIZE_DECREASE};
3094 // the other tags are for internal use
3100 struct DocBookFontState
3102 FontShape curr_fs = INHERIT_SHAPE;
3103 FontFamily curr_fam = INHERIT_FAMILY;
3104 FontSize curr_size = INHERIT_SIZE;
3106 // track whether we have opened these tags
3107 bool emph_flag = false;
3108 bool bold_flag = false;
3109 bool noun_flag = false;
3110 bool ubar_flag = false;
3111 bool dbar_flag = false;
3112 bool sout_flag = false;
3113 bool xout_flag = false;
3114 bool wave_flag = false;
3116 bool shap_flag = false;
3118 bool faml_flag = false;
3120 bool size_flag = false;
3123 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3125 std::string const & default_family,
3126 DocBookFontState & fs)
3128 vector<xml::FontTag> tagsToOpen;
3129 vector<xml::EndFontTag> tagsToClose;
3132 FontState curstate = font.fontInfo().emph();
3133 if (font_old.emph() != curstate)
3134 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3137 curstate = font.fontInfo().noun();
3138 if (font_old.noun() != curstate)
3139 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3142 curstate = font.fontInfo().underbar();
3143 if (font_old.underbar() != curstate)
3144 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3147 curstate = font.fontInfo().strikeout();
3148 if (font_old.strikeout() != curstate)
3149 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3152 curstate = font.fontInfo().xout();
3153 if (font_old.xout() != curstate)
3154 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3157 curstate = font.fontInfo().uuline();
3158 if (font_old.uuline() != curstate)
3159 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3162 curstate = font.fontInfo().uwave();
3163 if (font_old.uwave() != curstate)
3164 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3167 // a little hackish, but allows us to reuse what we have.
3168 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3169 if (font_old.series() != font.fontInfo().series())
3170 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3173 fs.curr_fs = font.fontInfo().shape();
3174 FontShape old_fs = font_old.shape();
3175 if (old_fs != fs.curr_fs) {
3177 OptionalFontType tag = fontShapeToXml(old_fs);
3179 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3180 fs.shap_flag = false;
3183 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3185 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3189 fs.curr_fam = font.fontInfo().family();
3190 FontFamily old_fam = font_old.family();
3191 if (old_fam != fs.curr_fam) {
3193 OptionalFontType tag = fontFamilyToXml(old_fam);
3195 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3196 fs.faml_flag = false;
3198 switch (fs.curr_fam) {
3200 // we will treat a "default" font family as roman, since we have
3201 // no other idea what to do.
3202 if (default_family != "rmdefault" && default_family != "default") {
3203 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3204 fs.faml_flag = true;
3208 if (default_family != "sfdefault") {
3209 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3210 fs.faml_flag = true;
3213 case TYPEWRITER_FAMILY:
3214 if (default_family != "ttdefault") {
3215 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3216 fs.faml_flag = true;
3219 case INHERIT_FAMILY:
3222 // the other tags are for internal use
3229 fs.curr_size = font.fontInfo().size();
3230 FontSize old_size = font_old.size();
3231 if (old_size != fs.curr_size) {
3233 OptionalFontType tag = fontSizeToXml(old_size);
3235 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3236 fs.size_flag = false;
3239 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3240 if (tag.has_value) {
3241 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3242 fs.size_flag = true;
3246 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3249 } // anonymous namespace
3252 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3254 OutputParams const & runparams,
3255 Font const & outerfont,
3256 bool start_paragraph, bool close_paragraph,
3257 pos_type initial) const
3259 // track whether we have opened these tags
3260 DocBookFontState fs;
3262 if (start_paragraph)
3263 xs.startDivision(allowEmpty());
3265 Layout const & style = *d->layout_;
3267 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3269 string const default_family =
3270 buf.masterBuffer()->params().fonts_default_family;
3272 vector<xml::FontTag> tagsToOpen;
3273 vector<xml::EndFontTag> tagsToClose;
3275 // parsing main loop
3276 for (pos_type i = initial; i < size(); ++i) {
3277 // let's not show deleted material in the output
3281 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3283 // Determine which tags should be opened or closed.
3284 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3287 // Other such tags? What about the other text ranges?
3289 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3290 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3291 for (; cit != cen; ++cit)
3294 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3295 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3296 for (; sit != sen; ++sit)
3299 tagsToClose.clear();
3302 if (Inset const * inset = getInset(i)) {
3303 if (!runparams.for_toc || inset->isInToc()) {
3304 OutputParams np = runparams;
3305 np.local_font = &font;
3306 // If the paragraph has size 1, then we are in the "special
3307 // case" where we do not output the containing paragraph info.
3308 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3309 // of that brittle logic is passed to this function through open_par.
3310 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3311 np.docbook_in_par = true;
3312 inset->docbook(xs, np);
3315 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3318 font_old = font.fontInfo();
3321 // FIXME, this code is just imported from XHTML
3322 // I'm worried about what happens if a branch, say, is itself
3323 // wrapped in some font stuff. I think that will not work.
3325 if (runparams.docbook_in_listing)
3327 if (close_paragraph)
3334 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3335 vector<xml::EndFontTag> & tagsToClose,
3336 bool & flag, FontState curstate, xml::FontTypes type)
3338 if (curstate == FONT_ON) {
3339 tagsToOpen.push_back(xhtmlStartFontTag(type));
3342 tagsToClose.push_back(xhtmlEndFontTag(type));
3347 } // anonymous namespace
3350 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3352 OutputParams const & runparams,
3353 Font const & outerfont,
3354 bool start_paragraph, bool close_paragraph,
3355 pos_type initial) const
3359 // track whether we have opened these tags
3360 bool emph_flag = false;
3361 bool bold_flag = false;
3362 bool noun_flag = false;
3363 bool ubar_flag = false;
3364 bool dbar_flag = false;
3365 bool sout_flag = false;
3366 bool xout_flag = false;
3367 bool wave_flag = false;
3369 bool shap_flag = false;
3371 bool faml_flag = false;
3373 bool size_flag = false;
3375 Layout const & style = *d->layout_;
3377 if (start_paragraph)
3378 xs.startDivision(allowEmpty());
3381 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3383 FontShape curr_fs = INHERIT_SHAPE;
3384 FontFamily curr_fam = INHERIT_FAMILY;
3385 FontSize curr_size = INHERIT_SIZE;
3387 string const default_family =
3388 buf.masterBuffer()->params().fonts_default_family;
3390 vector<xml::FontTag> tagsToOpen;
3391 vector<xml::EndFontTag> tagsToClose;
3393 // parsing main loop
3394 for (pos_type i = initial; i < size(); ++i) {
3395 // let's not show deleted material in the output
3399 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3402 FontState curstate = font.fontInfo().emph();
3403 if (font_old.emph() != curstate)
3404 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3407 curstate = font.fontInfo().noun();
3408 if (font_old.noun() != curstate)
3409 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3412 curstate = font.fontInfo().underbar();
3413 if (font_old.underbar() != curstate)
3414 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3417 curstate = font.fontInfo().strikeout();
3418 if (font_old.strikeout() != curstate)
3419 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3422 curstate = font.fontInfo().xout();
3423 if (font_old.xout() != curstate)
3424 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3427 curstate = font.fontInfo().uuline();
3428 if (font_old.uuline() != curstate)
3429 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3432 curstate = font.fontInfo().uwave();
3433 if (font_old.uwave() != curstate)
3434 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3437 // a little hackish, but allows us to reuse what we have.
3438 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3439 if (font_old.series() != font.fontInfo().series())
3440 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3443 curr_fs = font.fontInfo().shape();
3444 FontShape old_fs = font_old.shape();
3445 if (old_fs != curr_fs) {
3449 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3452 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3454 case SMALLCAPS_SHAPE:
3455 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3461 // the other tags are for internal use
3469 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3473 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3476 case SMALLCAPS_SHAPE:
3477 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3484 // the other tags are for internal use
3491 curr_fam = font.fontInfo().family();
3492 FontFamily old_fam = font_old.family();
3493 if (old_fam != curr_fam) {
3497 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3500 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3502 case TYPEWRITER_FAMILY:
3503 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3505 case INHERIT_FAMILY:
3508 // the other tags are for internal use
3516 // we will treat a "default" font family as roman, since we have
3517 // no other idea what to do.
3518 if (default_family != "rmdefault" && default_family != "default") {
3519 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3524 if (default_family != "sfdefault") {
3525 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3529 case TYPEWRITER_FAMILY:
3530 if (default_family != "ttdefault") {
3531 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3535 case INHERIT_FAMILY:
3538 // the other tags are for internal use
3545 curr_size = font.fontInfo().size();
3546 FontSize old_size = font_old.size();
3547 if (old_size != curr_size) {
3551 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3554 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3557 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3560 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3563 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3566 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3569 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3572 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3575 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3578 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3581 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3587 // the other tags are for internal use
3593 switch (curr_size) {
3595 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3599 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3603 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3607 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3611 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3615 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3619 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3623 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3627 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3631 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3635 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3642 // the other tags are for internal use
3649 // Other such tags? What about the other text ranges?
3651 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3652 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3653 for (; cit != cen; ++cit)
3656 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3657 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3658 for (; sit != sen; ++sit)
3661 tagsToClose.clear();
3664 Inset const * inset = getInset(i);
3666 if (!runparams.for_toc || inset->isInToc()) {
3667 OutputParams np = runparams;
3668 np.local_font = &font;
3669 // If the paragraph has size 1, then we are in the "special
3670 // case" where we do not output the containing paragraph info
3671 if (!inset->getLayout().htmlisblock() && size() != 1)
3672 np.html_in_par = true;
3673 retval += inset->xhtml(xs, np);
3676 char_type c = getUChar(buf.masterBuffer()->params(),
3678 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3679 xs << XMLStream::ESCAPE_NONE << " ";
3683 font_old = font.fontInfo();
3687 // I'm worried about what happens if a branch, say, is itself
3688 // wrapped in some font stuff. I think that will not work.
3690 if (close_paragraph)
3697 bool Paragraph::isHfill(pos_type pos) const
3699 Inset const * inset = getInset(pos);
3700 return inset && inset->isHfill();
3704 bool Paragraph::isNewline(pos_type pos) const
3706 // U+2028 LINE SEPARATOR
3707 // U+2029 PARAGRAPH SEPARATOR
3708 char_type const c = d->text_[pos];
3709 if (c == 0x2028 || c == 0x2029)
3711 Inset const * inset = getInset(pos);
3712 return inset && inset->lyxCode() == NEWLINE_CODE;
3716 bool Paragraph::isEnvSeparator(pos_type pos) const
3718 Inset const * inset = getInset(pos);
3719 return inset && inset->lyxCode() == SEPARATOR_CODE;
3723 bool Paragraph::isLineSeparator(pos_type pos) const
3725 char_type const c = d->text_[pos];
3726 if (isLineSeparatorChar(c))
3728 Inset const * inset = getInset(pos);
3729 return inset && inset->isLineSeparator();
3733 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3737 if (ignore_deleted && isDeleted(pos))
3739 if (Inset const * inset = getInset(pos))
3740 return !inset->isLetter();
3741 // if we have a hard hyphen (no en- or emdash) or apostrophe
3742 // we pass this to the spell checker
3743 // FIXME: this method is subject to change, visit
3744 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3745 // to get an impression how complex this is.
3746 if (isHardHyphenOrApostrophe(pos))
3748 char_type const c = d->text_[pos];
3749 // We want to pass the escape chars to the spellchecker
3750 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3751 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3755 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3757 pos_type const psize = size();
3760 char_type const c = d->text_[pos];
3761 if (c != '-' && c != '\'')
3763 int nextpos = pos + 1;
3764 int prevpos = pos > 0 ? pos - 1 : 0;
3765 if ((nextpos == psize || isSpace(nextpos))
3766 && (pos == 0 || isSpace(prevpos)))
3772 bool Paragraph::needsCProtection(bool const fragile) const
3774 // first check the layout of the paragraph, but only in insets
3775 InsetText const * textinset = inInset().asInsetText();
3776 bool const maintext = textinset
3777 ? textinset->text().isMainText()
3780 if (!maintext && layout().needcprotect) {
3781 // Environments need cprotection regardless the content
3782 if (layout().latextype == LATEX_ENVIRONMENT)
3785 // Commands need cprotection if they contain specific chars
3786 int const nchars_escape = 9;
3787 static char_type const chars_escape[nchars_escape] = {
3788 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3790 docstring const pars = asString();
3791 for (int k = 0; k < nchars_escape; k++) {
3792 if (contains(pars, chars_escape[k]))
3797 // now check whether we have insets that need cprotection
3798 pos_type size = pos_type(d->text_.size());
3799 for (pos_type i = 0; i < size; ++i) {
3802 Inset const * ins = getInset(i);
3803 if (ins->needsCProtection(maintext, fragile))
3805 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3806 // Environments need cprotection regardless the content
3808 // Now check math environments
3809 InsetMath const * im = getInset(i)->asInsetMath();
3810 if (!im || im->cell(0).empty())
3812 switch(im->cell(0)[0]->lyxCode()) {
3813 case MATH_AMSARRAY_CODE:
3814 case MATH_SUBSTACK_CODE:
3816 case MATH_XYMATRIX_CODE:
3817 // these need cprotection
3828 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3830 return d->speller_state_.getRange(pos);
3834 bool Paragraph::isChar(pos_type pos) const
3836 if (Inset const * inset = getInset(pos))
3837 return inset->isChar();
3838 char_type const c = d->text_[pos];
3839 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3843 bool Paragraph::isSpace(pos_type pos) const
3845 if (Inset const * inset = getInset(pos))
3846 return inset->isSpace();
3847 char_type const c = d->text_[pos];
3848 return lyx::isSpace(c);
3853 Paragraph::getParLanguage(BufferParams const & bparams) const
3856 return getFirstFontSettings(bparams).language();
3857 // FIXME: we should check the prev par as well (Lgb)
3858 return bparams.language;
3862 bool Paragraph::isRTL(BufferParams const & bparams) const
3864 return getParLanguage(bparams)->rightToLeft()
3865 && !inInset().getLayout().forceLTR();
3869 void Paragraph::changeLanguage(BufferParams const & bparams,
3870 Language const * from, Language const * to)
3872 // change language including dummy font change at the end
3873 for (pos_type i = 0; i <= size(); ++i) {
3874 Font font = getFontSettings(bparams, i);
3875 if (font.language() == from) {
3876 font.setLanguage(to);
3878 d->requestSpellCheck(i);
3884 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3886 Language const * doc_language = bparams.language;
3887 for (auto const & f : d->fontlist_)
3888 if (f.font().language() != ignore_language &&
3889 f.font().language() != latex_language &&
3890 f.font().language() != doc_language)
3896 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3898 for (auto const & f : d->fontlist_) {
3899 Language const * lang = f.font().language();
3900 if (lang != ignore_language &&
3901 lang != latex_language)
3907 docstring Paragraph::asString(int options) const
3909 return asString(0, size(), options);
3913 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3915 odocstringstream os;
3918 && options & AS_STR_LABEL
3919 && !d->params_.labelString().empty())
3920 os << d->params_.labelString() << ' ';
3922 for (pos_type i = beg; i < end; ++i) {
3923 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3925 char_type const c = d->text_[i];
3926 if (isPrintable(c) || c == '\t'
3927 || (c == '\n' && (options & AS_STR_NEWLINES)))
3929 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3930 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3931 LASSERT(runparams != nullptr, return docstring());
3932 getInset(i)->plaintext(os, *runparams);
3934 getInset(i)->toString(os);
3943 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3944 bool const shorten, bool const label) const
3946 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3947 if (label && !labelString().empty())
3948 os += labelString() + ' ';
3949 if (!layout().isTocCaption())
3951 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3954 char_type const c = d->text_[i];
3957 else if (c == META_INSET)
3958 getInset(i)->forOutliner(os, tmplen, false);
3961 Text::shortenForOutliner(os, maxlen);
3965 void Paragraph::setInsetOwner(Inset const * inset)
3967 d->inset_owner_ = inset;
3971 int Paragraph::id() const
3977 void Paragraph::setId(int id)
3983 Layout const & Paragraph::layout() const
3989 void Paragraph::setLayout(Layout const & layout)
3991 d->layout_ = &layout;
3995 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3997 setLayout(tc.defaultLayout());
4001 void Paragraph::setPlainLayout(DocumentClass const & tc)
4003 setLayout(tc.plainLayout());
4007 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4009 if (usePlainLayout())
4010 setPlainLayout(tclass);
4012 setDefaultLayout(tclass);
4016 Inset const & Paragraph::inInset() const
4018 LBUFERR(d->inset_owner_);
4019 return *d->inset_owner_;
4023 ParagraphParameters & Paragraph::params()
4029 ParagraphParameters const & Paragraph::params() const
4035 bool Paragraph::isFreeSpacing() const
4037 if (d->layout_->free_spacing)
4039 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4043 bool Paragraph::allowEmpty() const
4045 if (d->layout_->keepempty)
4047 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4051 bool Paragraph::brokenBiblio() const
4053 // There is a problem if there is no bibitem at position 0 in
4054 // paragraphs that need one, if there is another bibitem in the
4055 // paragraph or if this paragraph is not supposed to have
4056 // a bibitem inset at all.
4057 return ((d->layout_->labeltype == LABEL_BIBLIO
4058 && (d->insetlist_.find(BIBITEM_CODE) != 0
4059 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4060 || (d->layout_->labeltype != LABEL_BIBLIO
4061 && d->insetlist_.find(BIBITEM_CODE) != -1));
4065 int Paragraph::fixBiblio(Buffer const & buffer)
4067 // FIXME: when there was already an inset at 0, the return value is 1,
4068 // which does not tell whether another inset has been remove; the
4069 // cursor cannot be correctly updated.
4071 bool const track_changes = buffer.params().track_changes;
4072 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4074 // The case where paragraph is not BIBLIO
4075 if (d->layout_->labeltype != LABEL_BIBLIO) {
4076 if (bibitem_pos == -1)
4077 // No InsetBibitem => OK
4079 // There is an InsetBibitem: remove it!
4080 d->insetlist_.release(bibitem_pos);
4081 eraseChar(bibitem_pos, track_changes);
4082 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4085 bool const hasbibitem0 = bibitem_pos == 0;
4087 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4088 // There was an InsetBibitem at pos 0,
4089 // and no other one => OK
4090 if (bibitem_pos == -1)
4092 // there is a bibitem at the 0 position, but since
4093 // there is a second one, we copy the second on the
4094 // first. We're assuming there are at most two of
4095 // these, which there should be.
4096 // FIXME: why does it make sense to do that rather
4097 // than keep the first? (JMarc)
4098 Inset * inset = releaseInset(bibitem_pos);
4099 d->insetlist_.begin()->inset = inset;
4100 return -bibitem_pos;
4103 // We need to create an inset at the beginning
4104 Inset * inset = nullptr;
4105 if (bibitem_pos > 0) {
4106 // there was one somewhere in the paragraph, let's move it
4107 inset = d->insetlist_.release(bibitem_pos);
4108 eraseChar(bibitem_pos, track_changes);
4111 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4112 InsetCommandParams(BIBITEM_CODE));
4114 Font font(inherit_font, buffer.params().language);
4115 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4116 : Change::UNCHANGED));
4118 // This is needed to get the counters right
4119 buffer.updateBuffer();
4124 void Paragraph::checkAuthors(AuthorList const & authorList)
4126 d->changes_.checkAuthors(authorList);
4130 bool Paragraph::isChanged(pos_type pos) const
4132 return lookupChange(pos).changed();
4136 bool Paragraph::isInserted(pos_type pos) const
4138 return lookupChange(pos).inserted();
4142 bool Paragraph::isDeleted(pos_type pos) const
4144 return lookupChange(pos).deleted();
4148 InsetList const & Paragraph::insetList() const
4150 return d->insetlist_;
4154 void Paragraph::setInsetBuffers(Buffer & b)
4156 d->insetlist_.setBuffer(b);
4160 void Paragraph::resetBuffer()
4162 d->insetlist_.resetBuffer();
4166 Inset * Paragraph::releaseInset(pos_type pos)
4168 Inset * inset = d->insetlist_.release(pos);
4169 /// does not honour change tracking!
4170 eraseChar(pos, false);
4175 Inset * Paragraph::getInset(pos_type pos)
4177 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4178 ? d->insetlist_.get(pos) : nullptr;
4182 Inset const * Paragraph::getInset(pos_type pos) const
4184 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4185 ? d->insetlist_.get(pos) : nullptr;
4189 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4190 pos_type & right, TextCase action)
4192 // process sequences of modified characters; in change
4193 // tracking mode, this approach results in much better
4194 // usability than changing case on a char-by-char basis
4195 // We also need to track the current font, since font
4196 // changes within sequences can occur.
4197 vector<pair<char_type, Font> > changes;
4199 bool const trackChanges = bparams.track_changes;
4201 bool capitalize = true;
4203 for (; pos < right; ++pos) {
4204 char_type oldChar = d->text_[pos];
4205 char_type newChar = oldChar;
4207 // ignore insets and don't play with deleted text!
4208 if (oldChar != META_INSET && !isDeleted(pos)) {
4210 case text_lowercase:
4211 newChar = lowercase(oldChar);
4213 case text_capitalization:
4215 newChar = uppercase(oldChar);
4219 case text_uppercase:
4220 newChar = uppercase(oldChar);
4225 if (isWordSeparator(pos) || isDeleted(pos)) {
4226 // permit capitalization again
4230 if (oldChar != newChar) {
4231 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4232 if (pos != right - 1)
4234 // step behind the changing area
4238 int erasePos = pos - changes.size();
4239 for (size_t i = 0; i < changes.size(); i++) {
4240 insertChar(pos, changes[i].first,
4243 if (!eraseChar(erasePos, trackChanges)) {
4246 ++right; // expand selection
4254 int Paragraph::find(docstring const & str, bool cs, bool mw,
4255 pos_type start_pos, bool del) const
4257 pos_type pos = start_pos;
4258 int const strsize = str.length();
4260 pos_type const parsize = d->text_.size();
4261 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4262 // Ignore "invisible" letters such as ligature breaks
4263 // and hyphenation chars while searching
4264 while (pos < parsize - 1 && isInset(pos)) {
4265 odocstringstream os;
4266 getInset(pos)->toString(os);
4267 if (!getInset(pos)->isLetter() || !os.str().empty())
4271 if (cs && str[i] != d->text_[pos])
4273 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4275 if (!del && isDeleted(pos))
4282 // if necessary, check whether string matches word
4284 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4287 && !isWordSeparator(pos))
4291 return pos - start_pos;
4295 char_type Paragraph::getChar(pos_type pos) const
4297 return d->text_[pos];
4301 pos_type Paragraph::size() const
4303 return d->text_.size();
4307 bool Paragraph::empty() const
4309 return d->text_.empty();
4313 bool Paragraph::isInset(pos_type pos) const
4315 return d->text_[pos] == META_INSET;
4319 bool Paragraph::isSeparator(pos_type pos) const
4321 //FIXME: Are we sure this can be the only separator?
4322 return d->text_[pos] == ' ';
4326 void Paragraph::deregisterWords()
4328 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4329 Private::LangWordsMap::const_iterator ite = d->words_.end();
4330 for (; itl != ite; ++itl) {
4331 WordList & wl = theWordList(itl->first);
4332 Private::Words::const_iterator it = (itl->second).begin();
4333 Private::Words::const_iterator et = (itl->second).end();
4334 for (; it != et; ++it)
4341 void Paragraph::locateWord(pos_type & from, pos_type & to,
4342 word_location const loc, bool const ignore_deleted) const
4345 case WHOLE_WORD_STRICT:
4346 if (from == 0 || from == size()
4347 || isWordSeparator(from, ignore_deleted)
4348 || isWordSeparator(from - 1, ignore_deleted)) {
4355 // If we are already at the beginning of a word, do nothing
4356 if (!from || isWordSeparator(from - 1, ignore_deleted))
4361 // always move the cursor to the beginning of previous word
4362 while (from && !isWordSeparator(from - 1, ignore_deleted))
4366 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4369 // no need to move the 'from' cursor
4373 while (to < size() && !isWordSeparator(to, ignore_deleted))
4378 void Paragraph::collectWords()
4380 for (pos_type pos = 0; pos < size(); ++pos) {
4381 if (isWordSeparator(pos))
4383 pos_type from = pos;
4384 locateWord(from, pos, WHOLE_WORD);
4385 // Work around MSVC warning: The statement
4386 // if (pos < from + lyxrc.completion_minlength)
4387 // triggers a signed vs. unsigned warning.
4388 // I don't know why this happens, it could be a MSVC bug, or
4389 // related to LLP64 (windows) vs. LP64 (unix) programming
4390 // model, or the C++ standard might be ambigous in the section
4391 // defining the "usual arithmetic conversions". However, using
4392 // a temporary variable is safe and works on all compilers.
4393 pos_type const endpos = from + lyxrc.completion_minlength;
4396 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4397 if (cit == d->fontlist_.end())
4399 Language const * lang = cit->font().language();
4400 docstring const word = asString(from, pos, AS_STR_NONE);
4401 d->words_[lang->lang()].insert(word);
4406 void Paragraph::registerWords()
4408 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4409 Private::LangWordsMap::const_iterator ite = d->words_.end();
4410 for (; itl != ite; ++itl) {
4411 WordList & wl = theWordList(itl->first);
4412 Private::Words::const_iterator it = (itl->second).begin();
4413 Private::Words::const_iterator et = (itl->second).end();
4414 for (; it != et; ++it)
4420 void Paragraph::updateWords()
4428 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4430 SkipPositionsIterator begin = skips.begin();
4431 SkipPositions::iterator end = skips.end();
4432 if (pos > 0 && begin < end) {
4434 if (end->last == pos - 1) {
4439 skips.insert(end, FontSpan(pos, pos));
4443 Language * Paragraph::Private::locateSpellRange(
4444 pos_type & from, pos_type & to,
4445 SkipPositions & skips) const
4447 // skip leading white space
4448 while (from < to && owner_->isWordSeparator(from))
4450 // don't check empty range
4453 // get current language
4454 Language * lang = getSpellLanguage(from);
4455 pos_type last = from;
4456 bool samelang = true;
4457 bool sameinset = true;
4458 while (last < to && samelang && sameinset) {
4459 // hop to end of word
4460 while (last < to && !owner_->isWordSeparator(last)) {
4461 if (owner_->getInset(last)) {
4462 appendSkipPosition(skips, last);
4463 } else if (owner_->isDeleted(last)) {
4464 appendSkipPosition(skips, last);
4468 // hop to next word while checking for insets
4469 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4470 if (Inset const * inset = owner_->getInset(last))
4471 sameinset = inset->isChar() && inset->isLetter();
4472 if (sameinset && owner_->isDeleted(last)) {
4473 appendSkipPosition(skips, last);
4478 if (sameinset && last < to) {
4479 // now check for language change
4480 samelang = lang == getSpellLanguage(last);
4483 // if language change detected backstep is needed
4491 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4494 const_cast<Language *>(owner_->getFontSettings(
4495 inset_owner_->buffer().params(), from).language());
4496 if (lang == inset_owner_->buffer().params().language
4497 && !lyxrc.spellchecker_alt_lang.empty()) {
4499 string const lang_variety =
4500 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4501 lang->setCode(lang_code);
4502 lang->setVariety(lang_variety);
4508 void Paragraph::requestSpellCheck(pos_type pos)
4510 d->requestSpellCheck(pos);
4514 bool Paragraph::needsSpellCheck() const
4516 SpellChecker::ChangeNumber speller_change_number = 0;
4517 if (theSpellChecker())
4518 speller_change_number = theSpellChecker()->changeNumber();
4519 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4520 d->speller_state_.needsCompleteRefresh(speller_change_number);
4522 return d->needsSpellCheck();
4526 bool Paragraph::Private::ignoreWord(docstring const & word) const
4528 // Ignore words with digits
4529 // FIXME: make this customizable
4530 // (note that some checkers ignore words with digits by default)
4531 docstring::const_iterator cit = word.begin();
4532 docstring::const_iterator const end = word.end();
4533 for (; cit != end; ++cit) {
4534 if (isNumber((*cit)))
4541 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4542 WordLangTuple & wl, docstring_list & suggestions,
4543 bool do_suggestion, bool check_learned) const
4545 SpellChecker::Result result = SpellChecker::WORD_OK;
4546 SpellChecker * speller = theSpellChecker();
4550 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4553 locateWord(from, to, WHOLE_WORD, true);
4554 if (from == to || from >= size())
4557 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4558 Language * lang = d->getSpellLanguage(from);
4560 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4563 wl = WordLangTuple(word, lang);
4568 if (needsSpellCheck() || check_learned) {
4570 if (!d->ignoreWord(word)) {
4571 bool const trailing_dot = to < size() && d->text_[to] == '.';
4572 result = speller->check(wl);
4573 if (SpellChecker::misspelled(result) && trailing_dot) {
4574 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4575 result = speller->check(wl);
4576 if (!SpellChecker::misspelled(result)) {
4577 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4579 from << ".." << to << "]");
4581 // spell check with dot appended failed too
4582 // restore original word/lang value
4583 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4584 wl = WordLangTuple(word, lang);
4588 if (!SpellChecker::misspelled(result)) {
4589 // area up to the begin of the next word is not misspelled
4590 while (end < size() && isWordSeparator(end))
4593 d->setMisspelled(from, end, result);
4595 result = d->speller_state_.getState(from);
4599 suggestions.clear();
4601 if (SpellChecker::misspelled(result)) {
4602 LYXERR(Debug::GUI, "misspelled word: \"" <<
4604 from << ".." << to << "]");
4606 speller->suggest(wl, suggestions);
4612 void Paragraph::anonymize()
4614 // This is a very crude anonymization for now
4615 for (char_type & c : d->text_)
4616 if (isLetterChar(c) || isNumber(c))
4621 void Paragraph::Private::markMisspelledWords(
4622 pos_type const & first, pos_type const & last,
4623 SpellChecker::Result result,
4624 docstring const & word,
4625 SkipPositions const & skips)
4627 if (!SpellChecker::misspelled(result)) {
4628 setMisspelled(first, last, SpellChecker::WORD_OK);
4632 SpellChecker * speller = theSpellChecker();
4633 // locate and enumerate the error positions
4634 int nerrors = speller->numMisspelledWords();
4636 SkipPositionsIterator it = skips.begin();
4637 SkipPositionsIterator et = skips.end();
4638 for (int index = 0; index < nerrors; ++index) {
4641 speller->misspelledWord(index, wstart, wlen);
4642 /// should not happen if speller supports range checks
4643 if (!wlen) continue;
4644 docstring const misspelled = word.substr(wstart, wlen);
4645 wstart += first + numskipped;
4646 if (snext < wstart) {
4647 /// mark the range of correct spelling
4648 numskipped += countSkips(it, et, wstart);
4649 setMisspelled(snext,
4650 wstart - 1, SpellChecker::WORD_OK);
4652 snext = wstart + wlen;
4653 numskipped += countSkips(it, et, snext);
4654 /// mark the range of misspelling
4655 setMisspelled(wstart, snext, result);
4656 LYXERR(Debug::GUI, "misspelled word: \"" <<
4657 misspelled << "\" [" <<
4658 wstart << ".." << (snext-1) << "]");
4661 if (snext <= last) {
4662 /// mark the range of correct spelling at end
4663 setMisspelled(snext, last, SpellChecker::WORD_OK);
4668 void Paragraph::spellCheck() const
4670 SpellChecker * speller = theSpellChecker();
4671 if (!speller || empty() ||!needsSpellCheck())
4675 d->rangeOfSpellCheck(start, endpos);
4676 if (speller->canCheckParagraph()) {
4677 // loop until we leave the range
4678 for (pos_type first = start; first < endpos; ) {
4679 pos_type last = endpos;
4680 Private::SkipPositions skips;
4681 Language * lang = d->locateSpellRange(first, last, skips);
4682 if (first >= endpos)
4684 // start the spell checker on the unit of meaning
4685 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4686 WordLangTuple wl = WordLangTuple(word, lang);
4687 SpellChecker::Result result = word.size() ?
4688 speller->check(wl) : SpellChecker::WORD_OK;
4689 d->markMisspelledWords(first, last, result, word, skips);
4693 static docstring_list suggestions;
4694 pos_type to = endpos;
4695 while (start < endpos) {
4697 spellCheck(start, to, wl, suggestions, false);
4701 d->readySpellCheck();
4705 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4707 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4708 if (result || pos <= 0 || pos > size())
4710 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4711 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4716 string Paragraph::magicLabel() const
4719 ss << "magicparlabel-" << id();