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 Kimberly 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))
869 // Handle combining characters
870 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
871 otexstream & os, char_type c, char_type next,
872 OutputParams const & runparams)
874 // Writing next here may circumvent a possible font change between
875 // c and next. Since next is only output if it forms a surrogate pair
876 // with c we can ignore this:
877 // A font change inside a surrogate pair does not make sense and is
878 // hopefully impossible to input.
879 // FIXME: change tracking
880 // Is this correct WRT change tracking?
881 Encoding const & encoding = *(runparams.encoding);
882 docstring latex1 = encoding.latexChar(next).first;
883 if (runparams.inIPA) {
884 string const tipashortcut = Encodings::TIPAShortcut(next);
885 if (!tipashortcut.empty()) {
886 latex1 = from_ascii(tipashortcut);
889 docstring latex2 = encoding.latexChar(c).first;
891 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
892 // Encoding supports the combination:
893 // output as is (combining char after base char).
894 os << latex2 << latex1;
895 return latex1.length() + latex2.length();
898 os << latex1 << "{" << latex2 << "}";
899 return latex1.length() + latex2.length() + 2;
903 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
904 OutputParams const & runparams,
907 unsigned int & column,
909 Layout const & style)
911 if (style.pass_thru || runparams.pass_thru)
914 if (i + 1 < int(text_.size())) {
915 char_type next = text_[i + 1];
916 if (Encodings::isCombiningChar(next)) {
917 // This space has an accent, so we must always output it.
918 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
923 if (runparams.linelen > 0
924 && column > runparams.linelen
926 && text_[i - 1] != ' '
927 && (i + 1 < int(text_.size()))
928 // same in FreeSpacing mode
929 && !owner_->isFreeSpacing()
930 // In typewriter mode, we want to avoid
931 // ! . ? : at the end of a line
932 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
933 && (text_[i - 1] == '.'
934 || text_[i - 1] == '?'
935 || text_[i - 1] == ':'
936 || text_[i - 1] == '!'))) {
938 os.texrow().start(owner_->id(), i + 1);
940 } else if (style.free_spacing) {
949 void Paragraph::Private::latexInset(BufferParams const & bparams,
951 OutputParams & runparams,
954 Font const & outerfont,
956 Change & running_change,
957 Layout const & style,
959 unsigned int & column,
960 bool const fontswitch_inset,
961 bool const closeLanguage,
962 bool const lang_switched_at_inset)
964 Inset * inset = owner_->getInset(i);
967 if (style.pass_thru) {
968 odocstringstream ods;
969 inset->plaintext(ods, runparams);
974 // FIXME: move this to InsetNewline::latex
975 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
976 // newlines are handled differently here than
977 // the default in simpleTeXSpecialChars().
978 if (!style.newline_allowed) {
982 bool needPar = false;
983 column += running_font.latexWriteEndChanges(
984 os, bparams, runparams,
985 basefont, basefont, needPar);
989 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
992 basefont = owner_->getLayoutFont(bparams, outerfont);
993 running_font = basefont;
995 if (runparams.moving_arg)
999 os.texrow().start(owner_->id(), i + 1);
1003 if (owner_->isDeleted(i)) {
1004 if( ++runparams.inDeletedInset == 1)
1005 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1008 if (inset->canTrackChanges()) {
1009 column += Changes::latexMarkChange(os, bparams, running_change,
1010 Change(Change::UNCHANGED), runparams);
1011 running_change = Change(Change::UNCHANGED);
1015 odocstream::pos_type const len = os.os().tellp();
1017 if (inset->forceLTR(runparams)
1018 && running_font.isRightToLeft()
1019 // ERT is an exception, it should be output with no
1020 // decorations at all
1021 && inset->lyxCode() != ERT_CODE) {
1022 if (runparams.use_polyglossia) {
1024 } else if (running_font.language()->lang() == "farsi"
1025 || running_font.language()->lang() == "arabic_arabi")
1026 os << "\\textLR{" << termcmd;
1032 if (open_font && fontswitch_inset) {
1033 bool lang_closed = false;
1034 // Close language if needed
1035 if (closeLanguage && !lang_switched_at_inset) {
1036 // We need prev_font here as language changes directly at inset
1037 // will only be started inside the inset.
1038 Font const prev_font = (i > 0) ?
1039 owner_->getFont(bparams, i - 1, outerfont)
1041 Font tmpfont(basefont);
1042 tmpfont.setLanguage(prev_font.language());
1043 bool needPar = false;
1044 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1046 needPar, closeLanguage);
1048 lang_closed = count > 0;
1050 // Update the running_font, making sure, however,
1051 // to leave the language as it was.
1052 // FIXME: probably a better way to keep track of the old
1053 // language, than copying the entire font?
1054 Font const copy_font(running_font);
1055 basefont = owner_->getLayoutFont(bparams, outerfont);
1056 running_font = basefont;
1058 running_font.setLanguage(copy_font.language());
1059 OutputParams rp = runparams;
1060 rp.encoding = basefont.language()->encoding();
1061 // For these, we use switches, so they should be taken as
1062 // base inside the inset.
1063 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1064 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1065 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1066 // Now re-do font changes in a way needed here
1067 // (using switches with multi-par insets)
1068 InsetText const * textinset = inset->asInsetText();
1069 bool const cprotect = textinset
1070 ? textinset->hasCProtectContent(runparams.moving_arg)
1071 && !textinset->text().isMainText()
1073 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1079 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1083 runparams.local_font = &basefont;
1086 if (fontswitch_inset && !closeLanguage) {
1087 // The directionality has been switched at inset.
1088 // Force markup inside.
1089 runparams.local_font = &basefont;
1092 size_t const previous_row_count = os.texrow().rows();
1095 runparams.lastid = id_;
1096 runparams.lastpos = i;
1097 inset->latex(os, runparams);
1098 } catch (EncodingException & e) {
1099 // add location information and throw again.
1108 if (os.texrow().rows() > previous_row_count) {
1109 os.texrow().start(owner_->id(), i + 1);
1112 column += (unsigned int)(os.os().tellp() - len);
1115 if (owner_->isDeleted(i))
1116 --runparams.inDeletedInset;
1120 void Paragraph::Private::latexSpecialChar(otexstream & os,
1121 BufferParams const & bparams,
1122 OutputParams const & runparams,
1123 Font const & running_font,
1124 string & alien_script,
1125 Layout const & style,
1128 unsigned int & column)
1130 char_type const c = owner_->getUChar(bparams, runparams, i);
1132 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1133 || contains(style.pass_thru_chars, c)
1134 || contains(runparams.pass_thru_chars, c)) {
1135 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1139 os << "\\braceleft ";
1141 os << "\\braceright ";
1145 else if (c != '\0') {
1146 Encoding const * const enc = runparams.encoding;
1147 if (enc && !enc->encodable(c))
1148 throw EncodingException(c);
1154 // TIPA uses its own T3 encoding
1155 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1157 // If T1 font encoding is used, use the special
1158 // characters it provides.
1159 // NOTE: Some languages reset the font encoding internally to a
1160 // non-standard font encoding. If we are using such a language,
1161 // we do not output special T1 chars.
1162 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1163 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1164 && latexSpecialT1(c, os, i, column))
1166 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1167 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1168 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1171 // Otherwise, we use what LaTeX provides us.
1174 os << "\\textbackslash" << termcmd;
1178 os << "\\textless" << termcmd;
1182 os << "\\textgreater" << termcmd;
1186 os << "\\textbar" << termcmd;
1191 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1192 (end_pos == -1 || i + 1 < end_pos) &&
1193 text_[i+1] == '-') {
1194 // Prevent "--" becoming an en dash and "---" an em dash.
1195 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1201 os << "\\textquotedbl" << termcmd;
1206 case '%': case '#': case '{':
1214 os << "\\textasciitilde" << termcmd;
1219 os << "\\textasciicircum" << termcmd;
1226 // avoid being mistaken for optional arguments
1234 // Blanks are printed before font switching.
1235 // Sure? I am not! (try nice-latex)
1236 // I am sure it's correct. LyX might be smarter
1237 // in the future, but for now, nothing wrong is
1243 // XeTeX's dash behaviour is determined via a global setting
1244 if (bparams.use_dash_ligatures
1245 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1247 // TODO #10961: && not in inset Flex Code
1248 // TODO #10961: && not in layout LyXCode
1249 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1266 Encoding const & encoding = *(runparams.encoding);
1267 char_type next = '\0';
1268 if (i + 1 < int(text_.size())) {
1269 next = text_[i + 1];
1270 if (Encodings::isCombiningChar(next)) {
1271 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1276 pair<docstring, bool> latex = encoding.latexChar(c);
1277 docstring nextlatex;
1278 bool nexttipas = false;
1279 string nexttipashortcut;
1280 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1281 nextlatex = encoding.latexChar(next).first;
1282 if (runparams.inIPA) {
1283 nexttipashortcut = Encodings::TIPAShortcut(next);
1284 nexttipas = !nexttipashortcut.empty();
1288 if (runparams.inIPA) {
1289 string const tipashortcut = Encodings::TIPAShortcut(c);
1290 if (!tipashortcut.empty()) {
1291 latex.first = from_ascii(tipashortcut);
1292 latex.second = false;
1296 // eventually close "script wrapper" command (see `Paragraph::latex`)
1297 if (!alien_script.empty()
1298 && alien_script != Encodings::isKnownScriptChar(next)) {
1299 column += latex.first.length();
1300 alien_script.clear();
1301 os << latex.first << "}";
1305 && ((!prefixIs(nextlatex, '\\')
1306 && !prefixIs(nextlatex, '{')
1307 && !prefixIs(nextlatex, '}'))
1309 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1311 // Prevent eating of a following space or command corruption by
1312 // following characters
1313 if (next == ' ' || next == '\0') {
1314 column += latex.first.length() + 1;
1315 os << latex.first << "{}";
1317 column += latex.first.length();
1318 os << latex.first << " ";
1321 column += latex.first.length() - 1;
1329 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1330 pos_type i, unsigned int & column) const
1336 // In T1 encoding, these characters exist
1337 // but we should avoid ligatures
1338 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1340 os << "\\textcompwordmark" << termcmd;
1347 // soul.sty breaks with \char`\"
1348 os << "\\textquotedbl" << termcmd;
1357 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1358 pos_type i, unsigned int & column) const
1360 // TU encoding is currently on par with T1.
1361 return latexSpecialT1(c, os, i, column);
1365 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1366 pos_type /*i*/, unsigned int & column) const
1376 os << "\\textvertline" << termcmd;
1385 void Paragraph::Private::validate(LaTeXFeatures & features) const
1387 if (layout_->inpreamble && inset_owner_) {
1388 // FIXME: Using a string stream here circumvents the encoding
1389 // switching machinery of odocstream. Therefore the
1390 // output is wrong if this paragraph contains content
1391 // that needs to switch encoding.
1392 Buffer const & buf = inset_owner_->buffer();
1393 otexstringstream os;
1394 os << layout_->preamble();
1395 size_t const length = os.length();
1396 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1397 buf.getParFromID(owner_->id()).pit(), os,
1398 features.runparams(), string(), 0, -1, true);
1399 if (os.length() > length)
1400 features.addPreambleSnippet(os.release(), true);
1403 if (features.runparams().flavor == Flavor::Html
1404 && layout_->htmltitle()) {
1405 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1408 // check the params.
1409 if (!params_.spacing().isDefault())
1410 features.require("setspace");
1413 features.useLayout(layout_->name());
1416 fontlist_.validate(features);
1418 // then the indentation
1419 if (!params_.leftIndent().zero())
1420 features.require("ParagraphLeftIndent");
1423 InsetList::const_iterator icit = insetlist_.begin();
1424 InsetList::const_iterator iend = insetlist_.end();
1425 for (; icit != iend; ++icit) {
1427 features.inDeletedInset(owner_->isDeleted(icit->pos));
1428 if (icit->inset->lyxCode() == FOOT_CODE) {
1429 // FIXME: an item inset would make things much easier.
1430 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1431 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1432 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1433 && (icit->pos < begin_of_body_
1434 || (icit->pos == begin_of_body_
1435 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1436 features.saveNoteEnv("description");
1438 icit->inset->validate(features);
1439 features.inDeletedInset(false);
1440 if (layout_->needprotect &&
1441 icit->inset->lyxCode() == FOOT_CODE)
1442 features.require("NeedLyXFootnoteCode");
1446 // then the contents
1447 BufferParams const bp = features.runparams().is_child
1448 ? features.buffer().masterParams() : features.buffer().params();
1449 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1450 char_type c = text_[i];
1451 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1453 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1454 features.require("textquotedblp");
1455 else if (bp.main_font_encoding() != "T1"
1456 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1457 features.require("textquotedbl");
1458 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1459 // features that depend on the font or input encoding
1460 string feats = ci.textpreamble();
1461 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1462 if (fontenc.empty())
1463 fontenc = features.runparams().main_fontenc;
1464 while (!feats.empty()) {
1466 feats = split(feats, feat, ',');
1467 if (contains(feat, "!=")) {
1468 // a feature that is required except for the spcified
1469 // font or input encodings
1471 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1472 // multiple encodings are separated by semicolon
1473 vector<string> context = getVectorFromString(contexts, ";");
1474 // require feature if the context matches neither current font
1475 // nor input encoding
1476 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1477 && std::find(context.begin(), context.end(),
1478 features.runparams().encoding->name()) == context.end())
1479 features.require(realfeature);
1480 } else if (contains(feat, '=')) {
1481 // a feature that is required only for the spcified
1482 // font or input encodings
1484 string const contexts = split(feat, realfeature, '=');
1485 // multiple encodings are separated by semicolon
1486 vector<string> context = getVectorFromString(contexts, ";");
1487 // require feature if the context matches either current font
1488 // or input encoding
1489 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1490 || std::find(context.begin(), context.end(),
1491 features.runparams().encoding->name()) != context.end())
1492 features.require(realfeature);
1495 } else if (!bp.use_dash_ligatures
1496 && (c == 0x2013 || c == 0x2014)
1497 && bp.useNonTeXFonts
1498 && features.runparams().flavor == Flavor::XeTeX)
1499 // XeTeX's dash behaviour is determined via a global setting
1500 features.require("xetexdashbreakstate");
1501 BufferEncodings::validate(c, features);
1505 /////////////////////////////////////////////////////////////////////
1509 /////////////////////////////////////////////////////////////////////
1512 Layout const emptyParagraphLayout;
1515 Paragraph::Paragraph()
1516 : d(new Paragraph::Private(this, emptyParagraphLayout))
1523 Paragraph::Paragraph(Paragraph const & par)
1524 : itemdepth(par.itemdepth),
1525 d(new Paragraph::Private(*par.d, this))
1531 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1532 : itemdepth(par.itemdepth),
1533 d(new Paragraph::Private(*par.d, this, beg, end))
1539 Paragraph & Paragraph::operator=(Paragraph const & par)
1541 // needed as we will destroy the private part before copying it
1543 itemdepth = par.itemdepth;
1547 d = new Private(*par.d, this);
1554 Paragraph::~Paragraph()
1563 // this shall be called just before every "os << ..." action.
1564 void flushString(ostream & os, docstring & s)
1573 void Paragraph::write(ostream & os, BufferParams const & bparams,
1574 depth_type & depth) const
1576 // The beginning or end of a deeper (i.e. nested) area?
1577 if (depth != d->params_.depth()) {
1578 if (d->params_.depth() > depth) {
1579 while (d->params_.depth() > depth) {
1580 os << "\n\\begin_deeper";
1584 while (d->params_.depth() < depth) {
1585 os << "\n\\end_deeper";
1591 // First write the layout
1592 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1594 d->params_.write(os);
1596 Font font1(inherit_font, bparams.language);
1598 Change running_change = Change(Change::UNCHANGED);
1600 // this string is used as a buffer to avoid repetitive calls
1601 // to to_utf8(), which turn out to be expensive (JMarc)
1602 docstring write_buffer;
1605 for (pos_type i = 0; i <= size(); ++i) {
1607 Change const & change = lookupChange(i);
1608 if (change != running_change)
1609 flushString(os, write_buffer);
1610 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1611 running_change = change;
1616 // Write font changes
1617 Font font2 = getFontSettings(bparams, i);
1618 if (font2 != font1) {
1619 flushString(os, write_buffer);
1620 font2.lyxWriteChanges(font1, os);
1625 char_type const c = d->text_[i];
1628 if (Inset const * inset = getInset(i)) {
1629 flushString(os, write_buffer);
1630 if (inset->directWrite()) {
1631 // international char, let it write
1632 // code directly so it's shorter in
1638 os << "\\begin_inset ";
1640 os << "\n\\end_inset\n\n";
1643 // FIXME This can be removed again once the mystery
1644 // crash has been resolved.
1649 flushString(os, write_buffer);
1650 os << "\n\\backslash\n";
1654 flushString(os, write_buffer);
1655 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1662 if ((column > 70 && c == ' ')
1664 flushString(os, write_buffer);
1668 // this check is to amend a bug. LyX sometimes
1669 // inserts '\0' this could cause problems.
1671 write_buffer.push_back(c);
1673 LYXERR0("NUL char in structure.");
1679 flushString(os, write_buffer);
1680 os << "\n\\end_layout\n";
1681 // FIXME This can be removed again once the mystery
1682 // crash has been resolved.
1687 void Paragraph::validate(LaTeXFeatures & features) const
1689 d->validate(features);
1690 bool fragile = features.runparams().moving_arg;
1691 fragile |= layout().needprotect;
1692 if (inInset().getLayout().isNeedProtect())
1694 if (needsCProtection(fragile))
1695 features.require("cprotect");
1699 void Paragraph::insert(pos_type pos, docstring const & str,
1700 Font const & font, Change const & change)
1702 for (size_t i = 0, n = str.size(); i != n ; ++i)
1703 insertChar(pos + i, str[i], font, change);
1707 void Paragraph::appendChar(char_type c, Font const & font,
1708 Change const & change)
1711 d->changes_.insert(change, d->text_.size());
1712 // when appending characters, no need to update tables
1713 d->text_.push_back(c);
1714 setFont(d->text_.size() - 1, font);
1715 d->requestSpellCheck(d->text_.size() - 1);
1719 void Paragraph::appendString(docstring const & s, Font const & font,
1720 Change const & change)
1722 pos_type end = s.size();
1723 size_t oldsize = d->text_.size();
1724 size_t newsize = oldsize + end;
1725 size_t capacity = d->text_.capacity();
1726 if (newsize >= capacity)
1727 d->text_.reserve(max(capacity + 100, newsize));
1729 // when appending characters, no need to update tables
1732 // FIXME: Optimize this!
1733 for (size_t i = oldsize; i != newsize; ++i) {
1735 d->changes_.insert(change, i);
1736 d->requestSpellCheck(i);
1738 d->fontlist_.set(oldsize, font);
1739 d->fontlist_.set(newsize - 1, font);
1743 void Paragraph::insertChar(pos_type pos, char_type c,
1746 d->insertChar(pos, c, Change(trackChanges ?
1747 Change::INSERTED : Change::UNCHANGED));
1751 void Paragraph::insertChar(pos_type pos, char_type c,
1752 Font const & font, bool trackChanges)
1754 d->insertChar(pos, c, Change(trackChanges ?
1755 Change::INSERTED : Change::UNCHANGED));
1760 void Paragraph::insertChar(pos_type pos, char_type c,
1761 Font const & font, Change const & change)
1763 d->insertChar(pos, c, change);
1768 void Paragraph::resetFonts(Font const & font)
1770 d->fontlist_.clear();
1771 d->fontlist_.set(0, font);
1772 d->fontlist_.set(d->text_.size() - 1, font);
1775 // Gets uninstantiated font setting at position.
1776 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1780 LYXERR0("pos: " << pos << " size: " << size());
1784 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1785 if (cit != d->fontlist_.end())
1788 if (pos == size() && !empty())
1789 return getFontSettings(bparams, pos - 1);
1791 // Optimisation: avoid a full font instantiation if there is no
1792 // language change from previous call.
1793 static Font previous_font;
1794 static Language const * previous_lang = nullptr;
1795 Language const * lang = getParLanguage(bparams);
1796 if (lang != previous_lang) {
1797 previous_lang = lang;
1798 previous_font = Font(inherit_font, lang);
1800 return previous_font;
1804 FontSpan Paragraph::fontSpan(pos_type pos) const
1806 LBUFERR(pos <= size());
1809 return FontSpan(pos, pos);
1812 FontList::const_iterator cit = d->fontlist_.begin();
1813 FontList::const_iterator end = d->fontlist_.end();
1814 for (; cit != end; ++cit) {
1815 if (cit->pos() >= pos) {
1816 if (pos >= beginOfBody())
1817 return FontSpan(max(start, beginOfBody()),
1820 return FontSpan(start,
1821 min(beginOfBody() - 1,
1824 start = cit->pos() + 1;
1827 // This should not happen, but if so, we take no chances.
1828 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1829 LASSERT(false, return FontSpan(pos, pos));
1833 // Gets uninstantiated font setting at position 0
1834 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1836 if (!empty() && !d->fontlist_.empty())
1837 return d->fontlist_.begin()->font();
1839 // Optimisation: avoid a full font instantiation if there is no
1840 // language change from previous call.
1841 static Font previous_font;
1842 static Language const * previous_lang = nullptr;
1843 if (bparams.language != previous_lang) {
1844 previous_lang = bparams.language;
1845 previous_font = Font(inherit_font, bparams.language);
1848 return previous_font;
1852 // Gets the fully instantiated font at a given position in a paragraph
1853 // This is basically the same function as Text::GetFont() in text2.cpp.
1854 // The difference is that this one is used for generating the LaTeX file,
1855 // and thus cosmetic "improvements" are disallowed: This has to deliver
1856 // the true picture of the buffer. (Asger)
1857 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1858 Font const & outerfont) const
1862 Font font = getFontSettings(bparams, pos);
1864 pos_type const body_pos = beginOfBody();
1865 FontInfo & fi = font.fontInfo();
1867 fi.realize(d->layout_->labelfont);
1869 fi.realize(d->layout_->font);
1871 fi.realize(outerfont.fontInfo());
1872 fi.realize(bparams.getFont().fontInfo());
1878 Font const Paragraph::getLabelFont
1879 (BufferParams const & bparams, Font const & outerfont) const
1881 FontInfo tmpfont = d->layout_->labelfont;
1882 tmpfont.realize(outerfont.fontInfo());
1883 tmpfont.realize(bparams.getFont().fontInfo());
1884 return Font(tmpfont, getParLanguage(bparams));
1888 Font const Paragraph::getLayoutFont
1889 (BufferParams const & bparams, Font const & outerfont) const
1891 FontInfo tmpfont = d->layout_->font;
1892 tmpfont.realize(outerfont.fontInfo());
1893 tmpfont.realize(bparams.getFont().fontInfo());
1894 return Font(tmpfont, getParLanguage(bparams));
1898 char_type Paragraph::getUChar(BufferParams const & bparams,
1899 OutputParams const & rp,
1902 char_type c = d->text_[pos];
1904 // Return unchanged character in LTR languages
1905 // or if we use poylglossia/bidi (XeTeX).
1906 if (rp.useBidiPackage()
1907 || !getFontSettings(bparams, pos).isRightToLeft())
1910 // Without polyglossia/bidi, we need to account for some special cases.
1911 // FIXME This needs to be audited!
1913 // * The input is as expected for all delimiters
1914 // => checked for Hebrew!
1915 // * The output matches the display in the LyX workarea
1916 // => checked for Hebrew!
1917 // * The special cases below are really necessary
1918 // => checked for Hebrew!
1919 // * In arabic_arabi, brackets are transformed to Arabic
1920 // Ornate Parentheses. Is this is really wanted?
1922 string const & lang = getFontSettings(bparams, pos).language()->lang();
1925 // 1. In the following languages, parentheses need to be reversed.
1926 // Also with polyglodia/luabidi
1927 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1929 // 2. In the following languages, brackets don't need to be reversed.
1930 bool const reversebrackets = lang != "arabic_arabtex"
1931 && lang != "arabic_arabi"
1934 // Now swap delimiters if needed.
1945 if (reversebrackets)
1949 if (reversebrackets)
1970 void Paragraph::setFont(pos_type pos, Font const & font)
1972 LASSERT(pos <= size(), return);
1974 // First, reduce font against layout/label font
1975 // Update: The setCharFont() routine in text2.cpp already
1976 // reduces font, so we don't need to do that here. (Asger)
1978 d->fontlist_.set(pos, font);
1982 void Paragraph::makeSameLayout(Paragraph const & par)
1984 d->layout_ = par.d->layout_;
1985 d->params_ = par.d->params_;
1989 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1991 if (isFreeSpacing())
1997 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1998 if (eraseChar(pos, trackChanges))
2004 return count > 0 || pos > 0;
2008 bool Paragraph::hasSameLayout(Paragraph const & par) const
2010 return par.d->layout_ == d->layout_
2011 && d->params_.sameLayout(par.d->params_);
2015 depth_type Paragraph::getDepth() const
2017 return d->params_.depth();
2021 depth_type Paragraph::getMaxDepthAfter() const
2023 if (d->layout_->isEnvironment())
2024 return d->params_.depth() + 1;
2026 return d->params_.depth();
2030 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2032 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2033 return getDefaultAlign(bparams);
2035 return d->params_.align();
2039 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2041 LyXAlignment res = layout().align;
2042 if (isRTL(bparams)) {
2044 if (res == LYX_ALIGN_LEFT)
2045 res = LYX_ALIGN_RIGHT;
2046 else if (res == LYX_ALIGN_RIGHT)
2047 res = LYX_ALIGN_LEFT;
2053 docstring const & Paragraph::labelString() const
2055 return d->params_.labelString();
2059 // the next two functions are for the manual labels
2060 docstring const Paragraph::getLabelWidthString() const
2062 if (d->layout_->margintype == MARGIN_MANUAL
2063 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2064 return d->params_.labelWidthString();
2066 return _("Senseless with this layout!");
2070 void Paragraph::setLabelWidthString(docstring const & s)
2072 d->params_.labelWidthString(s);
2076 docstring Paragraph::expandLabel(Layout const & layout,
2077 BufferParams const & bparams) const
2079 return expandParagraphLabel(layout, bparams, true);
2083 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2084 BufferParams const & bparams, bool process_appendix) const
2086 DocumentClass const & tclass = bparams.documentClass();
2087 string const & lang = getParLanguage(bparams)->code();
2088 bool const in_appendix = process_appendix && d->params_.appendix();
2089 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2091 if (fmt.empty() && !layout.counter.empty())
2092 return tclass.counters().theCounter(layout.counter, lang);
2094 // handle 'inherited level parts' in 'fmt',
2095 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2096 size_t const i = fmt.find('@', 0);
2097 if (i != docstring::npos) {
2098 size_t const j = fmt.find('@', i + 1);
2099 if (j != docstring::npos) {
2100 docstring parent(fmt, i + 1, j - i - 1);
2101 docstring label = from_ascii("??");
2102 if (tclass.hasLayout(parent))
2103 label = expandParagraphLabel(tclass[parent], bparams,
2105 fmt = docstring(fmt, 0, i) + label
2106 + docstring(fmt, j + 1, docstring::npos);
2110 return tclass.counters().counterLabel(fmt, lang);
2114 void Paragraph::applyLayout(Layout const & new_layout)
2116 d->layout_ = &new_layout;
2117 LyXAlignment const oldAlign = d->params_.align();
2119 if (!(oldAlign & d->layout_->alignpossible)) {
2120 frontend::Alert::warning(_("Alignment not permitted"),
2121 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2122 d->params_.align(LYX_ALIGN_LAYOUT);
2127 pos_type Paragraph::beginOfBody() const
2129 return d->begin_of_body_;
2133 void Paragraph::setBeginOfBody()
2135 if (d->layout_->labeltype != LABEL_MANUAL) {
2136 d->begin_of_body_ = 0;
2140 // Unroll the first two cycles of the loop
2141 // and remember the previous character to
2142 // remove unnecessary getChar() calls
2144 pos_type end = size();
2145 bool prev_char_deleted = false;
2146 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2149 char_type previous_char = d->text_[i];
2150 if (!(isNewline(i) || isEnvSeparator(i))) {
2152 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2153 char_type temp = d->text_[i];
2154 prev_char_deleted = isDeleted(i);
2155 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2158 previous_char = temp;
2164 d->begin_of_body_ = i;
2168 bool Paragraph::allowParagraphCustomization() const
2170 return inInset().allowParagraphCustomization();
2174 bool Paragraph::usePlainLayout() const
2176 return inInset().usePlainLayout();
2180 bool Paragraph::isPassThru() const
2182 return inInset().isPassThru() || d->layout_->pass_thru;
2187 // paragraphs inside floats need different alignment tags to avoid
2190 bool noTrivlistCentering(InsetCode code)
2192 return code == FLOAT_CODE
2193 || code == WRAP_CODE
2194 || code == CELL_CODE;
2198 string correction(string const & orig)
2200 if (orig == "flushleft")
2201 return "raggedright";
2202 if (orig == "flushright")
2203 return "raggedleft";
2204 if (orig == "center")
2210 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2211 InsetCode code, bool const lastpar, int & col)
2213 string macro = suffix + "{";
2214 if (noTrivlistCentering(code)) {
2216 // the last paragraph in non-trivlist-aligned
2217 // context is special (to avoid unwanted whitespace)
2218 if (suffix == "\\begin") {
2219 macro = "\\" + correction(env) + "{}";
2220 os << from_ascii(macro);
2221 col += macro.size();
2226 macro += correction(env);
2230 if (suffix == "\\par\\end") {
2234 os << from_ascii(macro);
2235 col += macro.size();
2236 if (suffix == "\\begin") {
2246 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2247 otexstream & os, OutputParams const & runparams) const
2252 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2253 (layout_->toggle_indent != ITOGGLE_NEVER) :
2254 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2256 if (canindent && params_.noindent() && !layout_->pass_thru) {
2257 os << "\\noindent ";
2261 LyXAlignment const curAlign = params_.align();
2263 if (curAlign == layout_->align)
2267 case LYX_ALIGN_NONE:
2268 case LYX_ALIGN_BLOCK:
2269 case LYX_ALIGN_LAYOUT:
2270 case LYX_ALIGN_SPECIAL:
2271 case LYX_ALIGN_DECIMAL:
2273 case LYX_ALIGN_LEFT:
2274 case LYX_ALIGN_RIGHT:
2275 case LYX_ALIGN_CENTER:
2276 if (runparams.moving_arg) {
2283 string const begin_tag = "\\begin";
2284 InsetCode code = ownerCode();
2285 bool const lastpar = runparams.isLastPar;
2286 // RTL in classic (PDF)LaTeX (without the Bidi package)
2287 // Luabibdi (used by LuaTeX) behaves like classic
2288 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2289 && !runparams.useBidiPackage();
2292 case LYX_ALIGN_NONE:
2293 case LYX_ALIGN_BLOCK:
2294 case LYX_ALIGN_LAYOUT:
2295 case LYX_ALIGN_SPECIAL:
2296 case LYX_ALIGN_DECIMAL:
2298 case LYX_ALIGN_LEFT: {
2300 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2301 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2303 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2305 } case LYX_ALIGN_RIGHT: {
2307 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2308 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2310 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2312 } case LYX_ALIGN_CENTER: {
2313 corrected_env(os, begin_tag, "center", code, lastpar, column);
2322 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2323 otexstream & os, OutputParams const & runparams) const
2325 LyXAlignment const curAlign = params_.align();
2327 if (curAlign == layout_->align)
2331 case LYX_ALIGN_NONE:
2332 case LYX_ALIGN_BLOCK:
2333 case LYX_ALIGN_LAYOUT:
2334 case LYX_ALIGN_SPECIAL:
2335 case LYX_ALIGN_DECIMAL:
2337 case LYX_ALIGN_LEFT:
2338 case LYX_ALIGN_RIGHT:
2339 case LYX_ALIGN_CENTER:
2340 if (runparams.moving_arg)
2345 bool output = false;
2347 string const end_tag = "\\par\\end";
2348 InsetCode code = ownerCode();
2349 bool const lastpar = runparams.isLastPar;
2350 // RTL in classic (PDF)LaTeX (without the Bidi package)
2351 // Luabibdi (used by LuaTeX) behaves like classic
2352 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2353 && !runparams.useBidiPackage();
2356 case LYX_ALIGN_NONE:
2357 case LYX_ALIGN_BLOCK:
2358 case LYX_ALIGN_LAYOUT:
2359 case LYX_ALIGN_SPECIAL:
2360 case LYX_ALIGN_DECIMAL:
2362 case LYX_ALIGN_LEFT: {
2364 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2365 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2367 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2369 } case LYX_ALIGN_RIGHT: {
2371 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2372 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2374 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2376 } case LYX_ALIGN_CENTER: {
2377 corrected_env(os, end_tag, "center", code, lastpar, col);
2382 return output || lastpar;
2386 // This one spits out the text of the paragraph
2387 void Paragraph::latex(BufferParams const & bparams,
2388 Font const & outerfont,
2390 OutputParams const & runparams,
2391 int start_pos, int end_pos, bool force) const
2393 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2395 // FIXME This check should not be needed. Perhaps issue an
2396 // error if it triggers.
2397 Layout const & style = inInset().forcePlainLayout() ?
2398 bparams.documentClass().plainLayout() : *d->layout_;
2400 if (!force && style.inpreamble)
2403 bool const allowcust = allowParagraphCustomization();
2405 // Current base font for all inherited font changes, without any
2406 // change caused by an individual character, except for the language:
2407 // It is set to the language of the first character.
2408 // As long as we are in the label, this font is the base font of the
2409 // label. Before the first body character it is set to the base font
2413 // If there is an open font-encoding changing command (script wrapper),
2414 // alien_script is set to its name
2415 string alien_script;
2418 // Maybe we have to create a optional argument.
2419 pos_type body_pos = beginOfBody();
2420 unsigned int column = 0;
2422 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2423 Font const real_outerfont = (!inInset().inheritFont()
2424 && runparams.local_font != nullptr)
2425 ? Font(runparams.local_font->fontInfo()) : outerfont;
2428 // the optional argument is kept in curly brackets in
2429 // case it contains a ']'
2430 // This is not strictly needed, but if this is changed it
2431 // would be a file format change, and tex2lyx would need
2432 // to be adjusted, since it unconditionally removes the
2433 // braces when it parses \item.
2436 basefont = getLabelFont(bparams, real_outerfont);
2438 basefont = getLayoutFont(bparams, real_outerfont);
2441 // Which font is currently active?
2442 Font running_font(basefont);
2443 // Do we have an open font change?
2444 bool open_font = false;
2446 Change runningChange = Change(Change::UNCHANGED);
2448 Encoding const * const prev_encoding = runparams.encoding;
2450 os.texrow().start(id(), 0);
2452 // if the paragraph is empty, the loop will not be entered at all
2454 // For InTitle commands, we have already opened a group
2455 // in output_latex::TeXOnePar.
2456 if (style.isCommand() && !style.intitle) {
2460 if (!style.leftdelim().empty()) {
2461 os << style.leftdelim();
2462 column += style.leftdelim().size();
2465 column += d->startTeXParParams(bparams, os, runparams);
2468 // Whether a \par can be issued for insets typeset inline with text.
2469 // Yes if greater than 0. This has to be static.
2470 THREAD_LOCAL_STATIC int parInline = 0;
2472 for (pos_type i = 0; i < size(); ++i) {
2473 // First char in paragraph or after label?
2474 if (i == body_pos) {
2477 bool needPar = false;
2478 column += running_font.latexWriteEndChanges(
2479 os, bparams, runparams,
2480 basefont, basefont, needPar);
2483 basefont = getLayoutFont(bparams, real_outerfont);
2484 running_font = basefont;
2486 column += Changes::latexMarkChange(os, bparams,
2487 runningChange, Change(Change::UNCHANGED),
2489 runningChange = Change(Change::UNCHANGED);
2494 // For InTitle commands, we have already opened a group
2495 // in output_latex::TeXOnePar.
2496 if (style.isCommand() && !style.intitle) {
2501 if (!style.leftdelim().empty()) {
2502 os << style.leftdelim();
2503 column += style.leftdelim().size();
2507 column += d->startTeXParParams(bparams, os,
2511 runparams.wasDisplayMath = runparams.inDisplayMath;
2512 runparams.inDisplayMath = false;
2513 bool deleted_display_math = false;
2514 Change const & change = runparams.inDeletedInset
2515 ? runparams.changeOfDeletedInset : lookupChange(i);
2517 char_type const c = d->text_[i];
2519 // Check whether a display math inset follows
2520 bool output_changes;
2521 if (runparams.for_searchAdv == OutputParams::NoSearch)
2522 output_changes = bparams.output_changes;
2524 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2526 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2528 runparams.ctObject = getInset(i)->getCtObject(runparams);
2530 InsetMath const * im = getInset(i)->asInsetMath();
2531 if (im && im->asHullInset()
2532 && im->asHullInset()->outerDisplay()) {
2533 runparams.inDisplayMath = true;
2534 // runparams.inDeletedInset will be set by
2535 // latexInset later, but we need this info
2536 // before it is called. On the other hand, we
2537 // cannot set it here because it is a counter.
2538 deleted_display_math = isDeleted(i);
2540 if (output_changes && deleted_display_math
2541 && runningChange == change
2542 && change.type == Change::DELETED
2543 && !os.afterParbreak()) {
2544 // A display math in the same paragraph follows.
2545 // We have to close and then reopen \lyxdeleted,
2546 // otherwise the math will be shifted up.
2547 OutputParams rp = runparams;
2549 bool needPar = false;
2550 column += running_font.latexWriteEndChanges(
2551 os, bparams, rp, basefont,
2555 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2556 : getLayoutFont(bparams, real_outerfont);
2557 running_font = basefont;
2558 column += Changes::latexMarkChange(os, bparams,
2559 Change(Change::INSERTED), change, rp);
2563 if (output_changes && runningChange != change) {
2564 if (!alien_script.empty()) {
2567 alien_script.clear();
2570 bool needPar = false;
2571 column += running_font.latexWriteEndChanges(
2572 os, bparams, runparams,
2573 basefont, basefont, needPar);
2576 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2577 : getLayoutFont(bparams, real_outerfont);
2578 running_font = basefont;
2579 column += Changes::latexMarkChange(os, bparams, runningChange,
2581 runningChange = change;
2584 // do not output text which is marked deleted
2585 // if change tracking output is disabled
2586 if (!output_changes && change.deleted()) {
2592 // Fully instantiated font
2593 Font current_font = getFont(bparams, i, outerfont);
2595 Font const prev_font = (i > 0) ?
2596 getFont(bparams, i - 1, outerfont)
2599 Font const last_font = running_font;
2600 bool const in_ct_deletion = (output_changes
2601 && runningChange == change
2602 && change.type == Change::DELETED
2603 && !os.afterParbreak());
2604 // Insets where font switches are used (rather than font commands)
2605 bool const fontswitch_inset =
2608 && getInset(i)->allowMultiPar()
2609 && getInset(i)->lyxCode() != ERT_CODE
2610 && getInset(i)->producesOutput();
2612 bool closeLanguage = false;
2613 bool lang_switched_at_inset = false;
2614 if (fontswitch_inset) {
2615 // Some insets cannot be inside a font change command.
2616 // However, even such insets *can* be placed in \L or \R
2617 // or their equivalents (for RTL language switches),
2618 // so we don't close the language in those cases
2619 // (= differing isRightToLeft()).
2620 // ArabTeX, though, doesn't seem to handle this special behavior.
2621 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2622 || basefont.language()->lang() == "arabic_arabtex"
2623 || current_font.language()->lang() == "arabic_arabtex";
2624 // We need to check prev_font as language changes directly at inset
2625 // will only be started inside the inset.
2626 lang_switched_at_inset = prev_font.language() != current_font.language();
2629 // Do we need to close the previous font?
2630 bool langClosed = false;
2632 ((current_font != running_font
2633 || current_font.language() != running_font.language())
2634 || (fontswitch_inset
2635 && (current_font == prev_font))))
2637 // ensure there is no open script-wrapper
2638 if (!alien_script.empty()) {
2641 alien_script.clear();
2643 if (in_ct_deletion) {
2644 // We have to close and then reopen \lyxdeleted,
2645 // as strikeout needs to be on lowest level.
2650 // Force language closing
2651 current_font.setLanguage(basefont.language());
2652 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2653 bool needPar = false;
2654 column += running_font.latexWriteEndChanges(
2655 os, bparams, runparams, basefont,
2657 if (in_ct_deletion) {
2658 // We have to close and then reopen \lyxdeleted,
2659 // as strikeout needs to be on lowest level.
2660 OutputParams rp = runparams;
2661 column += Changes::latexMarkChange(os, bparams,
2662 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2665 // Has the language been closed in the latexWriteEndChanges() call above?
2666 langClosed = running_font.language() != basefont.language()
2667 && running_font.language() != nextfont.language()
2668 && (running_font.language()->encoding()->package() != Encoding::CJK);
2669 running_font = basefont;
2672 // if necessary, close language environment before opening CJK
2673 string const running_lang = running_font.language()->babel();
2674 string const lang_end_command = lyxrc.language_command_end;
2675 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2676 && !running_lang.empty()
2677 && running_lang == openLanguageName()
2678 && current_font.language()->encoding()->package() == Encoding::CJK) {
2679 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2680 os << from_ascii(end_tag);
2681 column += end_tag.length();
2685 // Switch file encoding if necessary (and allowed)
2686 if ((!fontswitch_inset || closeLanguage)
2687 && !runparams.pass_thru && !style.pass_thru &&
2688 runparams.encoding->package() != Encoding::none &&
2689 current_font.language()->encoding()->package() != Encoding::none) {
2690 pair<bool, int> const enc_switch =
2691 switchEncoding(os.os(), bparams, runparams,
2692 *(current_font.language()->encoding()));
2693 if (enc_switch.first) {
2694 column += enc_switch.second;
2695 runparams.encoding = current_font.language()->encoding();
2699 // A display math inset inside an ulem command will be output
2700 // as a box of width \linewidth, so we have to either disable
2701 // indentation if the inset starts a paragraph, or start a new
2702 // line to accommodate such box. This has to be done before
2703 // writing any font changing commands.
2704 if (runparams.inDisplayMath && !deleted_display_math
2705 && runparams.inulemcmd) {
2706 if (os.afterParbreak())
2712 // Do we need to change font?
2713 if ((current_font != running_font ||
2714 current_font.language() != running_font.language())
2715 && i != body_pos - 1)
2717 if (!fontswitch_inset) {
2718 if (in_ct_deletion) {
2719 // We have to close and then reopen \lyxdeleted,
2720 // as strikeout needs to be on lowest level.
2721 OutputParams rp = runparams;
2722 bool needPar = false;
2723 column += running_font.latexWriteEndChanges(
2724 os, bparams, rp, basefont,
2729 otexstringstream ots;
2730 InsetText const * textinset = inInset().asInsetText();
2731 bool const cprotect = textinset
2732 ? textinset->hasCProtectContent(runparams.moving_arg)
2733 && !textinset->text().isMainText()
2735 column += current_font.latexWriteStartChanges(ots, bparams,
2736 runparams, basefont, last_font, false,
2738 // Check again for display math in ulem commands as a
2739 // font change may also occur just before a math inset.
2740 if (runparams.inDisplayMath && !deleted_display_math
2741 && runparams.inulemcmd) {
2742 if (os.afterParbreak())
2747 running_font = current_font;
2749 docstring fontchange = ots.str();
2751 // check whether the fontchange ends with a \\textcolor
2752 // modifier and the text starts with a space. If so we
2753 // need to add } in order to prevent \\textcolor from gobbling
2754 // the space (bug 4473).
2755 docstring const last_modifier = rsplit(fontchange, '\\');
2756 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2757 os << from_ascii("{}");
2758 else if (ots.terminateCommand())
2760 if (in_ct_deletion) {
2761 // We have to close and then reopen \lyxdeleted,
2762 // as strikeout needs to be on lowest level.
2763 OutputParams rp = runparams;
2764 column += Changes::latexMarkChange(os, bparams,
2765 Change(Change::UNCHANGED), change, rp);
2768 running_font = current_font;
2769 open_font = !langClosed;
2773 // FIXME: think about end_pos implementation...
2774 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2775 // FIXME: integrate this case in latexSpecialChar
2776 // Do not print the separation of the optional argument
2777 // if style.pass_thru is false. This works because
2778 // latexSpecialChar ignores spaces if
2779 // style.pass_thru is false.
2780 if (i != body_pos - 1) {
2781 if (d->simpleTeXBlanks(bparams, runparams, os,
2782 i, column, current_font, style)) {
2783 // A surrogate pair was output. We
2784 // must not call latexSpecialChar
2785 // in this iteration, since it would output
2786 // the combining character again.
2793 OutputParams rp = runparams;
2794 rp.free_spacing = style.free_spacing;
2795 rp.local_font = ¤t_font;
2796 rp.intitle = style.intitle;
2798 // Two major modes: LaTeX or plain
2799 // Handle here those cases common to both modes
2800 // and then split to handle the two modes separately.
2801 if (c == META_INSET) {
2802 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2803 // Greyedout notes and, in general, all insets
2804 // with InsetLayout::isDisplay() == false,
2805 // are typeset inline with the text. So, we
2806 // can add a \par to the last paragraph of
2807 // such insets only if nothing else follows.
2808 bool incremented = false;
2809 Inset const * inset = getInset(i);
2810 InsetText const * textinset = inset
2811 ? inset->asInsetText()
2813 if (i + 1 == size() && textinset
2814 && !inset->getLayout().isDisplay()) {
2815 ParagraphList const & pars =
2816 textinset->text().paragraphs();
2817 pit_type const pit = pars.size() - 1;
2818 Font const lastfont =
2819 pit < 0 || pars[pit].empty()
2820 ? pars[pit].getLayoutFont(
2823 : pars[pit].getFont(bparams,
2824 pars[pit].size() - 1,
2826 if (lastfont.fontInfo().size() !=
2827 basefont.fontInfo().size()) {
2832 // We need to restore parts of this after insets with
2833 // allowMultiPar() true
2834 Font const save_basefont = basefont;
2835 d->latexInset(bparams, os, rp, running_font,
2836 basefont, real_outerfont, open_font,
2837 runningChange, style, i, column, fontswitch_inset,
2838 closeLanguage, lang_switched_at_inset);
2839 if (fontswitch_inset) {
2841 bool needPar = false;
2842 column += running_font.latexWriteEndChanges(
2843 os, bparams, runparams,
2844 basefont, basefont, needPar);
2847 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2848 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2849 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2854 if (runparams.ctObject == CtObject::DisplayObject
2855 || runparams.ctObject == CtObject::UDisplayObject) {
2856 // Close \lyx*deleted and force its
2857 // reopening (if needed)
2860 runningChange = Change(Change::UNCHANGED);
2861 runparams.ctObject = CtObject::Normal;
2864 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2865 if (!bparams.useNonTeXFonts)
2866 script = Encodings::isKnownScriptChar(c);
2867 if (script != alien_script) {
2868 if (!alien_script.empty()) {
2870 alien_script.clear();
2872 string fontenc = running_font.language()->fontenc(bparams);
2874 && !Encodings::fontencSupportsScript(fontenc, script)) {
2875 column += script.length() + 2;
2876 os << "\\" << script << "{";
2877 alien_script = script;
2881 d->latexSpecialChar(os, bparams, rp, running_font,
2882 alien_script, style, i, end_pos, column);
2883 } catch (EncodingException & e) {
2884 if (runparams.dryrun) {
2885 os << "<" << _("LyX Warning: ")
2886 << _("uncodable character") << " '";
2890 // add location information and throw again.
2898 // Set the encoding to that returned from latexSpecialChar (see
2899 // comment for encoding member in OutputParams.h)
2900 runparams.encoding = rp.encoding;
2902 // Also carry on the info on a closed ulem command for insets
2903 // such as Note that do not produce any output, so that no
2904 // command is ever executed but its opening was recorded.
2905 runparams.inulemcmd = rp.inulemcmd;
2907 // These need to be passed upstream as well
2908 runparams.need_maketitle = rp.need_maketitle;
2909 runparams.have_maketitle = rp.have_maketitle;
2911 // And finally, pass the post_macros upstream
2912 runparams.post_macro = rp.post_macro;
2915 // Close wrapper for alien script
2916 if (!alien_script.empty()) {
2918 alien_script.clear();
2921 Font const font = empty()
2922 ? getLayoutFont(bparams, real_outerfont)
2923 : getFont(bparams, size() - 1, real_outerfont);
2925 InsetText const * textinset = inInset().asInsetText();
2927 bool const maintext = textinset
2928 ? textinset->text().isMainText()
2931 size_t const numpars = textinset
2932 ? textinset->text().paragraphs().size()
2935 bool needPar = false;
2937 if (style.resfont.size() != font.fontInfo().size()
2938 && (!runparams.isLastPar || maintext
2939 || (numpars > 1 && d->ownerCode() != CELL_CODE
2940 && (inInset().getLayout().isDisplay()
2942 && !style.isCommand()) {
2946 // If we have an open font definition, we have to close it
2948 // Make sure that \\par is done with the font of the last
2949 // character if this has another size as the default.
2950 // This is necessary because LaTeX (and LyX on the screen)
2951 // calculates the space between the baselines according
2952 // to this font. (Matthias)
2954 // We must not change the font for the last paragraph
2955 // of non-multipar insets, tabular cells or commands,
2956 // since this produces unwanted whitespace.
2957 #ifdef FIXED_LANGUAGE_END_DETECTION
2959 running_font.latexWriteEndChanges(os, bparams,
2960 runparams, basefont,
2961 next_->getFont(bparams, 0, outerfont),
2964 running_font.latexWriteEndChanges(os, bparams,
2965 runparams, basefont, basefont, needPar);
2968 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2969 //FIXME: there as we start another \selectlanguage with the next paragraph if
2970 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2971 running_font.latexWriteEndChanges(os, bparams, runparams,
2972 basefont, basefont, needPar);
2976 // The \par could not be inserted at the same nesting
2977 // level of the font size change, so do it now.
2978 os << "{\\" << font.latexSize() << "\\par}";
2981 column += Changes::latexMarkChange(os, bparams, runningChange,
2982 Change(Change::UNCHANGED), runparams);
2984 // Needed if there is an optional argument but no contents.
2985 if (body_pos > 0 && body_pos == size()) {
2989 if (!style.rightdelim().empty()) {
2990 os << style.rightdelim();
2991 column += style.rightdelim().size();
2994 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2995 && runparams.encoding != prev_encoding) {
2996 runparams.encoding = prev_encoding;
2997 os << setEncoding(prev_encoding->iconvName());
3000 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3004 bool Paragraph::emptyTag() const
3006 for (pos_type i = 0; i < size(); ++i) {
3007 if (Inset const * inset = getInset(i)) {
3008 InsetCode lyx_code = inset->lyxCode();
3009 // FIXME testing like that is wrong. What is
3011 if (lyx_code != TOC_CODE &&
3012 lyx_code != INCLUDE_CODE &&
3013 lyx_code != GRAPHICS_CODE &&
3014 lyx_code != ERT_CODE &&
3015 lyx_code != LISTINGS_CODE &&
3016 lyx_code != FLOAT_CODE &&
3017 lyx_code != TABULAR_CODE) {
3021 char_type c = d->text_[i];
3022 if (c != ' ' && c != '\t')
3030 string Paragraph::getID(Buffer const &, OutputParams const &)
3033 for (pos_type i = 0; i < size(); ++i) {
3034 if (Inset const * inset = getInset(i)) {
3035 InsetCode lyx_code = inset->lyxCode();
3036 if (lyx_code == LABEL_CODE) {
3037 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3038 docstring const & id = il->getParam("name");
3039 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3047 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3050 for (i = 0; i < size(); ++i) {
3051 if (Inset const * inset = getInset(i)) {
3052 inset->docbook(xs, runparams);
3054 char_type c = d->text_[i];
3064 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3068 for (i = 0; i < size(); ++i) {
3069 if (Inset const * inset = getInset(i)) {
3070 inset->xhtml(xs, runparams);
3072 char_type c = d->text_[i];
3082 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3085 pos_type size = text_.size();
3086 for (pos_type i = initial; i < size; ++i) {
3087 Font font = owner_->getFont(buf.params(), i, outerfont);
3088 if (text_[i] == META_INSET)
3090 if (i != initial && font != font_old)
3101 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3102 vector<xml::EndFontTag> & tagsToClose,
3103 bool & flag, FontState curstate, xml::FontTypes type)
3105 if (curstate == FONT_ON) {
3106 tagsToOpen.push_back(docbookStartFontTag(type));
3109 tagsToClose.push_back(docbookEndFontTag(type));
3114 class OptionalFontType {
3119 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3120 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3123 OptionalFontType fontShapeToXml(FontShape fs)
3127 return {xml::FT_ITALIC};
3129 return {xml::FT_SLANTED};
3130 case SMALLCAPS_SHAPE:
3131 return {xml::FT_SMALLCAPS};
3136 // the other tags are for internal use
3142 OptionalFontType fontFamilyToXml(FontFamily fm)
3146 return {xml::FT_ROMAN};
3148 return {xml::FT_SANS};
3149 case TYPEWRITER_FAMILY:
3150 return {xml::FT_TYPE};
3151 case INHERIT_FAMILY:
3154 // the other tags are for internal use
3160 OptionalFontType fontSizeToXml(FontSize fs)
3164 return {xml::FT_SIZE_TINY};
3166 return {xml::FT_SIZE_SCRIPT};
3168 return {xml::FT_SIZE_FOOTNOTE};
3170 return {xml::FT_SIZE_SMALL};
3172 return {xml::FT_SIZE_LARGE};
3174 return {xml::FT_SIZE_LARGER};
3176 return {xml::FT_SIZE_LARGEST};
3178 return {xml::FT_SIZE_HUGE};
3180 return {xml::FT_SIZE_HUGER};
3182 return {xml::FT_SIZE_INCREASE};
3184 return {xml::FT_SIZE_DECREASE};
3189 // the other tags are for internal use
3195 struct DocBookFontState
3197 FontShape curr_fs = INHERIT_SHAPE;
3198 FontFamily curr_fam = INHERIT_FAMILY;
3199 FontSize curr_size = INHERIT_SIZE;
3201 // track whether we have opened these tags
3202 bool emph_flag = false;
3203 bool bold_flag = false;
3204 bool noun_flag = false;
3205 bool ubar_flag = false;
3206 bool dbar_flag = false;
3207 bool sout_flag = false;
3208 bool xout_flag = false;
3209 bool wave_flag = false;
3211 bool shap_flag = false;
3213 bool faml_flag = false;
3215 bool size_flag = false;
3218 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3220 std::string const & default_family,
3221 DocBookFontState & fs)
3223 vector<xml::FontTag> tagsToOpen;
3224 vector<xml::EndFontTag> tagsToClose;
3227 FontState curstate = font.fontInfo().emph();
3228 if (font_old.emph() != curstate)
3229 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3232 curstate = font.fontInfo().noun();
3233 if (font_old.noun() != curstate)
3234 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3237 curstate = font.fontInfo().underbar();
3238 if (font_old.underbar() != curstate)
3239 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3242 curstate = font.fontInfo().strikeout();
3243 if (font_old.strikeout() != curstate)
3244 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3247 curstate = font.fontInfo().xout();
3248 if (font_old.xout() != curstate)
3249 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3252 curstate = font.fontInfo().uuline();
3253 if (font_old.uuline() != curstate)
3254 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3257 curstate = font.fontInfo().uwave();
3258 if (font_old.uwave() != curstate)
3259 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3262 // a little hackish, but allows us to reuse what we have.
3263 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3264 if (font_old.series() != font.fontInfo().series())
3265 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3268 fs.curr_fs = font.fontInfo().shape();
3269 FontShape old_fs = font_old.shape();
3270 if (old_fs != fs.curr_fs) {
3272 OptionalFontType tag = fontShapeToXml(old_fs);
3274 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3275 fs.shap_flag = false;
3278 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3280 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3284 fs.curr_fam = font.fontInfo().family();
3285 FontFamily old_fam = font_old.family();
3286 if (old_fam != fs.curr_fam) {
3288 OptionalFontType tag = fontFamilyToXml(old_fam);
3290 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3291 fs.faml_flag = false;
3293 switch (fs.curr_fam) {
3295 // we will treat a "default" font family as roman, since we have
3296 // no other idea what to do.
3297 if (default_family != "rmdefault" && default_family != "default") {
3298 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3299 fs.faml_flag = true;
3303 if (default_family != "sfdefault") {
3304 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3305 fs.faml_flag = true;
3308 case TYPEWRITER_FAMILY:
3309 if (default_family != "ttdefault") {
3310 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3311 fs.faml_flag = true;
3314 case INHERIT_FAMILY:
3317 // the other tags are for internal use
3324 fs.curr_size = font.fontInfo().size();
3325 FontSize old_size = font_old.size();
3326 if (old_size != fs.curr_size) {
3328 OptionalFontType tag = fontSizeToXml(old_size);
3330 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3331 fs.size_flag = false;
3334 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3335 if (tag.has_value) {
3336 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3337 fs.size_flag = true;
3341 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3344 } // anonymous namespace
3347 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3348 OutputParams const & runparams,
3349 Font const & outerfont,
3352 bool ignore_fonts) const
3354 // Track whether we have opened these tags
3355 DocBookFontState fs;
3357 Layout const & style = *d->layout_;
3359 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3361 string const default_family =
3362 buf.masterBuffer()->params().fonts_default_family;
3364 vector<xml::FontTag> tagsToOpen;
3365 vector<xml::EndFontTag> tagsToClose;
3367 std::vector<docstring> generatedParagraphs;
3368 DocBookFontState old_fs = fs;
3369 odocstringstream os;
3370 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3371 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3373 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3374 // characters at some point.
3375 std::vector<char_type> delayedChars;
3377 // Parsing main loop.
3378 for (pos_type i = initial; i < size(); ++i) {
3379 // Don't show deleted material in the output.
3383 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3385 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3387 xs->closeFontTags();
3389 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3390 generatedParagraphs.push_back(os.str());
3392 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3393 // that the string stream must be reset.
3394 os.str(from_ascii(""));
3396 xs = new XMLStream(os);
3398 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3399 if (!ignore_fonts) {
3400 font_old = outerfont.fontInfo();
3405 // Determine which tags should be opened or closed regarding fonts.
3406 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3407 if (!ignore_fonts) {
3408 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3411 // Other such tags? What about the other text ranges?
3413 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3414 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3415 for (; cit != cen; ++cit)
3418 // Deal with the delayed characters *after* closing font tags.
3419 if (!delayedChars.empty()) {
3420 for (char_type c: delayedChars)
3422 delayedChars.clear();
3425 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3426 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3427 for (; sit != sen; ++sit)
3430 tagsToClose.clear();
3434 if (Inset const * inset = getInset(i)) {
3435 if (!runparams.for_toc || inset->isInToc()) {
3436 OutputParams np = runparams;
3437 np.local_font = &font;
3439 // TODO: special case will bite here.
3440 np.docbook_in_par = true;
3441 inset->docbook(*xs, np);
3444 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3445 if (lyx::isSpace(c) && !ignore_fonts)
3446 delayedChars.push_back(c);
3450 font_old = font.fontInfo();
3453 // FIXME, this code is just imported from XHTML
3454 // I'm worried about what happens if a branch, say, is itself
3455 // wrapped in some font stuff. I think that will not work.
3457 xs->closeFontTags();
3459 // Deal with the delayed characters *after* closing font tags.
3460 if (!delayedChars.empty())
3461 for (char_type c: delayedChars)
3464 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3465 // last line to get a clean output.
3466 if (runparams.docbook_in_listing && !is_last_par)
3469 // Finalise the last (and most likely only) paragraph.
3470 generatedParagraphs.push_back(os.str());
3473 return generatedParagraphs;
3479 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3480 vector<xml::EndFontTag> & tagsToClose,
3481 bool & flag, FontState curstate, xml::FontTypes type)
3483 if (curstate == FONT_ON) {
3484 tagsToOpen.push_back(xhtmlStartFontTag(type));
3487 tagsToClose.push_back(xhtmlEndFontTag(type));
3492 } // anonymous namespace
3495 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3497 OutputParams const & runparams,
3498 Font const & outerfont,
3499 bool start_paragraph, bool close_paragraph,
3500 pos_type initial) const
3504 // track whether we have opened these tags
3505 bool emph_flag = false;
3506 bool bold_flag = false;
3507 bool noun_flag = false;
3508 bool ubar_flag = false;
3509 bool dbar_flag = false;
3510 bool sout_flag = false;
3511 bool xout_flag = false;
3512 bool wave_flag = false;
3514 bool shap_flag = false;
3516 bool faml_flag = false;
3518 bool size_flag = false;
3520 Layout const & style = *d->layout_;
3522 if (start_paragraph)
3523 xs.startDivision(allowEmpty());
3526 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3528 FontShape curr_fs = INHERIT_SHAPE;
3529 FontFamily curr_fam = INHERIT_FAMILY;
3530 FontSize curr_size = INHERIT_SIZE;
3532 string const default_family =
3533 buf.masterBuffer()->params().fonts_default_family;
3535 vector<xml::FontTag> tagsToOpen;
3536 vector<xml::EndFontTag> tagsToClose;
3538 // parsing main loop
3539 for (pos_type i = initial; i < size(); ++i) {
3540 // let's not show deleted material in the output
3544 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3547 FontState curstate = font.fontInfo().emph();
3548 if (font_old.emph() != curstate)
3549 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3552 curstate = font.fontInfo().noun();
3553 if (font_old.noun() != curstate)
3554 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3557 curstate = font.fontInfo().underbar();
3558 if (font_old.underbar() != curstate)
3559 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3562 curstate = font.fontInfo().strikeout();
3563 if (font_old.strikeout() != curstate)
3564 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3567 curstate = font.fontInfo().xout();
3568 if (font_old.xout() != curstate)
3569 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3572 curstate = font.fontInfo().uuline();
3573 if (font_old.uuline() != curstate)
3574 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3577 curstate = font.fontInfo().uwave();
3578 if (font_old.uwave() != curstate)
3579 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3582 // a little hackish, but allows us to reuse what we have.
3583 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3584 if (font_old.series() != font.fontInfo().series())
3585 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3588 curr_fs = font.fontInfo().shape();
3589 FontShape old_fs = font_old.shape();
3590 if (old_fs != curr_fs) {
3594 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3597 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3599 case SMALLCAPS_SHAPE:
3600 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3606 // the other tags are for internal use
3614 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3618 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3621 case SMALLCAPS_SHAPE:
3622 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3629 // the other tags are for internal use
3636 curr_fam = font.fontInfo().family();
3637 FontFamily old_fam = font_old.family();
3638 if (old_fam != curr_fam) {
3642 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3645 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3647 case TYPEWRITER_FAMILY:
3648 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3650 case INHERIT_FAMILY:
3653 // the other tags are for internal use
3661 // we will treat a "default" font family as roman, since we have
3662 // no other idea what to do.
3663 if (default_family != "rmdefault" && default_family != "default") {
3664 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3669 if (default_family != "sfdefault") {
3670 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3674 case TYPEWRITER_FAMILY:
3675 if (default_family != "ttdefault") {
3676 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3680 case INHERIT_FAMILY:
3683 // the other tags are for internal use
3690 curr_size = font.fontInfo().size();
3691 FontSize old_size = font_old.size();
3692 if (old_size != curr_size) {
3696 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3699 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3702 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3705 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3708 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3711 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3714 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3717 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3720 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3723 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3726 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3732 // the other tags are for internal use
3738 switch (curr_size) {
3740 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3744 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3748 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3752 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3756 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3760 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3764 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3768 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3772 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3776 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3780 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3787 // the other tags are for internal use
3794 // Other such tags? What about the other text ranges?
3796 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3797 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3798 for (; cit != cen; ++cit)
3801 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3802 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3803 for (; sit != sen; ++sit)
3806 tagsToClose.clear();
3809 Inset const * inset = getInset(i);
3811 if (!runparams.for_toc || inset->isInToc()) {
3812 OutputParams np = runparams;
3813 np.local_font = &font;
3814 // If the paragraph has size 1, then we are in the "special
3815 // case" where we do not output the containing paragraph info
3816 if (!inset->getLayout().htmlisblock() && size() != 1)
3817 np.html_in_par = true;
3818 retval += inset->xhtml(xs, np);
3821 char_type c = getUChar(buf.masterBuffer()->params(),
3823 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3824 xs << XMLStream::ESCAPE_NONE << " ";
3828 font_old = font.fontInfo();
3832 // I'm worried about what happens if a branch, say, is itself
3833 // wrapped in some font stuff. I think that will not work.
3835 if (close_paragraph)
3842 bool Paragraph::isHfill(pos_type pos) const
3844 Inset const * inset = getInset(pos);
3845 return inset && inset->isHfill();
3849 bool Paragraph::isNewline(pos_type pos) const
3851 // U+2028 LINE SEPARATOR
3852 // U+2029 PARAGRAPH SEPARATOR
3853 char_type const c = d->text_[pos];
3854 if (c == 0x2028 || c == 0x2029)
3856 Inset const * inset = getInset(pos);
3857 return inset && inset->lyxCode() == NEWLINE_CODE;
3861 bool Paragraph::isEnvSeparator(pos_type pos) const
3863 Inset const * inset = getInset(pos);
3864 return inset && inset->lyxCode() == SEPARATOR_CODE;
3868 bool Paragraph::isLineSeparator(pos_type pos) const
3870 char_type const c = d->text_[pos];
3871 if (isLineSeparatorChar(c))
3873 Inset const * inset = getInset(pos);
3874 return inset && inset->isLineSeparator();
3878 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3882 if (ignore_deleted && isDeleted(pos))
3884 if (Inset const * inset = getInset(pos))
3885 return !inset->isLetter();
3886 // if we have a hard hyphen (no en- or emdash) or apostrophe
3887 // we pass this to the spell checker
3888 // FIXME: this method is subject to change, visit
3889 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3890 // to get an impression how complex this is.
3891 if (isHardHyphenOrApostrophe(pos))
3893 char_type const c = d->text_[pos];
3894 // We want to pass the escape chars to the spellchecker
3895 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3896 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3900 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3902 pos_type const psize = size();
3905 char_type const c = d->text_[pos];
3906 if (c != '-' && c != '\'')
3908 pos_type nextpos = pos + 1;
3909 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3910 if ((nextpos == psize || isSpace(nextpos))
3911 && (pos == 0 || isSpace(prevpos)))
3917 bool Paragraph::needsCProtection(bool const fragile) const
3919 // first check the layout of the paragraph, but only in insets
3920 InsetText const * textinset = inInset().asInsetText();
3921 bool const maintext = textinset
3922 ? textinset->text().isMainText()
3925 if (!maintext && layout().needcprotect) {
3926 // Environments need cprotection regardless the content
3927 if (layout().latextype == LATEX_ENVIRONMENT)
3930 // Commands need cprotection if they contain specific chars
3931 int const nchars_escape = 9;
3932 static char_type const chars_escape[nchars_escape] = {
3933 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3935 docstring const pars = asString();
3936 for (int k = 0; k < nchars_escape; k++) {
3937 if (contains(pars, chars_escape[k]))
3942 // now check whether we have insets that need cprotection
3943 pos_type size = pos_type(d->text_.size());
3944 for (pos_type i = 0; i < size; ++i) {
3947 Inset const * ins = getInset(i);
3948 if (ins->needsCProtection(maintext, fragile))
3950 // Now check math environments
3951 InsetMath const * im = getInset(i)->asInsetMath();
3952 if (!im || im->cell(0).empty())
3954 switch(im->cell(0)[0]->lyxCode()) {
3955 case MATH_AMSARRAY_CODE:
3956 case MATH_SUBSTACK_CODE:
3958 case MATH_XYMATRIX_CODE:
3959 // these need cprotection
3970 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3972 return d->speller_state_.getRange(pos);
3976 bool Paragraph::isChar(pos_type pos) const
3978 if (Inset const * inset = getInset(pos))
3979 return inset->isChar();
3980 char_type const c = d->text_[pos];
3981 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3985 bool Paragraph::isSpace(pos_type pos) const
3987 if (Inset const * inset = getInset(pos))
3988 return inset->isSpace();
3989 char_type const c = d->text_[pos];
3990 return lyx::isSpace(c);
3995 Paragraph::getParLanguage(BufferParams const & bparams) const
3998 return getFirstFontSettings(bparams).language();
3999 // FIXME: we should check the prev par as well (Lgb)
4000 return bparams.language;
4004 bool Paragraph::isRTL(BufferParams const & bparams) const
4006 return getParLanguage(bparams)->rightToLeft()
4007 && !inInset().getLayout().forceLTR();
4011 void Paragraph::changeLanguage(BufferParams const & bparams,
4012 Language const * from, Language const * to)
4014 // change language including dummy font change at the end
4015 for (pos_type i = 0; i <= size(); ++i) {
4016 Font font = getFontSettings(bparams, i);
4017 if (font.language() == from) {
4018 font.setLanguage(to);
4020 d->requestSpellCheck(i);
4026 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4028 Language const * doc_language = bparams.language;
4029 for (auto const & f : d->fontlist_)
4030 if (f.font().language() != ignore_language &&
4031 f.font().language() != latex_language &&
4032 f.font().language() != doc_language)
4038 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4040 for (auto const & f : d->fontlist_) {
4041 Language const * lang = f.font().language();
4042 if (lang != ignore_language &&
4043 lang != latex_language)
4049 docstring Paragraph::asString(int options) const
4051 return asString(0, size(), options);
4055 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4057 odocstringstream os;
4060 && options & AS_STR_LABEL
4061 && !d->params_.labelString().empty())
4062 os << d->params_.labelString() << ' ';
4064 for (pos_type i = beg; i < end; ++i) {
4065 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4067 char_type const c = d->text_[i];
4068 if (isPrintable(c) || c == '\t'
4069 || (c == '\n' && (options & AS_STR_NEWLINES)))
4071 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4072 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4073 LASSERT(runparams != nullptr, return docstring());
4074 getInset(i)->plaintext(os, *runparams);
4076 getInset(i)->toString(os);
4085 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4086 bool const shorten, bool const label) const
4088 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4089 if (label && !labelString().empty())
4090 os += labelString() + ' ';
4091 if (!layout().isTocCaption())
4093 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4096 char_type const c = d->text_[i];
4099 else if (c == META_INSET)
4100 getInset(i)->forOutliner(os, tmplen, false);
4103 Text::shortenForOutliner(os, maxlen);
4107 void Paragraph::setInsetOwner(Inset const * inset)
4109 d->inset_owner_ = inset;
4113 int Paragraph::id() const
4119 void Paragraph::setId(int id)
4125 Layout const & Paragraph::layout() const
4131 void Paragraph::setLayout(Layout const & layout)
4133 d->layout_ = &layout;
4137 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4139 setLayout(tc.defaultLayout());
4143 void Paragraph::setPlainLayout(DocumentClass const & tc)
4145 setLayout(tc.plainLayout());
4149 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4151 if (usePlainLayout())
4154 setDefaultLayout(tc);
4158 Inset const & Paragraph::inInset() const
4160 LBUFERR(d->inset_owner_);
4161 return *d->inset_owner_;
4165 ParagraphParameters & Paragraph::params()
4171 ParagraphParameters const & Paragraph::params() const
4177 bool Paragraph::isFreeSpacing() const
4179 if (d->layout_->free_spacing)
4181 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4185 bool Paragraph::allowEmpty() const
4187 if (d->layout_->keepempty)
4189 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4193 bool Paragraph::brokenBiblio() const
4195 // There is a problem if there is no bibitem at position 0 in
4196 // paragraphs that need one, if there is another bibitem in the
4197 // paragraph or if this paragraph is not supposed to have
4198 // a bibitem inset at all.
4199 return ((d->layout_->labeltype == LABEL_BIBLIO
4200 && (d->insetlist_.find(BIBITEM_CODE) != 0
4201 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4202 || (d->layout_->labeltype != LABEL_BIBLIO
4203 && d->insetlist_.find(BIBITEM_CODE) != -1));
4207 int Paragraph::fixBiblio(Buffer const & buffer)
4209 // FIXME: when there was already an inset at 0, the return value is 1,
4210 // which does not tell whether another inset has been removed; the
4211 // cursor cannot be correctly updated.
4213 bool const track_changes = buffer.params().track_changes;
4214 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4216 // The case where paragraph is not BIBLIO
4217 if (d->layout_->labeltype != LABEL_BIBLIO) {
4218 if (bibitem_pos == -1)
4219 // No InsetBibitem => OK
4221 // There is an InsetBibitem: remove it!
4222 d->insetlist_.release(bibitem_pos);
4223 eraseChar(bibitem_pos, track_changes);
4224 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4227 bool const hasbibitem0 = bibitem_pos == 0;
4229 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4230 // There was an InsetBibitem at pos 0,
4231 // and no other one => OK
4232 if (bibitem_pos == -1)
4234 // there is a bibitem at the 0 position, but since
4235 // there is a second one, we copy the second on the
4236 // first. We're assuming there are at most two of
4237 // these, which there should be.
4238 // FIXME: why does it make sense to do that rather
4239 // than keep the first? (JMarc)
4240 Inset * inset = releaseInset(bibitem_pos);
4241 d->insetlist_.begin()->inset = inset;
4242 // This needs to be done to update the counter (#8499)
4243 buffer.updateBuffer();
4244 return -bibitem_pos;
4247 // We need to create an inset at the beginning
4248 Inset * inset = nullptr;
4249 if (bibitem_pos > 0) {
4250 // there was one somewhere in the paragraph, let's move it
4251 inset = d->insetlist_.release(bibitem_pos);
4252 eraseChar(bibitem_pos, track_changes);
4255 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4256 InsetCommandParams(BIBITEM_CODE));
4258 Font font(inherit_font, buffer.params().language);
4259 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4260 : Change::UNCHANGED));
4262 // This is needed to get the counters right
4263 buffer.updateBuffer();
4268 void Paragraph::checkAuthors(AuthorList const & authorList)
4270 d->changes_.checkAuthors(authorList);
4274 bool Paragraph::isChanged(pos_type pos) const
4276 return lookupChange(pos).changed();
4280 bool Paragraph::isInserted(pos_type pos) const
4282 return lookupChange(pos).inserted();
4286 bool Paragraph::isDeleted(pos_type pos) const
4288 return lookupChange(pos).deleted();
4292 InsetList const & Paragraph::insetList() const
4294 return d->insetlist_;
4298 void Paragraph::setInsetBuffers(Buffer & b)
4300 d->insetlist_.setBuffer(b);
4304 void Paragraph::resetBuffer()
4306 d->insetlist_.resetBuffer();
4310 Inset * Paragraph::releaseInset(pos_type pos)
4312 Inset * inset = d->insetlist_.release(pos);
4313 /// does not honour change tracking!
4314 eraseChar(pos, false);
4319 Inset * Paragraph::getInset(pos_type pos)
4321 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4322 ? d->insetlist_.get(pos) : nullptr;
4326 Inset const * Paragraph::getInset(pos_type pos) const
4328 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4329 ? d->insetlist_.get(pos) : nullptr;
4333 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4334 pos_type & right, TextCase action)
4336 // process sequences of modified characters; in change
4337 // tracking mode, this approach results in much better
4338 // usability than changing case on a char-by-char basis
4339 // We also need to track the current font, since font
4340 // changes within sequences can occur.
4341 vector<pair<char_type, Font> > changes;
4343 bool const trackChanges = bparams.track_changes;
4345 bool capitalize = true;
4347 for (; pos < right; ++pos) {
4348 char_type oldChar = d->text_[pos];
4349 char_type newChar = oldChar;
4351 // ignore insets and don't play with deleted text!
4352 if (oldChar != META_INSET && !isDeleted(pos)) {
4354 case text_lowercase:
4355 newChar = lowercase(oldChar);
4357 case text_capitalization:
4359 newChar = uppercase(oldChar);
4363 case text_uppercase:
4364 newChar = uppercase(oldChar);
4369 if (isWordSeparator(pos) || isDeleted(pos)) {
4370 // permit capitalization again
4374 if (oldChar != newChar) {
4375 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4376 if (pos != right - 1)
4378 // step behind the changing area
4382 int erasePos = pos - changes.size();
4383 for (auto const & change : changes) {
4384 insertChar(pos, change.first, change.second, trackChanges);
4385 if (!eraseChar(erasePos, trackChanges)) {
4388 ++right; // expand selection
4396 int Paragraph::find(docstring const & str, bool cs, bool mw,
4397 pos_type start_pos, bool del) const
4399 pos_type pos = start_pos;
4400 int const strsize = str.length();
4402 pos_type const parsize = d->text_.size();
4403 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4404 // ignore deleted matter
4405 if (!del && isDeleted(pos)) {
4406 if (pos == parsize - 1)
4412 // Ignore "invisible" letters such as ligature breaks
4413 // and hyphenation chars while searching
4414 bool nonmatch = false;
4415 while (pos < parsize && isInset(pos)) {
4416 Inset const * inset = getInset(pos);
4417 if (!inset->isLetter() && !inset->isChar())
4419 odocstringstream os;
4420 inset->toString(os);
4421 if (!os.str().empty()) {
4422 int const insetstringsize = os.str().length();
4423 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4424 if (str[i] != os.str()[j]) {
4432 if (nonmatch || i == strsize)
4434 if (cs && str[i] != d->text_[pos])
4436 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4443 // if necessary, check whether string matches word
4445 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4448 && !isWordSeparator(pos))
4452 return pos - start_pos;
4456 char_type Paragraph::getChar(pos_type pos) const
4458 return d->text_[pos];
4462 pos_type Paragraph::size() const
4464 return d->text_.size();
4468 bool Paragraph::empty() const
4470 return d->text_.empty();
4474 bool Paragraph::isInset(pos_type pos) const
4476 return d->text_[pos] == META_INSET;
4480 bool Paragraph::isSeparator(pos_type pos) const
4482 //FIXME: Are we sure this can be the only separator?
4483 return d->text_[pos] == ' ';
4487 void Paragraph::deregisterWords()
4489 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4490 Private::LangWordsMap::const_iterator ite = d->words_.end();
4491 for (; itl != ite; ++itl) {
4492 WordList & wl = theWordList(itl->first);
4493 Private::Words::const_iterator it = (itl->second).begin();
4494 Private::Words::const_iterator et = (itl->second).end();
4495 for (; it != et; ++it)
4502 void Paragraph::locateWord(pos_type & from, pos_type & to,
4503 word_location const loc, bool const ignore_deleted) const
4506 case WHOLE_WORD_STRICT:
4507 if (from == 0 || from == size()
4508 || isWordSeparator(from, ignore_deleted)
4509 || isWordSeparator(from - 1, ignore_deleted)) {
4516 // If we are already at the beginning of a word, do nothing
4517 if (!from || isWordSeparator(from - 1, ignore_deleted))
4522 // always move the cursor to the beginning of previous word
4523 while (from && !isWordSeparator(from - 1, ignore_deleted))
4527 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4530 // no need to move the 'from' cursor
4534 while (to < size() && !isWordSeparator(to, ignore_deleted))
4539 void Paragraph::collectWords()
4541 for (pos_type pos = 0; pos < size(); ++pos) {
4542 if (isWordSeparator(pos))
4544 pos_type from = pos;
4545 locateWord(from, pos, WHOLE_WORD);
4546 // Work around MSVC warning: The statement
4547 // if (pos < from + lyxrc.completion_minlength)
4548 // triggers a signed vs. unsigned warning.
4549 // I don't know why this happens, it could be a MSVC bug, or
4550 // related to LLP64 (windows) vs. LP64 (unix) programming
4551 // model, or the C++ standard might be ambigous in the section
4552 // defining the "usual arithmetic conversions". However, using
4553 // a temporary variable is safe and works on all compilers.
4554 pos_type const endpos = from + lyxrc.completion_minlength;
4557 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4558 if (cit == d->fontlist_.end())
4560 Language const * lang = cit->font().language();
4561 docstring const word = asString(from, pos, AS_STR_NONE);
4562 d->words_[lang->lang()].insert(word);
4567 void Paragraph::registerWords()
4569 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4570 Private::LangWordsMap::const_iterator ite = d->words_.end();
4571 for (; itl != ite; ++itl) {
4572 WordList & wl = theWordList(itl->first);
4573 Private::Words::const_iterator it = (itl->second).begin();
4574 Private::Words::const_iterator et = (itl->second).end();
4575 for (; it != et; ++it)
4581 void Paragraph::updateWords()
4589 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4591 SkipPositionsIterator begin = skips.begin();
4592 SkipPositions::iterator end = skips.end();
4593 if (pos > 0 && begin < end) {
4595 if (end->last == pos - 1) {
4600 skips.insert(end, FontSpan(pos, pos));
4604 Language * Paragraph::Private::locateSpellRange(
4605 pos_type & from, pos_type & to,
4606 SkipPositions & skips) const
4608 // skip leading white space
4609 while (from < to && owner_->isWordSeparator(from))
4611 // don't check empty range
4614 // get current language
4615 Language * lang = getSpellLanguage(from);
4616 pos_type last = from;
4617 bool samelang = true;
4618 bool sameinset = true;
4619 while (last < to && samelang && sameinset) {
4620 // hop to end of word
4621 while (last < to && !owner_->isWordSeparator(last)) {
4622 Inset const * inset = owner_->getInset(last);
4623 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4624 // check for "invisible" letters such as ligature breaks
4625 odocstringstream os;
4626 inset->toString(os);
4627 if (os.str().length() != 0) {
4628 // avoid spell check of visible special char insets
4629 // stop the loop in front of the special char inset
4634 appendSkipPosition(skips, last);
4635 } else if (owner_->isDeleted(last)) {
4636 appendSkipPosition(skips, last);
4640 // hop to next word while checking for insets
4641 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4642 if (Inset const * inset = owner_->getInset(last))
4643 sameinset = inset->isChar() && inset->isLetter();
4644 if (sameinset && owner_->isDeleted(last)) {
4645 appendSkipPosition(skips, last);
4650 if (sameinset && last < to) {
4651 // now check for language change
4652 samelang = lang == getSpellLanguage(last);
4655 // if language change detected backstep is needed
4663 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4666 const_cast<Language *>(owner_->getFontSettings(
4667 inset_owner_->buffer().params(), from).language());
4668 if (lang == inset_owner_->buffer().params().language
4669 && !lyxrc.spellchecker_alt_lang.empty()) {
4671 string const lang_variety =
4672 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4673 lang->setCode(lang_code);
4674 lang->setVariety(lang_variety);
4680 void Paragraph::requestSpellCheck(pos_type pos)
4682 d->requestSpellCheck(pos);
4686 bool Paragraph::needsSpellCheck() const
4688 SpellChecker::ChangeNumber speller_change_number = 0;
4689 if (theSpellChecker())
4690 speller_change_number = theSpellChecker()->changeNumber();
4691 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4692 d->speller_state_.needsCompleteRefresh(speller_change_number);
4694 return d->needsSpellCheck();
4698 bool Paragraph::Private::ignoreWord(docstring const & word) const
4700 // Ignore words with digits
4701 // FIXME: make this customizable
4702 // (note that some checkers ignore words with digits by default)
4703 docstring::const_iterator cit = word.begin();
4704 docstring::const_iterator const end = word.end();
4705 for (; cit != end; ++cit) {
4706 if (isNumber((*cit)))
4713 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4714 WordLangTuple & wl, docstring_list & suggestions,
4715 bool do_suggestion, bool check_learned) const
4717 SpellChecker::Result result = SpellChecker::WORD_OK;
4718 SpellChecker * speller = theSpellChecker();
4722 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4725 locateWord(from, to, WHOLE_WORD, true);
4726 if (from == to || from >= size())
4729 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4730 Language * lang = d->getSpellLanguage(from);
4732 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4735 wl = WordLangTuple(word, lang);
4740 if (needsSpellCheck() || check_learned) {
4742 if (!d->ignoreWord(word)) {
4743 bool const trailing_dot = to < size() && d->text_[to] == '.';
4744 result = speller->check(wl);
4745 if (SpellChecker::misspelled(result) && trailing_dot) {
4746 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4747 result = speller->check(wl);
4748 if (!SpellChecker::misspelled(result)) {
4749 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4751 from << ".." << to << "]");
4753 // spell check with dot appended failed too
4754 // restore original word/lang value
4755 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4756 wl = WordLangTuple(word, lang);
4760 if (!SpellChecker::misspelled(result)) {
4761 // area up to the begin of the next word is not misspelled
4762 while (end < size() && isWordSeparator(end))
4765 d->setMisspelled(from, end, result);
4767 result = d->speller_state_.getState(from);
4771 suggestions.clear();
4773 if (SpellChecker::misspelled(result)) {
4774 LYXERR(Debug::GUI, "misspelled word: \"" <<
4776 from << ".." << to << "]");
4778 speller->suggest(wl, suggestions);
4784 void Paragraph::anonymize()
4786 // This is a very crude anonymization for now
4787 for (char_type & c : d->text_)
4788 if (isLetterChar(c) || isNumber(c))
4793 void Paragraph::Private::markMisspelledWords(
4794 pos_type const & first, pos_type const & last,
4795 SpellChecker::Result result,
4796 docstring const & word,
4797 SkipPositions const & skips)
4799 if (!SpellChecker::misspelled(result)) {
4800 setMisspelled(first, last, SpellChecker::WORD_OK);
4804 SpellChecker * speller = theSpellChecker();
4805 // locate and enumerate the error positions
4806 int nerrors = speller->numMisspelledWords();
4808 SkipPositionsIterator it = skips.begin();
4809 SkipPositionsIterator et = skips.end();
4810 for (int index = 0; index < nerrors; ++index) {
4813 speller->misspelledWord(index, wstart, wlen);
4814 /// should not happen if speller supports range checks
4815 if (!wlen) continue;
4816 docstring const misspelled = word.substr(wstart, wlen);
4817 wstart += first + numskipped;
4818 if (snext < wstart) {
4819 /// mark the range of correct spelling
4820 numskipped += countSkips(it, et, wstart);
4821 setMisspelled(snext,
4822 wstart - 1, SpellChecker::WORD_OK);
4824 snext = wstart + wlen;
4825 numskipped += countSkips(it, et, snext);
4826 /// mark the range of misspelling
4827 setMisspelled(wstart, snext, result);
4828 LYXERR(Debug::GUI, "misspelled word: \"" <<
4829 misspelled << "\" [" <<
4830 wstart << ".." << (snext-1) << "]");
4833 if (snext <= last) {
4834 /// mark the range of correct spelling at end
4835 setMisspelled(snext, last, SpellChecker::WORD_OK);
4840 void Paragraph::spellCheck() const
4842 SpellChecker * speller = theSpellChecker();
4843 if (!speller || empty() ||!needsSpellCheck())
4847 d->rangeOfSpellCheck(start, endpos);
4848 if (speller->canCheckParagraph()) {
4849 // loop until we leave the range
4850 for (pos_type first = start; first < endpos; ) {
4851 pos_type last = endpos;
4852 Private::SkipPositions skips;
4853 Language * lang = d->locateSpellRange(first, last, skips);
4854 if (first >= endpos)
4856 // start the spell checker on the unit of meaning
4857 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4858 WordLangTuple wl = WordLangTuple(word, lang);
4859 SpellChecker::Result result = !word.empty() ?
4860 speller->check(wl) : SpellChecker::WORD_OK;
4861 d->markMisspelledWords(first, last, result, word, skips);
4865 static docstring_list suggestions;
4866 pos_type to = endpos;
4867 while (start < endpos) {
4869 spellCheck(start, to, wl, suggestions, false);
4873 d->readySpellCheck();
4877 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4879 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4880 if (result || pos <= 0 || pos > size())
4882 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4883 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4888 string Paragraph::magicLabel() const
4891 ss << "magicparlabel-" << id();