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() || inset->allowMultiPar())) {
1043 bool closeLanguage = arabtex
1044 || basefont.isRightToLeft() == running_font.isRightToLeft();
1045 InsetText const * textinset = inset->asInsetText();
1046 bool const cprotect = textinset
1047 ? textinset->hasCProtectContent(runparams.moving_arg)
1048 && !textinset->text().isMainText()
1050 unsigned int count = running_font.latexWriteStartChanges(os, bparams,
1051 runparams, basefont,
1055 // if any font properties were closed, update the running_font,
1056 // making sure, however, to leave the language as it was
1058 // FIXME: probably a better way to keep track of the old
1059 // language, than copying the entire font?
1060 Font const copy_font(running_font);
1061 basefont = owner_->getLayoutFont(bparams, outerfont);
1062 running_font = basefont;
1064 running_font.setLanguage(copy_font.language());
1065 // For these, we use switches, so no need to close
1066 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1067 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1068 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1070 runparams.local_font = &basefont;
1074 size_t const previous_row_count = os.texrow().rows();
1077 runparams.lastid = id_;
1078 runparams.lastpos = i;
1079 inset->latex(os, runparams);
1080 } catch (EncodingException & e) {
1081 // add location information and throw again.
1090 if (os.texrow().rows() > previous_row_count) {
1091 os.texrow().start(owner_->id(), i + 1);
1094 column += (unsigned int)(os.os().tellp() - len);
1097 if (owner_->isDeleted(i))
1098 --runparams.inDeletedInset;
1102 void Paragraph::Private::latexSpecialChar(otexstream & os,
1103 BufferParams const & bparams,
1104 OutputParams const & runparams,
1105 Font const & running_font,
1106 string & alien_script,
1107 Layout const & style,
1110 unsigned int & column)
1112 char_type const c = owner_->getUChar(bparams, runparams, i);
1114 if (style.pass_thru || runparams.pass_thru
1115 || contains(style.pass_thru_chars, c)
1116 || contains(runparams.pass_thru_chars, c)) {
1118 Encoding const * const enc = runparams.encoding;
1119 if (enc && !enc->encodable(c))
1120 throw EncodingException(c);
1126 // TIPA uses its own T3 encoding
1127 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1129 // If T1 font encoding is used, use the special
1130 // characters it provides.
1131 // NOTE: Some languages reset the font encoding internally to a
1132 // non-standard font encoding. If we are using such a language,
1133 // we do not output special T1 chars.
1134 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1135 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1136 && latexSpecialT1(c, os, i, column))
1138 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1139 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1140 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1143 // Otherwise, we use what LaTeX provides us.
1146 os << "\\textbackslash" << termcmd;
1150 os << "\\textless" << termcmd;
1154 os << "\\textgreater" << termcmd;
1158 os << "\\textbar" << termcmd;
1163 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1164 (end_pos == -1 || i + 1 < end_pos) &&
1165 text_[i+1] == '-') {
1166 // Prevent "--" becoming an en dash and "---" an em dash.
1167 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1173 os << "\\textquotedbl" << termcmd;
1178 case '%': case '#': case '{':
1186 os << "\\textasciitilde" << termcmd;
1191 os << "\\textasciicircum" << termcmd;
1198 // avoid being mistaken for optional arguments
1206 // Blanks are printed before font switching.
1207 // Sure? I am not! (try nice-latex)
1208 // I am sure it's correct. LyX might be smarter
1209 // in the future, but for now, nothing wrong is
1215 // XeTeX's dash behaviour is determined via a global setting
1216 if (bparams.use_dash_ligatures
1217 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1219 // TODO #10961: && not in inset Flex Code
1220 // TODO #10961: && not in layout LyXCode
1221 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1238 Encoding const & encoding = *(runparams.encoding);
1239 char_type next = '\0';
1240 if (i + 1 < int(text_.size())) {
1241 next = text_[i + 1];
1242 if (Encodings::isCombiningChar(next)) {
1243 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1248 pair<docstring, bool> latex = encoding.latexChar(c);
1249 docstring nextlatex;
1250 bool nexttipas = false;
1251 string nexttipashortcut;
1252 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1253 nextlatex = encoding.latexChar(next).first;
1254 if (runparams.inIPA) {
1255 nexttipashortcut = Encodings::TIPAShortcut(next);
1256 nexttipas = !nexttipashortcut.empty();
1260 if (runparams.inIPA) {
1261 string const tipashortcut = Encodings::TIPAShortcut(c);
1262 if (!tipashortcut.empty()) {
1263 latex.first = from_ascii(tipashortcut);
1264 latex.second = false;
1268 // eventually close "script wrapper" command (see `Paragraph::latex`)
1269 if (!alien_script.empty()
1270 && alien_script != Encodings::isKnownScriptChar(next)) {
1271 column += latex.first.length();
1272 alien_script.clear();
1273 os << latex.first << "}";
1277 && ((!prefixIs(nextlatex, '\\')
1278 && !prefixIs(nextlatex, '{')
1279 && !prefixIs(nextlatex, '}'))
1281 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1283 // Prevent eating of a following space or command corruption by
1284 // following characters
1285 if (next == ' ' || next == '\0') {
1286 column += latex.first.length() + 1;
1287 os << latex.first << "{}";
1289 column += latex.first.length();
1290 os << latex.first << " ";
1293 column += latex.first.length() - 1;
1301 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1302 pos_type i, unsigned int & column)
1308 // In T1 encoding, these characters exist
1309 // but we should avoid ligatures
1310 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1312 os << "\\textcompwordmark" << termcmd;
1319 // soul.sty breaks with \char`\"
1320 os << "\\textquotedbl" << termcmd;
1329 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1330 pos_type i, unsigned int & column)
1332 // TU encoding is currently on par with T1.
1333 return latexSpecialT1(c, os, i, column);
1337 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1338 pos_type /*i*/, unsigned int & column)
1348 os << "\\textvertline" << termcmd;
1357 void Paragraph::Private::validate(LaTeXFeatures & features) const
1359 if (layout_->inpreamble && inset_owner_) {
1360 // FIXME: Using a string stream here circumvents the encoding
1361 // switching machinery of odocstream. Therefore the
1362 // output is wrong if this paragraph contains content
1363 // that needs to switch encoding.
1364 Buffer const & buf = inset_owner_->buffer();
1365 otexstringstream os;
1366 os << layout_->preamble();
1367 size_t const length = os.length();
1368 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1369 buf.getParFromID(owner_->id()).pit(), os,
1370 features.runparams(), string(), 0, -1, true);
1371 if (os.length() > length)
1372 features.addPreambleSnippet(os.release(), true);
1375 if (features.runparams().flavor == OutputParams::HTML
1376 && layout_->htmltitle()) {
1377 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1380 // check the params.
1381 if (!params_.spacing().isDefault())
1382 features.require("setspace");
1385 features.useLayout(layout_->name());
1388 fontlist_.validate(features);
1390 // then the indentation
1391 if (!params_.leftIndent().zero())
1392 features.require("ParagraphLeftIndent");
1395 InsetList::const_iterator icit = insetlist_.begin();
1396 InsetList::const_iterator iend = insetlist_.end();
1397 for (; icit != iend; ++icit) {
1399 features.inDeletedInset(owner_->isDeleted(icit->pos));
1400 if (icit->inset->lyxCode() == FOOT_CODE) {
1401 // FIXME: an item inset would make things much easier.
1402 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1403 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1404 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1405 && (icit->pos < begin_of_body_
1406 || (icit->pos == begin_of_body_
1407 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1408 features.saveNoteEnv("description");
1410 icit->inset->validate(features);
1411 features.inDeletedInset(false);
1412 if (layout_->needprotect &&
1413 icit->inset->lyxCode() == FOOT_CODE)
1414 features.require("NeedLyXFootnoteCode");
1418 // then the contents
1419 BufferParams const bp = features.runparams().is_child
1420 ? features.buffer().masterParams() : features.buffer().params();
1421 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1422 char_type c = text_[i];
1423 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1425 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1426 features.require("textquotedblp");
1427 else if (bp.main_font_encoding() != "T1"
1428 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1429 features.require("textquotedbl");
1430 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1431 // features that depend on the font or input encoding
1432 string feats = ci.textpreamble();
1433 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1434 if (fontenc.empty())
1435 fontenc = features.runparams().main_fontenc;
1436 while (!feats.empty()) {
1438 feats = split(feats, feat, ',');
1439 if (contains(feat, "!=")) {
1440 // a feature that is required except for the spcified
1441 // font or input encodings
1443 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1444 // multiple encodings are separated by semicolon
1445 vector<string> context = getVectorFromString(contexts, ";");
1446 // require feature if the context matches neither current font
1447 // nor input encoding
1448 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1449 && std::find(context.begin(), context.end(),
1450 features.runparams().encoding->name()) == context.end())
1451 features.require(realfeature);
1452 } else if (contains(feat, '=')) {
1453 // a feature that is required only for the spcified
1454 // font or input encodings
1456 string const contexts = split(feat, realfeature, '=');
1457 // multiple encodings are separated by semicolon
1458 vector<string> context = getVectorFromString(contexts, ";");
1459 // require feature if the context matches either current font
1460 // or input encoding
1461 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1462 || std::find(context.begin(), context.end(),
1463 features.runparams().encoding->name()) != context.end())
1464 features.require(realfeature);
1467 } else if (!bp.use_dash_ligatures
1468 && (c == 0x2013 || c == 0x2014)
1469 && bp.useNonTeXFonts
1470 && features.runparams().flavor == OutputParams::XETEX)
1471 // XeTeX's dash behaviour is determined via a global setting
1472 features.require("xetexdashbreakstate");
1473 BufferEncodings::validate(c, features);
1477 /////////////////////////////////////////////////////////////////////
1481 /////////////////////////////////////////////////////////////////////
1484 Layout const emptyParagraphLayout;
1487 Paragraph::Paragraph()
1488 : d(new Paragraph::Private(this, emptyParagraphLayout))
1495 Paragraph::Paragraph(Paragraph const & par)
1496 : itemdepth(par.itemdepth),
1497 d(new Paragraph::Private(*par.d, this))
1503 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1504 : itemdepth(par.itemdepth),
1505 d(new Paragraph::Private(*par.d, this, beg, end))
1511 Paragraph & Paragraph::operator=(Paragraph const & par)
1513 // needed as we will destroy the private part before copying it
1515 itemdepth = par.itemdepth;
1519 d = new Private(*par.d, this);
1526 Paragraph::~Paragraph()
1535 // this shall be called just before every "os << ..." action.
1536 void flushString(ostream & os, docstring & s)
1545 void Paragraph::write(ostream & os, BufferParams const & bparams,
1546 depth_type & dth) const
1548 // The beginning or end of a deeper (i.e. nested) area?
1549 if (dth != d->params_.depth()) {
1550 if (d->params_.depth() > dth) {
1551 while (d->params_.depth() > dth) {
1552 os << "\n\\begin_deeper";
1556 while (d->params_.depth() < dth) {
1557 os << "\n\\end_deeper";
1563 // First write the layout
1564 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1566 d->params_.write(os);
1568 Font font1(inherit_font, bparams.language);
1570 Change running_change = Change(Change::UNCHANGED);
1572 // this string is used as a buffer to avoid repetitive calls
1573 // to to_utf8(), which turn out to be expensive (JMarc)
1574 docstring write_buffer;
1577 for (pos_type i = 0; i <= size(); ++i) {
1579 Change const & change = lookupChange(i);
1580 if (change != running_change)
1581 flushString(os, write_buffer);
1582 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1583 running_change = change;
1588 // Write font changes
1589 Font font2 = getFontSettings(bparams, i);
1590 if (font2 != font1) {
1591 flushString(os, write_buffer);
1592 font2.lyxWriteChanges(font1, os);
1597 char_type const c = d->text_[i];
1600 if (Inset const * inset = getInset(i)) {
1601 flushString(os, write_buffer);
1602 if (inset->directWrite()) {
1603 // international char, let it write
1604 // code directly so it's shorter in
1610 os << "\\begin_inset ";
1612 os << "\n\\end_inset\n\n";
1615 // FIXME This can be removed again once the mystery
1616 // crash has been resolved.
1621 flushString(os, write_buffer);
1622 os << "\n\\backslash\n";
1626 flushString(os, write_buffer);
1627 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1634 if ((column > 70 && c == ' ')
1636 flushString(os, write_buffer);
1640 // this check is to amend a bug. LyX sometimes
1641 // inserts '\0' this could cause problems.
1643 write_buffer.push_back(c);
1645 LYXERR0("NUL char in structure.");
1651 flushString(os, write_buffer);
1652 os << "\n\\end_layout\n";
1653 // FIXME This can be removed again once the mystery
1654 // crash has been resolved.
1659 void Paragraph::validate(LaTeXFeatures & features) const
1661 d->validate(features);
1662 bool fragile = features.runparams().moving_arg;
1663 fragile |= layout().needprotect;
1664 if (inInset().getLayout().isNeedProtect())
1666 if (needsCProtection(fragile))
1667 features.require("cprotect");
1671 void Paragraph::insert(pos_type start, docstring const & str,
1672 Font const & font, Change const & change)
1674 for (size_t i = 0, n = str.size(); i != n ; ++i)
1675 insertChar(start + i, str[i], font, change);
1679 void Paragraph::appendChar(char_type c, Font const & font,
1680 Change const & change)
1683 d->changes_.insert(change, d->text_.size());
1684 // when appending characters, no need to update tables
1685 d->text_.push_back(c);
1686 setFont(d->text_.size() - 1, font);
1687 d->requestSpellCheck(d->text_.size() - 1);
1691 void Paragraph::appendString(docstring const & s, Font const & font,
1692 Change const & change)
1694 pos_type end = s.size();
1695 size_t oldsize = d->text_.size();
1696 size_t newsize = oldsize + end;
1697 size_t capacity = d->text_.capacity();
1698 if (newsize >= capacity)
1699 d->text_.reserve(max(capacity + 100, newsize));
1701 // when appending characters, no need to update tables
1704 // FIXME: Optimize this!
1705 for (size_t i = oldsize; i != newsize; ++i) {
1707 d->changes_.insert(change, i);
1708 d->requestSpellCheck(i);
1710 d->fontlist_.set(oldsize, font);
1711 d->fontlist_.set(newsize - 1, font);
1715 void Paragraph::insertChar(pos_type pos, char_type c,
1718 d->insertChar(pos, c, Change(trackChanges ?
1719 Change::INSERTED : Change::UNCHANGED));
1723 void Paragraph::insertChar(pos_type pos, char_type c,
1724 Font const & font, bool trackChanges)
1726 d->insertChar(pos, c, Change(trackChanges ?
1727 Change::INSERTED : Change::UNCHANGED));
1732 void Paragraph::insertChar(pos_type pos, char_type c,
1733 Font const & font, Change const & change)
1735 d->insertChar(pos, c, change);
1740 void Paragraph::resetFonts(Font const & font)
1742 d->fontlist_.clear();
1743 d->fontlist_.set(0, font);
1744 d->fontlist_.set(d->text_.size() - 1, font);
1747 // Gets uninstantiated font setting at position.
1748 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1752 LYXERR0("pos: " << pos << " size: " << size());
1756 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1757 if (cit != d->fontlist_.end())
1760 if (pos == size() && !empty())
1761 return getFontSettings(bparams, pos - 1);
1763 // Optimisation: avoid a full font instantiation if there is no
1764 // language change from previous call.
1765 static Font previous_font;
1766 static Language const * previous_lang = nullptr;
1767 Language const * lang = getParLanguage(bparams);
1768 if (lang != previous_lang) {
1769 previous_lang = lang;
1770 previous_font = Font(inherit_font, lang);
1772 return previous_font;
1776 FontSpan Paragraph::fontSpan(pos_type pos) const
1778 LBUFERR(pos <= size());
1781 return FontSpan(pos, pos);
1784 FontList::const_iterator cit = d->fontlist_.begin();
1785 FontList::const_iterator end = d->fontlist_.end();
1786 for (; cit != end; ++cit) {
1787 if (cit->pos() >= pos) {
1788 if (pos >= beginOfBody())
1789 return FontSpan(max(start, beginOfBody()),
1792 return FontSpan(start,
1793 min(beginOfBody() - 1,
1796 start = cit->pos() + 1;
1799 // This should not happen, but if so, we take no chances.
1800 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1801 LASSERT(false, return FontSpan(pos, pos));
1805 // Gets uninstantiated font setting at position 0
1806 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1808 if (!empty() && !d->fontlist_.empty())
1809 return d->fontlist_.begin()->font();
1811 // Optimisation: avoid a full font instantiation if there is no
1812 // language change from previous call.
1813 static Font previous_font;
1814 static Language const * previous_lang = nullptr;
1815 if (bparams.language != previous_lang) {
1816 previous_lang = bparams.language;
1817 previous_font = Font(inherit_font, bparams.language);
1820 return previous_font;
1824 // Gets the fully instantiated font at a given position in a paragraph
1825 // This is basically the same function as Text::GetFont() in text2.cpp.
1826 // The difference is that this one is used for generating the LaTeX file,
1827 // and thus cosmetic "improvements" are disallowed: This has to deliver
1828 // the true picture of the buffer. (Asger)
1829 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1830 Font const & outerfont) const
1834 Font font = getFontSettings(bparams, pos);
1836 pos_type const body_pos = beginOfBody();
1837 FontInfo & fi = font.fontInfo();
1839 fi.realize(d->layout_->labelfont);
1841 fi.realize(d->layout_->font);
1843 fi.realize(outerfont.fontInfo());
1844 fi.realize(bparams.getFont().fontInfo());
1850 Font const Paragraph::getLabelFont
1851 (BufferParams const & bparams, Font const & outerfont) const
1853 FontInfo tmpfont = d->layout_->labelfont;
1854 tmpfont.realize(outerfont.fontInfo());
1855 tmpfont.realize(bparams.getFont().fontInfo());
1856 return Font(tmpfont, getParLanguage(bparams));
1860 Font const Paragraph::getLayoutFont
1861 (BufferParams const & bparams, Font const & outerfont) const
1863 FontInfo tmpfont = d->layout_->font;
1864 tmpfont.realize(outerfont.fontInfo());
1865 tmpfont.realize(bparams.getFont().fontInfo());
1866 return Font(tmpfont, getParLanguage(bparams));
1870 char_type Paragraph::getUChar(BufferParams const & bparams,
1871 OutputParams const & rp,
1874 char_type c = d->text_[pos];
1876 // Return unchanged character in LTR languages
1877 // or if we use poylglossia/bidi (XeTeX).
1878 if (rp.useBidiPackage()
1879 || !getFontSettings(bparams, pos).isRightToLeft())
1882 // Without polyglossia/bidi, we need to account for some special cases.
1883 // FIXME This needs to be audited!
1885 // * The input is as expected for all delimiters
1886 // => checked for Hebrew!
1887 // * The output matches the display in the LyX workarea
1888 // => checked for Hebrew!
1889 // * The special cases below are really necessary
1890 // => checked for Hebrew!
1891 // * In arabic_arabi, brackets are transformed to Arabic
1892 // Ornate Parentheses. Is this is really wanted?
1894 string const & lang = getFontSettings(bparams, pos).language()->lang();
1897 // 1. In the following languages, parentheses need to be reversed.
1898 // Also with polyglodia/luabidi
1899 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1901 // 2. In the following languages, brackets don't need to be reversed.
1902 bool const reversebrackets = lang != "arabic_arabtex"
1903 && lang != "arabic_arabi"
1906 // Now swap delimiters if needed.
1917 if (reversebrackets)
1921 if (reversebrackets)
1942 void Paragraph::setFont(pos_type pos, Font const & font)
1944 LASSERT(pos <= size(), return);
1946 // First, reduce font against layout/label font
1947 // Update: The setCharFont() routine in text2.cpp already
1948 // reduces font, so we don't need to do that here. (Asger)
1950 d->fontlist_.set(pos, font);
1954 void Paragraph::makeSameLayout(Paragraph const & par)
1956 d->layout_ = par.d->layout_;
1957 d->params_ = par.d->params_;
1961 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1963 if (isFreeSpacing())
1969 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1970 if (eraseChar(pos, trackChanges))
1976 return count > 0 || pos > 0;
1980 bool Paragraph::hasSameLayout(Paragraph const & par) const
1982 return par.d->layout_ == d->layout_
1983 && d->params_.sameLayout(par.d->params_);
1987 depth_type Paragraph::getDepth() const
1989 return d->params_.depth();
1993 depth_type Paragraph::getMaxDepthAfter() const
1995 if (d->layout_->isEnvironment())
1996 return d->params_.depth() + 1;
1998 return d->params_.depth();
2002 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2004 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2005 return getDefaultAlign(bparams);
2007 return d->params_.align();
2011 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2013 LyXAlignment res = layout().align;
2014 if (isRTL(bparams)) {
2016 if (res == LYX_ALIGN_LEFT)
2017 res = LYX_ALIGN_RIGHT;
2018 else if (res == LYX_ALIGN_RIGHT)
2019 res = LYX_ALIGN_LEFT;
2025 docstring const & Paragraph::labelString() const
2027 return d->params_.labelString();
2031 // the next two functions are for the manual labels
2032 docstring const Paragraph::getLabelWidthString() const
2034 if (d->layout_->margintype == MARGIN_MANUAL
2035 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2036 return d->params_.labelWidthString();
2038 return _("Senseless with this layout!");
2042 void Paragraph::setLabelWidthString(docstring const & s)
2044 d->params_.labelWidthString(s);
2048 docstring Paragraph::expandLabel(Layout const & layout,
2049 BufferParams const & bparams) const
2051 return expandParagraphLabel(layout, bparams, true);
2055 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2056 BufferParams const & bparams, bool process_appendix) const
2058 DocumentClass const & tclass = bparams.documentClass();
2059 string const & lang = getParLanguage(bparams)->code();
2060 bool const in_appendix = process_appendix && d->params_.appendix();
2061 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2063 if (fmt.empty() && !layout.counter.empty())
2064 return tclass.counters().theCounter(layout.counter, lang);
2066 // handle 'inherited level parts' in 'fmt',
2067 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2068 size_t const i = fmt.find('@', 0);
2069 if (i != docstring::npos) {
2070 size_t const j = fmt.find('@', i + 1);
2071 if (j != docstring::npos) {
2072 docstring parent(fmt, i + 1, j - i - 1);
2073 docstring label = from_ascii("??");
2074 if (tclass.hasLayout(parent))
2075 label = expandParagraphLabel(tclass[parent], bparams,
2077 fmt = docstring(fmt, 0, i) + label
2078 + docstring(fmt, j + 1, docstring::npos);
2082 return tclass.counters().counterLabel(fmt, lang);
2086 void Paragraph::applyLayout(Layout const & new_layout)
2088 d->layout_ = &new_layout;
2089 LyXAlignment const oldAlign = d->params_.align();
2091 if (!(oldAlign & d->layout_->alignpossible)) {
2092 frontend::Alert::warning(_("Alignment not permitted"),
2093 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2094 d->params_.align(LYX_ALIGN_LAYOUT);
2099 pos_type Paragraph::beginOfBody() const
2101 return d->begin_of_body_;
2105 void Paragraph::setBeginOfBody()
2107 if (d->layout_->labeltype != LABEL_MANUAL) {
2108 d->begin_of_body_ = 0;
2112 // Unroll the first two cycles of the loop
2113 // and remember the previous character to
2114 // remove unnecessary getChar() calls
2116 pos_type end = size();
2117 bool prev_char_deleted = false;
2118 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2121 char_type previous_char = d->text_[i];
2122 if (!(isNewline(i) || isEnvSeparator(i))) {
2124 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2125 char_type temp = d->text_[i];
2126 prev_char_deleted = isDeleted(i);
2127 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2130 previous_char = temp;
2136 d->begin_of_body_ = i;
2140 bool Paragraph::allowParagraphCustomization() const
2142 return inInset().allowParagraphCustomization();
2146 bool Paragraph::usePlainLayout() const
2148 return inInset().usePlainLayout();
2152 bool Paragraph::isPassThru() const
2154 return inInset().isPassThru() || d->layout_->pass_thru;
2159 // paragraphs inside floats need different alignment tags to avoid
2162 bool noTrivlistCentering(InsetCode code)
2164 return code == FLOAT_CODE
2165 || code == WRAP_CODE
2166 || code == CELL_CODE;
2170 string correction(string const & orig)
2172 if (orig == "flushleft")
2173 return "raggedright";
2174 if (orig == "flushright")
2175 return "raggedleft";
2176 if (orig == "center")
2182 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2183 InsetCode code, bool const lastpar, int & col)
2185 string macro = suffix + "{";
2186 if (noTrivlistCentering(code)) {
2188 // the last paragraph in non-trivlist-aligned
2189 // context is special (to avoid unwanted whitespace)
2190 if (suffix == "\\begin") {
2191 macro = "\\" + correction(env) + "{}";
2192 os << from_ascii(macro);
2193 col += macro.size();
2198 macro += correction(env);
2202 if (suffix == "\\par\\end") {
2206 os << from_ascii(macro);
2207 col += macro.size();
2208 if (suffix == "\\begin") {
2218 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2219 otexstream & os, OutputParams const & runparams) const
2224 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2225 (layout_->toggle_indent != ITOGGLE_NEVER) :
2226 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2228 if (canindent && params_.noindent() && !layout_->pass_thru) {
2229 os << "\\noindent ";
2233 LyXAlignment const curAlign = params_.align();
2235 if (curAlign == layout_->align)
2239 case LYX_ALIGN_NONE:
2240 case LYX_ALIGN_BLOCK:
2241 case LYX_ALIGN_LAYOUT:
2242 case LYX_ALIGN_SPECIAL:
2243 case LYX_ALIGN_DECIMAL:
2245 case LYX_ALIGN_LEFT:
2246 case LYX_ALIGN_RIGHT:
2247 case LYX_ALIGN_CENTER:
2248 if (runparams.moving_arg) {
2255 string const begin_tag = "\\begin";
2256 InsetCode code = ownerCode();
2257 bool const lastpar = runparams.isLastPar;
2258 // RTL in classic (PDF)LaTeX (without the Bidi package)
2259 // Luabibdi (used by LuaTeX) behaves like classic
2260 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2261 && !runparams.useBidiPackage();
2264 case LYX_ALIGN_NONE:
2265 case LYX_ALIGN_BLOCK:
2266 case LYX_ALIGN_LAYOUT:
2267 case LYX_ALIGN_SPECIAL:
2268 case LYX_ALIGN_DECIMAL:
2270 case LYX_ALIGN_LEFT: {
2272 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2273 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2275 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2277 } case LYX_ALIGN_RIGHT: {
2279 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2280 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2282 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2284 } case LYX_ALIGN_CENTER: {
2285 corrected_env(os, begin_tag, "center", code, lastpar, column);
2294 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2295 otexstream & os, OutputParams const & runparams) const
2297 LyXAlignment const curAlign = params_.align();
2299 if (curAlign == layout_->align)
2303 case LYX_ALIGN_NONE:
2304 case LYX_ALIGN_BLOCK:
2305 case LYX_ALIGN_LAYOUT:
2306 case LYX_ALIGN_SPECIAL:
2307 case LYX_ALIGN_DECIMAL:
2309 case LYX_ALIGN_LEFT:
2310 case LYX_ALIGN_RIGHT:
2311 case LYX_ALIGN_CENTER:
2312 if (runparams.moving_arg)
2317 bool output = false;
2319 string const end_tag = "\\par\\end";
2320 InsetCode code = ownerCode();
2321 bool const lastpar = runparams.isLastPar;
2322 // RTL in classic (PDF)LaTeX (without the Bidi package)
2323 // Luabibdi (used by LuaTeX) behaves like classic
2324 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2325 && !runparams.useBidiPackage();
2328 case LYX_ALIGN_NONE:
2329 case LYX_ALIGN_BLOCK:
2330 case LYX_ALIGN_LAYOUT:
2331 case LYX_ALIGN_SPECIAL:
2332 case LYX_ALIGN_DECIMAL:
2334 case LYX_ALIGN_LEFT: {
2336 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2337 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2339 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2341 } case LYX_ALIGN_RIGHT: {
2343 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2344 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2346 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2348 } case LYX_ALIGN_CENTER: {
2349 corrected_env(os, end_tag, "center", code, lastpar, col);
2354 return output || lastpar;
2358 // This one spits out the text of the paragraph
2359 void Paragraph::latex(BufferParams const & bparams,
2360 Font const & outerfont,
2362 OutputParams const & runparams,
2363 int start_pos, int end_pos, bool force) const
2365 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2367 // FIXME This check should not be needed. Perhaps issue an
2368 // error if it triggers.
2369 Layout const & style = inInset().forcePlainLayout() ?
2370 bparams.documentClass().plainLayout() : *d->layout_;
2372 if (!force && style.inpreamble)
2375 bool const allowcust = allowParagraphCustomization();
2377 // Current base font for all inherited font changes, without any
2378 // change caused by an individual character, except for the language:
2379 // It is set to the language of the first character.
2380 // As long as we are in the label, this font is the base font of the
2381 // label. Before the first body character it is set to the base font
2385 // If there is an open font-encoding changing command (script wrapper),
2386 // alien_script is set to its name
2387 string alien_script;
2390 // Maybe we have to create a optional argument.
2391 pos_type body_pos = beginOfBody();
2392 unsigned int column = 0;
2394 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2395 Font const real_outerfont = (!inInset().inheritFont()
2396 && runparams.local_font != nullptr)
2397 ? Font(runparams.local_font->fontInfo()) : outerfont;
2400 // the optional argument is kept in curly brackets in
2401 // case it contains a ']'
2402 // This is not strictly needed, but if this is changed it
2403 // would be a file format change, and tex2lyx would need
2404 // to be adjusted, since it unconditionally removes the
2405 // braces when it parses \item.
2408 basefont = getLabelFont(bparams, real_outerfont);
2410 basefont = getLayoutFont(bparams, real_outerfont);
2413 // Which font is currently active?
2414 Font running_font(basefont);
2415 // Do we have an open font change?
2416 bool open_font = false;
2418 Change runningChange = Change(Change::UNCHANGED);
2420 Encoding const * const prev_encoding = runparams.encoding;
2422 os.texrow().start(id(), 0);
2424 // if the paragraph is empty, the loop will not be entered at all
2426 // For InTitle commands, we have already opened a group
2427 // in output_latex::TeXOnePar.
2428 if (style.isCommand() && !style.intitle) {
2432 if (!style.leftdelim().empty()) {
2433 os << style.leftdelim();
2434 column += style.leftdelim().size();
2437 column += d->startTeXParParams(bparams, os, runparams);
2440 // Whether a \par can be issued for insets typeset inline with text.
2441 // Yes if greater than 0. This has to be static.
2442 THREAD_LOCAL_STATIC int parInline = 0;
2444 for (pos_type i = 0; i < size(); ++i) {
2445 // First char in paragraph or after label?
2446 if (i == body_pos) {
2449 bool needPar = false;
2450 column += running_font.latexWriteEndChanges(
2451 os, bparams, runparams,
2452 basefont, basefont, needPar);
2455 basefont = getLayoutFont(bparams, real_outerfont);
2456 running_font = basefont;
2458 column += Changes::latexMarkChange(os, bparams,
2459 runningChange, Change(Change::UNCHANGED),
2461 runningChange = Change(Change::UNCHANGED);
2466 // For InTitle commands, we have already opened a group
2467 // in output_latex::TeXOnePar.
2468 if (style.isCommand() && !style.intitle) {
2473 if (!style.leftdelim().empty()) {
2474 os << style.leftdelim();
2475 column += style.leftdelim().size();
2479 column += d->startTeXParParams(bparams, os,
2483 runparams.wasDisplayMath = runparams.inDisplayMath;
2484 runparams.inDisplayMath = false;
2485 bool deleted_display_math = false;
2486 Change const & change = runparams.inDeletedInset
2487 ? runparams.changeOfDeletedInset : lookupChange(i);
2489 char_type const c = d->text_[i];
2491 // Check whether a display math inset follows
2493 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2495 runparams.ctObject = getInset(i)->CtObject(runparams);
2497 InsetMath const * im = getInset(i)->asInsetMath();
2498 if (im && im->asHullInset()
2499 && im->asHullInset()->outerDisplay()) {
2500 runparams.inDisplayMath = true;
2501 // runparams.inDeletedInset will be set by
2502 // latexInset later, but we need this info
2503 // before it is called. On the other hand, we
2504 // cannot set it here because it is a counter.
2505 deleted_display_math = isDeleted(i);
2507 if (bparams.output_changes && deleted_display_math
2508 && runningChange == change
2509 && change.type == Change::DELETED
2510 && !os.afterParbreak()) {
2511 // A display math in the same paragraph follows.
2512 // We have to close and then reopen \lyxdeleted,
2513 // otherwise the math will be shifted up.
2514 OutputParams rp = runparams;
2516 bool needPar = false;
2517 column += running_font.latexWriteEndChanges(
2518 os, bparams, rp, basefont,
2522 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2523 : getLayoutFont(bparams, real_outerfont);
2524 running_font = basefont;
2525 column += Changes::latexMarkChange(os, bparams,
2526 Change(Change::INSERTED), change, rp);
2530 if (bparams.output_changes && runningChange != change) {
2531 if (!alien_script.empty()) {
2534 alien_script.clear();
2537 bool needPar = false;
2538 column += running_font.latexWriteEndChanges(
2539 os, bparams, runparams,
2540 basefont, basefont, needPar);
2543 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2544 : getLayoutFont(bparams, real_outerfont);
2545 running_font = basefont;
2546 column += Changes::latexMarkChange(os, bparams, runningChange,
2548 runningChange = change;
2551 // do not output text which is marked deleted
2552 // if change tracking output is disabled
2553 if (!bparams.output_changes && change.deleted()) {
2559 // Fully instantiated font
2560 Font const current_font = getFont(bparams, i, outerfont);
2562 Font const prev_font = (i > 0) ?
2563 getFont(bparams, i - 1, outerfont)
2566 Font const last_font = running_font;
2567 bool const in_ct_deletion = (bparams.output_changes
2568 && runningChange == change
2569 && change.type == Change::DELETED
2570 && !os.afterParbreak());
2571 bool const multipar_inset =
2572 (c == META_INSET && getInset(i) && getInset(i)->allowMultiPar());
2574 // Do we need to close the previous font?
2576 ((current_font != running_font
2577 || current_font.language() != running_font.language())
2579 && (current_font == prev_font
2580 || current_font.language() == prev_font.language()))))
2582 // ensure there is no open script-wrapper
2583 if (!alien_script.empty()) {
2586 alien_script.clear();
2588 bool needPar = false;
2589 if (in_ct_deletion) {
2590 // We have to close and then reopen \lyxdeleted,
2591 // as strikeout needs to be on lowest level.
2595 column += running_font.latexWriteEndChanges(
2596 os, bparams, runparams, basefont,
2597 (i == body_pos-1) ? basefont : current_font,
2599 if (in_ct_deletion) {
2600 // We have to close and then reopen \lyxdeleted,
2601 // as strikeout needs to be on lowest level.
2602 OutputParams rp = runparams;
2603 column += Changes::latexMarkChange(os, bparams,
2604 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2606 running_font = basefont;
2610 // if necessary, close language environment before opening CJK
2611 string const running_lang = running_font.language()->babel();
2612 string const lang_end_command = lyxrc.language_command_end;
2613 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2614 && !running_lang.empty()
2615 && running_lang == openLanguageName()
2616 && current_font.language()->encoding()->package() == Encoding::CJK) {
2617 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2618 os << from_ascii(end_tag);
2619 column += end_tag.length();
2623 // Switch file encoding if necessary (and allowed)
2624 if (!runparams.pass_thru && !style.pass_thru &&
2625 runparams.encoding->package() != Encoding::none &&
2626 current_font.language()->encoding()->package() != Encoding::none) {
2627 pair<bool, int> const enc_switch =
2628 switchEncoding(os.os(), bparams, runparams,
2629 *(current_font.language()->encoding()));
2630 if (enc_switch.first) {
2631 column += enc_switch.second;
2632 runparams.encoding = current_font.language()->encoding();
2636 // A display math inset inside an ulem command will be output
2637 // as a box of width \linewidth, so we have to either disable
2638 // indentation if the inset starts a paragraph, or start a new
2639 // line to accommodate such box. This has to be done before
2640 // writing any font changing commands.
2641 if (runparams.inDisplayMath && !deleted_display_math
2642 && runparams.inulemcmd) {
2643 if (os.afterParbreak())
2649 // Do we need to change font?
2650 if ((current_font != running_font ||
2651 current_font.language() != running_font.language())
2652 && i != body_pos - 1)
2654 if (in_ct_deletion) {
2655 // We have to close and then reopen \lyxdeleted,
2656 // as strikeout needs to be on lowest level.
2657 bool needPar = false;
2658 OutputParams rp = runparams;
2659 column += running_font.latexWriteEndChanges(
2660 os, bparams, rp, basefont,
2665 otexstringstream ots;
2666 if (!multipar_inset) {
2667 InsetText const * textinset = inInset().asInsetText();
2668 bool const cprotect = textinset
2669 ? textinset->hasCProtectContent(runparams.moving_arg)
2670 && !textinset->text().isMainText()
2672 column += current_font.latexWriteStartChanges(ots, bparams,
2673 runparams, basefont, last_font, false,
2676 // Check again for display math in ulem commands as a
2677 // font change may also occur just before a math inset.
2678 if (runparams.inDisplayMath && !deleted_display_math
2679 && runparams.inulemcmd) {
2680 if (os.afterParbreak())
2685 running_font = current_font;
2687 docstring fontchange = ots.str();
2689 // check whether the fontchange ends with a \\textcolor
2690 // modifier and the text starts with a space. If so we
2691 // need to add } in order to prevent \\textcolor from gobbling
2692 // the space (bug 4473).
2693 docstring const last_modifier = rsplit(fontchange, '\\');
2694 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2695 os << from_ascii("{}");
2696 else if (ots.terminateCommand())
2698 if (in_ct_deletion) {
2699 // We have to close and then reopen \lyxdeleted,
2700 // as strikeout needs to be on lowest level.
2701 OutputParams rp = runparams;
2702 column += Changes::latexMarkChange(os, bparams,
2703 Change(Change::UNCHANGED), change, rp);
2707 // FIXME: think about end_pos implementation...
2708 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2709 // FIXME: integrate this case in latexSpecialChar
2710 // Do not print the separation of the optional argument
2711 // if style.pass_thru is false. This works because
2712 // latexSpecialChar ignores spaces if
2713 // style.pass_thru is false.
2714 if (i != body_pos - 1) {
2715 if (d->simpleTeXBlanks(bparams, runparams, os,
2716 i, column, current_font, style)) {
2717 // A surrogate pair was output. We
2718 // must not call latexSpecialChar
2719 // in this iteration, since it would output
2720 // the combining character again.
2727 OutputParams rp = runparams;
2728 rp.free_spacing = style.free_spacing;
2729 rp.local_font = ¤t_font;
2730 rp.intitle = style.intitle;
2732 // Two major modes: LaTeX or plain
2733 // Handle here those cases common to both modes
2734 // and then split to handle the two modes separately.
2735 if (c == META_INSET) {
2736 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2737 // Greyedout notes and, in general, all insets
2738 // with InsetLayout::isDisplay() == false,
2739 // are typeset inline with the text. So, we
2740 // can add a \par to the last paragraph of
2741 // such insets only if nothing else follows.
2742 bool incremented = false;
2743 Inset const * inset = getInset(i);
2744 InsetText const * textinset = inset
2745 ? inset->asInsetText()
2747 if (i + 1 == size() && textinset
2748 && !inset->getLayout().isDisplay()) {
2749 ParagraphList const & pars =
2750 textinset->text().paragraphs();
2751 pit_type const pit = pars.size() - 1;
2752 Font const lastfont =
2753 pit < 0 || pars[pit].empty()
2754 ? pars[pit].getLayoutFont(
2757 : pars[pit].getFont(bparams,
2758 pars[pit].size() - 1,
2760 if (lastfont.fontInfo().size() !=
2761 basefont.fontInfo().size()) {
2766 // We need to restore these after insets with
2767 // allowMultiPar() true
2768 Font const save_running_font = running_font;
2769 Font const save_basefont = basefont;
2770 d->latexInset(bparams, os, rp, running_font,
2771 basefont, real_outerfont, open_font,
2772 runningChange, style, i, column);
2773 if (multipar_inset) {
2774 running_font = save_running_font;
2775 basefont = save_basefont;
2780 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2781 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2782 // Close \lyx*deleted and force its
2783 // reopening (if needed)
2786 runningChange = Change(Change::UNCHANGED);
2787 runparams.ctObject = OutputParams::CT_NORMAL;
2790 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2791 if (!bparams.useNonTeXFonts)
2792 script = Encodings::isKnownScriptChar(c);
2793 if (script != alien_script) {
2794 if (!alien_script.empty()) {
2796 alien_script.clear();
2798 string fontenc = running_font.language()->fontenc(bparams);
2800 && !Encodings::fontencSupportsScript(fontenc, script)) {
2801 column += script.length() + 2;
2802 os << "\\" << script << "{";
2803 alien_script = script;
2807 d->latexSpecialChar(os, bparams, rp, running_font,
2808 alien_script, style, i, end_pos, column);
2809 } catch (EncodingException & e) {
2810 if (runparams.dryrun) {
2811 os << "<" << _("LyX Warning: ")
2812 << _("uncodable character") << " '";
2816 // add location information and throw again.
2824 // Set the encoding to that returned from latexSpecialChar (see
2825 // comment for encoding member in OutputParams.h)
2826 runparams.encoding = rp.encoding;
2828 // Also carry on the info on a closed ulem command for insets
2829 // such as Note that do not produce any output, so that no
2830 // command is ever executed but its opening was recorded.
2831 runparams.inulemcmd = rp.inulemcmd;
2833 // These need to be passed upstream as well
2834 runparams.need_maketitle = rp.need_maketitle;
2835 runparams.have_maketitle = rp.have_maketitle;
2837 // And finally, pass the post_macros upstream
2838 runparams.post_macro = rp.post_macro;
2841 // Close wrapper for alien script
2842 if (!alien_script.empty()) {
2844 alien_script.clear();
2847 // If we have an open font definition, we have to close it
2849 // Make sure that \\par is done with the font of the last
2850 // character if this has another size as the default.
2851 // This is necessary because LaTeX (and LyX on the screen)
2852 // calculates the space between the baselines according
2853 // to this font. (Matthias)
2855 // We must not change the font for the last paragraph
2856 // of non-multipar insets, tabular cells or commands,
2857 // since this produces unwanted whitespace.
2859 Font const font = empty()
2860 ? getLayoutFont(bparams, real_outerfont)
2861 : getFont(bparams, size() - 1, real_outerfont);
2863 InsetText const * textinset = inInset().asInsetText();
2865 bool const maintext = textinset
2866 ? textinset->text().isMainText()
2869 size_t const numpars = textinset
2870 ? textinset->text().paragraphs().size()
2873 bool needPar = false;
2875 if (style.resfont.size() != font.fontInfo().size()
2876 && (!runparams.isLastPar || maintext
2877 || (numpars > 1 && d->ownerCode() != CELL_CODE
2878 && (inInset().getLayout().isDisplay()
2880 && !style.isCommand()) {
2883 #ifdef FIXED_LANGUAGE_END_DETECTION
2885 running_font.latexWriteEndChanges(os, bparams,
2886 runparams, basefont,
2887 next_->getFont(bparams, 0, outerfont),
2890 running_font.latexWriteEndChanges(os, bparams,
2891 runparams, basefont, basefont, needPar);
2894 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2895 //FIXME: there as we start another \selectlanguage with the next paragraph if
2896 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2897 running_font.latexWriteEndChanges(os, bparams, runparams,
2898 basefont, basefont, needPar);
2901 // The \par could not be inserted at the same nesting
2902 // level of the font size change, so do it now.
2903 os << "{\\" << font.latexSize() << "\\par}";
2907 column += Changes::latexMarkChange(os, bparams, runningChange,
2908 Change(Change::UNCHANGED), runparams);
2910 // Needed if there is an optional argument but no contents.
2911 if (body_pos > 0 && body_pos == size()) {
2915 if (!style.rightdelim().empty()) {
2916 os << style.rightdelim();
2917 column += style.rightdelim().size();
2920 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2921 && runparams.encoding != prev_encoding) {
2922 runparams.encoding = prev_encoding;
2923 os << setEncoding(prev_encoding->iconvName());
2926 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2930 bool Paragraph::emptyTag() const
2932 for (pos_type i = 0; i < size(); ++i) {
2933 if (Inset const * inset = getInset(i)) {
2934 InsetCode lyx_code = inset->lyxCode();
2935 // FIXME testing like that is wrong. What is
2937 if (lyx_code != TOC_CODE &&
2938 lyx_code != INCLUDE_CODE &&
2939 lyx_code != GRAPHICS_CODE &&
2940 lyx_code != ERT_CODE &&
2941 lyx_code != LISTINGS_CODE &&
2942 lyx_code != FLOAT_CODE &&
2943 lyx_code != TABULAR_CODE) {
2947 char_type c = d->text_[i];
2948 if (c != ' ' && c != '\t')
2956 string Paragraph::getID(Buffer const &, OutputParams const &)
2959 for (pos_type i = 0; i < size(); ++i) {
2960 if (Inset const * inset = getInset(i)) {
2961 InsetCode lyx_code = inset->lyxCode();
2962 if (lyx_code == LABEL_CODE) {
2963 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2964 docstring const & id = il->getParam("name");
2965 return "id='" + to_utf8(xml::cleanID(id)) + "'";
2973 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
2976 for (i = 0; i < size(); ++i) {
2977 if (Inset const * inset = getInset(i)) {
2978 inset->docbook(xs, runparams);
2980 char_type c = d->text_[i];
2990 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
2994 for (i = 0; i < size(); ++i) {
2995 if (Inset const * inset = getInset(i)) {
2996 inset->xhtml(xs, runparams);
2998 char_type c = d->text_[i];
3008 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3011 pos_type size = text_.size();
3012 for (pos_type i = initial; i < size; ++i) {
3013 Font font = owner_->getFont(buf.params(), i, outerfont);
3014 if (text_[i] == META_INSET)
3016 if (i != initial && font != font_old)
3027 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3028 vector<xml::EndFontTag> & tagsToClose,
3029 bool & flag, FontState curstate, xml::FontTypes type)
3031 if (curstate == FONT_ON) {
3032 tagsToOpen.push_back(docbookStartFontTag(type));
3035 tagsToClose.push_back(docbookEndFontTag(type));
3040 class OptionalFontType {
3045 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3046 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3049 OptionalFontType fontShapeToXml(FontShape fs)
3053 return {xml::FT_ITALIC};
3055 return {xml::FT_SLANTED};
3056 case SMALLCAPS_SHAPE:
3057 return {xml::FT_SMALLCAPS};
3062 // the other tags are for internal use
3068 OptionalFontType fontFamilyToXml(FontFamily fm)
3072 return {xml::FT_ROMAN};
3074 return {xml::FT_SANS};
3075 case TYPEWRITER_FAMILY:
3076 return {xml::FT_TYPE};
3077 case INHERIT_FAMILY:
3080 // the other tags are for internal use
3086 OptionalFontType fontSizeToXml(FontSize fs)
3090 return {xml::FT_SIZE_TINY};
3092 return {xml::FT_SIZE_SCRIPT};
3094 return {xml::FT_SIZE_FOOTNOTE};
3096 return {xml::FT_SIZE_SMALL};
3098 return {xml::FT_SIZE_LARGE};
3100 return {xml::FT_SIZE_LARGER};
3102 return {xml::FT_SIZE_LARGEST};
3104 return {xml::FT_SIZE_HUGE};
3106 return {xml::FT_SIZE_HUGER};
3108 return {xml::FT_SIZE_INCREASE};
3110 return {xml::FT_SIZE_DECREASE};
3115 // the other tags are for internal use
3121 struct DocBookFontState
3123 FontShape curr_fs = INHERIT_SHAPE;
3124 FontFamily curr_fam = INHERIT_FAMILY;
3125 FontSize curr_size = INHERIT_SIZE;
3127 // track whether we have opened these tags
3128 bool emph_flag = false;
3129 bool bold_flag = false;
3130 bool noun_flag = false;
3131 bool ubar_flag = false;
3132 bool dbar_flag = false;
3133 bool sout_flag = false;
3134 bool xout_flag = false;
3135 bool wave_flag = false;
3137 bool shap_flag = false;
3139 bool faml_flag = false;
3141 bool size_flag = false;
3144 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3146 std::string const & default_family,
3147 DocBookFontState & fs)
3149 vector<xml::FontTag> tagsToOpen;
3150 vector<xml::EndFontTag> tagsToClose;
3153 FontState curstate = font.fontInfo().emph();
3154 if (font_old.emph() != curstate)
3155 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3158 curstate = font.fontInfo().noun();
3159 if (font_old.noun() != curstate)
3160 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3163 curstate = font.fontInfo().underbar();
3164 if (font_old.underbar() != curstate)
3165 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3168 curstate = font.fontInfo().strikeout();
3169 if (font_old.strikeout() != curstate)
3170 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3173 curstate = font.fontInfo().xout();
3174 if (font_old.xout() != curstate)
3175 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3178 curstate = font.fontInfo().uuline();
3179 if (font_old.uuline() != curstate)
3180 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3183 curstate = font.fontInfo().uwave();
3184 if (font_old.uwave() != curstate)
3185 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3188 // a little hackish, but allows us to reuse what we have.
3189 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3190 if (font_old.series() != font.fontInfo().series())
3191 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3194 fs.curr_fs = font.fontInfo().shape();
3195 FontShape old_fs = font_old.shape();
3196 if (old_fs != fs.curr_fs) {
3198 OptionalFontType tag = fontShapeToXml(old_fs);
3200 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3201 fs.shap_flag = false;
3204 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3206 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3210 fs.curr_fam = font.fontInfo().family();
3211 FontFamily old_fam = font_old.family();
3212 if (old_fam != fs.curr_fam) {
3214 OptionalFontType tag = fontFamilyToXml(old_fam);
3216 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3217 fs.faml_flag = false;
3219 switch (fs.curr_fam) {
3221 // we will treat a "default" font family as roman, since we have
3222 // no other idea what to do.
3223 if (default_family != "rmdefault" && default_family != "default") {
3224 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3225 fs.faml_flag = true;
3229 if (default_family != "sfdefault") {
3230 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3231 fs.faml_flag = true;
3234 case TYPEWRITER_FAMILY:
3235 if (default_family != "ttdefault") {
3236 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3237 fs.faml_flag = true;
3240 case INHERIT_FAMILY:
3243 // the other tags are for internal use
3250 fs.curr_size = font.fontInfo().size();
3251 FontSize old_size = font_old.size();
3252 if (old_size != fs.curr_size) {
3254 OptionalFontType tag = fontSizeToXml(old_size);
3256 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3257 fs.size_flag = false;
3260 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3261 if (tag.has_value) {
3262 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3263 fs.size_flag = true;
3267 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3270 } // anonymous namespace
3273 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3275 OutputParams const & runparams,
3276 Font const & outerfont,
3277 bool start_paragraph, bool close_paragraph,
3278 pos_type initial) const
3280 // track whether we have opened these tags
3281 DocBookFontState fs;
3283 if (start_paragraph)
3284 xs.startDivision(allowEmpty());
3286 Layout const & style = *d->layout_;
3288 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3290 string const default_family =
3291 buf.masterBuffer()->params().fonts_default_family;
3293 vector<xml::FontTag> tagsToOpen;
3294 vector<xml::EndFontTag> tagsToClose;
3296 // parsing main loop
3297 for (pos_type i = initial; i < size(); ++i) {
3298 // let's not show deleted material in the output
3302 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3304 // Determine which tags should be opened or closed.
3305 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3308 // Other such tags? What about the other text ranges?
3310 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3311 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3312 for (; cit != cen; ++cit)
3315 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3316 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3317 for (; sit != sen; ++sit)
3320 tagsToClose.clear();
3323 if (Inset const * inset = getInset(i)) {
3324 if (!runparams.for_toc || inset->isInToc()) {
3325 OutputParams np = runparams;
3326 np.local_font = &font;
3327 // If the paragraph has size 1, then we are in the "special
3328 // case" where we do not output the containing paragraph info.
3329 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3330 // of that brittle logic is passed to this function through open_par.
3331 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3332 np.docbook_in_par = true;
3333 inset->docbook(xs, np);
3336 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3339 font_old = font.fontInfo();
3342 // FIXME, this code is just imported from XHTML
3343 // I'm worried about what happens if a branch, say, is itself
3344 // wrapped in some font stuff. I think that will not work.
3346 if (runparams.docbook_in_listing)
3348 if (close_paragraph)
3355 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3356 vector<xml::EndFontTag> & tagsToClose,
3357 bool & flag, FontState curstate, xml::FontTypes type)
3359 if (curstate == FONT_ON) {
3360 tagsToOpen.push_back(xhtmlStartFontTag(type));
3363 tagsToClose.push_back(xhtmlEndFontTag(type));
3368 } // anonymous namespace
3371 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3373 OutputParams const & runparams,
3374 Font const & outerfont,
3375 bool start_paragraph, bool close_paragraph,
3376 pos_type initial) const
3380 // track whether we have opened these tags
3381 bool emph_flag = false;
3382 bool bold_flag = false;
3383 bool noun_flag = false;
3384 bool ubar_flag = false;
3385 bool dbar_flag = false;
3386 bool sout_flag = false;
3387 bool xout_flag = false;
3388 bool wave_flag = false;
3390 bool shap_flag = false;
3392 bool faml_flag = false;
3394 bool size_flag = false;
3396 Layout const & style = *d->layout_;
3398 if (start_paragraph)
3399 xs.startDivision(allowEmpty());
3402 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3404 FontShape curr_fs = INHERIT_SHAPE;
3405 FontFamily curr_fam = INHERIT_FAMILY;
3406 FontSize curr_size = INHERIT_SIZE;
3408 string const default_family =
3409 buf.masterBuffer()->params().fonts_default_family;
3411 vector<xml::FontTag> tagsToOpen;
3412 vector<xml::EndFontTag> tagsToClose;
3414 // parsing main loop
3415 for (pos_type i = initial; i < size(); ++i) {
3416 // let's not show deleted material in the output
3420 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3423 FontState curstate = font.fontInfo().emph();
3424 if (font_old.emph() != curstate)
3425 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3428 curstate = font.fontInfo().noun();
3429 if (font_old.noun() != curstate)
3430 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3433 curstate = font.fontInfo().underbar();
3434 if (font_old.underbar() != curstate)
3435 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3438 curstate = font.fontInfo().strikeout();
3439 if (font_old.strikeout() != curstate)
3440 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3443 curstate = font.fontInfo().xout();
3444 if (font_old.xout() != curstate)
3445 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3448 curstate = font.fontInfo().uuline();
3449 if (font_old.uuline() != curstate)
3450 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3453 curstate = font.fontInfo().uwave();
3454 if (font_old.uwave() != curstate)
3455 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3458 // a little hackish, but allows us to reuse what we have.
3459 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3460 if (font_old.series() != font.fontInfo().series())
3461 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3464 curr_fs = font.fontInfo().shape();
3465 FontShape old_fs = font_old.shape();
3466 if (old_fs != curr_fs) {
3470 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3473 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3475 case SMALLCAPS_SHAPE:
3476 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3482 // the other tags are for internal use
3490 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3494 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3497 case SMALLCAPS_SHAPE:
3498 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3505 // the other tags are for internal use
3512 curr_fam = font.fontInfo().family();
3513 FontFamily old_fam = font_old.family();
3514 if (old_fam != curr_fam) {
3518 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3521 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3523 case TYPEWRITER_FAMILY:
3524 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3526 case INHERIT_FAMILY:
3529 // the other tags are for internal use
3537 // we will treat a "default" font family as roman, since we have
3538 // no other idea what to do.
3539 if (default_family != "rmdefault" && default_family != "default") {
3540 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3545 if (default_family != "sfdefault") {
3546 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3550 case TYPEWRITER_FAMILY:
3551 if (default_family != "ttdefault") {
3552 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3556 case INHERIT_FAMILY:
3559 // the other tags are for internal use
3566 curr_size = font.fontInfo().size();
3567 FontSize old_size = font_old.size();
3568 if (old_size != curr_size) {
3572 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3575 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3578 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3581 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3584 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3587 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3590 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3593 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3596 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3599 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3602 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3608 // the other tags are for internal use
3614 switch (curr_size) {
3616 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3620 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3624 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3628 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3632 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3636 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3640 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3644 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3648 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3652 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3656 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3663 // the other tags are for internal use
3670 // Other such tags? What about the other text ranges?
3672 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3673 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3674 for (; cit != cen; ++cit)
3677 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3678 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3679 for (; sit != sen; ++sit)
3682 tagsToClose.clear();
3685 Inset const * inset = getInset(i);
3687 if (!runparams.for_toc || inset->isInToc()) {
3688 OutputParams np = runparams;
3689 np.local_font = &font;
3690 // If the paragraph has size 1, then we are in the "special
3691 // case" where we do not output the containing paragraph info
3692 if (!inset->getLayout().htmlisblock() && size() != 1)
3693 np.html_in_par = true;
3694 retval += inset->xhtml(xs, np);
3697 char_type c = getUChar(buf.masterBuffer()->params(),
3699 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3700 xs << XMLStream::ESCAPE_NONE << " ";
3704 font_old = font.fontInfo();
3708 // I'm worried about what happens if a branch, say, is itself
3709 // wrapped in some font stuff. I think that will not work.
3711 if (close_paragraph)
3718 bool Paragraph::isHfill(pos_type pos) const
3720 Inset const * inset = getInset(pos);
3721 return inset && inset->isHfill();
3725 bool Paragraph::isNewline(pos_type pos) const
3727 // U+2028 LINE SEPARATOR
3728 // U+2029 PARAGRAPH SEPARATOR
3729 char_type const c = d->text_[pos];
3730 if (c == 0x2028 || c == 0x2029)
3732 Inset const * inset = getInset(pos);
3733 return inset && inset->lyxCode() == NEWLINE_CODE;
3737 bool Paragraph::isEnvSeparator(pos_type pos) const
3739 Inset const * inset = getInset(pos);
3740 return inset && inset->lyxCode() == SEPARATOR_CODE;
3744 bool Paragraph::isLineSeparator(pos_type pos) const
3746 char_type const c = d->text_[pos];
3747 if (isLineSeparatorChar(c))
3749 Inset const * inset = getInset(pos);
3750 return inset && inset->isLineSeparator();
3754 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3758 if (ignore_deleted && isDeleted(pos))
3760 if (Inset const * inset = getInset(pos))
3761 return !inset->isLetter();
3762 // if we have a hard hyphen (no en- or emdash) or apostrophe
3763 // we pass this to the spell checker
3764 // FIXME: this method is subject to change, visit
3765 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3766 // to get an impression how complex this is.
3767 if (isHardHyphenOrApostrophe(pos))
3769 char_type const c = d->text_[pos];
3770 // We want to pass the escape chars to the spellchecker
3771 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3772 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3776 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3778 pos_type const psize = size();
3781 char_type const c = d->text_[pos];
3782 if (c != '-' && c != '\'')
3784 int nextpos = pos + 1;
3785 int prevpos = pos > 0 ? pos - 1 : 0;
3786 if ((nextpos == psize || isSpace(nextpos))
3787 && (pos == 0 || isSpace(prevpos)))
3793 bool Paragraph::needsCProtection(bool const fragile) const
3795 // first check the layout of the paragraph, but only in insets
3796 InsetText const * textinset = inInset().asInsetText();
3797 bool const maintext = textinset
3798 ? textinset->text().isMainText()
3801 if (!maintext && layout().needcprotect) {
3802 // Environments need cprotection regardless the content
3803 if (layout().latextype == LATEX_ENVIRONMENT)
3806 // Commands need cprotection if they contain specific chars
3807 int const nchars_escape = 9;
3808 static char_type const chars_escape[nchars_escape] = {
3809 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3811 docstring const pars = asString();
3812 for (int k = 0; k < nchars_escape; k++) {
3813 if (contains(pars, chars_escape[k]))
3818 // now check whether we have insets that need cprotection
3819 pos_type size = pos_type(d->text_.size());
3820 for (pos_type i = 0; i < size; ++i) {
3823 Inset const * ins = getInset(i);
3824 if (ins->needsCProtection(maintext, fragile))
3826 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3827 // Environments need cprotection regardless the content
3829 // Now check math environments
3830 InsetMath const * im = getInset(i)->asInsetMath();
3831 if (!im || im->cell(0).empty())
3833 switch(im->cell(0)[0]->lyxCode()) {
3834 case MATH_AMSARRAY_CODE:
3835 case MATH_SUBSTACK_CODE:
3837 case MATH_XYMATRIX_CODE:
3838 // these need cprotection
3849 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3851 return d->speller_state_.getRange(pos);
3855 bool Paragraph::isChar(pos_type pos) const
3857 if (Inset const * inset = getInset(pos))
3858 return inset->isChar();
3859 char_type const c = d->text_[pos];
3860 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3864 bool Paragraph::isSpace(pos_type pos) const
3866 if (Inset const * inset = getInset(pos))
3867 return inset->isSpace();
3868 char_type const c = d->text_[pos];
3869 return lyx::isSpace(c);
3874 Paragraph::getParLanguage(BufferParams const & bparams) const
3877 return getFirstFontSettings(bparams).language();
3878 // FIXME: we should check the prev par as well (Lgb)
3879 return bparams.language;
3883 bool Paragraph::isRTL(BufferParams const & bparams) const
3885 return getParLanguage(bparams)->rightToLeft()
3886 && !inInset().getLayout().forceLTR();
3890 void Paragraph::changeLanguage(BufferParams const & bparams,
3891 Language const * from, Language const * to)
3893 // change language including dummy font change at the end
3894 for (pos_type i = 0; i <= size(); ++i) {
3895 Font font = getFontSettings(bparams, i);
3896 if (font.language() == from) {
3897 font.setLanguage(to);
3899 d->requestSpellCheck(i);
3905 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3907 Language const * doc_language = bparams.language;
3908 for (auto const & f : d->fontlist_)
3909 if (f.font().language() != ignore_language &&
3910 f.font().language() != latex_language &&
3911 f.font().language() != doc_language)
3917 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3919 for (auto const & f : d->fontlist_) {
3920 Language const * lang = f.font().language();
3921 if (lang != ignore_language &&
3922 lang != latex_language)
3928 docstring Paragraph::asString(int options) const
3930 return asString(0, size(), options);
3934 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3936 odocstringstream os;
3939 && options & AS_STR_LABEL
3940 && !d->params_.labelString().empty())
3941 os << d->params_.labelString() << ' ';
3943 for (pos_type i = beg; i < end; ++i) {
3944 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3946 char_type const c = d->text_[i];
3947 if (isPrintable(c) || c == '\t'
3948 || (c == '\n' && (options & AS_STR_NEWLINES)))
3950 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3951 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3952 LASSERT(runparams != nullptr, return docstring());
3953 getInset(i)->plaintext(os, *runparams);
3955 getInset(i)->toString(os);
3964 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3965 bool const shorten, bool const label) const
3967 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3968 if (label && !labelString().empty())
3969 os += labelString() + ' ';
3970 if (!layout().isTocCaption())
3972 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3975 char_type const c = d->text_[i];
3978 else if (c == META_INSET)
3979 getInset(i)->forOutliner(os, tmplen, false);
3982 Text::shortenForOutliner(os, maxlen);
3986 void Paragraph::setInsetOwner(Inset const * inset)
3988 d->inset_owner_ = inset;
3992 int Paragraph::id() const
3998 void Paragraph::setId(int id)
4004 Layout const & Paragraph::layout() const
4010 void Paragraph::setLayout(Layout const & layout)
4012 d->layout_ = &layout;
4016 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4018 setLayout(tc.defaultLayout());
4022 void Paragraph::setPlainLayout(DocumentClass const & tc)
4024 setLayout(tc.plainLayout());
4028 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4030 if (usePlainLayout())
4031 setPlainLayout(tclass);
4033 setDefaultLayout(tclass);
4037 Inset const & Paragraph::inInset() const
4039 LBUFERR(d->inset_owner_);
4040 return *d->inset_owner_;
4044 ParagraphParameters & Paragraph::params()
4050 ParagraphParameters const & Paragraph::params() const
4056 bool Paragraph::isFreeSpacing() const
4058 if (d->layout_->free_spacing)
4060 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4064 bool Paragraph::allowEmpty() const
4066 if (d->layout_->keepempty)
4068 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4072 bool Paragraph::brokenBiblio() const
4074 // There is a problem if there is no bibitem at position 0 in
4075 // paragraphs that need one, if there is another bibitem in the
4076 // paragraph or if this paragraph is not supposed to have
4077 // a bibitem inset at all.
4078 return ((d->layout_->labeltype == LABEL_BIBLIO
4079 && (d->insetlist_.find(BIBITEM_CODE) != 0
4080 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4081 || (d->layout_->labeltype != LABEL_BIBLIO
4082 && d->insetlist_.find(BIBITEM_CODE) != -1));
4086 int Paragraph::fixBiblio(Buffer const & buffer)
4088 // FIXME: when there was already an inset at 0, the return value is 1,
4089 // which does not tell whether another inset has been removed; the
4090 // cursor cannot be correctly updated.
4092 bool const track_changes = buffer.params().track_changes;
4093 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4095 // The case where paragraph is not BIBLIO
4096 if (d->layout_->labeltype != LABEL_BIBLIO) {
4097 if (bibitem_pos == -1)
4098 // No InsetBibitem => OK
4100 // There is an InsetBibitem: remove it!
4101 d->insetlist_.release(bibitem_pos);
4102 eraseChar(bibitem_pos, track_changes);
4103 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4106 bool const hasbibitem0 = bibitem_pos == 0;
4108 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4109 // There was an InsetBibitem at pos 0,
4110 // and no other one => OK
4111 if (bibitem_pos == -1)
4113 // there is a bibitem at the 0 position, but since
4114 // there is a second one, we copy the second on the
4115 // first. We're assuming there are at most two of
4116 // these, which there should be.
4117 // FIXME: why does it make sense to do that rather
4118 // than keep the first? (JMarc)
4119 Inset * inset = releaseInset(bibitem_pos);
4120 d->insetlist_.begin()->inset = inset;
4121 // This needs to be done to update the counter (#8499)
4122 buffer.updateBuffer();
4123 return -bibitem_pos;
4126 // We need to create an inset at the beginning
4127 Inset * inset = nullptr;
4128 if (bibitem_pos > 0) {
4129 // there was one somewhere in the paragraph, let's move it
4130 inset = d->insetlist_.release(bibitem_pos);
4131 eraseChar(bibitem_pos, track_changes);
4134 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4135 InsetCommandParams(BIBITEM_CODE));
4137 Font font(inherit_font, buffer.params().language);
4138 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4139 : Change::UNCHANGED));
4141 // This is needed to get the counters right
4142 buffer.updateBuffer();
4147 void Paragraph::checkAuthors(AuthorList const & authorList)
4149 d->changes_.checkAuthors(authorList);
4153 bool Paragraph::isChanged(pos_type pos) const
4155 return lookupChange(pos).changed();
4159 bool Paragraph::isInserted(pos_type pos) const
4161 return lookupChange(pos).inserted();
4165 bool Paragraph::isDeleted(pos_type pos) const
4167 return lookupChange(pos).deleted();
4171 InsetList const & Paragraph::insetList() const
4173 return d->insetlist_;
4177 void Paragraph::setInsetBuffers(Buffer & b)
4179 d->insetlist_.setBuffer(b);
4183 void Paragraph::resetBuffer()
4185 d->insetlist_.resetBuffer();
4189 Inset * Paragraph::releaseInset(pos_type pos)
4191 Inset * inset = d->insetlist_.release(pos);
4192 /// does not honour change tracking!
4193 eraseChar(pos, false);
4198 Inset * Paragraph::getInset(pos_type pos)
4200 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4201 ? d->insetlist_.get(pos) : nullptr;
4205 Inset const * Paragraph::getInset(pos_type pos) const
4207 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4208 ? d->insetlist_.get(pos) : nullptr;
4212 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4213 pos_type & right, TextCase action)
4215 // process sequences of modified characters; in change
4216 // tracking mode, this approach results in much better
4217 // usability than changing case on a char-by-char basis
4218 // We also need to track the current font, since font
4219 // changes within sequences can occur.
4220 vector<pair<char_type, Font> > changes;
4222 bool const trackChanges = bparams.track_changes;
4224 bool capitalize = true;
4226 for (; pos < right; ++pos) {
4227 char_type oldChar = d->text_[pos];
4228 char_type newChar = oldChar;
4230 // ignore insets and don't play with deleted text!
4231 if (oldChar != META_INSET && !isDeleted(pos)) {
4233 case text_lowercase:
4234 newChar = lowercase(oldChar);
4236 case text_capitalization:
4238 newChar = uppercase(oldChar);
4242 case text_uppercase:
4243 newChar = uppercase(oldChar);
4248 if (isWordSeparator(pos) || isDeleted(pos)) {
4249 // permit capitalization again
4253 if (oldChar != newChar) {
4254 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4255 if (pos != right - 1)
4257 // step behind the changing area
4261 int erasePos = pos - changes.size();
4262 for (size_t i = 0; i < changes.size(); i++) {
4263 insertChar(pos, changes[i].first,
4266 if (!eraseChar(erasePos, trackChanges)) {
4269 ++right; // expand selection
4277 int Paragraph::find(docstring const & str, bool cs, bool mw,
4278 pos_type start_pos, bool del) const
4280 pos_type pos = start_pos;
4281 int const strsize = str.length();
4283 pos_type const parsize = d->text_.size();
4284 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4285 // Ignore "invisible" letters such as ligature breaks
4286 // and hyphenation chars while searching
4287 while (pos < parsize - 1 && isInset(pos)) {
4288 odocstringstream os;
4289 getInset(pos)->toString(os);
4290 if (!getInset(pos)->isLetter() || !os.str().empty())
4294 if (cs && str[i] != d->text_[pos])
4296 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4298 if (!del && isDeleted(pos))
4305 // if necessary, check whether string matches word
4307 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4310 && !isWordSeparator(pos))
4314 return pos - start_pos;
4318 char_type Paragraph::getChar(pos_type pos) const
4320 return d->text_[pos];
4324 pos_type Paragraph::size() const
4326 return d->text_.size();
4330 bool Paragraph::empty() const
4332 return d->text_.empty();
4336 bool Paragraph::isInset(pos_type pos) const
4338 return d->text_[pos] == META_INSET;
4342 bool Paragraph::isSeparator(pos_type pos) const
4344 //FIXME: Are we sure this can be the only separator?
4345 return d->text_[pos] == ' ';
4349 void Paragraph::deregisterWords()
4351 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4352 Private::LangWordsMap::const_iterator ite = d->words_.end();
4353 for (; itl != ite; ++itl) {
4354 WordList & wl = theWordList(itl->first);
4355 Private::Words::const_iterator it = (itl->second).begin();
4356 Private::Words::const_iterator et = (itl->second).end();
4357 for (; it != et; ++it)
4364 void Paragraph::locateWord(pos_type & from, pos_type & to,
4365 word_location const loc, bool const ignore_deleted) const
4368 case WHOLE_WORD_STRICT:
4369 if (from == 0 || from == size()
4370 || isWordSeparator(from, ignore_deleted)
4371 || isWordSeparator(from - 1, ignore_deleted)) {
4378 // If we are already at the beginning of a word, do nothing
4379 if (!from || isWordSeparator(from - 1, ignore_deleted))
4384 // always move the cursor to the beginning of previous word
4385 while (from && !isWordSeparator(from - 1, ignore_deleted))
4389 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4392 // no need to move the 'from' cursor
4396 while (to < size() && !isWordSeparator(to, ignore_deleted))
4401 void Paragraph::collectWords()
4403 for (pos_type pos = 0; pos < size(); ++pos) {
4404 if (isWordSeparator(pos))
4406 pos_type from = pos;
4407 locateWord(from, pos, WHOLE_WORD);
4408 // Work around MSVC warning: The statement
4409 // if (pos < from + lyxrc.completion_minlength)
4410 // triggers a signed vs. unsigned warning.
4411 // I don't know why this happens, it could be a MSVC bug, or
4412 // related to LLP64 (windows) vs. LP64 (unix) programming
4413 // model, or the C++ standard might be ambigous in the section
4414 // defining the "usual arithmetic conversions". However, using
4415 // a temporary variable is safe and works on all compilers.
4416 pos_type const endpos = from + lyxrc.completion_minlength;
4419 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4420 if (cit == d->fontlist_.end())
4422 Language const * lang = cit->font().language();
4423 docstring const word = asString(from, pos, AS_STR_NONE);
4424 d->words_[lang->lang()].insert(word);
4429 void Paragraph::registerWords()
4431 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4432 Private::LangWordsMap::const_iterator ite = d->words_.end();
4433 for (; itl != ite; ++itl) {
4434 WordList & wl = theWordList(itl->first);
4435 Private::Words::const_iterator it = (itl->second).begin();
4436 Private::Words::const_iterator et = (itl->second).end();
4437 for (; it != et; ++it)
4443 void Paragraph::updateWords()
4451 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4453 SkipPositionsIterator begin = skips.begin();
4454 SkipPositions::iterator end = skips.end();
4455 if (pos > 0 && begin < end) {
4457 if (end->last == pos - 1) {
4462 skips.insert(end, FontSpan(pos, pos));
4466 Language * Paragraph::Private::locateSpellRange(
4467 pos_type & from, pos_type & to,
4468 SkipPositions & skips) const
4470 // skip leading white space
4471 while (from < to && owner_->isWordSeparator(from))
4473 // don't check empty range
4476 // get current language
4477 Language * lang = getSpellLanguage(from);
4478 pos_type last = from;
4479 bool samelang = true;
4480 bool sameinset = true;
4481 while (last < to && samelang && sameinset) {
4482 // hop to end of word
4483 while (last < to && !owner_->isWordSeparator(last)) {
4484 if (owner_->getInset(last)) {
4485 appendSkipPosition(skips, last);
4486 } else if (owner_->isDeleted(last)) {
4487 appendSkipPosition(skips, last);
4491 // hop to next word while checking for insets
4492 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4493 if (Inset const * inset = owner_->getInset(last))
4494 sameinset = inset->isChar() && inset->isLetter();
4495 if (sameinset && owner_->isDeleted(last)) {
4496 appendSkipPosition(skips, last);
4501 if (sameinset && last < to) {
4502 // now check for language change
4503 samelang = lang == getSpellLanguage(last);
4506 // if language change detected backstep is needed
4514 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4517 const_cast<Language *>(owner_->getFontSettings(
4518 inset_owner_->buffer().params(), from).language());
4519 if (lang == inset_owner_->buffer().params().language
4520 && !lyxrc.spellchecker_alt_lang.empty()) {
4522 string const lang_variety =
4523 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4524 lang->setCode(lang_code);
4525 lang->setVariety(lang_variety);
4531 void Paragraph::requestSpellCheck(pos_type pos)
4533 d->requestSpellCheck(pos);
4537 bool Paragraph::needsSpellCheck() const
4539 SpellChecker::ChangeNumber speller_change_number = 0;
4540 if (theSpellChecker())
4541 speller_change_number = theSpellChecker()->changeNumber();
4542 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4543 d->speller_state_.needsCompleteRefresh(speller_change_number);
4545 return d->needsSpellCheck();
4549 bool Paragraph::Private::ignoreWord(docstring const & word) const
4551 // Ignore words with digits
4552 // FIXME: make this customizable
4553 // (note that some checkers ignore words with digits by default)
4554 docstring::const_iterator cit = word.begin();
4555 docstring::const_iterator const end = word.end();
4556 for (; cit != end; ++cit) {
4557 if (isNumber((*cit)))
4564 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4565 WordLangTuple & wl, docstring_list & suggestions,
4566 bool do_suggestion, bool check_learned) const
4568 SpellChecker::Result result = SpellChecker::WORD_OK;
4569 SpellChecker * speller = theSpellChecker();
4573 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4576 locateWord(from, to, WHOLE_WORD, true);
4577 if (from == to || from >= size())
4580 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4581 Language * lang = d->getSpellLanguage(from);
4583 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4586 wl = WordLangTuple(word, lang);
4591 if (needsSpellCheck() || check_learned) {
4593 if (!d->ignoreWord(word)) {
4594 bool const trailing_dot = to < size() && d->text_[to] == '.';
4595 result = speller->check(wl);
4596 if (SpellChecker::misspelled(result) && trailing_dot) {
4597 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4598 result = speller->check(wl);
4599 if (!SpellChecker::misspelled(result)) {
4600 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4602 from << ".." << to << "]");
4604 // spell check with dot appended failed too
4605 // restore original word/lang value
4606 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4607 wl = WordLangTuple(word, lang);
4611 if (!SpellChecker::misspelled(result)) {
4612 // area up to the begin of the next word is not misspelled
4613 while (end < size() && isWordSeparator(end))
4616 d->setMisspelled(from, end, result);
4618 result = d->speller_state_.getState(from);
4622 suggestions.clear();
4624 if (SpellChecker::misspelled(result)) {
4625 LYXERR(Debug::GUI, "misspelled word: \"" <<
4627 from << ".." << to << "]");
4629 speller->suggest(wl, suggestions);
4635 void Paragraph::anonymize()
4637 // This is a very crude anonymization for now
4638 for (char_type & c : d->text_)
4639 if (isLetterChar(c) || isNumber(c))
4644 void Paragraph::Private::markMisspelledWords(
4645 pos_type const & first, pos_type const & last,
4646 SpellChecker::Result result,
4647 docstring const & word,
4648 SkipPositions const & skips)
4650 if (!SpellChecker::misspelled(result)) {
4651 setMisspelled(first, last, SpellChecker::WORD_OK);
4655 SpellChecker * speller = theSpellChecker();
4656 // locate and enumerate the error positions
4657 int nerrors = speller->numMisspelledWords();
4659 SkipPositionsIterator it = skips.begin();
4660 SkipPositionsIterator et = skips.end();
4661 for (int index = 0; index < nerrors; ++index) {
4664 speller->misspelledWord(index, wstart, wlen);
4665 /// should not happen if speller supports range checks
4666 if (!wlen) continue;
4667 docstring const misspelled = word.substr(wstart, wlen);
4668 wstart += first + numskipped;
4669 if (snext < wstart) {
4670 /// mark the range of correct spelling
4671 numskipped += countSkips(it, et, wstart);
4672 setMisspelled(snext,
4673 wstart - 1, SpellChecker::WORD_OK);
4675 snext = wstart + wlen;
4676 numskipped += countSkips(it, et, snext);
4677 /// mark the range of misspelling
4678 setMisspelled(wstart, snext, result);
4679 LYXERR(Debug::GUI, "misspelled word: \"" <<
4680 misspelled << "\" [" <<
4681 wstart << ".." << (snext-1) << "]");
4684 if (snext <= last) {
4685 /// mark the range of correct spelling at end
4686 setMisspelled(snext, last, SpellChecker::WORD_OK);
4691 void Paragraph::spellCheck() const
4693 SpellChecker * speller = theSpellChecker();
4694 if (!speller || empty() ||!needsSpellCheck())
4698 d->rangeOfSpellCheck(start, endpos);
4699 if (speller->canCheckParagraph()) {
4700 // loop until we leave the range
4701 for (pos_type first = start; first < endpos; ) {
4702 pos_type last = endpos;
4703 Private::SkipPositions skips;
4704 Language * lang = d->locateSpellRange(first, last, skips);
4705 if (first >= endpos)
4707 // start the spell checker on the unit of meaning
4708 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4709 WordLangTuple wl = WordLangTuple(word, lang);
4710 SpellChecker::Result result = word.size() ?
4711 speller->check(wl) : SpellChecker::WORD_OK;
4712 d->markMisspelledWords(first, last, result, word, skips);
4716 static docstring_list suggestions;
4717 pos_type to = endpos;
4718 while (start < endpos) {
4720 spellCheck(start, to, wl, suggestions, false);
4724 d->readySpellCheck();
4728 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4730 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4731 if (result || pos <= 0 || pos > size())
4733 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4734 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4739 string Paragraph::magicLabel() const
4742 ss << "magicparlabel-" << id();