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_search
1133 || contains(style.pass_thru_chars, c)
1134 || contains(runparams.pass_thru_chars, c)) {
1135 if (runparams.for_search) {
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
2521 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2523 runparams.ctObject = getInset(i)->getCtObject(runparams);
2525 InsetMath const * im = getInset(i)->asInsetMath();
2526 if (im && im->asHullInset()
2527 && im->asHullInset()->outerDisplay()) {
2528 runparams.inDisplayMath = true;
2529 // runparams.inDeletedInset will be set by
2530 // latexInset later, but we need this info
2531 // before it is called. On the other hand, we
2532 // cannot set it here because it is a counter.
2533 deleted_display_math = isDeleted(i);
2535 if (bparams.output_changes && deleted_display_math
2536 && runningChange == change
2537 && change.type == Change::DELETED
2538 && !os.afterParbreak()) {
2539 // A display math in the same paragraph follows.
2540 // We have to close and then reopen \lyxdeleted,
2541 // otherwise the math will be shifted up.
2542 OutputParams rp = runparams;
2544 bool needPar = false;
2545 column += running_font.latexWriteEndChanges(
2546 os, bparams, rp, basefont,
2550 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2551 : getLayoutFont(bparams, real_outerfont);
2552 running_font = basefont;
2553 column += Changes::latexMarkChange(os, bparams,
2554 Change(Change::INSERTED), change, rp);
2558 if (bparams.output_changes && runningChange != change) {
2559 if (!alien_script.empty()) {
2562 alien_script.clear();
2565 bool needPar = false;
2566 column += running_font.latexWriteEndChanges(
2567 os, bparams, runparams,
2568 basefont, basefont, needPar);
2571 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2572 : getLayoutFont(bparams, real_outerfont);
2573 running_font = basefont;
2574 column += Changes::latexMarkChange(os, bparams, runningChange,
2576 runningChange = change;
2579 // do not output text which is marked deleted
2580 // if change tracking output is disabled
2581 if (!bparams.output_changes && change.deleted()) {
2587 // Fully instantiated font
2588 Font current_font = getFont(bparams, i, outerfont);
2590 Font const prev_font = (i > 0) ?
2591 getFont(bparams, i - 1, outerfont)
2594 Font const last_font = running_font;
2595 bool const in_ct_deletion = (bparams.output_changes
2596 && runningChange == change
2597 && change.type == Change::DELETED
2598 && !os.afterParbreak());
2599 // Insets where font switches are used (rather than font commands)
2600 bool const fontswitch_inset =
2603 && getInset(i)->allowMultiPar()
2604 && getInset(i)->lyxCode() != ERT_CODE
2605 && getInset(i)->producesOutput();
2607 bool closeLanguage = false;
2608 bool lang_switched_at_inset = false;
2609 if (fontswitch_inset) {
2610 // Some insets cannot be inside a font change command.
2611 // However, even such insets *can* be placed in \L or \R
2612 // or their equivalents (for RTL language switches),
2613 // so we don't close the language in those cases
2614 // (= differing isRightToLeft()).
2615 // ArabTeX, though, doesn't seem to handle this special behavior.
2616 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2617 || basefont.language()->lang() == "arabic_arabtex"
2618 || current_font.language()->lang() == "arabic_arabtex";
2619 // We need to check prev_font as language changes directly at inset
2620 // will only be started inside the inset.
2621 lang_switched_at_inset = prev_font.language() != current_font.language();
2624 // Do we need to close the previous font?
2625 bool langClosed = false;
2627 ((current_font != running_font
2628 || current_font.language() != running_font.language())
2629 || (fontswitch_inset
2630 && (current_font == prev_font))))
2632 // ensure there is no open script-wrapper
2633 if (!alien_script.empty()) {
2636 alien_script.clear();
2638 if (in_ct_deletion) {
2639 // We have to close and then reopen \lyxdeleted,
2640 // as strikeout needs to be on lowest level.
2645 // Force language closing
2646 current_font.setLanguage(basefont.language());
2647 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2648 bool needPar = false;
2649 column += running_font.latexWriteEndChanges(
2650 os, bparams, runparams, basefont,
2652 if (in_ct_deletion) {
2653 // We have to close and then reopen \lyxdeleted,
2654 // as strikeout needs to be on lowest level.
2655 OutputParams rp = runparams;
2656 column += Changes::latexMarkChange(os, bparams,
2657 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2660 // Has the language been closed in the latexWriteEndChanges() call above?
2661 langClosed = running_font.language() != basefont.language()
2662 && running_font.language() != nextfont.language()
2663 && (running_font.language()->encoding()->package() != Encoding::CJK);
2664 running_font = basefont;
2667 // if necessary, close language environment before opening CJK
2668 string const running_lang = running_font.language()->babel();
2669 string const lang_end_command = lyxrc.language_command_end;
2670 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2671 && !running_lang.empty()
2672 && running_lang == openLanguageName()
2673 && current_font.language()->encoding()->package() == Encoding::CJK) {
2674 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2675 os << from_ascii(end_tag);
2676 column += end_tag.length();
2680 // Switch file encoding if necessary (and allowed)
2681 if ((!fontswitch_inset || closeLanguage)
2682 && !runparams.pass_thru && !style.pass_thru &&
2683 runparams.encoding->package() != Encoding::none &&
2684 current_font.language()->encoding()->package() != Encoding::none) {
2685 pair<bool, int> const enc_switch =
2686 switchEncoding(os.os(), bparams, runparams,
2687 *(current_font.language()->encoding()));
2688 if (enc_switch.first) {
2689 column += enc_switch.second;
2690 runparams.encoding = current_font.language()->encoding();
2694 // A display math inset inside an ulem command will be output
2695 // as a box of width \linewidth, so we have to either disable
2696 // indentation if the inset starts a paragraph, or start a new
2697 // line to accommodate such box. This has to be done before
2698 // writing any font changing commands.
2699 if (runparams.inDisplayMath && !deleted_display_math
2700 && runparams.inulemcmd) {
2701 if (os.afterParbreak())
2707 // Do we need to change font?
2708 if ((current_font != running_font ||
2709 current_font.language() != running_font.language())
2710 && i != body_pos - 1)
2712 if (!fontswitch_inset) {
2713 if (in_ct_deletion) {
2714 // We have to close and then reopen \lyxdeleted,
2715 // as strikeout needs to be on lowest level.
2716 OutputParams rp = runparams;
2717 bool needPar = false;
2718 column += running_font.latexWriteEndChanges(
2719 os, bparams, rp, basefont,
2724 otexstringstream ots;
2725 InsetText const * textinset = inInset().asInsetText();
2726 bool const cprotect = textinset
2727 ? textinset->hasCProtectContent(runparams.moving_arg)
2728 && !textinset->text().isMainText()
2730 column += current_font.latexWriteStartChanges(ots, bparams,
2731 runparams, basefont, last_font, false,
2733 // Check again for display math in ulem commands as a
2734 // font change may also occur just before a math inset.
2735 if (runparams.inDisplayMath && !deleted_display_math
2736 && runparams.inulemcmd) {
2737 if (os.afterParbreak())
2742 running_font = current_font;
2744 docstring fontchange = ots.str();
2746 // check whether the fontchange ends with a \\textcolor
2747 // modifier and the text starts with a space. If so we
2748 // need to add } in order to prevent \\textcolor from gobbling
2749 // the space (bug 4473).
2750 docstring const last_modifier = rsplit(fontchange, '\\');
2751 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2752 os << from_ascii("{}");
2753 else if (ots.terminateCommand())
2755 if (in_ct_deletion) {
2756 // We have to close and then reopen \lyxdeleted,
2757 // as strikeout needs to be on lowest level.
2758 OutputParams rp = runparams;
2759 column += Changes::latexMarkChange(os, bparams,
2760 Change(Change::UNCHANGED), change, rp);
2763 running_font = current_font;
2764 open_font = !langClosed;
2768 // FIXME: think about end_pos implementation...
2769 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2770 // FIXME: integrate this case in latexSpecialChar
2771 // Do not print the separation of the optional argument
2772 // if style.pass_thru is false. This works because
2773 // latexSpecialChar ignores spaces if
2774 // style.pass_thru is false.
2775 if (i != body_pos - 1) {
2776 if (d->simpleTeXBlanks(bparams, runparams, os,
2777 i, column, current_font, style)) {
2778 // A surrogate pair was output. We
2779 // must not call latexSpecialChar
2780 // in this iteration, since it would output
2781 // the combining character again.
2788 OutputParams rp = runparams;
2789 rp.free_spacing = style.free_spacing;
2790 rp.local_font = ¤t_font;
2791 rp.intitle = style.intitle;
2793 // Two major modes: LaTeX or plain
2794 // Handle here those cases common to both modes
2795 // and then split to handle the two modes separately.
2796 if (c == META_INSET) {
2797 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2798 // Greyedout notes and, in general, all insets
2799 // with InsetLayout::isDisplay() == false,
2800 // are typeset inline with the text. So, we
2801 // can add a \par to the last paragraph of
2802 // such insets only if nothing else follows.
2803 bool incremented = false;
2804 Inset const * inset = getInset(i);
2805 InsetText const * textinset = inset
2806 ? inset->asInsetText()
2808 if (i + 1 == size() && textinset
2809 && !inset->getLayout().isDisplay()) {
2810 ParagraphList const & pars =
2811 textinset->text().paragraphs();
2812 pit_type const pit = pars.size() - 1;
2813 Font const lastfont =
2814 pit < 0 || pars[pit].empty()
2815 ? pars[pit].getLayoutFont(
2818 : pars[pit].getFont(bparams,
2819 pars[pit].size() - 1,
2821 if (lastfont.fontInfo().size() !=
2822 basefont.fontInfo().size()) {
2827 // We need to restore parts of this after insets with
2828 // allowMultiPar() true
2829 Font const save_basefont = basefont;
2830 d->latexInset(bparams, os, rp, running_font,
2831 basefont, real_outerfont, open_font,
2832 runningChange, style, i, column, fontswitch_inset,
2833 closeLanguage, lang_switched_at_inset);
2834 if (fontswitch_inset) {
2836 bool needPar = false;
2837 column += running_font.latexWriteEndChanges(
2838 os, bparams, runparams,
2839 basefont, basefont, needPar);
2842 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2843 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2844 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2849 if (runparams.ctObject == CtObject::DisplayObject
2850 || runparams.ctObject == CtObject::UDisplayObject) {
2851 // Close \lyx*deleted and force its
2852 // reopening (if needed)
2855 runningChange = Change(Change::UNCHANGED);
2856 runparams.ctObject = CtObject::Normal;
2859 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2860 if (!bparams.useNonTeXFonts)
2861 script = Encodings::isKnownScriptChar(c);
2862 if (script != alien_script) {
2863 if (!alien_script.empty()) {
2865 alien_script.clear();
2867 string fontenc = running_font.language()->fontenc(bparams);
2869 && !Encodings::fontencSupportsScript(fontenc, script)) {
2870 column += script.length() + 2;
2871 os << "\\" << script << "{";
2872 alien_script = script;
2876 d->latexSpecialChar(os, bparams, rp, running_font,
2877 alien_script, style, i, end_pos, column);
2878 } catch (EncodingException & e) {
2879 if (runparams.dryrun) {
2880 os << "<" << _("LyX Warning: ")
2881 << _("uncodable character") << " '";
2885 // add location information and throw again.
2893 // Set the encoding to that returned from latexSpecialChar (see
2894 // comment for encoding member in OutputParams.h)
2895 runparams.encoding = rp.encoding;
2897 // Also carry on the info on a closed ulem command for insets
2898 // such as Note that do not produce any output, so that no
2899 // command is ever executed but its opening was recorded.
2900 runparams.inulemcmd = rp.inulemcmd;
2902 // These need to be passed upstream as well
2903 runparams.need_maketitle = rp.need_maketitle;
2904 runparams.have_maketitle = rp.have_maketitle;
2906 // And finally, pass the post_macros upstream
2907 runparams.post_macro = rp.post_macro;
2910 // Close wrapper for alien script
2911 if (!alien_script.empty()) {
2913 alien_script.clear();
2916 Font const font = empty()
2917 ? getLayoutFont(bparams, real_outerfont)
2918 : getFont(bparams, size() - 1, real_outerfont);
2920 InsetText const * textinset = inInset().asInsetText();
2922 bool const maintext = textinset
2923 ? textinset->text().isMainText()
2926 size_t const numpars = textinset
2927 ? textinset->text().paragraphs().size()
2930 bool needPar = false;
2932 if (style.resfont.size() != font.fontInfo().size()
2933 && (!runparams.isLastPar || maintext
2934 || (numpars > 1 && d->ownerCode() != CELL_CODE
2935 && (inInset().getLayout().isDisplay()
2937 && !style.isCommand()) {
2941 // If we have an open font definition, we have to close it
2943 // Make sure that \\par is done with the font of the last
2944 // character if this has another size as the default.
2945 // This is necessary because LaTeX (and LyX on the screen)
2946 // calculates the space between the baselines according
2947 // to this font. (Matthias)
2949 // We must not change the font for the last paragraph
2950 // of non-multipar insets, tabular cells or commands,
2951 // since this produces unwanted whitespace.
2952 #ifdef FIXED_LANGUAGE_END_DETECTION
2954 running_font.latexWriteEndChanges(os, bparams,
2955 runparams, basefont,
2956 next_->getFont(bparams, 0, outerfont),
2959 running_font.latexWriteEndChanges(os, bparams,
2960 runparams, basefont, basefont, needPar);
2963 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2964 //FIXME: there as we start another \selectlanguage with the next paragraph if
2965 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2966 running_font.latexWriteEndChanges(os, bparams, runparams,
2967 basefont, basefont, needPar);
2971 // The \par could not be inserted at the same nesting
2972 // level of the font size change, so do it now.
2973 os << "{\\" << font.latexSize() << "\\par}";
2976 column += Changes::latexMarkChange(os, bparams, runningChange,
2977 Change(Change::UNCHANGED), runparams);
2979 // Needed if there is an optional argument but no contents.
2980 if (body_pos > 0 && body_pos == size()) {
2984 if (!style.rightdelim().empty()) {
2985 os << style.rightdelim();
2986 column += style.rightdelim().size();
2989 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2990 && runparams.encoding != prev_encoding) {
2991 runparams.encoding = prev_encoding;
2992 os << setEncoding(prev_encoding->iconvName());
2995 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2999 bool Paragraph::emptyTag() const
3001 for (pos_type i = 0; i < size(); ++i) {
3002 if (Inset const * inset = getInset(i)) {
3003 InsetCode lyx_code = inset->lyxCode();
3004 // FIXME testing like that is wrong. What is
3006 if (lyx_code != TOC_CODE &&
3007 lyx_code != INCLUDE_CODE &&
3008 lyx_code != GRAPHICS_CODE &&
3009 lyx_code != ERT_CODE &&
3010 lyx_code != LISTINGS_CODE &&
3011 lyx_code != FLOAT_CODE &&
3012 lyx_code != TABULAR_CODE) {
3016 char_type c = d->text_[i];
3017 if (c != ' ' && c != '\t')
3025 string Paragraph::getID(Buffer const &, OutputParams const &)
3028 for (pos_type i = 0; i < size(); ++i) {
3029 if (Inset const * inset = getInset(i)) {
3030 InsetCode lyx_code = inset->lyxCode();
3031 if (lyx_code == LABEL_CODE) {
3032 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3033 docstring const & id = il->getParam("name");
3034 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3042 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3045 for (i = 0; i < size(); ++i) {
3046 if (Inset const * inset = getInset(i)) {
3047 inset->docbook(xs, runparams);
3049 char_type c = d->text_[i];
3059 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3063 for (i = 0; i < size(); ++i) {
3064 if (Inset const * inset = getInset(i)) {
3065 inset->xhtml(xs, runparams);
3067 char_type c = d->text_[i];
3077 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3080 pos_type size = text_.size();
3081 for (pos_type i = initial; i < size; ++i) {
3082 Font font = owner_->getFont(buf.params(), i, outerfont);
3083 if (text_[i] == META_INSET)
3085 if (i != initial && font != font_old)
3096 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3097 vector<xml::EndFontTag> & tagsToClose,
3098 bool & flag, FontState curstate, xml::FontTypes type)
3100 if (curstate == FONT_ON) {
3101 tagsToOpen.push_back(docbookStartFontTag(type));
3104 tagsToClose.push_back(docbookEndFontTag(type));
3109 class OptionalFontType {
3114 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3115 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3118 OptionalFontType fontShapeToXml(FontShape fs)
3122 return {xml::FT_ITALIC};
3124 return {xml::FT_SLANTED};
3125 case SMALLCAPS_SHAPE:
3126 return {xml::FT_SMALLCAPS};
3131 // the other tags are for internal use
3137 OptionalFontType fontFamilyToXml(FontFamily fm)
3141 return {xml::FT_ROMAN};
3143 return {xml::FT_SANS};
3144 case TYPEWRITER_FAMILY:
3145 return {xml::FT_TYPE};
3146 case INHERIT_FAMILY:
3149 // the other tags are for internal use
3155 OptionalFontType fontSizeToXml(FontSize fs)
3159 return {xml::FT_SIZE_TINY};
3161 return {xml::FT_SIZE_SCRIPT};
3163 return {xml::FT_SIZE_FOOTNOTE};
3165 return {xml::FT_SIZE_SMALL};
3167 return {xml::FT_SIZE_LARGE};
3169 return {xml::FT_SIZE_LARGER};
3171 return {xml::FT_SIZE_LARGEST};
3173 return {xml::FT_SIZE_HUGE};
3175 return {xml::FT_SIZE_HUGER};
3177 return {xml::FT_SIZE_INCREASE};
3179 return {xml::FT_SIZE_DECREASE};
3184 // the other tags are for internal use
3190 struct DocBookFontState
3192 FontShape curr_fs = INHERIT_SHAPE;
3193 FontFamily curr_fam = INHERIT_FAMILY;
3194 FontSize curr_size = INHERIT_SIZE;
3196 // track whether we have opened these tags
3197 bool emph_flag = false;
3198 bool bold_flag = false;
3199 bool noun_flag = false;
3200 bool ubar_flag = false;
3201 bool dbar_flag = false;
3202 bool sout_flag = false;
3203 bool xout_flag = false;
3204 bool wave_flag = false;
3206 bool shap_flag = false;
3208 bool faml_flag = false;
3210 bool size_flag = false;
3213 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3215 std::string const & default_family,
3216 DocBookFontState & fs)
3218 vector<xml::FontTag> tagsToOpen;
3219 vector<xml::EndFontTag> tagsToClose;
3222 FontState curstate = font.fontInfo().emph();
3223 if (font_old.emph() != curstate)
3224 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3227 curstate = font.fontInfo().noun();
3228 if (font_old.noun() != curstate)
3229 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3232 curstate = font.fontInfo().underbar();
3233 if (font_old.underbar() != curstate)
3234 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3237 curstate = font.fontInfo().strikeout();
3238 if (font_old.strikeout() != curstate)
3239 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3242 curstate = font.fontInfo().xout();
3243 if (font_old.xout() != curstate)
3244 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3247 curstate = font.fontInfo().uuline();
3248 if (font_old.uuline() != curstate)
3249 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3252 curstate = font.fontInfo().uwave();
3253 if (font_old.uwave() != curstate)
3254 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3257 // a little hackish, but allows us to reuse what we have.
3258 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3259 if (font_old.series() != font.fontInfo().series())
3260 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3263 fs.curr_fs = font.fontInfo().shape();
3264 FontShape old_fs = font_old.shape();
3265 if (old_fs != fs.curr_fs) {
3267 OptionalFontType tag = fontShapeToXml(old_fs);
3269 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3270 fs.shap_flag = false;
3273 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3275 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3279 fs.curr_fam = font.fontInfo().family();
3280 FontFamily old_fam = font_old.family();
3281 if (old_fam != fs.curr_fam) {
3283 OptionalFontType tag = fontFamilyToXml(old_fam);
3285 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3286 fs.faml_flag = false;
3288 switch (fs.curr_fam) {
3290 // we will treat a "default" font family as roman, since we have
3291 // no other idea what to do.
3292 if (default_family != "rmdefault" && default_family != "default") {
3293 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3294 fs.faml_flag = true;
3298 if (default_family != "sfdefault") {
3299 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3300 fs.faml_flag = true;
3303 case TYPEWRITER_FAMILY:
3304 if (default_family != "ttdefault") {
3305 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3306 fs.faml_flag = true;
3309 case INHERIT_FAMILY:
3312 // the other tags are for internal use
3319 fs.curr_size = font.fontInfo().size();
3320 FontSize old_size = font_old.size();
3321 if (old_size != fs.curr_size) {
3323 OptionalFontType tag = fontSizeToXml(old_size);
3325 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3326 fs.size_flag = false;
3329 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3330 if (tag.has_value) {
3331 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3332 fs.size_flag = true;
3336 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3339 } // anonymous namespace
3342 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3343 OutputParams const & runparams,
3344 Font const & outerfont,
3347 bool ignore_fonts) const
3349 // Track whether we have opened these tags
3350 DocBookFontState fs;
3352 Layout const & style = *d->layout_;
3354 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3356 string const default_family =
3357 buf.masterBuffer()->params().fonts_default_family;
3359 vector<xml::FontTag> tagsToOpen;
3360 vector<xml::EndFontTag> tagsToClose;
3362 std::vector<docstring> generatedParagraphs;
3363 DocBookFontState old_fs = fs;
3364 odocstringstream os;
3365 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3366 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3368 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3369 // characters at some point.
3370 std::vector<char_type> delayedChars;
3372 // Parsing main loop.
3373 for (pos_type i = initial; i < size(); ++i) {
3374 // Don't show deleted material in the output.
3378 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3380 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3382 xs->closeFontTags();
3384 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3385 generatedParagraphs.push_back(os.str());
3387 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3388 // that the string stream must be reset.
3389 os.str(from_ascii(""));
3391 xs = new XMLStream(os);
3393 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3394 if (!ignore_fonts) {
3395 font_old = outerfont.fontInfo();
3400 // Determine which tags should be opened or closed regarding fonts.
3401 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3402 if (!ignore_fonts) {
3403 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3406 // Other such tags? What about the other text ranges?
3408 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3409 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3410 for (; cit != cen; ++cit)
3413 // Deal with the delayed characters *after* closing font tags.
3414 if (!delayedChars.empty()) {
3415 for (char_type c: delayedChars)
3417 delayedChars.clear();
3420 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3421 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3422 for (; sit != sen; ++sit)
3425 tagsToClose.clear();
3429 if (Inset const * inset = getInset(i)) {
3430 if (!runparams.for_toc || inset->isInToc()) {
3431 OutputParams np = runparams;
3432 np.local_font = &font;
3434 // TODO: special case will bite here.
3435 np.docbook_in_par = true;
3436 inset->docbook(*xs, np);
3439 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3440 if (lyx::isSpace(c) && !ignore_fonts)
3441 delayedChars.push_back(c);
3445 font_old = font.fontInfo();
3448 // FIXME, this code is just imported from XHTML
3449 // I'm worried about what happens if a branch, say, is itself
3450 // wrapped in some font stuff. I think that will not work.
3452 xs->closeFontTags();
3454 // Deal with the delayed characters *after* closing font tags.
3455 if (!delayedChars.empty())
3456 for (char_type c: delayedChars)
3459 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3460 // last line to get a clean output.
3461 if (runparams.docbook_in_listing && !is_last_par)
3464 // Finalise the last (and most likely only) paragraph.
3465 generatedParagraphs.push_back(os.str());
3468 return generatedParagraphs;
3474 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3475 vector<xml::EndFontTag> & tagsToClose,
3476 bool & flag, FontState curstate, xml::FontTypes type)
3478 if (curstate == FONT_ON) {
3479 tagsToOpen.push_back(xhtmlStartFontTag(type));
3482 tagsToClose.push_back(xhtmlEndFontTag(type));
3487 } // anonymous namespace
3490 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3492 OutputParams const & runparams,
3493 Font const & outerfont,
3494 bool start_paragraph, bool close_paragraph,
3495 pos_type initial) const
3499 // track whether we have opened these tags
3500 bool emph_flag = false;
3501 bool bold_flag = false;
3502 bool noun_flag = false;
3503 bool ubar_flag = false;
3504 bool dbar_flag = false;
3505 bool sout_flag = false;
3506 bool xout_flag = false;
3507 bool wave_flag = false;
3509 bool shap_flag = false;
3511 bool faml_flag = false;
3513 bool size_flag = false;
3515 Layout const & style = *d->layout_;
3517 if (start_paragraph)
3518 xs.startDivision(allowEmpty());
3521 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3523 FontShape curr_fs = INHERIT_SHAPE;
3524 FontFamily curr_fam = INHERIT_FAMILY;
3525 FontSize curr_size = INHERIT_SIZE;
3527 string const default_family =
3528 buf.masterBuffer()->params().fonts_default_family;
3530 vector<xml::FontTag> tagsToOpen;
3531 vector<xml::EndFontTag> tagsToClose;
3533 // parsing main loop
3534 for (pos_type i = initial; i < size(); ++i) {
3535 // let's not show deleted material in the output
3539 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3542 FontState curstate = font.fontInfo().emph();
3543 if (font_old.emph() != curstate)
3544 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3547 curstate = font.fontInfo().noun();
3548 if (font_old.noun() != curstate)
3549 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3552 curstate = font.fontInfo().underbar();
3553 if (font_old.underbar() != curstate)
3554 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3557 curstate = font.fontInfo().strikeout();
3558 if (font_old.strikeout() != curstate)
3559 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3562 curstate = font.fontInfo().xout();
3563 if (font_old.xout() != curstate)
3564 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3567 curstate = font.fontInfo().uuline();
3568 if (font_old.uuline() != curstate)
3569 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3572 curstate = font.fontInfo().uwave();
3573 if (font_old.uwave() != curstate)
3574 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3577 // a little hackish, but allows us to reuse what we have.
3578 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3579 if (font_old.series() != font.fontInfo().series())
3580 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3583 curr_fs = font.fontInfo().shape();
3584 FontShape old_fs = font_old.shape();
3585 if (old_fs != curr_fs) {
3589 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3592 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3594 case SMALLCAPS_SHAPE:
3595 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3601 // the other tags are for internal use
3609 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3613 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3616 case SMALLCAPS_SHAPE:
3617 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3624 // the other tags are for internal use
3631 curr_fam = font.fontInfo().family();
3632 FontFamily old_fam = font_old.family();
3633 if (old_fam != curr_fam) {
3637 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3640 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3642 case TYPEWRITER_FAMILY:
3643 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3645 case INHERIT_FAMILY:
3648 // the other tags are for internal use
3656 // we will treat a "default" font family as roman, since we have
3657 // no other idea what to do.
3658 if (default_family != "rmdefault" && default_family != "default") {
3659 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3664 if (default_family != "sfdefault") {
3665 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3669 case TYPEWRITER_FAMILY:
3670 if (default_family != "ttdefault") {
3671 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3675 case INHERIT_FAMILY:
3678 // the other tags are for internal use
3685 curr_size = font.fontInfo().size();
3686 FontSize old_size = font_old.size();
3687 if (old_size != curr_size) {
3691 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3694 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3697 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3700 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3703 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3706 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3709 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3712 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3715 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3718 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3721 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3727 // the other tags are for internal use
3733 switch (curr_size) {
3735 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3739 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3743 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3747 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3751 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3755 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3759 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3763 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3767 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3771 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3775 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3782 // the other tags are for internal use
3789 // Other such tags? What about the other text ranges?
3791 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3792 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3793 for (; cit != cen; ++cit)
3796 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3797 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3798 for (; sit != sen; ++sit)
3801 tagsToClose.clear();
3804 Inset const * inset = getInset(i);
3806 if (!runparams.for_toc || inset->isInToc()) {
3807 OutputParams np = runparams;
3808 np.local_font = &font;
3809 // If the paragraph has size 1, then we are in the "special
3810 // case" where we do not output the containing paragraph info
3811 if (!inset->getLayout().htmlisblock() && size() != 1)
3812 np.html_in_par = true;
3813 retval += inset->xhtml(xs, np);
3816 char_type c = getUChar(buf.masterBuffer()->params(),
3818 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3819 xs << XMLStream::ESCAPE_NONE << " ";
3823 font_old = font.fontInfo();
3827 // I'm worried about what happens if a branch, say, is itself
3828 // wrapped in some font stuff. I think that will not work.
3830 if (close_paragraph)
3837 bool Paragraph::isHfill(pos_type pos) const
3839 Inset const * inset = getInset(pos);
3840 return inset && inset->isHfill();
3844 bool Paragraph::isNewline(pos_type pos) const
3846 // U+2028 LINE SEPARATOR
3847 // U+2029 PARAGRAPH SEPARATOR
3848 char_type const c = d->text_[pos];
3849 if (c == 0x2028 || c == 0x2029)
3851 Inset const * inset = getInset(pos);
3852 return inset && inset->lyxCode() == NEWLINE_CODE;
3856 bool Paragraph::isEnvSeparator(pos_type pos) const
3858 Inset const * inset = getInset(pos);
3859 return inset && inset->lyxCode() == SEPARATOR_CODE;
3863 bool Paragraph::isLineSeparator(pos_type pos) const
3865 char_type const c = d->text_[pos];
3866 if (isLineSeparatorChar(c))
3868 Inset const * inset = getInset(pos);
3869 return inset && inset->isLineSeparator();
3873 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3877 if (ignore_deleted && isDeleted(pos))
3879 if (Inset const * inset = getInset(pos))
3880 return !inset->isLetter();
3881 // if we have a hard hyphen (no en- or emdash) or apostrophe
3882 // we pass this to the spell checker
3883 // FIXME: this method is subject to change, visit
3884 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3885 // to get an impression how complex this is.
3886 if (isHardHyphenOrApostrophe(pos))
3888 char_type const c = d->text_[pos];
3889 // We want to pass the escape chars to the spellchecker
3890 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3891 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3895 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3897 pos_type const psize = size();
3900 char_type const c = d->text_[pos];
3901 if (c != '-' && c != '\'')
3903 pos_type nextpos = pos + 1;
3904 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3905 if ((nextpos == psize || isSpace(nextpos))
3906 && (pos == 0 || isSpace(prevpos)))
3912 bool Paragraph::needsCProtection(bool const fragile) const
3914 // first check the layout of the paragraph, but only in insets
3915 InsetText const * textinset = inInset().asInsetText();
3916 bool const maintext = textinset
3917 ? textinset->text().isMainText()
3920 if (!maintext && layout().needcprotect) {
3921 // Environments need cprotection regardless the content
3922 if (layout().latextype == LATEX_ENVIRONMENT)
3925 // Commands need cprotection if they contain specific chars
3926 int const nchars_escape = 9;
3927 static char_type const chars_escape[nchars_escape] = {
3928 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3930 docstring const pars = asString();
3931 for (int k = 0; k < nchars_escape; k++) {
3932 if (contains(pars, chars_escape[k]))
3937 // now check whether we have insets that need cprotection
3938 pos_type size = pos_type(d->text_.size());
3939 for (pos_type i = 0; i < size; ++i) {
3942 Inset const * ins = getInset(i);
3943 if (ins->needsCProtection(maintext, fragile))
3945 // Now check math environments
3946 InsetMath const * im = getInset(i)->asInsetMath();
3947 if (!im || im->cell(0).empty())
3949 switch(im->cell(0)[0]->lyxCode()) {
3950 case MATH_AMSARRAY_CODE:
3951 case MATH_SUBSTACK_CODE:
3953 case MATH_XYMATRIX_CODE:
3954 // these need cprotection
3965 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3967 return d->speller_state_.getRange(pos);
3971 bool Paragraph::isChar(pos_type pos) const
3973 if (Inset const * inset = getInset(pos))
3974 return inset->isChar();
3975 char_type const c = d->text_[pos];
3976 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3980 bool Paragraph::isSpace(pos_type pos) const
3982 if (Inset const * inset = getInset(pos))
3983 return inset->isSpace();
3984 char_type const c = d->text_[pos];
3985 return lyx::isSpace(c);
3990 Paragraph::getParLanguage(BufferParams const & bparams) const
3993 return getFirstFontSettings(bparams).language();
3994 // FIXME: we should check the prev par as well (Lgb)
3995 return bparams.language;
3999 bool Paragraph::isRTL(BufferParams const & bparams) const
4001 return getParLanguage(bparams)->rightToLeft()
4002 && !inInset().getLayout().forceLTR();
4006 void Paragraph::changeLanguage(BufferParams const & bparams,
4007 Language const * from, Language const * to)
4009 // change language including dummy font change at the end
4010 for (pos_type i = 0; i <= size(); ++i) {
4011 Font font = getFontSettings(bparams, i);
4012 if (font.language() == from) {
4013 font.setLanguage(to);
4015 d->requestSpellCheck(i);
4021 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4023 Language const * doc_language = bparams.language;
4024 for (auto const & f : d->fontlist_)
4025 if (f.font().language() != ignore_language &&
4026 f.font().language() != latex_language &&
4027 f.font().language() != doc_language)
4033 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4035 for (auto const & f : d->fontlist_) {
4036 Language const * lang = f.font().language();
4037 if (lang != ignore_language &&
4038 lang != latex_language)
4044 docstring Paragraph::asString(int options) const
4046 return asString(0, size(), options);
4050 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4052 odocstringstream os;
4055 && options & AS_STR_LABEL
4056 && !d->params_.labelString().empty())
4057 os << d->params_.labelString() << ' ';
4059 for (pos_type i = beg; i < end; ++i) {
4060 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4062 char_type const c = d->text_[i];
4063 if (isPrintable(c) || c == '\t'
4064 || (c == '\n' && (options & AS_STR_NEWLINES)))
4066 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4067 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4068 LASSERT(runparams != nullptr, return docstring());
4069 getInset(i)->plaintext(os, *runparams);
4071 getInset(i)->toString(os);
4080 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4081 bool const shorten, bool const label) const
4083 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4084 if (label && !labelString().empty())
4085 os += labelString() + ' ';
4086 if (!layout().isTocCaption())
4088 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4091 char_type const c = d->text_[i];
4094 else if (c == META_INSET)
4095 getInset(i)->forOutliner(os, tmplen, false);
4098 Text::shortenForOutliner(os, maxlen);
4102 void Paragraph::setInsetOwner(Inset const * inset)
4104 d->inset_owner_ = inset;
4108 int Paragraph::id() const
4114 void Paragraph::setId(int id)
4120 Layout const & Paragraph::layout() const
4126 void Paragraph::setLayout(Layout const & layout)
4128 d->layout_ = &layout;
4132 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4134 setLayout(tc.defaultLayout());
4138 void Paragraph::setPlainLayout(DocumentClass const & tc)
4140 setLayout(tc.plainLayout());
4144 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4146 if (usePlainLayout())
4149 setDefaultLayout(tc);
4153 Inset const & Paragraph::inInset() const
4155 LBUFERR(d->inset_owner_);
4156 return *d->inset_owner_;
4160 ParagraphParameters & Paragraph::params()
4166 ParagraphParameters const & Paragraph::params() const
4172 bool Paragraph::isFreeSpacing() const
4174 if (d->layout_->free_spacing)
4176 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4180 bool Paragraph::allowEmpty() const
4182 if (d->layout_->keepempty)
4184 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4188 bool Paragraph::brokenBiblio() const
4190 // There is a problem if there is no bibitem at position 0 in
4191 // paragraphs that need one, if there is another bibitem in the
4192 // paragraph or if this paragraph is not supposed to have
4193 // a bibitem inset at all.
4194 return ((d->layout_->labeltype == LABEL_BIBLIO
4195 && (d->insetlist_.find(BIBITEM_CODE) != 0
4196 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4197 || (d->layout_->labeltype != LABEL_BIBLIO
4198 && d->insetlist_.find(BIBITEM_CODE) != -1));
4202 int Paragraph::fixBiblio(Buffer const & buffer)
4204 // FIXME: when there was already an inset at 0, the return value is 1,
4205 // which does not tell whether another inset has been removed; the
4206 // cursor cannot be correctly updated.
4208 bool const track_changes = buffer.params().track_changes;
4209 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4211 // The case where paragraph is not BIBLIO
4212 if (d->layout_->labeltype != LABEL_BIBLIO) {
4213 if (bibitem_pos == -1)
4214 // No InsetBibitem => OK
4216 // There is an InsetBibitem: remove it!
4217 d->insetlist_.release(bibitem_pos);
4218 eraseChar(bibitem_pos, track_changes);
4219 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4222 bool const hasbibitem0 = bibitem_pos == 0;
4224 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4225 // There was an InsetBibitem at pos 0,
4226 // and no other one => OK
4227 if (bibitem_pos == -1)
4229 // there is a bibitem at the 0 position, but since
4230 // there is a second one, we copy the second on the
4231 // first. We're assuming there are at most two of
4232 // these, which there should be.
4233 // FIXME: why does it make sense to do that rather
4234 // than keep the first? (JMarc)
4235 Inset * inset = releaseInset(bibitem_pos);
4236 d->insetlist_.begin()->inset = inset;
4237 // This needs to be done to update the counter (#8499)
4238 buffer.updateBuffer();
4239 return -bibitem_pos;
4242 // We need to create an inset at the beginning
4243 Inset * inset = nullptr;
4244 if (bibitem_pos > 0) {
4245 // there was one somewhere in the paragraph, let's move it
4246 inset = d->insetlist_.release(bibitem_pos);
4247 eraseChar(bibitem_pos, track_changes);
4250 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4251 InsetCommandParams(BIBITEM_CODE));
4253 Font font(inherit_font, buffer.params().language);
4254 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4255 : Change::UNCHANGED));
4257 // This is needed to get the counters right
4258 buffer.updateBuffer();
4263 void Paragraph::checkAuthors(AuthorList const & authorList)
4265 d->changes_.checkAuthors(authorList);
4269 bool Paragraph::isChanged(pos_type pos) const
4271 return lookupChange(pos).changed();
4275 bool Paragraph::isInserted(pos_type pos) const
4277 return lookupChange(pos).inserted();
4281 bool Paragraph::isDeleted(pos_type pos) const
4283 return lookupChange(pos).deleted();
4287 InsetList const & Paragraph::insetList() const
4289 return d->insetlist_;
4293 void Paragraph::setInsetBuffers(Buffer & b)
4295 d->insetlist_.setBuffer(b);
4299 void Paragraph::resetBuffer()
4301 d->insetlist_.resetBuffer();
4305 Inset * Paragraph::releaseInset(pos_type pos)
4307 Inset * inset = d->insetlist_.release(pos);
4308 /// does not honour change tracking!
4309 eraseChar(pos, false);
4314 Inset * Paragraph::getInset(pos_type pos)
4316 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4317 ? d->insetlist_.get(pos) : nullptr;
4321 Inset const * Paragraph::getInset(pos_type pos) const
4323 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4324 ? d->insetlist_.get(pos) : nullptr;
4328 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4329 pos_type & right, TextCase action)
4331 // process sequences of modified characters; in change
4332 // tracking mode, this approach results in much better
4333 // usability than changing case on a char-by-char basis
4334 // We also need to track the current font, since font
4335 // changes within sequences can occur.
4336 vector<pair<char_type, Font> > changes;
4338 bool const trackChanges = bparams.track_changes;
4340 bool capitalize = true;
4342 for (; pos < right; ++pos) {
4343 char_type oldChar = d->text_[pos];
4344 char_type newChar = oldChar;
4346 // ignore insets and don't play with deleted text!
4347 if (oldChar != META_INSET && !isDeleted(pos)) {
4349 case text_lowercase:
4350 newChar = lowercase(oldChar);
4352 case text_capitalization:
4354 newChar = uppercase(oldChar);
4358 case text_uppercase:
4359 newChar = uppercase(oldChar);
4364 if (isWordSeparator(pos) || isDeleted(pos)) {
4365 // permit capitalization again
4369 if (oldChar != newChar) {
4370 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4371 if (pos != right - 1)
4373 // step behind the changing area
4377 int erasePos = pos - changes.size();
4378 for (auto const & change : changes) {
4379 insertChar(pos, change.first, change.second, trackChanges);
4380 if (!eraseChar(erasePos, trackChanges)) {
4383 ++right; // expand selection
4391 int Paragraph::find(docstring const & str, bool cs, bool mw,
4392 pos_type start_pos, bool del) const
4394 pos_type pos = start_pos;
4395 int const strsize = str.length();
4397 pos_type const parsize = d->text_.size();
4398 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4399 // ignore deleted matter
4400 if (!del && isDeleted(pos)) {
4401 if (pos == parsize - 1)
4407 // Ignore "invisible" letters such as ligature breaks
4408 // and hyphenation chars while searching
4409 bool nonmatch = false;
4410 while (pos < parsize && isInset(pos)) {
4411 Inset const * inset = getInset(pos);
4412 if (!inset->isLetter() && !inset->isChar())
4414 odocstringstream os;
4415 inset->toString(os);
4416 if (!os.str().empty()) {
4417 int const insetstringsize = os.str().length();
4418 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4419 if (str[i] != os.str()[j]) {
4427 if (nonmatch || i == strsize)
4429 if (cs && str[i] != d->text_[pos])
4431 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4438 // if necessary, check whether string matches word
4440 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4443 && !isWordSeparator(pos))
4447 return pos - start_pos;
4451 char_type Paragraph::getChar(pos_type pos) const
4453 return d->text_[pos];
4457 pos_type Paragraph::size() const
4459 return d->text_.size();
4463 bool Paragraph::empty() const
4465 return d->text_.empty();
4469 bool Paragraph::isInset(pos_type pos) const
4471 return d->text_[pos] == META_INSET;
4475 bool Paragraph::isSeparator(pos_type pos) const
4477 //FIXME: Are we sure this can be the only separator?
4478 return d->text_[pos] == ' ';
4482 void Paragraph::deregisterWords()
4484 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4485 Private::LangWordsMap::const_iterator ite = d->words_.end();
4486 for (; itl != ite; ++itl) {
4487 WordList & wl = theWordList(itl->first);
4488 Private::Words::const_iterator it = (itl->second).begin();
4489 Private::Words::const_iterator et = (itl->second).end();
4490 for (; it != et; ++it)
4497 void Paragraph::locateWord(pos_type & from, pos_type & to,
4498 word_location const loc, bool const ignore_deleted) const
4501 case WHOLE_WORD_STRICT:
4502 if (from == 0 || from == size()
4503 || isWordSeparator(from, ignore_deleted)
4504 || isWordSeparator(from - 1, ignore_deleted)) {
4511 // If we are already at the beginning of a word, do nothing
4512 if (!from || isWordSeparator(from - 1, ignore_deleted))
4517 // always move the cursor to the beginning of previous word
4518 while (from && !isWordSeparator(from - 1, ignore_deleted))
4522 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4525 // no need to move the 'from' cursor
4529 while (to < size() && !isWordSeparator(to, ignore_deleted))
4534 void Paragraph::collectWords()
4536 for (pos_type pos = 0; pos < size(); ++pos) {
4537 if (isWordSeparator(pos))
4539 pos_type from = pos;
4540 locateWord(from, pos, WHOLE_WORD);
4541 // Work around MSVC warning: The statement
4542 // if (pos < from + lyxrc.completion_minlength)
4543 // triggers a signed vs. unsigned warning.
4544 // I don't know why this happens, it could be a MSVC bug, or
4545 // related to LLP64 (windows) vs. LP64 (unix) programming
4546 // model, or the C++ standard might be ambigous in the section
4547 // defining the "usual arithmetic conversions". However, using
4548 // a temporary variable is safe and works on all compilers.
4549 pos_type const endpos = from + lyxrc.completion_minlength;
4552 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4553 if (cit == d->fontlist_.end())
4555 Language const * lang = cit->font().language();
4556 docstring const word = asString(from, pos, AS_STR_NONE);
4557 d->words_[lang->lang()].insert(word);
4562 void Paragraph::registerWords()
4564 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4565 Private::LangWordsMap::const_iterator ite = d->words_.end();
4566 for (; itl != ite; ++itl) {
4567 WordList & wl = theWordList(itl->first);
4568 Private::Words::const_iterator it = (itl->second).begin();
4569 Private::Words::const_iterator et = (itl->second).end();
4570 for (; it != et; ++it)
4576 void Paragraph::updateWords()
4584 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4586 SkipPositionsIterator begin = skips.begin();
4587 SkipPositions::iterator end = skips.end();
4588 if (pos > 0 && begin < end) {
4590 if (end->last == pos - 1) {
4595 skips.insert(end, FontSpan(pos, pos));
4599 Language * Paragraph::Private::locateSpellRange(
4600 pos_type & from, pos_type & to,
4601 SkipPositions & skips) const
4603 // skip leading white space
4604 while (from < to && owner_->isWordSeparator(from))
4606 // don't check empty range
4609 // get current language
4610 Language * lang = getSpellLanguage(from);
4611 pos_type last = from;
4612 bool samelang = true;
4613 bool sameinset = true;
4614 while (last < to && samelang && sameinset) {
4615 // hop to end of word
4616 while (last < to && !owner_->isWordSeparator(last)) {
4617 Inset const * inset = owner_->getInset(last);
4618 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4619 // check for "invisible" letters such as ligature breaks
4620 odocstringstream os;
4621 inset->toString(os);
4622 if (os.str().length() != 0) {
4623 // avoid spell check of visible special char insets
4624 // stop the loop in front of the special char inset
4629 appendSkipPosition(skips, last);
4630 } else if (owner_->isDeleted(last)) {
4631 appendSkipPosition(skips, last);
4635 // hop to next word while checking for insets
4636 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4637 if (Inset const * inset = owner_->getInset(last))
4638 sameinset = inset->isChar() && inset->isLetter();
4639 if (sameinset && owner_->isDeleted(last)) {
4640 appendSkipPosition(skips, last);
4645 if (sameinset && last < to) {
4646 // now check for language change
4647 samelang = lang == getSpellLanguage(last);
4650 // if language change detected backstep is needed
4658 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4661 const_cast<Language *>(owner_->getFontSettings(
4662 inset_owner_->buffer().params(), from).language());
4663 if (lang == inset_owner_->buffer().params().language
4664 && !lyxrc.spellchecker_alt_lang.empty()) {
4666 string const lang_variety =
4667 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4668 lang->setCode(lang_code);
4669 lang->setVariety(lang_variety);
4675 void Paragraph::requestSpellCheck(pos_type pos)
4677 d->requestSpellCheck(pos);
4681 bool Paragraph::needsSpellCheck() const
4683 SpellChecker::ChangeNumber speller_change_number = 0;
4684 if (theSpellChecker())
4685 speller_change_number = theSpellChecker()->changeNumber();
4686 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4687 d->speller_state_.needsCompleteRefresh(speller_change_number);
4689 return d->needsSpellCheck();
4693 bool Paragraph::Private::ignoreWord(docstring const & word) const
4695 // Ignore words with digits
4696 // FIXME: make this customizable
4697 // (note that some checkers ignore words with digits by default)
4698 docstring::const_iterator cit = word.begin();
4699 docstring::const_iterator const end = word.end();
4700 for (; cit != end; ++cit) {
4701 if (isNumber((*cit)))
4708 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4709 WordLangTuple & wl, docstring_list & suggestions,
4710 bool do_suggestion, bool check_learned) const
4712 SpellChecker::Result result = SpellChecker::WORD_OK;
4713 SpellChecker * speller = theSpellChecker();
4717 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4720 locateWord(from, to, WHOLE_WORD, true);
4721 if (from == to || from >= size())
4724 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4725 Language * lang = d->getSpellLanguage(from);
4727 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4730 wl = WordLangTuple(word, lang);
4735 if (needsSpellCheck() || check_learned) {
4737 if (!d->ignoreWord(word)) {
4738 bool const trailing_dot = to < size() && d->text_[to] == '.';
4739 result = speller->check(wl);
4740 if (SpellChecker::misspelled(result) && trailing_dot) {
4741 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4742 result = speller->check(wl);
4743 if (!SpellChecker::misspelled(result)) {
4744 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4746 from << ".." << to << "]");
4748 // spell check with dot appended failed too
4749 // restore original word/lang value
4750 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4751 wl = WordLangTuple(word, lang);
4755 if (!SpellChecker::misspelled(result)) {
4756 // area up to the begin of the next word is not misspelled
4757 while (end < size() && isWordSeparator(end))
4760 d->setMisspelled(from, end, result);
4762 result = d->speller_state_.getState(from);
4766 suggestions.clear();
4768 if (SpellChecker::misspelled(result)) {
4769 LYXERR(Debug::GUI, "misspelled word: \"" <<
4771 from << ".." << to << "]");
4773 speller->suggest(wl, suggestions);
4779 void Paragraph::anonymize()
4781 // This is a very crude anonymization for now
4782 for (char_type & c : d->text_)
4783 if (isLetterChar(c) || isNumber(c))
4788 void Paragraph::Private::markMisspelledWords(
4789 pos_type const & first, pos_type const & last,
4790 SpellChecker::Result result,
4791 docstring const & word,
4792 SkipPositions const & skips)
4794 if (!SpellChecker::misspelled(result)) {
4795 setMisspelled(first, last, SpellChecker::WORD_OK);
4799 SpellChecker * speller = theSpellChecker();
4800 // locate and enumerate the error positions
4801 int nerrors = speller->numMisspelledWords();
4803 SkipPositionsIterator it = skips.begin();
4804 SkipPositionsIterator et = skips.end();
4805 for (int index = 0; index < nerrors; ++index) {
4808 speller->misspelledWord(index, wstart, wlen);
4809 /// should not happen if speller supports range checks
4810 if (!wlen) continue;
4811 docstring const misspelled = word.substr(wstart, wlen);
4812 wstart += first + numskipped;
4813 if (snext < wstart) {
4814 /// mark the range of correct spelling
4815 numskipped += countSkips(it, et, wstart);
4816 setMisspelled(snext,
4817 wstart - 1, SpellChecker::WORD_OK);
4819 snext = wstart + wlen;
4820 numskipped += countSkips(it, et, snext);
4821 /// mark the range of misspelling
4822 setMisspelled(wstart, snext, result);
4823 LYXERR(Debug::GUI, "misspelled word: \"" <<
4824 misspelled << "\" [" <<
4825 wstart << ".." << (snext-1) << "]");
4828 if (snext <= last) {
4829 /// mark the range of correct spelling at end
4830 setMisspelled(snext, last, SpellChecker::WORD_OK);
4835 void Paragraph::spellCheck() const
4837 SpellChecker * speller = theSpellChecker();
4838 if (!speller || empty() ||!needsSpellCheck())
4842 d->rangeOfSpellCheck(start, endpos);
4843 if (speller->canCheckParagraph()) {
4844 // loop until we leave the range
4845 for (pos_type first = start; first < endpos; ) {
4846 pos_type last = endpos;
4847 Private::SkipPositions skips;
4848 Language * lang = d->locateSpellRange(first, last, skips);
4849 if (first >= endpos)
4851 // start the spell checker on the unit of meaning
4852 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4853 WordLangTuple wl = WordLangTuple(word, lang);
4854 SpellChecker::Result result = !word.empty() ?
4855 speller->check(wl) : SpellChecker::WORD_OK;
4856 d->markMisspelledWords(first, last, result, word, skips);
4860 static docstring_list suggestions;
4861 pos_type to = endpos;
4862 while (start < endpos) {
4864 spellCheck(start, to, wl, suggestions, false);
4868 d->readySpellCheck();
4872 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4874 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4875 if (result || pos <= 0 || pos > size())
4877 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4878 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4883 string Paragraph::magicLabel() const
4886 ss << "magicparlabel-" << id();