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"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "output_docbook.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/Length.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 closeLanguage = arabtex
1044 || basefont.isRightToLeft() == running_font.isRightToLeft();
1045 unsigned int count = running_font.latexWriteStartChanges(os, bparams,
1046 runparams, basefont,
1047 running_font, true);
1049 // if any font properties were closed, update the running_font,
1050 // making sure, however, to leave the language as it was
1052 // FIXME: probably a better way to keep track of the old
1053 // language, than copying the entire font?
1054 Font const copy_font(running_font);
1055 basefont = owner_->getLayoutFont(bparams, outerfont);
1056 running_font = basefont;
1058 running_font.setLanguage(copy_font.language());
1059 // For these, we use switches, so no need to close
1060 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1061 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1062 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1064 runparams.local_font = &basefont;
1068 size_t const previous_row_count = os.texrow().rows();
1071 runparams.lastid = id_;
1072 runparams.lastpos = i;
1073 inset->latex(os, runparams);
1074 } catch (EncodingException & e) {
1075 // add location information and throw again.
1084 if (os.texrow().rows() > previous_row_count) {
1085 os.texrow().start(owner_->id(), i + 1);
1088 column += (unsigned int)(os.os().tellp() - len);
1091 if (owner_->isDeleted(i))
1092 --runparams.inDeletedInset;
1096 void Paragraph::Private::latexSpecialChar(otexstream & os,
1097 BufferParams const & bparams,
1098 OutputParams const & runparams,
1099 Font const & running_font,
1100 string & alien_script,
1101 Layout const & style,
1104 unsigned int & column)
1106 char_type const c = owner_->getUChar(bparams, runparams, i);
1108 if (style.pass_thru || runparams.pass_thru
1109 || contains(style.pass_thru_chars, c)
1110 || contains(runparams.pass_thru_chars, c)) {
1112 Encoding const * const enc = runparams.encoding;
1113 if (enc && !enc->encodable(c))
1114 throw EncodingException(c);
1120 // TIPA uses its own T3 encoding
1121 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1123 // If T1 font encoding is used, use the special
1124 // characters it provides.
1125 // NOTE: Some languages reset the font encoding internally to a
1126 // non-standard font encoding. If we are using such a language,
1127 // we do not output special T1 chars.
1128 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1129 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1130 && latexSpecialT1(c, os, i, column))
1132 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1133 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1134 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1137 // Otherwise, we use what LaTeX provides us.
1140 os << "\\textbackslash" << termcmd;
1144 os << "\\textless" << termcmd;
1148 os << "\\textgreater" << termcmd;
1152 os << "\\textbar" << termcmd;
1157 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1158 (end_pos == -1 || i + 1 < end_pos) &&
1159 text_[i+1] == '-') {
1160 // Prevent "--" becoming an en dash and "---" an em dash.
1161 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1167 os << "\\textquotedbl" << termcmd;
1172 case '%': case '#': case '{':
1180 os << "\\textasciitilde" << termcmd;
1185 os << "\\textasciicircum" << termcmd;
1192 // avoid being mistaken for optional arguments
1200 // Blanks are printed before font switching.
1201 // Sure? I am not! (try nice-latex)
1202 // I am sure it's correct. LyX might be smarter
1203 // in the future, but for now, nothing wrong is
1209 // XeTeX's dash behaviour is determined via a global setting
1210 if (bparams.use_dash_ligatures
1211 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1213 // TODO #10961: && not in inset Flex Code
1214 // TODO #10961: && not in layout LyXCode
1215 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1232 Encoding const & encoding = *(runparams.encoding);
1233 char_type next = '\0';
1234 if (i + 1 < int(text_.size())) {
1235 next = text_[i + 1];
1236 if (Encodings::isCombiningChar(next)) {
1237 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1242 pair<docstring, bool> latex = encoding.latexChar(c);
1243 docstring nextlatex;
1244 bool nexttipas = false;
1245 string nexttipashortcut;
1246 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1247 nextlatex = encoding.latexChar(next).first;
1248 if (runparams.inIPA) {
1249 nexttipashortcut = Encodings::TIPAShortcut(next);
1250 nexttipas = !nexttipashortcut.empty();
1254 if (runparams.inIPA) {
1255 string const tipashortcut = Encodings::TIPAShortcut(c);
1256 if (!tipashortcut.empty()) {
1257 latex.first = from_ascii(tipashortcut);
1258 latex.second = false;
1262 // eventually close "script wrapper" command (see `Paragraph::latex`)
1263 if (!alien_script.empty()
1264 && alien_script != Encodings::isKnownScriptChar(next)) {
1265 column += latex.first.length();
1266 alien_script.clear();
1267 os << latex.first << "}";
1271 && ((!prefixIs(nextlatex, '\\')
1272 && !prefixIs(nextlatex, '{')
1273 && !prefixIs(nextlatex, '}'))
1275 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1277 // Prevent eating of a following space or command corruption by
1278 // following characters
1279 if (next == ' ' || next == '\0') {
1280 column += latex.first.length() + 1;
1281 os << latex.first << "{}";
1283 column += latex.first.length();
1284 os << latex.first << " ";
1287 column += latex.first.length() - 1;
1295 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1296 pos_type i, unsigned int & column)
1302 // In T1 encoding, these characters exist
1303 // but we should avoid ligatures
1304 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1306 os << "\\textcompwordmark" << termcmd;
1313 // soul.sty breaks with \char`\"
1314 os << "\\textquotedbl" << termcmd;
1323 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1324 pos_type i, unsigned int & column)
1326 // TU encoding is currently on par with T1.
1327 return latexSpecialT1(c, os, i, column);
1331 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1332 pos_type /*i*/, unsigned int & column)
1342 os << "\\textvertline" << termcmd;
1351 void Paragraph::Private::validate(LaTeXFeatures & features) const
1353 if (layout_->inpreamble && inset_owner_) {
1354 // FIXME: Using a string stream here circumvents the encoding
1355 // switching machinery of odocstream. Therefore the
1356 // output is wrong if this paragraph contains content
1357 // that needs to switch encoding.
1358 Buffer const & buf = inset_owner_->buffer();
1359 otexstringstream os;
1360 os << layout_->preamble();
1361 size_t const length = os.length();
1362 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1363 buf.getParFromID(owner_->id()).pit(), os,
1364 features.runparams(), string(), 0, -1, true);
1365 if (os.length() > length)
1366 features.addPreambleSnippet(os.release(), true);
1369 if (features.runparams().flavor == OutputParams::HTML
1370 && layout_->htmltitle()) {
1371 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1374 // check the params.
1375 if (!params_.spacing().isDefault())
1376 features.require("setspace");
1379 features.useLayout(layout_->name());
1382 fontlist_.validate(features);
1384 // then the indentation
1385 if (!params_.leftIndent().zero())
1386 features.require("ParagraphLeftIndent");
1389 InsetList::const_iterator icit = insetlist_.begin();
1390 InsetList::const_iterator iend = insetlist_.end();
1391 for (; icit != iend; ++icit) {
1393 features.inDeletedInset(owner_->isDeleted(icit->pos));
1394 if (icit->inset->lyxCode() == FOOT_CODE) {
1395 // FIXME: an item inset would make things much easier.
1396 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1397 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1398 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1399 && (icit->pos < begin_of_body_
1400 || (icit->pos == begin_of_body_
1401 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1402 features.saveNoteEnv("description");
1404 icit->inset->validate(features);
1405 features.inDeletedInset(false);
1406 if (layout_->needprotect &&
1407 icit->inset->lyxCode() == FOOT_CODE)
1408 features.require("NeedLyXFootnoteCode");
1412 // then the contents
1413 BufferParams const bp = features.runparams().is_child
1414 ? features.buffer().masterParams() : features.buffer().params();
1415 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1416 char_type c = text_[i];
1417 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1419 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1420 features.require("textquotedblp");
1421 else if (bp.main_font_encoding() != "T1"
1422 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1423 features.require("textquotedbl");
1424 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1425 // features that depend on the font or input encoding
1426 string feats = ci.textpreamble();
1427 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1428 if (fontenc.empty())
1429 fontenc = features.runparams().main_fontenc;
1430 while (!feats.empty()) {
1432 feats = split(feats, feat, ',');
1433 if (contains(feat, "!=")) {
1434 // a feature that is required except for the spcified
1435 // font or input encodings
1437 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1438 // multiple encodings are separated by semicolon
1439 vector<string> context = getVectorFromString(contexts, ";");
1440 // require feature if the context matches neither current font
1441 // nor input encoding
1442 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1443 && std::find(context.begin(), context.end(),
1444 features.runparams().encoding->name()) == context.end())
1445 features.require(realfeature);
1446 } else if (contains(feat, '=')) {
1447 // a feature that is required only for the spcified
1448 // font or input encodings
1450 string const contexts = split(feat, realfeature, '=');
1451 // multiple encodings are separated by semicolon
1452 vector<string> context = getVectorFromString(contexts, ";");
1453 // require feature if the context matches either current font
1454 // or input encoding
1455 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1456 || std::find(context.begin(), context.end(),
1457 features.runparams().encoding->name()) != context.end())
1458 features.require(realfeature);
1461 } else if (!bp.use_dash_ligatures
1462 && (c == 0x2013 || c == 0x2014)
1463 && bp.useNonTeXFonts
1464 && features.runparams().flavor == OutputParams::XETEX)
1465 // XeTeX's dash behaviour is determined via a global setting
1466 features.require("xetexdashbreakstate");
1467 BufferEncodings::validate(c, features);
1471 /////////////////////////////////////////////////////////////////////
1475 /////////////////////////////////////////////////////////////////////
1478 Layout const emptyParagraphLayout;
1481 Paragraph::Paragraph()
1482 : d(new Paragraph::Private(this, emptyParagraphLayout))
1489 Paragraph::Paragraph(Paragraph const & par)
1490 : itemdepth(par.itemdepth),
1491 d(new Paragraph::Private(*par.d, this))
1497 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1498 : itemdepth(par.itemdepth),
1499 d(new Paragraph::Private(*par.d, this, beg, end))
1505 Paragraph & Paragraph::operator=(Paragraph const & par)
1507 // needed as we will destroy the private part before copying it
1509 itemdepth = par.itemdepth;
1513 d = new Private(*par.d, this);
1520 Paragraph::~Paragraph()
1529 // this shall be called just before every "os << ..." action.
1530 void flushString(ostream & os, docstring & s)
1539 void Paragraph::write(ostream & os, BufferParams const & bparams,
1540 depth_type & dth) const
1542 // The beginning or end of a deeper (i.e. nested) area?
1543 if (dth != d->params_.depth()) {
1544 if (d->params_.depth() > dth) {
1545 while (d->params_.depth() > dth) {
1546 os << "\n\\begin_deeper";
1550 while (d->params_.depth() < dth) {
1551 os << "\n\\end_deeper";
1557 // First write the layout
1558 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1560 d->params_.write(os);
1562 Font font1(inherit_font, bparams.language);
1564 Change running_change = Change(Change::UNCHANGED);
1566 // this string is used as a buffer to avoid repetitive calls
1567 // to to_utf8(), which turn out to be expensive (JMarc)
1568 docstring write_buffer;
1571 for (pos_type i = 0; i <= size(); ++i) {
1573 Change const & change = lookupChange(i);
1574 if (change != running_change)
1575 flushString(os, write_buffer);
1576 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1577 running_change = change;
1582 // Write font changes
1583 Font font2 = getFontSettings(bparams, i);
1584 if (font2 != font1) {
1585 flushString(os, write_buffer);
1586 font2.lyxWriteChanges(font1, os);
1591 char_type const c = d->text_[i];
1594 if (Inset const * inset = getInset(i)) {
1595 flushString(os, write_buffer);
1596 if (inset->directWrite()) {
1597 // international char, let it write
1598 // code directly so it's shorter in
1604 os << "\\begin_inset ";
1606 os << "\n\\end_inset\n\n";
1609 // FIXME This can be removed again once the mystery
1610 // crash has been resolved.
1615 flushString(os, write_buffer);
1616 os << "\n\\backslash\n";
1620 flushString(os, write_buffer);
1621 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1628 if ((column > 70 && c == ' ')
1630 flushString(os, write_buffer);
1634 // this check is to amend a bug. LyX sometimes
1635 // inserts '\0' this could cause problems.
1637 write_buffer.push_back(c);
1639 LYXERR0("NUL char in structure.");
1645 flushString(os, write_buffer);
1646 os << "\n\\end_layout\n";
1647 // FIXME This can be removed again once the mystery
1648 // crash has been resolved.
1653 void Paragraph::validate(LaTeXFeatures & features) const
1655 d->validate(features);
1656 bool fragile = features.runparams().moving_arg;
1657 fragile |= layout().needprotect;
1658 if (inInset().getLayout().isNeedProtect())
1660 if (needsCProtection(fragile))
1661 features.require("cprotect");
1665 void Paragraph::insert(pos_type start, docstring const & str,
1666 Font const & font, Change const & change)
1668 for (size_t i = 0, n = str.size(); i != n ; ++i)
1669 insertChar(start + i, str[i], font, change);
1673 void Paragraph::appendChar(char_type c, Font const & font,
1674 Change const & change)
1677 d->changes_.insert(change, d->text_.size());
1678 // when appending characters, no need to update tables
1679 d->text_.push_back(c);
1680 setFont(d->text_.size() - 1, font);
1681 d->requestSpellCheck(d->text_.size() - 1);
1685 void Paragraph::appendString(docstring const & s, Font const & font,
1686 Change const & change)
1688 pos_type end = s.size();
1689 size_t oldsize = d->text_.size();
1690 size_t newsize = oldsize + end;
1691 size_t capacity = d->text_.capacity();
1692 if (newsize >= capacity)
1693 d->text_.reserve(max(capacity + 100, newsize));
1695 // when appending characters, no need to update tables
1698 // FIXME: Optimize this!
1699 for (size_t i = oldsize; i != newsize; ++i) {
1701 d->changes_.insert(change, i);
1702 d->requestSpellCheck(i);
1704 d->fontlist_.set(oldsize, font);
1705 d->fontlist_.set(newsize - 1, font);
1709 void Paragraph::insertChar(pos_type pos, char_type c,
1712 d->insertChar(pos, c, Change(trackChanges ?
1713 Change::INSERTED : Change::UNCHANGED));
1717 void Paragraph::insertChar(pos_type pos, char_type c,
1718 Font const & font, bool trackChanges)
1720 d->insertChar(pos, c, Change(trackChanges ?
1721 Change::INSERTED : Change::UNCHANGED));
1726 void Paragraph::insertChar(pos_type pos, char_type c,
1727 Font const & font, Change const & change)
1729 d->insertChar(pos, c, change);
1734 void Paragraph::resetFonts(Font const & font)
1736 d->fontlist_.clear();
1737 d->fontlist_.set(0, font);
1738 d->fontlist_.set(d->text_.size() - 1, font);
1741 // Gets uninstantiated font setting at position.
1742 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1746 LYXERR0("pos: " << pos << " size: " << size());
1750 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1751 if (cit != d->fontlist_.end())
1754 if (pos == size() && !empty())
1755 return getFontSettings(bparams, pos - 1);
1757 // Optimisation: avoid a full font instantiation if there is no
1758 // language change from previous call.
1759 static Font previous_font;
1760 static Language const * previous_lang = nullptr;
1761 Language const * lang = getParLanguage(bparams);
1762 if (lang != previous_lang) {
1763 previous_lang = lang;
1764 previous_font = Font(inherit_font, lang);
1766 return previous_font;
1770 FontSpan Paragraph::fontSpan(pos_type pos) const
1772 LBUFERR(pos <= size());
1775 return FontSpan(pos, pos);
1778 FontList::const_iterator cit = d->fontlist_.begin();
1779 FontList::const_iterator end = d->fontlist_.end();
1780 for (; cit != end; ++cit) {
1781 if (cit->pos() >= pos) {
1782 if (pos >= beginOfBody())
1783 return FontSpan(max(start, beginOfBody()),
1786 return FontSpan(start,
1787 min(beginOfBody() - 1,
1790 start = cit->pos() + 1;
1793 // This should not happen, but if so, we take no chances.
1794 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1795 LASSERT(false, return FontSpan(pos, pos));
1799 // Gets uninstantiated font setting at position 0
1800 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1802 if (!empty() && !d->fontlist_.empty())
1803 return d->fontlist_.begin()->font();
1805 // Optimisation: avoid a full font instantiation if there is no
1806 // language change from previous call.
1807 static Font previous_font;
1808 static Language const * previous_lang = nullptr;
1809 if (bparams.language != previous_lang) {
1810 previous_lang = bparams.language;
1811 previous_font = Font(inherit_font, bparams.language);
1814 return previous_font;
1818 // Gets the fully instantiated font at a given position in a paragraph
1819 // This is basically the same function as Text::GetFont() in text2.cpp.
1820 // The difference is that this one is used for generating the LaTeX file,
1821 // and thus cosmetic "improvements" are disallowed: This has to deliver
1822 // the true picture of the buffer. (Asger)
1823 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1824 Font const & outerfont) const
1828 Font font = getFontSettings(bparams, pos);
1830 pos_type const body_pos = beginOfBody();
1831 FontInfo & fi = font.fontInfo();
1833 fi.realize(d->layout_->labelfont);
1835 fi.realize(d->layout_->font);
1837 fi.realize(outerfont.fontInfo());
1838 fi.realize(bparams.getFont().fontInfo());
1844 Font const Paragraph::getLabelFont
1845 (BufferParams const & bparams, Font const & outerfont) const
1847 FontInfo tmpfont = d->layout_->labelfont;
1848 tmpfont.realize(outerfont.fontInfo());
1849 tmpfont.realize(bparams.getFont().fontInfo());
1850 return Font(tmpfont, getParLanguage(bparams));
1854 Font const Paragraph::getLayoutFont
1855 (BufferParams const & bparams, Font const & outerfont) const
1857 FontInfo tmpfont = d->layout_->font;
1858 tmpfont.realize(outerfont.fontInfo());
1859 tmpfont.realize(bparams.getFont().fontInfo());
1860 return Font(tmpfont, getParLanguage(bparams));
1864 char_type Paragraph::getUChar(BufferParams const & bparams,
1865 OutputParams const & rp,
1868 char_type c = d->text_[pos];
1870 // Return unchanged character in LTR languages
1871 // or if we use poylglossia/bidi (XeTeX).
1872 if (rp.useBidiPackage()
1873 || !getFontSettings(bparams, pos).isRightToLeft())
1876 // Without polyglossia/bidi, we need to account for some special cases.
1877 // FIXME This needs to be audited!
1879 // * The input is as expected for all delimiters
1880 // => checked for Hebrew!
1881 // * The output matches the display in the LyX workarea
1882 // => checked for Hebrew!
1883 // * The special cases below are really necessary
1884 // => checked for Hebrew!
1885 // * In arabic_arabi, brackets are transformed to Arabic
1886 // Ornate Parentheses. Is this is really wanted?
1888 string const & lang = getFontSettings(bparams, pos).language()->lang();
1891 // 1. In the following languages, parentheses need to be reversed.
1892 // Also with polyglodia/luabidi
1893 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1895 // 2. In the following languages, brackets don't need to be reversed.
1896 bool const reversebrackets = lang != "arabic_arabtex"
1897 && lang != "arabic_arabi"
1900 // Now swap delimiters if needed.
1911 if (reversebrackets)
1915 if (reversebrackets)
1936 void Paragraph::setFont(pos_type pos, Font const & font)
1938 LASSERT(pos <= size(), return);
1940 // First, reduce font against layout/label font
1941 // Update: The setCharFont() routine in text2.cpp already
1942 // reduces font, so we don't need to do that here. (Asger)
1944 d->fontlist_.set(pos, font);
1948 void Paragraph::makeSameLayout(Paragraph const & par)
1950 d->layout_ = par.d->layout_;
1951 d->params_ = par.d->params_;
1955 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1957 if (isFreeSpacing())
1963 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1964 if (eraseChar(pos, trackChanges))
1970 return count > 0 || pos > 0;
1974 bool Paragraph::hasSameLayout(Paragraph const & par) const
1976 return par.d->layout_ == d->layout_
1977 && d->params_.sameLayout(par.d->params_);
1981 depth_type Paragraph::getDepth() const
1983 return d->params_.depth();
1987 depth_type Paragraph::getMaxDepthAfter() const
1989 if (d->layout_->isEnvironment())
1990 return d->params_.depth() + 1;
1992 return d->params_.depth();
1996 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
1998 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1999 return getDefaultAlign(bparams);
2001 return d->params_.align();
2005 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2007 LyXAlignment res = layout().align;
2008 if (isRTL(bparams)) {
2010 if (res == LYX_ALIGN_LEFT)
2011 res = LYX_ALIGN_RIGHT;
2012 else if (res == LYX_ALIGN_RIGHT)
2013 res = LYX_ALIGN_LEFT;
2019 docstring const & Paragraph::labelString() const
2021 return d->params_.labelString();
2025 // the next two functions are for the manual labels
2026 docstring const Paragraph::getLabelWidthString() const
2028 if (d->layout_->margintype == MARGIN_MANUAL
2029 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2030 return d->params_.labelWidthString();
2032 return _("Senseless with this layout!");
2036 void Paragraph::setLabelWidthString(docstring const & s)
2038 d->params_.labelWidthString(s);
2042 docstring Paragraph::expandLabel(Layout const & layout,
2043 BufferParams const & bparams) const
2045 return expandParagraphLabel(layout, bparams, true);
2049 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2050 BufferParams const & bparams, bool process_appendix) const
2052 DocumentClass const & tclass = bparams.documentClass();
2053 string const & lang = getParLanguage(bparams)->code();
2054 bool const in_appendix = process_appendix && d->params_.appendix();
2055 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2057 if (fmt.empty() && !layout.counter.empty())
2058 return tclass.counters().theCounter(layout.counter, lang);
2060 // handle 'inherited level parts' in 'fmt',
2061 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2062 size_t const i = fmt.find('@', 0);
2063 if (i != docstring::npos) {
2064 size_t const j = fmt.find('@', i + 1);
2065 if (j != docstring::npos) {
2066 docstring parent(fmt, i + 1, j - i - 1);
2067 docstring label = from_ascii("??");
2068 if (tclass.hasLayout(parent))
2069 label = expandParagraphLabel(tclass[parent], bparams,
2071 fmt = docstring(fmt, 0, i) + label
2072 + docstring(fmt, j + 1, docstring::npos);
2076 return tclass.counters().counterLabel(fmt, lang);
2080 void Paragraph::applyLayout(Layout const & new_layout)
2082 d->layout_ = &new_layout;
2083 LyXAlignment const oldAlign = d->params_.align();
2085 if (!(oldAlign & d->layout_->alignpossible)) {
2086 frontend::Alert::warning(_("Alignment not permitted"),
2087 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2088 d->params_.align(LYX_ALIGN_LAYOUT);
2093 pos_type Paragraph::beginOfBody() const
2095 return d->begin_of_body_;
2099 void Paragraph::setBeginOfBody()
2101 if (d->layout_->labeltype != LABEL_MANUAL) {
2102 d->begin_of_body_ = 0;
2106 // Unroll the first two cycles of the loop
2107 // and remember the previous character to
2108 // remove unnecessary getChar() calls
2110 pos_type end = size();
2111 bool prev_char_deleted = false;
2112 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2115 char_type previous_char = d->text_[i];
2116 if (!(isNewline(i) || isEnvSeparator(i))) {
2118 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2119 char_type temp = d->text_[i];
2120 prev_char_deleted = isDeleted(i);
2121 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2124 previous_char = temp;
2130 d->begin_of_body_ = i;
2134 bool Paragraph::allowParagraphCustomization() const
2136 return inInset().allowParagraphCustomization();
2140 bool Paragraph::usePlainLayout() const
2142 return inInset().usePlainLayout();
2146 bool Paragraph::isPassThru() const
2148 return inInset().isPassThru() || d->layout_->pass_thru;
2153 // paragraphs inside floats need different alignment tags to avoid
2156 bool noTrivlistCentering(InsetCode code)
2158 return code == FLOAT_CODE
2159 || code == WRAP_CODE
2160 || code == CELL_CODE;
2164 string correction(string const & orig)
2166 if (orig == "flushleft")
2167 return "raggedright";
2168 if (orig == "flushright")
2169 return "raggedleft";
2170 if (orig == "center")
2176 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2177 InsetCode code, bool const lastpar, int & col)
2179 string macro = suffix + "{";
2180 if (noTrivlistCentering(code)) {
2182 // the last paragraph in non-trivlist-aligned
2183 // context is special (to avoid unwanted whitespace)
2184 if (suffix == "\\begin") {
2185 macro = "\\" + correction(env) + "{}";
2186 os << from_ascii(macro);
2187 col += macro.size();
2192 macro += correction(env);
2196 if (suffix == "\\par\\end") {
2200 os << from_ascii(macro);
2201 col += macro.size();
2202 if (suffix == "\\begin") {
2212 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2213 otexstream & os, OutputParams const & runparams) const
2218 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2219 (layout_->toggle_indent != ITOGGLE_NEVER) :
2220 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2222 if (canindent && params_.noindent() && !layout_->pass_thru) {
2223 os << "\\noindent ";
2227 LyXAlignment const curAlign = params_.align();
2229 if (curAlign == layout_->align)
2233 case LYX_ALIGN_NONE:
2234 case LYX_ALIGN_BLOCK:
2235 case LYX_ALIGN_LAYOUT:
2236 case LYX_ALIGN_SPECIAL:
2237 case LYX_ALIGN_DECIMAL:
2239 case LYX_ALIGN_LEFT:
2240 case LYX_ALIGN_RIGHT:
2241 case LYX_ALIGN_CENTER:
2242 if (runparams.moving_arg) {
2249 string const begin_tag = "\\begin";
2250 InsetCode code = ownerCode();
2251 bool const lastpar = runparams.isLastPar;
2252 // RTL in classic (PDF)LaTeX (without the Bidi package)
2253 // Luabibdi (used by LuaTeX) behaves like classic
2254 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2255 && !runparams.useBidiPackage();
2258 case LYX_ALIGN_NONE:
2259 case LYX_ALIGN_BLOCK:
2260 case LYX_ALIGN_LAYOUT:
2261 case LYX_ALIGN_SPECIAL:
2262 case LYX_ALIGN_DECIMAL:
2264 case LYX_ALIGN_LEFT: {
2266 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2267 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2269 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2271 } case LYX_ALIGN_RIGHT: {
2273 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2274 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2276 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2278 } case LYX_ALIGN_CENTER: {
2279 corrected_env(os, begin_tag, "center", code, lastpar, column);
2288 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2289 otexstream & os, OutputParams const & runparams) const
2291 LyXAlignment const curAlign = params_.align();
2293 if (curAlign == layout_->align)
2297 case LYX_ALIGN_NONE:
2298 case LYX_ALIGN_BLOCK:
2299 case LYX_ALIGN_LAYOUT:
2300 case LYX_ALIGN_SPECIAL:
2301 case LYX_ALIGN_DECIMAL:
2303 case LYX_ALIGN_LEFT:
2304 case LYX_ALIGN_RIGHT:
2305 case LYX_ALIGN_CENTER:
2306 if (runparams.moving_arg)
2311 bool output = false;
2313 string const end_tag = "\\par\\end";
2314 InsetCode code = ownerCode();
2315 bool const lastpar = runparams.isLastPar;
2316 // RTL in classic (PDF)LaTeX (without the Bidi package)
2317 // Luabibdi (used by LuaTeX) behaves like classic
2318 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2319 && !runparams.useBidiPackage();
2322 case LYX_ALIGN_NONE:
2323 case LYX_ALIGN_BLOCK:
2324 case LYX_ALIGN_LAYOUT:
2325 case LYX_ALIGN_SPECIAL:
2326 case LYX_ALIGN_DECIMAL:
2328 case LYX_ALIGN_LEFT: {
2330 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2331 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2333 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2335 } case LYX_ALIGN_RIGHT: {
2337 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2338 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2340 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2342 } case LYX_ALIGN_CENTER: {
2343 corrected_env(os, end_tag, "center", code, lastpar, col);
2348 return output || lastpar;
2352 // This one spits out the text of the paragraph
2353 void Paragraph::latex(BufferParams const & bparams,
2354 Font const & outerfont,
2356 OutputParams const & runparams,
2357 int start_pos, int end_pos, bool force) const
2359 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2361 // FIXME This check should not be needed. Perhaps issue an
2362 // error if it triggers.
2363 Layout const & style = inInset().forcePlainLayout() ?
2364 bparams.documentClass().plainLayout() : *d->layout_;
2366 if (!force && style.inpreamble)
2369 bool const allowcust = allowParagraphCustomization();
2371 // Current base font for all inherited font changes, without any
2372 // change caused by an individual character, except for the language:
2373 // It is set to the language of the first character.
2374 // As long as we are in the label, this font is the base font of the
2375 // label. Before the first body character it is set to the base font
2379 // If there is an open font-encoding changing command (script wrapper),
2380 // alien_script is set to its name
2381 string alien_script;
2384 // Maybe we have to create a optional argument.
2385 pos_type body_pos = beginOfBody();
2386 unsigned int column = 0;
2388 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2389 Font const real_outerfont = (!inInset().inheritFont()
2390 && runparams.local_font != nullptr)
2391 ? Font(runparams.local_font->fontInfo()) : outerfont;
2394 // the optional argument is kept in curly brackets in
2395 // case it contains a ']'
2396 // This is not strictly needed, but if this is changed it
2397 // would be a file format change, and tex2lyx would need
2398 // to be adjusted, since it unconditionally removes the
2399 // braces when it parses \item.
2402 basefont = getLabelFont(bparams, real_outerfont);
2404 basefont = getLayoutFont(bparams, real_outerfont);
2407 // Which font is currently active?
2408 Font running_font(basefont);
2409 // Do we have an open font change?
2410 bool open_font = false;
2412 Change runningChange = Change(Change::UNCHANGED);
2414 Encoding const * const prev_encoding = runparams.encoding;
2416 os.texrow().start(id(), 0);
2418 // if the paragraph is empty, the loop will not be entered at all
2420 // For InTitle commands, we have already opened a group
2421 // in output_latex::TeXOnePar.
2422 if (style.isCommand() && !style.intitle) {
2426 if (!style.leftdelim().empty()) {
2427 os << style.leftdelim();
2428 column += style.leftdelim().size();
2431 column += d->startTeXParParams(bparams, os, runparams);
2434 // Whether a \par can be issued for insets typeset inline with text.
2435 // Yes if greater than 0. This has to be static.
2436 THREAD_LOCAL_STATIC int parInline = 0;
2438 for (pos_type i = 0; i < size(); ++i) {
2439 // First char in paragraph or after label?
2440 if (i == body_pos) {
2443 bool needPar = false;
2444 column += running_font.latexWriteEndChanges(
2445 os, bparams, runparams,
2446 basefont, basefont, needPar);
2449 basefont = getLayoutFont(bparams, real_outerfont);
2450 running_font = basefont;
2452 column += Changes::latexMarkChange(os, bparams,
2453 runningChange, Change(Change::UNCHANGED),
2455 runningChange = Change(Change::UNCHANGED);
2460 // For InTitle commands, we have already opened a group
2461 // in output_latex::TeXOnePar.
2462 if (style.isCommand() && !style.intitle) {
2467 if (!style.leftdelim().empty()) {
2468 os << style.leftdelim();
2469 column += style.leftdelim().size();
2473 column += d->startTeXParParams(bparams, os,
2477 runparams.wasDisplayMath = runparams.inDisplayMath;
2478 runparams.inDisplayMath = false;
2479 bool deleted_display_math = false;
2480 Change const & change = runparams.inDeletedInset
2481 ? runparams.changeOfDeletedInset : lookupChange(i);
2483 char_type const c = d->text_[i];
2485 // Check whether a display math inset follows
2487 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2489 runparams.ctObject = getInset(i)->CtObject(runparams);
2491 InsetMath const * im = getInset(i)->asInsetMath();
2492 if (im && im->asHullInset()
2493 && im->asHullInset()->outerDisplay()) {
2494 runparams.inDisplayMath = true;
2495 // runparams.inDeletedInset will be set by
2496 // latexInset later, but we need this info
2497 // before it is called. On the other hand, we
2498 // cannot set it here because it is a counter.
2499 deleted_display_math = isDeleted(i);
2501 if (bparams.output_changes && deleted_display_math
2502 && runningChange == change
2503 && change.type == Change::DELETED
2504 && !os.afterParbreak()) {
2505 // A display math in the same paragraph follows.
2506 // We have to close and then reopen \lyxdeleted,
2507 // otherwise the math will be shifted up.
2508 OutputParams rp = runparams;
2510 bool needPar = false;
2511 column += running_font.latexWriteEndChanges(
2512 os, bparams, rp, basefont,
2516 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2517 : getLayoutFont(bparams, real_outerfont);
2518 running_font = basefont;
2519 column += Changes::latexMarkChange(os, bparams,
2520 Change(Change::INSERTED), change, rp);
2524 if (bparams.output_changes && runningChange != change) {
2525 if (!alien_script.empty()) {
2528 alien_script.clear();
2531 bool needPar = false;
2532 column += running_font.latexWriteEndChanges(
2533 os, bparams, runparams,
2534 basefont, basefont, needPar);
2537 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2538 : getLayoutFont(bparams, real_outerfont);
2539 running_font = basefont;
2540 column += Changes::latexMarkChange(os, bparams, runningChange,
2542 runningChange = change;
2545 // do not output text which is marked deleted
2546 // if change tracking output is disabled
2547 if (!bparams.output_changes && change.deleted()) {
2553 // Fully instantiated font
2554 Font const current_font = getFont(bparams, i, outerfont);
2556 Font const prev_font = (i > 0) ?
2557 getFont(bparams, i - 1, outerfont)
2560 Font const last_font = running_font;
2561 bool const in_ct_deletion = (bparams.output_changes
2562 && runningChange == change
2563 && change.type == Change::DELETED
2564 && !os.afterParbreak());
2565 bool const non_inherit_inset =
2566 (c == META_INSET && getInset(i) && !getInset(i)->inheritFont());
2568 // Do we need to close the previous font?
2570 ((current_font != running_font
2571 || current_font.language() != running_font.language())
2572 || (non_inherit_inset
2573 && (current_font == prev_font
2574 || current_font.language() == prev_font.language()))))
2576 // ensure there is no open script-wrapper
2577 if (!alien_script.empty()) {
2580 alien_script.clear();
2582 bool needPar = false;
2583 if (in_ct_deletion) {
2584 // We have to close and then reopen \lyxdeleted,
2585 // as strikeout needs to be on lowest level.
2589 column += running_font.latexWriteEndChanges(
2590 os, bparams, runparams, basefont,
2591 (i == body_pos-1) ? basefont : current_font,
2593 if (in_ct_deletion) {
2594 // We have to close and then reopen \lyxdeleted,
2595 // as strikeout needs to be on lowest level.
2596 OutputParams rp = runparams;
2597 column += Changes::latexMarkChange(os, bparams,
2598 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2600 running_font = basefont;
2604 // if necessary, close language environment before opening CJK
2605 string const running_lang = running_font.language()->babel();
2606 string const lang_end_command = lyxrc.language_command_end;
2607 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2608 && !running_lang.empty()
2609 && running_lang == openLanguageName()
2610 && current_font.language()->encoding()->package() == Encoding::CJK) {
2611 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2612 os << from_ascii(end_tag);
2613 column += end_tag.length();
2617 // Switch file encoding if necessary (and allowed)
2618 if (!runparams.pass_thru && !style.pass_thru &&
2619 runparams.encoding->package() != Encoding::none &&
2620 current_font.language()->encoding()->package() != Encoding::none) {
2621 pair<bool, int> const enc_switch =
2622 switchEncoding(os.os(), bparams, runparams,
2623 *(current_font.language()->encoding()));
2624 if (enc_switch.first) {
2625 column += enc_switch.second;
2626 runparams.encoding = current_font.language()->encoding();
2630 // A display math inset inside an ulem command will be output
2631 // as a box of width \linewidth, so we have to either disable
2632 // indentation if the inset starts a paragraph, or start a new
2633 // line to accommodate such box. This has to be done before
2634 // writing any font changing commands.
2635 if (runparams.inDisplayMath && !deleted_display_math
2636 && runparams.inulemcmd) {
2637 if (os.afterParbreak())
2643 // Do we need to change font?
2644 if ((current_font != running_font ||
2645 current_font.language() != running_font.language())
2646 && i != body_pos - 1)
2648 if (in_ct_deletion) {
2649 // We have to close and then reopen \lyxdeleted,
2650 // as strikeout needs to be on lowest level.
2651 bool needPar = false;
2652 OutputParams rp = runparams;
2653 column += running_font.latexWriteEndChanges(
2654 os, bparams, rp, basefont,
2659 otexstringstream ots;
2660 if (!non_inherit_inset) {
2661 column += current_font.latexWriteStartChanges(ots, bparams,
2662 runparams, basefont, last_font);
2664 // Check again for display math in ulem commands as a
2665 // font change may also occur just before a math inset.
2666 if (runparams.inDisplayMath && !deleted_display_math
2667 && runparams.inulemcmd) {
2668 if (os.afterParbreak())
2673 running_font = current_font;
2675 docstring fontchange = ots.str();
2677 // check whether the fontchange ends with a \\textcolor
2678 // modifier and the text starts with a space. If so we
2679 // need to add } in order to prevent \\textcolor from gobbling
2680 // the space (bug 4473).
2681 docstring const last_modifier = rsplit(fontchange, '\\');
2682 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2683 os << from_ascii("{}");
2684 else if (ots.terminateCommand())
2686 if (in_ct_deletion) {
2687 // We have to close and then reopen \lyxdeleted,
2688 // as strikeout needs to be on lowest level.
2689 OutputParams rp = runparams;
2690 column += Changes::latexMarkChange(os, bparams,
2691 Change(Change::UNCHANGED), change, rp);
2695 // FIXME: think about end_pos implementation...
2696 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2697 // FIXME: integrate this case in latexSpecialChar
2698 // Do not print the separation of the optional argument
2699 // if style.pass_thru is false. This works because
2700 // latexSpecialChar ignores spaces if
2701 // style.pass_thru is false.
2702 if (i != body_pos - 1) {
2703 if (d->simpleTeXBlanks(bparams, runparams, os,
2704 i, column, current_font, style)) {
2705 // A surrogate pair was output. We
2706 // must not call latexSpecialChar
2707 // in this iteration, since it would output
2708 // the combining character again.
2715 OutputParams rp = runparams;
2716 rp.free_spacing = style.free_spacing;
2717 rp.local_font = ¤t_font;
2718 rp.intitle = style.intitle;
2720 // Two major modes: LaTeX or plain
2721 // Handle here those cases common to both modes
2722 // and then split to handle the two modes separately.
2723 if (c == META_INSET) {
2724 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2725 // Greyedout notes and, in general, all insets
2726 // with InsetLayout::isDisplay() == false,
2727 // are typeset inline with the text. So, we
2728 // can add a \par to the last paragraph of
2729 // such insets only if nothing else follows.
2730 bool incremented = false;
2731 Inset const * inset = getInset(i);
2732 InsetText const * textinset = inset
2733 ? inset->asInsetText()
2735 if (i + 1 == size() && textinset
2736 && !inset->getLayout().isDisplay()) {
2737 ParagraphList const & pars =
2738 textinset->text().paragraphs();
2739 pit_type const pit = pars.size() - 1;
2740 Font const lastfont =
2741 pit < 0 || pars[pit].empty()
2742 ? pars[pit].getLayoutFont(
2745 : pars[pit].getFont(bparams,
2746 pars[pit].size() - 1,
2748 if (lastfont.fontInfo().size() !=
2749 basefont.fontInfo().size()) {
2754 // We need to restore these after insets with
2755 // inheritFont() false
2756 Font const save_running_font = running_font;
2757 Font const save_basefont = basefont;
2758 d->latexInset(bparams, os, rp, running_font,
2759 basefont, real_outerfont, open_font,
2760 runningChange, style, i, column);
2761 if (non_inherit_inset) {
2762 running_font = save_running_font;
2763 basefont = save_basefont;
2768 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2769 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2770 // Close \lyx*deleted and force its
2771 // reopening (if needed)
2774 runningChange = Change(Change::UNCHANGED);
2775 runparams.ctObject = OutputParams::CT_NORMAL;
2778 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2779 if (!bparams.useNonTeXFonts)
2780 script = Encodings::isKnownScriptChar(c);
2781 if (script != alien_script) {
2782 if (!alien_script.empty()) {
2784 alien_script.clear();
2786 string fontenc = running_font.language()->fontenc(bparams);
2788 && !Encodings::fontencSupportsScript(fontenc, script)) {
2789 column += script.length() + 2;
2790 os << "\\" << script << "{";
2791 alien_script = script;
2795 d->latexSpecialChar(os, bparams, rp, running_font,
2796 alien_script, style, i, end_pos, column);
2797 } catch (EncodingException & e) {
2798 if (runparams.dryrun) {
2799 os << "<" << _("LyX Warning: ")
2800 << _("uncodable character") << " '";
2804 // add location information and throw again.
2812 // Set the encoding to that returned from latexSpecialChar (see
2813 // comment for encoding member in OutputParams.h)
2814 runparams.encoding = rp.encoding;
2816 // Also carry on the info on a closed ulem command for insets
2817 // such as Note that do not produce any output, so that no
2818 // command is ever executed but its opening was recorded.
2819 runparams.inulemcmd = rp.inulemcmd;
2821 // These need to be passed upstream as well
2822 runparams.need_maketitle = rp.need_maketitle;
2823 runparams.have_maketitle = rp.have_maketitle;
2825 // And finally, pass the post_macros upstream
2826 runparams.post_macro = rp.post_macro;
2829 // Close wrapper for alien script
2830 if (!alien_script.empty()) {
2832 alien_script.clear();
2835 // If we have an open font definition, we have to close it
2837 // Make sure that \\par is done with the font of the last
2838 // character if this has another size as the default.
2839 // This is necessary because LaTeX (and LyX on the screen)
2840 // calculates the space between the baselines according
2841 // to this font. (Matthias)
2843 // We must not change the font for the last paragraph
2844 // of non-multipar insets, tabular cells or commands,
2845 // since this produces unwanted whitespace.
2847 Font const font = empty()
2848 ? getLayoutFont(bparams, real_outerfont)
2849 : getFont(bparams, size() - 1, real_outerfont);
2851 InsetText const * textinset = inInset().asInsetText();
2853 bool const maintext = textinset
2854 ? textinset->text().isMainText()
2857 size_t const numpars = textinset
2858 ? textinset->text().paragraphs().size()
2861 bool needPar = false;
2863 if (style.resfont.size() != font.fontInfo().size()
2864 && (!runparams.isLastPar || maintext
2865 || (numpars > 1 && d->ownerCode() != CELL_CODE
2866 && (inInset().getLayout().isDisplay()
2868 && !style.isCommand()) {
2871 #ifdef FIXED_LANGUAGE_END_DETECTION
2873 running_font.latexWriteEndChanges(os, bparams,
2874 runparams, basefont,
2875 next_->getFont(bparams, 0, outerfont),
2878 running_font.latexWriteEndChanges(os, bparams,
2879 runparams, basefont, basefont, needPar);
2882 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2883 //FIXME: there as we start another \selectlanguage with the next paragraph if
2884 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2885 running_font.latexWriteEndChanges(os, bparams, runparams,
2886 basefont, basefont, needPar);
2889 // The \par could not be inserted at the same nesting
2890 // level of the font size change, so do it now.
2891 os << "{\\" << font.latexSize() << "\\par}";
2895 column += Changes::latexMarkChange(os, bparams, runningChange,
2896 Change(Change::UNCHANGED), runparams);
2898 // Needed if there is an optional argument but no contents.
2899 if (body_pos > 0 && body_pos == size()) {
2903 if (!style.rightdelim().empty()) {
2904 os << style.rightdelim();
2905 column += style.rightdelim().size();
2908 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2909 && runparams.encoding != prev_encoding) {
2910 runparams.encoding = prev_encoding;
2911 os << setEncoding(prev_encoding->iconvName());
2914 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2918 bool Paragraph::emptyTag() const
2920 for (pos_type i = 0; i < size(); ++i) {
2921 if (Inset const * inset = getInset(i)) {
2922 InsetCode lyx_code = inset->lyxCode();
2923 // FIXME testing like that is wrong. What is
2925 if (lyx_code != TOC_CODE &&
2926 lyx_code != INCLUDE_CODE &&
2927 lyx_code != GRAPHICS_CODE &&
2928 lyx_code != ERT_CODE &&
2929 lyx_code != LISTINGS_CODE &&
2930 lyx_code != FLOAT_CODE &&
2931 lyx_code != TABULAR_CODE) {
2935 char_type c = d->text_[i];
2936 if (c != ' ' && c != '\t')
2944 string Paragraph::getID(Buffer const &, OutputParams const &)
2947 for (pos_type i = 0; i < size(); ++i) {
2948 if (Inset const * inset = getInset(i)) {
2949 InsetCode lyx_code = inset->lyxCode();
2950 if (lyx_code == LABEL_CODE) {
2951 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2952 docstring const & id = il->getParam("name");
2953 return "id='" + to_utf8(xml::cleanID(id)) + "'";
2961 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
2964 for (i = 0; i < size(); ++i) {
2965 if (Inset const * inset = getInset(i)) {
2966 inset->docbook(xs, runparams);
2968 char_type c = d->text_[i];
2978 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
2982 for (i = 0; i < size(); ++i) {
2983 if (Inset const * inset = getInset(i)) {
2984 inset->xhtml(xs, runparams);
2986 char_type c = d->text_[i];
2996 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2999 pos_type size = text_.size();
3000 for (pos_type i = initial; i < size; ++i) {
3001 Font font = owner_->getFont(buf.params(), i, outerfont);
3002 if (text_[i] == META_INSET)
3004 if (i != initial && font != font_old)
3015 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3016 vector<xml::EndFontTag> & tagsToClose,
3017 bool & flag, FontState curstate, xml::FontTypes type)
3019 if (curstate == FONT_ON) {
3020 tagsToOpen.push_back(docbookStartFontTag(type));
3023 tagsToClose.push_back(docbookEndFontTag(type));
3028 class OptionalFontType {
3033 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3034 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3037 OptionalFontType fontShapeToXml(FontShape fs)
3041 return {xml::FT_ITALIC};
3043 return {xml::FT_SLANTED};
3044 case SMALLCAPS_SHAPE:
3045 return {xml::FT_SMALLCAPS};
3050 // the other tags are for internal use
3056 OptionalFontType fontFamilyToXml(FontFamily fm)
3060 return {xml::FT_ROMAN};
3062 return {xml::FT_SANS};
3063 case TYPEWRITER_FAMILY:
3064 return {xml::FT_TYPE};
3065 case INHERIT_FAMILY:
3068 // the other tags are for internal use
3074 OptionalFontType fontSizeToXml(FontSize fs)
3078 return {xml::FT_SIZE_TINY};
3080 return {xml::FT_SIZE_SCRIPT};
3082 return {xml::FT_SIZE_FOOTNOTE};
3084 return {xml::FT_SIZE_SMALL};
3086 return {xml::FT_SIZE_LARGE};
3088 return {xml::FT_SIZE_LARGER};
3090 return {xml::FT_SIZE_LARGEST};
3092 return {xml::FT_SIZE_HUGE};
3094 return {xml::FT_SIZE_HUGER};
3096 return {xml::FT_SIZE_INCREASE};
3098 return {xml::FT_SIZE_DECREASE};
3103 // the other tags are for internal use
3109 struct DocBookFontState
3111 FontShape curr_fs = INHERIT_SHAPE;
3112 FontFamily curr_fam = INHERIT_FAMILY;
3113 FontSize curr_size = INHERIT_SIZE;
3115 // track whether we have opened these tags
3116 bool emph_flag = false;
3117 bool bold_flag = false;
3118 bool noun_flag = false;
3119 bool ubar_flag = false;
3120 bool dbar_flag = false;
3121 bool sout_flag = false;
3122 bool xout_flag = false;
3123 bool wave_flag = false;
3125 bool shap_flag = false;
3127 bool faml_flag = false;
3129 bool size_flag = false;
3132 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3134 std::string const & default_family,
3135 DocBookFontState & fs)
3137 vector<xml::FontTag> tagsToOpen;
3138 vector<xml::EndFontTag> tagsToClose;
3141 FontState curstate = font.fontInfo().emph();
3142 if (font_old.emph() != curstate)
3143 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3146 curstate = font.fontInfo().noun();
3147 if (font_old.noun() != curstate)
3148 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3151 curstate = font.fontInfo().underbar();
3152 if (font_old.underbar() != curstate)
3153 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3156 curstate = font.fontInfo().strikeout();
3157 if (font_old.strikeout() != curstate)
3158 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3161 curstate = font.fontInfo().xout();
3162 if (font_old.xout() != curstate)
3163 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3166 curstate = font.fontInfo().uuline();
3167 if (font_old.uuline() != curstate)
3168 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3171 curstate = font.fontInfo().uwave();
3172 if (font_old.uwave() != curstate)
3173 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3176 // a little hackish, but allows us to reuse what we have.
3177 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3178 if (font_old.series() != font.fontInfo().series())
3179 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3182 fs.curr_fs = font.fontInfo().shape();
3183 FontShape old_fs = font_old.shape();
3184 if (old_fs != fs.curr_fs) {
3186 OptionalFontType tag = fontShapeToXml(old_fs);
3188 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3189 fs.shap_flag = false;
3192 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3194 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3198 fs.curr_fam = font.fontInfo().family();
3199 FontFamily old_fam = font_old.family();
3200 if (old_fam != fs.curr_fam) {
3202 OptionalFontType tag = fontFamilyToXml(old_fam);
3204 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3205 fs.faml_flag = false;
3207 switch (fs.curr_fam) {
3209 // we will treat a "default" font family as roman, since we have
3210 // no other idea what to do.
3211 if (default_family != "rmdefault" && default_family != "default") {
3212 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3213 fs.faml_flag = true;
3217 if (default_family != "sfdefault") {
3218 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3219 fs.faml_flag = true;
3222 case TYPEWRITER_FAMILY:
3223 if (default_family != "ttdefault") {
3224 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3225 fs.faml_flag = true;
3228 case INHERIT_FAMILY:
3231 // the other tags are for internal use
3238 fs.curr_size = font.fontInfo().size();
3239 FontSize old_size = font_old.size();
3240 if (old_size != fs.curr_size) {
3242 OptionalFontType tag = fontSizeToXml(old_size);
3244 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3245 fs.size_flag = false;
3248 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3249 if (tag.has_value) {
3250 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3251 fs.size_flag = true;
3255 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3258 } // anonymous namespace
3261 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3263 OutputParams const & runparams,
3264 Font const & outerfont,
3265 bool start_paragraph, bool close_paragraph,
3266 pos_type initial) const
3268 // track whether we have opened these tags
3269 DocBookFontState fs;
3271 if (start_paragraph)
3272 xs.startDivision(allowEmpty());
3274 Layout const & style = *d->layout_;
3276 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3278 string const default_family =
3279 buf.masterBuffer()->params().fonts_default_family;
3281 vector<xml::FontTag> tagsToOpen;
3282 vector<xml::EndFontTag> tagsToClose;
3284 // parsing main loop
3285 for (pos_type i = initial; i < size(); ++i) {
3286 // let's not show deleted material in the output
3290 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3292 // Determine which tags should be opened or closed.
3293 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3296 // Other such tags? What about the other text ranges?
3298 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3299 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3300 for (; cit != cen; ++cit)
3303 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3304 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3305 for (; sit != sen; ++sit)
3308 tagsToClose.clear();
3311 if (Inset const * inset = getInset(i)) {
3312 if (!runparams.for_toc || inset->isInToc()) {
3313 OutputParams np = runparams;
3314 np.local_font = &font;
3315 // If the paragraph has size 1, then we are in the "special
3316 // case" where we do not output the containing paragraph info.
3317 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3318 // of that brittle logic is passed to this function through open_par.
3319 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3320 np.docbook_in_par = true;
3321 inset->docbook(xs, np);
3324 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3327 font_old = font.fontInfo();
3330 // FIXME, this code is just imported from XHTML
3331 // I'm worried about what happens if a branch, say, is itself
3332 // wrapped in some font stuff. I think that will not work.
3334 if (runparams.docbook_in_listing)
3336 if (close_paragraph)
3343 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3344 vector<xml::EndFontTag> & tagsToClose,
3345 bool & flag, FontState curstate, xml::FontTypes type)
3347 if (curstate == FONT_ON) {
3348 tagsToOpen.push_back(xhtmlStartFontTag(type));
3351 tagsToClose.push_back(xhtmlEndFontTag(type));
3356 } // anonymous namespace
3359 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3361 OutputParams const & runparams,
3362 Font const & outerfont,
3363 bool start_paragraph, bool close_paragraph,
3364 pos_type initial) const
3368 // track whether we have opened these tags
3369 bool emph_flag = false;
3370 bool bold_flag = false;
3371 bool noun_flag = false;
3372 bool ubar_flag = false;
3373 bool dbar_flag = false;
3374 bool sout_flag = false;
3375 bool xout_flag = false;
3376 bool wave_flag = false;
3378 bool shap_flag = false;
3380 bool faml_flag = false;
3382 bool size_flag = false;
3384 Layout const & style = *d->layout_;
3386 if (start_paragraph)
3387 xs.startDivision(allowEmpty());
3390 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3392 FontShape curr_fs = INHERIT_SHAPE;
3393 FontFamily curr_fam = INHERIT_FAMILY;
3394 FontSize curr_size = INHERIT_SIZE;
3396 string const default_family =
3397 buf.masterBuffer()->params().fonts_default_family;
3399 vector<xml::FontTag> tagsToOpen;
3400 vector<xml::EndFontTag> tagsToClose;
3402 // parsing main loop
3403 for (pos_type i = initial; i < size(); ++i) {
3404 // let's not show deleted material in the output
3408 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3411 FontState curstate = font.fontInfo().emph();
3412 if (font_old.emph() != curstate)
3413 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3416 curstate = font.fontInfo().noun();
3417 if (font_old.noun() != curstate)
3418 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3421 curstate = font.fontInfo().underbar();
3422 if (font_old.underbar() != curstate)
3423 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3426 curstate = font.fontInfo().strikeout();
3427 if (font_old.strikeout() != curstate)
3428 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3431 curstate = font.fontInfo().xout();
3432 if (font_old.xout() != curstate)
3433 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3436 curstate = font.fontInfo().uuline();
3437 if (font_old.uuline() != curstate)
3438 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3441 curstate = font.fontInfo().uwave();
3442 if (font_old.uwave() != curstate)
3443 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3446 // a little hackish, but allows us to reuse what we have.
3447 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3448 if (font_old.series() != font.fontInfo().series())
3449 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3452 curr_fs = font.fontInfo().shape();
3453 FontShape old_fs = font_old.shape();
3454 if (old_fs != curr_fs) {
3458 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3461 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3463 case SMALLCAPS_SHAPE:
3464 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3470 // the other tags are for internal use
3478 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3482 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3485 case SMALLCAPS_SHAPE:
3486 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3493 // the other tags are for internal use
3500 curr_fam = font.fontInfo().family();
3501 FontFamily old_fam = font_old.family();
3502 if (old_fam != curr_fam) {
3506 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3509 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3511 case TYPEWRITER_FAMILY:
3512 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3514 case INHERIT_FAMILY:
3517 // the other tags are for internal use
3525 // we will treat a "default" font family as roman, since we have
3526 // no other idea what to do.
3527 if (default_family != "rmdefault" && default_family != "default") {
3528 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3533 if (default_family != "sfdefault") {
3534 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3538 case TYPEWRITER_FAMILY:
3539 if (default_family != "ttdefault") {
3540 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3544 case INHERIT_FAMILY:
3547 // the other tags are for internal use
3554 curr_size = font.fontInfo().size();
3555 FontSize old_size = font_old.size();
3556 if (old_size != curr_size) {
3560 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3563 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3566 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3569 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3572 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3575 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3578 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3581 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3584 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3587 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3590 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3596 // the other tags are for internal use
3602 switch (curr_size) {
3604 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3608 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3612 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3616 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3620 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3624 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3628 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3632 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3636 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3640 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3644 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3651 // the other tags are for internal use
3658 // Other such tags? What about the other text ranges?
3660 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3661 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3662 for (; cit != cen; ++cit)
3665 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3666 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3667 for (; sit != sen; ++sit)
3670 tagsToClose.clear();
3673 Inset const * inset = getInset(i);
3675 if (!runparams.for_toc || inset->isInToc()) {
3676 OutputParams np = runparams;
3677 np.local_font = &font;
3678 // If the paragraph has size 1, then we are in the "special
3679 // case" where we do not output the containing paragraph info
3680 if (!inset->getLayout().htmlisblock() && size() != 1)
3681 np.html_in_par = true;
3682 retval += inset->xhtml(xs, np);
3685 char_type c = getUChar(buf.masterBuffer()->params(),
3687 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3688 xs << XMLStream::ESCAPE_NONE << " ";
3692 font_old = font.fontInfo();
3696 // I'm worried about what happens if a branch, say, is itself
3697 // wrapped in some font stuff. I think that will not work.
3699 if (close_paragraph)
3706 bool Paragraph::isHfill(pos_type pos) const
3708 Inset const * inset = getInset(pos);
3709 return inset && inset->isHfill();
3713 bool Paragraph::isNewline(pos_type pos) const
3715 // U+2028 LINE SEPARATOR
3716 // U+2029 PARAGRAPH SEPARATOR
3717 char_type const c = d->text_[pos];
3718 if (c == 0x2028 || c == 0x2029)
3720 Inset const * inset = getInset(pos);
3721 return inset && inset->lyxCode() == NEWLINE_CODE;
3725 bool Paragraph::isEnvSeparator(pos_type pos) const
3727 Inset const * inset = getInset(pos);
3728 return inset && inset->lyxCode() == SEPARATOR_CODE;
3732 bool Paragraph::isLineSeparator(pos_type pos) const
3734 char_type const c = d->text_[pos];
3735 if (isLineSeparatorChar(c))
3737 Inset const * inset = getInset(pos);
3738 return inset && inset->isLineSeparator();
3742 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3746 if (ignore_deleted && isDeleted(pos))
3748 if (Inset const * inset = getInset(pos))
3749 return !inset->isLetter();
3750 // if we have a hard hyphen (no en- or emdash) or apostrophe
3751 // we pass this to the spell checker
3752 // FIXME: this method is subject to change, visit
3753 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3754 // to get an impression how complex this is.
3755 if (isHardHyphenOrApostrophe(pos))
3757 char_type const c = d->text_[pos];
3758 // We want to pass the escape chars to the spellchecker
3759 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3760 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3764 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3766 pos_type const psize = size();
3769 char_type const c = d->text_[pos];
3770 if (c != '-' && c != '\'')
3772 int nextpos = pos + 1;
3773 int prevpos = pos > 0 ? pos - 1 : 0;
3774 if ((nextpos == psize || isSpace(nextpos))
3775 && (pos == 0 || isSpace(prevpos)))
3781 bool Paragraph::needsCProtection(bool const fragile) const
3783 // first check the layout of the paragraph, but only in insets
3784 InsetText const * textinset = inInset().asInsetText();
3785 bool const maintext = textinset
3786 ? textinset->text().isMainText()
3789 if (!maintext && layout().needcprotect) {
3790 // Environments need cprotection regardless the content
3791 if (layout().latextype == LATEX_ENVIRONMENT)
3794 // Commands need cprotection if they contain specific chars
3795 int const nchars_escape = 9;
3796 static char_type const chars_escape[nchars_escape] = {
3797 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3799 docstring const pars = asString();
3800 for (int k = 0; k < nchars_escape; k++) {
3801 if (contains(pars, chars_escape[k]))
3806 // now check whether we have insets that need cprotection
3807 pos_type size = pos_type(d->text_.size());
3808 for (pos_type i = 0; i < size; ++i) {
3811 Inset const * ins = getInset(i);
3812 if (ins->needsCProtection(maintext, fragile))
3814 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3815 // Environments need cprotection regardless the content
3817 // Now check math environments
3818 InsetMath const * im = getInset(i)->asInsetMath();
3819 if (!im || im->cell(0).empty())
3821 switch(im->cell(0)[0]->lyxCode()) {
3822 case MATH_AMSARRAY_CODE:
3823 case MATH_SUBSTACK_CODE:
3825 case MATH_XYMATRIX_CODE:
3826 // these need cprotection
3837 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3839 return d->speller_state_.getRange(pos);
3843 bool Paragraph::isChar(pos_type pos) const
3845 if (Inset const * inset = getInset(pos))
3846 return inset->isChar();
3847 char_type const c = d->text_[pos];
3848 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3852 bool Paragraph::isSpace(pos_type pos) const
3854 if (Inset const * inset = getInset(pos))
3855 return inset->isSpace();
3856 char_type const c = d->text_[pos];
3857 return lyx::isSpace(c);
3862 Paragraph::getParLanguage(BufferParams const & bparams) const
3865 return getFirstFontSettings(bparams).language();
3866 // FIXME: we should check the prev par as well (Lgb)
3867 return bparams.language;
3871 bool Paragraph::isRTL(BufferParams const & bparams) const
3873 return getParLanguage(bparams)->rightToLeft()
3874 && !inInset().getLayout().forceLTR();
3878 void Paragraph::changeLanguage(BufferParams const & bparams,
3879 Language const * from, Language const * to)
3881 // change language including dummy font change at the end
3882 for (pos_type i = 0; i <= size(); ++i) {
3883 Font font = getFontSettings(bparams, i);
3884 if (font.language() == from) {
3885 font.setLanguage(to);
3887 d->requestSpellCheck(i);
3893 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3895 Language const * doc_language = bparams.language;
3896 for (auto const & f : d->fontlist_)
3897 if (f.font().language() != ignore_language &&
3898 f.font().language() != latex_language &&
3899 f.font().language() != doc_language)
3905 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3907 for (auto const & f : d->fontlist_) {
3908 Language const * lang = f.font().language();
3909 if (lang != ignore_language &&
3910 lang != latex_language)
3916 docstring Paragraph::asString(int options) const
3918 return asString(0, size(), options);
3922 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3924 odocstringstream os;
3927 && options & AS_STR_LABEL
3928 && !d->params_.labelString().empty())
3929 os << d->params_.labelString() << ' ';
3931 for (pos_type i = beg; i < end; ++i) {
3932 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3934 char_type const c = d->text_[i];
3935 if (isPrintable(c) || c == '\t'
3936 || (c == '\n' && (options & AS_STR_NEWLINES)))
3938 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3939 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3940 LASSERT(runparams != nullptr, return docstring());
3941 getInset(i)->plaintext(os, *runparams);
3943 getInset(i)->toString(os);
3952 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3953 bool const shorten, bool const label) const
3955 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3956 if (label && !labelString().empty())
3957 os += labelString() + ' ';
3958 if (!layout().isTocCaption())
3960 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3963 char_type const c = d->text_[i];
3966 else if (c == META_INSET)
3967 getInset(i)->forOutliner(os, tmplen, false);
3970 Text::shortenForOutliner(os, maxlen);
3974 void Paragraph::setInsetOwner(Inset const * inset)
3976 d->inset_owner_ = inset;
3980 int Paragraph::id() const
3986 void Paragraph::setId(int id)
3992 Layout const & Paragraph::layout() const
3998 void Paragraph::setLayout(Layout const & layout)
4000 d->layout_ = &layout;
4004 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4006 setLayout(tc.defaultLayout());
4010 void Paragraph::setPlainLayout(DocumentClass const & tc)
4012 setLayout(tc.plainLayout());
4016 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4018 if (usePlainLayout())
4019 setPlainLayout(tclass);
4021 setDefaultLayout(tclass);
4025 Inset const & Paragraph::inInset() const
4027 LBUFERR(d->inset_owner_);
4028 return *d->inset_owner_;
4032 ParagraphParameters & Paragraph::params()
4038 ParagraphParameters const & Paragraph::params() const
4044 bool Paragraph::isFreeSpacing() const
4046 if (d->layout_->free_spacing)
4048 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4052 bool Paragraph::allowEmpty() const
4054 if (d->layout_->keepempty)
4056 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4060 bool Paragraph::brokenBiblio() const
4062 // There is a problem if there is no bibitem at position 0 in
4063 // paragraphs that need one, if there is another bibitem in the
4064 // paragraph or if this paragraph is not supposed to have
4065 // a bibitem inset at all.
4066 return ((d->layout_->labeltype == LABEL_BIBLIO
4067 && (d->insetlist_.find(BIBITEM_CODE) != 0
4068 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4069 || (d->layout_->labeltype != LABEL_BIBLIO
4070 && d->insetlist_.find(BIBITEM_CODE) != -1));
4074 int Paragraph::fixBiblio(Buffer const & buffer)
4076 // FIXME: when there was already an inset at 0, the return value is 1,
4077 // which does not tell whether another inset has been removed; the
4078 // cursor cannot be correctly updated.
4080 bool const track_changes = buffer.params().track_changes;
4081 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4083 // The case where paragraph is not BIBLIO
4084 if (d->layout_->labeltype != LABEL_BIBLIO) {
4085 if (bibitem_pos == -1)
4086 // No InsetBibitem => OK
4088 // There is an InsetBibitem: remove it!
4089 d->insetlist_.release(bibitem_pos);
4090 eraseChar(bibitem_pos, track_changes);
4091 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4094 bool const hasbibitem0 = bibitem_pos == 0;
4096 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4097 // There was an InsetBibitem at pos 0,
4098 // and no other one => OK
4099 if (bibitem_pos == -1)
4101 // there is a bibitem at the 0 position, but since
4102 // there is a second one, we copy the second on the
4103 // first. We're assuming there are at most two of
4104 // these, which there should be.
4105 // FIXME: why does it make sense to do that rather
4106 // than keep the first? (JMarc)
4107 Inset * inset = releaseInset(bibitem_pos);
4108 d->insetlist_.begin()->inset = inset;
4109 // This needs to be done to update the counter (#8499)
4110 buffer.updateBuffer();
4111 return -bibitem_pos;
4114 // We need to create an inset at the beginning
4115 Inset * inset = nullptr;
4116 if (bibitem_pos > 0) {
4117 // there was one somewhere in the paragraph, let's move it
4118 inset = d->insetlist_.release(bibitem_pos);
4119 eraseChar(bibitem_pos, track_changes);
4122 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4123 InsetCommandParams(BIBITEM_CODE));
4125 Font font(inherit_font, buffer.params().language);
4126 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4127 : Change::UNCHANGED));
4129 // This is needed to get the counters right
4130 buffer.updateBuffer();
4135 void Paragraph::checkAuthors(AuthorList const & authorList)
4137 d->changes_.checkAuthors(authorList);
4141 bool Paragraph::isChanged(pos_type pos) const
4143 return lookupChange(pos).changed();
4147 bool Paragraph::isInserted(pos_type pos) const
4149 return lookupChange(pos).inserted();
4153 bool Paragraph::isDeleted(pos_type pos) const
4155 return lookupChange(pos).deleted();
4159 InsetList const & Paragraph::insetList() const
4161 return d->insetlist_;
4165 void Paragraph::setInsetBuffers(Buffer & b)
4167 d->insetlist_.setBuffer(b);
4171 void Paragraph::resetBuffer()
4173 d->insetlist_.resetBuffer();
4177 Inset * Paragraph::releaseInset(pos_type pos)
4179 Inset * inset = d->insetlist_.release(pos);
4180 /// does not honour change tracking!
4181 eraseChar(pos, false);
4186 Inset * Paragraph::getInset(pos_type pos)
4188 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4189 ? d->insetlist_.get(pos) : nullptr;
4193 Inset const * Paragraph::getInset(pos_type pos) const
4195 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4196 ? d->insetlist_.get(pos) : nullptr;
4200 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4201 pos_type & right, TextCase action)
4203 // process sequences of modified characters; in change
4204 // tracking mode, this approach results in much better
4205 // usability than changing case on a char-by-char basis
4206 // We also need to track the current font, since font
4207 // changes within sequences can occur.
4208 vector<pair<char_type, Font> > changes;
4210 bool const trackChanges = bparams.track_changes;
4212 bool capitalize = true;
4214 for (; pos < right; ++pos) {
4215 char_type oldChar = d->text_[pos];
4216 char_type newChar = oldChar;
4218 // ignore insets and don't play with deleted text!
4219 if (oldChar != META_INSET && !isDeleted(pos)) {
4221 case text_lowercase:
4222 newChar = lowercase(oldChar);
4224 case text_capitalization:
4226 newChar = uppercase(oldChar);
4230 case text_uppercase:
4231 newChar = uppercase(oldChar);
4236 if (isWordSeparator(pos) || isDeleted(pos)) {
4237 // permit capitalization again
4241 if (oldChar != newChar) {
4242 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4243 if (pos != right - 1)
4245 // step behind the changing area
4249 int erasePos = pos - changes.size();
4250 for (size_t i = 0; i < changes.size(); i++) {
4251 insertChar(pos, changes[i].first,
4254 if (!eraseChar(erasePos, trackChanges)) {
4257 ++right; // expand selection
4265 int Paragraph::find(docstring const & str, bool cs, bool mw,
4266 pos_type start_pos, bool del) const
4268 pos_type pos = start_pos;
4269 int const strsize = str.length();
4271 pos_type const parsize = d->text_.size();
4272 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4273 // Ignore "invisible" letters such as ligature breaks
4274 // and hyphenation chars while searching
4275 while (pos < parsize - 1 && isInset(pos)) {
4276 odocstringstream os;
4277 getInset(pos)->toString(os);
4278 if (!getInset(pos)->isLetter() || !os.str().empty())
4282 if (cs && str[i] != d->text_[pos])
4284 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4286 if (!del && isDeleted(pos))
4293 // if necessary, check whether string matches word
4295 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4298 && !isWordSeparator(pos))
4302 return pos - start_pos;
4306 char_type Paragraph::getChar(pos_type pos) const
4308 return d->text_[pos];
4312 pos_type Paragraph::size() const
4314 return d->text_.size();
4318 bool Paragraph::empty() const
4320 return d->text_.empty();
4324 bool Paragraph::isInset(pos_type pos) const
4326 return d->text_[pos] == META_INSET;
4330 bool Paragraph::isSeparator(pos_type pos) const
4332 //FIXME: Are we sure this can be the only separator?
4333 return d->text_[pos] == ' ';
4337 void Paragraph::deregisterWords()
4339 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4340 Private::LangWordsMap::const_iterator ite = d->words_.end();
4341 for (; itl != ite; ++itl) {
4342 WordList & wl = theWordList(itl->first);
4343 Private::Words::const_iterator it = (itl->second).begin();
4344 Private::Words::const_iterator et = (itl->second).end();
4345 for (; it != et; ++it)
4352 void Paragraph::locateWord(pos_type & from, pos_type & to,
4353 word_location const loc, bool const ignore_deleted) const
4356 case WHOLE_WORD_STRICT:
4357 if (from == 0 || from == size()
4358 || isWordSeparator(from, ignore_deleted)
4359 || isWordSeparator(from - 1, ignore_deleted)) {
4366 // If we are already at the beginning of a word, do nothing
4367 if (!from || isWordSeparator(from - 1, ignore_deleted))
4372 // always move the cursor to the beginning of previous word
4373 while (from && !isWordSeparator(from - 1, ignore_deleted))
4377 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4380 // no need to move the 'from' cursor
4384 while (to < size() && !isWordSeparator(to, ignore_deleted))
4389 void Paragraph::collectWords()
4391 for (pos_type pos = 0; pos < size(); ++pos) {
4392 if (isWordSeparator(pos))
4394 pos_type from = pos;
4395 locateWord(from, pos, WHOLE_WORD);
4396 // Work around MSVC warning: The statement
4397 // if (pos < from + lyxrc.completion_minlength)
4398 // triggers a signed vs. unsigned warning.
4399 // I don't know why this happens, it could be a MSVC bug, or
4400 // related to LLP64 (windows) vs. LP64 (unix) programming
4401 // model, or the C++ standard might be ambigous in the section
4402 // defining the "usual arithmetic conversions". However, using
4403 // a temporary variable is safe and works on all compilers.
4404 pos_type const endpos = from + lyxrc.completion_minlength;
4407 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4408 if (cit == d->fontlist_.end())
4410 Language const * lang = cit->font().language();
4411 docstring const word = asString(from, pos, AS_STR_NONE);
4412 d->words_[lang->lang()].insert(word);
4417 void Paragraph::registerWords()
4419 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4420 Private::LangWordsMap::const_iterator ite = d->words_.end();
4421 for (; itl != ite; ++itl) {
4422 WordList & wl = theWordList(itl->first);
4423 Private::Words::const_iterator it = (itl->second).begin();
4424 Private::Words::const_iterator et = (itl->second).end();
4425 for (; it != et; ++it)
4431 void Paragraph::updateWords()
4439 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4441 SkipPositionsIterator begin = skips.begin();
4442 SkipPositions::iterator end = skips.end();
4443 if (pos > 0 && begin < end) {
4445 if (end->last == pos - 1) {
4450 skips.insert(end, FontSpan(pos, pos));
4454 Language * Paragraph::Private::locateSpellRange(
4455 pos_type & from, pos_type & to,
4456 SkipPositions & skips) const
4458 // skip leading white space
4459 while (from < to && owner_->isWordSeparator(from))
4461 // don't check empty range
4464 // get current language
4465 Language * lang = getSpellLanguage(from);
4466 pos_type last = from;
4467 bool samelang = true;
4468 bool sameinset = true;
4469 while (last < to && samelang && sameinset) {
4470 // hop to end of word
4471 while (last < to && !owner_->isWordSeparator(last)) {
4472 if (owner_->getInset(last)) {
4473 appendSkipPosition(skips, last);
4474 } else if (owner_->isDeleted(last)) {
4475 appendSkipPosition(skips, last);
4479 // hop to next word while checking for insets
4480 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4481 if (Inset const * inset = owner_->getInset(last))
4482 sameinset = inset->isChar() && inset->isLetter();
4483 if (sameinset && owner_->isDeleted(last)) {
4484 appendSkipPosition(skips, last);
4489 if (sameinset && last < to) {
4490 // now check for language change
4491 samelang = lang == getSpellLanguage(last);
4494 // if language change detected backstep is needed
4502 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4505 const_cast<Language *>(owner_->getFontSettings(
4506 inset_owner_->buffer().params(), from).language());
4507 if (lang == inset_owner_->buffer().params().language
4508 && !lyxrc.spellchecker_alt_lang.empty()) {
4510 string const lang_variety =
4511 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4512 lang->setCode(lang_code);
4513 lang->setVariety(lang_variety);
4519 void Paragraph::requestSpellCheck(pos_type pos)
4521 d->requestSpellCheck(pos);
4525 bool Paragraph::needsSpellCheck() const
4527 SpellChecker::ChangeNumber speller_change_number = 0;
4528 if (theSpellChecker())
4529 speller_change_number = theSpellChecker()->changeNumber();
4530 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4531 d->speller_state_.needsCompleteRefresh(speller_change_number);
4533 return d->needsSpellCheck();
4537 bool Paragraph::Private::ignoreWord(docstring const & word) const
4539 // Ignore words with digits
4540 // FIXME: make this customizable
4541 // (note that some checkers ignore words with digits by default)
4542 docstring::const_iterator cit = word.begin();
4543 docstring::const_iterator const end = word.end();
4544 for (; cit != end; ++cit) {
4545 if (isNumber((*cit)))
4552 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4553 WordLangTuple & wl, docstring_list & suggestions,
4554 bool do_suggestion, bool check_learned) const
4556 SpellChecker::Result result = SpellChecker::WORD_OK;
4557 SpellChecker * speller = theSpellChecker();
4561 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4564 locateWord(from, to, WHOLE_WORD, true);
4565 if (from == to || from >= size())
4568 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4569 Language * lang = d->getSpellLanguage(from);
4571 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4574 wl = WordLangTuple(word, lang);
4579 if (needsSpellCheck() || check_learned) {
4581 if (!d->ignoreWord(word)) {
4582 bool const trailing_dot = to < size() && d->text_[to] == '.';
4583 result = speller->check(wl);
4584 if (SpellChecker::misspelled(result) && trailing_dot) {
4585 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4586 result = speller->check(wl);
4587 if (!SpellChecker::misspelled(result)) {
4588 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4590 from << ".." << to << "]");
4592 // spell check with dot appended failed too
4593 // restore original word/lang value
4594 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4595 wl = WordLangTuple(word, lang);
4599 if (!SpellChecker::misspelled(result)) {
4600 // area up to the begin of the next word is not misspelled
4601 while (end < size() && isWordSeparator(end))
4604 d->setMisspelled(from, end, result);
4606 result = d->speller_state_.getState(from);
4610 suggestions.clear();
4612 if (SpellChecker::misspelled(result)) {
4613 LYXERR(Debug::GUI, "misspelled word: \"" <<
4615 from << ".." << to << "]");
4617 speller->suggest(wl, suggestions);
4623 void Paragraph::anonymize()
4625 // This is a very crude anonymization for now
4626 for (char_type & c : d->text_)
4627 if (isLetterChar(c) || isNumber(c))
4632 void Paragraph::Private::markMisspelledWords(
4633 pos_type const & first, pos_type const & last,
4634 SpellChecker::Result result,
4635 docstring const & word,
4636 SkipPositions const & skips)
4638 if (!SpellChecker::misspelled(result)) {
4639 setMisspelled(first, last, SpellChecker::WORD_OK);
4643 SpellChecker * speller = theSpellChecker();
4644 // locate and enumerate the error positions
4645 int nerrors = speller->numMisspelledWords();
4647 SkipPositionsIterator it = skips.begin();
4648 SkipPositionsIterator et = skips.end();
4649 for (int index = 0; index < nerrors; ++index) {
4652 speller->misspelledWord(index, wstart, wlen);
4653 /// should not happen if speller supports range checks
4654 if (!wlen) continue;
4655 docstring const misspelled = word.substr(wstart, wlen);
4656 wstart += first + numskipped;
4657 if (snext < wstart) {
4658 /// mark the range of correct spelling
4659 numskipped += countSkips(it, et, wstart);
4660 setMisspelled(snext,
4661 wstart - 1, SpellChecker::WORD_OK);
4663 snext = wstart + wlen;
4664 numskipped += countSkips(it, et, snext);
4665 /// mark the range of misspelling
4666 setMisspelled(wstart, snext, result);
4667 LYXERR(Debug::GUI, "misspelled word: \"" <<
4668 misspelled << "\" [" <<
4669 wstart << ".." << (snext-1) << "]");
4672 if (snext <= last) {
4673 /// mark the range of correct spelling at end
4674 setMisspelled(snext, last, SpellChecker::WORD_OK);
4679 void Paragraph::spellCheck() const
4681 SpellChecker * speller = theSpellChecker();
4682 if (!speller || empty() ||!needsSpellCheck())
4686 d->rangeOfSpellCheck(start, endpos);
4687 if (speller->canCheckParagraph()) {
4688 // loop until we leave the range
4689 for (pos_type first = start; first < endpos; ) {
4690 pos_type last = endpos;
4691 Private::SkipPositions skips;
4692 Language * lang = d->locateSpellRange(first, last, skips);
4693 if (first >= endpos)
4695 // start the spell checker on the unit of meaning
4696 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4697 WordLangTuple wl = WordLangTuple(word, lang);
4698 SpellChecker::Result result = word.size() ?
4699 speller->check(wl) : SpellChecker::WORD_OK;
4700 d->markMisspelledWords(first, last, result, word, skips);
4704 static docstring_list suggestions;
4705 pos_type to = endpos;
4706 while (start < endpos) {
4708 spellCheck(start, to, wl, suggestions, false);
4712 d->readySpellCheck();
4716 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4718 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4719 if (result || pos <= 0 || pos > size())
4721 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4722 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4727 string Paragraph::magicLabel() const
4730 ss << "magicparlabel-" << id();