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"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "output_docbook.h"
40 #include "ParagraphParameters.h"
42 #include "SpellChecker.h"
43 #include "texstream.h"
46 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetArgument.h"
53 #include "insets/InsetBibitem.h"
54 #include "insets/InsetLabel.h"
55 #include "insets/InsetSpecialChar.h"
56 #include "insets/InsetText.h"
58 #include "mathed/InsetMathHull.h"
60 #include "support/debug.h"
61 #include "support/docstring_list.h"
62 #include "support/ExceptionMessage.h"
63 #include "support/gettext.h"
64 #include "support/lassert.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
73 using namespace lyx::support;
75 // OSX clang and msvc < 2015 do not support C++11 thread_local
76 #if defined(__APPLE__)
77 #define THREAD_LOCAL_STATIC static __thread
78 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
79 #define THREAD_LOCAL_STATIC static __declspec(thread)
81 #define THREAD_LOCAL_STATIC thread_local static
86 /////////////////////////////////////////////////////////////////////
90 /////////////////////////////////////////////////////////////////////
92 class SpellResultRange {
94 SpellResultRange(FontSpan range, SpellChecker::Result result)
95 : range_(range), result_(result)
98 FontSpan const & range() const { return range_; }
100 void range(FontSpan const & r) { range_ = r; }
102 SpellChecker::Result result() const { return result_; }
104 void result(SpellChecker::Result r) { result_ = r; }
106 bool contains(pos_type pos) const { return range_.contains(pos); }
108 bool covered(FontSpan const & r) const
110 // 1. first of new range inside current range or
111 // 2. last of new range inside current range or
112 // 3. first of current range inside new range or
113 // 4. last of current range inside new range
114 //FIXME: is this the same as !range_.intersect(r).empty() ?
115 return range_.contains(r.first) || range_.contains(r.last) ||
116 r.contains(range_.first) || r.contains(range_.last);
119 void shift(pos_type pos, int offset)
121 if (range_.first > pos) {
122 range_.first += offset;
123 range_.last += offset;
124 } else if (range_.last >= pos) {
125 range_.last += offset;
130 SpellChecker::Result result_ ;
134 /////////////////////////////////////////////////////////////////////
138 /////////////////////////////////////////////////////////////////////
140 class SpellCheckerState {
144 needs_refresh_ = true;
145 current_change_number_ = 0;
148 void setRange(FontSpan const & fp, SpellChecker::Result state)
151 RangesIterator et = ranges_.end();
152 RangesIterator it = ranges_.begin();
153 for (; it != et; ++it) {
154 if (!it->covered(fp))
155 result.push_back(SpellResultRange(it->range(), it->result()));
156 else if (state == SpellChecker::WORD_OK) {
157 // trim or split the current misspelled range
158 // store misspelled ranges only
159 FontSpan range = it->range();
160 if (fp.first > range.first) {
161 // misspelled area in front of WORD_OK
162 range.last = fp.first - 1;
163 result.push_back(SpellResultRange(range, it->result()));
166 if (fp.last < range.last) {
167 // misspelled area after WORD_OK range
168 range.first = fp.last + 1;
169 result.push_back(SpellResultRange(range, it->result()));
174 if (state != SpellChecker::WORD_OK)
175 ranges_.push_back(SpellResultRange(fp, state));
178 void increasePosAfterPos(pos_type pos)
180 correctRangesAfterPos(pos, 1);
184 void decreasePosAfterPos(pos_type pos)
186 correctRangesAfterPos(pos, -1);
190 void refreshLast(pos_type pos)
192 if (pos < refresh_.last)
196 SpellChecker::Result getState(pos_type pos) const
198 SpellChecker::Result result = SpellChecker::WORD_OK;
199 RangesIterator et = ranges_.end();
200 RangesIterator it = ranges_.begin();
201 for (; it != et; ++it) {
202 if(it->contains(pos)) {
209 FontSpan const & getRange(pos_type pos) const
211 /// empty span to indicate mismatch
212 static FontSpan empty_;
213 RangesIterator et = ranges_.end();
214 RangesIterator it = ranges_.begin();
215 for (; it != et; ++it) {
216 if(it->contains(pos)) {
223 bool needsRefresh() const
225 return needs_refresh_;
228 SpellChecker::ChangeNumber currentChangeNumber() const
230 return current_change_number_;
233 void refreshRange(pos_type & first, pos_type & last) const
235 first = refresh_.first;
236 last = refresh_.last;
239 void needsRefresh(pos_type pos)
241 if (needs_refresh_ && pos != -1) {
242 if (pos < refresh_.first)
243 refresh_.first = pos;
244 if (pos > refresh_.last)
246 } else if (pos != -1) {
247 // init request check for neighbour positions too
248 refresh_.first = pos > 0 ? pos - 1 : 0;
249 // no need for special end of paragraph check
250 refresh_.last = pos + 1;
252 needs_refresh_ = pos != -1;
255 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
257 needs_refresh_ = true;
260 current_change_number_ = change_number;
263 typedef vector<SpellResultRange> Ranges;
264 typedef Ranges::const_iterator RangesIterator;
266 /// the area of the paragraph with pending spell check
268 /// spell state cache version number
269 SpellChecker::ChangeNumber current_change_number_;
273 void correctRangesAfterPos(pos_type pos, int offset)
275 RangesIterator et = ranges_.end();
276 Ranges::iterator it = ranges_.begin();
277 for (; it != et; ++it) {
278 it->shift(pos, offset);
284 /////////////////////////////////////////////////////////////////////
286 // Paragraph::Private
288 /////////////////////////////////////////////////////////////////////
290 class Paragraph::Private
292 // Enforce our own "copy" constructor
293 Private(Private const &) = delete;
294 Private & operator=(Private const &) = delete;
295 // Unique ID generator
296 static int make_id();
299 Private(Paragraph * owner, Layout const & layout);
300 /// "Copy constructor"
301 Private(Private const &, Paragraph * owner);
302 /// Copy constructor from \p beg to \p end
303 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
306 void insertChar(pos_type pos, char_type c, Change const & change);
308 /// Output the surrogate pair formed by \p c and \p next to \p os.
309 /// \return the number of characters written.
310 int latexSurrogatePair(BufferParams const &, otexstream & os,
311 char_type c, char_type next,
312 OutputParams const &) const;
314 /// Output a space in appropriate formatting (or a surrogate pair
315 /// if the next character is a combining character).
316 /// \return whether a surrogate pair was output.
317 bool simpleTeXBlanks(BufferParams const &,
318 OutputParams const &,
321 unsigned int & column,
323 Layout const & style) const;
325 /// This could go to ParagraphParameters if we want to.
326 int startTeXParParams(BufferParams const &, otexstream &,
327 OutputParams const &) const;
329 /// This could go to ParagraphParameters if we want to.
330 bool endTeXParParams(BufferParams const &, otexstream &,
331 OutputParams const &) const;
334 void latexInset(BufferParams const &,
339 Font const & outerfont,
341 Change & running_change,
342 Layout const & style,
344 unsigned int & column,
345 bool const fontswitch_inset,
346 bool const closeLanguage,
347 bool const lang_switched_at_inset) const;
350 void latexSpecialChar(
352 BufferParams const & bparams,
353 OutputParams const & runparams,
354 Font const & running_font,
355 string & alien_script,
356 Layout const & style,
359 unsigned int & column) const;
366 unsigned int & column) const;
372 unsigned int & column) const;
378 unsigned int & column) const;
381 void validate(LaTeXFeatures & features) const;
383 /// Checks if the paragraph contains only text and no inset or font change.
384 bool onlyText(Buffer const & buf, Font const & outerfont,
385 pos_type initial) const;
387 /// a vector of speller skip positions
388 typedef vector<FontSpan> SkipPositions;
389 typedef SkipPositions::const_iterator SkipPositionsIterator;
391 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
393 Language * getSpellLanguage(pos_type const from) const;
395 Language * locateSpellRange(pos_type & from, pos_type & to,
396 SkipPositions & skips) const;
398 bool hasSpellerChange() const
400 SpellChecker::ChangeNumber speller_change_number = 0;
401 if (theSpellChecker())
402 speller_change_number = theSpellChecker()->changeNumber();
403 return speller_change_number > speller_state_.currentChangeNumber();
406 bool ignoreWord(docstring const & word) const;
408 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
410 pos_type textsize = owner_->size();
411 // check for sane arguments
412 if (to <= from || from >= textsize)
414 FontSpan fp = FontSpan(from, to - 1);
415 speller_state_.setRange(fp, state);
418 void requestSpellCheck(pos_type pos)
421 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
423 speller_state_.needsRefresh(pos);
426 void readySpellCheck()
428 speller_state_.needsRefresh(-1);
431 bool needsSpellCheck() const
433 return speller_state_.needsRefresh();
436 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
438 speller_state_.refreshRange(first, last);
440 last = owner_->size();
443 pos_type endpos = last;
444 owner_->locateWord(first, endpos, WHOLE_WORD, true);
447 owner_->locateWord(last, endpos, WHOLE_WORD, true);
452 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
456 while (it != et && it->first < start) {
457 long skip = it->last - it->first + 1;
465 void markMisspelledWords(Language const * lang,
466 pos_type const & first, pos_type const & last,
467 SpellChecker::Result result,
468 docstring const & word,
469 SkipPositions const & skips);
471 InsetCode ownerCode() const
473 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
476 /// Which Paragraph owns us?
480 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<string, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
514 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
515 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
522 int Paragraph::Private::make_id()
524 // The id is unique per session across buffers because it is used in
525 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
528 static int next_id(0);
533 Paragraph::Private::Private(Private const & p, Paragraph * owner)
534 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
535 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
536 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
537 layout_(p.layout_), id_(make_id())
539 requestSpellCheck(p.text_.size());
543 Paragraph::Private::Private(Private const & p, Paragraph * owner,
544 pos_type beg, pos_type end)
545 : owner_(owner), inset_owner_(p.inset_owner_),
546 params_(p.params_), changes_(p.changes_),
547 insetlist_(p.insetlist_, beg, end),
548 begin_of_body_(p.begin_of_body_), words_(p.words_),
549 layout_(p.layout_), id_(make_id())
551 if (beg >= pos_type(p.text_.size()))
553 text_ = p.text_.substr(beg, end - beg);
555 FontList::const_iterator fcit = fontlist_.begin();
556 FontList::const_iterator fend = fontlist_.end();
557 for (; fcit != fend; ++fcit) {
558 if (fcit->pos() < beg)
560 if (fcit->pos() >= end) {
561 // Add last entry in the fontlist_.
562 fontlist_.set(text_.size() - 1, fcit->font());
565 // Add a new entry in the fontlist_.
566 fontlist_.set(fcit->pos() - beg, fcit->font());
568 requestSpellCheck(p.text_.size());
572 /////////////////////////////////////////////////////////////////////
576 /////////////////////////////////////////////////////////////////////
580 /** This helper class should be instantiated at the start of methods
581 * that can create or merge changes. If as a result the value of
582 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
585 struct ChangesMonitor {
587 ChangesMonitor(Paragraph & par)
588 : par_(par), was_changed_(par.isChanged()) {}
592 /* We may need to run updateBuffer to check whether the buffer
593 * contains changes (and toggle the changes toolbar). We do it
595 * 1. the `changedness' of the paragraph has changed,
596 * 2. and we are not in the situation where the buffer has changes
597 * and new changes are added to the paragraph.
600 if (par_.isChanged() != was_changed_
601 && par_.inInset().isBufferValid()
602 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
603 par_.inInset().buffer().forceUpdate();
604 } catch(support::ExceptionMessage const &) {}
609 Paragraph const & par_;
616 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
617 bool output_active, TocBackend & backend) const
619 d->changes_.addToToc(cdit, buf, output_active, backend);
623 bool Paragraph::isDeleted(pos_type start, pos_type end) const
625 LASSERT(start >= 0 && start <= size(), return false);
626 LASSERT(end > start && end <= size() + 1, return false);
628 return d->changes_.isDeleted(start, end);
632 bool Paragraph::isChanged(pos_type start, pos_type end) const
634 LASSERT(start >= 0 && start <= size(), return false);
635 LASSERT(end > start && end <= size() + 1, return false);
637 return d->changes_.isChanged(start, end);
640 // FIXME: Ideally the diverse isChanged() methods should account for that!
641 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
643 LASSERT(start >= 0 && start <= size(), return false);
644 LASSERT(end > start && end <= size() + 1, return false);
646 for (auto const & icit : d->insetlist_) {
647 if (icit.pos < start)
651 if (icit.inset && icit.inset->isChanged())
657 bool Paragraph::isChanged() const
659 return d->changes_.isChanged();
663 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
665 // keep the logic here in sync with the logic of eraseChars()
669 Change const & change = d->changes_.lookup(size());
670 return change.inserted() && change.currentAuthor();
673 Change Paragraph::parEndChange() const
675 return d->changes_.lookup(size());
679 void Paragraph::setChange(Change const & change)
681 // Make sure that Buffer::hasChangesPresent is updated
682 ChangesMonitor cm(*this);
684 // beware of the imaginary end-of-par character!
685 d->changes_.set(change, 0, size() + 1);
688 * Propagate the change recursively - but not in case of DELETED!
690 * Imagine that your co-author makes changes in an existing inset. He
691 * sends your document to you and you come to the conclusion that the
692 * inset should go completely. If you erase it, LyX must not delete all
693 * text within the inset. Otherwise, the change tracked insertions of
694 * your co-author get lost and there is no way to restore them later.
696 * Conclusion: An inset's content should remain untouched if you delete it
699 if (!change.deleted()) {
700 for (pos_type pos = 0; pos < size(); ++pos) {
701 if (Inset * inset = getInset(pos))
702 inset->setChange(change);
708 void Paragraph::setChange(pos_type pos, Change const & change)
710 // Make sure that Buffer::hasChangesPresent is updated
711 ChangesMonitor cm(*this);
713 LASSERT(pos >= 0 && pos <= size(), return);
714 d->changes_.set(change, pos);
716 // see comment in setChange(Change const &) above
717 if (!change.deleted() && pos < size())
718 if (Inset * inset = getInset(pos))
719 inset->setChange(change);
723 Change const & Paragraph::lookupChange(pos_type pos) const
725 LBUFERR(pos >= 0 && pos <= size());
726 return d->changes_.lookup(pos);
730 void Paragraph::acceptChanges(pos_type start, pos_type end)
732 // Make sure that Buffer::hasChangesPresent is updated
733 ChangesMonitor cm(*this);
735 LASSERT(start >= 0 && start <= size(), return);
736 LASSERT(end > start && end <= size() + 1, return);
738 for (pos_type pos = start; pos < end; ++pos) {
739 switch (lookupChange(pos).type) {
740 case Change::UNCHANGED:
741 // accept changes in nested inset
742 if (Inset * inset = getInset(pos))
743 inset->acceptChanges();
746 case Change::INSERTED:
747 d->changes_.set(Change(Change::UNCHANGED), pos);
748 // also accept changes in nested inset
749 if (Inset * inset = getInset(pos))
750 inset->acceptChanges();
753 case Change::DELETED:
754 // Suppress access to non-existent
755 // "end-of-paragraph char"
757 eraseChar(pos, false);
768 void Paragraph::rejectChanges(pos_type start, pos_type end)
770 LASSERT(start >= 0 && start <= size(), return);
771 LASSERT(end > start && end <= size() + 1, return);
773 // Make sure that Buffer::hasChangesPresent is updated
774 ChangesMonitor cm(*this);
776 for (pos_type pos = start; pos < end; ++pos) {
777 switch (lookupChange(pos).type) {
778 case Change::UNCHANGED:
779 // reject changes in nested inset
780 if (Inset * inset = getInset(pos))
781 inset->rejectChanges();
784 case Change::INSERTED:
785 // Suppress access to non-existent
786 // "end-of-paragraph char"
788 eraseChar(pos, false);
794 case Change::DELETED:
795 d->changes_.set(Change(Change::UNCHANGED), pos);
797 // Do NOT reject changes within a deleted inset!
798 // There may be insertions of a co-author inside of it!
806 void Paragraph::Private::insertChar(pos_type pos, char_type c,
807 Change const & change)
809 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
811 // Make sure that Buffer::hasChangesPresent is updated
812 ChangesMonitor cm(*owner_);
815 changes_.insert(change, pos);
817 // This is actually very common when parsing buffers (and
818 // maybe inserting ascii text)
819 if (pos == pos_type(text_.size())) {
820 // when appending characters, no need to update tables
822 // but we want spell checking
823 requestSpellCheck(pos);
827 text_.insert(text_.begin() + pos, c);
829 // Update the font table.
830 fontlist_.increasePosAfterPos(pos);
833 insetlist_.increasePosAfterPos(pos);
835 // Update list of misspelled positions
836 speller_state_.increasePosAfterPos(pos);
839 if (inset_owner_ && inset_owner_->isBufferValid())
840 theSession().bookmarks().adjustPosAfterPos(inset_owner_->buffer().fileName(),
845 bool Paragraph::insertInset(pos_type pos, Inset * inset,
846 Font const & font, Change const & change)
848 LASSERT(inset, return false);
849 LASSERT(pos >= 0 && pos <= size(), return false);
851 // Make sure that Buffer::hasChangesPresent is updated
852 ChangesMonitor cm(*this);
854 // Paragraph::insertInset() can be used in cut/copy/paste operation where
855 // d->inset_owner_ is not set yet.
856 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
859 d->insertChar(pos, META_INSET, change);
860 LASSERT(d->text_[pos] == META_INSET, return false);
862 // Add a new entry in the insetlist_.
863 d->insetlist_.insert(inset, pos);
865 // Some insets require run of spell checker
866 requestSpellCheck(pos);
872 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
874 LASSERT(pos >= 0 && pos <= size(), return false);
876 // Make sure that Buffer::hasChangesPresent is updated
877 ChangesMonitor cm(*this);
879 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
882 Change change = d->changes_.lookup(pos);
884 // set the character to DELETED if
885 // a) it was previously unchanged or
886 // b) it was inserted by a co-author
888 if (!change.changed() ||
889 (change.inserted() && !change.currentAuthor())) {
890 setChange(pos, Change(Change::DELETED));
891 // request run of spell checker
892 requestSpellCheck(pos);
896 if (change.deleted())
900 // Don't physically access the imaginary end-of-paragraph character.
901 // eraseChar() can only mark it as DELETED. A physical deletion of
902 // end-of-par must be handled externally.
908 d->changes_.erase(pos);
910 // if it is an inset, delete the inset entry
911 if (d->text_[pos] == META_INSET)
912 d->insetlist_.erase(pos);
914 d->text_.erase(d->text_.begin() + pos);
916 // Update the fontlist_
917 d->fontlist_.erase(pos);
919 // Update the insetlist_
920 d->insetlist_.decreasePosAfterPos(pos);
922 // Update list of misspelled positions
923 d->speller_state_.decreasePosAfterPos(pos);
924 d->speller_state_.refreshLast(size());
927 if (d->inset_owner_ && d->inset_owner_->isBufferValid())
928 theSession().bookmarks().adjustPosAfterPos(d->inset_owner_->buffer().fileName(),
935 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
937 LASSERT(start >= 0 && start <= size(), return 0);
938 LASSERT(end >= start && end <= size() + 1, return 0);
941 for (pos_type count = end - start; count; --count) {
942 if (!eraseChar(i, trackChanges))
949 // Handle combining characters
950 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
951 otexstream & os, char_type c, char_type next,
952 OutputParams const & runparams) const
954 // Writing next here may circumvent a possible font change between
955 // c and next. Since next is only output if it forms a surrogate pair
956 // with c we can ignore this:
957 // A font change inside a surrogate pair does not make sense and is
958 // hopefully impossible to input.
959 // FIXME: change tracking
960 // Is this correct WRT change tracking?
961 Encoding const & encoding = *(runparams.encoding);
962 docstring latex1 = encoding.latexChar(next).first;
963 if (runparams.inIPA) {
964 string const tipashortcut = Encodings::TIPAShortcut(next);
965 if (!tipashortcut.empty()) {
966 latex1 = from_ascii(tipashortcut);
969 docstring latex2 = encoding.latexChar(c).first;
971 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
972 // Encoding supports the combination:
973 // output as is (combining char after base char).
974 os << latex2 << latex1;
975 return latex1.length() + latex2.length();
978 os << latex1 << "{" << latex2 << "}";
979 return latex1.length() + latex2.length() + 2;
983 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
984 OutputParams const & runparams,
987 unsigned int & column,
989 Layout const & style) const
991 if (style.pass_thru || runparams.pass_thru)
994 if (i + 1 < int(text_.size())) {
995 char_type next = text_[i + 1];
996 if (Encodings::isCombiningChar(next)) {
997 // This space has an accent, so we must always output it.
998 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
1003 if (runparams.linelen > 0
1004 && column > runparams.linelen
1006 && text_[i - 1] != ' '
1007 && (i + 1 < int(text_.size()))
1008 // same in FreeSpacing mode
1009 && !owner_->isFreeSpacing()
1010 // In typewriter mode, we want to avoid
1011 // ! . ? : at the end of a line
1012 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1013 && (text_[i - 1] == '.'
1014 || text_[i - 1] == '?'
1015 || text_[i - 1] == ':'
1016 || text_[i - 1] == '!'))) {
1018 os.texrow().start(owner_->id(), i + 1);
1020 } else if (style.free_spacing) {
1029 void Paragraph::Private::latexInset(BufferParams const & bparams,
1031 OutputParams & runparams,
1032 Font & running_font,
1034 Font const & outerfont,
1036 Change & running_change,
1037 Layout const & style,
1039 unsigned int & column,
1040 bool const fontswitch_inset,
1041 bool const closeLanguage,
1042 bool const lang_switched_at_inset) const
1044 Inset * inset = owner_->getInset(i);
1047 if (style.pass_thru) {
1048 odocstringstream ods;
1049 inset->plaintext(ods, runparams);
1054 // FIXME: move this to InsetNewline::latex
1055 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1056 // newlines are handled differently here than
1057 // the default in simpleTeXSpecialChars().
1058 if (!style.newline_allowed) {
1062 bool needPar = false;
1063 column += running_font.latexWriteEndChanges(
1064 os, bparams, runparams,
1065 basefont, basefont, needPar);
1069 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1072 basefont = owner_->getLayoutFont(bparams, outerfont);
1073 running_font = basefont;
1075 if (runparams.moving_arg)
1079 os.texrow().start(owner_->id(), i + 1);
1083 if (owner_->isDeleted(i)) {
1084 if( ++runparams.inDeletedInset == 1)
1085 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1088 if (inset->canTrackChanges()) {
1089 column += Changes::latexMarkChange(os, bparams, running_change,
1090 Change(Change::UNCHANGED), runparams);
1091 running_change = Change(Change::UNCHANGED);
1094 unsigned int close_brace = 0;
1095 bool const disp_env = (inset->isEnvironment() && inset->getLayout().isDisplay())
1096 || runparams.inDisplayMath;
1098 odocstream::pos_type const len = os.os().tellp();
1100 if (inset->forceLTR(runparams)
1101 // babel with Xe/LuaTeX does not need a switch
1102 // and \L is not defined there.
1103 && (!runparams.isFullUnicode() || !runparams.use_babel)
1104 && running_font.isRightToLeft()) {
1105 if (runparams.use_polyglossia) {
1107 // Displayed environments go in an LTR environment
1109 os << "\\begin{LTR}";
1112 if (runparams.flavor == Flavor::LuaTeX) {
1113 // luabidi's \LRE needs extra grouping
1114 // (possibly a LuaTeX bug)
1121 } else if (running_font.language()->lang() == "farsi"
1122 || running_font.language()->lang() == "arabic_arabi") {
1123 os << "\\textLR{" << termcmd;
1134 if (open_font && fontswitch_inset) {
1135 bool lang_closed = false;
1136 // Close language if needed
1137 if (closeLanguage && !lang_switched_at_inset) {
1138 // We need prev_font here as language changes directly at inset
1139 // will only be started inside the inset.
1140 Font const prev_font = (i > 0) ?
1141 owner_->getFont(bparams, i - 1, outerfont)
1143 Font tmpfont(basefont);
1144 tmpfont.setLanguage(prev_font.language());
1145 bool needPar = false;
1146 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1148 needPar, closeLanguage);
1150 lang_closed = count > 0;
1152 // Update the running_font, making sure, however,
1153 // to leave the language as it was.
1154 // FIXME: probably a better way to keep track of the old
1155 // language, than copying the entire font?
1156 Font const copy_font(running_font);
1157 basefont = owner_->getLayoutFont(bparams, outerfont);
1158 running_font = basefont;
1160 running_font.setLanguage(copy_font.language());
1161 OutputParams rp = runparams;
1162 rp.encoding = basefont.language()->encoding();
1163 // For these, we use switches, so they should be taken as
1164 // base inside the inset.
1165 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1166 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1167 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1168 // Now re-do font changes in a way needed here
1169 // (using switches with multi-par insets)
1170 InsetText const * textinset = inset->asInsetText();
1171 bool const cprotect = textinset
1172 ? textinset->hasCProtectContent(runparams.moving_arg)
1173 && !textinset->text().isMainText()
1174 && inset->lyxCode() != BRANCH_CODE
1176 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1182 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1186 runparams.local_font = &basefont;
1189 if (fontswitch_inset && !closeLanguage) {
1190 // The directionality has been switched at inset.
1191 // Force markup inside.
1192 runparams.local_font = &basefont;
1195 size_t const previous_row_count = os.texrow().rows();
1198 runparams.lastid = id_;
1199 runparams.lastpos = i;
1200 inset->latex(os, runparams);
1201 } catch (EncodingException & e) {
1202 // add location information and throw again.
1208 if (!close_env.empty())
1209 os << "\\end{" << close_env << "}";
1211 if (close_brace > 0) {
1212 for (unsigned i = 0; i < close_brace; ++i)
1218 if (os.texrow().rows() > previous_row_count) {
1219 os.texrow().start(owner_->id(), i + 1);
1222 column += (unsigned int)(os.os().tellp() - len);
1225 if (owner_->isDeleted(i))
1226 --runparams.inDeletedInset;
1230 void Paragraph::Private::latexSpecialChar(otexstream & os,
1231 BufferParams const & bparams,
1232 OutputParams const & runparams,
1233 Font const & running_font,
1234 string & alien_script,
1235 Layout const & style,
1238 unsigned int & column) const
1240 char_type const c = owner_->getUChar(bparams, runparams, i);
1242 if (style.pass_thru || runparams.pass_thru || runparams.find_effective()
1243 || contains(style.pass_thru_chars, c)
1244 || contains(runparams.pass_thru_chars, c)) {
1245 if (runparams.find_effective()) {
1251 os << "\\braceleft ";
1254 os << "\\braceright ";
1257 os << "\\lyxdollar ";
1260 os << "\\lyxtilde ";
1270 else if (c != '\0') {
1271 Encoding const * const enc = runparams.encoding;
1272 if (enc && !enc->encodable(c))
1273 throw EncodingException(c);
1279 // TIPA uses its own T3 encoding
1280 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1282 // If T1 font encoding is used, use the special
1283 // characters it provides.
1284 // NOTE: Some languages reset the font encoding internally to a
1285 // non-standard font encoding. If we are using such a language,
1286 // we do not output special T1 chars.
1287 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1288 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1289 && latexSpecialT1(c, os, i, column))
1291 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1292 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1293 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1296 // Otherwise, we use what LaTeX provides us.
1299 os << "\\textbackslash" << termcmd;
1303 os << "\\textless" << termcmd;
1307 os << "\\textgreater" << termcmd;
1311 os << "\\textbar" << termcmd;
1316 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1317 (end_pos == -1 || i + 1 < end_pos) &&
1318 text_[i+1] == '-') {
1319 // Prevent "--" becoming an en dash and "---" an em dash.
1320 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1326 os << "\\textquotedbl" << termcmd;
1331 case '%': case '#': case '{':
1339 os << "\\textasciitilde" << termcmd;
1344 os << "\\textasciicircum" << termcmd;
1351 // avoid being mistaken for optional arguments
1359 // Blanks are printed before font switching.
1360 // Sure? I am not! (try nice-latex)
1361 // I am sure it's correct. LyX might be smarter
1362 // in the future, but for now, nothing wrong is
1368 // XeTeX's dash behaviour is determined via a global setting
1369 if (bparams.use_dash_ligatures
1370 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1372 // TODO #10961: && not in inset Flex Code
1373 // TODO #10961: && not in layout LyXCode
1374 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1391 Encoding const & encoding = *(runparams.encoding);
1392 char_type next = '\0';
1393 if (i + 1 < int(text_.size())) {
1394 next = text_[i + 1];
1395 if (Encodings::isCombiningChar(next)) {
1396 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1401 pair<docstring, bool> latex = encoding.latexChar(c);
1402 docstring nextlatex;
1403 bool nexttipas = false;
1404 string nexttipashortcut;
1405 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1406 nextlatex = encoding.latexChar(next).first;
1407 if (runparams.inIPA) {
1408 nexttipashortcut = Encodings::TIPAShortcut(next);
1409 nexttipas = !nexttipashortcut.empty();
1413 if (runparams.inIPA) {
1414 string const tipashortcut = Encodings::TIPAShortcut(c);
1415 if (!tipashortcut.empty()) {
1416 latex.first = from_ascii(tipashortcut);
1417 latex.second = false;
1421 // eventually close "script wrapper" command (see `Paragraph::latex`)
1422 if (!alien_script.empty()
1423 && alien_script != Encodings::isKnownScriptChar(next)) {
1424 column += latex.first.length();
1425 alien_script.clear();
1426 os << latex.first << "}";
1430 && ((!prefixIs(nextlatex, '\\')
1431 && !prefixIs(nextlatex, '{')
1432 && !prefixIs(nextlatex, '}'))
1434 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1436 // Prevent eating of a following space or command corruption by
1437 // following characters
1438 if (next == ' ' || next == '\0') {
1439 column += latex.first.length() + 1;
1440 os << latex.first << "{}";
1442 column += latex.first.length();
1443 os << latex.first << " ";
1446 column += latex.first.length() - 1;
1454 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1455 pos_type i, unsigned int & column) const
1461 // In T1 encoding, these characters exist
1462 // but we should avoid ligatures
1463 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1465 os << "\\textcompwordmark" << termcmd;
1472 // soul.sty breaks with \char`\"
1473 os << "\\textquotedbl" << termcmd;
1482 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1483 pos_type i, unsigned int & column) const
1485 // TU encoding is currently on par with T1.
1486 return latexSpecialT1(c, os, i, column);
1490 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1491 pos_type /*i*/, unsigned int & column) const
1501 os << "\\textvertline" << termcmd;
1510 void Paragraph::Private::validate(LaTeXFeatures & features) const
1512 if (layout_->inpreamble && inset_owner_) {
1513 // FIXME: Using a string stream here circumvents the encoding
1514 // switching machinery of odocstream. Therefore the
1515 // output is wrong if this paragraph contains content
1516 // that needs to switch encoding.
1517 Buffer const & buf = inset_owner_->buffer();
1518 otexstringstream os;
1519 os << layout_->preamble();
1520 size_t const length = os.length();
1521 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1522 buf.getParFromID(owner_->id()).pit(), os,
1523 features.runparams(), string(), 0, -1, true);
1524 if (os.length() > length)
1525 features.addPreambleSnippet(os.release(), true);
1528 if (features.runparams().flavor == Flavor::Html
1529 && layout_->htmltitle()) {
1530 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1533 // check the params.
1534 if (!params_.spacing().isDefault())
1535 features.require("setspace");
1538 features.useLayout(layout_->name());
1541 fontlist_.validate(features);
1543 // then the indentation
1544 if (!params_.leftIndent().zero())
1545 features.require("ParagraphLeftIndent");
1548 InsetList::const_iterator icit = insetlist_.begin();
1549 InsetList::const_iterator iend = insetlist_.end();
1550 for (; icit != iend; ++icit) {
1552 features.inDeletedInset(owner_->isDeleted(icit->pos));
1553 if (icit->inset->lyxCode() == FOOT_CODE) {
1554 // FIXME: an item inset would make things much easier.
1555 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1556 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1557 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1558 && (icit->pos < begin_of_body_
1559 || (icit->pos == begin_of_body_
1560 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1561 features.saveNoteEnv("description");
1563 icit->inset->validate(features);
1564 features.inDeletedInset(false);
1565 if (layout_->needprotect &&
1566 icit->inset->lyxCode() == FOOT_CODE)
1567 features.require("NeedLyXFootnoteCode");
1571 // then the contents
1572 BufferParams const bp = features.runparams().is_child
1573 ? features.buffer().masterParams() : features.buffer().params();
1574 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1575 char_type c = text_[i];
1576 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1578 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1579 features.require("textquotedblp");
1580 else if (features.runparams().main_fontenc != "T1"
1581 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1582 features.require("textquotedbl");
1583 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1584 // features that depend on the font or input encoding
1585 string feats = ci.textPreamble();
1586 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1587 if (fontenc.empty())
1588 fontenc = features.runparams().main_fontenc;
1589 while (!feats.empty()) {
1591 feats = split(feats, feat, ',');
1592 if (contains(feat, "!=")) {
1593 // a feature that is required except for the spcified
1594 // font or input encodings
1596 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1597 // multiple encodings are separated by semicolon
1598 vector<string> context = getVectorFromString(contexts, ";");
1599 // require feature if the context matches neither current font
1600 // nor input encoding
1601 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1602 && std::find(context.begin(), context.end(),
1603 features.runparams().encoding->name()) == context.end())
1604 features.require(realfeature);
1605 } else if (contains(feat, '=')) {
1606 // a feature that is required only for the spcified
1607 // font or input encodings
1609 string const contexts = split(feat, realfeature, '=');
1610 // multiple encodings are separated by semicolon
1611 vector<string> context = getVectorFromString(contexts, ";");
1612 // require feature if the context matches either current font
1613 // or input encoding
1614 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1615 || std::find(context.begin(), context.end(),
1616 features.runparams().encoding->name()) != context.end())
1617 features.require(realfeature);
1620 } else if (!bp.use_dash_ligatures
1621 && (c == 0x2013 || c == 0x2014)
1622 && bp.useNonTeXFonts
1623 && features.runparams().flavor == Flavor::XeTeX)
1624 // XeTeX's dash behaviour is determined via a global setting
1625 features.require("xetexdashbreakstate");
1626 BufferEncodings::validate(c, features);
1630 /////////////////////////////////////////////////////////////////////
1634 /////////////////////////////////////////////////////////////////////
1637 Layout const emptyParagraphLayout;
1640 Paragraph::Paragraph()
1641 : d(new Paragraph::Private(this, emptyParagraphLayout))
1648 Paragraph::Paragraph(Paragraph const & par)
1649 : itemdepth(par.itemdepth),
1650 d(new Paragraph::Private(*par.d, this))
1656 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1657 : itemdepth(par.itemdepth),
1658 d(new Paragraph::Private(*par.d, this, beg, end))
1664 Paragraph & Paragraph::operator=(Paragraph const & par)
1666 // needed as we will destroy the private part before copying it
1668 itemdepth = par.itemdepth;
1672 d = new Private(*par.d, this);
1679 Paragraph::~Paragraph()
1688 // this shall be called just before every "os << ..." action.
1689 void flushString(ostream & os, docstring & s)
1698 void Paragraph::write(ostream & os, BufferParams const & bparams,
1699 depth_type & depth) const
1701 // The beginning or end of a deeper (i.e. nested) area?
1702 if (depth != d->params_.depth()) {
1703 if (d->params_.depth() > depth) {
1704 while (d->params_.depth() > depth) {
1705 os << "\n\\begin_deeper";
1709 while (d->params_.depth() < depth) {
1710 os << "\n\\end_deeper";
1716 // First write the layout
1717 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1719 d->params_.write(os);
1721 Font font1(inherit_font, bparams.language);
1723 Change running_change = Change(Change::UNCHANGED);
1725 // this string is used as a buffer to avoid repetitive calls
1726 // to to_utf8(), which turn out to be expensive (JMarc)
1727 docstring write_buffer;
1730 for (pos_type i = 0; i <= size(); ++i) {
1732 Change const & change = lookupChange(i);
1733 if (change != running_change)
1734 flushString(os, write_buffer);
1735 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1736 running_change = change;
1741 // Write font changes
1742 Font font2 = getFontSettings(bparams, i);
1743 if (font2 != font1) {
1744 flushString(os, write_buffer);
1745 font2.lyxWriteChanges(font1, os);
1750 char_type const c = d->text_[i];
1753 if (Inset const * inset = getInset(i)) {
1754 flushString(os, write_buffer);
1755 if (inset->directWrite()) {
1756 // international char, let it write
1757 // code directly so it's shorter in
1763 os << "\\begin_inset ";
1765 os << "\n\\end_inset\n\n";
1768 // FIXME This can be removed again once the mystery
1769 // crash has been resolved.
1774 flushString(os, write_buffer);
1775 os << "\n\\backslash\n";
1784 case 0x061F: // ؟ U+061F ARABIC QUESTION MARK
1785 case 0x061B: // ؛ U+061B ARABIC SEMICOLON
1786 case 0x060C: // ، U+060C ARABIC COMMA
1787 flushString(os, write_buffer);
1788 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1789 os << to_utf8(docstring(1, c)) << '\n';
1792 os << to_utf8(docstring(1, c));
1794 case 0x2014: // — U+2014 EM DASH
1795 case 0x3002: // 。 U+3002 IDEOGRAPHIC FULL STOP
1796 case 0xFF01: // ! U+FF01 FULLWIDTH EXCLAMATION MARK
1797 case 0xFF1F: // ? U+FF1F FULLWIDTH QUESTION MARK
1798 case 0xFF1A: // : U+FF1A FULLWIDTH COLON
1799 case 0xFF1B: // ; U+FF1B FULLWIDTH SEMICOLON
1800 case 0xFF0C: // , U+FF0C FULLWIDTH COMMA
1801 flushString(os, write_buffer);
1802 os << to_utf8(docstring(1, c)) << '\n';
1807 flushString(os, write_buffer);
1811 // this check is to amend a bug. LyX sometimes
1812 // inserts '\0' this could cause problems.
1814 write_buffer.push_back(c);
1816 LYXERR0("NUL char in structure.");
1822 flushString(os, write_buffer);
1823 os << "\n\\end_layout\n";
1824 // FIXME This can be removed again once the mystery
1825 // crash has been resolved.
1830 void Paragraph::validate(LaTeXFeatures & features) const
1832 d->validate(features);
1833 bool fragile = features.runparams().moving_arg;
1834 fragile |= layout().needprotect;
1835 if (inInset().getLayout().isNeedProtect())
1837 if (needsCProtection(fragile))
1838 features.require("cprotect");
1842 void Paragraph::insert(pos_type pos, docstring const & str,
1843 Font const & font, Change const & change)
1845 for (size_t i = 0, n = str.size(); i != n ; ++i)
1846 insertChar(pos + i, str[i], font, change);
1850 void Paragraph::appendChar(char_type c, Font const & font,
1851 Change const & change)
1853 // Make sure that Buffer::hasChangesPresent is updated
1854 ChangesMonitor cm(*this);
1857 d->changes_.insert(change, d->text_.size());
1858 // when appending characters, no need to update tables
1859 d->text_.push_back(c);
1860 setFont(d->text_.size() - 1, font);
1861 d->requestSpellCheck(d->text_.size() - 1);
1865 void Paragraph::appendString(docstring const & s, Font const & font,
1866 Change const & change)
1868 // Make sure that Buffer::hasChangesPresent is updated
1869 ChangesMonitor cm(*this);
1871 pos_type end = s.size();
1872 size_t oldsize = d->text_.size();
1873 size_t newsize = oldsize + end;
1874 size_t capacity = d->text_.capacity();
1875 if (newsize >= capacity)
1876 d->text_.reserve(max(capacity + 100, newsize));
1878 // when appending characters, no need to update tables
1881 // FIXME: Optimize this!
1882 for (size_t i = oldsize; i != newsize; ++i) {
1884 d->changes_.insert(change, i);
1885 d->requestSpellCheck(i);
1887 d->fontlist_.set(oldsize, font);
1888 d->fontlist_.set(newsize - 1, font);
1892 void Paragraph::insertChar(pos_type pos, char_type c,
1895 d->insertChar(pos, c, Change(trackChanges ?
1896 Change::INSERTED : Change::UNCHANGED));
1900 void Paragraph::insertChar(pos_type pos, char_type c,
1901 Font const & font, bool trackChanges)
1903 d->insertChar(pos, c, Change(trackChanges ?
1904 Change::INSERTED : Change::UNCHANGED));
1909 void Paragraph::insertChar(pos_type pos, char_type c,
1910 Font const & font, Change const & change)
1912 d->insertChar(pos, c, change);
1917 void Paragraph::resetFonts(Font const & font)
1919 d->fontlist_.clear();
1920 d->fontlist_.set(0, font);
1921 d->fontlist_.set(d->text_.size() - 1, font);
1924 // Gets uninstantiated font setting at position.
1925 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1929 LYXERR0("pos: " << pos << " size: " << size());
1933 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1934 if (cit != d->fontlist_.end())
1937 if (pos == size() && !empty())
1938 return getFontSettings(bparams, pos - 1);
1940 // Optimisation: avoid a full font instantiation if there is no
1941 // language change from previous call.
1942 static Font previous_font;
1943 static Language const * previous_lang = nullptr;
1944 Language const * lang = getParLanguage(bparams);
1945 if (lang != previous_lang) {
1946 previous_lang = lang;
1947 previous_font = Font(inherit_font, lang);
1949 return previous_font;
1953 FontSpan Paragraph::fontSpan(pos_type pos) const
1955 LBUFERR(pos <= size());
1958 return FontSpan(pos, pos);
1961 FontList::const_iterator cit = d->fontlist_.begin();
1962 FontList::const_iterator end = d->fontlist_.end();
1963 for (; cit != end; ++cit) {
1964 if (cit->pos() >= pos) {
1965 if (pos >= beginOfBody())
1966 return FontSpan(max(start, beginOfBody()),
1969 return FontSpan(start,
1970 min(beginOfBody() - 1,
1973 start = cit->pos() + 1;
1976 // This should not happen, but if so, we take no chances.
1977 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1978 LASSERT(false, /**/);
1979 return FontSpan(pos, pos);
1983 // Gets uninstantiated font setting at position 0
1984 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1986 if (!empty() && !d->fontlist_.empty())
1987 return d->fontlist_.begin()->font();
1989 // Optimisation: avoid a full font instantiation if there is no
1990 // language change from previous call.
1991 static Font previous_font;
1992 static Language const * previous_lang = nullptr;
1993 if (bparams.language != previous_lang) {
1994 previous_lang = bparams.language;
1995 previous_font = Font(inherit_font, bparams.language);
1998 return previous_font;
2002 // Gets the fully instantiated font at a given position in a paragraph
2003 // This is basically the same function as TextMetrics::displayFont().
2004 // The difference is that this one is used for generating the LaTeX file,
2005 // and thus cosmetic "improvements" are disallowed: This has to deliver
2006 // the true picture of the buffer. (Asger)
2007 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
2008 Font const & outerfont) const
2012 Font font = getFontSettings(bparams, pos);
2014 pos_type const body_pos = beginOfBody();
2015 FontInfo & fi = font.fontInfo();
2017 fi.realize(d->layout_->labelfont);
2019 fi.realize(d->layout_->font);
2021 fi.realize(outerfont.fontInfo());
2022 fi.realize(bparams.getFont().fontInfo());
2028 Font const Paragraph::getLabelFont
2029 (BufferParams const & bparams, Font const & outerfont) const
2031 FontInfo tmpfont = d->layout_->labelfont;
2032 tmpfont.realize(outerfont.fontInfo());
2033 tmpfont.realize(bparams.getFont().fontInfo());
2034 return Font(tmpfont, getParLanguage(bparams));
2038 Font const Paragraph::getLayoutFont
2039 (BufferParams const & bparams, Font const & outerfont) const
2041 FontInfo tmpfont = d->layout_->font;
2042 tmpfont.realize(outerfont.fontInfo());
2043 tmpfont.realize(bparams.getFont().fontInfo());
2044 return Font(tmpfont, getParLanguage(bparams));
2048 char_type Paragraph::getUChar(BufferParams const & bparams,
2049 OutputParams const & rp,
2052 char_type c = d->text_[pos];
2054 // Return unchanged character in LTR languages
2055 // or if we use poylglossia/bidi (XeTeX)
2056 // or with babel and Xe/LuaTeX.
2057 if (!getFontSettings(bparams, pos).isRightToLeft()
2058 || rp.useBidiPackage()
2059 || (rp.use_babel && rp.isFullUnicode()))
2062 // Without polyglossia/bidi, we need to account for some special cases.
2063 // FIXME This needs to be audited!
2065 // * The input is as expected for all delimiters
2066 // => checked for Hebrew!
2067 // * The output matches the display in the LyX workarea
2068 // => checked for Hebrew!
2069 // * The special cases below are really necessary
2070 // => checked for Hebrew!
2071 // * In arabic_arabi, brackets are transformed to Arabic
2072 // Ornate Parentheses. Is this is really wanted?
2074 string const & lang = getFontSettings(bparams, pos).language()->lang();
2077 // 1. In the following languages, parentheses need to be reversed.
2078 // Also with polyglodia/luabidi
2079 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2081 // 2. In the following languages, brackets don't need to be reversed.
2082 bool const reversebrackets = lang != "arabic_arabtex"
2083 && lang != "arabic_arabi"
2086 // Now swap delimiters if needed.
2097 if (reversebrackets)
2101 if (reversebrackets)
2122 void Paragraph::setFont(pos_type pos, Font const & font)
2124 LASSERT(pos <= size(), return);
2126 // Text::setCharFont() already reduces font against layout/label
2127 // font, so we don't need to do that here. (Asger)
2128 d->fontlist_.set(pos, font);
2132 void Paragraph::makeSameLayout(Paragraph const & par)
2134 d->layout_ = par.d->layout_;
2135 d->params_ = par.d->params_;
2139 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2141 if (isFreeSpacing())
2147 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2148 if (eraseChar(pos, trackChanges))
2154 return count > 0 || pos > 0;
2158 bool Paragraph::hasSameLayout(Paragraph const & par) const
2160 return par.d->layout_ == d->layout_
2161 && d->params_.sameLayout(par.d->params_);
2165 depth_type Paragraph::getDepth() const
2167 return d->params_.depth();
2171 depth_type Paragraph::getMaxDepthAfter() const
2173 if (d->layout_->isEnvironment())
2174 return d->params_.depth() + 1;
2176 return d->params_.depth();
2180 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2182 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2183 return getDefaultAlign(bparams);
2185 return d->params_.align();
2189 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2191 LyXAlignment res = layout().align;
2192 if (isRTL(bparams)) {
2194 if (res == LYX_ALIGN_LEFT)
2195 res = LYX_ALIGN_RIGHT;
2196 else if (res == LYX_ALIGN_RIGHT)
2197 res = LYX_ALIGN_LEFT;
2203 docstring const & Paragraph::labelString() const
2205 return d->params_.labelString();
2209 // the next two functions are for the manual labels
2210 docstring const Paragraph::getLabelWidthString() const
2212 if (d->layout_->margintype == MARGIN_MANUAL
2213 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2214 return d->params_.labelWidthString();
2216 return _("Senseless with this layout!");
2220 void Paragraph::setLabelWidthString(docstring const & s)
2222 d->params_.labelWidthString(s);
2226 docstring Paragraph::expandLabel(Layout const & layout,
2227 BufferParams const & bparams) const
2229 return expandParagraphLabel(layout, bparams, true);
2233 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2234 BufferParams const & bparams, bool process_appendix) const
2236 DocumentClass const & tclass = bparams.documentClass();
2237 string const & lang = getParLanguage(bparams)->code();
2238 bool const in_appendix = process_appendix && d->params_.appendix();
2239 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2241 if (fmt.empty() && !layout.counter.empty())
2242 return tclass.counters().theCounter(layout.counter, lang);
2244 // handle 'inherited level parts' in 'fmt',
2245 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2246 size_t const i = fmt.find('@', 0);
2247 if (i != docstring::npos) {
2248 size_t const j = fmt.find('@', i + 1);
2249 if (j != docstring::npos) {
2250 docstring parent(fmt, i + 1, j - i - 1);
2251 docstring label = from_ascii("??");
2252 if (tclass.hasLayout(parent))
2253 label = expandParagraphLabel(tclass[parent], bparams,
2255 fmt = docstring(fmt, 0, i) + label
2256 + docstring(fmt, j + 1, docstring::npos);
2260 return tclass.counters().counterLabel(fmt, lang);
2264 void Paragraph::applyLayout(Layout const & new_layout)
2266 d->layout_ = &new_layout;
2267 LyXAlignment const oldAlign = d->params_.align();
2269 if (!(oldAlign & d->layout_->alignpossible)) {
2270 frontend::Alert::warning(_("Alignment not permitted"),
2271 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2272 d->params_.align(LYX_ALIGN_LAYOUT);
2277 pos_type Paragraph::beginOfBody() const
2279 return d->begin_of_body_;
2283 void Paragraph::setBeginOfBody()
2285 if (d->layout_->labeltype != LABEL_MANUAL) {
2286 d->begin_of_body_ = 0;
2290 // Unroll the first two cycles of the loop
2291 // and remember the previous character to
2292 // remove unnecessary getChar() calls
2294 pos_type end = size();
2295 bool prev_char_deleted = false;
2296 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2299 char_type previous_char = d->text_[i];
2300 if (!(isNewline(i) || isEnvSeparator(i))) {
2302 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2303 char_type temp = d->text_[i];
2304 prev_char_deleted = isDeleted(i);
2305 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2308 previous_char = temp;
2314 d->begin_of_body_ = i;
2318 bool Paragraph::allowParagraphCustomization() const
2320 return inInset().allowParagraphCustomization();
2324 bool Paragraph::usePlainLayout() const
2326 return inInset().usePlainLayout();
2330 bool Paragraph::isPassThru() const
2332 return inInset().isPassThru() || d->layout_->pass_thru;
2336 bool Paragraph::parbreakIsNewline() const
2338 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2342 bool Paragraph::allowedInContext(Cursor const & cur, InsetLayout const & il) const
2344 set<docstring> const & allowed_insets = il.allowedInInsets();
2345 set<docstring> const & allowed_layouts = il.allowedInLayouts();
2347 bool in_allowed_inset =
2348 allowed_insets.find(inInset().getLayout().name()) != allowed_insets.end();
2350 bool in_allowed_layout =
2351 allowed_layouts.find(d->layout_->name()) != allowed_layouts.end();
2353 if (!in_allowed_inset && inInset().asInsetArgument()) {
2354 // check if the argument allows the inset in question
2355 if (cur.depth() > 1) {
2356 docstring parlayout = cur[cur.depth() - 2].inset().getLayout().name()
2357 + from_ascii("@") + from_ascii(inInset().asInsetArgument()->name());
2358 if (allowed_insets.find(parlayout) != allowed_insets.end())
2359 in_allowed_inset = true;
2364 // check if we exceed the number of allowed insets in this inset
2365 if (in_allowed_inset && inInset().asInsetText() && il.allowedOccurrences() != -1) {
2366 ParagraphList & pars = cur.text()->paragraphs();
2367 for (Paragraph const & par : pars) {
2368 for (auto const & table : par.insetList())
2369 if (table.inset->getLayout().name() == il.name())
2372 if (have_ins >= il.allowedOccurrences())
2377 // check if we exceed the number of allowed insets in the layout group
2378 if (in_allowed_layout && il.allowedOccurrences() != -1) {
2379 pit_type pit = cur.pit();
2380 pit_type lastpit = cur.pit();
2381 ParagraphList & pars = cur.text()->paragraphs();
2382 // If we are not on a list-type environment or AllowedOccurrencesPerItem
2383 // is false, we check the whole paragraph group
2384 if (d->layout_->isEnvironment()
2385 && !(il.allowedOccurrencesPerItem()
2386 && (d->layout_->latextype == LATEX_LIST_ENVIRONMENT
2387 || d->layout_->latextype == LATEX_ITEM_ENVIRONMENT))) {
2388 lastpit = cur.lastpit();
2389 // get the first paragraph in sequence with this layout
2390 depth_type const current_depth = params().depth();
2394 Paragraph cpar = pars[pit - 1];
2395 if (&cpar.layout() == d->layout_
2396 && cpar.params().depth() == current_depth)
2402 for (; pit <= lastpit; ++pit) {
2403 if (&pars[pit].layout() != d->layout_)
2405 for (auto const & table : pars[pit].insetList())
2406 if (table.inset->getLayout().name() == il.name())
2409 if (have_ins >= il.allowedOccurrences())
2413 if (in_allowed_layout || in_allowed_inset)
2416 return (allowed_insets.empty() && allowed_layouts.empty());
2420 bool Paragraph::isPartOfTextSequence() const
2422 for (pos_type i = 0; i < size(); ++i) {
2423 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2431 // paragraphs inside floats need different alignment tags to avoid
2434 bool noTrivlistCentering(InsetCode code)
2436 return code == FLOAT_CODE
2437 || code == WRAP_CODE
2438 || code == CELL_CODE;
2442 string correction(string const & orig)
2444 if (orig == "flushleft")
2445 return "raggedright";
2446 if (orig == "flushright")
2447 return "raggedleft";
2448 if (orig == "center")
2454 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2455 InsetCode code, bool const lastpar, int & col)
2457 string macro = suffix + "{";
2458 if (noTrivlistCentering(code)) {
2460 // the last paragraph in non-trivlist-aligned
2461 // context is special (to avoid unwanted whitespace)
2462 if (suffix == "\\begin") {
2463 macro = "\\" + correction(env) + "{}";
2464 os << from_ascii(macro);
2465 col += macro.size();
2470 macro += correction(env);
2474 if (suffix == "\\par\\end") {
2478 os << from_ascii(macro);
2479 col += macro.size();
2480 if (suffix == "\\begin") {
2490 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2491 otexstream & os, OutputParams const & runparams) const
2496 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2497 (layout_->toggle_indent != ITOGGLE_NEVER) :
2498 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2500 LyXAlignment const curAlign = params_.align();
2502 // Do not output \\noindent for paragraphs
2503 // 1. that cannot have indentation or are indented always,
2504 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2505 // 3. that are PassThru,
2506 // 4. or that are centered.
2507 if (canindent && params_.noindent()
2508 && owner_->isPartOfTextSequence()
2509 && !layout_->pass_thru
2510 && curAlign != LYX_ALIGN_CENTER) {
2511 if (!owner_->empty()
2512 && owner_->getInset(0)
2513 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2514 // If the paragraph starts with a vspace, the \\noindent
2515 // needs to come after that (as it leaves vmode).
2516 // If the paragraph consists only of the vspace,
2517 // \\noindent is not needed at all.
2518 runparams.need_noindent = owner_->size() > 1;
2520 os << "\\noindent" << termcmd;
2525 if (curAlign == layout_->align)
2529 case LYX_ALIGN_NONE:
2530 case LYX_ALIGN_BLOCK:
2531 case LYX_ALIGN_LAYOUT:
2532 case LYX_ALIGN_SPECIAL:
2533 case LYX_ALIGN_DECIMAL:
2535 case LYX_ALIGN_LEFT:
2536 case LYX_ALIGN_RIGHT:
2537 case LYX_ALIGN_CENTER:
2538 if (runparams.moving_arg) {
2545 string const begin_tag = "\\begin";
2546 InsetCode code = ownerCode();
2547 bool const lastpar = runparams.isLastPar;
2548 // RTL in classic (PDF)LaTeX (without the Bidi package)
2549 // Luabibdi (used by LuaTeX) behaves like classic
2550 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2551 && !runparams.useBidiPackage();
2554 case LYX_ALIGN_NONE:
2555 case LYX_ALIGN_BLOCK:
2556 case LYX_ALIGN_LAYOUT:
2557 case LYX_ALIGN_SPECIAL:
2558 case LYX_ALIGN_DECIMAL:
2560 case LYX_ALIGN_LEFT: {
2562 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2563 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2565 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2567 } case LYX_ALIGN_RIGHT: {
2569 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2570 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2572 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2574 } case LYX_ALIGN_CENTER: {
2575 corrected_env(os, begin_tag, "center", code, lastpar, column);
2584 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2585 otexstream & os, OutputParams const & runparams) const
2587 LyXAlignment const curAlign = params_.align();
2589 if (curAlign == layout_->align)
2593 case LYX_ALIGN_NONE:
2594 case LYX_ALIGN_BLOCK:
2595 case LYX_ALIGN_LAYOUT:
2596 case LYX_ALIGN_SPECIAL:
2597 case LYX_ALIGN_DECIMAL:
2599 case LYX_ALIGN_LEFT:
2600 case LYX_ALIGN_RIGHT:
2601 case LYX_ALIGN_CENTER:
2602 if (runparams.moving_arg)
2607 bool output = false;
2609 string const end_tag = "\\par\\end";
2610 InsetCode code = ownerCode();
2611 bool const lastpar = runparams.isLastPar;
2612 // RTL in classic (PDF)LaTeX (without the Bidi package)
2613 // Luabibdi (used by LuaTeX) behaves like classic
2614 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2615 && !runparams.useBidiPackage();
2618 case LYX_ALIGN_NONE:
2619 case LYX_ALIGN_BLOCK:
2620 case LYX_ALIGN_LAYOUT:
2621 case LYX_ALIGN_SPECIAL:
2622 case LYX_ALIGN_DECIMAL:
2624 case LYX_ALIGN_LEFT: {
2626 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2627 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2629 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2631 } case LYX_ALIGN_RIGHT: {
2633 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2634 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2636 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2638 } case LYX_ALIGN_CENTER: {
2639 corrected_env(os, end_tag, "center", code, lastpar, col);
2644 return output || lastpar;
2648 // This one spits out the text of the paragraph
2649 void Paragraph::latex(BufferParams const & bparams,
2650 Font const & outerfont,
2652 OutputParams const & runparams,
2653 int start_pos, int end_pos, bool force) const
2655 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2657 // FIXME This check should not be needed. Perhaps issue an
2658 // error if it triggers.
2659 Layout const & style = inInset().forcePlainLayout() ?
2660 bparams.documentClass().plainLayout() : *d->layout_;
2662 if (!force && style.inpreamble)
2665 bool const allowcust = allowParagraphCustomization();
2667 // Current base font for all inherited font changes, without any
2668 // change caused by an individual character, except for the language:
2669 // It is set to the language of the first character.
2670 // As long as we are in the label, this font is the base font of the
2671 // label. Before the first body character it is set to the base font
2675 // If there is an open font-encoding changing command (script wrapper),
2676 // alien_script is set to its name
2677 string alien_script;
2680 // Maybe we have to create a optional argument.
2681 pos_type body_pos = beginOfBody();
2682 unsigned int column = 0;
2684 // If we are inside an non inheritFont() inset,
2685 // the outerfont is the buffer's main font
2686 Font const real_outerfont =
2687 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2690 // the optional argument is kept in curly brackets in
2691 // case it contains a ']'
2692 // This is not strictly needed, but if this is changed it
2693 // would be a file format change, and tex2lyx would need
2694 // to be adjusted, since it unconditionally removes the
2695 // braces when it parses \item.
2698 basefont = getLabelFont(bparams, real_outerfont);
2700 basefont = getLayoutFont(bparams, real_outerfont);
2703 // Which font is currently active?
2704 Font running_font(basefont);
2705 // Do we have an open font change?
2706 bool open_font = false;
2708 Change runningChange =
2709 runparams.inDeletedInset && !inInset().canTrackChanges()
2710 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2712 Encoding const * const prev_encoding = runparams.encoding;
2714 os.texrow().start(id(), 0);
2716 // if the paragraph is empty, the loop will not be entered at all
2718 // For InTitle commands, we have already opened a group
2719 // in output_latex::TeXOnePar.
2720 if (style.isCommand() && !style.intitle) {
2724 if (!style.leftdelim().empty()) {
2725 os << style.leftdelim();
2726 column += style.leftdelim().size();
2729 column += d->startTeXParParams(bparams, os, runparams);
2732 // Whether a \par can be issued for insets typeset inline with text.
2733 // Yes if greater than 0. This has to be static.
2734 THREAD_LOCAL_STATIC int parInline = 0;
2736 for (pos_type i = 0; i < size(); ++i) {
2737 // First char in paragraph or after label?
2738 if (i == body_pos) {
2741 bool needPar = false;
2742 column += running_font.latexWriteEndChanges(
2743 os, bparams, runparams,
2744 basefont, basefont, needPar);
2747 basefont = getLayoutFont(bparams, real_outerfont);
2748 running_font = basefont;
2750 column += Changes::latexMarkChange(os, bparams,
2751 runningChange, Change(Change::UNCHANGED),
2753 runningChange = Change(Change::UNCHANGED);
2755 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2758 // For InTitle commands, we have already opened a group
2759 // in output_latex::TeXOnePar.
2760 if (style.isCommand() && !style.intitle) {
2765 if (!style.leftdelim().empty()) {
2766 os << style.leftdelim();
2767 column += style.leftdelim().size();
2771 column += d->startTeXParParams(bparams, os,
2775 runparams.wasDisplayMath = runparams.inDisplayMath;
2776 runparams.inDisplayMath = false;
2777 bool deleted_display_math = false;
2778 Change const & change = runparams.inDeletedInset
2779 ? runparams.changeOfDeletedInset : lookupChange(i);
2781 char_type const c = d->text_[i];
2783 // Check whether a display math inset follows
2784 bool output_changes;
2785 if (!runparams.find_effective())
2786 output_changes = bparams.output_changes;
2788 output_changes = runparams.find_with_deleted();
2790 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2792 runparams.ctObject = getInset(i)->getCtObject(runparams);
2794 InsetMath const * im = getInset(i)->asInsetMath();
2795 if (im && im->asHullInset()
2796 && im->asHullInset()->outerDisplay()) {
2797 runparams.inDisplayMath = true;
2798 // runparams.inDeletedInset will be set by
2799 // latexInset later, but we need this info
2800 // before it is called. On the other hand, we
2801 // cannot set it here because it is a counter.
2802 deleted_display_math = isDeleted(i);
2804 if (output_changes && deleted_display_math
2805 && runningChange == change
2806 && change.type == Change::DELETED
2807 && !os.afterParbreak()) {
2808 // A display math in the same paragraph follows.
2809 // We have to close and then reopen \lyxdeleted,
2810 // otherwise the math will be shifted up.
2811 OutputParams rp = runparams;
2813 bool needPar = false;
2814 column += running_font.latexWriteEndChanges(
2815 os, bparams, rp, basefont,
2819 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2820 : getLayoutFont(bparams, real_outerfont);
2821 running_font = basefont;
2822 column += Changes::latexMarkChange(os, bparams,
2823 Change(Change::INSERTED), change, rp);
2827 if (output_changes && runningChange != change) {
2828 if (!alien_script.empty()) {
2831 alien_script.clear();
2834 bool needPar = false;
2835 column += running_font.latexWriteEndChanges(
2836 os, bparams, runparams,
2837 basefont, basefont, needPar);
2840 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2841 : getLayoutFont(bparams, real_outerfont);
2842 running_font = basefont;
2843 column += Changes::latexMarkChange(os, bparams, runningChange,
2845 runningChange = change;
2848 // do not output text which is marked deleted
2849 // if change tracking output is disabled
2850 if (!output_changes && change.deleted()) {
2856 // Fully instantiated font
2857 Font current_font = getFont(bparams, i, outerfont);
2859 Font const prev_font = (i > 0) ?
2860 getFont(bparams, i - 1, outerfont)
2863 Font const last_font = running_font;
2864 bool const in_ct_deletion = (output_changes
2865 && runningChange == change
2866 && change.type == Change::DELETED
2867 && !os.afterParbreak());
2868 // Insets where font switches are used (rather than font commands)
2869 bool const fontswitch_inset =
2872 && getInset(i)->allowMultiPar()
2873 && getInset(i)->lyxCode() != ERT_CODE
2874 && (getInset(i)->producesOutput()
2875 // FIXME Something more general?
2876 // Comments do not "produce output" but are still
2877 // part of the TeX source and require font switches
2878 // to be closed (otherwise LaTeX fails).
2879 || getInset(i)->layoutName() == "Note:Comment");
2881 bool closeLanguage = false;
2882 bool lang_switched_at_inset = false;
2883 if (fontswitch_inset) {
2884 // Some insets cannot be inside a font change command.
2885 // However, even such insets *can* be placed in \L or \R
2886 // or their equivalents (for RTL language switches),
2887 // so we don't close the language in those cases
2888 // (= differing isRightToLeft()).
2889 // ArabTeX, though, doesn't seem to handle this special behavior.
2890 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2891 || basefont.language()->lang() == "arabic_arabtex"
2892 || current_font.language()->lang() == "arabic_arabtex";
2893 // We need to check prev_font as language changes directly at inset
2894 // will only be started inside the inset.
2895 lang_switched_at_inset = prev_font.language() != current_font.language();
2898 // Do we need to close the previous font?
2899 bool langClosed = false;
2901 ((current_font != running_font
2902 || current_font.language() != running_font.language())
2903 || (fontswitch_inset
2904 && (current_font == prev_font))))
2906 // ensure there is no open script-wrapper
2907 if (!alien_script.empty()) {
2910 alien_script.clear();
2912 if (in_ct_deletion) {
2913 // We have to close and then reopen \lyxdeleted,
2914 // as strikeout needs to be on lowest level.
2918 if (closeLanguage) {
2919 // Force language closing
2920 current_font.setLanguage(basefont.language());
2923 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2924 bool needPar = false;
2925 column += running_font.latexWriteEndChanges(
2926 os, bparams, runparams, basefont,
2928 if (in_ct_deletion) {
2929 // We have to close and then reopen \lyxdeleted,
2930 // as strikeout needs to be on lowest level.
2931 OutputParams rp = runparams;
2932 column += Changes::latexMarkChange(os, bparams,
2933 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2935 // Has the language been closed in the latexWriteEndChanges() call above?
2936 langClosed |= running_font.language() != basefont.language()
2937 && running_font.language() != nextfont.language()
2938 && (running_font.language()->encoding()->package() != Encoding::CJK);
2939 running_font = basefont;
2940 open_font &= !langClosed;
2943 // if necessary, close language environment before opening CJK
2944 string const running_lang = running_font.language()->babel();
2945 string const lang_end_command = lyxrc.language_command_end;
2946 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2947 && !running_lang.empty()
2948 && running_lang == openLanguageName()
2949 && current_font.language()->encoding()->package() == Encoding::CJK) {
2950 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2951 os << from_ascii(end_tag);
2952 column += end_tag.length();
2953 if (!languageStackEmpty())
2957 // Switch file encoding if necessary (and allowed)
2958 if ((!fontswitch_inset || closeLanguage)
2959 && !runparams.pass_thru && !style.pass_thru &&
2960 runparams.encoding->package() != Encoding::none &&
2961 current_font.language()->encoding()->package() != Encoding::none) {
2962 pair<bool, int> const enc_switch =
2963 switchEncoding(os.os(), bparams, runparams,
2964 *(current_font.language()->encoding()));
2965 if (enc_switch.first) {
2966 column += enc_switch.second;
2967 runparams.encoding = current_font.language()->encoding();
2971 // A display math inset inside an ulem command will be output
2972 // as a box of width \linewidth, so we have to either disable
2973 // indentation if the inset starts a paragraph, or start a new
2974 // line to accommodate such box. This has to be done before
2975 // writing any font changing commands.
2976 if (runparams.inDisplayMath && !deleted_display_math
2977 && runparams.inulemcmd) {
2978 if (os.afterParbreak())
2984 // Do we need to change font?
2985 if ((current_font != running_font ||
2986 current_font.language() != running_font.language())
2987 && i != body_pos - 1)
2989 if (!fontswitch_inset) {
2990 if (in_ct_deletion) {
2991 // We have to close and then reopen \lyxdeleted,
2992 // as strikeout needs to be on lowest level.
2993 OutputParams rp = runparams;
2994 bool needPar = false;
2995 column += running_font.latexWriteEndChanges(
2996 os, bparams, rp, basefont,
3001 otexstringstream ots;
3002 InsetText const * textinset = inInset().asInsetText();
3003 bool const cprotect = textinset
3004 ? textinset->hasCProtectContent(runparams.moving_arg)
3005 && !textinset->text().isMainText()
3006 && inInset().lyxCode() != BRANCH_CODE
3008 column += current_font.latexWriteStartChanges(ots, bparams,
3009 runparams, basefont, last_font, false,
3011 // Check again for display math in ulem commands as a
3012 // font change may also occur just before a math inset.
3013 if (runparams.inDisplayMath && !deleted_display_math
3014 && runparams.inulemcmd) {
3015 if (os.afterParbreak())
3020 running_font = current_font;
3022 docstring fontchange = ots.str();
3024 // check whether the fontchange ends with a \\textcolor
3025 // modifier and the text starts with a space. If so we
3026 // need to add } in order to prevent \\textcolor from gobbling
3027 // the space (bug 4473).
3028 docstring const last_modifier = rsplit(fontchange, '\\');
3029 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
3030 os << from_ascii("{}");
3031 else if (ots.terminateCommand())
3033 if (in_ct_deletion) {
3034 // We have to close and then reopen \lyxdeleted,
3035 // as strikeout needs to be on lowest level.
3036 OutputParams rp = runparams;
3037 column += Changes::latexMarkChange(os, bparams,
3038 Change(Change::UNCHANGED), change, rp);
3040 } else {// if fontswitch_inset
3041 if (current_font != running_font || !langClosed)
3042 // font is still open in fontswitch_insets if we have
3043 // a non-lang font difference or if the language
3044 // is the only difference but has not been forcedly
3047 running_font = current_font;
3051 // FIXME: think about end_pos implementation...
3052 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
3053 // FIXME: integrate this case in latexSpecialChar
3054 // Do not print the separation of the optional argument
3055 // if style.pass_thru is false. This works because
3056 // latexSpecialChar ignores spaces if
3057 // style.pass_thru is false.
3058 if (i != body_pos - 1) {
3059 if (d->simpleTeXBlanks(bparams, runparams, os,
3060 i, column, current_font, style)) {
3061 // A surrogate pair was output. We
3062 // must not call latexSpecialChar
3063 // in this iteration, since it would output
3064 // the combining character again.
3071 OutputParams rp = runparams;
3072 rp.free_spacing = style.free_spacing;
3073 rp.local_font = ¤t_font;
3074 rp.intitle = style.intitle;
3076 // Two major modes: LaTeX or plain
3077 // Handle here those cases common to both modes
3078 // and then split to handle the two modes separately.
3079 if (c == META_INSET) {
3080 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3081 // Greyedout notes and, in general, all insets
3082 // with InsetLayout::isDisplay() == false,
3083 // are typeset inline with the text. So, we
3084 // can add a \par to the last paragraph of
3085 // such insets only if nothing else follows.
3086 bool incremented = false;
3087 Inset const * inset = getInset(i);
3088 InsetText const * textinset = inset
3089 ? inset->asInsetText()
3091 if (i + 1 == size() && textinset
3092 && !inset->getLayout().isDisplay()) {
3093 ParagraphList const & pars =
3094 textinset->text().paragraphs();
3095 pit_type const pit = pars.size() - 1;
3096 Font const lastfont =
3097 pit < 0 || pars[pit].empty()
3098 ? pars[pit].getLayoutFont(
3101 : pars[pit].getFont(bparams,
3102 pars[pit].size() - 1,
3104 if (lastfont.fontInfo().size() !=
3105 basefont.fontInfo().size()) {
3110 // We need to restore parts of this after insets with
3111 // allowMultiPar() true
3112 Font const save_basefont = basefont;
3113 d->latexInset(bparams, os, rp, running_font,
3114 basefont, real_outerfont, open_font,
3115 runningChange, style, i, column, fontswitch_inset,
3116 closeLanguage, (lang_switched_at_inset || langClosed));
3117 if (fontswitch_inset) {
3119 bool needPar = false;
3120 column += running_font.latexWriteEndChanges(
3121 os, bparams, runparams,
3122 basefont, basefont, needPar);
3125 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3126 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3127 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3132 if (runparams.ctObject == CtObject::DisplayObject
3133 || runparams.ctObject == CtObject::UDisplayObject) {
3134 // Close \lyx*deleted and force its
3135 // reopening (if needed)
3138 runningChange = Change(Change::UNCHANGED);
3139 runparams.ctObject = CtObject::Normal;
3142 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3143 if (!bparams.useNonTeXFonts)
3144 script = Encodings::isKnownScriptChar(c);
3145 if (script != alien_script) {
3146 if (!alien_script.empty()) {
3148 alien_script.clear();
3150 string fontenc = running_font.language()->fontenc(bparams);
3152 && !Encodings::fontencSupportsScript(fontenc, script)) {
3153 column += script.length() + 2;
3154 os << "\\" << script << "{";
3155 alien_script = script;
3159 d->latexSpecialChar(os, bparams, rp, running_font,
3160 alien_script, style, i, end_pos, column);
3161 } catch (EncodingException & e) {
3162 if (runparams.dryrun) {
3163 os << "<" << _("LyX Warning: ")
3164 << _("uncodable character") << " '";
3168 // add location information and throw again.
3176 // Set the encoding to that returned from latexSpecialChar (see
3177 // comment for encoding member in OutputParams.h)
3178 runparams.encoding = rp.encoding;
3180 // Also carry on the info on a closed ulem command for insets
3181 // such as Note that do not produce any output, so that no
3182 // command is ever executed but its opening was recorded.
3183 runparams.inulemcmd = rp.inulemcmd;
3185 // These need to be passed upstream as well
3186 runparams.need_maketitle = rp.need_maketitle;
3187 runparams.have_maketitle = rp.have_maketitle;
3189 // And finally, pass the post_macros upstream
3190 runparams.post_macro = rp.post_macro;
3193 // Close wrapper for alien script
3194 if (!alien_script.empty()) {
3196 alien_script.clear();
3199 Font const font = empty()
3200 ? getLayoutFont(bparams, real_outerfont)
3201 : getFont(bparams, size() - 1, real_outerfont);
3203 InsetText const * textinset = inInset().asInsetText();
3205 bool const maintext = textinset
3206 ? textinset->text().isMainText()
3209 size_t const numpars = textinset
3210 ? textinset->text().paragraphs().size()
3213 bool needPar = false;
3215 if (style.resfont.size() != font.fontInfo().size()
3216 && (!runparams.isLastPar || maintext
3217 || (numpars > 1 && d->ownerCode() != CELL_CODE
3218 && (inInset().getLayout().isDisplay()
3220 && !style.isCommand()) {
3224 // If we have an open font definition, we have to close it
3226 // Make sure that \\par is done with the font of the last
3227 // character if this has another size as the default.
3228 // This is necessary because LaTeX (and LyX on the screen)
3229 // calculates the space between the baselines according
3230 // to this font. (Matthias)
3232 // We must not change the font for the last paragraph
3233 // of non-multipar insets, tabular cells or commands,
3234 // since this produces unwanted whitespace.
3235 #ifdef FIXED_LANGUAGE_END_DETECTION
3237 running_font.latexWriteEndChanges(os, bparams,
3238 runparams, basefont,
3239 next_->getFont(bparams, 0, outerfont),
3242 running_font.latexWriteEndChanges(os, bparams,
3243 runparams, basefont, basefont, needPar);
3246 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3247 //FIXME: there as we start another \selectlanguage with the next paragraph if
3248 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3249 running_font.latexWriteEndChanges(os, bparams, runparams,
3250 basefont, basefont, needPar);
3254 // The \par could not be inserted at the same nesting
3255 // level of the font size change, so do it now.
3256 os << "{\\" << font.latexSize() << "\\par}";
3259 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3260 column += Changes::latexMarkChange(os, bparams, runningChange,
3261 Change(Change::UNCHANGED), runparams);
3263 // Needed if there is an optional argument but no contents.
3264 if (body_pos > 0 && body_pos == size()) {
3268 if (!style.rightdelim().empty()) {
3269 os << style.rightdelim();
3270 column += style.rightdelim().size();
3273 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3274 && runparams.encoding != prev_encoding) {
3275 runparams.encoding = prev_encoding;
3276 os << setEncoding(prev_encoding->iconvName());
3279 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3283 bool Paragraph::emptyTag() const
3285 for (pos_type i = 0; i < size(); ++i) {
3286 if (Inset const * inset = getInset(i)) {
3287 InsetCode lyx_code = inset->lyxCode();
3288 // FIXME testing like that is wrong. What is
3290 if (lyx_code != TOC_CODE &&
3291 lyx_code != INCLUDE_CODE &&
3292 lyx_code != GRAPHICS_CODE &&
3293 lyx_code != ERT_CODE &&
3294 lyx_code != LISTINGS_CODE &&
3295 lyx_code != FLOAT_CODE &&
3296 lyx_code != TABULAR_CODE) {
3300 char_type c = d->text_[i];
3301 if (c != ' ' && c != '\t')
3309 string Paragraph::getID(Buffer const &, OutputParams const &)
3312 for (pos_type i = 0; i < size(); ++i) {
3313 if (Inset const * inset = getInset(i)) {
3314 InsetCode lyx_code = inset->lyxCode();
3315 if (lyx_code == LABEL_CODE) {
3316 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3317 docstring const & id = il->getParam("name");
3318 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3326 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3329 for (i = 0; i < size(); ++i) {
3330 if (Inset const * inset = getInset(i)) {
3331 inset->docbook(xs, runparams);
3333 char_type c = d->text_[i];
3343 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3347 for (i = 0; i < size(); ++i) {
3348 if (Inset const * inset = getInset(i)) {
3349 inset->xhtml(xs, runparams);
3351 char_type c = d->text_[i];
3361 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3364 pos_type size = text_.size();
3365 for (pos_type i = initial; i < size; ++i) {
3366 Font font = owner_->getFont(buf.params(), i, outerfont);
3367 if (text_[i] == META_INSET)
3369 if (i != initial && font != font_old)
3380 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3381 vector<xml::EndFontTag> & tagsToClose,
3382 bool & flag, FontState curstate, xml::FontTypes type)
3384 if (curstate == FONT_ON) {
3385 tagsToOpen.push_back(docbookStartFontTag(type));
3388 tagsToClose.push_back(docbookEndFontTag(type));
3393 class OptionalFontType {
3398 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3399 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3402 OptionalFontType fontShapeToXml(FontShape fs)
3406 return {xml::FT_ITALIC};
3408 return {xml::FT_SLANTED};
3409 case SMALLCAPS_SHAPE:
3410 return {xml::FT_SMALLCAPS};
3415 // the other tags are for internal use
3421 OptionalFontType fontFamilyToXml(FontFamily fm)
3425 return {xml::FT_ROMAN};
3427 return {xml::FT_SANS};
3428 case TYPEWRITER_FAMILY:
3429 return {xml::FT_TYPE};
3430 case INHERIT_FAMILY:
3433 // the other tags are for internal use
3439 OptionalFontType fontSizeToXml(FontSize fs)
3443 return {xml::FT_SIZE_TINY};
3445 return {xml::FT_SIZE_SCRIPT};
3447 return {xml::FT_SIZE_FOOTNOTE};
3449 return {xml::FT_SIZE_SMALL};
3451 return {xml::FT_SIZE_LARGE};
3453 return {xml::FT_SIZE_LARGER};
3455 return {xml::FT_SIZE_LARGEST};
3457 return {xml::FT_SIZE_HUGE};
3459 return {xml::FT_SIZE_HUGER};
3461 return {xml::FT_SIZE_INCREASE};
3463 return {xml::FT_SIZE_DECREASE};
3468 // the other tags are for internal use
3474 struct DocBookFontState
3476 FontShape curr_fs = INHERIT_SHAPE;
3477 FontFamily curr_fam = INHERIT_FAMILY;
3478 FontSize curr_size = INHERIT_SIZE;
3480 // track whether we have opened these tags
3481 bool emph_flag = false;
3482 bool bold_flag = false;
3483 bool noun_flag = false;
3484 bool ubar_flag = false;
3485 bool dbar_flag = false;
3486 bool sout_flag = false;
3487 bool xout_flag = false;
3488 bool wave_flag = false;
3490 bool shap_flag = false;
3492 bool faml_flag = false;
3494 bool size_flag = false;
3497 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3499 std::string const & default_family,
3500 DocBookFontState & fs)
3502 vector<xml::FontTag> tagsToOpen;
3503 vector<xml::EndFontTag> tagsToClose;
3506 FontState curstate = font.fontInfo().emph();
3507 if (font_old.emph() != curstate)
3508 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3511 curstate = font.fontInfo().noun();
3512 if (font_old.noun() != curstate)
3513 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3516 curstate = font.fontInfo().underbar();
3517 if (font_old.underbar() != curstate)
3518 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3521 curstate = font.fontInfo().strikeout();
3522 if (font_old.strikeout() != curstate)
3523 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3526 curstate = font.fontInfo().xout();
3527 if (font_old.xout() != curstate)
3528 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3531 curstate = font.fontInfo().uuline();
3532 if (font_old.uuline() != curstate)
3533 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3536 curstate = font.fontInfo().uwave();
3537 if (font_old.uwave() != curstate)
3538 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3541 // a little hackish, but allows us to reuse what we have.
3542 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3543 if (font_old.series() != font.fontInfo().series())
3544 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3547 fs.curr_fs = font.fontInfo().shape();
3548 FontShape old_fs = font_old.shape();
3549 if (old_fs != fs.curr_fs) {
3551 OptionalFontType tag = fontShapeToXml(old_fs);
3553 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3554 fs.shap_flag = false;
3557 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3559 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3563 fs.curr_fam = font.fontInfo().family();
3564 FontFamily old_fam = font_old.family();
3565 if (old_fam != fs.curr_fam) {
3567 OptionalFontType tag = fontFamilyToXml(old_fam);
3569 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3570 fs.faml_flag = false;
3572 switch (fs.curr_fam) {
3574 // we will treat a "default" font family as roman, since we have
3575 // no other idea what to do.
3576 if (default_family != "rmdefault" && default_family != "default") {
3577 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3578 fs.faml_flag = true;
3582 if (default_family != "sfdefault") {
3583 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3584 fs.faml_flag = true;
3587 case TYPEWRITER_FAMILY:
3588 if (default_family != "ttdefault") {
3589 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3590 fs.faml_flag = true;
3593 case INHERIT_FAMILY:
3596 // the other tags are for internal use
3603 fs.curr_size = font.fontInfo().size();
3604 FontSize old_size = font_old.size();
3605 if (old_size != fs.curr_size) {
3607 OptionalFontType tag = fontSizeToXml(old_size);
3609 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3610 fs.size_flag = false;
3613 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3614 if (tag.has_value) {
3615 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3616 fs.size_flag = true;
3620 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3623 } // anonymous namespace
3626 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3627 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3628 OutputParams const & runparams,
3629 Font const & outerfont,
3632 bool ignore_fonts) const
3634 // Return values: segregation of the content of this paragraph.
3635 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3636 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3637 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3639 // Internal string stream to store the output before being added to one of the previous lists.
3640 odocstringstream os;
3642 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3643 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3645 OutputParams rp = runparams;
3646 for (pos_type i = initial; i < size(); ++i) {
3647 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3648 const InsetArgument * arg = getInset(i)->asInsetArgument();
3649 if (arg->docbookargumentbeforemaintag()) {
3650 auto xs_local = XMLStream(os);
3651 arg->docbook(xs_local, rp);
3653 prependedParagraphs.push_back(os.str());
3654 os.str(from_ascii(""));
3656 rp.docbook_prepended_arguments.insert(arg);
3657 } else if (arg->docbookargumentaftermaintag()) {
3658 rp.docbook_appended_arguments.insert(arg);
3663 // State variables for the main loop.
3664 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3665 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3666 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3667 // This requires to store delayed characters at some point.
3669 // Track whether we have opened font tags
3670 DocBookFontState fs;
3671 DocBookFontState old_fs = fs;
3673 Layout const & style = *d->layout_;
3675 // Conversion of the font opening/closing into DocBook tags.
3676 vector<xml::FontTag> tagsToOpen;
3677 vector<xml::EndFontTag> tagsToClose;
3679 // Parsing main loop.
3680 for (pos_type i = initial; i < size(); ++i) {
3681 bool ignore_fonts_i = ignore_fonts
3682 || style.docbooknofontinside()
3683 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3685 // Don't show deleted material in the output.
3689 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3691 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3692 if (!ignore_fonts_i)
3693 xs->closeFontTags();
3695 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3696 generatedParagraphs.push_back(os.str());
3698 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3699 // that the string stream must be reset.
3700 os.str(from_ascii(""));
3702 xs = new XMLStream(os);
3704 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3705 if (!ignore_fonts_i) {
3710 // Determine which tags should be opened or closed regarding fonts.
3711 FontInfo const font_old = (i == 0 ?
3712 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3713 getFont(buf.masterBuffer()->params(), i - 1, outerfont).fontInfo());
3714 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3715 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3716 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3718 if (!ignore_fonts_i) {
3719 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3720 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3721 for (; cit != cen; ++cit)
3725 // Deal with the delayed characters *after* closing font tags.
3726 if (!delayedChars.empty()) {
3727 for (const docstring& c: delayedChars)
3728 *xs << XMLStream::ESCAPE_NONE << c;
3729 delayedChars.clear();
3732 if (!ignore_fonts_i) {
3733 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3734 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3735 for (; sit != sen; ++sit)
3738 tagsToClose.clear();
3742 // Finally, write the next character or inset.
3743 if (Inset const * inset = getInset(i)) {
3744 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3745 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3746 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3748 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3749 // Arguments may need to be output
3750 OutputParams np = rp;
3751 np.local_font = &font;
3753 // TODO: special case will bite here.
3754 np.docbook_in_par = true;
3755 inset->docbook(*xs, np);
3758 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3759 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3760 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3761 delayedChars.push_back(from_ascii(" "));
3763 delayedChars.emplace_back(1, c);
3765 } else { // No need to delay the character.
3766 if (c == '\'' && !ignore_fonts)
3767 *xs << XMLStream::ESCAPE_NONE << "’";
3774 // FIXME, this code is just imported from XHTML
3775 // I'm worried about what happens if a branch, say, is itself
3776 // wrapped in some font stuff. I think that will not work.
3778 xs->closeFontTags();
3780 // Deal with the delayed characters *after* closing font tags.
3781 if (!delayedChars.empty()) {
3782 for (const docstring &c: delayedChars)
3783 *xs << XMLStream::ESCAPE_NONE << c;
3784 delayedChars.clear();
3787 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3788 // last line to get a clean output.
3789 if (rp.docbook_in_listing && !is_last_par)
3792 // Finalise the last (and most likely only) paragraph.
3793 generatedParagraphs.push_back(os.str());
3794 os.str(from_ascii(""));
3797 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3798 for (pos_type i = initial; i < size(); ++i) {
3799 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3800 const InsetArgument * arg = getInset(i)->asInsetArgument();
3801 if (arg->docbookargumentaftermaintag()) {
3802 // Don't use rp, as this argument would not generate anything.
3803 auto xs_local = XMLStream(os);
3804 arg->docbook(xs_local, runparams);
3806 appendedParagraphs.push_back(os.str());
3807 os.str(from_ascii(""));
3812 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3818 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3819 vector<xml::EndFontTag> & tagsToClose,
3820 bool & flag, FontState curstate, xml::FontTypes type)
3822 if (curstate == FONT_ON) {
3823 tagsToOpen.push_back(xhtmlStartFontTag(type));
3826 tagsToClose.push_back(xhtmlEndFontTag(type));
3831 } // anonymous namespace
3834 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3836 OutputParams const & runparams,
3837 Font const & outerfont,
3838 bool start_paragraph, bool close_paragraph,
3839 pos_type initial) const
3843 // track whether we have opened these tags
3844 bool emph_flag = false;
3845 bool bold_flag = false;
3846 bool noun_flag = false;
3847 bool ubar_flag = false;
3848 bool dbar_flag = false;
3849 bool sout_flag = false;
3850 bool xout_flag = false;
3851 bool wave_flag = false;
3853 bool shap_flag = false;
3855 bool faml_flag = false;
3857 bool size_flag = false;
3859 Layout const & style = *d->layout_;
3861 if (start_paragraph)
3862 xs.startDivision(allowEmpty());
3865 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3867 FontShape curr_fs = INHERIT_SHAPE;
3868 FontFamily curr_fam = INHERIT_FAMILY;
3869 FontSize curr_size = INHERIT_SIZE;
3871 string const default_family =
3872 buf.masterBuffer()->params().fonts_default_family;
3874 vector<xml::FontTag> tagsToOpen;
3875 vector<xml::EndFontTag> tagsToClose;
3877 // parsing main loop
3878 for (pos_type i = initial; i < size(); ++i) {
3879 // let's not show deleted material in the output
3883 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3886 FontState curstate = font.fontInfo().emph();
3887 if (font_old.emph() != curstate)
3888 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3891 curstate = font.fontInfo().noun();
3892 if (font_old.noun() != curstate)
3893 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3896 curstate = font.fontInfo().underbar();
3897 if (font_old.underbar() != curstate)
3898 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3901 curstate = font.fontInfo().strikeout();
3902 if (font_old.strikeout() != curstate)
3903 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3906 curstate = font.fontInfo().xout();
3907 if (font_old.xout() != curstate)
3908 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3911 curstate = font.fontInfo().uuline();
3912 if (font_old.uuline() != curstate)
3913 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3916 curstate = font.fontInfo().uwave();
3917 if (font_old.uwave() != curstate)
3918 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3921 // a little hackish, but allows us to reuse what we have.
3922 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3923 if (font_old.series() != font.fontInfo().series())
3924 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3927 curr_fs = font.fontInfo().shape();
3928 FontShape old_fs = font_old.shape();
3929 if (old_fs != curr_fs) {
3933 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3936 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3938 case SMALLCAPS_SHAPE:
3939 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3945 // the other tags are for internal use
3953 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3957 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3960 case SMALLCAPS_SHAPE:
3961 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3968 // the other tags are for internal use
3975 curr_fam = font.fontInfo().family();
3976 FontFamily old_fam = font_old.family();
3977 if (old_fam != curr_fam) {
3981 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3984 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3986 case TYPEWRITER_FAMILY:
3987 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3989 case INHERIT_FAMILY:
3992 // the other tags are for internal use
4000 // we will treat a "default" font family as roman, since we have
4001 // no other idea what to do.
4002 if (default_family != "rmdefault" && default_family != "default") {
4003 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
4008 if (default_family != "sfdefault") {
4009 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
4013 case TYPEWRITER_FAMILY:
4014 if (default_family != "ttdefault") {
4015 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
4019 case INHERIT_FAMILY:
4022 // the other tags are for internal use
4029 curr_size = font.fontInfo().size();
4030 FontSize old_size = font_old.size();
4031 if (old_size != curr_size) {
4035 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
4038 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
4041 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
4044 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
4047 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
4050 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
4053 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
4056 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
4059 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
4062 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
4065 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
4071 // the other tags are for internal use
4077 switch (curr_size) {
4079 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4083 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4087 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4091 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4095 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4099 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4103 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4107 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4111 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4115 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4119 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4126 // the other tags are for internal use
4133 // Other such tags? What about the other text ranges?
4135 for (auto const & t : tagsToClose)
4137 for (auto const & t : tagsToOpen)
4139 tagsToClose.clear();
4142 Inset const * inset = getInset(i);
4144 if (!runparams.for_toc || inset->isInToc()) {
4145 OutputParams np = runparams;
4146 np.local_font = &font;
4147 // If the paragraph has size 1, then we are in the "special
4148 // case" where we do not output the containing paragraph info
4149 if (!inset->getLayout().htmlisblock() && size() != 1)
4150 np.html_in_par = true;
4151 retval += inset->xhtml(xs, np);
4154 char_type c = getUChar(buf.masterBuffer()->params(),
4156 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4157 xs << XMLStream::ESCAPE_NONE << " ";
4159 xs << XMLStream::ESCAPE_NONE << "’";
4163 font_old = font.fontInfo();
4167 // I'm worried about what happens if a branch, say, is itself
4168 // wrapped in some font stuff. I think that will not work.
4170 if (close_paragraph)
4177 bool Paragraph::isHfill(pos_type pos) const
4179 Inset const * inset = getInset(pos);
4180 return inset && inset->isHfill();
4184 bool Paragraph::isNewline(pos_type pos) const
4186 // U+2028 LINE SEPARATOR
4187 // U+2029 PARAGRAPH SEPARATOR
4188 char_type const c = d->text_[pos];
4189 if (c == 0x2028 || c == 0x2029)
4191 Inset const * inset = getInset(pos);
4192 return inset && inset->lyxCode() == NEWLINE_CODE;
4196 bool Paragraph::isEnvSeparator(pos_type pos) const
4198 Inset const * inset = getInset(pos);
4199 return inset && inset->lyxCode() == SEPARATOR_CODE;
4203 bool Paragraph::isLineSeparator(pos_type pos) const
4205 char_type const c = d->text_[pos];
4206 if (isLineSeparatorChar(c))
4208 Inset const * inset = getInset(pos);
4209 return inset && inset->isLineSeparator();
4213 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4217 if (ignore_deleted && isDeleted(pos))
4219 if (Inset const * inset = getInset(pos))
4220 return !inset->isLetter();
4221 // if we have a hard hyphen (no en- or emdash) or apostrophe
4222 // we pass this to the spell checker
4223 // FIXME: this method is subject to change, visit
4224 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4225 // to get an impression how complex this is.
4226 if (isHardHyphenOrApostrophe(pos))
4228 char_type const c = d->text_[pos];
4229 // We want to pass the escape chars to the spellchecker
4230 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4231 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4235 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4237 pos_type const psize = size();
4240 char_type const c = d->text_[pos];
4241 if (c != '-' && c != '\'')
4243 pos_type nextpos = pos + 1;
4244 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4245 if ((nextpos == psize || isSpace(nextpos))
4246 && (pos == 0 || isSpace(prevpos)))
4252 bool Paragraph::needsCProtection(bool const fragile) const
4254 // first check the layout of the paragraph, but only in insets
4255 InsetText const * textinset = inInset().asInsetText();
4256 bool const maintext = textinset
4257 ? textinset->text().isMainText()
4260 if (!maintext && layout().needcprotect) {
4261 // Environments need cprotection regardless the content
4262 if (layout().latextype == LATEX_ENVIRONMENT)
4265 // Commands need cprotection if they contain specific chars
4266 int const nchars_escape = 9;
4267 static char_type const chars_escape[nchars_escape] = {
4268 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4270 docstring const pars = asString();
4271 for (int k = 0; k < nchars_escape; k++) {
4272 if (contains(pars, chars_escape[k]))
4277 // now check whether we have insets that need cprotection
4278 for (auto const & icit : d->insetlist_) {
4279 Inset const * ins = icit.inset;
4282 if (ins->needsCProtection(maintext, fragile))
4290 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4292 return d->speller_state_.getRange(pos);
4296 bool Paragraph::isChar(pos_type pos) const
4298 if (Inset const * inset = getInset(pos))
4299 return inset->isChar();
4300 char_type const c = d->text_[pos];
4301 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4305 bool Paragraph::isSpace(pos_type pos) const
4307 if (Inset const * inset = getInset(pos))
4308 return inset->isSpace();
4309 char_type const c = d->text_[pos];
4310 return lyx::isSpace(c);
4315 Paragraph::getParLanguage(BufferParams const & bparams) const
4318 return getFirstFontSettings(bparams).language();
4319 // FIXME: we should check the prev par as well (Lgb)
4320 return bparams.language;
4324 bool Paragraph::isRTL(BufferParams const & bparams) const
4326 return getParLanguage(bparams)->rightToLeft()
4327 && !inInset().getLayout().forceLTR();
4331 void Paragraph::changeLanguage(BufferParams const & bparams,
4332 Language const * from, Language const * to)
4334 // change language including dummy font change at the end
4335 for (pos_type i = 0; i <= size(); ++i) {
4336 Font font = getFontSettings(bparams, i);
4337 if (font.language() == from) {
4338 font.setLanguage(to);
4340 d->requestSpellCheck(i);
4346 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4348 Language const * doc_language = bparams.language;
4349 for (auto const & f : d->fontlist_)
4350 if (f.font().language() != ignore_language &&
4351 f.font().language() != latex_language &&
4352 f.font().language() != doc_language)
4358 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4360 for (auto const & f : d->fontlist_) {
4361 Language const * lang = f.font().language();
4362 if (lang != ignore_language &&
4363 lang != latex_language)
4369 docstring Paragraph::asString(int options) const
4371 return asString(0, size(), options);
4375 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4377 odocstringstream os;
4380 && options & AS_STR_LABEL
4381 && d->layout_->labeltype != LABEL_MANUAL
4382 && !d->params_.labelString().empty())
4383 os << d->params_.labelString() << ' ';
4385 for (pos_type i = beg; i < end; ++i) {
4386 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4388 char_type const c = d->text_[i];
4389 if (isPrintable(c) || c == '\t'
4390 || (c == '\n' && (options & AS_STR_NEWLINES)))
4392 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4393 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4394 LASSERT(runparams != nullptr, return docstring());
4395 if (runparams->find_effective() && getInset(i)->hasToString())
4396 getInset(i)->toString(os);
4398 getInset(i)->plaintext(os, *runparams);
4399 } else if (c == META_INSET && (options & AS_STR_MATHED)
4400 && getInset(i)->lyxCode() == REF_CODE) {
4401 Buffer const & buf = getInset(i)->buffer();
4402 OutputParams rp(&buf.params().encoding());
4403 Font const font(inherit_font, buf.params().language);
4404 rp.local_font = &font;
4406 getInset(i)->latex(ots, rp);
4408 getInset(i)->toString(os);
4417 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4418 bool const shorten, bool const label) const
4420 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4421 if (label && !labelString().empty())
4422 os += labelString() + ' ';
4423 if (!layout().isTocCaption())
4425 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4428 char_type const c = d->text_[i];
4431 else if (c == META_INSET)
4432 getInset(i)->forOutliner(os, tmplen, false);
4435 Text::shortenForOutliner(os, maxlen);
4439 void Paragraph::setInsetOwner(Inset const * inset)
4441 d->inset_owner_ = inset;
4445 int Paragraph::id() const
4451 void Paragraph::setId(int id)
4457 Layout const & Paragraph::layout() const
4463 void Paragraph::setLayout(Layout const & layout)
4465 d->layout_ = &layout;
4469 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4471 setLayout(tc.defaultLayout());
4475 void Paragraph::setPlainLayout(DocumentClass const & tc)
4477 setLayout(tc.plainLayout());
4481 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4483 if (usePlainLayout())
4486 setDefaultLayout(tc);
4490 Inset const & Paragraph::inInset() const
4492 LBUFERR(d->inset_owner_);
4493 return *d->inset_owner_;
4497 ParagraphParameters & Paragraph::params()
4503 ParagraphParameters const & Paragraph::params() const
4509 bool Paragraph::isFreeSpacing() const
4511 if (d->layout_->free_spacing)
4513 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4517 bool Paragraph::allowEmpty() const
4519 if (d->layout_->keepempty)
4521 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4525 bool Paragraph::brokenBiblio() const
4527 // There is a problem if there is no bibitem at position 0 in
4528 // paragraphs that need one, if there is another bibitem in the
4529 // paragraph or if this paragraph is not supposed to have
4530 // a bibitem inset at all.
4531 return ((d->layout_->labeltype == LABEL_BIBLIO
4532 && (d->insetlist_.find(BIBITEM_CODE) != 0
4533 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4534 || (d->layout_->labeltype != LABEL_BIBLIO
4535 && d->insetlist_.find(BIBITEM_CODE) != -1));
4539 int Paragraph::fixBiblio(Buffer const & buffer)
4541 // FIXME: when there was already an inset at 0, the return value is 1,
4542 // which does not tell whether another inset has been removed; the
4543 // cursor cannot be correctly updated.
4545 bool const track_changes = buffer.params().track_changes;
4546 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4548 // The case where paragraph is not BIBLIO
4549 if (d->layout_->labeltype != LABEL_BIBLIO) {
4550 if (bibitem_pos == -1)
4551 // No InsetBibitem => OK
4553 // There is an InsetBibitem: remove it!
4554 d->insetlist_.release(bibitem_pos);
4555 eraseChar(bibitem_pos, track_changes);
4556 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4559 bool const hasbibitem0 = bibitem_pos == 0;
4561 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4562 // There was an InsetBibitem at pos 0,
4563 // and no other one => OK
4564 if (bibitem_pos == -1)
4566 // there is a bibitem at the 0 position, but since
4567 // there is a second one, we copy the second on the
4568 // first. We're assuming there are at most two of
4569 // these, which there should be.
4570 // FIXME: why does it make sense to do that rather
4571 // than keep the first? (JMarc)
4572 Inset * inset = releaseInset(bibitem_pos);
4573 d->insetlist_.begin()->inset = inset;
4574 // This needs to be done to update the counter (#8499)
4575 buffer.updateBuffer();
4576 return -bibitem_pos;
4579 // We need to create an inset at the beginning
4580 Inset * inset = nullptr;
4581 if (bibitem_pos > 0) {
4582 // there was one somewhere in the paragraph, let's move it
4583 inset = d->insetlist_.release(bibitem_pos);
4584 eraseChar(bibitem_pos, track_changes);
4587 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4588 InsetCommandParams(BIBITEM_CODE));
4590 Font font(inherit_font, buffer.params().language);
4591 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4592 : Change::UNCHANGED));
4594 // This is needed to get the counters right
4595 buffer.updateBuffer();
4600 void Paragraph::checkAuthors(AuthorList const & authorList)
4602 d->changes_.checkAuthors(authorList);
4606 bool Paragraph::isChanged(pos_type pos) const
4608 return lookupChange(pos).changed();
4612 bool Paragraph::isInserted(pos_type pos) const
4614 return lookupChange(pos).inserted();
4618 bool Paragraph::isDeleted(pos_type pos) const
4620 return lookupChange(pos).deleted();
4624 InsetList const & Paragraph::insetList() const
4626 return d->insetlist_;
4630 void Paragraph::setInsetBuffers(Buffer & b)
4632 d->insetlist_.setBuffer(b);
4636 void Paragraph::resetBuffer()
4638 d->insetlist_.resetBuffer();
4642 Inset * Paragraph::releaseInset(pos_type pos)
4644 Inset * inset = d->insetlist_.release(pos);
4645 /// does not honour change tracking!
4646 eraseChar(pos, false);
4651 Inset * Paragraph::getInset(pos_type pos)
4653 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4654 ? d->insetlist_.get(pos) : nullptr;
4658 Inset const * Paragraph::getInset(pos_type pos) const
4660 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4661 ? d->insetlist_.get(pos) : nullptr;
4665 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4666 pos_type & right, TextCase action)
4668 // process sequences of modified characters; in change
4669 // tracking mode, this approach results in much better
4670 // usability than changing case on a char-by-char basis
4671 // We also need to track the current font, since font
4672 // changes within sequences can occur.
4673 vector<pair<char_type, Font> > changes;
4675 bool const trackChanges = bparams.track_changes;
4677 bool capitalize = true;
4679 for (; pos < right; ++pos) {
4680 char_type oldChar = d->text_[pos];
4681 char_type newChar = oldChar;
4683 // ignore insets and don't play with deleted text!
4684 if (oldChar != META_INSET && !isDeleted(pos)) {
4686 case text_lowercase:
4687 newChar = lowercase(oldChar);
4689 case text_capitalization:
4691 newChar = uppercase(oldChar);
4695 case text_uppercase:
4696 newChar = uppercase(oldChar);
4701 if (isWordSeparator(pos) || isDeleted(pos)) {
4702 // permit capitalization again
4706 if (oldChar != newChar) {
4707 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4708 if (pos != right - 1)
4710 // step behind the changing area
4714 int erasePos = pos - changes.size();
4715 for (auto const & change : changes) {
4716 insertChar(pos, change.first, change.second, trackChanges);
4717 if (!eraseChar(erasePos, trackChanges)) {
4720 ++right; // expand selection
4727 int Paragraph::find(docstring const & str, bool cs, bool mw,
4728 pos_type start_pos, bool del) const
4730 pos_type pos = start_pos;
4731 int const strsize = str.length();
4733 pos_type const parsize = d->text_.size();
4734 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4735 // ignore deleted matter
4736 if (!del && isDeleted(pos)) {
4737 if (pos == parsize - 1)
4743 // Ignore "invisible" letters such as ligature breaks
4744 // and hyphenation chars while searching
4745 bool nonmatch = false;
4746 while (pos < parsize && isInset(pos)) {
4747 Inset const * inset = getInset(pos);
4748 if (!inset->isLetter() && !inset->isChar())
4750 odocstringstream os;
4751 if (inset->lyxCode() == lyx::QUOTE_CODE || inset->lyxCode() == lyx::SPACE_CODE) {
4753 op.find_set_feature(OutputParams::SearchQuick);
4754 inset->plaintext(os, op);
4757 inset->toString(os);
4759 docstring const insetstring = os.str();
4760 if (!insetstring.empty()) {
4761 int const insetstringsize = insetstring.length();
4762 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4763 if ((cs && str[i] != insetstring[j])
4764 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4772 if (nonmatch || i == strsize)
4774 char_type dp = d->text_[pos];
4775 if (cs && str[i] != dp)
4777 if (!cs && uppercase(str[i]) != uppercase(dp))
4784 // if necessary, check whether string matches word
4786 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4789 && !isWordSeparator(pos))
4793 return pos - start_pos;
4797 char_type Paragraph::getChar(pos_type pos) const
4799 return d->text_[pos];
4803 pos_type Paragraph::size() const
4805 return d->text_.size();
4809 bool Paragraph::empty() const
4811 return d->text_.empty();
4815 bool Paragraph::isInset(pos_type pos) const
4817 return d->text_[pos] == META_INSET;
4821 bool Paragraph::isSeparator(pos_type pos) const
4823 //FIXME: Are we sure this can be the only separator?
4824 return d->text_[pos] == ' ';
4828 void Paragraph::deregisterWords()
4830 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4831 Private::LangWordsMap::const_iterator ite = d->words_.end();
4832 for (; itl != ite; ++itl) {
4833 WordList & wl = theWordList(itl->first);
4834 Private::Words::const_iterator it = (itl->second).begin();
4835 Private::Words::const_iterator et = (itl->second).end();
4836 for (; it != et; ++it)
4843 void Paragraph::locateWord(pos_type & from, pos_type & to,
4844 word_location const loc, bool const ignore_deleted) const
4847 case WHOLE_WORD_STRICT:
4848 if (from == 0 || from == size()
4849 || isWordSeparator(from, ignore_deleted)
4850 || isWordSeparator(from - 1, ignore_deleted)) {
4857 // If we are already at the beginning of a word, do nothing
4858 if (!from || isWordSeparator(from - 1, ignore_deleted))
4863 // always move the cursor to the beginning of previous word
4864 while (from && !isWordSeparator(from - 1, ignore_deleted))
4868 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4871 // no need to move the 'from' cursor
4875 while (to < size() && !isWordSeparator(to, ignore_deleted))
4880 void Paragraph::collectWords()
4882 for (pos_type pos = 0; pos < size(); ++pos) {
4883 if (isWordSeparator(pos))
4885 pos_type from = pos;
4886 locateWord(from, pos, WHOLE_WORD);
4887 // Work around MSVC warning: The statement
4888 // if (pos < from + lyxrc.completion_minlength)
4889 // triggers a signed vs. unsigned warning.
4890 // I don't know why this happens, it could be a MSVC bug, or
4891 // related to LLP64 (windows) vs. LP64 (unix) programming
4892 // model, or the C++ standard might be ambigous in the section
4893 // defining the "usual arithmetic conversions". However, using
4894 // a temporary variable is safe and works on all compilers.
4895 pos_type const endpos = from + lyxrc.completion_minlength;
4898 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4899 if (cit == d->fontlist_.end())
4901 Language const * lang = cit->font().language();
4902 docstring const word = asString(from, pos, AS_STR_NONE);
4903 d->words_[lang->lang()].insert(word);
4908 void Paragraph::registerWords()
4910 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4911 Private::LangWordsMap::const_iterator ite = d->words_.end();
4912 for (; itl != ite; ++itl) {
4913 WordList & wl = theWordList(itl->first);
4914 Private::Words::const_iterator it = (itl->second).begin();
4915 Private::Words::const_iterator et = (itl->second).end();
4916 for (; it != et; ++it)
4922 void Paragraph::updateWords()
4930 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4932 SkipPositionsIterator begin = skips.begin();
4933 SkipPositions::iterator end = skips.end();
4934 if (pos > 0 && begin < end) {
4936 if (end->last == pos - 1) {
4941 skips.insert(end, FontSpan(pos, pos));
4945 Language * Paragraph::Private::locateSpellRange(
4946 pos_type & from, pos_type & to,
4947 SkipPositions & skips) const
4949 // skip leading white space
4950 while (from < to && owner_->isWordSeparator(from))
4952 // don't check empty range
4955 // get current language
4956 Language * lang = getSpellLanguage(from);
4957 pos_type last = from;
4958 bool samelang = true;
4959 bool sameinset = true;
4960 while (last < to && samelang && sameinset) {
4961 // hop to end of word
4962 while (last < to && !owner_->isWordSeparator(last)) {
4963 Inset const * inset = owner_->getInset(last);
4964 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4965 // check for "invisible" letters such as ligature breaks
4966 odocstringstream os;
4967 inset->toString(os);
4968 if (os.str().length() != 0) {
4969 // avoid spell check of visible special char insets
4970 // stop the loop in front of the special char inset
4975 appendSkipPosition(skips, last);
4976 } else if (owner_->isDeleted(last)) {
4977 appendSkipPosition(skips, last);
4981 // hop to next word while checking for insets
4982 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4983 if (Inset const * inset = owner_->getInset(last))
4984 sameinset = inset->isChar() && inset->isLetter();
4985 if (sameinset && owner_->isDeleted(last)) {
4986 appendSkipPosition(skips, last);
4991 if (sameinset && last < to) {
4992 // now check for language change
4993 samelang = lang == getSpellLanguage(last);
4996 // if language change detected backstep is needed
5004 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
5007 const_cast<Language *>(owner_->getFontSettings(
5008 inset_owner_->buffer().params(), from).language());
5009 if (lang == inset_owner_->buffer().params().language
5010 && !lyxrc.spellchecker_alt_lang.empty()) {
5012 string const lang_variety =
5013 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
5014 lang->setCode(lang_code);
5015 lang->setVariety(lang_variety);
5021 void Paragraph::requestSpellCheck(pos_type pos)
5023 d->requestSpellCheck(pos);
5025 // Also request spellcheck within (text) insets
5026 for (auto const & insets : insetList()) {
5027 if (!insets.inset->asInsetText())
5029 ParagraphList & inset_pars =
5030 insets.inset->asInsetText()->paragraphs();
5031 ParagraphList::iterator pit = inset_pars.begin();
5032 ParagraphList::iterator pend = inset_pars.end();
5033 for (; pit != pend; ++pit)
5034 pit->requestSpellCheck();
5040 bool Paragraph::needsSpellCheck() const
5042 SpellChecker::ChangeNumber speller_change_number = 0;
5043 if (theSpellChecker())
5044 speller_change_number = theSpellChecker()->changeNumber();
5045 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
5046 d->speller_state_.needsCompleteRefresh(speller_change_number);
5048 return d->needsSpellCheck();
5052 bool Paragraph::Private::ignoreWord(docstring const & word) const
5054 // Ignore words with digits
5055 // FIXME: make this customizable
5056 // (note that some checkers ignore words with digits by default)
5057 docstring::const_iterator cit = word.begin();
5058 docstring::const_iterator const end = word.end();
5059 for (; cit != end; ++cit) {
5060 if (isNumber((*cit)))
5067 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
5068 WordLangTuple & wl, docstring_list & suggestions,
5069 bool do_suggestion, bool check_learned) const
5071 SpellChecker::Result result = SpellChecker::WORD_OK;
5072 SpellChecker * speller = theSpellChecker();
5076 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
5079 locateWord(from, to, WHOLE_WORD, true);
5080 if (from == to || from >= size())
5083 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5084 Language * lang = d->getSpellLanguage(from);
5086 BufferParams const & bparams = d->inset_owner_->buffer().params();
5088 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5091 wl = WordLangTuple(word, lang);
5096 if (needsSpellCheck() || check_learned) {
5098 if (!d->ignoreWord(word)) {
5099 bool const trailing_dot = to < size() && d->text_[to] == '.';
5100 result = speller->check(wl, bparams.spellignore());
5101 if (SpellChecker::misspelled(result) && trailing_dot) {
5102 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5103 result = speller->check(wl, bparams.spellignore());
5104 if (!SpellChecker::misspelled(result)) {
5105 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5107 from << ".." << to << "]");
5109 // spell check with dot appended failed too
5110 // restore original word/lang value
5111 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5112 wl = WordLangTuple(word, lang);
5116 if (!SpellChecker::misspelled(result)) {
5117 // area up to the begin of the next word is not misspelled
5118 while (end < size() && isWordSeparator(end))
5121 d->setMisspelled(from, end, result);
5123 result = d->speller_state_.getState(from);
5127 suggestions.clear();
5129 if (SpellChecker::misspelled(result)) {
5130 LYXERR(Debug::GUI, "misspelled word: \"" <<
5132 from << ".." << to << "]");
5134 speller->suggest(wl, suggestions);
5140 void Paragraph::anonymize()
5142 // This is a very crude anonymization for now
5143 for (char_type & c : d->text_)
5144 if (isLetterChar(c) || isNumber(c))
5149 void Paragraph::Private::markMisspelledWords(
5150 Language const * lang,
5151 pos_type const & first, pos_type const & last,
5152 SpellChecker::Result result,
5153 docstring const & word,
5154 SkipPositions const & skips)
5156 if (!SpellChecker::misspelled(result)) {
5157 setMisspelled(first, last, SpellChecker::WORD_OK);
5161 SpellChecker * speller = theSpellChecker();
5162 // locate and enumerate the error positions
5163 int nerrors = speller->numMisspelledWords();
5165 SkipPositionsIterator it = skips.begin();
5166 SkipPositionsIterator et = skips.end();
5167 for (int index = 0; index < nerrors; ++index) {
5170 speller->misspelledWord(index, wstart, wlen);
5171 /// should not happen if speller supports range checks
5174 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5175 wstart += first + numskipped;
5176 if (snext < wstart) {
5177 /// mark the range of correct spelling
5178 numskipped += countSkips(it, et, wstart);
5179 setMisspelled(snext,
5180 wstart - 1, SpellChecker::WORD_OK);
5182 snext = wstart + wlen;
5183 // Check whether the candidate is in the document's local dict
5184 SpellChecker::Result actresult = result;
5185 if (inset_owner_->buffer().params().spellignored(candidate))
5186 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5187 numskipped += countSkips(it, et, snext);
5188 /// mark the range of misspelling
5189 setMisspelled(wstart, snext, actresult);
5190 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5191 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5192 candidate.word() << "\" [" <<
5193 wstart << ".." << (snext-1) << "]");
5195 LYXERR(Debug::GUI, "misspelled word: \"" <<
5196 candidate.word() << "\" [" <<
5197 wstart << ".." << (snext-1) << "]");
5200 if (snext <= last) {
5201 /// mark the range of correct spelling at end
5202 setMisspelled(snext, last, SpellChecker::WORD_OK);
5207 void Paragraph::spellCheck() const
5209 SpellChecker * speller = theSpellChecker();
5210 if (!speller || empty() ||!needsSpellCheck())
5214 d->rangeOfSpellCheck(start, endpos);
5215 if (speller->canCheckParagraph()) {
5216 // loop until we leave the range
5217 for (pos_type first = start; first < endpos; ) {
5218 pos_type last = endpos;
5219 Private::SkipPositions skips;
5220 Language * lang = d->locateSpellRange(first, last, skips);
5221 if (first >= endpos)
5223 // start the spell checker on the unit of meaning
5224 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5225 WordLangTuple wl = WordLangTuple(word, lang);
5226 BufferParams const & bparams = d->inset_owner_->buffer().params();
5227 SpellChecker::Result result = !word.empty() ?
5228 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5229 d->markMisspelledWords(lang, first, last, result, word, skips);
5233 static docstring_list suggestions;
5234 pos_type to = endpos;
5235 while (start < endpos) {
5237 spellCheck(start, to, wl, suggestions, false);
5241 d->readySpellCheck();
5245 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5247 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5248 if (result || pos <= 0 || pos > size())
5250 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5251 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5256 string Paragraph::magicLabel() const
5259 ss << "magicparlabel-" << id();