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);
767 void Paragraph::rejectChanges(pos_type start, pos_type end)
769 LASSERT(start >= 0 && start <= size(), return);
770 LASSERT(end > start && end <= size() + 1, return);
772 // Make sure that Buffer::hasChangesPresent is updated
773 ChangesMonitor cm(*this);
775 for (pos_type pos = start; pos < end; ++pos) {
776 switch (lookupChange(pos).type) {
777 case Change::UNCHANGED:
778 // reject changes in nested inset
779 if (Inset * inset = getInset(pos))
780 inset->rejectChanges();
783 case Change::INSERTED:
784 // Suppress access to non-existent
785 // "end-of-paragraph char"
787 eraseChar(pos, false);
793 case Change::DELETED:
794 d->changes_.set(Change(Change::UNCHANGED), pos);
796 // Do NOT reject changes within a deleted inset!
797 // There may be insertions of a co-author inside of it!
805 void Paragraph::Private::insertChar(pos_type pos, char_type c,
806 Change const & change)
808 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
810 // Make sure that Buffer::hasChangesPresent is updated
811 ChangesMonitor cm(*owner_);
814 changes_.insert(change, pos);
816 // This is actually very common when parsing buffers (and
817 // maybe inserting ascii text)
818 if (pos == pos_type(text_.size())) {
819 // when appending characters, no need to update tables
821 // but we want spell checking
822 requestSpellCheck(pos);
826 text_.insert(text_.begin() + pos, c);
828 // Update the font table.
829 fontlist_.increasePosAfterPos(pos);
832 insetlist_.increasePosAfterPos(pos);
834 // Update list of misspelled positions
835 speller_state_.increasePosAfterPos(pos);
838 if (inset_owner_ && inset_owner_->isBufferValid())
839 theSession().bookmarks().adjustPosAfterPos(inset_owner_->buffer().fileName(),
844 bool Paragraph::insertInset(pos_type pos, Inset * inset,
845 Font const & font, Change const & change)
847 LASSERT(inset, return false);
848 LASSERT(pos >= 0 && pos <= size(), return false);
850 // Make sure that Buffer::hasChangesPresent is updated
851 ChangesMonitor cm(*this);
853 // Paragraph::insertInset() can be used in cut/copy/paste operation where
854 // d->inset_owner_ is not set yet.
855 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
858 d->insertChar(pos, META_INSET, change);
859 LASSERT(d->text_[pos] == META_INSET, return false);
861 // Add a new entry in the insetlist_.
862 d->insetlist_.insert(inset, pos);
864 // Some insets require run of spell checker
865 requestSpellCheck(pos);
871 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
873 LASSERT(pos >= 0 && pos <= size(), return false);
875 // Make sure that Buffer::hasChangesPresent is updated
876 ChangesMonitor cm(*this);
878 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
881 Change change = d->changes_.lookup(pos);
883 // set the character to DELETED if
884 // a) it was previously unchanged or
885 // b) it was inserted by a co-author
887 if (!change.changed() ||
888 (change.inserted() && !change.currentAuthor())) {
889 setChange(pos, Change(Change::DELETED));
890 // request run of spell checker
891 requestSpellCheck(pos);
895 if (change.deleted())
899 // Don't physically access the imaginary end-of-paragraph character.
900 // eraseChar() can only mark it as DELETED. A physical deletion of
901 // end-of-par must be handled externally.
907 d->changes_.erase(pos);
909 // if it is an inset, delete the inset entry
910 if (d->text_[pos] == META_INSET)
911 d->insetlist_.erase(pos);
913 d->text_.erase(d->text_.begin() + pos);
915 // Update the fontlist_
916 d->fontlist_.erase(pos);
918 // Update the insetlist_
919 d->insetlist_.decreasePosAfterPos(pos);
921 // Update list of misspelled positions
922 d->speller_state_.decreasePosAfterPos(pos);
923 d->speller_state_.refreshLast(size());
926 if (d->inset_owner_ && d->inset_owner_->isBufferValid())
927 theSession().bookmarks().adjustPosAfterPos(d->inset_owner_->buffer().fileName(),
934 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
936 LASSERT(start >= 0 && start <= size(), return 0);
937 LASSERT(end >= start && end <= size() + 1, return 0);
940 for (pos_type count = end - start; count; --count) {
941 if (!eraseChar(i, trackChanges))
948 // Handle combining characters
949 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
950 otexstream & os, char_type c, char_type next,
951 OutputParams const & runparams) const
953 // Writing next here may circumvent a possible font change between
954 // c and next. Since next is only output if it forms a surrogate pair
955 // with c we can ignore this:
956 // A font change inside a surrogate pair does not make sense and is
957 // hopefully impossible to input.
958 // FIXME: change tracking
959 // Is this correct WRT change tracking?
960 Encoding const & encoding = *(runparams.encoding);
961 docstring latex1 = encoding.latexChar(next).first;
962 if (runparams.inIPA) {
963 string const tipashortcut = Encodings::TIPAShortcut(next);
964 if (!tipashortcut.empty()) {
965 latex1 = from_ascii(tipashortcut);
968 docstring latex2 = encoding.latexChar(c).first;
970 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
971 // Encoding supports the combination:
972 // output as is (combining char after base char).
973 os << latex2 << latex1;
974 return latex1.length() + latex2.length();
977 os << latex1 << "{" << latex2 << "}";
978 return latex1.length() + latex2.length() + 2;
982 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
983 OutputParams const & runparams,
986 unsigned int & column,
988 Layout const & style) const
990 if (style.pass_thru || runparams.pass_thru)
993 if (i + 1 < int(text_.size())) {
994 char_type next = text_[i + 1];
995 if (Encodings::isCombiningChar(next)) {
996 // This space has an accent, so we must always output it.
997 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
1002 if (runparams.linelen > 0
1003 && column > runparams.linelen
1005 && text_[i - 1] != ' '
1006 && (i + 1 < int(text_.size()))
1007 // same in FreeSpacing mode
1008 && !owner_->isFreeSpacing()
1009 // In typewriter mode, we want to avoid
1010 // ! . ? : at the end of a line
1011 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1012 && (text_[i - 1] == '.'
1013 || text_[i - 1] == '?'
1014 || text_[i - 1] == ':'
1015 || text_[i - 1] == '!'))) {
1017 os.texrow().start(owner_->id(), i + 1);
1019 } else if (style.free_spacing) {
1028 void Paragraph::Private::latexInset(BufferParams const & bparams,
1030 OutputParams & runparams,
1031 Font & running_font,
1033 Font const & outerfont,
1035 Change & running_change,
1036 Layout const & style,
1038 unsigned int & column,
1039 bool const fontswitch_inset,
1040 bool const closeLanguage,
1041 bool const lang_switched_at_inset) const
1043 Inset * inset = owner_->getInset(i);
1046 if (style.pass_thru) {
1047 odocstringstream ods;
1048 inset->plaintext(ods, runparams);
1053 // FIXME: move this to InsetNewline::latex
1054 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1055 // newlines are handled differently here than
1056 // the default in simpleTeXSpecialChars().
1057 if (!style.newline_allowed) {
1061 bool needPar = false;
1062 column += running_font.latexWriteEndChanges(
1063 os, bparams, runparams,
1064 basefont, basefont, needPar);
1068 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1071 basefont = owner_->getLayoutFont(bparams, outerfont);
1072 running_font = basefont;
1074 if (runparams.moving_arg)
1078 os.texrow().start(owner_->id(), i + 1);
1082 if (owner_->isDeleted(i)) {
1083 if( ++runparams.inDeletedInset == 1)
1084 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1087 if (inset->canTrackChanges()) {
1088 column += Changes::latexMarkChange(os, bparams, running_change,
1089 Change(Change::UNCHANGED), runparams);
1090 running_change = Change(Change::UNCHANGED);
1093 unsigned int close_brace = 0;
1094 bool const disp_env = (inset->isEnvironment() && inset->getLayout().isDisplay())
1095 || runparams.inDisplayMath;
1097 odocstream::pos_type const len = os.os().tellp();
1099 if (inset->forceLTR(runparams)
1100 // babel with LuaTeX does not need a switch
1101 // babel with XeTeX needs a switch only if bidi is used
1102 // and \L is not defined there.
1103 && (!runparams.isFullUnicode() || bparams.useBidiPackage(runparams) || runparams.use_polyglossia)
1104 && running_font.isRightToLeft()) {
1105 if (bparams.useBidiPackage(runparams) || 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
1175 && !runparams.no_cprotect
1177 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1183 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1187 runparams.local_font = &basefont;
1190 if (fontswitch_inset && !closeLanguage) {
1191 // The directionality has been switched at inset.
1192 // Force markup inside.
1193 runparams.local_font = &basefont;
1196 size_t const previous_row_count = os.texrow().rows();
1199 runparams.lastid = id_;
1200 runparams.lastpos = i;
1201 inset->latex(os, runparams);
1202 } catch (EncodingException & e) {
1203 // add location information and throw again.
1209 if (!close_env.empty())
1210 os << "\\end{" << close_env << "}";
1212 if (close_brace > 0) {
1213 for (unsigned i = 0; i < close_brace; ++i)
1219 if (os.texrow().rows() > previous_row_count) {
1220 os.texrow().start(owner_->id(), i + 1);
1223 column += (unsigned int)(os.os().tellp() - len);
1226 if (owner_->isDeleted(i))
1227 --runparams.inDeletedInset;
1231 void Paragraph::Private::latexSpecialChar(otexstream & os,
1232 BufferParams const & bparams,
1233 OutputParams const & runparams,
1234 Font const & running_font,
1235 string & alien_script,
1236 Layout const & style,
1239 unsigned int & column) const
1241 char_type const c = owner_->getUChar(bparams, runparams, i);
1243 if ((style.pass_thru || runparams.pass_thru || runparams.find_effective()
1244 || contains(style.pass_thru_chars, c)
1245 || contains(runparams.pass_thru_chars, c))
1246 && !contains(runparams.no_pass_thru_chars, c)) {
1247 if (runparams.find_effective()) {
1253 os << "\\braceleft ";
1256 os << "\\braceright ";
1259 os << "\\lyxdollar ";
1262 os << "\\lyxtilde ";
1272 else if (c != '\0') {
1273 Encoding const * const enc = runparams.encoding;
1274 if (enc && !enc->encodable(c))
1275 throw EncodingException(c);
1281 // TIPA uses its own T3 encoding
1282 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1284 // If T1 font encoding is used, use the special
1285 // characters it provides.
1286 // NOTE: Some languages reset the font encoding internally to a
1287 // non-standard font encoding. If we are using such a language,
1288 // we do not output special T1 chars.
1289 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1290 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1291 && latexSpecialT1(c, os, i, column))
1293 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1294 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1295 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1298 // Otherwise, we use what LaTeX provides us.
1301 os << "\\textbackslash" << termcmd;
1305 os << "\\textless" << termcmd;
1309 os << "\\textgreater" << termcmd;
1313 os << "\\textbar" << termcmd;
1318 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1319 (end_pos == -1 || i + 1 < end_pos) &&
1320 text_[i+1] == '-') {
1321 // Prevent "--" becoming an en dash and "---" an em dash.
1322 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1328 os << "\\textquotedbl" << termcmd;
1333 case '%': case '#': case '{':
1341 os << "\\textasciitilde" << termcmd;
1346 os << "\\textasciicircum" << termcmd;
1353 // avoid being mistaken for optional arguments
1361 // Blanks are printed before font switching.
1362 // Sure? I am not! (try nice-latex)
1363 // I am sure it's correct. LyX might be smarter
1364 // in the future, but for now, nothing wrong is
1370 // XeTeX's dash behaviour is determined via a global setting
1371 if (bparams.use_dash_ligatures
1372 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1374 // TODO #10961: && not in inset Flex Code
1375 // TODO #10961: && not in layout LyXCode
1376 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1393 Encoding const & encoding = *(runparams.encoding);
1394 char_type next = '\0';
1395 if (i + 1 < int(text_.size())) {
1396 next = text_[i + 1];
1397 if (Encodings::isCombiningChar(next)) {
1398 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1403 pair<docstring, bool> latex = encoding.latexChar(c);
1404 docstring nextlatex;
1405 bool nexttipas = false;
1406 string nexttipashortcut;
1407 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1408 nextlatex = encoding.latexChar(next).first;
1409 if (runparams.inIPA) {
1410 nexttipashortcut = Encodings::TIPAShortcut(next);
1411 nexttipas = !nexttipashortcut.empty();
1415 if (runparams.inIPA) {
1416 string const tipashortcut = Encodings::TIPAShortcut(c);
1417 if (!tipashortcut.empty()) {
1418 latex.first = from_ascii(tipashortcut);
1419 latex.second = false;
1423 // eventually close "script wrapper" command (see `Paragraph::latex`)
1424 if (!alien_script.empty()
1425 && alien_script != Encodings::isKnownScriptChar(next)) {
1426 column += latex.first.length();
1427 alien_script.clear();
1428 os << latex.first << "}";
1432 && ((!prefixIs(nextlatex, '\\')
1433 && !prefixIs(nextlatex, '{')
1434 && !prefixIs(nextlatex, '}'))
1436 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1438 // Prevent eating of a following space or command corruption by
1439 // following characters
1440 if (next == ' ' || next == '\0') {
1441 column += latex.first.length() + 1;
1442 os << latex.first << "{}";
1444 column += latex.first.length();
1445 os << latex.first << " ";
1448 column += latex.first.length() - 1;
1456 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1457 pos_type i, unsigned int & column) const
1463 // In T1 encoding, these characters exist
1464 // but we should avoid ligatures
1465 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1467 os << "\\textcompwordmark" << termcmd;
1474 // soul.sty breaks with \char`\"
1475 os << "\\textquotedbl" << termcmd;
1484 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1485 pos_type i, unsigned int & column) const
1487 // TU encoding is currently on par with T1.
1488 return latexSpecialT1(c, os, i, column);
1492 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1493 pos_type /*i*/, unsigned int & column) const
1503 os << "\\textvertline" << termcmd;
1512 void Paragraph::Private::validate(LaTeXFeatures & features) const
1514 if (layout_->inpreamble && inset_owner_) {
1515 // FIXME: Using a string stream here circumvents the encoding
1516 // switching machinery of odocstream. Therefore the
1517 // output is wrong if this paragraph contains content
1518 // that needs to switch encoding.
1519 Buffer const & buf = inset_owner_->buffer();
1520 otexstringstream os;
1521 os << layout_->preamble();
1522 size_t const length = os.length();
1523 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1524 buf.getParFromID(owner_->id()).pit(), os,
1525 features.runparams(), string(), 0, -1, true);
1526 if (os.length() > length)
1527 features.addPreambleSnippet(os.release(), true);
1530 if (features.runparams().flavor == Flavor::Html
1531 && layout_->htmltitle()) {
1532 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1535 // check the params.
1536 if (!params_.spacing().isDefault())
1537 features.require("setspace");
1540 features.useLayout(layout_->name());
1543 fontlist_.validate(features);
1545 // then the indentation
1546 if (!params_.leftIndent().zero())
1547 features.require("ParagraphLeftIndent");
1550 InsetList::const_iterator icit = insetlist_.begin();
1551 InsetList::const_iterator iend = insetlist_.end();
1552 for (; icit != iend; ++icit) {
1554 features.inDeletedInset(owner_->isDeleted(icit->pos));
1555 if (icit->inset->lyxCode() == FOOT_CODE) {
1556 // FIXME: an item inset would make things much easier.
1557 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1558 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1559 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1560 && (icit->pos < begin_of_body_
1561 || (icit->pos == begin_of_body_
1562 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1563 features.saveNoteEnv("description");
1565 icit->inset->validate(features);
1566 features.inDeletedInset(false);
1567 if (layout_->needprotect &&
1568 icit->inset->lyxCode() == FOOT_CODE)
1569 features.require("NeedLyXFootnoteCode");
1573 // then the contents
1574 BufferParams const bp = features.runparams().is_child
1575 ? features.buffer().masterParams() : features.buffer().params();
1576 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1577 char_type c = text_[i];
1578 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1580 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1581 features.require("textquotedblp");
1582 else if (features.runparams().main_fontenc != "T1"
1583 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1584 features.require("textquotedbl");
1585 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1586 // features that depend on the font or input encoding
1587 string feats = ci.textPreamble();
1588 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1589 if (fontenc.empty())
1590 fontenc = features.runparams().main_fontenc;
1591 while (!feats.empty()) {
1593 feats = split(feats, feat, ',');
1594 if (contains(feat, "!=")) {
1595 // a feature that is required except for the spcified
1596 // font or input encodings
1598 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1599 // multiple encodings are separated by semicolon
1600 vector<string> context = getVectorFromString(contexts, ";");
1601 // require feature if the context matches neither current font
1602 // nor input encoding
1603 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1604 && std::find(context.begin(), context.end(),
1605 features.runparams().encoding->name()) == context.end())
1606 features.require(realfeature);
1607 } else if (contains(feat, '=')) {
1608 // a feature that is required only for the spcified
1609 // font or input encodings
1611 string const contexts = split(feat, realfeature, '=');
1612 // multiple encodings are separated by semicolon
1613 vector<string> context = getVectorFromString(contexts, ";");
1614 // require feature if the context matches either current font
1615 // or input encoding
1616 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1617 || std::find(context.begin(), context.end(),
1618 features.runparams().encoding->name()) != context.end())
1619 features.require(realfeature);
1622 } else if (!bp.use_dash_ligatures
1623 && (c == 0x2013 || c == 0x2014)
1624 && bp.useNonTeXFonts
1625 && features.runparams().flavor == Flavor::XeTeX)
1626 // XeTeX's dash behaviour is determined via a global setting
1627 features.require("xetexdashbreakstate");
1628 BufferEncodings::validate(c, features);
1632 /////////////////////////////////////////////////////////////////////
1636 /////////////////////////////////////////////////////////////////////
1639 Layout const emptyParagraphLayout;
1642 Paragraph::Paragraph()
1643 : d(new Paragraph::Private(this, emptyParagraphLayout))
1650 Paragraph::Paragraph(Paragraph const & par)
1651 : itemdepth(par.itemdepth),
1652 d(new Paragraph::Private(*par.d, this))
1658 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1659 : itemdepth(par.itemdepth),
1660 d(new Paragraph::Private(*par.d, this, beg, end))
1666 Paragraph & Paragraph::operator=(Paragraph const & par)
1668 // needed as we will destroy the private part before copying it
1670 itemdepth = par.itemdepth;
1674 d = new Private(*par.d, this);
1681 Paragraph::~Paragraph()
1690 // this shall be called just before every "os << ..." action.
1691 void flushString(ostream & os, docstring & s)
1700 void Paragraph::write(ostream & os, BufferParams const & bparams,
1701 depth_type & depth) const
1703 // The beginning or end of a deeper (i.e. nested) area?
1704 if (depth != d->params_.depth()) {
1705 if (d->params_.depth() > depth) {
1706 while (d->params_.depth() > depth) {
1707 os << "\n\\begin_deeper";
1711 while (d->params_.depth() < depth) {
1712 os << "\n\\end_deeper";
1718 // First write the layout
1719 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1721 d->params_.write(os);
1723 Font font1(inherit_font, bparams.language);
1725 Change running_change = Change(Change::UNCHANGED);
1727 // this string is used as a buffer to avoid repetitive calls
1728 // to to_utf8(), which turn out to be expensive (JMarc)
1729 docstring write_buffer;
1732 for (pos_type i = 0; i <= size(); ++i) {
1734 Change const & change = lookupChange(i);
1735 if (change != running_change)
1736 flushString(os, write_buffer);
1737 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1738 running_change = change;
1743 // Write font changes
1744 Font font2 = getFontSettings(bparams, i);
1745 if (font2 != font1) {
1746 flushString(os, write_buffer);
1747 font2.lyxWriteChanges(font1, os);
1752 char_type const c = d->text_[i];
1755 if (Inset const * inset = getInset(i)) {
1756 flushString(os, write_buffer);
1757 if (inset->directWrite()) {
1758 // international char, let it write
1759 // code directly so it's shorter in
1765 os << "\\begin_inset ";
1767 os << "\n\\end_inset\n\n";
1770 // FIXME This can be removed again once the mystery
1771 // crash has been resolved.
1776 flushString(os, write_buffer);
1777 os << "\n\\backslash\n";
1786 case 0x061F: // ؟ U+061F ARABIC QUESTION MARK
1787 case 0x061B: // ؛ U+061B ARABIC SEMICOLON
1788 case 0x060C: // ، U+060C ARABIC COMMA
1789 flushString(os, write_buffer);
1790 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1791 os << to_utf8(docstring(1, c)) << '\n';
1794 os << to_utf8(docstring(1, c));
1796 case 0x2014: // — U+2014 EM DASH
1797 case 0x3002: // 。 U+3002 IDEOGRAPHIC FULL STOP
1798 case 0xFF01: // ! U+FF01 FULLWIDTH EXCLAMATION MARK
1799 case 0xFF1F: // ? U+FF1F FULLWIDTH QUESTION MARK
1800 case 0xFF1A: // : U+FF1A FULLWIDTH COLON
1801 case 0xFF1B: // ; U+FF1B FULLWIDTH SEMICOLON
1802 case 0xFF0C: // , U+FF0C FULLWIDTH COMMA
1803 flushString(os, write_buffer);
1804 os << to_utf8(docstring(1, c)) << '\n';
1809 flushString(os, write_buffer);
1813 // this check is to amend a bug. LyX sometimes
1814 // inserts '\0' this could cause problems.
1816 write_buffer.push_back(c);
1818 LYXERR0("NUL char in structure.");
1824 flushString(os, write_buffer);
1825 os << "\n\\end_layout\n";
1826 // FIXME This can be removed again once the mystery
1827 // crash has been resolved.
1832 void Paragraph::validate(LaTeXFeatures & features) const
1834 d->validate(features);
1835 bool fragile = features.runparams().moving_arg;
1836 fragile |= layout().needprotect;
1837 if (inInset().getLayout().isNeedProtect())
1839 if (needsCProtection(fragile))
1840 features.require("cprotect");
1844 void Paragraph::insert(pos_type pos, docstring const & str,
1845 Font const & font, Change const & change)
1847 for (size_t i = 0, n = str.size(); i != n ; ++i)
1848 insertChar(pos + i, str[i], font, change);
1852 void Paragraph::appendChar(char_type c, Font const & font,
1853 Change const & change)
1855 // Make sure that Buffer::hasChangesPresent is updated
1856 ChangesMonitor cm(*this);
1859 d->changes_.insert(change, d->text_.size());
1860 // when appending characters, no need to update tables
1861 d->text_.push_back(c);
1862 setFont(d->text_.size() - 1, font);
1863 d->requestSpellCheck(d->text_.size() - 1);
1867 void Paragraph::appendString(docstring const & s, Font const & font,
1868 Change const & change)
1870 // Make sure that Buffer::hasChangesPresent is updated
1871 ChangesMonitor cm(*this);
1873 pos_type end = s.size();
1874 size_t oldsize = d->text_.size();
1875 size_t newsize = oldsize + end;
1876 size_t capacity = d->text_.capacity();
1877 if (newsize >= capacity)
1878 d->text_.reserve(max(capacity + 100, newsize));
1880 // when appending characters, no need to update tables
1883 // FIXME: Optimize this!
1884 for (size_t i = oldsize; i != newsize; ++i) {
1886 d->changes_.insert(change, i);
1887 d->requestSpellCheck(i);
1889 d->fontlist_.set(oldsize, font);
1890 d->fontlist_.set(newsize - 1, font);
1894 void Paragraph::insertChar(pos_type pos, char_type c,
1897 d->insertChar(pos, c, Change(trackChanges ?
1898 Change::INSERTED : Change::UNCHANGED));
1902 void Paragraph::insertChar(pos_type pos, char_type c,
1903 Font const & font, bool trackChanges)
1905 d->insertChar(pos, c, Change(trackChanges ?
1906 Change::INSERTED : Change::UNCHANGED));
1911 void Paragraph::insertChar(pos_type pos, char_type c,
1912 Font const & font, Change const & change)
1914 d->insertChar(pos, c, change);
1919 void Paragraph::resetFonts(Font const & font)
1921 d->fontlist_.clear();
1922 d->fontlist_.set(0, font);
1923 d->fontlist_.set(d->text_.size() - 1, font);
1926 // Gets uninstantiated font setting at position.
1927 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1931 LYXERR0("pos: " << pos << " size: " << size());
1935 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1936 if (cit != d->fontlist_.end())
1939 if (pos == size() && !empty())
1940 return getFontSettings(bparams, pos - 1);
1942 // Optimisation: avoid a full font instantiation if there is no
1943 // language change from previous call.
1944 static Font previous_font;
1945 static Language const * previous_lang = nullptr;
1946 Language const * lang = getParLanguage(bparams);
1947 if (lang != previous_lang) {
1948 previous_lang = lang;
1949 previous_font = Font(inherit_font, lang);
1951 return previous_font;
1955 FontSpan Paragraph::fontSpan(pos_type pos) const
1957 LBUFERR(pos <= size());
1960 return FontSpan(pos, pos);
1963 FontList::const_iterator cit = d->fontlist_.begin();
1964 FontList::const_iterator end = d->fontlist_.end();
1965 for (; cit != end; ++cit) {
1966 if (cit->pos() >= pos) {
1967 if (pos >= beginOfBody())
1968 return FontSpan(max(start, beginOfBody()),
1971 return FontSpan(start,
1972 min(beginOfBody() - 1,
1975 start = cit->pos() + 1;
1978 // This should not happen, but if so, we take no chances.
1979 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1980 LASSERT(false, /**/);
1981 return FontSpan(pos, pos);
1985 // Gets uninstantiated font setting at position 0
1986 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1988 if (!empty() && !d->fontlist_.empty())
1989 return d->fontlist_.begin()->font();
1991 // Optimisation: avoid a full font instantiation if there is no
1992 // language change from previous call.
1993 static Font previous_font;
1994 static Language const * previous_lang = nullptr;
1995 if (bparams.language != previous_lang) {
1996 previous_lang = bparams.language;
1997 previous_font = Font(inherit_font, bparams.language);
2000 return previous_font;
2004 // Gets the fully instantiated font at a given position in a paragraph
2005 // This is basically the same function as TextMetrics::displayFont().
2006 // The difference is that this one is used for generating the LaTeX file,
2007 // and thus cosmetic "improvements" are disallowed: This has to deliver
2008 // the true picture of the buffer. (Asger)
2009 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
2010 Font const & outerfont) const
2014 Font font = getFontSettings(bparams, pos);
2016 pos_type const body_pos = beginOfBody();
2017 FontInfo & fi = font.fontInfo();
2019 fi.realize(d->layout_->labelfont);
2021 fi.realize(d->layout_->font);
2023 fi.realize(outerfont.fontInfo());
2024 fi.realize(bparams.getFont().fontInfo());
2030 Font const Paragraph::getLabelFont
2031 (BufferParams const & bparams, Font const & outerfont) const
2033 FontInfo tmpfont = d->layout_->labelfont;
2034 tmpfont.realize(outerfont.fontInfo());
2035 tmpfont.realize(bparams.getFont().fontInfo());
2036 return Font(tmpfont, getParLanguage(bparams));
2040 Font const Paragraph::getLayoutFont
2041 (BufferParams const & bparams, Font const & outerfont) const
2043 FontInfo tmpfont = d->layout_->font;
2044 tmpfont.realize(outerfont.fontInfo());
2045 tmpfont.realize(bparams.getFont().fontInfo());
2046 return Font(tmpfont, getParLanguage(bparams));
2050 char_type Paragraph::getUChar(BufferParams const & bparams,
2051 OutputParams const & rp,
2054 char_type c = d->text_[pos];
2056 // Return unchanged character
2057 // 1. in all LTR languages
2058 // 2. if we use XeTeX (both with babel and polyglossia)
2059 // 3. if we use LuaTeX with babel
2060 if (!getFontSettings(bparams, pos).isRightToLeft()
2061 || rp.flavor == Flavor::XeTeX
2062 || (rp.use_babel && rp.flavor == Flavor::LuaTeX))
2065 // For the remaining cases, we need to account for some special cases.
2066 // FIXME This needs to be audited!
2068 // * The input is as expected for all delimiters
2069 // => checked for Hebrew!
2070 // * The output matches the display in the LyX workarea
2071 // => checked for Hebrew!
2072 // * The special cases below are really necessary
2073 // => checked for Hebrew!
2074 // * In arabic_arabi, brackets are transformed to Arabic
2075 // Ornate Parentheses. Is this is really wanted?
2076 // => Yes, in file ararabeyes.enc from the arabi bundle
2077 // the slot of the left bracket (slot 91) is encoded as
2078 // "ornaterightparenthesis". This is also the reason
2079 // brackets don't need to be mirrored with arabi
2081 string const & lang = getFontSettings(bparams, pos).language()->lang();
2084 // These are the cases where we need to mirror delimiters in RTL context
2085 // in the remaining cases (polyglossia + LuaTeX or classic [pdf]latex):
2086 // 1. With polyglossia and LuaTeX (luabidi) parentheses and brackets
2087 // need to be mirrored in RTL, regardless of the language, or script.
2088 // 2. In the languages that follow, parentheses need to be mirrored
2089 // in classic (pdf)latex
2090 bool const reverseparens = (rp.use_polyglossia || lang == "hebrew");
2091 // 3. In all RTL languages except for those that follow, brackets
2092 // need to be mirrored in classic (pdf)latex
2093 bool const reversebrackets = rp.use_polyglossia
2094 || (lang != "arabic_arabtex"
2095 && lang != "arabic_arabi"
2096 && lang != "farsi");
2098 // Now swap delimiters if needed.
2109 if (reversebrackets)
2113 if (reversebrackets)
2134 void Paragraph::setFont(pos_type pos, Font const & font)
2136 LASSERT(pos <= size(), return);
2138 // Text::setCharFont() already reduces font against layout/label
2139 // font, so we don't need to do that here. (Asger)
2140 d->fontlist_.set(pos, font);
2144 void Paragraph::makeSameLayout(Paragraph const & par)
2146 d->layout_ = par.d->layout_;
2147 d->params_ = par.d->params_;
2151 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2153 if (isFreeSpacing())
2159 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2160 if (eraseChar(pos, trackChanges))
2166 return count > 0 || pos > 0;
2170 bool Paragraph::hasSameLayout(Paragraph const & par) const
2172 return par.d->layout_ == d->layout_
2173 && d->params_.sameLayout(par.d->params_);
2177 depth_type Paragraph::getDepth() const
2179 return d->params_.depth();
2183 depth_type Paragraph::getMaxDepthAfter() const
2185 if (d->layout_->isEnvironment())
2186 return d->params_.depth() + 1;
2188 return d->params_.depth();
2192 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2194 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2195 return getDefaultAlign(bparams);
2197 return d->params_.align();
2201 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2203 LyXAlignment res = layout().align;
2204 if (isRTL(bparams)) {
2206 if (res == LYX_ALIGN_LEFT)
2207 res = LYX_ALIGN_RIGHT;
2208 else if (res == LYX_ALIGN_RIGHT)
2209 res = LYX_ALIGN_LEFT;
2215 docstring const & Paragraph::labelString() const
2217 return d->params_.labelString();
2221 // the next two functions are for the manual labels
2222 docstring const Paragraph::getLabelWidthString() const
2224 if (d->layout_->margintype == MARGIN_MANUAL
2225 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2226 return d->params_.labelWidthString();
2228 return _("Senseless with this layout!");
2232 void Paragraph::setLabelWidthString(docstring const & s)
2234 d->params_.labelWidthString(s);
2238 docstring Paragraph::expandLabel(Layout const & layout,
2239 BufferParams const & bparams) const
2241 return expandParagraphLabel(layout, bparams, true);
2245 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2246 BufferParams const & bparams, bool process_appendix) const
2248 DocumentClass const & tclass = bparams.documentClass();
2249 string const & lang = getParLanguage(bparams)->code();
2250 bool const in_appendix = process_appendix && d->params_.appendix();
2251 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2253 if (fmt.empty() && !layout.counter.empty())
2254 return tclass.counters().theCounter(layout.counter, lang);
2256 // handle 'inherited level parts' in 'fmt',
2257 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2258 size_t const i = fmt.find('@', 0);
2259 if (i != docstring::npos) {
2260 size_t const j = fmt.find('@', i + 1);
2261 if (j != docstring::npos) {
2262 docstring parent(fmt, i + 1, j - i - 1);
2263 docstring label = from_ascii("??");
2264 if (tclass.hasLayout(parent))
2265 label = expandParagraphLabel(tclass[parent], bparams,
2267 fmt = docstring(fmt, 0, i) + label
2268 + docstring(fmt, j + 1, docstring::npos);
2272 return tclass.counters().counterLabel(fmt, lang);
2276 void Paragraph::applyLayout(Layout const & new_layout)
2278 d->layout_ = &new_layout;
2279 LyXAlignment const oldAlign = d->params_.align();
2281 if (!(oldAlign & d->layout_->alignpossible)) {
2282 frontend::Alert::warning(_("Alignment not permitted"),
2283 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2284 d->params_.align(LYX_ALIGN_LAYOUT);
2289 pos_type Paragraph::beginOfBody() const
2291 return d->begin_of_body_;
2295 void Paragraph::setBeginOfBody()
2297 if (d->layout_->labeltype != LABEL_MANUAL) {
2298 d->begin_of_body_ = 0;
2302 // Unroll the first two cycles of the loop
2303 // and remember the previous character to
2304 // remove unnecessary getChar() calls
2306 pos_type end = size();
2307 bool prev_char_deleted = false;
2308 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2311 char_type previous_char = d->text_[i];
2312 if (!(isNewline(i) || isEnvSeparator(i))) {
2314 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2315 char_type temp = d->text_[i];
2316 prev_char_deleted = isDeleted(i);
2317 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2320 previous_char = temp;
2326 d->begin_of_body_ = i;
2330 bool Paragraph::allowParagraphCustomization() const
2332 return inInset().allowParagraphCustomization();
2336 bool Paragraph::usePlainLayout() const
2338 return inInset().usePlainLayout();
2342 bool Paragraph::isPassThru() const
2344 return inInset().isPassThru() || d->layout_->pass_thru;
2348 bool Paragraph::parbreakIsNewline() const
2350 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2354 bool Paragraph::allowedInContext(Cursor const & cur, InsetLayout const & il) const
2356 set<docstring> const & allowed_insets = il.allowedInInsets();
2357 set<docstring> const & allowed_layouts = il.allowedInLayouts();
2359 bool in_allowed_inset =
2360 allowed_insets.find(inInset().getLayout().name()) != allowed_insets.end();
2362 bool in_allowed_layout =
2363 allowed_layouts.find(d->layout_->name()) != allowed_layouts.end();
2365 if (!in_allowed_inset && inInset().asInsetArgument()) {
2366 // check if the argument allows the inset in question
2367 if (cur.depth() > 1) {
2368 docstring parlayout = cur[cur.depth() - 2].inset().getLayout().name()
2369 + from_ascii("@") + from_ascii(inInset().asInsetArgument()->name());
2370 if (allowed_insets.find(parlayout) != allowed_insets.end())
2371 in_allowed_inset = true;
2376 // check if we exceed the number of allowed insets in this inset
2377 if (in_allowed_inset && inInset().asInsetText() && il.allowedOccurrences() != -1) {
2378 ParagraphList & pars = cur.text()->paragraphs();
2379 for (Paragraph const & par : pars) {
2380 for (auto const & elem : par.insetList())
2381 if (elem.inset->getLayout().name() == il.name())
2384 if (have_ins >= il.allowedOccurrences())
2389 // check if we exceed the number of allowed insets in the layout group
2390 if (in_allowed_layout && il.allowedOccurrences() != -1) {
2391 pit_type pit = cur.pit();
2392 pit_type lastpit = cur.pit();
2393 ParagraphList & pars = cur.text()->paragraphs();
2394 // If we are not on a list-type environment or AllowedOccurrencesPerItem
2395 // is false, we check the whole paragraph group
2396 if (d->layout_->isEnvironment()
2397 && !(il.allowedOccurrencesPerItem()
2398 && (d->layout_->latextype == LATEX_LIST_ENVIRONMENT
2399 || d->layout_->latextype == LATEX_ITEM_ENVIRONMENT))) {
2400 lastpit = cur.lastpit();
2401 // get the first paragraph in sequence with this layout
2402 depth_type const current_depth = params().depth();
2406 Paragraph cpar = pars[pit - 1];
2407 if (&cpar.layout() == d->layout_
2408 && cpar.params().depth() == current_depth)
2414 for (; pit <= lastpit; ++pit) {
2415 if (&pars[pit].layout() != d->layout_)
2417 for (auto const & elem : pars[pit].insetList())
2418 if (elem.inset->getLayout().name() == il.name())
2421 if (have_ins >= il.allowedOccurrences())
2425 if (in_allowed_layout || in_allowed_inset)
2428 return (allowed_insets.empty() && allowed_layouts.empty());
2432 bool Paragraph::isPartOfTextSequence() const
2434 for (pos_type i = 0; i < size(); ++i) {
2435 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2443 // paragraphs inside floats need different alignment tags to avoid
2446 bool noTrivlistCentering(InsetCode code)
2448 return code == FLOAT_CODE
2449 || code == WRAP_CODE
2450 || code == CELL_CODE;
2454 string correction(string const & orig)
2456 if (orig == "flushleft")
2457 return "raggedright";
2458 if (orig == "flushright")
2459 return "raggedleft";
2460 if (orig == "center")
2466 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2467 InsetCode code, bool const lastpar, int & col)
2469 string macro = suffix + "{";
2470 if (noTrivlistCentering(code)) {
2472 // the last paragraph in non-trivlist-aligned
2473 // context is special (to avoid unwanted whitespace)
2474 if (suffix == "\\begin") {
2475 macro = "\\" + correction(env) + "{}";
2476 os << from_ascii(macro);
2477 col += macro.size();
2482 macro += correction(env);
2486 if (suffix == "\\par\\end") {
2490 os << from_ascii(macro);
2491 col += macro.size();
2492 if (suffix == "\\begin") {
2502 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2503 otexstream & os, OutputParams const & runparams) const
2508 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2509 (layout_->toggle_indent != ITOGGLE_NEVER) :
2510 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2512 LyXAlignment const curAlign = params_.align();
2514 // Do not output \\noindent for paragraphs
2515 // 1. that cannot have indentation or are indented always,
2516 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2517 // 3. that are PassThru,
2518 // 4. or that are centered.
2519 if (canindent && params_.noindent()
2520 && owner_->isPartOfTextSequence()
2521 && !layout_->pass_thru
2522 && curAlign != LYX_ALIGN_CENTER) {
2523 if (!owner_->empty()
2524 && owner_->getInset(0)
2525 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2526 // If the paragraph starts with a vspace, the \\noindent
2527 // needs to come after that (as it leaves vmode).
2528 // If the paragraph consists only of the vspace,
2529 // \\noindent is not needed at all.
2530 runparams.need_noindent = owner_->size() > 1;
2532 os << "\\noindent" << termcmd;
2537 if (curAlign == layout_->align)
2541 case LYX_ALIGN_NONE:
2542 case LYX_ALIGN_BLOCK:
2543 case LYX_ALIGN_LAYOUT:
2544 case LYX_ALIGN_SPECIAL:
2545 case LYX_ALIGN_DECIMAL:
2547 case LYX_ALIGN_LEFT:
2548 case LYX_ALIGN_RIGHT:
2549 case LYX_ALIGN_CENTER:
2550 if (runparams.moving_arg) {
2557 string const begin_tag = "\\begin";
2558 InsetCode code = ownerCode();
2559 bool const lastpar = runparams.isLastPar;
2560 // RTL in classic (PDF)LaTeX (without the Bidi package)
2561 // Luabibdi (used by LuaTeX) behaves like classic
2562 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2563 && !bparams.useBidiPackage(runparams);
2566 case LYX_ALIGN_NONE:
2567 case LYX_ALIGN_BLOCK:
2568 case LYX_ALIGN_LAYOUT:
2569 case LYX_ALIGN_SPECIAL:
2570 case LYX_ALIGN_DECIMAL:
2572 case LYX_ALIGN_LEFT: {
2574 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2575 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2577 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2579 } case LYX_ALIGN_RIGHT: {
2581 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2582 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2584 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2586 } case LYX_ALIGN_CENTER: {
2587 corrected_env(os, begin_tag, "center", code, lastpar, column);
2596 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2597 otexstream & os, OutputParams const & runparams) const
2599 LyXAlignment const curAlign = params_.align();
2601 if (curAlign == layout_->align)
2605 case LYX_ALIGN_NONE:
2606 case LYX_ALIGN_BLOCK:
2607 case LYX_ALIGN_LAYOUT:
2608 case LYX_ALIGN_SPECIAL:
2609 case LYX_ALIGN_DECIMAL:
2611 case LYX_ALIGN_LEFT:
2612 case LYX_ALIGN_RIGHT:
2613 case LYX_ALIGN_CENTER:
2614 if (runparams.moving_arg)
2619 bool output = false;
2621 string const end_tag = "\\par\\end";
2622 InsetCode code = ownerCode();
2623 bool const lastpar = runparams.isLastPar;
2624 // RTL in classic (PDF)LaTeX (without the Bidi package)
2625 // Luabibdi (used by LuaTeX) behaves like classic
2626 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2627 && !bparams.useBidiPackage(runparams);
2630 case LYX_ALIGN_NONE:
2631 case LYX_ALIGN_BLOCK:
2632 case LYX_ALIGN_LAYOUT:
2633 case LYX_ALIGN_SPECIAL:
2634 case LYX_ALIGN_DECIMAL:
2636 case LYX_ALIGN_LEFT: {
2638 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2639 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2641 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2643 } case LYX_ALIGN_RIGHT: {
2645 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2646 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2648 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2650 } case LYX_ALIGN_CENTER: {
2651 corrected_env(os, end_tag, "center", code, lastpar, col);
2656 return output || lastpar;
2660 // This one spits out the text of the paragraph
2661 void Paragraph::latex(BufferParams const & bparams,
2662 Font const & outerfont,
2664 OutputParams const & runparams,
2665 int start_pos, int end_pos, bool force) const
2667 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2669 // FIXME This check should not be needed. Perhaps issue an
2670 // error if it triggers.
2671 Layout const & style = inInset().forcePlainLayout() ?
2672 bparams.documentClass().plainLayout() : *d->layout_;
2674 if (!force && style.inpreamble)
2677 bool const allowcust = allowParagraphCustomization();
2679 // Current base font for all inherited font changes, without any
2680 // change caused by an individual character, except for the language:
2681 // It is set to the language of the first character.
2682 // As long as we are in the label, this font is the base font of the
2683 // label. Before the first body character it is set to the base font
2687 // If there is an open font-encoding changing command (script wrapper),
2688 // alien_script is set to its name
2689 string alien_script;
2692 // Maybe we have to create a optional argument.
2693 pos_type body_pos = beginOfBody();
2694 unsigned int column = 0;
2696 // If we are inside an non inheritFont() inset,
2697 // the outerfont is the buffer's main font
2698 Font const real_outerfont =
2699 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2702 // the optional argument is kept in curly brackets in
2703 // case it contains a ']'
2704 // This is not strictly needed, but if this is changed it
2705 // would be a file format change, and tex2lyx would need
2706 // to be adjusted, since it unconditionally removes the
2707 // braces when it parses \item.
2710 basefont = getLabelFont(bparams, real_outerfont);
2712 basefont = getLayoutFont(bparams, real_outerfont);
2715 // Which font is currently active?
2716 Font running_font(basefont);
2717 // Do we have an open font change?
2718 bool open_font = false;
2720 Change runningChange =
2721 runparams.inDeletedInset && !inInset().canTrackChanges()
2722 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2724 Encoding const * const prev_encoding = runparams.encoding;
2726 os.texrow().start(id(), 0);
2728 // if the paragraph is empty, the loop will not be entered at all
2730 // For InTitle commands, we have already opened a group
2731 // in output_latex::TeXOnePar.
2732 if (style.isCommand() && !style.intitle) {
2736 if (!style.leftdelim().empty()) {
2737 os << style.leftdelim();
2738 column += style.leftdelim().size();
2741 column += d->startTeXParParams(bparams, os, runparams);
2744 // Whether a \par can be issued for insets typeset inline with text.
2745 // Yes if greater than 0. This has to be static.
2746 THREAD_LOCAL_STATIC int parInline = 0;
2748 for (pos_type i = 0; i < size(); ++i) {
2749 // First char in paragraph or after label?
2750 if (i == body_pos) {
2753 bool needPar = false;
2754 column += running_font.latexWriteEndChanges(
2755 os, bparams, runparams,
2756 basefont, basefont, needPar);
2759 basefont = getLayoutFont(bparams, real_outerfont);
2760 running_font = basefont;
2762 column += Changes::latexMarkChange(os, bparams,
2763 runningChange, Change(Change::UNCHANGED),
2765 runningChange = Change(Change::UNCHANGED);
2767 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2770 // For InTitle commands, we have already opened a group
2771 // in output_latex::TeXOnePar.
2772 if (style.isCommand() && !style.intitle) {
2777 if (!style.leftdelim().empty()) {
2778 os << style.leftdelim();
2779 column += style.leftdelim().size();
2783 column += d->startTeXParParams(bparams, os,
2787 runparams.wasDisplayMath = runparams.inDisplayMath;
2788 runparams.inDisplayMath = false;
2789 bool deleted_display_math = false;
2790 Change const & change = runparams.inDeletedInset
2791 ? runparams.changeOfDeletedInset : lookupChange(i);
2793 char_type const c = d->text_[i];
2795 // Check whether a display math inset follows
2796 bool output_changes;
2797 if (!runparams.find_effective())
2798 output_changes = bparams.output_changes;
2800 output_changes = runparams.find_with_deleted();
2802 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2804 runparams.ctObject = getInset(i)->getCtObject(runparams);
2806 InsetMath const * im = getInset(i)->asInsetMath();
2807 if (im && im->asHullInset()
2808 && im->asHullInset()->outerDisplay()) {
2809 runparams.inDisplayMath = true;
2810 // runparams.inDeletedInset will be set by
2811 // latexInset later, but we need this info
2812 // before it is called. On the other hand, we
2813 // cannot set it here because it is a counter.
2814 deleted_display_math = isDeleted(i);
2816 if (output_changes && deleted_display_math
2817 && runningChange == change
2818 && change.type == Change::DELETED
2819 && !os.afterParbreak()) {
2820 // A display math in the same paragraph follows.
2821 // We have to close and then reopen \lyxdeleted,
2822 // otherwise the math will be shifted up.
2823 OutputParams rp = runparams;
2825 bool needPar = false;
2826 column += running_font.latexWriteEndChanges(
2827 os, bparams, rp, basefont,
2831 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2832 : getLayoutFont(bparams, real_outerfont);
2833 running_font = basefont;
2834 column += Changes::latexMarkChange(os, bparams,
2835 Change(Change::INSERTED), change, rp);
2839 if (output_changes && runningChange != change) {
2840 if (!alien_script.empty()) {
2843 alien_script.clear();
2846 bool needPar = false;
2847 column += running_font.latexWriteEndChanges(
2848 os, bparams, runparams,
2849 basefont, basefont, needPar);
2852 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2853 : getLayoutFont(bparams, real_outerfont);
2854 running_font = basefont;
2855 column += Changes::latexMarkChange(os, bparams, runningChange,
2857 runningChange = change;
2860 // do not output text which is marked deleted
2861 // if change tracking output is disabled
2862 if (!output_changes && change.deleted()) {
2868 // Fully instantiated font
2869 Font current_font = getFont(bparams, i, outerfont);
2871 Font const prev_font = (i > 0) ?
2872 getFont(bparams, i - 1, outerfont)
2875 Font const last_font = running_font;
2876 bool const in_ct_deletion = (output_changes
2877 && runningChange == change
2878 && change.type == Change::DELETED
2879 && !os.afterParbreak());
2880 // Insets where font switches are used (rather than font commands)
2881 bool const fontswitch_inset =
2884 && getInset(i)->allowMultiPar()
2885 && getInset(i)->lyxCode() != ERT_CODE
2886 && (getInset(i)->producesOutput()
2887 // FIXME Something more general?
2888 // Comments do not "produce output" but are still
2889 // part of the TeX source and require font switches
2890 // to be closed (otherwise LaTeX fails).
2891 || getInset(i)->layoutName() == "Note:Comment");
2893 bool closeLanguage = false;
2894 bool lang_switched_at_inset = false;
2895 if (fontswitch_inset) {
2896 // Some insets cannot be inside a font change command.
2897 // However, even such insets *can* be placed in \L or \R
2898 // or their equivalents (for RTL language switches),
2899 // so we don't close the language in those cases
2900 // (= differing isRightToLeft()).
2901 // ArabTeX, though, doesn't seem to handle this special behavior.
2902 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2903 || basefont.language()->lang() == "arabic_arabtex"
2904 || current_font.language()->lang() == "arabic_arabtex";
2905 // We need to check prev_font as language changes directly at inset
2906 // will only be started inside the inset.
2907 lang_switched_at_inset = prev_font.language() != current_font.language();
2910 // Do we need to close the previous font?
2911 bool langClosed = false;
2913 ((current_font != running_font
2914 || current_font.language() != running_font.language())
2915 || (fontswitch_inset
2916 && (current_font == prev_font))))
2918 // ensure there is no open script-wrapper
2919 if (!alien_script.empty()) {
2922 alien_script.clear();
2924 if (in_ct_deletion) {
2925 // We have to close and then reopen \lyxdeleted,
2926 // as strikeout needs to be on lowest level.
2930 if (closeLanguage) {
2931 // Force language closing
2932 current_font.setLanguage(basefont.language());
2935 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2936 bool needPar = false;
2937 column += running_font.latexWriteEndChanges(
2938 os, bparams, runparams, basefont,
2940 if (in_ct_deletion) {
2941 // We have to close and then reopen \lyxdeleted,
2942 // as strikeout needs to be on lowest level.
2943 OutputParams rp = runparams;
2944 column += Changes::latexMarkChange(os, bparams,
2945 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2947 // Has the language been closed in the latexWriteEndChanges() call above?
2948 langClosed |= running_font.language() != basefont.language()
2949 && running_font.language() != nextfont.language()
2950 && (running_font.language()->encoding()->package() != Encoding::CJK);
2951 running_font = basefont;
2952 open_font &= !langClosed;
2955 // if necessary, close language environment before opening CJK
2956 string const running_lang = running_font.language()->babel();
2957 string const lang_end_command = lyxrc.language_command_end;
2958 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2959 && !running_lang.empty()
2960 && running_lang == openLanguageName()
2961 && current_font.language()->encoding()->package() == Encoding::CJK) {
2962 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2963 os << from_ascii(end_tag);
2964 column += end_tag.length();
2965 if (!languageStackEmpty())
2969 // Switch file encoding if necessary (and allowed)
2970 if ((!fontswitch_inset || closeLanguage)
2971 && !runparams.pass_thru && !style.pass_thru &&
2972 runparams.encoding->package() != Encoding::none &&
2973 current_font.language()->encoding()->package() != Encoding::none) {
2974 pair<bool, int> const enc_switch =
2975 switchEncoding(os.os(), bparams, runparams,
2976 *(current_font.language()->encoding()));
2977 if (enc_switch.first) {
2978 column += enc_switch.second;
2979 runparams.encoding = current_font.language()->encoding();
2983 // A display math inset inside an ulem command will be output
2984 // as a box of width \linewidth, so we have to either disable
2985 // indentation if the inset starts a paragraph, or start a new
2986 // line to accommodate such box. This has to be done before
2987 // writing any font changing commands.
2988 if (runparams.inDisplayMath && !deleted_display_math
2989 && runparams.inulemcmd) {
2990 if (os.afterParbreak())
2996 // Do we need to change font?
2997 if ((current_font != running_font ||
2998 current_font.language() != running_font.language())
2999 && i != body_pos - 1)
3001 if (!fontswitch_inset) {
3002 if (in_ct_deletion) {
3003 // We have to close and then reopen \lyxdeleted,
3004 // as strikeout needs to be on lowest level.
3005 OutputParams rp = runparams;
3006 bool needPar = false;
3007 column += running_font.latexWriteEndChanges(
3008 os, bparams, rp, basefont,
3013 otexstringstream ots;
3014 InsetText const * textinset = inInset().asInsetText();
3015 bool const cprotect = textinset
3016 ? textinset->hasCProtectContent(runparams.moving_arg)
3017 && !textinset->text().isMainText()
3018 && inInset().lyxCode() != BRANCH_CODE
3019 && !runparams.no_cprotect
3021 column += current_font.latexWriteStartChanges(ots, bparams,
3022 runparams, basefont, last_font, false,
3024 // Check again for display math in ulem commands as a
3025 // font change may also occur just before a math inset.
3026 if (runparams.inDisplayMath && !deleted_display_math
3027 && runparams.inulemcmd) {
3028 if (os.afterParbreak())
3033 running_font = current_font;
3035 docstring fontchange = ots.str();
3037 // check whether the fontchange ends with a \\textcolor
3038 // modifier and the text starts with a space. If so we
3039 // need to add } in order to prevent \\textcolor from gobbling
3040 // the space (bug 4473).
3041 docstring const last_modifier = rsplit(fontchange, '\\');
3042 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
3043 os << from_ascii("{}");
3044 else if (ots.terminateCommand())
3046 if (in_ct_deletion) {
3047 // We have to close and then reopen \lyxdeleted,
3048 // as strikeout needs to be on lowest level.
3049 OutputParams rp = runparams;
3050 column += Changes::latexMarkChange(os, bparams,
3051 Change(Change::UNCHANGED), change, rp);
3053 } else {// if fontswitch_inset
3054 if (current_font != running_font || !langClosed)
3055 // font is still open in fontswitch_insets if we have
3056 // a non-lang font difference or if the language
3057 // is the only difference but has not been forcedly
3060 running_font = current_font;
3064 // FIXME: think about end_pos implementation...
3065 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
3066 // FIXME: integrate this case in latexSpecialChar
3067 // Do not print the separation of the optional argument
3068 // if style.pass_thru is false. This works because
3069 // latexSpecialChar ignores spaces if
3070 // style.pass_thru is false.
3071 if (i != body_pos - 1) {
3072 if (d->simpleTeXBlanks(bparams, runparams, os,
3073 i, column, current_font, style)) {
3074 // A surrogate pair was output. We
3075 // must not call latexSpecialChar
3076 // in this iteration, since it would output
3077 // the combining character again.
3084 OutputParams rp = runparams;
3085 rp.free_spacing = style.free_spacing;
3086 rp.local_font = ¤t_font;
3087 rp.intitle = style.intitle;
3089 // Two major modes: LaTeX or plain
3090 // Handle here those cases common to both modes
3091 // and then split to handle the two modes separately.
3092 if (c == META_INSET) {
3093 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3094 // Greyedout notes and, in general, all insets
3095 // with InsetLayout::isDisplay() == false,
3096 // are typeset inline with the text. So, we
3097 // can add a \par to the last paragraph of
3098 // such insets only if nothing else follows.
3099 bool incremented = false;
3100 Inset const * inset = getInset(i);
3101 InsetText const * textinset = inset
3102 ? inset->asInsetText()
3104 if (i + 1 == size() && textinset
3105 && !inset->getLayout().isDisplay()) {
3106 ParagraphList const & pars =
3107 textinset->text().paragraphs();
3108 pit_type const pit = pars.size() - 1;
3109 Font const lastfont =
3110 pit < 0 || pars[pit].empty()
3111 ? pars[pit].getLayoutFont(
3114 : pars[pit].getFont(bparams,
3115 pars[pit].size() - 1,
3117 if (lastfont.fontInfo().size() !=
3118 basefont.fontInfo().size()) {
3123 // We need to restore parts of this after insets with
3124 // allowMultiPar() true
3125 Font const save_basefont = basefont;
3126 d->latexInset(bparams, os, rp, running_font,
3127 basefont, real_outerfont, open_font,
3128 runningChange, style, i, column, fontswitch_inset,
3129 closeLanguage, (lang_switched_at_inset || langClosed));
3130 if (fontswitch_inset) {
3132 bool needPar = false;
3133 column += running_font.latexWriteEndChanges(
3134 os, bparams, runparams,
3135 basefont, basefont, needPar);
3138 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3139 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3140 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3145 if (runparams.ctObject == CtObject::DisplayObject
3146 || runparams.ctObject == CtObject::UDisplayObject) {
3147 // Close \lyx*deleted and force its
3148 // reopening (if needed)
3151 runningChange = Change(Change::UNCHANGED);
3152 runparams.ctObject = CtObject::Normal;
3155 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3156 if (!bparams.useNonTeXFonts && !runparams.pass_thru
3157 && !contains(runparams.pass_thru_chars, c))
3158 script = Encodings::isKnownScriptChar(c);
3159 if (script != alien_script) {
3160 if (!alien_script.empty()) {
3162 alien_script.clear();
3164 string fontenc = running_font.language()->fontenc(bparams);
3166 && !Encodings::fontencSupportsScript(fontenc, script)) {
3167 column += script.length() + 2;
3168 os << "\\" << script << "{";
3169 alien_script = script;
3173 d->latexSpecialChar(os, bparams, rp, running_font,
3174 alien_script, style, i, end_pos, column);
3175 } catch (EncodingException & e) {
3176 if (runparams.dryrun) {
3177 os << "<" << _("LyX Warning: ")
3178 << _("uncodable character") << " '";
3182 // add location information and throw again.
3190 // Set the encoding to that returned from latexSpecialChar (see
3191 // comment for encoding member in OutputParams.h)
3192 runparams.encoding = rp.encoding;
3194 // Also carry on the info on a closed ulem command for insets
3195 // such as Note that do not produce any output, so that no
3196 // command is ever executed but its opening was recorded.
3197 runparams.inulemcmd = rp.inulemcmd;
3199 // These need to be passed upstream as well
3200 runparams.need_maketitle = rp.need_maketitle;
3201 runparams.have_maketitle = rp.have_maketitle;
3203 // And finally, pass the post_macros upstream
3204 runparams.post_macro = rp.post_macro;
3207 // Close wrapper for alien script
3208 if (!alien_script.empty()) {
3210 alien_script.clear();
3213 Font const font = empty()
3214 ? getLayoutFont(bparams, real_outerfont)
3215 : getFont(bparams, size() - 1, real_outerfont);
3217 InsetText const * textinset = inInset().asInsetText();
3219 bool const maintext = textinset
3220 ? textinset->text().isMainText()
3223 size_t const numpars = textinset
3224 ? textinset->text().paragraphs().size()
3227 bool needPar = false;
3229 if (style.resfont.size() != font.fontInfo().size()
3230 && (!runparams.isLastPar || maintext
3231 || (numpars > 1 && d->ownerCode() != CELL_CODE
3232 && (inInset().getLayout().isDisplay()
3234 && !style.isCommand()) {
3238 // If we have an open font definition, we have to close it
3240 // Make sure that \\par is done with the font of the last
3241 // character if this has another size as the default.
3242 // This is necessary because LaTeX (and LyX on the screen)
3243 // calculates the space between the baselines according
3244 // to this font. (Matthias)
3246 // We must not change the font for the last paragraph
3247 // of non-multipar insets, tabular cells or commands,
3248 // since this produces unwanted whitespace.
3249 #ifdef FIXED_LANGUAGE_END_DETECTION
3251 running_font.latexWriteEndChanges(os, bparams,
3252 runparams, basefont,
3253 next_->getFont(bparams, 0, outerfont),
3256 running_font.latexWriteEndChanges(os, bparams,
3257 runparams, basefont, basefont, needPar);
3260 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3261 //FIXME: there as we start another \selectlanguage with the next paragraph if
3262 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3263 running_font.latexWriteEndChanges(os, bparams, runparams,
3264 basefont, basefont, needPar);
3268 // The \par could not be inserted at the same nesting
3269 // level of the font size change, so do it now.
3270 os << "{\\" << font.latexSize() << "\\par}";
3273 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3274 column += Changes::latexMarkChange(os, bparams, runningChange,
3275 Change(Change::UNCHANGED), runparams);
3277 // Needed if there is an optional argument but no contents.
3278 if (body_pos > 0 && body_pos == size()) {
3282 if (!style.rightdelim().empty()) {
3283 os << style.rightdelim();
3284 column += style.rightdelim().size();
3287 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3288 && runparams.encoding != prev_encoding) {
3289 runparams.encoding = prev_encoding;
3290 os << setEncoding(prev_encoding->iconvName());
3293 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3297 bool Paragraph::emptyTag() const
3299 for (pos_type i = 0; i < size(); ++i) {
3300 if (Inset const * inset = getInset(i)) {
3301 InsetCode lyx_code = inset->lyxCode();
3302 // FIXME testing like that is wrong. What is
3304 if (lyx_code != TOC_CODE &&
3305 lyx_code != INCLUDE_CODE &&
3306 lyx_code != GRAPHICS_CODE &&
3307 lyx_code != ERT_CODE &&
3308 lyx_code != LISTINGS_CODE &&
3309 lyx_code != FLOAT_CODE &&
3310 lyx_code != TABULAR_CODE) {
3314 char_type c = d->text_[i];
3315 if (c != ' ' && c != '\t')
3323 string Paragraph::getID(Buffer const &, OutputParams const &)
3326 for (pos_type i = 0; i < size(); ++i) {
3327 if (Inset const * inset = getInset(i)) {
3328 InsetCode lyx_code = inset->lyxCode();
3329 if (lyx_code == LABEL_CODE) {
3330 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3331 docstring const & id = il->getParam("name");
3332 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3340 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3343 for (i = 0; i < size(); ++i) {
3344 if (Inset const * inset = getInset(i)) {
3345 inset->docbook(xs, runparams);
3347 char_type c = d->text_[i];
3357 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3361 for (i = 0; i < size(); ++i) {
3362 if (Inset const * inset = getInset(i)) {
3363 inset->xhtml(xs, runparams);
3365 char_type c = d->text_[i];
3375 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3378 pos_type size = text_.size();
3379 for (pos_type i = initial; i < size; ++i) {
3380 Font font = owner_->getFont(buf.params(), i, outerfont);
3381 if (text_[i] == META_INSET)
3383 if (i != initial && font != font_old)
3394 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3395 vector<xml::EndFontTag> & tagsToClose,
3396 bool & flag, FontState curstate, xml::FontTypes type)
3398 if (curstate == FONT_ON) {
3399 tagsToOpen.push_back(docbookStartFontTag(type));
3402 tagsToClose.push_back(docbookEndFontTag(type));
3407 class OptionalFontType {
3412 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3413 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3416 OptionalFontType fontShapeToXml(FontShape fs)
3420 return {xml::FT_ITALIC};
3422 return {xml::FT_SLANTED};
3423 case SMALLCAPS_SHAPE:
3424 return {xml::FT_SMALLCAPS};
3429 // the other tags are for internal use
3435 OptionalFontType fontFamilyToXml(FontFamily fm)
3439 return {xml::FT_ROMAN};
3441 return {xml::FT_SANS};
3442 case TYPEWRITER_FAMILY:
3443 return {xml::FT_TYPE};
3444 case INHERIT_FAMILY:
3447 // the other tags are for internal use
3453 OptionalFontType fontSizeToXml(FontSize fs)
3457 return {xml::FT_SIZE_TINY};
3459 return {xml::FT_SIZE_SCRIPT};
3461 return {xml::FT_SIZE_FOOTNOTE};
3463 return {xml::FT_SIZE_SMALL};
3465 return {xml::FT_SIZE_LARGE};
3467 return {xml::FT_SIZE_LARGER};
3469 return {xml::FT_SIZE_LARGEST};
3471 return {xml::FT_SIZE_HUGE};
3473 return {xml::FT_SIZE_HUGER};
3475 return {xml::FT_SIZE_INCREASE};
3477 return {xml::FT_SIZE_DECREASE};
3482 // the other tags are for internal use
3488 struct DocBookFontState
3490 FontShape curr_fs = INHERIT_SHAPE;
3491 FontFamily curr_fam = INHERIT_FAMILY;
3492 FontSize curr_size = INHERIT_SIZE;
3494 // track whether we have opened these tags
3495 bool emph_flag = false;
3496 bool bold_flag = false;
3497 bool noun_flag = false;
3498 bool ubar_flag = false;
3499 bool dbar_flag = false;
3500 bool sout_flag = false;
3501 bool xout_flag = false;
3502 bool wave_flag = false;
3504 bool shap_flag = false;
3506 bool faml_flag = false;
3508 bool size_flag = false;
3511 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3513 std::string const & default_family,
3514 DocBookFontState & fs)
3516 vector<xml::FontTag> tagsToOpen;
3517 vector<xml::EndFontTag> tagsToClose;
3520 FontState curstate = font.fontInfo().emph();
3521 if (font_old.emph() != curstate)
3522 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3525 curstate = font.fontInfo().noun();
3526 if (font_old.noun() != curstate)
3527 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3530 curstate = font.fontInfo().underbar();
3531 if (font_old.underbar() != curstate)
3532 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3535 curstate = font.fontInfo().strikeout();
3536 if (font_old.strikeout() != curstate)
3537 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3540 curstate = font.fontInfo().xout();
3541 if (font_old.xout() != curstate)
3542 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3545 curstate = font.fontInfo().uuline();
3546 if (font_old.uuline() != curstate)
3547 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3550 curstate = font.fontInfo().uwave();
3551 if (font_old.uwave() != curstate)
3552 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3555 // a little hackish, but allows us to reuse what we have.
3556 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3557 if (font_old.series() != font.fontInfo().series())
3558 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3561 fs.curr_fs = font.fontInfo().shape();
3562 FontShape old_fs = font_old.shape();
3563 if (old_fs != fs.curr_fs) {
3565 OptionalFontType tag = fontShapeToXml(old_fs);
3567 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3568 fs.shap_flag = false;
3571 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3573 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3577 fs.curr_fam = font.fontInfo().family();
3578 FontFamily old_fam = font_old.family();
3579 if (old_fam != fs.curr_fam) {
3581 OptionalFontType tag = fontFamilyToXml(old_fam);
3583 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3584 fs.faml_flag = false;
3586 switch (fs.curr_fam) {
3588 // we will treat a "default" font family as roman, since we have
3589 // no other idea what to do.
3590 if (default_family != "rmdefault" && default_family != "default") {
3591 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3592 fs.faml_flag = true;
3596 if (default_family != "sfdefault") {
3597 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3598 fs.faml_flag = true;
3601 case TYPEWRITER_FAMILY:
3602 if (default_family != "ttdefault") {
3603 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3604 fs.faml_flag = true;
3607 case INHERIT_FAMILY:
3610 // the other tags are for internal use
3617 fs.curr_size = font.fontInfo().size();
3618 FontSize old_size = font_old.size();
3619 if (old_size != fs.curr_size) {
3621 OptionalFontType tag = fontSizeToXml(old_size);
3623 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3624 fs.size_flag = false;
3627 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3628 if (tag.has_value) {
3629 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3630 fs.size_flag = true;
3634 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3637 } // anonymous namespace
3640 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3641 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3642 OutputParams const & runparams,
3643 Font const & outerfont,
3646 bool ignore_fonts) const
3648 // Return values: segregation of the content of this paragraph.
3649 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3650 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3651 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3653 // Internal string stream to store the output before being added to one of the previous lists.
3654 odocstringstream os;
3656 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3657 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3659 OutputParams rp = runparams;
3660 for (pos_type i = initial; i < size(); ++i) {
3661 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3662 const InsetArgument * arg = getInset(i)->asInsetArgument();
3663 if (arg->docbookargumentbeforemaintag()) {
3664 auto xs_local = XMLStream(os);
3665 arg->docbook(xs_local, rp);
3667 prependedParagraphs.push_back(os.str());
3668 os.str(from_ascii(""));
3670 rp.docbook_prepended_arguments.insert(arg);
3671 } else if (arg->docbookargumentaftermaintag()) {
3672 rp.docbook_appended_arguments.insert(arg);
3678 // State variables for the main loop.
3679 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3680 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3681 xs->startDivision(false);
3682 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3683 // This requires to store delayed characters at some point.
3685 // Track whether we have opened font tags
3686 DocBookFontState fs;
3687 DocBookFontState old_fs = fs;
3689 Layout const & style = *d->layout_;
3691 // Conversion of the font opening/closing into DocBook tags.
3692 vector<xml::FontTag> tagsToOpen;
3693 vector<xml::EndFontTag> tagsToClose;
3695 // Parsing main loop.
3696 for (pos_type i = initial; i < size(); ++i) {
3697 bool ignore_fonts_i = ignore_fonts
3698 || style.docbooknofontinside()
3699 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3701 // Don't show deleted material in the output.
3705 // If this is an InsetNewline, generate a new paragraph (this is the reason why generatedParagraphs is a list
3706 // of paragraphs). Also reset the fonts, so that tags are closed in this paragraph.
3707 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3708 if (!ignore_fonts_i)
3709 xs->closeFontTags();
3711 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3712 generatedParagraphs.push_back(os.str());
3716 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3717 // that the string stream must be reset.
3718 os.str(from_ascii(""));
3720 xs = new XMLStream(os);
3721 xs->startDivision(false);
3723 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3724 if (!ignore_fonts_i) {
3729 // Determine which tags should be opened or closed regarding fonts. Consider the last output character (i.e. not
3731 int last_output_char = (i == 0) ? 0 : i - 1;
3733 while (last_output_char > 0 && isDeleted(last_output_char))
3736 FontInfo const font_old = (i == 0 ?
3737 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3738 getFont(buf.masterBuffer()->params(), last_output_char, outerfont).fontInfo());
3739 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3740 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3741 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3743 if (!ignore_fonts_i) {
3744 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3745 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3746 for (; cit != cen; ++cit)
3750 // Deal with the delayed characters *after* closing font tags.
3751 if (!delayedChars.empty()) {
3752 for (const docstring& c: delayedChars)
3753 *xs << XMLStream::ESCAPE_NONE << c;
3754 delayedChars.clear();
3757 if (!ignore_fonts_i) {
3758 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3759 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3760 for (; sit != sen; ++sit)
3764 // The font tags are no longer useful; free their memory right now.
3765 tagsToClose.clear();
3768 // Finally, write the next character or inset.
3769 if (Inset const * inset = getInset(i)) {
3770 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3771 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3772 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3774 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3775 // Arguments may need to be output
3776 OutputParams np = rp;
3777 np.local_font = &font;
3779 // TODO: special case will bite here.
3780 np.docbook_in_par = true;
3781 inset->docbook(*xs, np);
3784 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3785 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3786 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3787 delayedChars.push_back(from_ascii(" "));
3789 delayedChars.emplace_back(1, c);
3791 } else { // No need to delay the character.
3792 if (c == '\'' && !ignore_fonts)
3793 *xs << XMLStream::ESCAPE_NONE << "’";
3800 // Ensure that the tags are closed at the right place. Otherwise, there might be an open font tag with no content
3801 // that no other code cares to close.
3802 *xs << xml::NullTag();
3804 // FIXME, this code is just imported from XHTML
3805 // I'm worried about what happens if a branch, say, is itself
3806 // wrapped in some font stuff. I think that will not work.
3808 xs->closeFontTags();
3810 // Close the potentially remaining tags, like pending font tags.
3811 // There is no need to check for ignore_fonts, as these tags won't be
3812 // inserted in the stack in the first place if ignore_fonts is false.
3815 // Deal with the delayed characters *after* closing font tags.
3816 if (!delayedChars.empty()) {
3817 for (const docstring &c: delayedChars)
3818 *xs << XMLStream::ESCAPE_NONE << c;
3819 delayedChars.clear();
3822 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3823 // last line to get a clean output.
3824 if (rp.docbook_in_listing && !is_last_par)
3827 // Finalise the last (and most likely only) paragraph.
3828 generatedParagraphs.push_back(os.str());
3829 os.str(from_ascii(""));
3832 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3833 for (pos_type i = initial; i < size(); ++i) {
3834 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3835 const InsetArgument * arg = getInset(i)->asInsetArgument();
3836 if (arg->docbookargumentaftermaintag()) {
3837 // Don't use rp, as this argument would not generate anything.
3838 auto xs_local = XMLStream(os);
3839 arg->docbook(xs_local, runparams);
3841 appendedParagraphs.push_back(os.str());
3842 os.str(from_ascii(""));
3847 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3853 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3854 vector<xml::EndFontTag> & tagsToClose,
3855 bool & flag, FontState curstate, xml::FontTypes type)
3857 if (curstate == FONT_ON) {
3858 tagsToOpen.push_back(xhtmlStartFontTag(type));
3861 tagsToClose.push_back(xhtmlEndFontTag(type));
3866 } // anonymous namespace
3869 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3871 OutputParams const & runparams,
3872 Font const & outerfont,
3873 bool start_paragraph, bool close_paragraph,
3874 pos_type initial) const
3878 // track whether we have opened these tags
3879 bool emph_flag = false;
3880 bool bold_flag = false;
3881 bool noun_flag = false;
3882 bool ubar_flag = false;
3883 bool dbar_flag = false;
3884 bool sout_flag = false;
3885 bool xout_flag = false;
3886 bool wave_flag = false;
3888 bool shap_flag = false;
3890 bool faml_flag = false;
3892 bool size_flag = false;
3894 Layout const & style = *d->layout_;
3896 if (start_paragraph)
3897 xs.startDivision(allowEmpty());
3900 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3902 FontShape curr_fs = INHERIT_SHAPE;
3903 FontFamily curr_fam = INHERIT_FAMILY;
3904 FontSize curr_size = INHERIT_SIZE;
3906 string const default_family =
3907 buf.masterBuffer()->params().fonts_default_family;
3909 vector<xml::FontTag> tagsToOpen;
3910 vector<xml::EndFontTag> tagsToClose;
3912 // parsing main loop
3913 for (pos_type i = initial; i < size(); ++i) {
3914 // let's not show deleted material in the output
3918 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3921 FontState curstate = font.fontInfo().emph();
3922 if (font_old.emph() != curstate)
3923 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3926 curstate = font.fontInfo().noun();
3927 if (font_old.noun() != curstate)
3928 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3931 curstate = font.fontInfo().underbar();
3932 if (font_old.underbar() != curstate)
3933 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3936 curstate = font.fontInfo().strikeout();
3937 if (font_old.strikeout() != curstate)
3938 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3941 curstate = font.fontInfo().xout();
3942 if (font_old.xout() != curstate)
3943 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3946 curstate = font.fontInfo().uuline();
3947 if (font_old.uuline() != curstate)
3948 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3951 curstate = font.fontInfo().uwave();
3952 if (font_old.uwave() != curstate)
3953 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3956 // a little hackish, but allows us to reuse what we have.
3957 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3958 if (font_old.series() != font.fontInfo().series())
3959 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3962 curr_fs = font.fontInfo().shape();
3963 FontShape old_fs = font_old.shape();
3964 if (old_fs != curr_fs) {
3968 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3971 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3973 case SMALLCAPS_SHAPE:
3974 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3980 // the other tags are for internal use
3988 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3992 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3995 case SMALLCAPS_SHAPE:
3996 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
4003 // the other tags are for internal use
4010 curr_fam = font.fontInfo().family();
4011 FontFamily old_fam = font_old.family();
4012 if (old_fam != curr_fam) {
4016 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
4019 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
4021 case TYPEWRITER_FAMILY:
4022 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
4024 case INHERIT_FAMILY:
4027 // the other tags are for internal use
4035 // we will treat a "default" font family as roman, since we have
4036 // no other idea what to do.
4037 if (default_family != "rmdefault" && default_family != "default") {
4038 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
4043 if (default_family != "sfdefault") {
4044 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
4048 case TYPEWRITER_FAMILY:
4049 if (default_family != "ttdefault") {
4050 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
4054 case INHERIT_FAMILY:
4057 // the other tags are for internal use
4064 curr_size = font.fontInfo().size();
4065 FontSize old_size = font_old.size();
4066 if (old_size != curr_size) {
4070 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
4073 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
4076 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
4079 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
4082 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
4085 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
4088 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
4091 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
4094 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
4097 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
4100 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
4106 // the other tags are for internal use
4112 switch (curr_size) {
4114 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4118 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4122 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4126 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4130 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4134 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4138 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4142 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4146 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4150 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4154 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4161 // the other tags are for internal use
4168 // Other such tags? What about the other text ranges?
4170 for (auto const & t : tagsToClose)
4172 for (auto const & t : tagsToOpen)
4174 tagsToClose.clear();
4177 Inset const * inset = getInset(i);
4179 if (!runparams.for_toc || inset->isInToc()) {
4180 OutputParams np = runparams;
4181 np.local_font = &font;
4182 // If the paragraph has size 1, then we are in the "special
4183 // case" where we do not output the containing paragraph info
4184 if (!inset->getLayout().htmlisblock() && size() != 1)
4185 np.html_in_par = true;
4186 retval += inset->xhtml(xs, np);
4189 char_type c = getUChar(buf.masterBuffer()->params(),
4191 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4192 xs << XMLStream::ESCAPE_NONE << " ";
4194 xs << XMLStream::ESCAPE_NONE << "’";
4198 font_old = font.fontInfo();
4202 // I'm worried about what happens if a branch, say, is itself
4203 // wrapped in some font stuff. I think that will not work.
4205 if (close_paragraph)
4212 bool Paragraph::isHfill(pos_type pos) const
4214 Inset const * inset = getInset(pos);
4215 return inset && inset->isHfill();
4219 bool Paragraph::isNewline(pos_type pos) const
4221 // U+2028 LINE SEPARATOR
4222 // U+2029 PARAGRAPH SEPARATOR
4223 char_type const c = d->text_[pos];
4224 if (c == 0x2028 || c == 0x2029)
4226 Inset const * inset = getInset(pos);
4227 return inset && inset->lyxCode() == NEWLINE_CODE;
4231 bool Paragraph::isEnvSeparator(pos_type pos) const
4233 Inset const * inset = getInset(pos);
4234 return inset && inset->lyxCode() == SEPARATOR_CODE;
4238 bool Paragraph::isLineSeparator(pos_type pos) const
4240 char_type const c = d->text_[pos];
4241 if (isLineSeparatorChar(c))
4243 Inset const * inset = getInset(pos);
4244 return inset && inset->isLineSeparator();
4248 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4252 if (ignore_deleted && isDeleted(pos))
4254 if (Inset const * inset = getInset(pos))
4255 return !inset->isLetter();
4256 // if we have a hard hyphen (no en- or emdash) or apostrophe
4257 // we pass this to the spell checker
4258 // FIXME: this method is subject to change, visit
4259 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4260 // to get an impression how complex this is.
4261 if (isHardHyphenOrApostrophe(pos))
4263 char_type const c = d->text_[pos];
4264 // We want to pass the escape chars to the spellchecker
4265 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4266 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4270 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4272 pos_type const psize = size();
4275 char_type const c = d->text_[pos];
4276 if (c != '-' && c != '\'')
4278 pos_type nextpos = pos + 1;
4279 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4280 if ((nextpos == psize || isSpace(nextpos))
4281 && (pos == 0 || isSpace(prevpos)))
4287 bool Paragraph::needsCProtection(bool const fragile) const
4289 // first check the layout of the paragraph, but only in insets
4290 // and not in tables
4291 InsetText const * textinset = inInset().asInsetText();
4292 bool const maintext = textinset
4293 ? textinset->text().isMainText() || inInset().lyxCode() == CELL_CODE
4296 if (!maintext && layout().needcprotect) {
4297 // Environments need cprotection regardless the content
4298 if (layout().latextype == LATEX_ENVIRONMENT)
4301 // Commands need cprotection if they contain specific chars
4302 int const nchars_escape = 9;
4303 static char_type const chars_escape[nchars_escape] = {
4304 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4306 docstring const pars = asString();
4307 for (int k = 0; k < nchars_escape; k++) {
4308 if (contains(pars, chars_escape[k]))
4313 // now check whether we have insets that need cprotection
4314 for (auto const & icit : d->insetlist_) {
4315 Inset const * ins = icit.inset;
4318 if (ins->needsCProtection(maintext, fragile))
4326 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4328 return d->speller_state_.getRange(pos);
4332 bool Paragraph::isChar(pos_type pos) const
4334 if (Inset const * inset = getInset(pos))
4335 return inset->isChar();
4336 char_type const c = d->text_[pos];
4337 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4341 bool Paragraph::isSpace(pos_type pos) const
4343 if (Inset const * inset = getInset(pos))
4344 return inset->isSpace();
4345 char_type const c = d->text_[pos];
4346 return lyx::isSpace(c);
4351 Paragraph::getParLanguage(BufferParams const & bparams) const
4354 return getFirstFontSettings(bparams).language();
4355 // FIXME: we should check the prev par as well (Lgb)
4356 return bparams.language;
4360 bool Paragraph::isRTL(BufferParams const & bparams) const
4362 return getParLanguage(bparams)->rightToLeft()
4363 && !inInset().getLayout().forceLTR();
4367 void Paragraph::changeLanguage(BufferParams const & bparams,
4368 Language const * from, Language const * to)
4370 // change language including dummy font change at the end
4371 for (pos_type i = 0; i <= size(); ++i) {
4372 Font font = getFontSettings(bparams, i);
4373 if (font.language() == from) {
4374 font.setLanguage(to);
4376 d->requestSpellCheck(i);
4382 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4384 Language const * doc_language = bparams.language;
4385 for (auto const & f : d->fontlist_)
4386 if (f.font().language() != ignore_language &&
4387 f.font().language() != latex_language &&
4388 f.font().language() != doc_language)
4394 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4396 for (auto const & f : d->fontlist_) {
4397 Language const * lang = f.font().language();
4398 if (lang != ignore_language &&
4399 lang != latex_language)
4405 docstring Paragraph::asString(int options) const
4407 return asString(0, size(), options);
4411 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4413 odocstringstream os;
4416 && options & AS_STR_LABEL
4417 && d->layout_->labeltype != LABEL_MANUAL
4418 && !d->params_.labelString().empty())
4419 os << d->params_.labelString() << ' ';
4421 for (pos_type i = beg; i < end; ++i) {
4422 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4424 char_type const c = d->text_[i];
4425 if (isPrintable(c) || c == '\t'
4426 || (c == '\n' && (options & AS_STR_NEWLINES)))
4428 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4429 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4430 LASSERT(runparams != nullptr, return docstring());
4431 if (runparams->find_effective() && getInset(i)->findUsesToString())
4432 getInset(i)->toString(os);
4434 getInset(i)->plaintext(os, *runparams);
4435 } else if (c == META_INSET && (options & AS_STR_MATHED)
4436 && getInset(i)->lyxCode() == REF_CODE) {
4437 Buffer const & buf = getInset(i)->buffer();
4438 OutputParams rp(&buf.params().encoding());
4439 Font const font(inherit_font, buf.params().language);
4440 rp.local_font = &font;
4442 getInset(i)->latex(ots, rp);
4444 getInset(i)->toString(os);
4453 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4454 bool const shorten, bool const label) const
4456 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4457 if (label && !labelString().empty())
4458 os += labelString() + ' ';
4459 if (!layout().isTocCaption())
4461 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4464 char_type const c = d->text_[i];
4467 else if (c == META_INSET)
4468 getInset(i)->forOutliner(os, tmplen, false);
4471 Text::shortenForOutliner(os, maxlen);
4475 void Paragraph::setInsetOwner(Inset const * inset)
4477 d->inset_owner_ = inset;
4481 int Paragraph::id() const
4487 void Paragraph::setId(int id)
4493 Layout const & Paragraph::layout() const
4499 void Paragraph::setLayout(Layout const & layout)
4501 d->layout_ = &layout;
4505 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4507 setLayout(tc.defaultLayout());
4511 void Paragraph::setPlainLayout(DocumentClass const & tc)
4513 setLayout(tc.plainLayout());
4517 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4519 if (usePlainLayout())
4522 setDefaultLayout(tc);
4526 Inset const & Paragraph::inInset() const
4528 LBUFERR(d->inset_owner_);
4529 return *d->inset_owner_;
4533 ParagraphParameters & Paragraph::params()
4539 ParagraphParameters const & Paragraph::params() const
4545 bool Paragraph::isFreeSpacing() const
4547 if (d->layout_->free_spacing)
4549 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4553 bool Paragraph::allowEmpty() const
4555 if (d->layout_->keepempty)
4557 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4561 int Paragraph::getInsetPos(InsetCode const code, int startpos,
4562 bool ignore_deleted) const
4564 while (startpos != -1) {
4565 int found_pos = d->insetlist_.find(code, startpos);
4566 if (found_pos == -1)
4569 if (isDeleted(found_pos) && ignore_deleted) {
4570 // we're not interested in deleted insets
4571 if (found_pos + 1 == size())
4573 startpos = found_pos + 1;
4582 bool Paragraph::brokenBiblio() const
4584 // There is a problem if there is no bibitem at position 0 in
4585 // paragraphs that need one, if there is another bibitem in the
4586 // paragraph or if this paragraph is not supposed to have
4587 // a bibitem inset at all.
4588 return ((d->layout_->labeltype == LABEL_BIBLIO
4589 && (getInsetPos(BIBITEM_CODE, 0, true) != 0
4590 || getInsetPos(BIBITEM_CODE, 1, true) > 0))
4591 || (d->layout_->labeltype != LABEL_BIBLIO
4592 && getInsetPos(BIBITEM_CODE, 0, true) != -1));
4596 int Paragraph::fixBiblio(Buffer const & buffer)
4598 // FIXME: when there was already an inset at 0, the return value is 1,
4599 // which does not tell whether another inset has been removed; the
4600 // cursor cannot be correctly updated.
4602 bool const track_changes = buffer.params().track_changes;
4603 int bibitem_pos = getInsetPos(BIBITEM_CODE, 0, true);
4605 // The case where paragraph is not BIBLIO
4606 if (d->layout_->labeltype != LABEL_BIBLIO) {
4607 if (bibitem_pos == -1)
4608 // No InsetBibitem => OK
4610 // There is an InsetBibitem: remove it!
4611 d->insetlist_.release(bibitem_pos);
4612 eraseChar(bibitem_pos, track_changes);
4613 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4616 bool const hasbibitem0 = bibitem_pos == 0;
4618 bibitem_pos = getInsetPos(BIBITEM_CODE, 0, true);
4619 // There was an InsetBibitem at pos 0,
4620 // and no other one => OK
4621 if (bibitem_pos == -1)
4623 // there is a bibitem at the 0 position, but since
4624 // there is a second one, we copy the second on the
4625 // first. We're assuming there are at most two of
4626 // these, which there should be.
4627 // FIXME: why does it make sense to do that rather
4628 // than keep the first? (JMarc)
4629 Inset * inset = releaseInset(bibitem_pos);
4630 d->insetlist_.begin()->inset = inset;
4631 // This needs to be done to update the counter (#8499)
4632 buffer.updateBuffer();
4633 return -bibitem_pos;
4636 // We need to create an inset at the beginning
4637 Inset * inset = nullptr;
4638 if (bibitem_pos > 0) {
4639 // There was one somewhere in the paragraph, let's move it
4640 // * With change tracking, we use a clone
4641 // and leave the old inset at its position
4643 // * Without change tracking, we release the inset
4644 // from its previous InsetList position
4645 inset = track_changes
4646 ? new InsetBibitem(const_cast<Buffer *>(&buffer),
4647 getInset(bibitem_pos)->asInsetCommand()->params())
4648 : d->insetlist_.release(bibitem_pos);
4649 eraseChar(bibitem_pos, track_changes);
4651 // No inset found -- make a fresh one
4652 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4653 InsetCommandParams(BIBITEM_CODE));
4655 Font font(inherit_font, buffer.params().language);
4656 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4657 : Change::UNCHANGED));
4659 // This is needed to get the counters right
4660 buffer.updateBuffer();
4665 void Paragraph::checkAuthors(AuthorList const & authorList)
4667 d->changes_.checkAuthors(authorList);
4671 bool Paragraph::isChanged(pos_type pos) const
4673 return lookupChange(pos).changed();
4677 bool Paragraph::isInserted(pos_type pos) const
4679 return lookupChange(pos).inserted();
4683 bool Paragraph::isDeleted(pos_type pos) const
4685 return lookupChange(pos).deleted();
4689 InsetList const & Paragraph::insetList() const
4691 return d->insetlist_;
4695 void Paragraph::setInsetBuffers(Buffer & b)
4697 d->insetlist_.setBuffer(b);
4701 void Paragraph::resetBuffer()
4703 d->insetlist_.resetBuffer();
4707 Inset * Paragraph::releaseInset(pos_type pos)
4709 Inset * inset = d->insetlist_.release(pos);
4710 /// does not honour change tracking!
4711 eraseChar(pos, false);
4716 Inset * Paragraph::getInset(pos_type pos)
4718 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4719 ? d->insetlist_.get(pos) : nullptr;
4723 Inset const * Paragraph::getInset(pos_type pos) const
4725 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4726 ? d->insetlist_.get(pos) : nullptr;
4730 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4731 pos_type & right, TextCase action)
4733 // process sequences of modified characters; in change
4734 // tracking mode, this approach results in much better
4735 // usability than changing case on a char-by-char basis
4736 // We also need to track the current font, since font
4737 // changes within sequences can occur.
4738 vector<pair<char_type, Font> > changes;
4740 bool const trackChanges = bparams.track_changes;
4742 bool capitalize = true;
4744 for (; pos < right; ++pos) {
4745 char_type oldChar = d->text_[pos];
4746 char_type newChar = oldChar;
4748 // ignore insets and don't play with deleted text!
4749 if (oldChar != META_INSET && !isDeleted(pos)) {
4751 case text_lowercase:
4752 newChar = lowercase(oldChar);
4754 case text_capitalization:
4756 newChar = uppercase(oldChar);
4760 case text_uppercase:
4761 newChar = uppercase(oldChar);
4766 if (isWordSeparator(pos) || isDeleted(pos)) {
4767 // permit capitalization again
4771 if (oldChar != newChar) {
4772 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4773 if (pos != right - 1)
4775 // step behind the changing area
4779 int erasePos = pos - changes.size();
4780 for (auto const & change : changes) {
4781 insertChar(pos, change.first, change.second, trackChanges);
4782 if (!eraseChar(erasePos, trackChanges)) {
4785 ++right; // expand selection
4792 int Paragraph::find(docstring const & str, bool cs, bool mw,
4793 pos_type start_pos, bool del) const
4795 pos_type pos = start_pos;
4796 int const strsize = str.length();
4798 pos_type const parsize = d->text_.size();
4799 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4800 // ignore deleted matter
4801 if (!del && isDeleted(pos)) {
4802 if (pos == parsize - 1)
4808 // Ignore "invisible" letters such as ligature breaks
4809 // and hyphenation chars while searching
4810 bool nonmatch = false;
4811 while (pos < parsize && isInset(pos)) {
4812 Inset const * inset = getInset(pos);
4813 if (!inset->isLetter() && !inset->isChar())
4815 odocstringstream os;
4816 if (inset->lyxCode() == lyx::QUOTE_CODE || inset->lyxCode() == lyx::SPACE_CODE) {
4818 op.find_set_feature(OutputParams::SearchQuick);
4819 inset->plaintext(os, op);
4822 inset->toString(os);
4824 docstring const insetstring = os.str();
4825 if (!insetstring.empty()) {
4826 int const insetstringsize = insetstring.length();
4827 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4828 if ((cs && str[i] != insetstring[j])
4829 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4837 if (nonmatch || i == strsize)
4839 char_type dp = d->text_[pos];
4840 if (cs && str[i] != dp)
4842 if (!cs && uppercase(str[i]) != uppercase(dp))
4849 // if necessary, check whether string matches word
4851 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4854 && !isWordSeparator(pos))
4858 return pos - start_pos;
4862 char_type Paragraph::getChar(pos_type pos) const
4864 return d->text_[pos];
4868 pos_type Paragraph::size() const
4870 return d->text_.size();
4874 bool Paragraph::empty() const
4876 return d->text_.empty();
4880 bool Paragraph::isInset(pos_type pos) const
4882 return d->text_[pos] == META_INSET;
4886 bool Paragraph::isSeparator(pos_type pos) const
4888 //FIXME: Are we sure this can be the only separator?
4889 return d->text_[pos] == ' ';
4893 void Paragraph::deregisterWords()
4895 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4896 Private::LangWordsMap::const_iterator ite = d->words_.end();
4897 for (; itl != ite; ++itl) {
4898 WordList & wl = theWordList(itl->first);
4899 Private::Words::const_iterator it = (itl->second).begin();
4900 Private::Words::const_iterator et = (itl->second).end();
4901 for (; it != et; ++it)
4908 void Paragraph::locateWord(pos_type & from, pos_type & to,
4909 word_location const loc, bool const ignore_deleted) const
4912 case WHOLE_WORD_STRICT:
4913 if (from == 0 || from == size()
4914 || isWordSeparator(from, ignore_deleted)
4915 || isWordSeparator(from - 1, ignore_deleted)) {
4922 // If we are already at the beginning of a word, do nothing
4923 if (!from || isWordSeparator(from - 1, ignore_deleted))
4928 // always move the cursor to the beginning of previous word
4929 while (from && !isWordSeparator(from - 1, ignore_deleted))
4933 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4936 // no need to move the 'from' cursor
4940 while (to < size() && !isWordSeparator(to, ignore_deleted))
4945 void Paragraph::collectWords()
4947 for (pos_type pos = 0; pos < size(); ++pos) {
4948 if (isWordSeparator(pos))
4950 pos_type from = pos;
4951 locateWord(from, pos, WHOLE_WORD);
4952 // Work around MSVC warning: The statement
4953 // if (pos < from + lyxrc.completion_minlength)
4954 // triggers a signed vs. unsigned warning.
4955 // I don't know why this happens, it could be a MSVC bug, or
4956 // related to LLP64 (windows) vs. LP64 (unix) programming
4957 // model, or the C++ standard might be ambigous in the section
4958 // defining the "usual arithmetic conversions". However, using
4959 // a temporary variable is safe and works on all compilers.
4960 pos_type const endpos = from + lyxrc.completion_minlength;
4963 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4964 if (cit == d->fontlist_.end())
4966 Language const * lang = cit->font().language();
4967 docstring const word = asString(from, pos, AS_STR_NONE);
4968 d->words_[lang->lang()].insert(word);
4973 void Paragraph::registerWords()
4975 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4976 Private::LangWordsMap::const_iterator ite = d->words_.end();
4977 for (; itl != ite; ++itl) {
4978 WordList & wl = theWordList(itl->first);
4979 Private::Words::const_iterator it = (itl->second).begin();
4980 Private::Words::const_iterator et = (itl->second).end();
4981 for (; it != et; ++it)
4987 void Paragraph::updateWords()
4995 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4997 SkipPositionsIterator begin = skips.begin();
4998 SkipPositions::iterator end = skips.end();
4999 if (pos > 0 && begin < end) {
5001 if (end->last == pos - 1) {
5006 skips.insert(end, FontSpan(pos, pos));
5010 Language * Paragraph::Private::locateSpellRange(
5011 pos_type & from, pos_type & to,
5012 SkipPositions & skips) const
5014 // skip leading white space
5015 while (from < to && owner_->isWordSeparator(from))
5017 // don't check empty range
5020 // get current language
5021 Language * lang = getSpellLanguage(from);
5022 pos_type last = from;
5023 bool samelang = true;
5024 bool sameinset = true;
5025 while (last < to && samelang && sameinset) {
5026 // hop to end of word
5027 while (last < to && !owner_->isWordSeparator(last)) {
5028 Inset const * inset = owner_->getInset(last);
5029 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
5030 // check for "invisible" letters such as ligature breaks
5031 odocstringstream os;
5032 inset->toString(os);
5033 if (os.str().length() != 0) {
5034 // avoid spell check of visible special char insets
5035 // stop the loop in front of the special char inset
5040 appendSkipPosition(skips, last);
5041 } else if (owner_->isDeleted(last)) {
5042 appendSkipPosition(skips, last);
5046 // hop to next word while checking for insets
5047 while (sameinset && last < to && owner_->isWordSeparator(last)) {
5048 if (Inset const * inset = owner_->getInset(last))
5049 sameinset = inset->isChar() && inset->isLetter();
5050 if (sameinset && owner_->isDeleted(last)) {
5051 appendSkipPosition(skips, last);
5056 if (sameinset && last < to) {
5057 // now check for language change
5058 samelang = lang == getSpellLanguage(last);
5061 // if language change detected backstep is needed
5069 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
5072 const_cast<Language *>(owner_->getFontSettings(
5073 inset_owner_->buffer().params(), from).language());
5074 if (lang == inset_owner_->buffer().params().language
5075 && !lyxrc.spellchecker_alt_lang.empty()) {
5077 string const lang_variety =
5078 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
5079 lang->setCode(lang_code);
5080 lang->setVariety(lang_variety);
5086 void Paragraph::requestSpellCheck(pos_type pos)
5088 d->requestSpellCheck(pos);
5090 // Also request spellcheck within (text) insets
5091 for (auto const & insets : insetList()) {
5092 if (!insets.inset->asInsetText())
5094 ParagraphList & inset_pars =
5095 insets.inset->asInsetText()->paragraphs();
5096 ParagraphList::iterator pit = inset_pars.begin();
5097 ParagraphList::iterator pend = inset_pars.end();
5098 for (; pit != pend; ++pit)
5099 pit->requestSpellCheck();
5105 bool Paragraph::needsSpellCheck() const
5107 SpellChecker::ChangeNumber speller_change_number = 0;
5108 if (theSpellChecker())
5109 speller_change_number = theSpellChecker()->changeNumber();
5110 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
5111 d->speller_state_.needsCompleteRefresh(speller_change_number);
5113 return d->needsSpellCheck();
5117 bool Paragraph::Private::ignoreWord(docstring const & word) const
5119 // Ignore words with digits
5120 // FIXME: make this customizable
5121 // (note that some checkers ignore words with digits by default)
5122 docstring::const_iterator cit = word.begin();
5123 docstring::const_iterator const end = word.end();
5124 for (; cit != end; ++cit) {
5125 if (isNumber((*cit)))
5132 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
5133 WordLangTuple & wl, docstring_list & suggestions,
5134 bool do_suggestion, bool check_learned) const
5136 SpellChecker::Result result = SpellChecker::WORD_OK;
5137 SpellChecker * speller = theSpellChecker();
5141 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
5144 locateWord(from, to, WHOLE_WORD, true);
5145 if (from == to || from >= size())
5148 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5149 Language * lang = d->getSpellLanguage(from);
5151 BufferParams const & bparams = d->inset_owner_->buffer().params();
5153 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5156 wl = WordLangTuple(word, lang);
5161 if (needsSpellCheck() || check_learned) {
5163 if (!d->ignoreWord(word)) {
5164 bool const trailing_dot = to < size() && d->text_[to] == '.';
5165 result = speller->check(wl, bparams.spellignore());
5166 if (SpellChecker::misspelled(result) && trailing_dot) {
5167 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5168 result = speller->check(wl, bparams.spellignore());
5169 if (!SpellChecker::misspelled(result)) {
5170 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5172 from << ".." << to << "]");
5174 // spell check with dot appended failed too
5175 // restore original word/lang value
5176 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5177 wl = WordLangTuple(word, lang);
5181 if (!SpellChecker::misspelled(result)) {
5182 // area up to the begin of the next word is not misspelled
5183 while (end < size() && isWordSeparator(end))
5186 d->setMisspelled(from, end, result);
5188 result = d->speller_state_.getState(from);
5192 suggestions.clear();
5194 if (SpellChecker::misspelled(result)) {
5195 LYXERR(Debug::GUI, "misspelled word: \"" <<
5197 from << ".." << to << "]");
5199 speller->suggest(wl, suggestions);
5205 void Paragraph::anonymize()
5207 // This is a very crude anonymization for now
5208 for (char_type & c : d->text_)
5209 if (isLetterChar(c) || isNumber(c))
5214 void Paragraph::Private::markMisspelledWords(
5215 Language const * lang,
5216 pos_type const & first, pos_type const & last,
5217 SpellChecker::Result result,
5218 docstring const & word,
5219 SkipPositions const & skips)
5221 if (!SpellChecker::misspelled(result)) {
5222 setMisspelled(first, last, SpellChecker::WORD_OK);
5226 SpellChecker * speller = theSpellChecker();
5227 // locate and enumerate the error positions
5228 int nerrors = speller->numMisspelledWords();
5230 SkipPositionsIterator it = skips.begin();
5231 SkipPositionsIterator et = skips.end();
5232 for (int index = 0; index < nerrors; ++index) {
5235 speller->misspelledWord(index, wstart, wlen);
5236 /// should not happen if speller supports range checks
5239 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5240 wstart += first + numskipped;
5241 if (snext < wstart) {
5242 /// mark the range of correct spelling
5243 numskipped += countSkips(it, et, wstart);
5244 setMisspelled(snext,
5245 wstart - 1, SpellChecker::WORD_OK);
5247 snext = wstart + wlen;
5248 // Check whether the candidate is in the document's local dict
5249 SpellChecker::Result actresult = result;
5250 if (inset_owner_->buffer().params().spellignored(candidate))
5251 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5252 numskipped += countSkips(it, et, snext);
5253 /// mark the range of misspelling
5254 setMisspelled(wstart, snext, actresult);
5255 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5256 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5257 candidate.word() << "\" [" <<
5258 wstart << ".." << (snext-1) << "]");
5260 LYXERR(Debug::GUI, "misspelled word: \"" <<
5261 candidate.word() << "\" [" <<
5262 wstart << ".." << (snext-1) << "]");
5265 if (snext <= last) {
5266 /// mark the range of correct spelling at end
5267 setMisspelled(snext, last, SpellChecker::WORD_OK);
5272 void Paragraph::spellCheck() const
5274 SpellChecker * speller = theSpellChecker();
5275 if (!speller || empty() ||!needsSpellCheck())
5279 d->rangeOfSpellCheck(start, endpos);
5280 if (speller->canCheckParagraph()) {
5281 // loop until we leave the range
5282 for (pos_type first = start; first < endpos; ) {
5283 pos_type last = endpos;
5284 Private::SkipPositions skips;
5285 Language * lang = d->locateSpellRange(first, last, skips);
5286 if (first >= endpos)
5288 // start the spell checker on the unit of meaning
5289 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5290 WordLangTuple wl = WordLangTuple(word, lang);
5291 BufferParams const & bparams = d->inset_owner_->buffer().params();
5292 SpellChecker::Result result = !word.empty() ?
5293 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5294 d->markMisspelledWords(lang, first, last, result, word, skips);
5298 static docstring_list suggestions;
5299 pos_type to = endpos;
5300 while (start < endpos) {
5302 spellCheck(start, to, wl, suggestions, false);
5306 d->readySpellCheck();
5310 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5312 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5313 if (result || pos <= 0 || pos > size())
5315 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5316 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5321 string Paragraph::magicLabel() const
5324 ss << "magicparlabel-" << id();