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"
24 #include "BufferParams.h"
25 #include "BufferEncodings.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "output_xhtml.h"
38 #include "output_docbook.h"
39 #include "ParagraphParameters.h"
40 #include "SpellChecker.h"
41 #include "texstream.h"
44 #include "TextClass.h"
45 #include "WordLangTuple.h"
48 #include "frontends/alert.h"
50 #include "insets/InsetBibitem.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetSpecialChar.h"
53 #include "insets/InsetText.h"
55 #include "mathed/InsetMathHull.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
69 using namespace lyx::support;
71 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
72 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
73 #define THREAD_LOCAL_STATIC static __thread
74 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
75 #define THREAD_LOCAL_STATIC static __declspec(thread)
77 #define THREAD_LOCAL_STATIC thread_local static
82 /////////////////////////////////////////////////////////////////////
86 /////////////////////////////////////////////////////////////////////
88 class SpellResultRange {
90 SpellResultRange(FontSpan range, SpellChecker::Result result)
91 : range_(range), result_(result)
94 FontSpan const & range() const { return range_; }
96 void range(FontSpan const & r) { range_ = r; }
98 SpellChecker::Result result() const { return result_; }
100 void result(SpellChecker::Result r) { result_ = r; }
102 bool contains(pos_type pos) const { return range_.contains(pos); }
104 bool covered(FontSpan const & r) const
106 // 1. first of new range inside current range or
107 // 2. last of new range inside current range or
108 // 3. first of current range inside new range or
109 // 4. last of current range inside new range
110 //FIXME: is this the same as !range_.intersect(r).empty() ?
111 return range_.contains(r.first) || range_.contains(r.last) ||
112 r.contains(range_.first) || r.contains(range_.last);
115 void shift(pos_type pos, int offset)
117 if (range_.first > pos) {
118 range_.first += offset;
119 range_.last += offset;
120 } else if (range_.last >= pos) {
121 range_.last += offset;
126 SpellChecker::Result result_ ;
130 /////////////////////////////////////////////////////////////////////
134 /////////////////////////////////////////////////////////////////////
136 class SpellCheckerState {
140 needs_refresh_ = true;
141 current_change_number_ = 0;
144 void setRange(FontSpan const & fp, SpellChecker::Result state)
147 RangesIterator et = ranges_.end();
148 RangesIterator it = ranges_.begin();
149 for (; it != et; ++it) {
150 if (!it->covered(fp))
151 result.push_back(SpellResultRange(it->range(), it->result()));
152 else if (state == SpellChecker::WORD_OK) {
153 // trim or split the current misspelled range
154 // store misspelled ranges only
155 FontSpan range = it->range();
156 if (fp.first > range.first) {
157 // misspelled area in front of WORD_OK
158 range.last = fp.first - 1;
159 result.push_back(SpellResultRange(range, it->result()));
162 if (fp.last < range.last) {
163 // misspelled area after WORD_OK range
164 range.first = fp.last + 1;
165 result.push_back(SpellResultRange(range, it->result()));
170 if (state != SpellChecker::WORD_OK)
171 ranges_.push_back(SpellResultRange(fp, state));
174 void increasePosAfterPos(pos_type pos)
176 correctRangesAfterPos(pos, 1);
180 void decreasePosAfterPos(pos_type pos)
182 correctRangesAfterPos(pos, -1);
186 void refreshLast(pos_type pos)
188 if (pos < refresh_.last)
192 SpellChecker::Result getState(pos_type pos) const
194 SpellChecker::Result result = SpellChecker::WORD_OK;
195 RangesIterator et = ranges_.end();
196 RangesIterator it = ranges_.begin();
197 for (; it != et; ++it) {
198 if(it->contains(pos)) {
205 FontSpan const & getRange(pos_type pos) const
207 /// empty span to indicate mismatch
208 static FontSpan empty_;
209 RangesIterator et = ranges_.end();
210 RangesIterator it = ranges_.begin();
211 for (; it != et; ++it) {
212 if(it->contains(pos)) {
219 bool needsRefresh() const
221 return needs_refresh_;
224 SpellChecker::ChangeNumber currentChangeNumber() const
226 return current_change_number_;
229 void refreshRange(pos_type & first, pos_type & last) const
231 first = refresh_.first;
232 last = refresh_.last;
235 void needsRefresh(pos_type pos)
237 if (needs_refresh_ && pos != -1) {
238 if (pos < refresh_.first)
239 refresh_.first = pos;
240 if (pos > refresh_.last)
242 } else if (pos != -1) {
243 // init request check for neighbour positions too
244 refresh_.first = pos > 0 ? pos - 1 : 0;
245 // no need for special end of paragraph check
246 refresh_.last = pos + 1;
248 needs_refresh_ = pos != -1;
251 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
253 needs_refresh_ = true;
256 current_change_number_ = change_number;
259 typedef vector<SpellResultRange> Ranges;
260 typedef Ranges::const_iterator RangesIterator;
262 /// the area of the paragraph with pending spell check
264 /// spell state cache version number
265 SpellChecker::ChangeNumber current_change_number_;
269 void correctRangesAfterPos(pos_type pos, int offset)
271 RangesIterator et = ranges_.end();
272 Ranges::iterator it = ranges_.begin();
273 for (; it != et; ++it) {
274 it->shift(pos, offset);
280 /////////////////////////////////////////////////////////////////////
282 // Paragraph::Private
284 /////////////////////////////////////////////////////////////////////
286 class Paragraph::Private
288 // Enforce our own "copy" constructor
289 Private(Private const &) = delete;
290 Private & operator=(Private const &) = delete;
291 // Unique ID generator
292 static int make_id();
295 Private(Paragraph * owner, Layout const & layout);
296 /// "Copy constructor"
297 Private(Private const &, Paragraph * owner);
298 /// Copy constructor from \p beg to \p end
299 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
302 void insertChar(pos_type pos, char_type c, Change const & change);
304 /// Output the surrogate pair formed by \p c and \p next to \p os.
305 /// \return the number of characters written.
306 int latexSurrogatePair(BufferParams const &, otexstream & os,
307 char_type c, char_type next,
308 OutputParams const &);
310 /// Output a space in appropriate formatting (or a surrogate pair
311 /// if the next character is a combining character).
312 /// \return whether a surrogate pair was output.
313 bool simpleTeXBlanks(BufferParams const &,
314 OutputParams const &,
317 unsigned int & column,
319 Layout const & style);
321 /// This could go to ParagraphParameters if we want to.
322 int startTeXParParams(BufferParams const &, otexstream &,
323 OutputParams const &) const;
325 /// This could go to ParagraphParameters if we want to.
326 bool endTeXParParams(BufferParams const &, otexstream &,
327 OutputParams const &) const;
330 void latexInset(BufferParams const &,
335 Font const & outerfont,
337 Change & running_change,
338 Layout const & style,
340 unsigned int & column,
341 bool const fontswitch_inset,
342 bool const closeLanguage,
343 bool const lang_switched_at_inset);
346 void latexSpecialChar(
348 BufferParams const & bparams,
349 OutputParams const & runparams,
350 Font const & running_font,
351 string & alien_script,
352 Layout const & style,
355 unsigned int & column);
362 unsigned int & column) const;
368 unsigned int & column) const;
374 unsigned int & column) const;
377 void validate(LaTeXFeatures & features) const;
379 /// Checks if the paragraph contains only text and no inset or font change.
380 bool onlyText(Buffer const & buf, Font const & outerfont,
381 pos_type initial) const;
383 /// a vector of speller skip positions
384 typedef vector<FontSpan> SkipPositions;
385 typedef SkipPositions::const_iterator SkipPositionsIterator;
387 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
389 Language * getSpellLanguage(pos_type const from) const;
391 Language * locateSpellRange(pos_type & from, pos_type & to,
392 SkipPositions & skips) const;
394 bool hasSpellerChange() const
396 SpellChecker::ChangeNumber speller_change_number = 0;
397 if (theSpellChecker())
398 speller_change_number = theSpellChecker()->changeNumber();
399 return speller_change_number > speller_state_.currentChangeNumber();
402 bool ignoreWord(docstring const & word) const ;
404 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
406 pos_type textsize = owner_->size();
407 // check for sane arguments
408 if (to <= from || from >= textsize)
410 FontSpan fp = FontSpan(from, to - 1);
411 speller_state_.setRange(fp, state);
414 void requestSpellCheck(pos_type pos)
417 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
419 speller_state_.needsRefresh(pos);
422 void readySpellCheck()
424 speller_state_.needsRefresh(-1);
427 bool needsSpellCheck() const
429 return speller_state_.needsRefresh();
432 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
434 speller_state_.refreshRange(first, last);
436 last = owner_->size();
439 pos_type endpos = last;
440 owner_->locateWord(first, endpos, WHOLE_WORD, true);
443 owner_->locateWord(last, endpos, WHOLE_WORD, true);
448 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
452 while (it != et && it->first < start) {
453 long skip = it->last - it->first + 1;
461 void markMisspelledWords(pos_type const & first, pos_type const & last,
462 SpellChecker::Result result,
463 docstring const & word,
464 SkipPositions const & skips);
466 InsetCode ownerCode() const
468 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
471 /// Which Paragraph owns us?
475 Inset const * inset_owner_;
481 ParagraphParameters params_;
483 /// for recording and looking up changes
487 InsetList insetlist_;
490 pos_type begin_of_body_;
492 typedef docstring TextContainer;
496 typedef set<docstring> Words;
497 typedef map<string, Words> LangWordsMap;
501 Layout const * layout_;
503 SpellCheckerState speller_state_;
509 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
510 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
517 int Paragraph::Private::make_id()
519 // The id is unique per session across buffers because it is used in
520 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
523 static int next_id(0);
528 Paragraph::Private::Private(Private const & p, Paragraph * owner)
529 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
530 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
531 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
532 layout_(p.layout_), id_(make_id())
534 requestSpellCheck(p.text_.size());
538 Paragraph::Private::Private(Private const & p, Paragraph * owner,
539 pos_type beg, pos_type end)
540 : owner_(owner), inset_owner_(p.inset_owner_),
541 params_(p.params_), changes_(p.changes_),
542 insetlist_(p.insetlist_, beg, end),
543 begin_of_body_(p.begin_of_body_), words_(p.words_),
544 layout_(p.layout_), id_(make_id())
546 if (beg >= pos_type(p.text_.size()))
548 text_ = p.text_.substr(beg, end - beg);
550 FontList::const_iterator fcit = fontlist_.begin();
551 FontList::const_iterator fend = fontlist_.end();
552 for (; fcit != fend; ++fcit) {
553 if (fcit->pos() < beg)
555 if (fcit->pos() >= end) {
556 // Add last entry in the fontlist_.
557 fontlist_.set(text_.size() - 1, fcit->font());
560 // Add a new entry in the fontlist_.
561 fontlist_.set(fcit->pos() - beg, fcit->font());
563 requestSpellCheck(p.text_.size());
567 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
568 bool output_active, TocBackend & backend) const
570 d->changes_.addToToc(cdit, buf, output_active, backend);
574 bool Paragraph::isDeleted(pos_type start, pos_type end) const
576 LASSERT(start >= 0 && start <= size(), return false);
577 LASSERT(end > start && end <= size() + 1, return false);
579 return d->changes_.isDeleted(start, end);
583 bool Paragraph::isChanged(pos_type start, pos_type end) const
585 LASSERT(start >= 0 && start <= size(), return false);
586 LASSERT(end > start && end <= size() + 1, return false);
588 return d->changes_.isChanged(start, end);
591 // FIXME: Ideally the diverse isChanged() methods should account for that!
592 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
594 LASSERT(start >= 0 && start <= size(), return false);
595 LASSERT(end > start && end <= size() + 1, return false);
597 for (auto const & icit : d->insetlist_) {
598 if (icit.pos < start)
602 if (icit.inset && icit.inset->isChanged())
608 bool Paragraph::isChanged() const
610 return d->changes_.isChanged();
614 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
616 // keep the logic here in sync with the logic of eraseChars()
620 Change const & change = d->changes_.lookup(size());
621 return change.inserted() && change.currentAuthor();
624 Change Paragraph::parEndChange() const
626 return d->changes_.lookup(size());
630 void Paragraph::setChange(Change const & change)
632 // beware of the imaginary end-of-par character!
633 d->changes_.set(change, 0, size() + 1);
636 * Propagate the change recursively - but not in case of DELETED!
638 * Imagine that your co-author makes changes in an existing inset. He
639 * sends your document to you and you come to the conclusion that the
640 * inset should go completely. If you erase it, LyX must not delete all
641 * text within the inset. Otherwise, the change tracked insertions of
642 * your co-author get lost and there is no way to restore them later.
644 * Conclusion: An inset's content should remain untouched if you delete it
647 if (!change.deleted()) {
648 for (pos_type pos = 0; pos < size(); ++pos) {
649 if (Inset * inset = getInset(pos))
650 inset->setChange(change);
656 void Paragraph::setChange(pos_type pos, Change const & change)
658 LASSERT(pos >= 0 && pos <= size(), return);
659 d->changes_.set(change, pos);
661 // see comment in setChange(Change const &) above
662 if (!change.deleted() && pos < size())
663 if (Inset * inset = getInset(pos))
664 inset->setChange(change);
668 Change const & Paragraph::lookupChange(pos_type pos) const
670 LBUFERR(pos >= 0 && pos <= size());
671 return d->changes_.lookup(pos);
675 void Paragraph::acceptChanges(pos_type start, pos_type end)
677 LASSERT(start >= 0 && start <= size(), return);
678 LASSERT(end > start && end <= size() + 1, return);
680 for (pos_type pos = start; pos < end; ++pos) {
681 switch (lookupChange(pos).type) {
682 case Change::UNCHANGED:
683 // accept changes in nested inset
684 if (Inset * inset = getInset(pos))
685 inset->acceptChanges();
688 case Change::INSERTED:
689 d->changes_.set(Change(Change::UNCHANGED), pos);
690 // also accept changes in nested inset
691 if (Inset * inset = getInset(pos))
692 inset->acceptChanges();
695 case Change::DELETED:
696 // Suppress access to non-existent
697 // "end-of-paragraph char"
699 eraseChar(pos, false);
710 void Paragraph::rejectChanges(pos_type start, pos_type end)
712 LASSERT(start >= 0 && start <= size(), return);
713 LASSERT(end > start && end <= size() + 1, return);
715 for (pos_type pos = start; pos < end; ++pos) {
716 switch (lookupChange(pos).type) {
717 case Change::UNCHANGED:
718 // reject changes in nested inset
719 if (Inset * inset = getInset(pos))
720 inset->rejectChanges();
723 case Change::INSERTED:
724 // Suppress access to non-existent
725 // "end-of-paragraph char"
727 eraseChar(pos, false);
733 case Change::DELETED:
734 d->changes_.set(Change(Change::UNCHANGED), pos);
736 // Do NOT reject changes within a deleted inset!
737 // There may be insertions of a co-author inside of it!
745 void Paragraph::Private::insertChar(pos_type pos, char_type c,
746 Change const & change)
748 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
751 changes_.insert(change, pos);
753 // This is actually very common when parsing buffers (and
754 // maybe inserting ascii text)
755 if (pos == pos_type(text_.size())) {
756 // when appending characters, no need to update tables
758 // but we want spell checking
759 requestSpellCheck(pos);
763 text_.insert(text_.begin() + pos, c);
765 // Update the font table.
766 fontlist_.increasePosAfterPos(pos);
769 insetlist_.increasePosAfterPos(pos);
771 // Update list of misspelled positions
772 speller_state_.increasePosAfterPos(pos);
776 bool Paragraph::insertInset(pos_type pos, Inset * inset,
777 Font const & font, Change const & change)
779 LASSERT(inset, return false);
780 LASSERT(pos >= 0 && pos <= size(), return false);
782 // Paragraph::insertInset() can be used in cut/copy/paste operation where
783 // d->inset_owner_ is not set yet.
784 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
787 d->insertChar(pos, META_INSET, change);
788 LASSERT(d->text_[pos] == META_INSET, return false);
790 // Add a new entry in the insetlist_.
791 d->insetlist_.insert(inset, pos);
793 // Some insets require run of spell checker
794 requestSpellCheck(pos);
800 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
802 LASSERT(pos >= 0 && pos <= size(), return false);
804 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
807 Change change = d->changes_.lookup(pos);
809 // set the character to DELETED if
810 // a) it was previously unchanged or
811 // b) it was inserted by a co-author
813 if (!change.changed() ||
814 (change.inserted() && !change.currentAuthor())) {
815 setChange(pos, Change(Change::DELETED));
816 // request run of spell checker
817 requestSpellCheck(pos);
821 if (change.deleted())
825 // Don't physically access the imaginary end-of-paragraph character.
826 // eraseChar() can only mark it as DELETED. A physical deletion of
827 // end-of-par must be handled externally.
833 d->changes_.erase(pos);
835 // if it is an inset, delete the inset entry
836 if (d->text_[pos] == META_INSET)
837 d->insetlist_.erase(pos);
839 d->text_.erase(d->text_.begin() + pos);
841 // Update the fontlist_
842 d->fontlist_.erase(pos);
844 // Update the insetlist_
845 d->insetlist_.decreasePosAfterPos(pos);
847 // Update list of misspelled positions
848 d->speller_state_.decreasePosAfterPos(pos);
849 d->speller_state_.refreshLast(size());
855 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
857 LASSERT(start >= 0 && start <= size(), return 0);
858 LASSERT(end >= start && end <= size() + 1, return 0);
861 for (pos_type count = end - start; count; --count) {
862 if (!eraseChar(i, trackChanges))
868 // Handle combining characters
869 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
870 otexstream & os, char_type c, char_type next,
871 OutputParams const & runparams)
873 // Writing next here may circumvent a possible font change between
874 // c and next. Since next is only output if it forms a surrogate pair
875 // with c we can ignore this:
876 // A font change inside a surrogate pair does not make sense and is
877 // hopefully impossible to input.
878 // FIXME: change tracking
879 // Is this correct WRT change tracking?
880 Encoding const & encoding = *(runparams.encoding);
881 docstring latex1 = encoding.latexChar(next).first;
882 if (runparams.inIPA) {
883 string const tipashortcut = Encodings::TIPAShortcut(next);
884 if (!tipashortcut.empty()) {
885 latex1 = from_ascii(tipashortcut);
888 docstring latex2 = encoding.latexChar(c).first;
890 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
891 // Encoding supports the combination:
892 // output as is (combining char after base char).
893 os << latex2 << latex1;
894 return latex1.length() + latex2.length();
897 os << latex1 << "{" << latex2 << "}";
898 return latex1.length() + latex2.length() + 2;
902 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
903 OutputParams const & runparams,
906 unsigned int & column,
908 Layout const & style)
910 if (style.pass_thru || runparams.pass_thru)
913 if (i + 1 < int(text_.size())) {
914 char_type next = text_[i + 1];
915 if (Encodings::isCombiningChar(next)) {
916 // This space has an accent, so we must always output it.
917 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
922 if (runparams.linelen > 0
923 && column > runparams.linelen
925 && text_[i - 1] != ' '
926 && (i + 1 < int(text_.size()))
927 // same in FreeSpacing mode
928 && !owner_->isFreeSpacing()
929 // In typewriter mode, we want to avoid
930 // ! . ? : at the end of a line
931 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
932 && (text_[i - 1] == '.'
933 || text_[i - 1] == '?'
934 || text_[i - 1] == ':'
935 || text_[i - 1] == '!'))) {
937 os.texrow().start(owner_->id(), i + 1);
939 } else if (style.free_spacing) {
948 void Paragraph::Private::latexInset(BufferParams const & bparams,
950 OutputParams & runparams,
953 Font const & outerfont,
955 Change & running_change,
956 Layout const & style,
958 unsigned int & column,
959 bool const fontswitch_inset,
960 bool const closeLanguage,
961 bool const lang_switched_at_inset)
963 Inset * inset = owner_->getInset(i);
966 if (style.pass_thru) {
967 odocstringstream ods;
968 inset->plaintext(ods, runparams);
973 // FIXME: move this to InsetNewline::latex
974 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
975 // newlines are handled differently here than
976 // the default in simpleTeXSpecialChars().
977 if (!style.newline_allowed) {
981 bool needPar = false;
982 column += running_font.latexWriteEndChanges(
983 os, bparams, runparams,
984 basefont, basefont, needPar);
988 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
991 basefont = owner_->getLayoutFont(bparams, outerfont);
992 running_font = basefont;
994 if (runparams.moving_arg)
998 os.texrow().start(owner_->id(), i + 1);
1002 if (owner_->isDeleted(i)) {
1003 if( ++runparams.inDeletedInset == 1)
1004 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1007 if (inset->canTrackChanges()) {
1008 column += Changes::latexMarkChange(os, bparams, running_change,
1009 Change(Change::UNCHANGED), runparams);
1010 running_change = Change(Change::UNCHANGED);
1014 odocstream::pos_type const len = os.os().tellp();
1016 if (inset->forceLTR(runparams)
1017 && running_font.isRightToLeft()
1018 // ERT is an exception, it should be output with no
1019 // decorations at all
1020 && inset->lyxCode() != ERT_CODE) {
1021 if (runparams.use_polyglossia) {
1023 } else if (running_font.language()->lang() == "farsi"
1024 || running_font.language()->lang() == "arabic_arabi")
1025 os << "\\textLR{" << termcmd;
1031 if (open_font && fontswitch_inset) {
1032 bool lang_closed = false;
1033 // Close language if needed
1034 if (closeLanguage && !lang_switched_at_inset) {
1035 // We need prev_font here as language changes directly at inset
1036 // will only be started inside the inset.
1037 Font const prev_font = (i > 0) ?
1038 owner_->getFont(bparams, i - 1, outerfont)
1040 Font tmpfont(basefont);
1041 tmpfont.setLanguage(prev_font.language());
1042 bool needPar = false;
1043 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1045 needPar, closeLanguage);
1047 lang_closed = count > 0;
1049 // Update the running_font, making sure, however,
1050 // to leave the language as it was.
1051 // FIXME: probably a better way to keep track of the old
1052 // language, than copying the entire font?
1053 Font const copy_font(running_font);
1054 basefont = owner_->getLayoutFont(bparams, outerfont);
1055 running_font = basefont;
1057 running_font.setLanguage(copy_font.language());
1058 OutputParams rp = runparams;
1059 rp.encoding = basefont.language()->encoding();
1060 // For these, we use switches, so they should be taken as
1061 // base inside the inset.
1062 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1063 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1064 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1065 // Now re-do font changes in a way needed here
1066 // (using switches with multi-par insets)
1067 InsetText const * textinset = inset->asInsetText();
1068 bool const cprotect = textinset
1069 ? textinset->hasCProtectContent(runparams.moving_arg)
1070 && !textinset->text().isMainText()
1072 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1078 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1082 runparams.local_font = &basefont;
1085 if (fontswitch_inset && !closeLanguage) {
1086 // The directionality has been switched at inset.
1087 // Force markup inside.
1088 runparams.local_font = &basefont;
1091 size_t const previous_row_count = os.texrow().rows();
1094 runparams.lastid = id_;
1095 runparams.lastpos = i;
1096 inset->latex(os, runparams);
1097 } catch (EncodingException & e) {
1098 // add location information and throw again.
1107 if (os.texrow().rows() > previous_row_count) {
1108 os.texrow().start(owner_->id(), i + 1);
1111 column += (unsigned int)(os.os().tellp() - len);
1114 if (owner_->isDeleted(i))
1115 --runparams.inDeletedInset;
1119 void Paragraph::Private::latexSpecialChar(otexstream & os,
1120 BufferParams const & bparams,
1121 OutputParams const & runparams,
1122 Font const & running_font,
1123 string & alien_script,
1124 Layout const & style,
1127 unsigned int & column)
1129 char_type const c = owner_->getUChar(bparams, runparams, i);
1131 if (style.pass_thru || runparams.pass_thru
1132 || contains(style.pass_thru_chars, c)
1133 || contains(runparams.pass_thru_chars, c)) {
1135 Encoding const * const enc = runparams.encoding;
1136 if (enc && !enc->encodable(c))
1137 throw EncodingException(c);
1143 // TIPA uses its own T3 encoding
1144 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1146 // If T1 font encoding is used, use the special
1147 // characters it provides.
1148 // NOTE: Some languages reset the font encoding internally to a
1149 // non-standard font encoding. If we are using such a language,
1150 // we do not output special T1 chars.
1151 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1152 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1153 && latexSpecialT1(c, os, i, column))
1155 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1156 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1157 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1160 // Otherwise, we use what LaTeX provides us.
1163 os << "\\textbackslash" << termcmd;
1167 os << "\\textless" << termcmd;
1171 os << "\\textgreater" << termcmd;
1175 os << "\\textbar" << termcmd;
1180 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1181 (end_pos == -1 || i + 1 < end_pos) &&
1182 text_[i+1] == '-') {
1183 // Prevent "--" becoming an en dash and "---" an em dash.
1184 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1190 os << "\\textquotedbl" << termcmd;
1195 case '%': case '#': case '{':
1203 os << "\\textasciitilde" << termcmd;
1208 os << "\\textasciicircum" << termcmd;
1215 // avoid being mistaken for optional arguments
1223 // Blanks are printed before font switching.
1224 // Sure? I am not! (try nice-latex)
1225 // I am sure it's correct. LyX might be smarter
1226 // in the future, but for now, nothing wrong is
1232 // XeTeX's dash behaviour is determined via a global setting
1233 if (bparams.use_dash_ligatures
1234 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1236 // TODO #10961: && not in inset Flex Code
1237 // TODO #10961: && not in layout LyXCode
1238 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1255 Encoding const & encoding = *(runparams.encoding);
1256 char_type next = '\0';
1257 if (i + 1 < int(text_.size())) {
1258 next = text_[i + 1];
1259 if (Encodings::isCombiningChar(next)) {
1260 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1265 pair<docstring, bool> latex = encoding.latexChar(c);
1266 docstring nextlatex;
1267 bool nexttipas = false;
1268 string nexttipashortcut;
1269 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1270 nextlatex = encoding.latexChar(next).first;
1271 if (runparams.inIPA) {
1272 nexttipashortcut = Encodings::TIPAShortcut(next);
1273 nexttipas = !nexttipashortcut.empty();
1277 if (runparams.inIPA) {
1278 string const tipashortcut = Encodings::TIPAShortcut(c);
1279 if (!tipashortcut.empty()) {
1280 latex.first = from_ascii(tipashortcut);
1281 latex.second = false;
1285 // eventually close "script wrapper" command (see `Paragraph::latex`)
1286 if (!alien_script.empty()
1287 && alien_script != Encodings::isKnownScriptChar(next)) {
1288 column += latex.first.length();
1289 alien_script.clear();
1290 os << latex.first << "}";
1294 && ((!prefixIs(nextlatex, '\\')
1295 && !prefixIs(nextlatex, '{')
1296 && !prefixIs(nextlatex, '}'))
1298 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1300 // Prevent eating of a following space or command corruption by
1301 // following characters
1302 if (next == ' ' || next == '\0') {
1303 column += latex.first.length() + 1;
1304 os << latex.first << "{}";
1306 column += latex.first.length();
1307 os << latex.first << " ";
1310 column += latex.first.length() - 1;
1318 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1319 pos_type i, unsigned int & column) const
1325 // In T1 encoding, these characters exist
1326 // but we should avoid ligatures
1327 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1329 os << "\\textcompwordmark" << termcmd;
1336 // soul.sty breaks with \char`\"
1337 os << "\\textquotedbl" << termcmd;
1346 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1347 pos_type i, unsigned int & column) const
1349 // TU encoding is currently on par with T1.
1350 return latexSpecialT1(c, os, i, column);
1354 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1355 pos_type /*i*/, unsigned int & column) const
1365 os << "\\textvertline" << termcmd;
1374 void Paragraph::Private::validate(LaTeXFeatures & features) const
1376 if (layout_->inpreamble && inset_owner_) {
1377 // FIXME: Using a string stream here circumvents the encoding
1378 // switching machinery of odocstream. Therefore the
1379 // output is wrong if this paragraph contains content
1380 // that needs to switch encoding.
1381 Buffer const & buf = inset_owner_->buffer();
1382 otexstringstream os;
1383 os << layout_->preamble();
1384 size_t const length = os.length();
1385 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1386 buf.getParFromID(owner_->id()).pit(), os,
1387 features.runparams(), string(), 0, -1, true);
1388 if (os.length() > length)
1389 features.addPreambleSnippet(os.release(), true);
1392 if (features.runparams().flavor == OutputParams::HTML
1393 && layout_->htmltitle()) {
1394 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1397 // check the params.
1398 if (!params_.spacing().isDefault())
1399 features.require("setspace");
1402 features.useLayout(layout_->name());
1405 fontlist_.validate(features);
1407 // then the indentation
1408 if (!params_.leftIndent().zero())
1409 features.require("ParagraphLeftIndent");
1412 InsetList::const_iterator icit = insetlist_.begin();
1413 InsetList::const_iterator iend = insetlist_.end();
1414 for (; icit != iend; ++icit) {
1416 features.inDeletedInset(owner_->isDeleted(icit->pos));
1417 if (icit->inset->lyxCode() == FOOT_CODE) {
1418 // FIXME: an item inset would make things much easier.
1419 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1420 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1421 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1422 && (icit->pos < begin_of_body_
1423 || (icit->pos == begin_of_body_
1424 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1425 features.saveNoteEnv("description");
1427 icit->inset->validate(features);
1428 features.inDeletedInset(false);
1429 if (layout_->needprotect &&
1430 icit->inset->lyxCode() == FOOT_CODE)
1431 features.require("NeedLyXFootnoteCode");
1435 // then the contents
1436 BufferParams const bp = features.runparams().is_child
1437 ? features.buffer().masterParams() : features.buffer().params();
1438 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1439 char_type c = text_[i];
1440 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1442 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1443 features.require("textquotedblp");
1444 else if (bp.main_font_encoding() != "T1"
1445 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1446 features.require("textquotedbl");
1447 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1448 // features that depend on the font or input encoding
1449 string feats = ci.textpreamble();
1450 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1451 if (fontenc.empty())
1452 fontenc = features.runparams().main_fontenc;
1453 while (!feats.empty()) {
1455 feats = split(feats, feat, ',');
1456 if (contains(feat, "!=")) {
1457 // a feature that is required except for the spcified
1458 // font or input encodings
1460 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1461 // multiple encodings are separated by semicolon
1462 vector<string> context = getVectorFromString(contexts, ";");
1463 // require feature if the context matches neither current font
1464 // nor input encoding
1465 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1466 && std::find(context.begin(), context.end(),
1467 features.runparams().encoding->name()) == context.end())
1468 features.require(realfeature);
1469 } else if (contains(feat, '=')) {
1470 // a feature that is required only for the spcified
1471 // font or input encodings
1473 string const contexts = split(feat, realfeature, '=');
1474 // multiple encodings are separated by semicolon
1475 vector<string> context = getVectorFromString(contexts, ";");
1476 // require feature if the context matches either current font
1477 // or input encoding
1478 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1479 || std::find(context.begin(), context.end(),
1480 features.runparams().encoding->name()) != context.end())
1481 features.require(realfeature);
1484 } else if (!bp.use_dash_ligatures
1485 && (c == 0x2013 || c == 0x2014)
1486 && bp.useNonTeXFonts
1487 && features.runparams().flavor == OutputParams::XETEX)
1488 // XeTeX's dash behaviour is determined via a global setting
1489 features.require("xetexdashbreakstate");
1490 BufferEncodings::validate(c, features);
1494 /////////////////////////////////////////////////////////////////////
1498 /////////////////////////////////////////////////////////////////////
1501 Layout const emptyParagraphLayout;
1504 Paragraph::Paragraph()
1505 : d(new Paragraph::Private(this, emptyParagraphLayout))
1512 Paragraph::Paragraph(Paragraph const & par)
1513 : itemdepth(par.itemdepth),
1514 d(new Paragraph::Private(*par.d, this))
1520 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1521 : itemdepth(par.itemdepth),
1522 d(new Paragraph::Private(*par.d, this, beg, end))
1528 Paragraph & Paragraph::operator=(Paragraph const & par)
1530 // needed as we will destroy the private part before copying it
1532 itemdepth = par.itemdepth;
1536 d = new Private(*par.d, this);
1543 Paragraph::~Paragraph()
1552 // this shall be called just before every "os << ..." action.
1553 void flushString(ostream & os, docstring & s)
1562 void Paragraph::write(ostream & os, BufferParams const & bparams,
1563 depth_type & depth) const
1565 // The beginning or end of a deeper (i.e. nested) area?
1566 if (depth != d->params_.depth()) {
1567 if (d->params_.depth() > depth) {
1568 while (d->params_.depth() > depth) {
1569 os << "\n\\begin_deeper";
1573 while (d->params_.depth() < depth) {
1574 os << "\n\\end_deeper";
1580 // First write the layout
1581 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1583 d->params_.write(os);
1585 Font font1(inherit_font, bparams.language);
1587 Change running_change = Change(Change::UNCHANGED);
1589 // this string is used as a buffer to avoid repetitive calls
1590 // to to_utf8(), which turn out to be expensive (JMarc)
1591 docstring write_buffer;
1594 for (pos_type i = 0; i <= size(); ++i) {
1596 Change const & change = lookupChange(i);
1597 if (change != running_change)
1598 flushString(os, write_buffer);
1599 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1600 running_change = change;
1605 // Write font changes
1606 Font font2 = getFontSettings(bparams, i);
1607 if (font2 != font1) {
1608 flushString(os, write_buffer);
1609 font2.lyxWriteChanges(font1, os);
1614 char_type const c = d->text_[i];
1617 if (Inset const * inset = getInset(i)) {
1618 flushString(os, write_buffer);
1619 if (inset->directWrite()) {
1620 // international char, let it write
1621 // code directly so it's shorter in
1627 os << "\\begin_inset ";
1629 os << "\n\\end_inset\n\n";
1632 // FIXME This can be removed again once the mystery
1633 // crash has been resolved.
1638 flushString(os, write_buffer);
1639 os << "\n\\backslash\n";
1643 flushString(os, write_buffer);
1644 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1651 if ((column > 70 && c == ' ')
1653 flushString(os, write_buffer);
1657 // this check is to amend a bug. LyX sometimes
1658 // inserts '\0' this could cause problems.
1660 write_buffer.push_back(c);
1662 LYXERR0("NUL char in structure.");
1668 flushString(os, write_buffer);
1669 os << "\n\\end_layout\n";
1670 // FIXME This can be removed again once the mystery
1671 // crash has been resolved.
1676 void Paragraph::validate(LaTeXFeatures & features) const
1678 d->validate(features);
1679 bool fragile = features.runparams().moving_arg;
1680 fragile |= layout().needprotect;
1681 if (inInset().getLayout().isNeedProtect())
1683 if (needsCProtection(fragile))
1684 features.require("cprotect");
1688 void Paragraph::insert(pos_type pos, docstring const & str,
1689 Font const & font, Change const & change)
1691 for (size_t i = 0, n = str.size(); i != n ; ++i)
1692 insertChar(pos + i, str[i], font, change);
1696 void Paragraph::appendChar(char_type c, Font const & font,
1697 Change const & change)
1700 d->changes_.insert(change, d->text_.size());
1701 // when appending characters, no need to update tables
1702 d->text_.push_back(c);
1703 setFont(d->text_.size() - 1, font);
1704 d->requestSpellCheck(d->text_.size() - 1);
1708 void Paragraph::appendString(docstring const & s, Font const & font,
1709 Change const & change)
1711 pos_type end = s.size();
1712 size_t oldsize = d->text_.size();
1713 size_t newsize = oldsize + end;
1714 size_t capacity = d->text_.capacity();
1715 if (newsize >= capacity)
1716 d->text_.reserve(max(capacity + 100, newsize));
1718 // when appending characters, no need to update tables
1721 // FIXME: Optimize this!
1722 for (size_t i = oldsize; i != newsize; ++i) {
1724 d->changes_.insert(change, i);
1725 d->requestSpellCheck(i);
1727 d->fontlist_.set(oldsize, font);
1728 d->fontlist_.set(newsize - 1, font);
1732 void Paragraph::insertChar(pos_type pos, char_type c,
1735 d->insertChar(pos, c, Change(trackChanges ?
1736 Change::INSERTED : Change::UNCHANGED));
1740 void Paragraph::insertChar(pos_type pos, char_type c,
1741 Font const & font, bool trackChanges)
1743 d->insertChar(pos, c, Change(trackChanges ?
1744 Change::INSERTED : Change::UNCHANGED));
1749 void Paragraph::insertChar(pos_type pos, char_type c,
1750 Font const & font, Change const & change)
1752 d->insertChar(pos, c, change);
1757 void Paragraph::resetFonts(Font const & font)
1759 d->fontlist_.clear();
1760 d->fontlist_.set(0, font);
1761 d->fontlist_.set(d->text_.size() - 1, font);
1764 // Gets uninstantiated font setting at position.
1765 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1769 LYXERR0("pos: " << pos << " size: " << size());
1773 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1774 if (cit != d->fontlist_.end())
1777 if (pos == size() && !empty())
1778 return getFontSettings(bparams, pos - 1);
1780 // Optimisation: avoid a full font instantiation if there is no
1781 // language change from previous call.
1782 static Font previous_font;
1783 static Language const * previous_lang = nullptr;
1784 Language const * lang = getParLanguage(bparams);
1785 if (lang != previous_lang) {
1786 previous_lang = lang;
1787 previous_font = Font(inherit_font, lang);
1789 return previous_font;
1793 FontSpan Paragraph::fontSpan(pos_type pos) const
1795 LBUFERR(pos <= size());
1798 return FontSpan(pos, pos);
1801 FontList::const_iterator cit = d->fontlist_.begin();
1802 FontList::const_iterator end = d->fontlist_.end();
1803 for (; cit != end; ++cit) {
1804 if (cit->pos() >= pos) {
1805 if (pos >= beginOfBody())
1806 return FontSpan(max(start, beginOfBody()),
1809 return FontSpan(start,
1810 min(beginOfBody() - 1,
1813 start = cit->pos() + 1;
1816 // This should not happen, but if so, we take no chances.
1817 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1818 LASSERT(false, return FontSpan(pos, pos));
1822 // Gets uninstantiated font setting at position 0
1823 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1825 if (!empty() && !d->fontlist_.empty())
1826 return d->fontlist_.begin()->font();
1828 // Optimisation: avoid a full font instantiation if there is no
1829 // language change from previous call.
1830 static Font previous_font;
1831 static Language const * previous_lang = nullptr;
1832 if (bparams.language != previous_lang) {
1833 previous_lang = bparams.language;
1834 previous_font = Font(inherit_font, bparams.language);
1837 return previous_font;
1841 // Gets the fully instantiated font at a given position in a paragraph
1842 // This is basically the same function as Text::GetFont() in text2.cpp.
1843 // The difference is that this one is used for generating the LaTeX file,
1844 // and thus cosmetic "improvements" are disallowed: This has to deliver
1845 // the true picture of the buffer. (Asger)
1846 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1847 Font const & outerfont) const
1851 Font font = getFontSettings(bparams, pos);
1853 pos_type const body_pos = beginOfBody();
1854 FontInfo & fi = font.fontInfo();
1856 fi.realize(d->layout_->labelfont);
1858 fi.realize(d->layout_->font);
1860 fi.realize(outerfont.fontInfo());
1861 fi.realize(bparams.getFont().fontInfo());
1867 Font const Paragraph::getLabelFont
1868 (BufferParams const & bparams, Font const & outerfont) const
1870 FontInfo tmpfont = d->layout_->labelfont;
1871 tmpfont.realize(outerfont.fontInfo());
1872 tmpfont.realize(bparams.getFont().fontInfo());
1873 return Font(tmpfont, getParLanguage(bparams));
1877 Font const Paragraph::getLayoutFont
1878 (BufferParams const & bparams, Font const & outerfont) const
1880 FontInfo tmpfont = d->layout_->font;
1881 tmpfont.realize(outerfont.fontInfo());
1882 tmpfont.realize(bparams.getFont().fontInfo());
1883 return Font(tmpfont, getParLanguage(bparams));
1887 char_type Paragraph::getUChar(BufferParams const & bparams,
1888 OutputParams const & rp,
1891 char_type c = d->text_[pos];
1893 // Return unchanged character in LTR languages
1894 // or if we use poylglossia/bidi (XeTeX).
1895 if (rp.useBidiPackage()
1896 || !getFontSettings(bparams, pos).isRightToLeft())
1899 // Without polyglossia/bidi, we need to account for some special cases.
1900 // FIXME This needs to be audited!
1902 // * The input is as expected for all delimiters
1903 // => checked for Hebrew!
1904 // * The output matches the display in the LyX workarea
1905 // => checked for Hebrew!
1906 // * The special cases below are really necessary
1907 // => checked for Hebrew!
1908 // * In arabic_arabi, brackets are transformed to Arabic
1909 // Ornate Parentheses. Is this is really wanted?
1911 string const & lang = getFontSettings(bparams, pos).language()->lang();
1914 // 1. In the following languages, parentheses need to be reversed.
1915 // Also with polyglodia/luabidi
1916 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1918 // 2. In the following languages, brackets don't need to be reversed.
1919 bool const reversebrackets = lang != "arabic_arabtex"
1920 && lang != "arabic_arabi"
1923 // Now swap delimiters if needed.
1934 if (reversebrackets)
1938 if (reversebrackets)
1959 void Paragraph::setFont(pos_type pos, Font const & font)
1961 LASSERT(pos <= size(), return);
1963 // First, reduce font against layout/label font
1964 // Update: The setCharFont() routine in text2.cpp already
1965 // reduces font, so we don't need to do that here. (Asger)
1967 d->fontlist_.set(pos, font);
1971 void Paragraph::makeSameLayout(Paragraph const & par)
1973 d->layout_ = par.d->layout_;
1974 d->params_ = par.d->params_;
1978 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1980 if (isFreeSpacing())
1986 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1987 if (eraseChar(pos, trackChanges))
1993 return count > 0 || pos > 0;
1997 bool Paragraph::hasSameLayout(Paragraph const & par) const
1999 return par.d->layout_ == d->layout_
2000 && d->params_.sameLayout(par.d->params_);
2004 depth_type Paragraph::getDepth() const
2006 return d->params_.depth();
2010 depth_type Paragraph::getMaxDepthAfter() const
2012 if (d->layout_->isEnvironment())
2013 return d->params_.depth() + 1;
2015 return d->params_.depth();
2019 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2021 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2022 return getDefaultAlign(bparams);
2024 return d->params_.align();
2028 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2030 LyXAlignment res = layout().align;
2031 if (isRTL(bparams)) {
2033 if (res == LYX_ALIGN_LEFT)
2034 res = LYX_ALIGN_RIGHT;
2035 else if (res == LYX_ALIGN_RIGHT)
2036 res = LYX_ALIGN_LEFT;
2042 docstring const & Paragraph::labelString() const
2044 return d->params_.labelString();
2048 // the next two functions are for the manual labels
2049 docstring const Paragraph::getLabelWidthString() const
2051 if (d->layout_->margintype == MARGIN_MANUAL
2052 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2053 return d->params_.labelWidthString();
2055 return _("Senseless with this layout!");
2059 void Paragraph::setLabelWidthString(docstring const & s)
2061 d->params_.labelWidthString(s);
2065 docstring Paragraph::expandLabel(Layout const & layout,
2066 BufferParams const & bparams) const
2068 return expandParagraphLabel(layout, bparams, true);
2072 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2073 BufferParams const & bparams, bool process_appendix) const
2075 DocumentClass const & tclass = bparams.documentClass();
2076 string const & lang = getParLanguage(bparams)->code();
2077 bool const in_appendix = process_appendix && d->params_.appendix();
2078 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2080 if (fmt.empty() && !layout.counter.empty())
2081 return tclass.counters().theCounter(layout.counter, lang);
2083 // handle 'inherited level parts' in 'fmt',
2084 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2085 size_t const i = fmt.find('@', 0);
2086 if (i != docstring::npos) {
2087 size_t const j = fmt.find('@', i + 1);
2088 if (j != docstring::npos) {
2089 docstring parent(fmt, i + 1, j - i - 1);
2090 docstring label = from_ascii("??");
2091 if (tclass.hasLayout(parent))
2092 label = expandParagraphLabel(tclass[parent], bparams,
2094 fmt = docstring(fmt, 0, i) + label
2095 + docstring(fmt, j + 1, docstring::npos);
2099 return tclass.counters().counterLabel(fmt, lang);
2103 void Paragraph::applyLayout(Layout const & new_layout)
2105 d->layout_ = &new_layout;
2106 LyXAlignment const oldAlign = d->params_.align();
2108 if (!(oldAlign & d->layout_->alignpossible)) {
2109 frontend::Alert::warning(_("Alignment not permitted"),
2110 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2111 d->params_.align(LYX_ALIGN_LAYOUT);
2116 pos_type Paragraph::beginOfBody() const
2118 return d->begin_of_body_;
2122 void Paragraph::setBeginOfBody()
2124 if (d->layout_->labeltype != LABEL_MANUAL) {
2125 d->begin_of_body_ = 0;
2129 // Unroll the first two cycles of the loop
2130 // and remember the previous character to
2131 // remove unnecessary getChar() calls
2133 pos_type end = size();
2134 bool prev_char_deleted = false;
2135 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2138 char_type previous_char = d->text_[i];
2139 if (!(isNewline(i) || isEnvSeparator(i))) {
2141 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2142 char_type temp = d->text_[i];
2143 prev_char_deleted = isDeleted(i);
2144 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2147 previous_char = temp;
2153 d->begin_of_body_ = i;
2157 bool Paragraph::allowParagraphCustomization() const
2159 return inInset().allowParagraphCustomization();
2163 bool Paragraph::usePlainLayout() const
2165 return inInset().usePlainLayout();
2169 bool Paragraph::isPassThru() const
2171 return inInset().isPassThru() || d->layout_->pass_thru;
2176 // paragraphs inside floats need different alignment tags to avoid
2179 bool noTrivlistCentering(InsetCode code)
2181 return code == FLOAT_CODE
2182 || code == WRAP_CODE
2183 || code == CELL_CODE;
2187 string correction(string const & orig)
2189 if (orig == "flushleft")
2190 return "raggedright";
2191 if (orig == "flushright")
2192 return "raggedleft";
2193 if (orig == "center")
2199 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2200 InsetCode code, bool const lastpar, int & col)
2202 string macro = suffix + "{";
2203 if (noTrivlistCentering(code)) {
2205 // the last paragraph in non-trivlist-aligned
2206 // context is special (to avoid unwanted whitespace)
2207 if (suffix == "\\begin") {
2208 macro = "\\" + correction(env) + "{}";
2209 os << from_ascii(macro);
2210 col += macro.size();
2215 macro += correction(env);
2219 if (suffix == "\\par\\end") {
2223 os << from_ascii(macro);
2224 col += macro.size();
2225 if (suffix == "\\begin") {
2235 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2236 otexstream & os, OutputParams const & runparams) const
2241 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2242 (layout_->toggle_indent != ITOGGLE_NEVER) :
2243 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2245 if (canindent && params_.noindent() && !layout_->pass_thru) {
2246 os << "\\noindent ";
2250 LyXAlignment const curAlign = params_.align();
2252 if (curAlign == layout_->align)
2256 case LYX_ALIGN_NONE:
2257 case LYX_ALIGN_BLOCK:
2258 case LYX_ALIGN_LAYOUT:
2259 case LYX_ALIGN_SPECIAL:
2260 case LYX_ALIGN_DECIMAL:
2262 case LYX_ALIGN_LEFT:
2263 case LYX_ALIGN_RIGHT:
2264 case LYX_ALIGN_CENTER:
2265 if (runparams.moving_arg) {
2272 string const begin_tag = "\\begin";
2273 InsetCode code = ownerCode();
2274 bool const lastpar = runparams.isLastPar;
2275 // RTL in classic (PDF)LaTeX (without the Bidi package)
2276 // Luabibdi (used by LuaTeX) behaves like classic
2277 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2278 && !runparams.useBidiPackage();
2281 case LYX_ALIGN_NONE:
2282 case LYX_ALIGN_BLOCK:
2283 case LYX_ALIGN_LAYOUT:
2284 case LYX_ALIGN_SPECIAL:
2285 case LYX_ALIGN_DECIMAL:
2287 case LYX_ALIGN_LEFT: {
2289 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2290 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2292 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2294 } case LYX_ALIGN_RIGHT: {
2296 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2297 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2299 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2301 } case LYX_ALIGN_CENTER: {
2302 corrected_env(os, begin_tag, "center", code, lastpar, column);
2311 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2312 otexstream & os, OutputParams const & runparams) const
2314 LyXAlignment const curAlign = params_.align();
2316 if (curAlign == layout_->align)
2320 case LYX_ALIGN_NONE:
2321 case LYX_ALIGN_BLOCK:
2322 case LYX_ALIGN_LAYOUT:
2323 case LYX_ALIGN_SPECIAL:
2324 case LYX_ALIGN_DECIMAL:
2326 case LYX_ALIGN_LEFT:
2327 case LYX_ALIGN_RIGHT:
2328 case LYX_ALIGN_CENTER:
2329 if (runparams.moving_arg)
2334 bool output = false;
2336 string const end_tag = "\\par\\end";
2337 InsetCode code = ownerCode();
2338 bool const lastpar = runparams.isLastPar;
2339 // RTL in classic (PDF)LaTeX (without the Bidi package)
2340 // Luabibdi (used by LuaTeX) behaves like classic
2341 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2342 && !runparams.useBidiPackage();
2345 case LYX_ALIGN_NONE:
2346 case LYX_ALIGN_BLOCK:
2347 case LYX_ALIGN_LAYOUT:
2348 case LYX_ALIGN_SPECIAL:
2349 case LYX_ALIGN_DECIMAL:
2351 case LYX_ALIGN_LEFT: {
2353 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2354 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2356 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2358 } case LYX_ALIGN_RIGHT: {
2360 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2361 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2363 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2365 } case LYX_ALIGN_CENTER: {
2366 corrected_env(os, end_tag, "center", code, lastpar, col);
2371 return output || lastpar;
2375 // This one spits out the text of the paragraph
2376 void Paragraph::latex(BufferParams const & bparams,
2377 Font const & outerfont,
2379 OutputParams const & runparams,
2380 int start_pos, int end_pos, bool force) const
2382 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2384 // FIXME This check should not be needed. Perhaps issue an
2385 // error if it triggers.
2386 Layout const & style = inInset().forcePlainLayout() ?
2387 bparams.documentClass().plainLayout() : *d->layout_;
2389 if (!force && style.inpreamble)
2392 bool const allowcust = allowParagraphCustomization();
2394 // Current base font for all inherited font changes, without any
2395 // change caused by an individual character, except for the language:
2396 // It is set to the language of the first character.
2397 // As long as we are in the label, this font is the base font of the
2398 // label. Before the first body character it is set to the base font
2402 // If there is an open font-encoding changing command (script wrapper),
2403 // alien_script is set to its name
2404 string alien_script;
2407 // Maybe we have to create a optional argument.
2408 pos_type body_pos = beginOfBody();
2409 unsigned int column = 0;
2411 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2412 Font const real_outerfont = (!inInset().inheritFont()
2413 && runparams.local_font != nullptr)
2414 ? Font(runparams.local_font->fontInfo()) : outerfont;
2417 // the optional argument is kept in curly brackets in
2418 // case it contains a ']'
2419 // This is not strictly needed, but if this is changed it
2420 // would be a file format change, and tex2lyx would need
2421 // to be adjusted, since it unconditionally removes the
2422 // braces when it parses \item.
2425 basefont = getLabelFont(bparams, real_outerfont);
2427 basefont = getLayoutFont(bparams, real_outerfont);
2430 // Which font is currently active?
2431 Font running_font(basefont);
2432 // Do we have an open font change?
2433 bool open_font = false;
2435 Change runningChange = Change(Change::UNCHANGED);
2437 Encoding const * const prev_encoding = runparams.encoding;
2439 os.texrow().start(id(), 0);
2441 // if the paragraph is empty, the loop will not be entered at all
2443 // For InTitle commands, we have already opened a group
2444 // in output_latex::TeXOnePar.
2445 if (style.isCommand() && !style.intitle) {
2449 if (!style.leftdelim().empty()) {
2450 os << style.leftdelim();
2451 column += style.leftdelim().size();
2454 column += d->startTeXParParams(bparams, os, runparams);
2457 // Whether a \par can be issued for insets typeset inline with text.
2458 // Yes if greater than 0. This has to be static.
2459 THREAD_LOCAL_STATIC int parInline = 0;
2461 for (pos_type i = 0; i < size(); ++i) {
2462 // First char in paragraph or after label?
2463 if (i == body_pos) {
2466 bool needPar = false;
2467 column += running_font.latexWriteEndChanges(
2468 os, bparams, runparams,
2469 basefont, basefont, needPar);
2472 basefont = getLayoutFont(bparams, real_outerfont);
2473 running_font = basefont;
2475 column += Changes::latexMarkChange(os, bparams,
2476 runningChange, Change(Change::UNCHANGED),
2478 runningChange = Change(Change::UNCHANGED);
2483 // For InTitle commands, we have already opened a group
2484 // in output_latex::TeXOnePar.
2485 if (style.isCommand() && !style.intitle) {
2490 if (!style.leftdelim().empty()) {
2491 os << style.leftdelim();
2492 column += style.leftdelim().size();
2496 column += d->startTeXParParams(bparams, os,
2500 runparams.wasDisplayMath = runparams.inDisplayMath;
2501 runparams.inDisplayMath = false;
2502 bool deleted_display_math = false;
2503 Change const & change = runparams.inDeletedInset
2504 ? runparams.changeOfDeletedInset : lookupChange(i);
2506 char_type const c = d->text_[i];
2508 // Check whether a display math inset follows
2510 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2512 runparams.ctObject = getInset(i)->CtObject(runparams);
2514 InsetMath const * im = getInset(i)->asInsetMath();
2515 if (im && im->asHullInset()
2516 && im->asHullInset()->outerDisplay()) {
2517 runparams.inDisplayMath = true;
2518 // runparams.inDeletedInset will be set by
2519 // latexInset later, but we need this info
2520 // before it is called. On the other hand, we
2521 // cannot set it here because it is a counter.
2522 deleted_display_math = isDeleted(i);
2524 if (bparams.output_changes && deleted_display_math
2525 && runningChange == change
2526 && change.type == Change::DELETED
2527 && !os.afterParbreak()) {
2528 // A display math in the same paragraph follows.
2529 // We have to close and then reopen \lyxdeleted,
2530 // otherwise the math will be shifted up.
2531 OutputParams rp = runparams;
2533 bool needPar = false;
2534 column += running_font.latexWriteEndChanges(
2535 os, bparams, rp, basefont,
2539 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2540 : getLayoutFont(bparams, real_outerfont);
2541 running_font = basefont;
2542 column += Changes::latexMarkChange(os, bparams,
2543 Change(Change::INSERTED), change, rp);
2547 if (bparams.output_changes && runningChange != change) {
2548 if (!alien_script.empty()) {
2551 alien_script.clear();
2554 bool needPar = false;
2555 column += running_font.latexWriteEndChanges(
2556 os, bparams, runparams,
2557 basefont, basefont, needPar);
2560 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2561 : getLayoutFont(bparams, real_outerfont);
2562 running_font = basefont;
2563 column += Changes::latexMarkChange(os, bparams, runningChange,
2565 runningChange = change;
2568 // do not output text which is marked deleted
2569 // if change tracking output is disabled
2570 if (!bparams.output_changes && change.deleted()) {
2576 // Fully instantiated font
2577 Font current_font = getFont(bparams, i, outerfont);
2579 Font const prev_font = (i > 0) ?
2580 getFont(bparams, i - 1, outerfont)
2583 Font const last_font = running_font;
2584 bool const in_ct_deletion = (bparams.output_changes
2585 && runningChange == change
2586 && change.type == Change::DELETED
2587 && !os.afterParbreak());
2588 // Insets where font switches are used (rather than font commands)
2589 bool const fontswitch_inset =
2592 && getInset(i)->allowMultiPar()
2593 && getInset(i)->lyxCode() != ERT_CODE;
2595 bool closeLanguage = false;
2596 bool lang_switched_at_inset = false;
2597 if (fontswitch_inset) {
2598 // Some insets cannot be inside a font change command.
2599 // However, even such insets *can* be placed in \L or \R
2600 // or their equivalents (for RTL language switches),
2601 // so we don't close the language in those cases
2602 // (= differing isRightToLeft()).
2603 // ArabTeX, though, doesn't seem to handle this special behavior.
2604 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2605 || basefont.language()->lang() == "arabic_arabtex"
2606 || current_font.language()->lang() == "arabic_arabtex";
2607 // We need to check prev_font as language changes directly at inset
2608 // will only be started inside the inset.
2609 lang_switched_at_inset = prev_font.language() != current_font.language();
2612 // Do we need to close the previous font?
2613 bool langClosed = false;
2615 ((current_font != running_font
2616 || current_font.language() != running_font.language())
2617 || (fontswitch_inset
2618 && (current_font == prev_font))))
2620 // ensure there is no open script-wrapper
2621 if (!alien_script.empty()) {
2624 alien_script.clear();
2626 bool needPar = false;
2627 if (in_ct_deletion) {
2628 // We have to close and then reopen \lyxdeleted,
2629 // as strikeout needs to be on lowest level.
2634 // Force language closing
2635 current_font.setLanguage(basefont.language());
2636 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2637 column += running_font.latexWriteEndChanges(
2638 os, bparams, runparams, basefont,
2640 if (in_ct_deletion) {
2641 // We have to close and then reopen \lyxdeleted,
2642 // as strikeout needs to be on lowest level.
2643 OutputParams rp = runparams;
2644 column += Changes::latexMarkChange(os, bparams,
2645 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2648 // Has the language been closed in the latexWriteEndChanges() call above?
2649 langClosed = running_font.language() != basefont.language()
2650 && running_font.language() != nextfont.language()
2651 && (running_font.language()->encoding()->package() != Encoding::CJK);
2652 running_font = basefont;
2655 // if necessary, close language environment before opening CJK
2656 string const running_lang = running_font.language()->babel();
2657 string const lang_end_command = lyxrc.language_command_end;
2658 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2659 && !running_lang.empty()
2660 && running_lang == openLanguageName()
2661 && current_font.language()->encoding()->package() == Encoding::CJK) {
2662 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2663 os << from_ascii(end_tag);
2664 column += end_tag.length();
2668 // Switch file encoding if necessary (and allowed)
2669 if ((!fontswitch_inset || closeLanguage)
2670 && !runparams.pass_thru && !style.pass_thru &&
2671 runparams.encoding->package() != Encoding::none &&
2672 current_font.language()->encoding()->package() != Encoding::none) {
2673 pair<bool, int> const enc_switch =
2674 switchEncoding(os.os(), bparams, runparams,
2675 *(current_font.language()->encoding()));
2676 if (enc_switch.first) {
2677 column += enc_switch.second;
2678 runparams.encoding = current_font.language()->encoding();
2682 // A display math inset inside an ulem command will be output
2683 // as a box of width \linewidth, so we have to either disable
2684 // indentation if the inset starts a paragraph, or start a new
2685 // line to accommodate such box. This has to be done before
2686 // writing any font changing commands.
2687 if (runparams.inDisplayMath && !deleted_display_math
2688 && runparams.inulemcmd) {
2689 if (os.afterParbreak())
2695 // Do we need to change font?
2696 if ((current_font != running_font ||
2697 current_font.language() != running_font.language())
2698 && i != body_pos - 1)
2700 if (!fontswitch_inset) {
2701 if (in_ct_deletion) {
2702 // We have to close and then reopen \lyxdeleted,
2703 // as strikeout needs to be on lowest level.
2704 bool needPar = false;
2705 OutputParams rp = runparams;
2706 column += running_font.latexWriteEndChanges(
2707 os, bparams, rp, basefont,
2712 otexstringstream ots;
2713 InsetText const * textinset = inInset().asInsetText();
2714 bool const cprotect = textinset
2715 ? textinset->hasCProtectContent(runparams.moving_arg)
2716 && !textinset->text().isMainText()
2718 column += current_font.latexWriteStartChanges(ots, bparams,
2719 runparams, basefont, last_font, false,
2721 // Check again for display math in ulem commands as a
2722 // font change may also occur just before a math inset.
2723 if (runparams.inDisplayMath && !deleted_display_math
2724 && runparams.inulemcmd) {
2725 if (os.afterParbreak())
2730 running_font = current_font;
2732 docstring fontchange = ots.str();
2734 // check whether the fontchange ends with a \\textcolor
2735 // modifier and the text starts with a space. If so we
2736 // need to add } in order to prevent \\textcolor from gobbling
2737 // the space (bug 4473).
2738 docstring const last_modifier = rsplit(fontchange, '\\');
2739 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2740 os << from_ascii("{}");
2741 else if (ots.terminateCommand())
2743 if (in_ct_deletion) {
2744 // We have to close and then reopen \lyxdeleted,
2745 // as strikeout needs to be on lowest level.
2746 OutputParams rp = runparams;
2747 column += Changes::latexMarkChange(os, bparams,
2748 Change(Change::UNCHANGED), change, rp);
2751 running_font = current_font;
2752 open_font = !langClosed;
2756 // FIXME: think about end_pos implementation...
2757 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2758 // FIXME: integrate this case in latexSpecialChar
2759 // Do not print the separation of the optional argument
2760 // if style.pass_thru is false. This works because
2761 // latexSpecialChar ignores spaces if
2762 // style.pass_thru is false.
2763 if (i != body_pos - 1) {
2764 if (d->simpleTeXBlanks(bparams, runparams, os,
2765 i, column, current_font, style)) {
2766 // A surrogate pair was output. We
2767 // must not call latexSpecialChar
2768 // in this iteration, since it would output
2769 // the combining character again.
2776 OutputParams rp = runparams;
2777 rp.free_spacing = style.free_spacing;
2778 rp.local_font = ¤t_font;
2779 rp.intitle = style.intitle;
2781 // Two major modes: LaTeX or plain
2782 // Handle here those cases common to both modes
2783 // and then split to handle the two modes separately.
2784 if (c == META_INSET) {
2785 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2786 // Greyedout notes and, in general, all insets
2787 // with InsetLayout::isDisplay() == false,
2788 // are typeset inline with the text. So, we
2789 // can add a \par to the last paragraph of
2790 // such insets only if nothing else follows.
2791 bool incremented = false;
2792 Inset const * inset = getInset(i);
2793 InsetText const * textinset = inset
2794 ? inset->asInsetText()
2796 if (i + 1 == size() && textinset
2797 && !inset->getLayout().isDisplay()) {
2798 ParagraphList const & pars =
2799 textinset->text().paragraphs();
2800 pit_type const pit = pars.size() - 1;
2801 Font const lastfont =
2802 pit < 0 || pars[pit].empty()
2803 ? pars[pit].getLayoutFont(
2806 : pars[pit].getFont(bparams,
2807 pars[pit].size() - 1,
2809 if (lastfont.fontInfo().size() !=
2810 basefont.fontInfo().size()) {
2815 // We need to restore parts of this after insets with
2816 // allowMultiPar() true
2817 Font const save_basefont = basefont;
2818 d->latexInset(bparams, os, rp, running_font,
2819 basefont, real_outerfont, open_font,
2820 runningChange, style, i, column, fontswitch_inset,
2821 closeLanguage, lang_switched_at_inset);
2822 if (fontswitch_inset) {
2824 bool needPar = false;
2825 column += running_font.latexWriteEndChanges(
2826 os, bparams, runparams,
2827 basefont, basefont, needPar);
2830 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2831 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2832 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2837 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2838 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2839 // Close \lyx*deleted and force its
2840 // reopening (if needed)
2843 runningChange = Change(Change::UNCHANGED);
2844 runparams.ctObject = OutputParams::CT_NORMAL;
2847 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2848 if (!bparams.useNonTeXFonts)
2849 script = Encodings::isKnownScriptChar(c);
2850 if (script != alien_script) {
2851 if (!alien_script.empty()) {
2853 alien_script.clear();
2855 string fontenc = running_font.language()->fontenc(bparams);
2857 && !Encodings::fontencSupportsScript(fontenc, script)) {
2858 column += script.length() + 2;
2859 os << "\\" << script << "{";
2860 alien_script = script;
2864 d->latexSpecialChar(os, bparams, rp, running_font,
2865 alien_script, style, i, end_pos, column);
2866 } catch (EncodingException & e) {
2867 if (runparams.dryrun) {
2868 os << "<" << _("LyX Warning: ")
2869 << _("uncodable character") << " '";
2873 // add location information and throw again.
2881 // Set the encoding to that returned from latexSpecialChar (see
2882 // comment for encoding member in OutputParams.h)
2883 runparams.encoding = rp.encoding;
2885 // Also carry on the info on a closed ulem command for insets
2886 // such as Note that do not produce any output, so that no
2887 // command is ever executed but its opening was recorded.
2888 runparams.inulemcmd = rp.inulemcmd;
2890 // These need to be passed upstream as well
2891 runparams.need_maketitle = rp.need_maketitle;
2892 runparams.have_maketitle = rp.have_maketitle;
2894 // And finally, pass the post_macros upstream
2895 runparams.post_macro = rp.post_macro;
2898 // Close wrapper for alien script
2899 if (!alien_script.empty()) {
2901 alien_script.clear();
2904 // If we have an open font definition, we have to close it
2906 // Make sure that \\par is done with the font of the last
2907 // character if this has another size as the default.
2908 // This is necessary because LaTeX (and LyX on the screen)
2909 // calculates the space between the baselines according
2910 // to this font. (Matthias)
2912 // We must not change the font for the last paragraph
2913 // of non-multipar insets, tabular cells or commands,
2914 // since this produces unwanted whitespace.
2916 Font const font = empty()
2917 ? getLayoutFont(bparams, real_outerfont)
2918 : getFont(bparams, size() - 1, real_outerfont);
2920 InsetText const * textinset = inInset().asInsetText();
2922 bool const maintext = textinset
2923 ? textinset->text().isMainText()
2926 size_t const numpars = textinset
2927 ? textinset->text().paragraphs().size()
2930 bool needPar = false;
2932 if (style.resfont.size() != font.fontInfo().size()
2933 && (!runparams.isLastPar || maintext
2934 || (numpars > 1 && d->ownerCode() != CELL_CODE
2935 && (inInset().getLayout().isDisplay()
2937 && !style.isCommand()) {
2940 #ifdef FIXED_LANGUAGE_END_DETECTION
2942 running_font.latexWriteEndChanges(os, bparams,
2943 runparams, basefont,
2944 next_->getFont(bparams, 0, outerfont),
2947 running_font.latexWriteEndChanges(os, bparams,
2948 runparams, basefont, basefont, needPar);
2951 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2952 //FIXME: there as we start another \selectlanguage with the next paragraph if
2953 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2954 running_font.latexWriteEndChanges(os, bparams, runparams,
2955 basefont, basefont, needPar);
2958 // The \par could not be inserted at the same nesting
2959 // level of the font size change, so do it now.
2960 os << "{\\" << font.latexSize() << "\\par}";
2964 column += Changes::latexMarkChange(os, bparams, runningChange,
2965 Change(Change::UNCHANGED), runparams);
2967 // Needed if there is an optional argument but no contents.
2968 if (body_pos > 0 && body_pos == size()) {
2972 if (!style.rightdelim().empty()) {
2973 os << style.rightdelim();
2974 column += style.rightdelim().size();
2977 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2978 && runparams.encoding != prev_encoding) {
2979 runparams.encoding = prev_encoding;
2980 os << setEncoding(prev_encoding->iconvName());
2983 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2987 bool Paragraph::emptyTag() const
2989 for (pos_type i = 0; i < size(); ++i) {
2990 if (Inset const * inset = getInset(i)) {
2991 InsetCode lyx_code = inset->lyxCode();
2992 // FIXME testing like that is wrong. What is
2994 if (lyx_code != TOC_CODE &&
2995 lyx_code != INCLUDE_CODE &&
2996 lyx_code != GRAPHICS_CODE &&
2997 lyx_code != ERT_CODE &&
2998 lyx_code != LISTINGS_CODE &&
2999 lyx_code != FLOAT_CODE &&
3000 lyx_code != TABULAR_CODE) {
3004 char_type c = d->text_[i];
3005 if (c != ' ' && c != '\t')
3013 string Paragraph::getID(Buffer const &, OutputParams const &)
3016 for (pos_type i = 0; i < size(); ++i) {
3017 if (Inset const * inset = getInset(i)) {
3018 InsetCode lyx_code = inset->lyxCode();
3019 if (lyx_code == LABEL_CODE) {
3020 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3021 docstring const & id = il->getParam("name");
3022 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3030 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3033 for (i = 0; i < size(); ++i) {
3034 if (Inset const * inset = getInset(i)) {
3035 inset->docbook(xs, runparams);
3037 char_type c = d->text_[i];
3047 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3051 for (i = 0; i < size(); ++i) {
3052 if (Inset const * inset = getInset(i)) {
3053 inset->xhtml(xs, runparams);
3055 char_type c = d->text_[i];
3065 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3068 pos_type size = text_.size();
3069 for (pos_type i = initial; i < size; ++i) {
3070 Font font = owner_->getFont(buf.params(), i, outerfont);
3071 if (text_[i] == META_INSET)
3073 if (i != initial && font != font_old)
3084 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3085 vector<xml::EndFontTag> & tagsToClose,
3086 bool & flag, FontState curstate, xml::FontTypes type)
3088 if (curstate == FONT_ON) {
3089 tagsToOpen.push_back(docbookStartFontTag(type));
3092 tagsToClose.push_back(docbookEndFontTag(type));
3097 class OptionalFontType {
3102 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3103 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3106 OptionalFontType fontShapeToXml(FontShape fs)
3110 return {xml::FT_ITALIC};
3112 return {xml::FT_SLANTED};
3113 case SMALLCAPS_SHAPE:
3114 return {xml::FT_SMALLCAPS};
3119 // the other tags are for internal use
3125 OptionalFontType fontFamilyToXml(FontFamily fm)
3129 return {xml::FT_ROMAN};
3131 return {xml::FT_SANS};
3132 case TYPEWRITER_FAMILY:
3133 return {xml::FT_TYPE};
3134 case INHERIT_FAMILY:
3137 // the other tags are for internal use
3143 OptionalFontType fontSizeToXml(FontSize fs)
3147 return {xml::FT_SIZE_TINY};
3149 return {xml::FT_SIZE_SCRIPT};
3151 return {xml::FT_SIZE_FOOTNOTE};
3153 return {xml::FT_SIZE_SMALL};
3155 return {xml::FT_SIZE_LARGE};
3157 return {xml::FT_SIZE_LARGER};
3159 return {xml::FT_SIZE_LARGEST};
3161 return {xml::FT_SIZE_HUGE};
3163 return {xml::FT_SIZE_HUGER};
3165 return {xml::FT_SIZE_INCREASE};
3167 return {xml::FT_SIZE_DECREASE};
3172 // the other tags are for internal use
3178 struct DocBookFontState
3180 FontShape curr_fs = INHERIT_SHAPE;
3181 FontFamily curr_fam = INHERIT_FAMILY;
3182 FontSize curr_size = INHERIT_SIZE;
3184 // track whether we have opened these tags
3185 bool emph_flag = false;
3186 bool bold_flag = false;
3187 bool noun_flag = false;
3188 bool ubar_flag = false;
3189 bool dbar_flag = false;
3190 bool sout_flag = false;
3191 bool xout_flag = false;
3192 bool wave_flag = false;
3194 bool shap_flag = false;
3196 bool faml_flag = false;
3198 bool size_flag = false;
3201 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3203 std::string const & default_family,
3204 DocBookFontState & fs)
3206 vector<xml::FontTag> tagsToOpen;
3207 vector<xml::EndFontTag> tagsToClose;
3210 FontState curstate = font.fontInfo().emph();
3211 if (font_old.emph() != curstate)
3212 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3215 curstate = font.fontInfo().noun();
3216 if (font_old.noun() != curstate)
3217 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3220 curstate = font.fontInfo().underbar();
3221 if (font_old.underbar() != curstate)
3222 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3225 curstate = font.fontInfo().strikeout();
3226 if (font_old.strikeout() != curstate)
3227 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3230 curstate = font.fontInfo().xout();
3231 if (font_old.xout() != curstate)
3232 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3235 curstate = font.fontInfo().uuline();
3236 if (font_old.uuline() != curstate)
3237 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3240 curstate = font.fontInfo().uwave();
3241 if (font_old.uwave() != curstate)
3242 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3245 // a little hackish, but allows us to reuse what we have.
3246 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3247 if (font_old.series() != font.fontInfo().series())
3248 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3251 fs.curr_fs = font.fontInfo().shape();
3252 FontShape old_fs = font_old.shape();
3253 if (old_fs != fs.curr_fs) {
3255 OptionalFontType tag = fontShapeToXml(old_fs);
3257 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3258 fs.shap_flag = false;
3261 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3263 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3267 fs.curr_fam = font.fontInfo().family();
3268 FontFamily old_fam = font_old.family();
3269 if (old_fam != fs.curr_fam) {
3271 OptionalFontType tag = fontFamilyToXml(old_fam);
3273 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3274 fs.faml_flag = false;
3276 switch (fs.curr_fam) {
3278 // we will treat a "default" font family as roman, since we have
3279 // no other idea what to do.
3280 if (default_family != "rmdefault" && default_family != "default") {
3281 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3282 fs.faml_flag = true;
3286 if (default_family != "sfdefault") {
3287 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3288 fs.faml_flag = true;
3291 case TYPEWRITER_FAMILY:
3292 if (default_family != "ttdefault") {
3293 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3294 fs.faml_flag = true;
3297 case INHERIT_FAMILY:
3300 // the other tags are for internal use
3307 fs.curr_size = font.fontInfo().size();
3308 FontSize old_size = font_old.size();
3309 if (old_size != fs.curr_size) {
3311 OptionalFontType tag = fontSizeToXml(old_size);
3313 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3314 fs.size_flag = false;
3317 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3318 if (tag.has_value) {
3319 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3320 fs.size_flag = true;
3324 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3327 } // anonymous namespace
3330 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3331 OutputParams const & runparams,
3332 Font const & outerfont,
3335 bool ignore_fonts) const
3337 // Track whether we have opened these tags
3338 DocBookFontState fs;
3340 Layout const & style = *d->layout_;
3342 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3344 string const default_family =
3345 buf.masterBuffer()->params().fonts_default_family;
3347 vector<xml::FontTag> tagsToOpen;
3348 vector<xml::EndFontTag> tagsToClose;
3350 std::vector<docstring> generatedParagraphs;
3351 DocBookFontState old_fs = fs;
3352 odocstringstream os;
3353 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3354 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3356 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3357 // characters at some point.
3358 std::vector<char_type> delayedChars;
3360 // Parsing main loop.
3361 for (pos_type i = initial; i < size(); ++i) {
3362 // Don't show deleted material in the output.
3366 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3368 if (getInset(i) != nullptr && getInset(i)->lyxCode() == NEWLINE_CODE) {
3370 xs->closeFontTags();
3372 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3373 generatedParagraphs.push_back(os.str());
3375 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3376 // that the string stream must be reset.
3377 os.str(from_ascii(""));
3379 xs = new XMLStream(os);
3381 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3382 if (!ignore_fonts) {
3383 font_old = outerfont.fontInfo();
3388 // Determine which tags should be opened or closed regarding fonts.
3389 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3390 if (!ignore_fonts) {
3391 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3394 // Other such tags? What about the other text ranges?
3396 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3397 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3398 for (; cit != cen; ++cit)
3401 // Deal with the delayed characters *after* closing font tags.
3402 if (!delayedChars.empty()) {
3403 for (char_type c: delayedChars)
3405 delayedChars.clear();
3408 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3409 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3410 for (; sit != sen; ++sit)
3413 tagsToClose.clear();
3417 if (Inset const * inset = getInset(i)) {
3418 if (!runparams.for_toc || inset->isInToc()) {
3419 OutputParams np = runparams;
3420 np.local_font = &font;
3422 // TODO: special case will bite here.
3423 np.docbook_in_par = true;
3424 inset->docbook(*xs, np);
3427 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3428 if (lyx::isSpace(c) && !ignore_fonts)
3429 delayedChars.push_back(c);
3433 font_old = font.fontInfo();
3436 // FIXME, this code is just imported from XHTML
3437 // I'm worried about what happens if a branch, say, is itself
3438 // wrapped in some font stuff. I think that will not work.
3440 xs->closeFontTags();
3442 // Deal with the delayed characters *after* closing font tags.
3443 if (!delayedChars.empty())
3444 for (char_type c: delayedChars)
3447 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3448 // last line to get a clean output.
3449 if (runparams.docbook_in_listing && !is_last_par)
3452 // Finalise the last (and most likely only) paragraph.
3453 generatedParagraphs.push_back(os.str());
3456 return generatedParagraphs;
3462 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3463 vector<xml::EndFontTag> & tagsToClose,
3464 bool & flag, FontState curstate, xml::FontTypes type)
3466 if (curstate == FONT_ON) {
3467 tagsToOpen.push_back(xhtmlStartFontTag(type));
3470 tagsToClose.push_back(xhtmlEndFontTag(type));
3475 } // anonymous namespace
3478 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3480 OutputParams const & runparams,
3481 Font const & outerfont,
3482 bool start_paragraph, bool close_paragraph,
3483 pos_type initial) const
3487 // track whether we have opened these tags
3488 bool emph_flag = false;
3489 bool bold_flag = false;
3490 bool noun_flag = false;
3491 bool ubar_flag = false;
3492 bool dbar_flag = false;
3493 bool sout_flag = false;
3494 bool xout_flag = false;
3495 bool wave_flag = false;
3497 bool shap_flag = false;
3499 bool faml_flag = false;
3501 bool size_flag = false;
3503 Layout const & style = *d->layout_;
3505 if (start_paragraph)
3506 xs.startDivision(allowEmpty());
3509 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3511 FontShape curr_fs = INHERIT_SHAPE;
3512 FontFamily curr_fam = INHERIT_FAMILY;
3513 FontSize curr_size = INHERIT_SIZE;
3515 string const default_family =
3516 buf.masterBuffer()->params().fonts_default_family;
3518 vector<xml::FontTag> tagsToOpen;
3519 vector<xml::EndFontTag> tagsToClose;
3521 // parsing main loop
3522 for (pos_type i = initial; i < size(); ++i) {
3523 // let's not show deleted material in the output
3527 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3530 FontState curstate = font.fontInfo().emph();
3531 if (font_old.emph() != curstate)
3532 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3535 curstate = font.fontInfo().noun();
3536 if (font_old.noun() != curstate)
3537 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3540 curstate = font.fontInfo().underbar();
3541 if (font_old.underbar() != curstate)
3542 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3545 curstate = font.fontInfo().strikeout();
3546 if (font_old.strikeout() != curstate)
3547 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3550 curstate = font.fontInfo().xout();
3551 if (font_old.xout() != curstate)
3552 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3555 curstate = font.fontInfo().uuline();
3556 if (font_old.uuline() != curstate)
3557 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3560 curstate = font.fontInfo().uwave();
3561 if (font_old.uwave() != curstate)
3562 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3565 // a little hackish, but allows us to reuse what we have.
3566 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3567 if (font_old.series() != font.fontInfo().series())
3568 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3571 curr_fs = font.fontInfo().shape();
3572 FontShape old_fs = font_old.shape();
3573 if (old_fs != curr_fs) {
3577 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3580 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3582 case SMALLCAPS_SHAPE:
3583 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3589 // the other tags are for internal use
3597 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3601 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3604 case SMALLCAPS_SHAPE:
3605 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3612 // the other tags are for internal use
3619 curr_fam = font.fontInfo().family();
3620 FontFamily old_fam = font_old.family();
3621 if (old_fam != curr_fam) {
3625 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3628 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3630 case TYPEWRITER_FAMILY:
3631 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3633 case INHERIT_FAMILY:
3636 // the other tags are for internal use
3644 // we will treat a "default" font family as roman, since we have
3645 // no other idea what to do.
3646 if (default_family != "rmdefault" && default_family != "default") {
3647 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3652 if (default_family != "sfdefault") {
3653 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3657 case TYPEWRITER_FAMILY:
3658 if (default_family != "ttdefault") {
3659 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3663 case INHERIT_FAMILY:
3666 // the other tags are for internal use
3673 curr_size = font.fontInfo().size();
3674 FontSize old_size = font_old.size();
3675 if (old_size != curr_size) {
3679 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3682 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3685 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3688 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3691 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3694 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3697 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3700 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3703 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3706 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3709 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3715 // the other tags are for internal use
3721 switch (curr_size) {
3723 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3727 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3731 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3735 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3739 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3743 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3747 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3751 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3755 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3759 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3763 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3770 // the other tags are for internal use
3777 // Other such tags? What about the other text ranges?
3779 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3780 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3781 for (; cit != cen; ++cit)
3784 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3785 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3786 for (; sit != sen; ++sit)
3789 tagsToClose.clear();
3792 Inset const * inset = getInset(i);
3794 if (!runparams.for_toc || inset->isInToc()) {
3795 OutputParams np = runparams;
3796 np.local_font = &font;
3797 // If the paragraph has size 1, then we are in the "special
3798 // case" where we do not output the containing paragraph info
3799 if (!inset->getLayout().htmlisblock() && size() != 1)
3800 np.html_in_par = true;
3801 retval += inset->xhtml(xs, np);
3804 char_type c = getUChar(buf.masterBuffer()->params(),
3806 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3807 xs << XMLStream::ESCAPE_NONE << " ";
3811 font_old = font.fontInfo();
3815 // I'm worried about what happens if a branch, say, is itself
3816 // wrapped in some font stuff. I think that will not work.
3818 if (close_paragraph)
3825 bool Paragraph::isHfill(pos_type pos) const
3827 Inset const * inset = getInset(pos);
3828 return inset && inset->isHfill();
3832 bool Paragraph::isNewline(pos_type pos) const
3834 // U+2028 LINE SEPARATOR
3835 // U+2029 PARAGRAPH SEPARATOR
3836 char_type const c = d->text_[pos];
3837 if (c == 0x2028 || c == 0x2029)
3839 Inset const * inset = getInset(pos);
3840 return inset && inset->lyxCode() == NEWLINE_CODE;
3844 bool Paragraph::isEnvSeparator(pos_type pos) const
3846 Inset const * inset = getInset(pos);
3847 return inset && inset->lyxCode() == SEPARATOR_CODE;
3851 bool Paragraph::isLineSeparator(pos_type pos) const
3853 char_type const c = d->text_[pos];
3854 if (isLineSeparatorChar(c))
3856 Inset const * inset = getInset(pos);
3857 return inset && inset->isLineSeparator();
3861 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3865 if (ignore_deleted && isDeleted(pos))
3867 if (Inset const * inset = getInset(pos))
3868 return !inset->isLetter();
3869 // if we have a hard hyphen (no en- or emdash) or apostrophe
3870 // we pass this to the spell checker
3871 // FIXME: this method is subject to change, visit
3872 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3873 // to get an impression how complex this is.
3874 if (isHardHyphenOrApostrophe(pos))
3876 char_type const c = d->text_[pos];
3877 // We want to pass the escape chars to the spellchecker
3878 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3879 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3883 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3885 pos_type const psize = size();
3888 char_type const c = d->text_[pos];
3889 if (c != '-' && c != '\'')
3891 pos_type nextpos = pos + 1;
3892 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3893 if ((nextpos == psize || isSpace(nextpos))
3894 && (pos == 0 || isSpace(prevpos)))
3900 bool Paragraph::needsCProtection(bool const fragile) const
3902 // first check the layout of the paragraph, but only in insets
3903 InsetText const * textinset = inInset().asInsetText();
3904 bool const maintext = textinset
3905 ? textinset->text().isMainText()
3908 if (!maintext && layout().needcprotect) {
3909 // Environments need cprotection regardless the content
3910 if (layout().latextype == LATEX_ENVIRONMENT)
3913 // Commands need cprotection if they contain specific chars
3914 int const nchars_escape = 9;
3915 static char_type const chars_escape[nchars_escape] = {
3916 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3918 docstring const pars = asString();
3919 for (int k = 0; k < nchars_escape; k++) {
3920 if (contains(pars, chars_escape[k]))
3925 // now check whether we have insets that need cprotection
3926 pos_type size = pos_type(d->text_.size());
3927 for (pos_type i = 0; i < size; ++i) {
3930 Inset const * ins = getInset(i);
3931 if (ins->needsCProtection(maintext, fragile))
3933 // Now check math environments
3934 InsetMath const * im = getInset(i)->asInsetMath();
3935 if (!im || im->cell(0).empty())
3937 switch(im->cell(0)[0]->lyxCode()) {
3938 case MATH_AMSARRAY_CODE:
3939 case MATH_SUBSTACK_CODE:
3941 case MATH_XYMATRIX_CODE:
3942 // these need cprotection
3953 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3955 return d->speller_state_.getRange(pos);
3959 bool Paragraph::isChar(pos_type pos) const
3961 if (Inset const * inset = getInset(pos))
3962 return inset->isChar();
3963 char_type const c = d->text_[pos];
3964 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3968 bool Paragraph::isSpace(pos_type pos) const
3970 if (Inset const * inset = getInset(pos))
3971 return inset->isSpace();
3972 char_type const c = d->text_[pos];
3973 return lyx::isSpace(c);
3978 Paragraph::getParLanguage(BufferParams const & bparams) const
3981 return getFirstFontSettings(bparams).language();
3982 // FIXME: we should check the prev par as well (Lgb)
3983 return bparams.language;
3987 bool Paragraph::isRTL(BufferParams const & bparams) const
3989 return getParLanguage(bparams)->rightToLeft()
3990 && !inInset().getLayout().forceLTR();
3994 void Paragraph::changeLanguage(BufferParams const & bparams,
3995 Language const * from, Language const * to)
3997 // change language including dummy font change at the end
3998 for (pos_type i = 0; i <= size(); ++i) {
3999 Font font = getFontSettings(bparams, i);
4000 if (font.language() == from) {
4001 font.setLanguage(to);
4003 d->requestSpellCheck(i);
4009 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4011 Language const * doc_language = bparams.language;
4012 for (auto const & f : d->fontlist_)
4013 if (f.font().language() != ignore_language &&
4014 f.font().language() != latex_language &&
4015 f.font().language() != doc_language)
4021 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4023 for (auto const & f : d->fontlist_) {
4024 Language const * lang = f.font().language();
4025 if (lang != ignore_language &&
4026 lang != latex_language)
4032 docstring Paragraph::asString(int options) const
4034 return asString(0, size(), options);
4038 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4040 odocstringstream os;
4043 && options & AS_STR_LABEL
4044 && !d->params_.labelString().empty())
4045 os << d->params_.labelString() << ' ';
4047 for (pos_type i = beg; i < end; ++i) {
4048 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4050 char_type const c = d->text_[i];
4051 if (isPrintable(c) || c == '\t'
4052 || (c == '\n' && (options & AS_STR_NEWLINES)))
4054 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4055 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4056 LASSERT(runparams != nullptr, return docstring());
4057 getInset(i)->plaintext(os, *runparams);
4059 getInset(i)->toString(os);
4068 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4069 bool const shorten, bool const label) const
4071 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4072 if (label && !labelString().empty())
4073 os += labelString() + ' ';
4074 if (!layout().isTocCaption())
4076 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4079 char_type const c = d->text_[i];
4082 else if (c == META_INSET)
4083 getInset(i)->forOutliner(os, tmplen, false);
4086 Text::shortenForOutliner(os, maxlen);
4090 void Paragraph::setInsetOwner(Inset const * inset)
4092 d->inset_owner_ = inset;
4096 int Paragraph::id() const
4102 void Paragraph::setId(int id)
4108 Layout const & Paragraph::layout() const
4114 void Paragraph::setLayout(Layout const & layout)
4116 d->layout_ = &layout;
4120 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4122 setLayout(tc.defaultLayout());
4126 void Paragraph::setPlainLayout(DocumentClass const & tc)
4128 setLayout(tc.plainLayout());
4132 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4134 if (usePlainLayout())
4137 setDefaultLayout(tc);
4141 Inset const & Paragraph::inInset() const
4143 LBUFERR(d->inset_owner_);
4144 return *d->inset_owner_;
4148 ParagraphParameters & Paragraph::params()
4154 ParagraphParameters const & Paragraph::params() const
4160 bool Paragraph::isFreeSpacing() const
4162 if (d->layout_->free_spacing)
4164 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4168 bool Paragraph::allowEmpty() const
4170 if (d->layout_->keepempty)
4172 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4176 bool Paragraph::brokenBiblio() const
4178 // There is a problem if there is no bibitem at position 0 in
4179 // paragraphs that need one, if there is another bibitem in the
4180 // paragraph or if this paragraph is not supposed to have
4181 // a bibitem inset at all.
4182 return ((d->layout_->labeltype == LABEL_BIBLIO
4183 && (d->insetlist_.find(BIBITEM_CODE) != 0
4184 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4185 || (d->layout_->labeltype != LABEL_BIBLIO
4186 && d->insetlist_.find(BIBITEM_CODE) != -1));
4190 int Paragraph::fixBiblio(Buffer const & buffer)
4192 // FIXME: when there was already an inset at 0, the return value is 1,
4193 // which does not tell whether another inset has been removed; the
4194 // cursor cannot be correctly updated.
4196 bool const track_changes = buffer.params().track_changes;
4197 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4199 // The case where paragraph is not BIBLIO
4200 if (d->layout_->labeltype != LABEL_BIBLIO) {
4201 if (bibitem_pos == -1)
4202 // No InsetBibitem => OK
4204 // There is an InsetBibitem: remove it!
4205 d->insetlist_.release(bibitem_pos);
4206 eraseChar(bibitem_pos, track_changes);
4207 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4210 bool const hasbibitem0 = bibitem_pos == 0;
4212 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4213 // There was an InsetBibitem at pos 0,
4214 // and no other one => OK
4215 if (bibitem_pos == -1)
4217 // there is a bibitem at the 0 position, but since
4218 // there is a second one, we copy the second on the
4219 // first. We're assuming there are at most two of
4220 // these, which there should be.
4221 // FIXME: why does it make sense to do that rather
4222 // than keep the first? (JMarc)
4223 Inset * inset = releaseInset(bibitem_pos);
4224 d->insetlist_.begin()->inset = inset;
4225 // This needs to be done to update the counter (#8499)
4226 buffer.updateBuffer();
4227 return -bibitem_pos;
4230 // We need to create an inset at the beginning
4231 Inset * inset = nullptr;
4232 if (bibitem_pos > 0) {
4233 // there was one somewhere in the paragraph, let's move it
4234 inset = d->insetlist_.release(bibitem_pos);
4235 eraseChar(bibitem_pos, track_changes);
4238 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4239 InsetCommandParams(BIBITEM_CODE));
4241 Font font(inherit_font, buffer.params().language);
4242 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4243 : Change::UNCHANGED));
4245 // This is needed to get the counters right
4246 buffer.updateBuffer();
4251 void Paragraph::checkAuthors(AuthorList const & authorList)
4253 d->changes_.checkAuthors(authorList);
4257 bool Paragraph::isChanged(pos_type pos) const
4259 return lookupChange(pos).changed();
4263 bool Paragraph::isInserted(pos_type pos) const
4265 return lookupChange(pos).inserted();
4269 bool Paragraph::isDeleted(pos_type pos) const
4271 return lookupChange(pos).deleted();
4275 InsetList const & Paragraph::insetList() const
4277 return d->insetlist_;
4281 void Paragraph::setInsetBuffers(Buffer & b)
4283 d->insetlist_.setBuffer(b);
4287 void Paragraph::resetBuffer()
4289 d->insetlist_.resetBuffer();
4293 Inset * Paragraph::releaseInset(pos_type pos)
4295 Inset * inset = d->insetlist_.release(pos);
4296 /// does not honour change tracking!
4297 eraseChar(pos, false);
4302 Inset * Paragraph::getInset(pos_type pos)
4304 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4305 ? d->insetlist_.get(pos) : nullptr;
4309 Inset const * Paragraph::getInset(pos_type pos) const
4311 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4312 ? d->insetlist_.get(pos) : nullptr;
4316 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4317 pos_type & right, TextCase action)
4319 // process sequences of modified characters; in change
4320 // tracking mode, this approach results in much better
4321 // usability than changing case on a char-by-char basis
4322 // We also need to track the current font, since font
4323 // changes within sequences can occur.
4324 vector<pair<char_type, Font> > changes;
4326 bool const trackChanges = bparams.track_changes;
4328 bool capitalize = true;
4330 for (; pos < right; ++pos) {
4331 char_type oldChar = d->text_[pos];
4332 char_type newChar = oldChar;
4334 // ignore insets and don't play with deleted text!
4335 if (oldChar != META_INSET && !isDeleted(pos)) {
4337 case text_lowercase:
4338 newChar = lowercase(oldChar);
4340 case text_capitalization:
4342 newChar = uppercase(oldChar);
4346 case text_uppercase:
4347 newChar = uppercase(oldChar);
4352 if (isWordSeparator(pos) || isDeleted(pos)) {
4353 // permit capitalization again
4357 if (oldChar != newChar) {
4358 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4359 if (pos != right - 1)
4361 // step behind the changing area
4365 int erasePos = pos - changes.size();
4366 for (auto const & change : changes) {
4367 insertChar(pos, change.first, change.second, trackChanges);
4368 if (!eraseChar(erasePos, trackChanges)) {
4371 ++right; // expand selection
4379 int Paragraph::find(docstring const & str, bool cs, bool mw,
4380 pos_type start_pos, bool del) const
4382 pos_type pos = start_pos;
4383 int const strsize = str.length();
4385 pos_type const parsize = d->text_.size();
4386 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4387 // Ignore "invisible" letters such as ligature breaks
4388 // and hyphenation chars while searching
4389 while (pos < parsize - 1 && isInset(pos)) {
4390 Inset const * inset = getInset(pos);
4391 if (!inset->isLetter())
4393 odocstringstream os;
4394 inset->toString(os);
4395 if (!os.str().empty())
4399 if (cs && str[i] != d->text_[pos])
4401 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4403 if (!del && isDeleted(pos))
4410 // if necessary, check whether string matches word
4412 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4415 && !isWordSeparator(pos))
4419 return pos - start_pos;
4423 char_type Paragraph::getChar(pos_type pos) const
4425 return d->text_[pos];
4429 pos_type Paragraph::size() const
4431 return d->text_.size();
4435 bool Paragraph::empty() const
4437 return d->text_.empty();
4441 bool Paragraph::isInset(pos_type pos) const
4443 return d->text_[pos] == META_INSET;
4447 bool Paragraph::isSeparator(pos_type pos) const
4449 //FIXME: Are we sure this can be the only separator?
4450 return d->text_[pos] == ' ';
4454 void Paragraph::deregisterWords()
4456 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4457 Private::LangWordsMap::const_iterator ite = d->words_.end();
4458 for (; itl != ite; ++itl) {
4459 WordList & wl = theWordList(itl->first);
4460 Private::Words::const_iterator it = (itl->second).begin();
4461 Private::Words::const_iterator et = (itl->second).end();
4462 for (; it != et; ++it)
4469 void Paragraph::locateWord(pos_type & from, pos_type & to,
4470 word_location const loc, bool const ignore_deleted) const
4473 case WHOLE_WORD_STRICT:
4474 if (from == 0 || from == size()
4475 || isWordSeparator(from, ignore_deleted)
4476 || isWordSeparator(from - 1, ignore_deleted)) {
4483 // If we are already at the beginning of a word, do nothing
4484 if (!from || isWordSeparator(from - 1, ignore_deleted))
4489 // always move the cursor to the beginning of previous word
4490 while (from && !isWordSeparator(from - 1, ignore_deleted))
4494 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4497 // no need to move the 'from' cursor
4501 while (to < size() && !isWordSeparator(to, ignore_deleted))
4506 void Paragraph::collectWords()
4508 for (pos_type pos = 0; pos < size(); ++pos) {
4509 if (isWordSeparator(pos))
4511 pos_type from = pos;
4512 locateWord(from, pos, WHOLE_WORD);
4513 // Work around MSVC warning: The statement
4514 // if (pos < from + lyxrc.completion_minlength)
4515 // triggers a signed vs. unsigned warning.
4516 // I don't know why this happens, it could be a MSVC bug, or
4517 // related to LLP64 (windows) vs. LP64 (unix) programming
4518 // model, or the C++ standard might be ambigous in the section
4519 // defining the "usual arithmetic conversions". However, using
4520 // a temporary variable is safe and works on all compilers.
4521 pos_type const endpos = from + lyxrc.completion_minlength;
4524 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4525 if (cit == d->fontlist_.end())
4527 Language const * lang = cit->font().language();
4528 docstring const word = asString(from, pos, AS_STR_NONE);
4529 d->words_[lang->lang()].insert(word);
4534 void Paragraph::registerWords()
4536 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4537 Private::LangWordsMap::const_iterator ite = d->words_.end();
4538 for (; itl != ite; ++itl) {
4539 WordList & wl = theWordList(itl->first);
4540 Private::Words::const_iterator it = (itl->second).begin();
4541 Private::Words::const_iterator et = (itl->second).end();
4542 for (; it != et; ++it)
4548 void Paragraph::updateWords()
4556 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4558 SkipPositionsIterator begin = skips.begin();
4559 SkipPositions::iterator end = skips.end();
4560 if (pos > 0 && begin < end) {
4562 if (end->last == pos - 1) {
4567 skips.insert(end, FontSpan(pos, pos));
4571 Language * Paragraph::Private::locateSpellRange(
4572 pos_type & from, pos_type & to,
4573 SkipPositions & skips) const
4575 // skip leading white space
4576 while (from < to && owner_->isWordSeparator(from))
4578 // don't check empty range
4581 // get current language
4582 Language * lang = getSpellLanguage(from);
4583 pos_type last = from;
4584 bool samelang = true;
4585 bool sameinset = true;
4586 while (last < to && samelang && sameinset) {
4587 // hop to end of word
4588 while (last < to && !owner_->isWordSeparator(last)) {
4589 Inset const * inset = owner_->getInset(last);
4590 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4591 // check for "invisible" letters such as ligature breaks
4592 odocstringstream os;
4593 inset->toString(os);
4594 if (os.str().length() != 0) {
4595 // avoid spell check of visible special char insets
4596 // stop the loop in front of the special char inset
4601 appendSkipPosition(skips, last);
4602 } else if (owner_->isDeleted(last)) {
4603 appendSkipPosition(skips, last);
4607 // hop to next word while checking for insets
4608 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4609 if (Inset const * inset = owner_->getInset(last))
4610 sameinset = inset->isChar() && inset->isLetter();
4611 if (sameinset && owner_->isDeleted(last)) {
4612 appendSkipPosition(skips, last);
4617 if (sameinset && last < to) {
4618 // now check for language change
4619 samelang = lang == getSpellLanguage(last);
4622 // if language change detected backstep is needed
4630 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4633 const_cast<Language *>(owner_->getFontSettings(
4634 inset_owner_->buffer().params(), from).language());
4635 if (lang == inset_owner_->buffer().params().language
4636 && !lyxrc.spellchecker_alt_lang.empty()) {
4638 string const lang_variety =
4639 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4640 lang->setCode(lang_code);
4641 lang->setVariety(lang_variety);
4647 void Paragraph::requestSpellCheck(pos_type pos)
4649 d->requestSpellCheck(pos);
4653 bool Paragraph::needsSpellCheck() const
4655 SpellChecker::ChangeNumber speller_change_number = 0;
4656 if (theSpellChecker())
4657 speller_change_number = theSpellChecker()->changeNumber();
4658 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4659 d->speller_state_.needsCompleteRefresh(speller_change_number);
4661 return d->needsSpellCheck();
4665 bool Paragraph::Private::ignoreWord(docstring const & word) const
4667 // Ignore words with digits
4668 // FIXME: make this customizable
4669 // (note that some checkers ignore words with digits by default)
4670 docstring::const_iterator cit = word.begin();
4671 docstring::const_iterator const end = word.end();
4672 for (; cit != end; ++cit) {
4673 if (isNumber((*cit)))
4680 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4681 WordLangTuple & wl, docstring_list & suggestions,
4682 bool do_suggestion, bool check_learned) const
4684 SpellChecker::Result result = SpellChecker::WORD_OK;
4685 SpellChecker * speller = theSpellChecker();
4689 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4692 locateWord(from, to, WHOLE_WORD, true);
4693 if (from == to || from >= size())
4696 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4697 Language * lang = d->getSpellLanguage(from);
4699 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4702 wl = WordLangTuple(word, lang);
4707 if (needsSpellCheck() || check_learned) {
4709 if (!d->ignoreWord(word)) {
4710 bool const trailing_dot = to < size() && d->text_[to] == '.';
4711 result = speller->check(wl);
4712 if (SpellChecker::misspelled(result) && trailing_dot) {
4713 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4714 result = speller->check(wl);
4715 if (!SpellChecker::misspelled(result)) {
4716 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4718 from << ".." << to << "]");
4720 // spell check with dot appended failed too
4721 // restore original word/lang value
4722 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4723 wl = WordLangTuple(word, lang);
4727 if (!SpellChecker::misspelled(result)) {
4728 // area up to the begin of the next word is not misspelled
4729 while (end < size() && isWordSeparator(end))
4732 d->setMisspelled(from, end, result);
4734 result = d->speller_state_.getState(from);
4738 suggestions.clear();
4740 if (SpellChecker::misspelled(result)) {
4741 LYXERR(Debug::GUI, "misspelled word: \"" <<
4743 from << ".." << to << "]");
4745 speller->suggest(wl, suggestions);
4751 void Paragraph::anonymize()
4753 // This is a very crude anonymization for now
4754 for (char_type & c : d->text_)
4755 if (isLetterChar(c) || isNumber(c))
4760 void Paragraph::Private::markMisspelledWords(
4761 pos_type const & first, pos_type const & last,
4762 SpellChecker::Result result,
4763 docstring const & word,
4764 SkipPositions const & skips)
4766 if (!SpellChecker::misspelled(result)) {
4767 setMisspelled(first, last, SpellChecker::WORD_OK);
4771 SpellChecker * speller = theSpellChecker();
4772 // locate and enumerate the error positions
4773 int nerrors = speller->numMisspelledWords();
4775 SkipPositionsIterator it = skips.begin();
4776 SkipPositionsIterator et = skips.end();
4777 for (int index = 0; index < nerrors; ++index) {
4780 speller->misspelledWord(index, wstart, wlen);
4781 /// should not happen if speller supports range checks
4782 if (!wlen) continue;
4783 docstring const misspelled = word.substr(wstart, wlen);
4784 wstart += first + numskipped;
4785 if (snext < wstart) {
4786 /// mark the range of correct spelling
4787 numskipped += countSkips(it, et, wstart);
4788 setMisspelled(snext,
4789 wstart - 1, SpellChecker::WORD_OK);
4791 snext = wstart + wlen;
4792 numskipped += countSkips(it, et, snext);
4793 /// mark the range of misspelling
4794 setMisspelled(wstart, snext, result);
4795 LYXERR(Debug::GUI, "misspelled word: \"" <<
4796 misspelled << "\" [" <<
4797 wstart << ".." << (snext-1) << "]");
4800 if (snext <= last) {
4801 /// mark the range of correct spelling at end
4802 setMisspelled(snext, last, SpellChecker::WORD_OK);
4807 void Paragraph::spellCheck() const
4809 SpellChecker * speller = theSpellChecker();
4810 if (!speller || empty() ||!needsSpellCheck())
4814 d->rangeOfSpellCheck(start, endpos);
4815 if (speller->canCheckParagraph()) {
4816 // loop until we leave the range
4817 for (pos_type first = start; first < endpos; ) {
4818 pos_type last = endpos;
4819 Private::SkipPositions skips;
4820 Language * lang = d->locateSpellRange(first, last, skips);
4821 if (first >= endpos)
4823 // start the spell checker on the unit of meaning
4824 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4825 WordLangTuple wl = WordLangTuple(word, lang);
4826 SpellChecker::Result result = !word.empty() ?
4827 speller->check(wl) : SpellChecker::WORD_OK;
4828 d->markMisspelledWords(first, last, result, word, skips);
4832 static docstring_list suggestions;
4833 pos_type to = endpos;
4834 while (start < endpos) {
4836 spellCheck(start, to, wl, suggestions, false);
4840 d->readySpellCheck();
4844 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4846 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4847 if (result || pos <= 0 || pos > size())
4849 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4850 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4855 string Paragraph::magicLabel() const
4858 ss << "magicparlabel-" << id();