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 ((c == '\\') && runparams.for_search)
1137 else if (c != '\0') {
1138 Encoding const * const enc = runparams.encoding;
1139 if (enc && !enc->encodable(c))
1140 throw EncodingException(c);
1146 // TIPA uses its own T3 encoding
1147 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1149 // If T1 font encoding is used, use the special
1150 // characters it provides.
1151 // NOTE: Some languages reset the font encoding internally to a
1152 // non-standard font encoding. If we are using such a language,
1153 // we do not output special T1 chars.
1154 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1155 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1156 && latexSpecialT1(c, os, i, column))
1158 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1159 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1160 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1163 // Otherwise, we use what LaTeX provides us.
1166 os << "\\textbackslash" << termcmd;
1170 os << "\\textless" << termcmd;
1174 os << "\\textgreater" << termcmd;
1178 os << "\\textbar" << termcmd;
1183 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1184 (end_pos == -1 || i + 1 < end_pos) &&
1185 text_[i+1] == '-') {
1186 // Prevent "--" becoming an en dash and "---" an em dash.
1187 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1193 os << "\\textquotedbl" << termcmd;
1198 case '%': case '#': case '{':
1206 os << "\\textasciitilde" << termcmd;
1211 os << "\\textasciicircum" << termcmd;
1218 // avoid being mistaken for optional arguments
1226 // Blanks are printed before font switching.
1227 // Sure? I am not! (try nice-latex)
1228 // I am sure it's correct. LyX might be smarter
1229 // in the future, but for now, nothing wrong is
1235 // XeTeX's dash behaviour is determined via a global setting
1236 if (bparams.use_dash_ligatures
1237 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1239 // TODO #10961: && not in inset Flex Code
1240 // TODO #10961: && not in layout LyXCode
1241 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1258 Encoding const & encoding = *(runparams.encoding);
1259 char_type next = '\0';
1260 if (i + 1 < int(text_.size())) {
1261 next = text_[i + 1];
1262 if (Encodings::isCombiningChar(next)) {
1263 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1268 pair<docstring, bool> latex = encoding.latexChar(c);
1269 docstring nextlatex;
1270 bool nexttipas = false;
1271 string nexttipashortcut;
1272 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1273 nextlatex = encoding.latexChar(next).first;
1274 if (runparams.inIPA) {
1275 nexttipashortcut = Encodings::TIPAShortcut(next);
1276 nexttipas = !nexttipashortcut.empty();
1280 if (runparams.inIPA) {
1281 string const tipashortcut = Encodings::TIPAShortcut(c);
1282 if (!tipashortcut.empty()) {
1283 latex.first = from_ascii(tipashortcut);
1284 latex.second = false;
1288 // eventually close "script wrapper" command (see `Paragraph::latex`)
1289 if (!alien_script.empty()
1290 && alien_script != Encodings::isKnownScriptChar(next)) {
1291 column += latex.first.length();
1292 alien_script.clear();
1293 os << latex.first << "}";
1297 && ((!prefixIs(nextlatex, '\\')
1298 && !prefixIs(nextlatex, '{')
1299 && !prefixIs(nextlatex, '}'))
1301 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1303 // Prevent eating of a following space or command corruption by
1304 // following characters
1305 if (next == ' ' || next == '\0') {
1306 column += latex.first.length() + 1;
1307 os << latex.first << "{}";
1309 column += latex.first.length();
1310 os << latex.first << " ";
1313 column += latex.first.length() - 1;
1321 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1322 pos_type i, unsigned int & column) const
1328 // In T1 encoding, these characters exist
1329 // but we should avoid ligatures
1330 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1332 os << "\\textcompwordmark" << termcmd;
1339 // soul.sty breaks with \char`\"
1340 os << "\\textquotedbl" << termcmd;
1349 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1350 pos_type i, unsigned int & column) const
1352 // TU encoding is currently on par with T1.
1353 return latexSpecialT1(c, os, i, column);
1357 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1358 pos_type /*i*/, unsigned int & column) const
1368 os << "\\textvertline" << termcmd;
1377 void Paragraph::Private::validate(LaTeXFeatures & features) const
1379 if (layout_->inpreamble && inset_owner_) {
1380 // FIXME: Using a string stream here circumvents the encoding
1381 // switching machinery of odocstream. Therefore the
1382 // output is wrong if this paragraph contains content
1383 // that needs to switch encoding.
1384 Buffer const & buf = inset_owner_->buffer();
1385 otexstringstream os;
1386 os << layout_->preamble();
1387 size_t const length = os.length();
1388 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1389 buf.getParFromID(owner_->id()).pit(), os,
1390 features.runparams(), string(), 0, -1, true);
1391 if (os.length() > length)
1392 features.addPreambleSnippet(os.release(), true);
1395 if (features.runparams().flavor == Flavor::Html
1396 && layout_->htmltitle()) {
1397 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1400 // check the params.
1401 if (!params_.spacing().isDefault())
1402 features.require("setspace");
1405 features.useLayout(layout_->name());
1408 fontlist_.validate(features);
1410 // then the indentation
1411 if (!params_.leftIndent().zero())
1412 features.require("ParagraphLeftIndent");
1415 InsetList::const_iterator icit = insetlist_.begin();
1416 InsetList::const_iterator iend = insetlist_.end();
1417 for (; icit != iend; ++icit) {
1419 features.inDeletedInset(owner_->isDeleted(icit->pos));
1420 if (icit->inset->lyxCode() == FOOT_CODE) {
1421 // FIXME: an item inset would make things much easier.
1422 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1423 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1424 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1425 && (icit->pos < begin_of_body_
1426 || (icit->pos == begin_of_body_
1427 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1428 features.saveNoteEnv("description");
1430 icit->inset->validate(features);
1431 features.inDeletedInset(false);
1432 if (layout_->needprotect &&
1433 icit->inset->lyxCode() == FOOT_CODE)
1434 features.require("NeedLyXFootnoteCode");
1438 // then the contents
1439 BufferParams const bp = features.runparams().is_child
1440 ? features.buffer().masterParams() : features.buffer().params();
1441 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1442 char_type c = text_[i];
1443 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1445 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1446 features.require("textquotedblp");
1447 else if (bp.main_font_encoding() != "T1"
1448 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1449 features.require("textquotedbl");
1450 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1451 // features that depend on the font or input encoding
1452 string feats = ci.textpreamble();
1453 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1454 if (fontenc.empty())
1455 fontenc = features.runparams().main_fontenc;
1456 while (!feats.empty()) {
1458 feats = split(feats, feat, ',');
1459 if (contains(feat, "!=")) {
1460 // a feature that is required except for the spcified
1461 // font or input encodings
1463 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1464 // multiple encodings are separated by semicolon
1465 vector<string> context = getVectorFromString(contexts, ";");
1466 // require feature if the context matches neither current font
1467 // nor input encoding
1468 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1469 && std::find(context.begin(), context.end(),
1470 features.runparams().encoding->name()) == context.end())
1471 features.require(realfeature);
1472 } else if (contains(feat, '=')) {
1473 // a feature that is required only for the spcified
1474 // font or input encodings
1476 string const contexts = split(feat, realfeature, '=');
1477 // multiple encodings are separated by semicolon
1478 vector<string> context = getVectorFromString(contexts, ";");
1479 // require feature if the context matches either current font
1480 // or input encoding
1481 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1482 || std::find(context.begin(), context.end(),
1483 features.runparams().encoding->name()) != context.end())
1484 features.require(realfeature);
1487 } else if (!bp.use_dash_ligatures
1488 && (c == 0x2013 || c == 0x2014)
1489 && bp.useNonTeXFonts
1490 && features.runparams().flavor == Flavor::XeTeX)
1491 // XeTeX's dash behaviour is determined via a global setting
1492 features.require("xetexdashbreakstate");
1493 BufferEncodings::validate(c, features);
1497 /////////////////////////////////////////////////////////////////////
1501 /////////////////////////////////////////////////////////////////////
1504 Layout const emptyParagraphLayout;
1507 Paragraph::Paragraph()
1508 : d(new Paragraph::Private(this, emptyParagraphLayout))
1515 Paragraph::Paragraph(Paragraph const & par)
1516 : itemdepth(par.itemdepth),
1517 d(new Paragraph::Private(*par.d, this))
1523 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1524 : itemdepth(par.itemdepth),
1525 d(new Paragraph::Private(*par.d, this, beg, end))
1531 Paragraph & Paragraph::operator=(Paragraph const & par)
1533 // needed as we will destroy the private part before copying it
1535 itemdepth = par.itemdepth;
1539 d = new Private(*par.d, this);
1546 Paragraph::~Paragraph()
1555 // this shall be called just before every "os << ..." action.
1556 void flushString(ostream & os, docstring & s)
1565 void Paragraph::write(ostream & os, BufferParams const & bparams,
1566 depth_type & depth) const
1568 // The beginning or end of a deeper (i.e. nested) area?
1569 if (depth != d->params_.depth()) {
1570 if (d->params_.depth() > depth) {
1571 while (d->params_.depth() > depth) {
1572 os << "\n\\begin_deeper";
1576 while (d->params_.depth() < depth) {
1577 os << "\n\\end_deeper";
1583 // First write the layout
1584 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1586 d->params_.write(os);
1588 Font font1(inherit_font, bparams.language);
1590 Change running_change = Change(Change::UNCHANGED);
1592 // this string is used as a buffer to avoid repetitive calls
1593 // to to_utf8(), which turn out to be expensive (JMarc)
1594 docstring write_buffer;
1597 for (pos_type i = 0; i <= size(); ++i) {
1599 Change const & change = lookupChange(i);
1600 if (change != running_change)
1601 flushString(os, write_buffer);
1602 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1603 running_change = change;
1608 // Write font changes
1609 Font font2 = getFontSettings(bparams, i);
1610 if (font2 != font1) {
1611 flushString(os, write_buffer);
1612 font2.lyxWriteChanges(font1, os);
1617 char_type const c = d->text_[i];
1620 if (Inset const * inset = getInset(i)) {
1621 flushString(os, write_buffer);
1622 if (inset->directWrite()) {
1623 // international char, let it write
1624 // code directly so it's shorter in
1630 os << "\\begin_inset ";
1632 os << "\n\\end_inset\n\n";
1635 // FIXME This can be removed again once the mystery
1636 // crash has been resolved.
1641 flushString(os, write_buffer);
1642 os << "\n\\backslash\n";
1646 flushString(os, write_buffer);
1647 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1654 if ((column > 70 && c == ' ')
1656 flushString(os, write_buffer);
1660 // this check is to amend a bug. LyX sometimes
1661 // inserts '\0' this could cause problems.
1663 write_buffer.push_back(c);
1665 LYXERR0("NUL char in structure.");
1671 flushString(os, write_buffer);
1672 os << "\n\\end_layout\n";
1673 // FIXME This can be removed again once the mystery
1674 // crash has been resolved.
1679 void Paragraph::validate(LaTeXFeatures & features) const
1681 d->validate(features);
1682 bool fragile = features.runparams().moving_arg;
1683 fragile |= layout().needprotect;
1684 if (inInset().getLayout().isNeedProtect())
1686 if (needsCProtection(fragile))
1687 features.require("cprotect");
1691 void Paragraph::insert(pos_type pos, docstring const & str,
1692 Font const & font, Change const & change)
1694 for (size_t i = 0, n = str.size(); i != n ; ++i)
1695 insertChar(pos + i, str[i], font, change);
1699 void Paragraph::appendChar(char_type c, Font const & font,
1700 Change const & change)
1703 d->changes_.insert(change, d->text_.size());
1704 // when appending characters, no need to update tables
1705 d->text_.push_back(c);
1706 setFont(d->text_.size() - 1, font);
1707 d->requestSpellCheck(d->text_.size() - 1);
1711 void Paragraph::appendString(docstring const & s, Font const & font,
1712 Change const & change)
1714 pos_type end = s.size();
1715 size_t oldsize = d->text_.size();
1716 size_t newsize = oldsize + end;
1717 size_t capacity = d->text_.capacity();
1718 if (newsize >= capacity)
1719 d->text_.reserve(max(capacity + 100, newsize));
1721 // when appending characters, no need to update tables
1724 // FIXME: Optimize this!
1725 for (size_t i = oldsize; i != newsize; ++i) {
1727 d->changes_.insert(change, i);
1728 d->requestSpellCheck(i);
1730 d->fontlist_.set(oldsize, font);
1731 d->fontlist_.set(newsize - 1, font);
1735 void Paragraph::insertChar(pos_type pos, char_type c,
1738 d->insertChar(pos, c, Change(trackChanges ?
1739 Change::INSERTED : Change::UNCHANGED));
1743 void Paragraph::insertChar(pos_type pos, char_type c,
1744 Font const & font, bool trackChanges)
1746 d->insertChar(pos, c, Change(trackChanges ?
1747 Change::INSERTED : Change::UNCHANGED));
1752 void Paragraph::insertChar(pos_type pos, char_type c,
1753 Font const & font, Change const & change)
1755 d->insertChar(pos, c, change);
1760 void Paragraph::resetFonts(Font const & font)
1762 d->fontlist_.clear();
1763 d->fontlist_.set(0, font);
1764 d->fontlist_.set(d->text_.size() - 1, font);
1767 // Gets uninstantiated font setting at position.
1768 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1772 LYXERR0("pos: " << pos << " size: " << size());
1776 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1777 if (cit != d->fontlist_.end())
1780 if (pos == size() && !empty())
1781 return getFontSettings(bparams, pos - 1);
1783 // Optimisation: avoid a full font instantiation if there is no
1784 // language change from previous call.
1785 static Font previous_font;
1786 static Language const * previous_lang = nullptr;
1787 Language const * lang = getParLanguage(bparams);
1788 if (lang != previous_lang) {
1789 previous_lang = lang;
1790 previous_font = Font(inherit_font, lang);
1792 return previous_font;
1796 FontSpan Paragraph::fontSpan(pos_type pos) const
1798 LBUFERR(pos <= size());
1801 return FontSpan(pos, pos);
1804 FontList::const_iterator cit = d->fontlist_.begin();
1805 FontList::const_iterator end = d->fontlist_.end();
1806 for (; cit != end; ++cit) {
1807 if (cit->pos() >= pos) {
1808 if (pos >= beginOfBody())
1809 return FontSpan(max(start, beginOfBody()),
1812 return FontSpan(start,
1813 min(beginOfBody() - 1,
1816 start = cit->pos() + 1;
1819 // This should not happen, but if so, we take no chances.
1820 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1821 LASSERT(false, return FontSpan(pos, pos));
1825 // Gets uninstantiated font setting at position 0
1826 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1828 if (!empty() && !d->fontlist_.empty())
1829 return d->fontlist_.begin()->font();
1831 // Optimisation: avoid a full font instantiation if there is no
1832 // language change from previous call.
1833 static Font previous_font;
1834 static Language const * previous_lang = nullptr;
1835 if (bparams.language != previous_lang) {
1836 previous_lang = bparams.language;
1837 previous_font = Font(inherit_font, bparams.language);
1840 return previous_font;
1844 // Gets the fully instantiated font at a given position in a paragraph
1845 // This is basically the same function as Text::GetFont() in text2.cpp.
1846 // The difference is that this one is used for generating the LaTeX file,
1847 // and thus cosmetic "improvements" are disallowed: This has to deliver
1848 // the true picture of the buffer. (Asger)
1849 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1850 Font const & outerfont) const
1854 Font font = getFontSettings(bparams, pos);
1856 pos_type const body_pos = beginOfBody();
1857 FontInfo & fi = font.fontInfo();
1859 fi.realize(d->layout_->labelfont);
1861 fi.realize(d->layout_->font);
1863 fi.realize(outerfont.fontInfo());
1864 fi.realize(bparams.getFont().fontInfo());
1870 Font const Paragraph::getLabelFont
1871 (BufferParams const & bparams, Font const & outerfont) const
1873 FontInfo tmpfont = d->layout_->labelfont;
1874 tmpfont.realize(outerfont.fontInfo());
1875 tmpfont.realize(bparams.getFont().fontInfo());
1876 return Font(tmpfont, getParLanguage(bparams));
1880 Font const Paragraph::getLayoutFont
1881 (BufferParams const & bparams, Font const & outerfont) const
1883 FontInfo tmpfont = d->layout_->font;
1884 tmpfont.realize(outerfont.fontInfo());
1885 tmpfont.realize(bparams.getFont().fontInfo());
1886 return Font(tmpfont, getParLanguage(bparams));
1890 char_type Paragraph::getUChar(BufferParams const & bparams,
1891 OutputParams const & rp,
1894 char_type c = d->text_[pos];
1896 // Return unchanged character in LTR languages
1897 // or if we use poylglossia/bidi (XeTeX).
1898 if (rp.useBidiPackage()
1899 || !getFontSettings(bparams, pos).isRightToLeft())
1902 // Without polyglossia/bidi, we need to account for some special cases.
1903 // FIXME This needs to be audited!
1905 // * The input is as expected for all delimiters
1906 // => checked for Hebrew!
1907 // * The output matches the display in the LyX workarea
1908 // => checked for Hebrew!
1909 // * The special cases below are really necessary
1910 // => checked for Hebrew!
1911 // * In arabic_arabi, brackets are transformed to Arabic
1912 // Ornate Parentheses. Is this is really wanted?
1914 string const & lang = getFontSettings(bparams, pos).language()->lang();
1917 // 1. In the following languages, parentheses need to be reversed.
1918 // Also with polyglodia/luabidi
1919 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1921 // 2. In the following languages, brackets don't need to be reversed.
1922 bool const reversebrackets = lang != "arabic_arabtex"
1923 && lang != "arabic_arabi"
1926 // Now swap delimiters if needed.
1937 if (reversebrackets)
1941 if (reversebrackets)
1962 void Paragraph::setFont(pos_type pos, Font const & font)
1964 LASSERT(pos <= size(), return);
1966 // First, reduce font against layout/label font
1967 // Update: The setCharFont() routine in text2.cpp already
1968 // reduces font, so we don't need to do that here. (Asger)
1970 d->fontlist_.set(pos, font);
1974 void Paragraph::makeSameLayout(Paragraph const & par)
1976 d->layout_ = par.d->layout_;
1977 d->params_ = par.d->params_;
1981 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1983 if (isFreeSpacing())
1989 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1990 if (eraseChar(pos, trackChanges))
1996 return count > 0 || pos > 0;
2000 bool Paragraph::hasSameLayout(Paragraph const & par) const
2002 return par.d->layout_ == d->layout_
2003 && d->params_.sameLayout(par.d->params_);
2007 depth_type Paragraph::getDepth() const
2009 return d->params_.depth();
2013 depth_type Paragraph::getMaxDepthAfter() const
2015 if (d->layout_->isEnvironment())
2016 return d->params_.depth() + 1;
2018 return d->params_.depth();
2022 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2024 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2025 return getDefaultAlign(bparams);
2027 return d->params_.align();
2031 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2033 LyXAlignment res = layout().align;
2034 if (isRTL(bparams)) {
2036 if (res == LYX_ALIGN_LEFT)
2037 res = LYX_ALIGN_RIGHT;
2038 else if (res == LYX_ALIGN_RIGHT)
2039 res = LYX_ALIGN_LEFT;
2045 docstring const & Paragraph::labelString() const
2047 return d->params_.labelString();
2051 // the next two functions are for the manual labels
2052 docstring const Paragraph::getLabelWidthString() const
2054 if (d->layout_->margintype == MARGIN_MANUAL
2055 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2056 return d->params_.labelWidthString();
2058 return _("Senseless with this layout!");
2062 void Paragraph::setLabelWidthString(docstring const & s)
2064 d->params_.labelWidthString(s);
2068 docstring Paragraph::expandLabel(Layout const & layout,
2069 BufferParams const & bparams) const
2071 return expandParagraphLabel(layout, bparams, true);
2075 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2076 BufferParams const & bparams, bool process_appendix) const
2078 DocumentClass const & tclass = bparams.documentClass();
2079 string const & lang = getParLanguage(bparams)->code();
2080 bool const in_appendix = process_appendix && d->params_.appendix();
2081 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2083 if (fmt.empty() && !layout.counter.empty())
2084 return tclass.counters().theCounter(layout.counter, lang);
2086 // handle 'inherited level parts' in 'fmt',
2087 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2088 size_t const i = fmt.find('@', 0);
2089 if (i != docstring::npos) {
2090 size_t const j = fmt.find('@', i + 1);
2091 if (j != docstring::npos) {
2092 docstring parent(fmt, i + 1, j - i - 1);
2093 docstring label = from_ascii("??");
2094 if (tclass.hasLayout(parent))
2095 label = expandParagraphLabel(tclass[parent], bparams,
2097 fmt = docstring(fmt, 0, i) + label
2098 + docstring(fmt, j + 1, docstring::npos);
2102 return tclass.counters().counterLabel(fmt, lang);
2106 void Paragraph::applyLayout(Layout const & new_layout)
2108 d->layout_ = &new_layout;
2109 LyXAlignment const oldAlign = d->params_.align();
2111 if (!(oldAlign & d->layout_->alignpossible)) {
2112 frontend::Alert::warning(_("Alignment not permitted"),
2113 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2114 d->params_.align(LYX_ALIGN_LAYOUT);
2119 pos_type Paragraph::beginOfBody() const
2121 return d->begin_of_body_;
2125 void Paragraph::setBeginOfBody()
2127 if (d->layout_->labeltype != LABEL_MANUAL) {
2128 d->begin_of_body_ = 0;
2132 // Unroll the first two cycles of the loop
2133 // and remember the previous character to
2134 // remove unnecessary getChar() calls
2136 pos_type end = size();
2137 bool prev_char_deleted = false;
2138 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2141 char_type previous_char = d->text_[i];
2142 if (!(isNewline(i) || isEnvSeparator(i))) {
2144 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2145 char_type temp = d->text_[i];
2146 prev_char_deleted = isDeleted(i);
2147 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2150 previous_char = temp;
2156 d->begin_of_body_ = i;
2160 bool Paragraph::allowParagraphCustomization() const
2162 return inInset().allowParagraphCustomization();
2166 bool Paragraph::usePlainLayout() const
2168 return inInset().usePlainLayout();
2172 bool Paragraph::isPassThru() const
2174 return inInset().isPassThru() || d->layout_->pass_thru;
2179 // paragraphs inside floats need different alignment tags to avoid
2182 bool noTrivlistCentering(InsetCode code)
2184 return code == FLOAT_CODE
2185 || code == WRAP_CODE
2186 || code == CELL_CODE;
2190 string correction(string const & orig)
2192 if (orig == "flushleft")
2193 return "raggedright";
2194 if (orig == "flushright")
2195 return "raggedleft";
2196 if (orig == "center")
2202 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2203 InsetCode code, bool const lastpar, int & col)
2205 string macro = suffix + "{";
2206 if (noTrivlistCentering(code)) {
2208 // the last paragraph in non-trivlist-aligned
2209 // context is special (to avoid unwanted whitespace)
2210 if (suffix == "\\begin") {
2211 macro = "\\" + correction(env) + "{}";
2212 os << from_ascii(macro);
2213 col += macro.size();
2218 macro += correction(env);
2222 if (suffix == "\\par\\end") {
2226 os << from_ascii(macro);
2227 col += macro.size();
2228 if (suffix == "\\begin") {
2238 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2239 otexstream & os, OutputParams const & runparams) const
2244 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2245 (layout_->toggle_indent != ITOGGLE_NEVER) :
2246 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2248 if (canindent && params_.noindent() && !layout_->pass_thru) {
2249 os << "\\noindent ";
2253 LyXAlignment const curAlign = params_.align();
2255 if (curAlign == layout_->align)
2259 case LYX_ALIGN_NONE:
2260 case LYX_ALIGN_BLOCK:
2261 case LYX_ALIGN_LAYOUT:
2262 case LYX_ALIGN_SPECIAL:
2263 case LYX_ALIGN_DECIMAL:
2265 case LYX_ALIGN_LEFT:
2266 case LYX_ALIGN_RIGHT:
2267 case LYX_ALIGN_CENTER:
2268 if (runparams.moving_arg) {
2275 string const begin_tag = "\\begin";
2276 InsetCode code = ownerCode();
2277 bool const lastpar = runparams.isLastPar;
2278 // RTL in classic (PDF)LaTeX (without the Bidi package)
2279 // Luabibdi (used by LuaTeX) behaves like classic
2280 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2281 && !runparams.useBidiPackage();
2284 case LYX_ALIGN_NONE:
2285 case LYX_ALIGN_BLOCK:
2286 case LYX_ALIGN_LAYOUT:
2287 case LYX_ALIGN_SPECIAL:
2288 case LYX_ALIGN_DECIMAL:
2290 case LYX_ALIGN_LEFT: {
2292 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2293 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2295 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2297 } case LYX_ALIGN_RIGHT: {
2299 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2300 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2302 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2304 } case LYX_ALIGN_CENTER: {
2305 corrected_env(os, begin_tag, "center", code, lastpar, column);
2314 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2315 otexstream & os, OutputParams const & runparams) const
2317 LyXAlignment const curAlign = params_.align();
2319 if (curAlign == layout_->align)
2323 case LYX_ALIGN_NONE:
2324 case LYX_ALIGN_BLOCK:
2325 case LYX_ALIGN_LAYOUT:
2326 case LYX_ALIGN_SPECIAL:
2327 case LYX_ALIGN_DECIMAL:
2329 case LYX_ALIGN_LEFT:
2330 case LYX_ALIGN_RIGHT:
2331 case LYX_ALIGN_CENTER:
2332 if (runparams.moving_arg)
2337 bool output = false;
2339 string const end_tag = "\\par\\end";
2340 InsetCode code = ownerCode();
2341 bool const lastpar = runparams.isLastPar;
2342 // RTL in classic (PDF)LaTeX (without the Bidi package)
2343 // Luabibdi (used by LuaTeX) behaves like classic
2344 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2345 && !runparams.useBidiPackage();
2348 case LYX_ALIGN_NONE:
2349 case LYX_ALIGN_BLOCK:
2350 case LYX_ALIGN_LAYOUT:
2351 case LYX_ALIGN_SPECIAL:
2352 case LYX_ALIGN_DECIMAL:
2354 case LYX_ALIGN_LEFT: {
2356 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2357 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2359 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2361 } case LYX_ALIGN_RIGHT: {
2363 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2364 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2366 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2368 } case LYX_ALIGN_CENTER: {
2369 corrected_env(os, end_tag, "center", code, lastpar, col);
2374 return output || lastpar;
2378 // This one spits out the text of the paragraph
2379 void Paragraph::latex(BufferParams const & bparams,
2380 Font const & outerfont,
2382 OutputParams const & runparams,
2383 int start_pos, int end_pos, bool force) const
2385 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2387 // FIXME This check should not be needed. Perhaps issue an
2388 // error if it triggers.
2389 Layout const & style = inInset().forcePlainLayout() ?
2390 bparams.documentClass().plainLayout() : *d->layout_;
2392 if (!force && style.inpreamble)
2395 bool const allowcust = allowParagraphCustomization();
2397 // Current base font for all inherited font changes, without any
2398 // change caused by an individual character, except for the language:
2399 // It is set to the language of the first character.
2400 // As long as we are in the label, this font is the base font of the
2401 // label. Before the first body character it is set to the base font
2405 // If there is an open font-encoding changing command (script wrapper),
2406 // alien_script is set to its name
2407 string alien_script;
2410 // Maybe we have to create a optional argument.
2411 pos_type body_pos = beginOfBody();
2412 unsigned int column = 0;
2414 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2415 Font const real_outerfont = (!inInset().inheritFont()
2416 && runparams.local_font != nullptr)
2417 ? Font(runparams.local_font->fontInfo()) : outerfont;
2420 // the optional argument is kept in curly brackets in
2421 // case it contains a ']'
2422 // This is not strictly needed, but if this is changed it
2423 // would be a file format change, and tex2lyx would need
2424 // to be adjusted, since it unconditionally removes the
2425 // braces when it parses \item.
2428 basefont = getLabelFont(bparams, real_outerfont);
2430 basefont = getLayoutFont(bparams, real_outerfont);
2433 // Which font is currently active?
2434 Font running_font(basefont);
2435 // Do we have an open font change?
2436 bool open_font = false;
2438 Change runningChange = Change(Change::UNCHANGED);
2440 Encoding const * const prev_encoding = runparams.encoding;
2442 os.texrow().start(id(), 0);
2444 // if the paragraph is empty, the loop will not be entered at all
2446 // For InTitle commands, we have already opened a group
2447 // in output_latex::TeXOnePar.
2448 if (style.isCommand() && !style.intitle) {
2452 if (!style.leftdelim().empty()) {
2453 os << style.leftdelim();
2454 column += style.leftdelim().size();
2457 column += d->startTeXParParams(bparams, os, runparams);
2460 // Whether a \par can be issued for insets typeset inline with text.
2461 // Yes if greater than 0. This has to be static.
2462 THREAD_LOCAL_STATIC int parInline = 0;
2464 for (pos_type i = 0; i < size(); ++i) {
2465 // First char in paragraph or after label?
2466 if (i == body_pos) {
2469 bool needPar = false;
2470 column += running_font.latexWriteEndChanges(
2471 os, bparams, runparams,
2472 basefont, basefont, needPar);
2475 basefont = getLayoutFont(bparams, real_outerfont);
2476 running_font = basefont;
2478 column += Changes::latexMarkChange(os, bparams,
2479 runningChange, Change(Change::UNCHANGED),
2481 runningChange = Change(Change::UNCHANGED);
2486 // For InTitle commands, we have already opened a group
2487 // in output_latex::TeXOnePar.
2488 if (style.isCommand() && !style.intitle) {
2493 if (!style.leftdelim().empty()) {
2494 os << style.leftdelim();
2495 column += style.leftdelim().size();
2499 column += d->startTeXParParams(bparams, os,
2503 runparams.wasDisplayMath = runparams.inDisplayMath;
2504 runparams.inDisplayMath = false;
2505 bool deleted_display_math = false;
2506 Change const & change = runparams.inDeletedInset
2507 ? runparams.changeOfDeletedInset : lookupChange(i);
2509 char_type const c = d->text_[i];
2511 // Check whether a display math inset follows
2513 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2515 runparams.ctObject = getInset(i)->getCtObject(runparams);
2517 InsetMath const * im = getInset(i)->asInsetMath();
2518 if (im && im->asHullInset()
2519 && im->asHullInset()->outerDisplay()) {
2520 runparams.inDisplayMath = true;
2521 // runparams.inDeletedInset will be set by
2522 // latexInset later, but we need this info
2523 // before it is called. On the other hand, we
2524 // cannot set it here because it is a counter.
2525 deleted_display_math = isDeleted(i);
2527 if (bparams.output_changes && deleted_display_math
2528 && runningChange == change
2529 && change.type == Change::DELETED
2530 && !os.afterParbreak()) {
2531 // A display math in the same paragraph follows.
2532 // We have to close and then reopen \lyxdeleted,
2533 // otherwise the math will be shifted up.
2534 OutputParams rp = runparams;
2536 bool needPar = false;
2537 column += running_font.latexWriteEndChanges(
2538 os, bparams, rp, basefont,
2542 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2543 : getLayoutFont(bparams, real_outerfont);
2544 running_font = basefont;
2545 column += Changes::latexMarkChange(os, bparams,
2546 Change(Change::INSERTED), change, rp);
2550 if (bparams.output_changes && runningChange != change) {
2551 if (!alien_script.empty()) {
2554 alien_script.clear();
2557 bool needPar = false;
2558 column += running_font.latexWriteEndChanges(
2559 os, bparams, runparams,
2560 basefont, basefont, needPar);
2563 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2564 : getLayoutFont(bparams, real_outerfont);
2565 running_font = basefont;
2566 column += Changes::latexMarkChange(os, bparams, runningChange,
2568 runningChange = change;
2571 // do not output text which is marked deleted
2572 // if change tracking output is disabled
2573 if (!bparams.output_changes && change.deleted()) {
2579 // Fully instantiated font
2580 Font current_font = getFont(bparams, i, outerfont);
2582 Font const prev_font = (i > 0) ?
2583 getFont(bparams, i - 1, outerfont)
2586 Font const last_font = running_font;
2587 bool const in_ct_deletion = (bparams.output_changes
2588 && runningChange == change
2589 && change.type == Change::DELETED
2590 && !os.afterParbreak());
2591 // Insets where font switches are used (rather than font commands)
2592 bool const fontswitch_inset =
2595 && getInset(i)->allowMultiPar()
2596 && getInset(i)->lyxCode() != ERT_CODE
2597 && getInset(i)->producesOutput();
2599 bool closeLanguage = false;
2600 bool lang_switched_at_inset = false;
2601 if (fontswitch_inset) {
2602 // Some insets cannot be inside a font change command.
2603 // However, even such insets *can* be placed in \L or \R
2604 // or their equivalents (for RTL language switches),
2605 // so we don't close the language in those cases
2606 // (= differing isRightToLeft()).
2607 // ArabTeX, though, doesn't seem to handle this special behavior.
2608 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2609 || basefont.language()->lang() == "arabic_arabtex"
2610 || current_font.language()->lang() == "arabic_arabtex";
2611 // We need to check prev_font as language changes directly at inset
2612 // will only be started inside the inset.
2613 lang_switched_at_inset = prev_font.language() != current_font.language();
2616 // Do we need to close the previous font?
2617 bool langClosed = false;
2619 ((current_font != running_font
2620 || current_font.language() != running_font.language())
2621 || (fontswitch_inset
2622 && (current_font == prev_font))))
2624 // ensure there is no open script-wrapper
2625 if (!alien_script.empty()) {
2628 alien_script.clear();
2630 if (in_ct_deletion) {
2631 // We have to close and then reopen \lyxdeleted,
2632 // as strikeout needs to be on lowest level.
2637 // Force language closing
2638 current_font.setLanguage(basefont.language());
2639 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2640 bool needPar = false;
2641 column += running_font.latexWriteEndChanges(
2642 os, bparams, runparams, basefont,
2644 if (in_ct_deletion) {
2645 // We have to close and then reopen \lyxdeleted,
2646 // as strikeout needs to be on lowest level.
2647 OutputParams rp = runparams;
2648 column += Changes::latexMarkChange(os, bparams,
2649 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2652 // Has the language been closed in the latexWriteEndChanges() call above?
2653 langClosed = running_font.language() != basefont.language()
2654 && running_font.language() != nextfont.language()
2655 && (running_font.language()->encoding()->package() != Encoding::CJK);
2656 running_font = basefont;
2659 // if necessary, close language environment before opening CJK
2660 string const running_lang = running_font.language()->babel();
2661 string const lang_end_command = lyxrc.language_command_end;
2662 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2663 && !running_lang.empty()
2664 && running_lang == openLanguageName()
2665 && current_font.language()->encoding()->package() == Encoding::CJK) {
2666 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2667 os << from_ascii(end_tag);
2668 column += end_tag.length();
2672 // Switch file encoding if necessary (and allowed)
2673 if ((!fontswitch_inset || closeLanguage)
2674 && !runparams.pass_thru && !style.pass_thru &&
2675 runparams.encoding->package() != Encoding::none &&
2676 current_font.language()->encoding()->package() != Encoding::none) {
2677 pair<bool, int> const enc_switch =
2678 switchEncoding(os.os(), bparams, runparams,
2679 *(current_font.language()->encoding()));
2680 if (enc_switch.first) {
2681 column += enc_switch.second;
2682 runparams.encoding = current_font.language()->encoding();
2686 // A display math inset inside an ulem command will be output
2687 // as a box of width \linewidth, so we have to either disable
2688 // indentation if the inset starts a paragraph, or start a new
2689 // line to accommodate such box. This has to be done before
2690 // writing any font changing commands.
2691 if (runparams.inDisplayMath && !deleted_display_math
2692 && runparams.inulemcmd) {
2693 if (os.afterParbreak())
2699 // Do we need to change font?
2700 if ((current_font != running_font ||
2701 current_font.language() != running_font.language())
2702 && i != body_pos - 1)
2704 if (!fontswitch_inset) {
2705 if (in_ct_deletion) {
2706 // We have to close and then reopen \lyxdeleted,
2707 // as strikeout needs to be on lowest level.
2708 OutputParams rp = runparams;
2709 bool needPar = false;
2710 column += running_font.latexWriteEndChanges(
2711 os, bparams, rp, basefont,
2716 otexstringstream ots;
2717 InsetText const * textinset = inInset().asInsetText();
2718 bool const cprotect = textinset
2719 ? textinset->hasCProtectContent(runparams.moving_arg)
2720 && !textinset->text().isMainText()
2722 column += current_font.latexWriteStartChanges(ots, bparams,
2723 runparams, basefont, last_font, false,
2725 // Check again for display math in ulem commands as a
2726 // font change may also occur just before a math inset.
2727 if (runparams.inDisplayMath && !deleted_display_math
2728 && runparams.inulemcmd) {
2729 if (os.afterParbreak())
2734 running_font = current_font;
2736 docstring fontchange = ots.str();
2738 // check whether the fontchange ends with a \\textcolor
2739 // modifier and the text starts with a space. If so we
2740 // need to add } in order to prevent \\textcolor from gobbling
2741 // the space (bug 4473).
2742 docstring const last_modifier = rsplit(fontchange, '\\');
2743 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2744 os << from_ascii("{}");
2745 else if (ots.terminateCommand())
2747 if (in_ct_deletion) {
2748 // We have to close and then reopen \lyxdeleted,
2749 // as strikeout needs to be on lowest level.
2750 OutputParams rp = runparams;
2751 column += Changes::latexMarkChange(os, bparams,
2752 Change(Change::UNCHANGED), change, rp);
2755 running_font = current_font;
2756 open_font = !langClosed;
2760 // FIXME: think about end_pos implementation...
2761 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2762 // FIXME: integrate this case in latexSpecialChar
2763 // Do not print the separation of the optional argument
2764 // if style.pass_thru is false. This works because
2765 // latexSpecialChar ignores spaces if
2766 // style.pass_thru is false.
2767 if (i != body_pos - 1) {
2768 if (d->simpleTeXBlanks(bparams, runparams, os,
2769 i, column, current_font, style)) {
2770 // A surrogate pair was output. We
2771 // must not call latexSpecialChar
2772 // in this iteration, since it would output
2773 // the combining character again.
2780 OutputParams rp = runparams;
2781 rp.free_spacing = style.free_spacing;
2782 rp.local_font = ¤t_font;
2783 rp.intitle = style.intitle;
2785 // Two major modes: LaTeX or plain
2786 // Handle here those cases common to both modes
2787 // and then split to handle the two modes separately.
2788 if (c == META_INSET) {
2789 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2790 // Greyedout notes and, in general, all insets
2791 // with InsetLayout::isDisplay() == false,
2792 // are typeset inline with the text. So, we
2793 // can add a \par to the last paragraph of
2794 // such insets only if nothing else follows.
2795 bool incremented = false;
2796 Inset const * inset = getInset(i);
2797 InsetText const * textinset = inset
2798 ? inset->asInsetText()
2800 if (i + 1 == size() && textinset
2801 && !inset->getLayout().isDisplay()) {
2802 ParagraphList const & pars =
2803 textinset->text().paragraphs();
2804 pit_type const pit = pars.size() - 1;
2805 Font const lastfont =
2806 pit < 0 || pars[pit].empty()
2807 ? pars[pit].getLayoutFont(
2810 : pars[pit].getFont(bparams,
2811 pars[pit].size() - 1,
2813 if (lastfont.fontInfo().size() !=
2814 basefont.fontInfo().size()) {
2819 // We need to restore parts of this after insets with
2820 // allowMultiPar() true
2821 Font const save_basefont = basefont;
2822 d->latexInset(bparams, os, rp, running_font,
2823 basefont, real_outerfont, open_font,
2824 runningChange, style, i, column, fontswitch_inset,
2825 closeLanguage, lang_switched_at_inset);
2826 if (fontswitch_inset) {
2828 bool needPar = false;
2829 column += running_font.latexWriteEndChanges(
2830 os, bparams, runparams,
2831 basefont, basefont, needPar);
2834 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2835 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2836 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2841 if (runparams.ctObject == CtObject::DisplayObject
2842 || runparams.ctObject == CtObject::UDisplayObject) {
2843 // Close \lyx*deleted and force its
2844 // reopening (if needed)
2847 runningChange = Change(Change::UNCHANGED);
2848 runparams.ctObject = CtObject::Normal;
2851 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2852 if (!bparams.useNonTeXFonts)
2853 script = Encodings::isKnownScriptChar(c);
2854 if (script != alien_script) {
2855 if (!alien_script.empty()) {
2857 alien_script.clear();
2859 string fontenc = running_font.language()->fontenc(bparams);
2861 && !Encodings::fontencSupportsScript(fontenc, script)) {
2862 column += script.length() + 2;
2863 os << "\\" << script << "{";
2864 alien_script = script;
2868 d->latexSpecialChar(os, bparams, rp, running_font,
2869 alien_script, style, i, end_pos, column);
2870 } catch (EncodingException & e) {
2871 if (runparams.dryrun) {
2872 os << "<" << _("LyX Warning: ")
2873 << _("uncodable character") << " '";
2877 // add location information and throw again.
2885 // Set the encoding to that returned from latexSpecialChar (see
2886 // comment for encoding member in OutputParams.h)
2887 runparams.encoding = rp.encoding;
2889 // Also carry on the info on a closed ulem command for insets
2890 // such as Note that do not produce any output, so that no
2891 // command is ever executed but its opening was recorded.
2892 runparams.inulemcmd = rp.inulemcmd;
2894 // These need to be passed upstream as well
2895 runparams.need_maketitle = rp.need_maketitle;
2896 runparams.have_maketitle = rp.have_maketitle;
2898 // And finally, pass the post_macros upstream
2899 runparams.post_macro = rp.post_macro;
2902 // Close wrapper for alien script
2903 if (!alien_script.empty()) {
2905 alien_script.clear();
2908 Font const font = empty()
2909 ? getLayoutFont(bparams, real_outerfont)
2910 : getFont(bparams, size() - 1, real_outerfont);
2912 InsetText const * textinset = inInset().asInsetText();
2914 bool const maintext = textinset
2915 ? textinset->text().isMainText()
2918 size_t const numpars = textinset
2919 ? textinset->text().paragraphs().size()
2922 bool needPar = false;
2924 if (style.resfont.size() != font.fontInfo().size()
2925 && (!runparams.isLastPar || maintext
2926 || (numpars > 1 && d->ownerCode() != CELL_CODE
2927 && (inInset().getLayout().isDisplay()
2929 && !style.isCommand()) {
2933 // If we have an open font definition, we have to close it
2935 // Make sure that \\par is done with the font of the last
2936 // character if this has another size as the default.
2937 // This is necessary because LaTeX (and LyX on the screen)
2938 // calculates the space between the baselines according
2939 // to this font. (Matthias)
2941 // We must not change the font for the last paragraph
2942 // of non-multipar insets, tabular cells or commands,
2943 // since this produces unwanted whitespace.
2944 #ifdef FIXED_LANGUAGE_END_DETECTION
2946 running_font.latexWriteEndChanges(os, bparams,
2947 runparams, basefont,
2948 next_->getFont(bparams, 0, outerfont),
2951 running_font.latexWriteEndChanges(os, bparams,
2952 runparams, basefont, basefont, needPar);
2955 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2956 //FIXME: there as we start another \selectlanguage with the next paragraph if
2957 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2958 running_font.latexWriteEndChanges(os, bparams, runparams,
2959 basefont, basefont, needPar);
2963 // The \par could not be inserted at the same nesting
2964 // level of the font size change, so do it now.
2965 os << "{\\" << font.latexSize() << "\\par}";
2968 column += Changes::latexMarkChange(os, bparams, runningChange,
2969 Change(Change::UNCHANGED), runparams);
2971 // Needed if there is an optional argument but no contents.
2972 if (body_pos > 0 && body_pos == size()) {
2976 if (!style.rightdelim().empty()) {
2977 os << style.rightdelim();
2978 column += style.rightdelim().size();
2981 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2982 && runparams.encoding != prev_encoding) {
2983 runparams.encoding = prev_encoding;
2984 os << setEncoding(prev_encoding->iconvName());
2987 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2991 bool Paragraph::emptyTag() const
2993 for (pos_type i = 0; i < size(); ++i) {
2994 if (Inset const * inset = getInset(i)) {
2995 InsetCode lyx_code = inset->lyxCode();
2996 // FIXME testing like that is wrong. What is
2998 if (lyx_code != TOC_CODE &&
2999 lyx_code != INCLUDE_CODE &&
3000 lyx_code != GRAPHICS_CODE &&
3001 lyx_code != ERT_CODE &&
3002 lyx_code != LISTINGS_CODE &&
3003 lyx_code != FLOAT_CODE &&
3004 lyx_code != TABULAR_CODE) {
3008 char_type c = d->text_[i];
3009 if (c != ' ' && c != '\t')
3017 string Paragraph::getID(Buffer const &, OutputParams const &)
3020 for (pos_type i = 0; i < size(); ++i) {
3021 if (Inset const * inset = getInset(i)) {
3022 InsetCode lyx_code = inset->lyxCode();
3023 if (lyx_code == LABEL_CODE) {
3024 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3025 docstring const & id = il->getParam("name");
3026 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3034 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3037 for (i = 0; i < size(); ++i) {
3038 if (Inset const * inset = getInset(i)) {
3039 inset->docbook(xs, runparams);
3041 char_type c = d->text_[i];
3051 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3055 for (i = 0; i < size(); ++i) {
3056 if (Inset const * inset = getInset(i)) {
3057 inset->xhtml(xs, runparams);
3059 char_type c = d->text_[i];
3069 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3072 pos_type size = text_.size();
3073 for (pos_type i = initial; i < size; ++i) {
3074 Font font = owner_->getFont(buf.params(), i, outerfont);
3075 if (text_[i] == META_INSET)
3077 if (i != initial && font != font_old)
3088 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3089 vector<xml::EndFontTag> & tagsToClose,
3090 bool & flag, FontState curstate, xml::FontTypes type)
3092 if (curstate == FONT_ON) {
3093 tagsToOpen.push_back(docbookStartFontTag(type));
3096 tagsToClose.push_back(docbookEndFontTag(type));
3101 class OptionalFontType {
3106 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3107 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3110 OptionalFontType fontShapeToXml(FontShape fs)
3114 return {xml::FT_ITALIC};
3116 return {xml::FT_SLANTED};
3117 case SMALLCAPS_SHAPE:
3118 return {xml::FT_SMALLCAPS};
3123 // the other tags are for internal use
3129 OptionalFontType fontFamilyToXml(FontFamily fm)
3133 return {xml::FT_ROMAN};
3135 return {xml::FT_SANS};
3136 case TYPEWRITER_FAMILY:
3137 return {xml::FT_TYPE};
3138 case INHERIT_FAMILY:
3141 // the other tags are for internal use
3147 OptionalFontType fontSizeToXml(FontSize fs)
3151 return {xml::FT_SIZE_TINY};
3153 return {xml::FT_SIZE_SCRIPT};
3155 return {xml::FT_SIZE_FOOTNOTE};
3157 return {xml::FT_SIZE_SMALL};
3159 return {xml::FT_SIZE_LARGE};
3161 return {xml::FT_SIZE_LARGER};
3163 return {xml::FT_SIZE_LARGEST};
3165 return {xml::FT_SIZE_HUGE};
3167 return {xml::FT_SIZE_HUGER};
3169 return {xml::FT_SIZE_INCREASE};
3171 return {xml::FT_SIZE_DECREASE};
3176 // the other tags are for internal use
3182 struct DocBookFontState
3184 FontShape curr_fs = INHERIT_SHAPE;
3185 FontFamily curr_fam = INHERIT_FAMILY;
3186 FontSize curr_size = INHERIT_SIZE;
3188 // track whether we have opened these tags
3189 bool emph_flag = false;
3190 bool bold_flag = false;
3191 bool noun_flag = false;
3192 bool ubar_flag = false;
3193 bool dbar_flag = false;
3194 bool sout_flag = false;
3195 bool xout_flag = false;
3196 bool wave_flag = false;
3198 bool shap_flag = false;
3200 bool faml_flag = false;
3202 bool size_flag = false;
3205 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3207 std::string const & default_family,
3208 DocBookFontState & fs)
3210 vector<xml::FontTag> tagsToOpen;
3211 vector<xml::EndFontTag> tagsToClose;
3214 FontState curstate = font.fontInfo().emph();
3215 if (font_old.emph() != curstate)
3216 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3219 curstate = font.fontInfo().noun();
3220 if (font_old.noun() != curstate)
3221 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3224 curstate = font.fontInfo().underbar();
3225 if (font_old.underbar() != curstate)
3226 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3229 curstate = font.fontInfo().strikeout();
3230 if (font_old.strikeout() != curstate)
3231 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3234 curstate = font.fontInfo().xout();
3235 if (font_old.xout() != curstate)
3236 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3239 curstate = font.fontInfo().uuline();
3240 if (font_old.uuline() != curstate)
3241 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3244 curstate = font.fontInfo().uwave();
3245 if (font_old.uwave() != curstate)
3246 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3249 // a little hackish, but allows us to reuse what we have.
3250 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3251 if (font_old.series() != font.fontInfo().series())
3252 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3255 fs.curr_fs = font.fontInfo().shape();
3256 FontShape old_fs = font_old.shape();
3257 if (old_fs != fs.curr_fs) {
3259 OptionalFontType tag = fontShapeToXml(old_fs);
3261 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3262 fs.shap_flag = false;
3265 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3267 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3271 fs.curr_fam = font.fontInfo().family();
3272 FontFamily old_fam = font_old.family();
3273 if (old_fam != fs.curr_fam) {
3275 OptionalFontType tag = fontFamilyToXml(old_fam);
3277 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3278 fs.faml_flag = false;
3280 switch (fs.curr_fam) {
3282 // we will treat a "default" font family as roman, since we have
3283 // no other idea what to do.
3284 if (default_family != "rmdefault" && default_family != "default") {
3285 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3286 fs.faml_flag = true;
3290 if (default_family != "sfdefault") {
3291 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3292 fs.faml_flag = true;
3295 case TYPEWRITER_FAMILY:
3296 if (default_family != "ttdefault") {
3297 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3298 fs.faml_flag = true;
3301 case INHERIT_FAMILY:
3304 // the other tags are for internal use
3311 fs.curr_size = font.fontInfo().size();
3312 FontSize old_size = font_old.size();
3313 if (old_size != fs.curr_size) {
3315 OptionalFontType tag = fontSizeToXml(old_size);
3317 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3318 fs.size_flag = false;
3321 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3322 if (tag.has_value) {
3323 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3324 fs.size_flag = true;
3328 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3331 } // anonymous namespace
3334 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3335 OutputParams const & runparams,
3336 Font const & outerfont,
3339 bool ignore_fonts) const
3341 // Track whether we have opened these tags
3342 DocBookFontState fs;
3344 Layout const & style = *d->layout_;
3346 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3348 string const default_family =
3349 buf.masterBuffer()->params().fonts_default_family;
3351 vector<xml::FontTag> tagsToOpen;
3352 vector<xml::EndFontTag> tagsToClose;
3354 std::vector<docstring> generatedParagraphs;
3355 DocBookFontState old_fs = fs;
3356 odocstringstream os;
3357 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3358 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3360 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3361 // characters at some point.
3362 std::vector<char_type> delayedChars;
3364 // Parsing main loop.
3365 for (pos_type i = initial; i < size(); ++i) {
3366 // Don't show deleted material in the output.
3370 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3372 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3374 xs->closeFontTags();
3376 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3377 generatedParagraphs.push_back(os.str());
3379 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3380 // that the string stream must be reset.
3381 os.str(from_ascii(""));
3383 xs = new XMLStream(os);
3385 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3386 if (!ignore_fonts) {
3387 font_old = outerfont.fontInfo();
3392 // Determine which tags should be opened or closed regarding fonts.
3393 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3394 if (!ignore_fonts) {
3395 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3398 // Other such tags? What about the other text ranges?
3400 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3401 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3402 for (; cit != cen; ++cit)
3405 // Deal with the delayed characters *after* closing font tags.
3406 if (!delayedChars.empty()) {
3407 for (char_type c: delayedChars)
3409 delayedChars.clear();
3412 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3413 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3414 for (; sit != sen; ++sit)
3417 tagsToClose.clear();
3421 if (Inset const * inset = getInset(i)) {
3422 if (!runparams.for_toc || inset->isInToc()) {
3423 OutputParams np = runparams;
3424 np.local_font = &font;
3426 // TODO: special case will bite here.
3427 np.docbook_in_par = true;
3428 inset->docbook(*xs, np);
3431 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3432 if (lyx::isSpace(c) && !ignore_fonts)
3433 delayedChars.push_back(c);
3437 font_old = font.fontInfo();
3440 // FIXME, this code is just imported from XHTML
3441 // I'm worried about what happens if a branch, say, is itself
3442 // wrapped in some font stuff. I think that will not work.
3444 xs->closeFontTags();
3446 // Deal with the delayed characters *after* closing font tags.
3447 if (!delayedChars.empty())
3448 for (char_type c: delayedChars)
3451 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3452 // last line to get a clean output.
3453 if (runparams.docbook_in_listing && !is_last_par)
3456 // Finalise the last (and most likely only) paragraph.
3457 generatedParagraphs.push_back(os.str());
3460 return generatedParagraphs;
3466 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3467 vector<xml::EndFontTag> & tagsToClose,
3468 bool & flag, FontState curstate, xml::FontTypes type)
3470 if (curstate == FONT_ON) {
3471 tagsToOpen.push_back(xhtmlStartFontTag(type));
3474 tagsToClose.push_back(xhtmlEndFontTag(type));
3479 } // anonymous namespace
3482 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3484 OutputParams const & runparams,
3485 Font const & outerfont,
3486 bool start_paragraph, bool close_paragraph,
3487 pos_type initial) const
3491 // track whether we have opened these tags
3492 bool emph_flag = false;
3493 bool bold_flag = false;
3494 bool noun_flag = false;
3495 bool ubar_flag = false;
3496 bool dbar_flag = false;
3497 bool sout_flag = false;
3498 bool xout_flag = false;
3499 bool wave_flag = false;
3501 bool shap_flag = false;
3503 bool faml_flag = false;
3505 bool size_flag = false;
3507 Layout const & style = *d->layout_;
3509 if (start_paragraph)
3510 xs.startDivision(allowEmpty());
3513 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3515 FontShape curr_fs = INHERIT_SHAPE;
3516 FontFamily curr_fam = INHERIT_FAMILY;
3517 FontSize curr_size = INHERIT_SIZE;
3519 string const default_family =
3520 buf.masterBuffer()->params().fonts_default_family;
3522 vector<xml::FontTag> tagsToOpen;
3523 vector<xml::EndFontTag> tagsToClose;
3525 // parsing main loop
3526 for (pos_type i = initial; i < size(); ++i) {
3527 // let's not show deleted material in the output
3531 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3534 FontState curstate = font.fontInfo().emph();
3535 if (font_old.emph() != curstate)
3536 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3539 curstate = font.fontInfo().noun();
3540 if (font_old.noun() != curstate)
3541 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3544 curstate = font.fontInfo().underbar();
3545 if (font_old.underbar() != curstate)
3546 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3549 curstate = font.fontInfo().strikeout();
3550 if (font_old.strikeout() != curstate)
3551 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3554 curstate = font.fontInfo().xout();
3555 if (font_old.xout() != curstate)
3556 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3559 curstate = font.fontInfo().uuline();
3560 if (font_old.uuline() != curstate)
3561 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3564 curstate = font.fontInfo().uwave();
3565 if (font_old.uwave() != curstate)
3566 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3569 // a little hackish, but allows us to reuse what we have.
3570 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3571 if (font_old.series() != font.fontInfo().series())
3572 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3575 curr_fs = font.fontInfo().shape();
3576 FontShape old_fs = font_old.shape();
3577 if (old_fs != curr_fs) {
3581 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3584 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3586 case SMALLCAPS_SHAPE:
3587 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3593 // the other tags are for internal use
3601 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3605 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3608 case SMALLCAPS_SHAPE:
3609 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3616 // the other tags are for internal use
3623 curr_fam = font.fontInfo().family();
3624 FontFamily old_fam = font_old.family();
3625 if (old_fam != curr_fam) {
3629 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3632 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3634 case TYPEWRITER_FAMILY:
3635 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3637 case INHERIT_FAMILY:
3640 // the other tags are for internal use
3648 // we will treat a "default" font family as roman, since we have
3649 // no other idea what to do.
3650 if (default_family != "rmdefault" && default_family != "default") {
3651 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3656 if (default_family != "sfdefault") {
3657 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3661 case TYPEWRITER_FAMILY:
3662 if (default_family != "ttdefault") {
3663 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3667 case INHERIT_FAMILY:
3670 // the other tags are for internal use
3677 curr_size = font.fontInfo().size();
3678 FontSize old_size = font_old.size();
3679 if (old_size != curr_size) {
3683 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3686 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3689 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3692 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3695 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3698 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3701 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3704 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3707 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3710 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3713 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3719 // the other tags are for internal use
3725 switch (curr_size) {
3727 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3731 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3735 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3739 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3743 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3747 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3751 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3755 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3759 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3763 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3767 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3774 // the other tags are for internal use
3781 // Other such tags? What about the other text ranges?
3783 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3784 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3785 for (; cit != cen; ++cit)
3788 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3789 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3790 for (; sit != sen; ++sit)
3793 tagsToClose.clear();
3796 Inset const * inset = getInset(i);
3798 if (!runparams.for_toc || inset->isInToc()) {
3799 OutputParams np = runparams;
3800 np.local_font = &font;
3801 // If the paragraph has size 1, then we are in the "special
3802 // case" where we do not output the containing paragraph info
3803 if (!inset->getLayout().htmlisblock() && size() != 1)
3804 np.html_in_par = true;
3805 retval += inset->xhtml(xs, np);
3808 char_type c = getUChar(buf.masterBuffer()->params(),
3810 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3811 xs << XMLStream::ESCAPE_NONE << " ";
3815 font_old = font.fontInfo();
3819 // I'm worried about what happens if a branch, say, is itself
3820 // wrapped in some font stuff. I think that will not work.
3822 if (close_paragraph)
3829 bool Paragraph::isHfill(pos_type pos) const
3831 Inset const * inset = getInset(pos);
3832 return inset && inset->isHfill();
3836 bool Paragraph::isNewline(pos_type pos) const
3838 // U+2028 LINE SEPARATOR
3839 // U+2029 PARAGRAPH SEPARATOR
3840 char_type const c = d->text_[pos];
3841 if (c == 0x2028 || c == 0x2029)
3843 Inset const * inset = getInset(pos);
3844 return inset && inset->lyxCode() == NEWLINE_CODE;
3848 bool Paragraph::isEnvSeparator(pos_type pos) const
3850 Inset const * inset = getInset(pos);
3851 return inset && inset->lyxCode() == SEPARATOR_CODE;
3855 bool Paragraph::isLineSeparator(pos_type pos) const
3857 char_type const c = d->text_[pos];
3858 if (isLineSeparatorChar(c))
3860 Inset const * inset = getInset(pos);
3861 return inset && inset->isLineSeparator();
3865 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3869 if (ignore_deleted && isDeleted(pos))
3871 if (Inset const * inset = getInset(pos))
3872 return !inset->isLetter();
3873 // if we have a hard hyphen (no en- or emdash) or apostrophe
3874 // we pass this to the spell checker
3875 // FIXME: this method is subject to change, visit
3876 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3877 // to get an impression how complex this is.
3878 if (isHardHyphenOrApostrophe(pos))
3880 char_type const c = d->text_[pos];
3881 // We want to pass the escape chars to the spellchecker
3882 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3883 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3887 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3889 pos_type const psize = size();
3892 char_type const c = d->text_[pos];
3893 if (c != '-' && c != '\'')
3895 pos_type nextpos = pos + 1;
3896 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3897 if ((nextpos == psize || isSpace(nextpos))
3898 && (pos == 0 || isSpace(prevpos)))
3904 bool Paragraph::needsCProtection(bool const fragile) const
3906 // first check the layout of the paragraph, but only in insets
3907 InsetText const * textinset = inInset().asInsetText();
3908 bool const maintext = textinset
3909 ? textinset->text().isMainText()
3912 if (!maintext && layout().needcprotect) {
3913 // Environments need cprotection regardless the content
3914 if (layout().latextype == LATEX_ENVIRONMENT)
3917 // Commands need cprotection if they contain specific chars
3918 int const nchars_escape = 9;
3919 static char_type const chars_escape[nchars_escape] = {
3920 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3922 docstring const pars = asString();
3923 for (int k = 0; k < nchars_escape; k++) {
3924 if (contains(pars, chars_escape[k]))
3929 // now check whether we have insets that need cprotection
3930 pos_type size = pos_type(d->text_.size());
3931 for (pos_type i = 0; i < size; ++i) {
3934 Inset const * ins = getInset(i);
3935 if (ins->needsCProtection(maintext, fragile))
3937 // Now check math environments
3938 InsetMath const * im = getInset(i)->asInsetMath();
3939 if (!im || im->cell(0).empty())
3941 switch(im->cell(0)[0]->lyxCode()) {
3942 case MATH_AMSARRAY_CODE:
3943 case MATH_SUBSTACK_CODE:
3945 case MATH_XYMATRIX_CODE:
3946 // these need cprotection
3957 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3959 return d->speller_state_.getRange(pos);
3963 bool Paragraph::isChar(pos_type pos) const
3965 if (Inset const * inset = getInset(pos))
3966 return inset->isChar();
3967 char_type const c = d->text_[pos];
3968 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3972 bool Paragraph::isSpace(pos_type pos) const
3974 if (Inset const * inset = getInset(pos))
3975 return inset->isSpace();
3976 char_type const c = d->text_[pos];
3977 return lyx::isSpace(c);
3982 Paragraph::getParLanguage(BufferParams const & bparams) const
3985 return getFirstFontSettings(bparams).language();
3986 // FIXME: we should check the prev par as well (Lgb)
3987 return bparams.language;
3991 bool Paragraph::isRTL(BufferParams const & bparams) const
3993 return getParLanguage(bparams)->rightToLeft()
3994 && !inInset().getLayout().forceLTR();
3998 void Paragraph::changeLanguage(BufferParams const & bparams,
3999 Language const * from, Language const * to)
4001 // change language including dummy font change at the end
4002 for (pos_type i = 0; i <= size(); ++i) {
4003 Font font = getFontSettings(bparams, i);
4004 if (font.language() == from) {
4005 font.setLanguage(to);
4007 d->requestSpellCheck(i);
4013 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4015 Language const * doc_language = bparams.language;
4016 for (auto const & f : d->fontlist_)
4017 if (f.font().language() != ignore_language &&
4018 f.font().language() != latex_language &&
4019 f.font().language() != doc_language)
4025 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4027 for (auto const & f : d->fontlist_) {
4028 Language const * lang = f.font().language();
4029 if (lang != ignore_language &&
4030 lang != latex_language)
4036 docstring Paragraph::asString(int options) const
4038 return asString(0, size(), options);
4042 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4044 odocstringstream os;
4047 && options & AS_STR_LABEL
4048 && !d->params_.labelString().empty())
4049 os << d->params_.labelString() << ' ';
4051 for (pos_type i = beg; i < end; ++i) {
4052 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4054 char_type const c = d->text_[i];
4055 if (isPrintable(c) || c == '\t'
4056 || (c == '\n' && (options & AS_STR_NEWLINES)))
4058 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4059 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4060 LASSERT(runparams != nullptr, return docstring());
4061 getInset(i)->plaintext(os, *runparams);
4063 getInset(i)->toString(os);
4072 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4073 bool const shorten, bool const label) const
4075 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4076 if (label && !labelString().empty())
4077 os += labelString() + ' ';
4078 if (!layout().isTocCaption())
4080 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4083 char_type const c = d->text_[i];
4086 else if (c == META_INSET)
4087 getInset(i)->forOutliner(os, tmplen, false);
4090 Text::shortenForOutliner(os, maxlen);
4094 void Paragraph::setInsetOwner(Inset const * inset)
4096 d->inset_owner_ = inset;
4100 int Paragraph::id() const
4106 void Paragraph::setId(int id)
4112 Layout const & Paragraph::layout() const
4118 void Paragraph::setLayout(Layout const & layout)
4120 d->layout_ = &layout;
4124 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4126 setLayout(tc.defaultLayout());
4130 void Paragraph::setPlainLayout(DocumentClass const & tc)
4132 setLayout(tc.plainLayout());
4136 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4138 if (usePlainLayout())
4141 setDefaultLayout(tc);
4145 Inset const & Paragraph::inInset() const
4147 LBUFERR(d->inset_owner_);
4148 return *d->inset_owner_;
4152 ParagraphParameters & Paragraph::params()
4158 ParagraphParameters const & Paragraph::params() const
4164 bool Paragraph::isFreeSpacing() const
4166 if (d->layout_->free_spacing)
4168 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4172 bool Paragraph::allowEmpty() const
4174 if (d->layout_->keepempty)
4176 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4180 bool Paragraph::brokenBiblio() const
4182 // There is a problem if there is no bibitem at position 0 in
4183 // paragraphs that need one, if there is another bibitem in the
4184 // paragraph or if this paragraph is not supposed to have
4185 // a bibitem inset at all.
4186 return ((d->layout_->labeltype == LABEL_BIBLIO
4187 && (d->insetlist_.find(BIBITEM_CODE) != 0
4188 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4189 || (d->layout_->labeltype != LABEL_BIBLIO
4190 && d->insetlist_.find(BIBITEM_CODE) != -1));
4194 int Paragraph::fixBiblio(Buffer const & buffer)
4196 // FIXME: when there was already an inset at 0, the return value is 1,
4197 // which does not tell whether another inset has been removed; the
4198 // cursor cannot be correctly updated.
4200 bool const track_changes = buffer.params().track_changes;
4201 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4203 // The case where paragraph is not BIBLIO
4204 if (d->layout_->labeltype != LABEL_BIBLIO) {
4205 if (bibitem_pos == -1)
4206 // No InsetBibitem => OK
4208 // There is an InsetBibitem: remove it!
4209 d->insetlist_.release(bibitem_pos);
4210 eraseChar(bibitem_pos, track_changes);
4211 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4214 bool const hasbibitem0 = bibitem_pos == 0;
4216 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4217 // There was an InsetBibitem at pos 0,
4218 // and no other one => OK
4219 if (bibitem_pos == -1)
4221 // there is a bibitem at the 0 position, but since
4222 // there is a second one, we copy the second on the
4223 // first. We're assuming there are at most two of
4224 // these, which there should be.
4225 // FIXME: why does it make sense to do that rather
4226 // than keep the first? (JMarc)
4227 Inset * inset = releaseInset(bibitem_pos);
4228 d->insetlist_.begin()->inset = inset;
4229 // This needs to be done to update the counter (#8499)
4230 buffer.updateBuffer();
4231 return -bibitem_pos;
4234 // We need to create an inset at the beginning
4235 Inset * inset = nullptr;
4236 if (bibitem_pos > 0) {
4237 // there was one somewhere in the paragraph, let's move it
4238 inset = d->insetlist_.release(bibitem_pos);
4239 eraseChar(bibitem_pos, track_changes);
4242 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4243 InsetCommandParams(BIBITEM_CODE));
4245 Font font(inherit_font, buffer.params().language);
4246 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4247 : Change::UNCHANGED));
4249 // This is needed to get the counters right
4250 buffer.updateBuffer();
4255 void Paragraph::checkAuthors(AuthorList const & authorList)
4257 d->changes_.checkAuthors(authorList);
4261 bool Paragraph::isChanged(pos_type pos) const
4263 return lookupChange(pos).changed();
4267 bool Paragraph::isInserted(pos_type pos) const
4269 return lookupChange(pos).inserted();
4273 bool Paragraph::isDeleted(pos_type pos) const
4275 return lookupChange(pos).deleted();
4279 InsetList const & Paragraph::insetList() const
4281 return d->insetlist_;
4285 void Paragraph::setInsetBuffers(Buffer & b)
4287 d->insetlist_.setBuffer(b);
4291 void Paragraph::resetBuffer()
4293 d->insetlist_.resetBuffer();
4297 Inset * Paragraph::releaseInset(pos_type pos)
4299 Inset * inset = d->insetlist_.release(pos);
4300 /// does not honour change tracking!
4301 eraseChar(pos, false);
4306 Inset * Paragraph::getInset(pos_type pos)
4308 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4309 ? d->insetlist_.get(pos) : nullptr;
4313 Inset const * Paragraph::getInset(pos_type pos) const
4315 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4316 ? d->insetlist_.get(pos) : nullptr;
4320 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4321 pos_type & right, TextCase action)
4323 // process sequences of modified characters; in change
4324 // tracking mode, this approach results in much better
4325 // usability than changing case on a char-by-char basis
4326 // We also need to track the current font, since font
4327 // changes within sequences can occur.
4328 vector<pair<char_type, Font> > changes;
4330 bool const trackChanges = bparams.track_changes;
4332 bool capitalize = true;
4334 for (; pos < right; ++pos) {
4335 char_type oldChar = d->text_[pos];
4336 char_type newChar = oldChar;
4338 // ignore insets and don't play with deleted text!
4339 if (oldChar != META_INSET && !isDeleted(pos)) {
4341 case text_lowercase:
4342 newChar = lowercase(oldChar);
4344 case text_capitalization:
4346 newChar = uppercase(oldChar);
4350 case text_uppercase:
4351 newChar = uppercase(oldChar);
4356 if (isWordSeparator(pos) || isDeleted(pos)) {
4357 // permit capitalization again
4361 if (oldChar != newChar) {
4362 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4363 if (pos != right - 1)
4365 // step behind the changing area
4369 int erasePos = pos - changes.size();
4370 for (auto const & change : changes) {
4371 insertChar(pos, change.first, change.second, trackChanges);
4372 if (!eraseChar(erasePos, trackChanges)) {
4375 ++right; // expand selection
4383 int Paragraph::find(docstring const & str, bool cs, bool mw,
4384 pos_type start_pos, bool del) const
4386 pos_type pos = start_pos;
4387 int const strsize = str.length();
4389 pos_type const parsize = d->text_.size();
4390 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4391 // ignore deleted matter
4392 if (!del && isDeleted(pos)) {
4393 if (pos == parsize - 1)
4399 // Ignore "invisible" letters such as ligature breaks
4400 // and hyphenation chars while searching
4401 bool nonmatch = false;
4402 while (pos < parsize && isInset(pos)) {
4403 Inset const * inset = getInset(pos);
4404 if (!inset->isLetter() && !inset->isChar())
4406 odocstringstream os;
4407 inset->toString(os);
4408 if (!os.str().empty()) {
4409 int const insetstringsize = os.str().length();
4410 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4411 if (str[i] != os.str()[j]) {
4419 if (nonmatch || i == strsize)
4421 if (cs && str[i] != d->text_[pos])
4423 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4430 // if necessary, check whether string matches word
4432 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4435 && !isWordSeparator(pos))
4439 return pos - start_pos;
4443 char_type Paragraph::getChar(pos_type pos) const
4445 return d->text_[pos];
4449 pos_type Paragraph::size() const
4451 return d->text_.size();
4455 bool Paragraph::empty() const
4457 return d->text_.empty();
4461 bool Paragraph::isInset(pos_type pos) const
4463 return d->text_[pos] == META_INSET;
4467 bool Paragraph::isSeparator(pos_type pos) const
4469 //FIXME: Are we sure this can be the only separator?
4470 return d->text_[pos] == ' ';
4474 void Paragraph::deregisterWords()
4476 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4477 Private::LangWordsMap::const_iterator ite = d->words_.end();
4478 for (; itl != ite; ++itl) {
4479 WordList & wl = theWordList(itl->first);
4480 Private::Words::const_iterator it = (itl->second).begin();
4481 Private::Words::const_iterator et = (itl->second).end();
4482 for (; it != et; ++it)
4489 void Paragraph::locateWord(pos_type & from, pos_type & to,
4490 word_location const loc, bool const ignore_deleted) const
4493 case WHOLE_WORD_STRICT:
4494 if (from == 0 || from == size()
4495 || isWordSeparator(from, ignore_deleted)
4496 || isWordSeparator(from - 1, ignore_deleted)) {
4503 // If we are already at the beginning of a word, do nothing
4504 if (!from || isWordSeparator(from - 1, ignore_deleted))
4509 // always move the cursor to the beginning of previous word
4510 while (from && !isWordSeparator(from - 1, ignore_deleted))
4514 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4517 // no need to move the 'from' cursor
4521 while (to < size() && !isWordSeparator(to, ignore_deleted))
4526 void Paragraph::collectWords()
4528 for (pos_type pos = 0; pos < size(); ++pos) {
4529 if (isWordSeparator(pos))
4531 pos_type from = pos;
4532 locateWord(from, pos, WHOLE_WORD);
4533 // Work around MSVC warning: The statement
4534 // if (pos < from + lyxrc.completion_minlength)
4535 // triggers a signed vs. unsigned warning.
4536 // I don't know why this happens, it could be a MSVC bug, or
4537 // related to LLP64 (windows) vs. LP64 (unix) programming
4538 // model, or the C++ standard might be ambigous in the section
4539 // defining the "usual arithmetic conversions". However, using
4540 // a temporary variable is safe and works on all compilers.
4541 pos_type const endpos = from + lyxrc.completion_minlength;
4544 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4545 if (cit == d->fontlist_.end())
4547 Language const * lang = cit->font().language();
4548 docstring const word = asString(from, pos, AS_STR_NONE);
4549 d->words_[lang->lang()].insert(word);
4554 void Paragraph::registerWords()
4556 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4557 Private::LangWordsMap::const_iterator ite = d->words_.end();
4558 for (; itl != ite; ++itl) {
4559 WordList & wl = theWordList(itl->first);
4560 Private::Words::const_iterator it = (itl->second).begin();
4561 Private::Words::const_iterator et = (itl->second).end();
4562 for (; it != et; ++it)
4568 void Paragraph::updateWords()
4576 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4578 SkipPositionsIterator begin = skips.begin();
4579 SkipPositions::iterator end = skips.end();
4580 if (pos > 0 && begin < end) {
4582 if (end->last == pos - 1) {
4587 skips.insert(end, FontSpan(pos, pos));
4591 Language * Paragraph::Private::locateSpellRange(
4592 pos_type & from, pos_type & to,
4593 SkipPositions & skips) const
4595 // skip leading white space
4596 while (from < to && owner_->isWordSeparator(from))
4598 // don't check empty range
4601 // get current language
4602 Language * lang = getSpellLanguage(from);
4603 pos_type last = from;
4604 bool samelang = true;
4605 bool sameinset = true;
4606 while (last < to && samelang && sameinset) {
4607 // hop to end of word
4608 while (last < to && !owner_->isWordSeparator(last)) {
4609 Inset const * inset = owner_->getInset(last);
4610 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4611 // check for "invisible" letters such as ligature breaks
4612 odocstringstream os;
4613 inset->toString(os);
4614 if (os.str().length() != 0) {
4615 // avoid spell check of visible special char insets
4616 // stop the loop in front of the special char inset
4621 appendSkipPosition(skips, last);
4622 } else if (owner_->isDeleted(last)) {
4623 appendSkipPosition(skips, last);
4627 // hop to next word while checking for insets
4628 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4629 if (Inset const * inset = owner_->getInset(last))
4630 sameinset = inset->isChar() && inset->isLetter();
4631 if (sameinset && owner_->isDeleted(last)) {
4632 appendSkipPosition(skips, last);
4637 if (sameinset && last < to) {
4638 // now check for language change
4639 samelang = lang == getSpellLanguage(last);
4642 // if language change detected backstep is needed
4650 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4653 const_cast<Language *>(owner_->getFontSettings(
4654 inset_owner_->buffer().params(), from).language());
4655 if (lang == inset_owner_->buffer().params().language
4656 && !lyxrc.spellchecker_alt_lang.empty()) {
4658 string const lang_variety =
4659 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4660 lang->setCode(lang_code);
4661 lang->setVariety(lang_variety);
4667 void Paragraph::requestSpellCheck(pos_type pos)
4669 d->requestSpellCheck(pos);
4673 bool Paragraph::needsSpellCheck() const
4675 SpellChecker::ChangeNumber speller_change_number = 0;
4676 if (theSpellChecker())
4677 speller_change_number = theSpellChecker()->changeNumber();
4678 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4679 d->speller_state_.needsCompleteRefresh(speller_change_number);
4681 return d->needsSpellCheck();
4685 bool Paragraph::Private::ignoreWord(docstring const & word) const
4687 // Ignore words with digits
4688 // FIXME: make this customizable
4689 // (note that some checkers ignore words with digits by default)
4690 docstring::const_iterator cit = word.begin();
4691 docstring::const_iterator const end = word.end();
4692 for (; cit != end; ++cit) {
4693 if (isNumber((*cit)))
4700 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4701 WordLangTuple & wl, docstring_list & suggestions,
4702 bool do_suggestion, bool check_learned) const
4704 SpellChecker::Result result = SpellChecker::WORD_OK;
4705 SpellChecker * speller = theSpellChecker();
4709 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4712 locateWord(from, to, WHOLE_WORD, true);
4713 if (from == to || from >= size())
4716 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4717 Language * lang = d->getSpellLanguage(from);
4719 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4722 wl = WordLangTuple(word, lang);
4727 if (needsSpellCheck() || check_learned) {
4729 if (!d->ignoreWord(word)) {
4730 bool const trailing_dot = to < size() && d->text_[to] == '.';
4731 result = speller->check(wl);
4732 if (SpellChecker::misspelled(result) && trailing_dot) {
4733 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4734 result = speller->check(wl);
4735 if (!SpellChecker::misspelled(result)) {
4736 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4738 from << ".." << to << "]");
4740 // spell check with dot appended failed too
4741 // restore original word/lang value
4742 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4743 wl = WordLangTuple(word, lang);
4747 if (!SpellChecker::misspelled(result)) {
4748 // area up to the begin of the next word is not misspelled
4749 while (end < size() && isWordSeparator(end))
4752 d->setMisspelled(from, end, result);
4754 result = d->speller_state_.getState(from);
4758 suggestions.clear();
4760 if (SpellChecker::misspelled(result)) {
4761 LYXERR(Debug::GUI, "misspelled word: \"" <<
4763 from << ".." << to << "]");
4765 speller->suggest(wl, suggestions);
4771 void Paragraph::anonymize()
4773 // This is a very crude anonymization for now
4774 for (char_type & c : d->text_)
4775 if (isLetterChar(c) || isNumber(c))
4780 void Paragraph::Private::markMisspelledWords(
4781 pos_type const & first, pos_type const & last,
4782 SpellChecker::Result result,
4783 docstring const & word,
4784 SkipPositions const & skips)
4786 if (!SpellChecker::misspelled(result)) {
4787 setMisspelled(first, last, SpellChecker::WORD_OK);
4791 SpellChecker * speller = theSpellChecker();
4792 // locate and enumerate the error positions
4793 int nerrors = speller->numMisspelledWords();
4795 SkipPositionsIterator it = skips.begin();
4796 SkipPositionsIterator et = skips.end();
4797 for (int index = 0; index < nerrors; ++index) {
4800 speller->misspelledWord(index, wstart, wlen);
4801 /// should not happen if speller supports range checks
4802 if (!wlen) continue;
4803 docstring const misspelled = word.substr(wstart, wlen);
4804 wstart += first + numskipped;
4805 if (snext < wstart) {
4806 /// mark the range of correct spelling
4807 numskipped += countSkips(it, et, wstart);
4808 setMisspelled(snext,
4809 wstart - 1, SpellChecker::WORD_OK);
4811 snext = wstart + wlen;
4812 numskipped += countSkips(it, et, snext);
4813 /// mark the range of misspelling
4814 setMisspelled(wstart, snext, result);
4815 LYXERR(Debug::GUI, "misspelled word: \"" <<
4816 misspelled << "\" [" <<
4817 wstart << ".." << (snext-1) << "]");
4820 if (snext <= last) {
4821 /// mark the range of correct spelling at end
4822 setMisspelled(snext, last, SpellChecker::WORD_OK);
4827 void Paragraph::spellCheck() const
4829 SpellChecker * speller = theSpellChecker();
4830 if (!speller || empty() ||!needsSpellCheck())
4834 d->rangeOfSpellCheck(start, endpos);
4835 if (speller->canCheckParagraph()) {
4836 // loop until we leave the range
4837 for (pos_type first = start; first < endpos; ) {
4838 pos_type last = endpos;
4839 Private::SkipPositions skips;
4840 Language * lang = d->locateSpellRange(first, last, skips);
4841 if (first >= endpos)
4843 // start the spell checker on the unit of meaning
4844 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4845 WordLangTuple wl = WordLangTuple(word, lang);
4846 SpellChecker::Result result = !word.empty() ?
4847 speller->check(wl) : SpellChecker::WORD_OK;
4848 d->markMisspelledWords(first, last, result, word, skips);
4852 static docstring_list suggestions;
4853 pos_type to = endpos;
4854 while (start < endpos) {
4856 spellCheck(start, to, wl, suggestions, false);
4860 d->readySpellCheck();
4864 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4866 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4867 if (result || pos <= 0 || pos > size())
4869 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4870 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4875 string Paragraph::magicLabel() const
4878 ss << "magicparlabel-" << id();