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
1176 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1182 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1186 runparams.local_font = &basefont;
1189 if (fontswitch_inset && !closeLanguage) {
1190 // The directionality has been switched at inset.
1191 // Force markup inside.
1192 runparams.local_font = &basefont;
1195 size_t const previous_row_count = os.texrow().rows();
1198 runparams.lastid = id_;
1199 runparams.lastpos = i;
1200 inset->latex(os, runparams);
1201 } catch (EncodingException & e) {
1202 // add location information and throw again.
1208 if (!close_env.empty())
1209 os << "\\end{" << close_env << "}";
1211 if (close_brace > 0) {
1212 for (unsigned i = 0; i < close_brace; ++i)
1218 if (os.texrow().rows() > previous_row_count) {
1219 os.texrow().start(owner_->id(), i + 1);
1222 column += (unsigned int)(os.os().tellp() - len);
1225 if (owner_->isDeleted(i))
1226 --runparams.inDeletedInset;
1230 void Paragraph::Private::latexSpecialChar(otexstream & os,
1231 BufferParams const & bparams,
1232 OutputParams const & runparams,
1233 Font const & running_font,
1234 string & alien_script,
1235 Layout const & style,
1238 unsigned int & column) const
1240 char_type const c = owner_->getUChar(bparams, runparams, i);
1242 if (style.pass_thru || runparams.pass_thru || runparams.find_effective()
1243 || contains(style.pass_thru_chars, c)
1244 || contains(runparams.pass_thru_chars, c)) {
1245 if (runparams.find_effective()) {
1251 os << "\\braceleft ";
1254 os << "\\braceright ";
1257 os << "\\lyxdollar ";
1260 os << "\\lyxtilde ";
1270 else if (c != '\0') {
1271 Encoding const * const enc = runparams.encoding;
1272 if (enc && !enc->encodable(c))
1273 throw EncodingException(c);
1279 // TIPA uses its own T3 encoding
1280 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1282 // If T1 font encoding is used, use the special
1283 // characters it provides.
1284 // NOTE: Some languages reset the font encoding internally to a
1285 // non-standard font encoding. If we are using such a language,
1286 // we do not output special T1 chars.
1287 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1288 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1289 && latexSpecialT1(c, os, i, column))
1291 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1292 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1293 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1296 // Otherwise, we use what LaTeX provides us.
1299 os << "\\textbackslash" << termcmd;
1303 os << "\\textless" << termcmd;
1307 os << "\\textgreater" << termcmd;
1311 os << "\\textbar" << termcmd;
1316 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1317 (end_pos == -1 || i + 1 < end_pos) &&
1318 text_[i+1] == '-') {
1319 // Prevent "--" becoming an en dash and "---" an em dash.
1320 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1326 os << "\\textquotedbl" << termcmd;
1331 case '%': case '#': case '{':
1339 os << "\\textasciitilde" << termcmd;
1344 os << "\\textasciicircum" << termcmd;
1351 // avoid being mistaken for optional arguments
1359 // Blanks are printed before font switching.
1360 // Sure? I am not! (try nice-latex)
1361 // I am sure it's correct. LyX might be smarter
1362 // in the future, but for now, nothing wrong is
1368 // XeTeX's dash behaviour is determined via a global setting
1369 if (bparams.use_dash_ligatures
1370 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1372 // TODO #10961: && not in inset Flex Code
1373 // TODO #10961: && not in layout LyXCode
1374 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1391 Encoding const & encoding = *(runparams.encoding);
1392 char_type next = '\0';
1393 if (i + 1 < int(text_.size())) {
1394 next = text_[i + 1];
1395 if (Encodings::isCombiningChar(next)) {
1396 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1401 pair<docstring, bool> latex = encoding.latexChar(c);
1402 docstring nextlatex;
1403 bool nexttipas = false;
1404 string nexttipashortcut;
1405 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1406 nextlatex = encoding.latexChar(next).first;
1407 if (runparams.inIPA) {
1408 nexttipashortcut = Encodings::TIPAShortcut(next);
1409 nexttipas = !nexttipashortcut.empty();
1413 if (runparams.inIPA) {
1414 string const tipashortcut = Encodings::TIPAShortcut(c);
1415 if (!tipashortcut.empty()) {
1416 latex.first = from_ascii(tipashortcut);
1417 latex.second = false;
1421 // eventually close "script wrapper" command (see `Paragraph::latex`)
1422 if (!alien_script.empty()
1423 && alien_script != Encodings::isKnownScriptChar(next)) {
1424 column += latex.first.length();
1425 alien_script.clear();
1426 os << latex.first << "}";
1430 && ((!prefixIs(nextlatex, '\\')
1431 && !prefixIs(nextlatex, '{')
1432 && !prefixIs(nextlatex, '}'))
1434 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1436 // Prevent eating of a following space or command corruption by
1437 // following characters
1438 if (next == ' ' || next == '\0') {
1439 column += latex.first.length() + 1;
1440 os << latex.first << "{}";
1442 column += latex.first.length();
1443 os << latex.first << " ";
1446 column += latex.first.length() - 1;
1454 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1455 pos_type i, unsigned int & column) const
1461 // In T1 encoding, these characters exist
1462 // but we should avoid ligatures
1463 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1465 os << "\\textcompwordmark" << termcmd;
1472 // soul.sty breaks with \char`\"
1473 os << "\\textquotedbl" << termcmd;
1482 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1483 pos_type i, unsigned int & column) const
1485 // TU encoding is currently on par with T1.
1486 return latexSpecialT1(c, os, i, column);
1490 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1491 pos_type /*i*/, unsigned int & column) const
1501 os << "\\textvertline" << termcmd;
1510 void Paragraph::Private::validate(LaTeXFeatures & features) const
1512 if (layout_->inpreamble && inset_owner_) {
1513 // FIXME: Using a string stream here circumvents the encoding
1514 // switching machinery of odocstream. Therefore the
1515 // output is wrong if this paragraph contains content
1516 // that needs to switch encoding.
1517 Buffer const & buf = inset_owner_->buffer();
1518 otexstringstream os;
1519 os << layout_->preamble();
1520 size_t const length = os.length();
1521 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1522 buf.getParFromID(owner_->id()).pit(), os,
1523 features.runparams(), string(), 0, -1, true);
1524 if (os.length() > length)
1525 features.addPreambleSnippet(os.release(), true);
1528 if (features.runparams().flavor == Flavor::Html
1529 && layout_->htmltitle()) {
1530 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1533 // check the params.
1534 if (!params_.spacing().isDefault())
1535 features.require("setspace");
1538 features.useLayout(layout_->name());
1541 fontlist_.validate(features);
1543 // then the indentation
1544 if (!params_.leftIndent().zero())
1545 features.require("ParagraphLeftIndent");
1548 InsetList::const_iterator icit = insetlist_.begin();
1549 InsetList::const_iterator iend = insetlist_.end();
1550 for (; icit != iend; ++icit) {
1552 features.inDeletedInset(owner_->isDeleted(icit->pos));
1553 if (icit->inset->lyxCode() == FOOT_CODE) {
1554 // FIXME: an item inset would make things much easier.
1555 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1556 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1557 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1558 && (icit->pos < begin_of_body_
1559 || (icit->pos == begin_of_body_
1560 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1561 features.saveNoteEnv("description");
1563 icit->inset->validate(features);
1564 features.inDeletedInset(false);
1565 if (layout_->needprotect &&
1566 icit->inset->lyxCode() == FOOT_CODE)
1567 features.require("NeedLyXFootnoteCode");
1571 // then the contents
1572 BufferParams const bp = features.runparams().is_child
1573 ? features.buffer().masterParams() : features.buffer().params();
1574 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1575 char_type c = text_[i];
1576 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1578 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1579 features.require("textquotedblp");
1580 else if (features.runparams().main_fontenc != "T1"
1581 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1582 features.require("textquotedbl");
1583 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1584 // features that depend on the font or input encoding
1585 string feats = ci.textPreamble();
1586 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1587 if (fontenc.empty())
1588 fontenc = features.runparams().main_fontenc;
1589 while (!feats.empty()) {
1591 feats = split(feats, feat, ',');
1592 if (contains(feat, "!=")) {
1593 // a feature that is required except for the spcified
1594 // font or input encodings
1596 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1597 // multiple encodings are separated by semicolon
1598 vector<string> context = getVectorFromString(contexts, ";");
1599 // require feature if the context matches neither current font
1600 // nor input encoding
1601 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1602 && std::find(context.begin(), context.end(),
1603 features.runparams().encoding->name()) == context.end())
1604 features.require(realfeature);
1605 } else if (contains(feat, '=')) {
1606 // a feature that is required only for the spcified
1607 // font or input encodings
1609 string const contexts = split(feat, realfeature, '=');
1610 // multiple encodings are separated by semicolon
1611 vector<string> context = getVectorFromString(contexts, ";");
1612 // require feature if the context matches either current font
1613 // or input encoding
1614 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1615 || std::find(context.begin(), context.end(),
1616 features.runparams().encoding->name()) != context.end())
1617 features.require(realfeature);
1620 } else if (!bp.use_dash_ligatures
1621 && (c == 0x2013 || c == 0x2014)
1622 && bp.useNonTeXFonts
1623 && features.runparams().flavor == Flavor::XeTeX)
1624 // XeTeX's dash behaviour is determined via a global setting
1625 features.require("xetexdashbreakstate");
1626 BufferEncodings::validate(c, features);
1630 /////////////////////////////////////////////////////////////////////
1634 /////////////////////////////////////////////////////////////////////
1637 Layout const emptyParagraphLayout;
1640 Paragraph::Paragraph()
1641 : d(new Paragraph::Private(this, emptyParagraphLayout))
1648 Paragraph::Paragraph(Paragraph const & par)
1649 : itemdepth(par.itemdepth),
1650 d(new Paragraph::Private(*par.d, this))
1656 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1657 : itemdepth(par.itemdepth),
1658 d(new Paragraph::Private(*par.d, this, beg, end))
1664 Paragraph & Paragraph::operator=(Paragraph const & par)
1666 // needed as we will destroy the private part before copying it
1668 itemdepth = par.itemdepth;
1672 d = new Private(*par.d, this);
1679 Paragraph::~Paragraph()
1688 // this shall be called just before every "os << ..." action.
1689 void flushString(ostream & os, docstring & s)
1698 void Paragraph::write(ostream & os, BufferParams const & bparams,
1699 depth_type & depth) const
1701 // The beginning or end of a deeper (i.e. nested) area?
1702 if (depth != d->params_.depth()) {
1703 if (d->params_.depth() > depth) {
1704 while (d->params_.depth() > depth) {
1705 os << "\n\\begin_deeper";
1709 while (d->params_.depth() < depth) {
1710 os << "\n\\end_deeper";
1716 // First write the layout
1717 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1719 d->params_.write(os);
1721 Font font1(inherit_font, bparams.language);
1723 Change running_change = Change(Change::UNCHANGED);
1725 // this string is used as a buffer to avoid repetitive calls
1726 // to to_utf8(), which turn out to be expensive (JMarc)
1727 docstring write_buffer;
1730 for (pos_type i = 0; i <= size(); ++i) {
1732 Change const & change = lookupChange(i);
1733 if (change != running_change)
1734 flushString(os, write_buffer);
1735 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1736 running_change = change;
1741 // Write font changes
1742 Font font2 = getFontSettings(bparams, i);
1743 if (font2 != font1) {
1744 flushString(os, write_buffer);
1745 font2.lyxWriteChanges(font1, os);
1750 char_type const c = d->text_[i];
1753 if (Inset const * inset = getInset(i)) {
1754 flushString(os, write_buffer);
1755 if (inset->directWrite()) {
1756 // international char, let it write
1757 // code directly so it's shorter in
1763 os << "\\begin_inset ";
1765 os << "\n\\end_inset\n\n";
1768 // FIXME This can be removed again once the mystery
1769 // crash has been resolved.
1774 flushString(os, write_buffer);
1775 os << "\n\\backslash\n";
1784 case 0x061F: // ؟ U+061F ARABIC QUESTION MARK
1785 case 0x061B: // ؛ U+061B ARABIC SEMICOLON
1786 case 0x060C: // ، U+060C ARABIC COMMA
1787 flushString(os, write_buffer);
1788 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1789 os << to_utf8(docstring(1, c)) << '\n';
1792 os << to_utf8(docstring(1, c));
1794 case 0x2014: // — U+2014 EM DASH
1795 case 0x3002: // 。 U+3002 IDEOGRAPHIC FULL STOP
1796 case 0xFF01: // ! U+FF01 FULLWIDTH EXCLAMATION MARK
1797 case 0xFF1F: // ? U+FF1F FULLWIDTH QUESTION MARK
1798 case 0xFF1A: // : U+FF1A FULLWIDTH COLON
1799 case 0xFF1B: // ; U+FF1B FULLWIDTH SEMICOLON
1800 case 0xFF0C: // , U+FF0C FULLWIDTH COMMA
1801 flushString(os, write_buffer);
1802 os << to_utf8(docstring(1, c)) << '\n';
1807 flushString(os, write_buffer);
1811 // this check is to amend a bug. LyX sometimes
1812 // inserts '\0' this could cause problems.
1814 write_buffer.push_back(c);
1816 LYXERR0("NUL char in structure.");
1822 flushString(os, write_buffer);
1823 os << "\n\\end_layout\n";
1824 // FIXME This can be removed again once the mystery
1825 // crash has been resolved.
1830 void Paragraph::validate(LaTeXFeatures & features) const
1832 d->validate(features);
1833 bool fragile = features.runparams().moving_arg;
1834 fragile |= layout().needprotect;
1835 if (inInset().getLayout().isNeedProtect())
1837 if (needsCProtection(fragile))
1838 features.require("cprotect");
1842 void Paragraph::insert(pos_type pos, docstring const & str,
1843 Font const & font, Change const & change)
1845 for (size_t i = 0, n = str.size(); i != n ; ++i)
1846 insertChar(pos + i, str[i], font, change);
1850 void Paragraph::appendChar(char_type c, Font const & font,
1851 Change const & change)
1853 // Make sure that Buffer::hasChangesPresent is updated
1854 ChangesMonitor cm(*this);
1857 d->changes_.insert(change, d->text_.size());
1858 // when appending characters, no need to update tables
1859 d->text_.push_back(c);
1860 setFont(d->text_.size() - 1, font);
1861 d->requestSpellCheck(d->text_.size() - 1);
1865 void Paragraph::appendString(docstring const & s, Font const & font,
1866 Change const & change)
1868 // Make sure that Buffer::hasChangesPresent is updated
1869 ChangesMonitor cm(*this);
1871 pos_type end = s.size();
1872 size_t oldsize = d->text_.size();
1873 size_t newsize = oldsize + end;
1874 size_t capacity = d->text_.capacity();
1875 if (newsize >= capacity)
1876 d->text_.reserve(max(capacity + 100, newsize));
1878 // when appending characters, no need to update tables
1881 // FIXME: Optimize this!
1882 for (size_t i = oldsize; i != newsize; ++i) {
1884 d->changes_.insert(change, i);
1885 d->requestSpellCheck(i);
1887 d->fontlist_.set(oldsize, font);
1888 d->fontlist_.set(newsize - 1, font);
1892 void Paragraph::insertChar(pos_type pos, char_type c,
1895 d->insertChar(pos, c, Change(trackChanges ?
1896 Change::INSERTED : Change::UNCHANGED));
1900 void Paragraph::insertChar(pos_type pos, char_type c,
1901 Font const & font, bool trackChanges)
1903 d->insertChar(pos, c, Change(trackChanges ?
1904 Change::INSERTED : Change::UNCHANGED));
1909 void Paragraph::insertChar(pos_type pos, char_type c,
1910 Font const & font, Change const & change)
1912 d->insertChar(pos, c, change);
1917 void Paragraph::resetFonts(Font const & font)
1919 d->fontlist_.clear();
1920 d->fontlist_.set(0, font);
1921 d->fontlist_.set(d->text_.size() - 1, font);
1924 // Gets uninstantiated font setting at position.
1925 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1929 LYXERR0("pos: " << pos << " size: " << size());
1933 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1934 if (cit != d->fontlist_.end())
1937 if (pos == size() && !empty())
1938 return getFontSettings(bparams, pos - 1);
1940 // Optimisation: avoid a full font instantiation if there is no
1941 // language change from previous call.
1942 static Font previous_font;
1943 static Language const * previous_lang = nullptr;
1944 Language const * lang = getParLanguage(bparams);
1945 if (lang != previous_lang) {
1946 previous_lang = lang;
1947 previous_font = Font(inherit_font, lang);
1949 return previous_font;
1953 FontSpan Paragraph::fontSpan(pos_type pos) const
1955 LBUFERR(pos <= size());
1958 return FontSpan(pos, pos);
1961 FontList::const_iterator cit = d->fontlist_.begin();
1962 FontList::const_iterator end = d->fontlist_.end();
1963 for (; cit != end; ++cit) {
1964 if (cit->pos() >= pos) {
1965 if (pos >= beginOfBody())
1966 return FontSpan(max(start, beginOfBody()),
1969 return FontSpan(start,
1970 min(beginOfBody() - 1,
1973 start = cit->pos() + 1;
1976 // This should not happen, but if so, we take no chances.
1977 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1978 LASSERT(false, /**/);
1979 return FontSpan(pos, pos);
1983 // Gets uninstantiated font setting at position 0
1984 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1986 if (!empty() && !d->fontlist_.empty())
1987 return d->fontlist_.begin()->font();
1989 // Optimisation: avoid a full font instantiation if there is no
1990 // language change from previous call.
1991 static Font previous_font;
1992 static Language const * previous_lang = nullptr;
1993 if (bparams.language != previous_lang) {
1994 previous_lang = bparams.language;
1995 previous_font = Font(inherit_font, bparams.language);
1998 return previous_font;
2002 // Gets the fully instantiated font at a given position in a paragraph
2003 // This is basically the same function as TextMetrics::displayFont().
2004 // The difference is that this one is used for generating the LaTeX file,
2005 // and thus cosmetic "improvements" are disallowed: This has to deliver
2006 // the true picture of the buffer. (Asger)
2007 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
2008 Font const & outerfont) const
2012 Font font = getFontSettings(bparams, pos);
2014 pos_type const body_pos = beginOfBody();
2015 FontInfo & fi = font.fontInfo();
2017 fi.realize(d->layout_->labelfont);
2019 fi.realize(d->layout_->font);
2021 fi.realize(outerfont.fontInfo());
2022 fi.realize(bparams.getFont().fontInfo());
2028 Font const Paragraph::getLabelFont
2029 (BufferParams const & bparams, Font const & outerfont) const
2031 FontInfo tmpfont = d->layout_->labelfont;
2032 tmpfont.realize(outerfont.fontInfo());
2033 tmpfont.realize(bparams.getFont().fontInfo());
2034 return Font(tmpfont, getParLanguage(bparams));
2038 Font const Paragraph::getLayoutFont
2039 (BufferParams const & bparams, Font const & outerfont) const
2041 FontInfo tmpfont = d->layout_->font;
2042 tmpfont.realize(outerfont.fontInfo());
2043 tmpfont.realize(bparams.getFont().fontInfo());
2044 return Font(tmpfont, getParLanguage(bparams));
2048 char_type Paragraph::getUChar(BufferParams const & bparams,
2049 OutputParams const & rp,
2052 char_type c = d->text_[pos];
2054 // Return unchanged character
2055 // 1. in all LTR languages
2056 // 2. if we use XeTeX (both with babel and polyglossia)
2057 // 3. if we use LuaTeX with babel
2058 if (!getFontSettings(bparams, pos).isRightToLeft()
2059 || rp.flavor == Flavor::XeTeX
2060 || (rp.use_babel && rp.flavor == Flavor::LuaTeX))
2063 // For the remaining cases, we need to account for some special cases.
2064 // FIXME This needs to be audited!
2066 // * The input is as expected for all delimiters
2067 // => checked for Hebrew!
2068 // * The output matches the display in the LyX workarea
2069 // => checked for Hebrew!
2070 // * The special cases below are really necessary
2071 // => checked for Hebrew!
2072 // * In arabic_arabi, brackets are transformed to Arabic
2073 // Ornate Parentheses. Is this is really wanted?
2074 // => Yes, in file ararabeyes.enc from the arabi bundle
2075 // the slot of the left bracket (slot 91) is encoded as
2076 // "ornaterightparenthesis". This is also the reason
2077 // brackets don't need to be mirrored with arabi
2079 string const & lang = getFontSettings(bparams, pos).language()->lang();
2082 // These are the cases where we need to mirror delimiters in RTL context
2083 // in the remaining cases (polyglossia + LuaTeX or classic [pdf]latex):
2084 // 1. With polyglossia and LuaTeX (luabidi) parentheses and brackets
2085 // need to be mirrored in RTL, regardless of the language, or script.
2086 // 2. In the languages that follow, parentheses need to be mirrored
2087 // in classic (pdf)latex
2088 bool const reverseparens = (rp.use_polyglossia || lang == "hebrew");
2089 // 3. In all RTL languages except for those that follow, brackets
2090 // need to be mirrored in classic (pdf)latex
2091 bool const reversebrackets = rp.use_polyglossia
2092 || (lang != "arabic_arabtex"
2093 && lang != "arabic_arabi"
2094 && lang != "farsi");
2096 // Now swap delimiters if needed.
2107 if (reversebrackets)
2111 if (reversebrackets)
2132 void Paragraph::setFont(pos_type pos, Font const & font)
2134 LASSERT(pos <= size(), return);
2136 // Text::setCharFont() already reduces font against layout/label
2137 // font, so we don't need to do that here. (Asger)
2138 d->fontlist_.set(pos, font);
2142 void Paragraph::makeSameLayout(Paragraph const & par)
2144 d->layout_ = par.d->layout_;
2145 d->params_ = par.d->params_;
2149 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2151 if (isFreeSpacing())
2157 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2158 if (eraseChar(pos, trackChanges))
2164 return count > 0 || pos > 0;
2168 bool Paragraph::hasSameLayout(Paragraph const & par) const
2170 return par.d->layout_ == d->layout_
2171 && d->params_.sameLayout(par.d->params_);
2175 depth_type Paragraph::getDepth() const
2177 return d->params_.depth();
2181 depth_type Paragraph::getMaxDepthAfter() const
2183 if (d->layout_->isEnvironment())
2184 return d->params_.depth() + 1;
2186 return d->params_.depth();
2190 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2192 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2193 return getDefaultAlign(bparams);
2195 return d->params_.align();
2199 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2201 LyXAlignment res = layout().align;
2202 if (isRTL(bparams)) {
2204 if (res == LYX_ALIGN_LEFT)
2205 res = LYX_ALIGN_RIGHT;
2206 else if (res == LYX_ALIGN_RIGHT)
2207 res = LYX_ALIGN_LEFT;
2213 docstring const & Paragraph::labelString() const
2215 return d->params_.labelString();
2219 // the next two functions are for the manual labels
2220 docstring const Paragraph::getLabelWidthString() const
2222 if (d->layout_->margintype == MARGIN_MANUAL
2223 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2224 return d->params_.labelWidthString();
2226 return _("Senseless with this layout!");
2230 void Paragraph::setLabelWidthString(docstring const & s)
2232 d->params_.labelWidthString(s);
2236 docstring Paragraph::expandLabel(Layout const & layout,
2237 BufferParams const & bparams) const
2239 return expandParagraphLabel(layout, bparams, true);
2243 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2244 BufferParams const & bparams, bool process_appendix) const
2246 DocumentClass const & tclass = bparams.documentClass();
2247 string const & lang = getParLanguage(bparams)->code();
2248 bool const in_appendix = process_appendix && d->params_.appendix();
2249 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2251 if (fmt.empty() && !layout.counter.empty())
2252 return tclass.counters().theCounter(layout.counter, lang);
2254 // handle 'inherited level parts' in 'fmt',
2255 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2256 size_t const i = fmt.find('@', 0);
2257 if (i != docstring::npos) {
2258 size_t const j = fmt.find('@', i + 1);
2259 if (j != docstring::npos) {
2260 docstring parent(fmt, i + 1, j - i - 1);
2261 docstring label = from_ascii("??");
2262 if (tclass.hasLayout(parent))
2263 label = expandParagraphLabel(tclass[parent], bparams,
2265 fmt = docstring(fmt, 0, i) + label
2266 + docstring(fmt, j + 1, docstring::npos);
2270 return tclass.counters().counterLabel(fmt, lang);
2274 void Paragraph::applyLayout(Layout const & new_layout)
2276 d->layout_ = &new_layout;
2277 LyXAlignment const oldAlign = d->params_.align();
2279 if (!(oldAlign & d->layout_->alignpossible)) {
2280 frontend::Alert::warning(_("Alignment not permitted"),
2281 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2282 d->params_.align(LYX_ALIGN_LAYOUT);
2287 pos_type Paragraph::beginOfBody() const
2289 return d->begin_of_body_;
2293 void Paragraph::setBeginOfBody()
2295 if (d->layout_->labeltype != LABEL_MANUAL) {
2296 d->begin_of_body_ = 0;
2300 // Unroll the first two cycles of the loop
2301 // and remember the previous character to
2302 // remove unnecessary getChar() calls
2304 pos_type end = size();
2305 bool prev_char_deleted = false;
2306 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2309 char_type previous_char = d->text_[i];
2310 if (!(isNewline(i) || isEnvSeparator(i))) {
2312 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2313 char_type temp = d->text_[i];
2314 prev_char_deleted = isDeleted(i);
2315 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2318 previous_char = temp;
2324 d->begin_of_body_ = i;
2328 bool Paragraph::allowParagraphCustomization() const
2330 return inInset().allowParagraphCustomization();
2334 bool Paragraph::usePlainLayout() const
2336 return inInset().usePlainLayout();
2340 bool Paragraph::isPassThru() const
2342 return inInset().isPassThru() || d->layout_->pass_thru;
2346 bool Paragraph::parbreakIsNewline() const
2348 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2352 bool Paragraph::allowedInContext(Cursor const & cur, InsetLayout const & il) const
2354 set<docstring> const & allowed_insets = il.allowedInInsets();
2355 set<docstring> const & allowed_layouts = il.allowedInLayouts();
2357 bool in_allowed_inset =
2358 allowed_insets.find(inInset().getLayout().name()) != allowed_insets.end();
2360 bool in_allowed_layout =
2361 allowed_layouts.find(d->layout_->name()) != allowed_layouts.end();
2363 if (!in_allowed_inset && inInset().asInsetArgument()) {
2364 // check if the argument allows the inset in question
2365 if (cur.depth() > 1) {
2366 docstring parlayout = cur[cur.depth() - 2].inset().getLayout().name()
2367 + from_ascii("@") + from_ascii(inInset().asInsetArgument()->name());
2368 if (allowed_insets.find(parlayout) != allowed_insets.end())
2369 in_allowed_inset = true;
2374 // check if we exceed the number of allowed insets in this inset
2375 if (in_allowed_inset && inInset().asInsetText() && il.allowedOccurrences() != -1) {
2376 ParagraphList & pars = cur.text()->paragraphs();
2377 for (Paragraph const & par : pars) {
2378 for (auto const & elem : par.insetList())
2379 if (elem.inset->getLayout().name() == il.name())
2382 if (have_ins >= il.allowedOccurrences())
2387 // check if we exceed the number of allowed insets in the layout group
2388 if (in_allowed_layout && il.allowedOccurrences() != -1) {
2389 pit_type pit = cur.pit();
2390 pit_type lastpit = cur.pit();
2391 ParagraphList & pars = cur.text()->paragraphs();
2392 // If we are not on a list-type environment or AllowedOccurrencesPerItem
2393 // is false, we check the whole paragraph group
2394 if (d->layout_->isEnvironment()
2395 && !(il.allowedOccurrencesPerItem()
2396 && (d->layout_->latextype == LATEX_LIST_ENVIRONMENT
2397 || d->layout_->latextype == LATEX_ITEM_ENVIRONMENT))) {
2398 lastpit = cur.lastpit();
2399 // get the first paragraph in sequence with this layout
2400 depth_type const current_depth = params().depth();
2404 Paragraph cpar = pars[pit - 1];
2405 if (&cpar.layout() == d->layout_
2406 && cpar.params().depth() == current_depth)
2412 for (; pit <= lastpit; ++pit) {
2413 if (&pars[pit].layout() != d->layout_)
2415 for (auto const & elem : pars[pit].insetList())
2416 if (elem.inset->getLayout().name() == il.name())
2419 if (have_ins >= il.allowedOccurrences())
2423 if (in_allowed_layout || in_allowed_inset)
2426 return (allowed_insets.empty() && allowed_layouts.empty());
2430 bool Paragraph::isPartOfTextSequence() const
2432 for (pos_type i = 0; i < size(); ++i) {
2433 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2441 // paragraphs inside floats need different alignment tags to avoid
2444 bool noTrivlistCentering(InsetCode code)
2446 return code == FLOAT_CODE
2447 || code == WRAP_CODE
2448 || code == CELL_CODE;
2452 string correction(string const & orig)
2454 if (orig == "flushleft")
2455 return "raggedright";
2456 if (orig == "flushright")
2457 return "raggedleft";
2458 if (orig == "center")
2464 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2465 InsetCode code, bool const lastpar, int & col)
2467 string macro = suffix + "{";
2468 if (noTrivlistCentering(code)) {
2470 // the last paragraph in non-trivlist-aligned
2471 // context is special (to avoid unwanted whitespace)
2472 if (suffix == "\\begin") {
2473 macro = "\\" + correction(env) + "{}";
2474 os << from_ascii(macro);
2475 col += macro.size();
2480 macro += correction(env);
2484 if (suffix == "\\par\\end") {
2488 os << from_ascii(macro);
2489 col += macro.size();
2490 if (suffix == "\\begin") {
2500 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2501 otexstream & os, OutputParams const & runparams) const
2506 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2507 (layout_->toggle_indent != ITOGGLE_NEVER) :
2508 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2510 LyXAlignment const curAlign = params_.align();
2512 // Do not output \\noindent for paragraphs
2513 // 1. that cannot have indentation or are indented always,
2514 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2515 // 3. that are PassThru,
2516 // 4. or that are centered.
2517 if (canindent && params_.noindent()
2518 && owner_->isPartOfTextSequence()
2519 && !layout_->pass_thru
2520 && curAlign != LYX_ALIGN_CENTER) {
2521 if (!owner_->empty()
2522 && owner_->getInset(0)
2523 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2524 // If the paragraph starts with a vspace, the \\noindent
2525 // needs to come after that (as it leaves vmode).
2526 // If the paragraph consists only of the vspace,
2527 // \\noindent is not needed at all.
2528 runparams.need_noindent = owner_->size() > 1;
2530 os << "\\noindent" << termcmd;
2535 if (curAlign == layout_->align)
2539 case LYX_ALIGN_NONE:
2540 case LYX_ALIGN_BLOCK:
2541 case LYX_ALIGN_LAYOUT:
2542 case LYX_ALIGN_SPECIAL:
2543 case LYX_ALIGN_DECIMAL:
2545 case LYX_ALIGN_LEFT:
2546 case LYX_ALIGN_RIGHT:
2547 case LYX_ALIGN_CENTER:
2548 if (runparams.moving_arg) {
2555 string const begin_tag = "\\begin";
2556 InsetCode code = ownerCode();
2557 bool const lastpar = runparams.isLastPar;
2558 // RTL in classic (PDF)LaTeX (without the Bidi package)
2559 // Luabibdi (used by LuaTeX) behaves like classic
2560 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2561 && !bparams.useBidiPackage(runparams);
2564 case LYX_ALIGN_NONE:
2565 case LYX_ALIGN_BLOCK:
2566 case LYX_ALIGN_LAYOUT:
2567 case LYX_ALIGN_SPECIAL:
2568 case LYX_ALIGN_DECIMAL:
2570 case LYX_ALIGN_LEFT: {
2572 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2573 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2575 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2577 } case LYX_ALIGN_RIGHT: {
2579 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2580 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2582 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2584 } case LYX_ALIGN_CENTER: {
2585 corrected_env(os, begin_tag, "center", code, lastpar, column);
2594 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2595 otexstream & os, OutputParams const & runparams) const
2597 LyXAlignment const curAlign = params_.align();
2599 if (curAlign == layout_->align)
2603 case LYX_ALIGN_NONE:
2604 case LYX_ALIGN_BLOCK:
2605 case LYX_ALIGN_LAYOUT:
2606 case LYX_ALIGN_SPECIAL:
2607 case LYX_ALIGN_DECIMAL:
2609 case LYX_ALIGN_LEFT:
2610 case LYX_ALIGN_RIGHT:
2611 case LYX_ALIGN_CENTER:
2612 if (runparams.moving_arg)
2617 bool output = false;
2619 string const end_tag = "\\par\\end";
2620 InsetCode code = ownerCode();
2621 bool const lastpar = runparams.isLastPar;
2622 // RTL in classic (PDF)LaTeX (without the Bidi package)
2623 // Luabibdi (used by LuaTeX) behaves like classic
2624 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2625 && !bparams.useBidiPackage(runparams);
2628 case LYX_ALIGN_NONE:
2629 case LYX_ALIGN_BLOCK:
2630 case LYX_ALIGN_LAYOUT:
2631 case LYX_ALIGN_SPECIAL:
2632 case LYX_ALIGN_DECIMAL:
2634 case LYX_ALIGN_LEFT: {
2636 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2637 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2639 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2641 } case LYX_ALIGN_RIGHT: {
2643 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2644 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2646 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2648 } case LYX_ALIGN_CENTER: {
2649 corrected_env(os, end_tag, "center", code, lastpar, col);
2654 return output || lastpar;
2658 // This one spits out the text of the paragraph
2659 void Paragraph::latex(BufferParams const & bparams,
2660 Font const & outerfont,
2662 OutputParams const & runparams,
2663 int start_pos, int end_pos, bool force) const
2665 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2667 // FIXME This check should not be needed. Perhaps issue an
2668 // error if it triggers.
2669 Layout const & style = inInset().forcePlainLayout() ?
2670 bparams.documentClass().plainLayout() : *d->layout_;
2672 if (!force && style.inpreamble)
2675 bool const allowcust = allowParagraphCustomization();
2677 // Current base font for all inherited font changes, without any
2678 // change caused by an individual character, except for the language:
2679 // It is set to the language of the first character.
2680 // As long as we are in the label, this font is the base font of the
2681 // label. Before the first body character it is set to the base font
2685 // If there is an open font-encoding changing command (script wrapper),
2686 // alien_script is set to its name
2687 string alien_script;
2690 // Maybe we have to create a optional argument.
2691 pos_type body_pos = beginOfBody();
2692 unsigned int column = 0;
2694 // If we are inside an non inheritFont() inset,
2695 // the outerfont is the buffer's main font
2696 Font const real_outerfont =
2697 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2700 // the optional argument is kept in curly brackets in
2701 // case it contains a ']'
2702 // This is not strictly needed, but if this is changed it
2703 // would be a file format change, and tex2lyx would need
2704 // to be adjusted, since it unconditionally removes the
2705 // braces when it parses \item.
2708 basefont = getLabelFont(bparams, real_outerfont);
2710 basefont = getLayoutFont(bparams, real_outerfont);
2713 // Which font is currently active?
2714 Font running_font(basefont);
2715 // Do we have an open font change?
2716 bool open_font = false;
2718 Change runningChange =
2719 runparams.inDeletedInset && !inInset().canTrackChanges()
2720 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2722 Encoding const * const prev_encoding = runparams.encoding;
2724 os.texrow().start(id(), 0);
2726 // if the paragraph is empty, the loop will not be entered at all
2728 // For InTitle commands, we have already opened a group
2729 // in output_latex::TeXOnePar.
2730 if (style.isCommand() && !style.intitle) {
2734 if (!style.leftdelim().empty()) {
2735 os << style.leftdelim();
2736 column += style.leftdelim().size();
2739 column += d->startTeXParParams(bparams, os, runparams);
2742 // Whether a \par can be issued for insets typeset inline with text.
2743 // Yes if greater than 0. This has to be static.
2744 THREAD_LOCAL_STATIC int parInline = 0;
2746 for (pos_type i = 0; i < size(); ++i) {
2747 // First char in paragraph or after label?
2748 if (i == body_pos) {
2751 bool needPar = false;
2752 column += running_font.latexWriteEndChanges(
2753 os, bparams, runparams,
2754 basefont, basefont, needPar);
2757 basefont = getLayoutFont(bparams, real_outerfont);
2758 running_font = basefont;
2760 column += Changes::latexMarkChange(os, bparams,
2761 runningChange, Change(Change::UNCHANGED),
2763 runningChange = Change(Change::UNCHANGED);
2765 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2768 // For InTitle commands, we have already opened a group
2769 // in output_latex::TeXOnePar.
2770 if (style.isCommand() && !style.intitle) {
2775 if (!style.leftdelim().empty()) {
2776 os << style.leftdelim();
2777 column += style.leftdelim().size();
2781 column += d->startTeXParParams(bparams, os,
2785 runparams.wasDisplayMath = runparams.inDisplayMath;
2786 runparams.inDisplayMath = false;
2787 bool deleted_display_math = false;
2788 Change const & change = runparams.inDeletedInset
2789 ? runparams.changeOfDeletedInset : lookupChange(i);
2791 char_type const c = d->text_[i];
2793 // Check whether a display math inset follows
2794 bool output_changes;
2795 if (!runparams.find_effective())
2796 output_changes = bparams.output_changes;
2798 output_changes = runparams.find_with_deleted();
2800 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2802 runparams.ctObject = getInset(i)->getCtObject(runparams);
2804 InsetMath const * im = getInset(i)->asInsetMath();
2805 if (im && im->asHullInset()
2806 && im->asHullInset()->outerDisplay()) {
2807 runparams.inDisplayMath = true;
2808 // runparams.inDeletedInset will be set by
2809 // latexInset later, but we need this info
2810 // before it is called. On the other hand, we
2811 // cannot set it here because it is a counter.
2812 deleted_display_math = isDeleted(i);
2814 if (output_changes && deleted_display_math
2815 && runningChange == change
2816 && change.type == Change::DELETED
2817 && !os.afterParbreak()) {
2818 // A display math in the same paragraph follows.
2819 // We have to close and then reopen \lyxdeleted,
2820 // otherwise the math will be shifted up.
2821 OutputParams rp = runparams;
2823 bool needPar = false;
2824 column += running_font.latexWriteEndChanges(
2825 os, bparams, rp, basefont,
2829 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2830 : getLayoutFont(bparams, real_outerfont);
2831 running_font = basefont;
2832 column += Changes::latexMarkChange(os, bparams,
2833 Change(Change::INSERTED), change, rp);
2837 if (output_changes && runningChange != change) {
2838 if (!alien_script.empty()) {
2841 alien_script.clear();
2844 bool needPar = false;
2845 column += running_font.latexWriteEndChanges(
2846 os, bparams, runparams,
2847 basefont, basefont, needPar);
2850 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2851 : getLayoutFont(bparams, real_outerfont);
2852 running_font = basefont;
2853 column += Changes::latexMarkChange(os, bparams, runningChange,
2855 runningChange = change;
2858 // do not output text which is marked deleted
2859 // if change tracking output is disabled
2860 if (!output_changes && change.deleted()) {
2866 // Fully instantiated font
2867 Font current_font = getFont(bparams, i, outerfont);
2869 Font const prev_font = (i > 0) ?
2870 getFont(bparams, i - 1, outerfont)
2873 Font const last_font = running_font;
2874 bool const in_ct_deletion = (output_changes
2875 && runningChange == change
2876 && change.type == Change::DELETED
2877 && !os.afterParbreak());
2878 // Insets where font switches are used (rather than font commands)
2879 bool const fontswitch_inset =
2882 && getInset(i)->allowMultiPar()
2883 && getInset(i)->lyxCode() != ERT_CODE
2884 && (getInset(i)->producesOutput()
2885 // FIXME Something more general?
2886 // Comments do not "produce output" but are still
2887 // part of the TeX source and require font switches
2888 // to be closed (otherwise LaTeX fails).
2889 || getInset(i)->layoutName() == "Note:Comment");
2891 bool closeLanguage = false;
2892 bool lang_switched_at_inset = false;
2893 if (fontswitch_inset) {
2894 // Some insets cannot be inside a font change command.
2895 // However, even such insets *can* be placed in \L or \R
2896 // or their equivalents (for RTL language switches),
2897 // so we don't close the language in those cases
2898 // (= differing isRightToLeft()).
2899 // ArabTeX, though, doesn't seem to handle this special behavior.
2900 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2901 || basefont.language()->lang() == "arabic_arabtex"
2902 || current_font.language()->lang() == "arabic_arabtex";
2903 // We need to check prev_font as language changes directly at inset
2904 // will only be started inside the inset.
2905 lang_switched_at_inset = prev_font.language() != current_font.language();
2908 // Do we need to close the previous font?
2909 bool langClosed = false;
2911 ((current_font != running_font
2912 || current_font.language() != running_font.language())
2913 || (fontswitch_inset
2914 && (current_font == prev_font))))
2916 // ensure there is no open script-wrapper
2917 if (!alien_script.empty()) {
2920 alien_script.clear();
2922 if (in_ct_deletion) {
2923 // We have to close and then reopen \lyxdeleted,
2924 // as strikeout needs to be on lowest level.
2928 if (closeLanguage) {
2929 // Force language closing
2930 current_font.setLanguage(basefont.language());
2933 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2934 bool needPar = false;
2935 column += running_font.latexWriteEndChanges(
2936 os, bparams, runparams, basefont,
2938 if (in_ct_deletion) {
2939 // We have to close and then reopen \lyxdeleted,
2940 // as strikeout needs to be on lowest level.
2941 OutputParams rp = runparams;
2942 column += Changes::latexMarkChange(os, bparams,
2943 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2945 // Has the language been closed in the latexWriteEndChanges() call above?
2946 langClosed |= running_font.language() != basefont.language()
2947 && running_font.language() != nextfont.language()
2948 && (running_font.language()->encoding()->package() != Encoding::CJK);
2949 running_font = basefont;
2950 open_font &= !langClosed;
2953 // if necessary, close language environment before opening CJK
2954 string const running_lang = running_font.language()->babel();
2955 string const lang_end_command = lyxrc.language_command_end;
2956 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2957 && !running_lang.empty()
2958 && running_lang == openLanguageName()
2959 && current_font.language()->encoding()->package() == Encoding::CJK) {
2960 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2961 os << from_ascii(end_tag);
2962 column += end_tag.length();
2963 if (!languageStackEmpty())
2967 // Switch file encoding if necessary (and allowed)
2968 if ((!fontswitch_inset || closeLanguage)
2969 && !runparams.pass_thru && !style.pass_thru &&
2970 runparams.encoding->package() != Encoding::none &&
2971 current_font.language()->encoding()->package() != Encoding::none) {
2972 pair<bool, int> const enc_switch =
2973 switchEncoding(os.os(), bparams, runparams,
2974 *(current_font.language()->encoding()));
2975 if (enc_switch.first) {
2976 column += enc_switch.second;
2977 runparams.encoding = current_font.language()->encoding();
2981 // A display math inset inside an ulem command will be output
2982 // as a box of width \linewidth, so we have to either disable
2983 // indentation if the inset starts a paragraph, or start a new
2984 // line to accommodate such box. This has to be done before
2985 // writing any font changing commands.
2986 if (runparams.inDisplayMath && !deleted_display_math
2987 && runparams.inulemcmd) {
2988 if (os.afterParbreak())
2994 // Do we need to change font?
2995 if ((current_font != running_font ||
2996 current_font.language() != running_font.language())
2997 && i != body_pos - 1)
2999 if (!fontswitch_inset) {
3000 if (in_ct_deletion) {
3001 // We have to close and then reopen \lyxdeleted,
3002 // as strikeout needs to be on lowest level.
3003 OutputParams rp = runparams;
3004 bool needPar = false;
3005 column += running_font.latexWriteEndChanges(
3006 os, bparams, rp, basefont,
3011 otexstringstream ots;
3012 InsetText const * textinset = inInset().asInsetText();
3013 bool const cprotect = textinset
3014 ? textinset->hasCProtectContent(runparams.moving_arg)
3015 && !textinset->text().isMainText()
3016 && inInset().lyxCode() != BRANCH_CODE
3018 column += current_font.latexWriteStartChanges(ots, bparams,
3019 runparams, basefont, last_font, false,
3021 // Check again for display math in ulem commands as a
3022 // font change may also occur just before a math inset.
3023 if (runparams.inDisplayMath && !deleted_display_math
3024 && runparams.inulemcmd) {
3025 if (os.afterParbreak())
3030 running_font = current_font;
3032 docstring fontchange = ots.str();
3034 // check whether the fontchange ends with a \\textcolor
3035 // modifier and the text starts with a space. If so we
3036 // need to add } in order to prevent \\textcolor from gobbling
3037 // the space (bug 4473).
3038 docstring const last_modifier = rsplit(fontchange, '\\');
3039 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
3040 os << from_ascii("{}");
3041 else if (ots.terminateCommand())
3043 if (in_ct_deletion) {
3044 // We have to close and then reopen \lyxdeleted,
3045 // as strikeout needs to be on lowest level.
3046 OutputParams rp = runparams;
3047 column += Changes::latexMarkChange(os, bparams,
3048 Change(Change::UNCHANGED), change, rp);
3050 } else {// if fontswitch_inset
3051 if (current_font != running_font || !langClosed)
3052 // font is still open in fontswitch_insets if we have
3053 // a non-lang font difference or if the language
3054 // is the only difference but has not been forcedly
3057 running_font = current_font;
3061 // FIXME: think about end_pos implementation...
3062 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
3063 // FIXME: integrate this case in latexSpecialChar
3064 // Do not print the separation of the optional argument
3065 // if style.pass_thru is false. This works because
3066 // latexSpecialChar ignores spaces if
3067 // style.pass_thru is false.
3068 if (i != body_pos - 1) {
3069 if (d->simpleTeXBlanks(bparams, runparams, os,
3070 i, column, current_font, style)) {
3071 // A surrogate pair was output. We
3072 // must not call latexSpecialChar
3073 // in this iteration, since it would output
3074 // the combining character again.
3081 OutputParams rp = runparams;
3082 rp.free_spacing = style.free_spacing;
3083 rp.local_font = ¤t_font;
3084 rp.intitle = style.intitle;
3086 // Two major modes: LaTeX or plain
3087 // Handle here those cases common to both modes
3088 // and then split to handle the two modes separately.
3089 if (c == META_INSET) {
3090 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3091 // Greyedout notes and, in general, all insets
3092 // with InsetLayout::isDisplay() == false,
3093 // are typeset inline with the text. So, we
3094 // can add a \par to the last paragraph of
3095 // such insets only if nothing else follows.
3096 bool incremented = false;
3097 Inset const * inset = getInset(i);
3098 InsetText const * textinset = inset
3099 ? inset->asInsetText()
3101 if (i + 1 == size() && textinset
3102 && !inset->getLayout().isDisplay()) {
3103 ParagraphList const & pars =
3104 textinset->text().paragraphs();
3105 pit_type const pit = pars.size() - 1;
3106 Font const lastfont =
3107 pit < 0 || pars[pit].empty()
3108 ? pars[pit].getLayoutFont(
3111 : pars[pit].getFont(bparams,
3112 pars[pit].size() - 1,
3114 if (lastfont.fontInfo().size() !=
3115 basefont.fontInfo().size()) {
3120 // We need to restore parts of this after insets with
3121 // allowMultiPar() true
3122 Font const save_basefont = basefont;
3123 d->latexInset(bparams, os, rp, running_font,
3124 basefont, real_outerfont, open_font,
3125 runningChange, style, i, column, fontswitch_inset,
3126 closeLanguage, (lang_switched_at_inset || langClosed));
3127 if (fontswitch_inset) {
3129 bool needPar = false;
3130 column += running_font.latexWriteEndChanges(
3131 os, bparams, runparams,
3132 basefont, basefont, needPar);
3135 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3136 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3137 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3142 if (runparams.ctObject == CtObject::DisplayObject
3143 || runparams.ctObject == CtObject::UDisplayObject) {
3144 // Close \lyx*deleted and force its
3145 // reopening (if needed)
3148 runningChange = Change(Change::UNCHANGED);
3149 runparams.ctObject = CtObject::Normal;
3152 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3153 if (!bparams.useNonTeXFonts && !runparams.pass_thru
3154 && !contains(runparams.pass_thru_chars, c))
3155 script = Encodings::isKnownScriptChar(c);
3156 if (script != alien_script) {
3157 if (!alien_script.empty()) {
3159 alien_script.clear();
3161 string fontenc = running_font.language()->fontenc(bparams);
3163 && !Encodings::fontencSupportsScript(fontenc, script)) {
3164 column += script.length() + 2;
3165 os << "\\" << script << "{";
3166 alien_script = script;
3170 d->latexSpecialChar(os, bparams, rp, running_font,
3171 alien_script, style, i, end_pos, column);
3172 } catch (EncodingException & e) {
3173 if (runparams.dryrun) {
3174 os << "<" << _("LyX Warning: ")
3175 << _("uncodable character") << " '";
3179 // add location information and throw again.
3187 // Set the encoding to that returned from latexSpecialChar (see
3188 // comment for encoding member in OutputParams.h)
3189 runparams.encoding = rp.encoding;
3191 // Also carry on the info on a closed ulem command for insets
3192 // such as Note that do not produce any output, so that no
3193 // command is ever executed but its opening was recorded.
3194 runparams.inulemcmd = rp.inulemcmd;
3196 // These need to be passed upstream as well
3197 runparams.need_maketitle = rp.need_maketitle;
3198 runparams.have_maketitle = rp.have_maketitle;
3200 // And finally, pass the post_macros upstream
3201 runparams.post_macro = rp.post_macro;
3204 // Close wrapper for alien script
3205 if (!alien_script.empty()) {
3207 alien_script.clear();
3210 Font const font = empty()
3211 ? getLayoutFont(bparams, real_outerfont)
3212 : getFont(bparams, size() - 1, real_outerfont);
3214 InsetText const * textinset = inInset().asInsetText();
3216 bool const maintext = textinset
3217 ? textinset->text().isMainText()
3220 size_t const numpars = textinset
3221 ? textinset->text().paragraphs().size()
3224 bool needPar = false;
3226 if (style.resfont.size() != font.fontInfo().size()
3227 && (!runparams.isLastPar || maintext
3228 || (numpars > 1 && d->ownerCode() != CELL_CODE
3229 && (inInset().getLayout().isDisplay()
3231 && !style.isCommand()) {
3235 // If we have an open font definition, we have to close it
3237 // Make sure that \\par is done with the font of the last
3238 // character if this has another size as the default.
3239 // This is necessary because LaTeX (and LyX on the screen)
3240 // calculates the space between the baselines according
3241 // to this font. (Matthias)
3243 // We must not change the font for the last paragraph
3244 // of non-multipar insets, tabular cells or commands,
3245 // since this produces unwanted whitespace.
3246 #ifdef FIXED_LANGUAGE_END_DETECTION
3248 running_font.latexWriteEndChanges(os, bparams,
3249 runparams, basefont,
3250 next_->getFont(bparams, 0, outerfont),
3253 running_font.latexWriteEndChanges(os, bparams,
3254 runparams, basefont, basefont, needPar);
3257 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3258 //FIXME: there as we start another \selectlanguage with the next paragraph if
3259 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3260 running_font.latexWriteEndChanges(os, bparams, runparams,
3261 basefont, basefont, needPar);
3265 // The \par could not be inserted at the same nesting
3266 // level of the font size change, so do it now.
3267 os << "{\\" << font.latexSize() << "\\par}";
3270 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3271 column += Changes::latexMarkChange(os, bparams, runningChange,
3272 Change(Change::UNCHANGED), runparams);
3274 // Needed if there is an optional argument but no contents.
3275 if (body_pos > 0 && body_pos == size()) {
3279 if (!style.rightdelim().empty()) {
3280 os << style.rightdelim();
3281 column += style.rightdelim().size();
3284 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3285 && runparams.encoding != prev_encoding) {
3286 runparams.encoding = prev_encoding;
3287 os << setEncoding(prev_encoding->iconvName());
3290 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3294 bool Paragraph::emptyTag() const
3296 for (pos_type i = 0; i < size(); ++i) {
3297 if (Inset const * inset = getInset(i)) {
3298 InsetCode lyx_code = inset->lyxCode();
3299 // FIXME testing like that is wrong. What is
3301 if (lyx_code != TOC_CODE &&
3302 lyx_code != INCLUDE_CODE &&
3303 lyx_code != GRAPHICS_CODE &&
3304 lyx_code != ERT_CODE &&
3305 lyx_code != LISTINGS_CODE &&
3306 lyx_code != FLOAT_CODE &&
3307 lyx_code != TABULAR_CODE) {
3311 char_type c = d->text_[i];
3312 if (c != ' ' && c != '\t')
3320 string Paragraph::getID(Buffer const &, OutputParams const &)
3323 for (pos_type i = 0; i < size(); ++i) {
3324 if (Inset const * inset = getInset(i)) {
3325 InsetCode lyx_code = inset->lyxCode();
3326 if (lyx_code == LABEL_CODE) {
3327 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3328 docstring const & id = il->getParam("name");
3329 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3337 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3340 for (i = 0; i < size(); ++i) {
3341 if (Inset const * inset = getInset(i)) {
3342 inset->docbook(xs, runparams);
3344 char_type c = d->text_[i];
3354 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3358 for (i = 0; i < size(); ++i) {
3359 if (Inset const * inset = getInset(i)) {
3360 inset->xhtml(xs, runparams);
3362 char_type c = d->text_[i];
3372 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3375 pos_type size = text_.size();
3376 for (pos_type i = initial; i < size; ++i) {
3377 Font font = owner_->getFont(buf.params(), i, outerfont);
3378 if (text_[i] == META_INSET)
3380 if (i != initial && font != font_old)
3391 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3392 vector<xml::EndFontTag> & tagsToClose,
3393 bool & flag, FontState curstate, xml::FontTypes type)
3395 if (curstate == FONT_ON) {
3396 tagsToOpen.push_back(docbookStartFontTag(type));
3399 tagsToClose.push_back(docbookEndFontTag(type));
3404 class OptionalFontType {
3409 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3410 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3413 OptionalFontType fontShapeToXml(FontShape fs)
3417 return {xml::FT_ITALIC};
3419 return {xml::FT_SLANTED};
3420 case SMALLCAPS_SHAPE:
3421 return {xml::FT_SMALLCAPS};
3426 // the other tags are for internal use
3432 OptionalFontType fontFamilyToXml(FontFamily fm)
3436 return {xml::FT_ROMAN};
3438 return {xml::FT_SANS};
3439 case TYPEWRITER_FAMILY:
3440 return {xml::FT_TYPE};
3441 case INHERIT_FAMILY:
3444 // the other tags are for internal use
3450 OptionalFontType fontSizeToXml(FontSize fs)
3454 return {xml::FT_SIZE_TINY};
3456 return {xml::FT_SIZE_SCRIPT};
3458 return {xml::FT_SIZE_FOOTNOTE};
3460 return {xml::FT_SIZE_SMALL};
3462 return {xml::FT_SIZE_LARGE};
3464 return {xml::FT_SIZE_LARGER};
3466 return {xml::FT_SIZE_LARGEST};
3468 return {xml::FT_SIZE_HUGE};
3470 return {xml::FT_SIZE_HUGER};
3472 return {xml::FT_SIZE_INCREASE};
3474 return {xml::FT_SIZE_DECREASE};
3479 // the other tags are for internal use
3485 struct DocBookFontState
3487 FontShape curr_fs = INHERIT_SHAPE;
3488 FontFamily curr_fam = INHERIT_FAMILY;
3489 FontSize curr_size = INHERIT_SIZE;
3491 // track whether we have opened these tags
3492 bool emph_flag = false;
3493 bool bold_flag = false;
3494 bool noun_flag = false;
3495 bool ubar_flag = false;
3496 bool dbar_flag = false;
3497 bool sout_flag = false;
3498 bool xout_flag = false;
3499 bool wave_flag = false;
3501 bool shap_flag = false;
3503 bool faml_flag = false;
3505 bool size_flag = false;
3508 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3510 std::string const & default_family,
3511 DocBookFontState & fs)
3513 vector<xml::FontTag> tagsToOpen;
3514 vector<xml::EndFontTag> tagsToClose;
3517 FontState curstate = font.fontInfo().emph();
3518 if (font_old.emph() != curstate)
3519 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3522 curstate = font.fontInfo().noun();
3523 if (font_old.noun() != curstate)
3524 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3527 curstate = font.fontInfo().underbar();
3528 if (font_old.underbar() != curstate)
3529 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3532 curstate = font.fontInfo().strikeout();
3533 if (font_old.strikeout() != curstate)
3534 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3537 curstate = font.fontInfo().xout();
3538 if (font_old.xout() != curstate)
3539 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3542 curstate = font.fontInfo().uuline();
3543 if (font_old.uuline() != curstate)
3544 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3547 curstate = font.fontInfo().uwave();
3548 if (font_old.uwave() != curstate)
3549 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3552 // a little hackish, but allows us to reuse what we have.
3553 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3554 if (font_old.series() != font.fontInfo().series())
3555 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3558 fs.curr_fs = font.fontInfo().shape();
3559 FontShape old_fs = font_old.shape();
3560 if (old_fs != fs.curr_fs) {
3562 OptionalFontType tag = fontShapeToXml(old_fs);
3564 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3565 fs.shap_flag = false;
3568 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3570 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3574 fs.curr_fam = font.fontInfo().family();
3575 FontFamily old_fam = font_old.family();
3576 if (old_fam != fs.curr_fam) {
3578 OptionalFontType tag = fontFamilyToXml(old_fam);
3580 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3581 fs.faml_flag = false;
3583 switch (fs.curr_fam) {
3585 // we will treat a "default" font family as roman, since we have
3586 // no other idea what to do.
3587 if (default_family != "rmdefault" && default_family != "default") {
3588 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3589 fs.faml_flag = true;
3593 if (default_family != "sfdefault") {
3594 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3595 fs.faml_flag = true;
3598 case TYPEWRITER_FAMILY:
3599 if (default_family != "ttdefault") {
3600 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3601 fs.faml_flag = true;
3604 case INHERIT_FAMILY:
3607 // the other tags are for internal use
3614 fs.curr_size = font.fontInfo().size();
3615 FontSize old_size = font_old.size();
3616 if (old_size != fs.curr_size) {
3618 OptionalFontType tag = fontSizeToXml(old_size);
3620 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3621 fs.size_flag = false;
3624 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3625 if (tag.has_value) {
3626 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3627 fs.size_flag = true;
3631 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3634 } // anonymous namespace
3637 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3638 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3639 OutputParams const & runparams,
3640 Font const & outerfont,
3643 bool ignore_fonts) const
3645 // Return values: segregation of the content of this paragraph.
3646 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3647 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3648 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3650 // Internal string stream to store the output before being added to one of the previous lists.
3651 odocstringstream os;
3653 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3654 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3656 OutputParams rp = runparams;
3657 for (pos_type i = initial; i < size(); ++i) {
3658 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3659 const InsetArgument * arg = getInset(i)->asInsetArgument();
3660 if (arg->docbookargumentbeforemaintag()) {
3661 auto xs_local = XMLStream(os);
3662 arg->docbook(xs_local, rp);
3664 prependedParagraphs.push_back(os.str());
3665 os.str(from_ascii(""));
3667 rp.docbook_prepended_arguments.insert(arg);
3668 } else if (arg->docbookargumentaftermaintag()) {
3669 rp.docbook_appended_arguments.insert(arg);
3675 // State variables for the main loop.
3676 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3677 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3678 xs->startDivision(false);
3679 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3680 // This requires to store delayed characters at some point.
3682 // Track whether we have opened font tags
3683 DocBookFontState fs;
3684 DocBookFontState old_fs = fs;
3686 Layout const & style = *d->layout_;
3688 // Conversion of the font opening/closing into DocBook tags.
3689 vector<xml::FontTag> tagsToOpen;
3690 vector<xml::EndFontTag> tagsToClose;
3692 // Parsing main loop.
3693 for (pos_type i = initial; i < size(); ++i) {
3694 bool ignore_fonts_i = ignore_fonts
3695 || style.docbooknofontinside()
3696 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3698 // Don't show deleted material in the output.
3702 // If this is an InsetNewline, generate a new paragraph (this is the reason why generatedParagraphs is a list
3703 // of paragraphs). Also reset the fonts, so that tags are closed in this paragraph.
3704 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3705 if (!ignore_fonts_i)
3706 xs->closeFontTags();
3708 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3709 generatedParagraphs.push_back(os.str());
3713 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3714 // that the string stream must be reset.
3715 os.str(from_ascii(""));
3717 xs = new XMLStream(os);
3718 xs->startDivision(false);
3720 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3721 if (!ignore_fonts_i) {
3726 // Determine which tags should be opened or closed regarding fonts. Consider the last output character (i.e. not
3728 int last_output_char = (i == 0) ? 0 : i - 1;
3730 while (last_output_char > 0 && isDeleted(last_output_char))
3733 FontInfo const font_old = (i == 0 ?
3734 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3735 getFont(buf.masterBuffer()->params(), last_output_char, outerfont).fontInfo());
3736 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3737 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3738 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3740 if (!ignore_fonts_i) {
3741 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3742 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3743 for (; cit != cen; ++cit)
3747 // Deal with the delayed characters *after* closing font tags.
3748 if (!delayedChars.empty()) {
3749 for (const docstring& c: delayedChars)
3750 *xs << XMLStream::ESCAPE_NONE << c;
3751 delayedChars.clear();
3754 if (!ignore_fonts_i) {
3755 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3756 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3757 for (; sit != sen; ++sit)
3761 // The font tags are no longer useful; free their memory right now.
3762 tagsToClose.clear();
3765 // Finally, write the next character or inset.
3766 if (Inset const * inset = getInset(i)) {
3767 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3768 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3769 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3771 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3772 // Arguments may need to be output
3773 OutputParams np = rp;
3774 np.local_font = &font;
3776 // TODO: special case will bite here.
3777 np.docbook_in_par = true;
3778 inset->docbook(*xs, np);
3781 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3782 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3783 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3784 delayedChars.push_back(from_ascii(" "));
3786 delayedChars.emplace_back(1, c);
3788 } else { // No need to delay the character.
3789 if (c == '\'' && !ignore_fonts)
3790 *xs << XMLStream::ESCAPE_NONE << "’";
3797 // Ensure that the tags are closed at the right place. Otherwise, there might be an open font tag with no content
3798 // that no other code cares to close.
3799 *xs << xml::NullTag();
3801 // FIXME, this code is just imported from XHTML
3802 // I'm worried about what happens if a branch, say, is itself
3803 // wrapped in some font stuff. I think that will not work.
3805 xs->closeFontTags();
3807 // Close the potentially remaining tags, like pending font tags.
3808 // There is no need to check for ignore_fonts, as these tags won't be
3809 // inserted in the stack in the first place if ignore_fonts is false.
3812 // Deal with the delayed characters *after* closing font tags.
3813 if (!delayedChars.empty()) {
3814 for (const docstring &c: delayedChars)
3815 *xs << XMLStream::ESCAPE_NONE << c;
3816 delayedChars.clear();
3819 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3820 // last line to get a clean output.
3821 if (rp.docbook_in_listing && !is_last_par)
3824 // Finalise the last (and most likely only) paragraph.
3825 generatedParagraphs.push_back(os.str());
3826 os.str(from_ascii(""));
3829 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3830 for (pos_type i = initial; i < size(); ++i) {
3831 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3832 const InsetArgument * arg = getInset(i)->asInsetArgument();
3833 if (arg->docbookargumentaftermaintag()) {
3834 // Don't use rp, as this argument would not generate anything.
3835 auto xs_local = XMLStream(os);
3836 arg->docbook(xs_local, runparams);
3838 appendedParagraphs.push_back(os.str());
3839 os.str(from_ascii(""));
3844 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3850 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3851 vector<xml::EndFontTag> & tagsToClose,
3852 bool & flag, FontState curstate, xml::FontTypes type)
3854 if (curstate == FONT_ON) {
3855 tagsToOpen.push_back(xhtmlStartFontTag(type));
3858 tagsToClose.push_back(xhtmlEndFontTag(type));
3863 } // anonymous namespace
3866 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3868 OutputParams const & runparams,
3869 Font const & outerfont,
3870 bool start_paragraph, bool close_paragraph,
3871 pos_type initial) const
3875 // track whether we have opened these tags
3876 bool emph_flag = false;
3877 bool bold_flag = false;
3878 bool noun_flag = false;
3879 bool ubar_flag = false;
3880 bool dbar_flag = false;
3881 bool sout_flag = false;
3882 bool xout_flag = false;
3883 bool wave_flag = false;
3885 bool shap_flag = false;
3887 bool faml_flag = false;
3889 bool size_flag = false;
3891 Layout const & style = *d->layout_;
3893 if (start_paragraph)
3894 xs.startDivision(allowEmpty());
3897 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3899 FontShape curr_fs = INHERIT_SHAPE;
3900 FontFamily curr_fam = INHERIT_FAMILY;
3901 FontSize curr_size = INHERIT_SIZE;
3903 string const default_family =
3904 buf.masterBuffer()->params().fonts_default_family;
3906 vector<xml::FontTag> tagsToOpen;
3907 vector<xml::EndFontTag> tagsToClose;
3909 // parsing main loop
3910 for (pos_type i = initial; i < size(); ++i) {
3911 // let's not show deleted material in the output
3915 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3918 FontState curstate = font.fontInfo().emph();
3919 if (font_old.emph() != curstate)
3920 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3923 curstate = font.fontInfo().noun();
3924 if (font_old.noun() != curstate)
3925 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3928 curstate = font.fontInfo().underbar();
3929 if (font_old.underbar() != curstate)
3930 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3933 curstate = font.fontInfo().strikeout();
3934 if (font_old.strikeout() != curstate)
3935 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3938 curstate = font.fontInfo().xout();
3939 if (font_old.xout() != curstate)
3940 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3943 curstate = font.fontInfo().uuline();
3944 if (font_old.uuline() != curstate)
3945 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3948 curstate = font.fontInfo().uwave();
3949 if (font_old.uwave() != curstate)
3950 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3953 // a little hackish, but allows us to reuse what we have.
3954 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3955 if (font_old.series() != font.fontInfo().series())
3956 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3959 curr_fs = font.fontInfo().shape();
3960 FontShape old_fs = font_old.shape();
3961 if (old_fs != curr_fs) {
3965 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3968 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3970 case SMALLCAPS_SHAPE:
3971 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3977 // the other tags are for internal use
3985 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3989 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3992 case SMALLCAPS_SHAPE:
3993 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
4000 // the other tags are for internal use
4007 curr_fam = font.fontInfo().family();
4008 FontFamily old_fam = font_old.family();
4009 if (old_fam != curr_fam) {
4013 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
4016 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
4018 case TYPEWRITER_FAMILY:
4019 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
4021 case INHERIT_FAMILY:
4024 // the other tags are for internal use
4032 // we will treat a "default" font family as roman, since we have
4033 // no other idea what to do.
4034 if (default_family != "rmdefault" && default_family != "default") {
4035 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
4040 if (default_family != "sfdefault") {
4041 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
4045 case TYPEWRITER_FAMILY:
4046 if (default_family != "ttdefault") {
4047 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
4051 case INHERIT_FAMILY:
4054 // the other tags are for internal use
4061 curr_size = font.fontInfo().size();
4062 FontSize old_size = font_old.size();
4063 if (old_size != curr_size) {
4067 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
4070 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
4073 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
4076 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
4079 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
4082 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
4085 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
4088 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
4091 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
4094 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
4097 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
4103 // the other tags are for internal use
4109 switch (curr_size) {
4111 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4115 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4119 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4123 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4127 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4131 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4135 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4139 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4143 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4147 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4151 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4158 // the other tags are for internal use
4165 // Other such tags? What about the other text ranges?
4167 for (auto const & t : tagsToClose)
4169 for (auto const & t : tagsToOpen)
4171 tagsToClose.clear();
4174 Inset const * inset = getInset(i);
4176 if (!runparams.for_toc || inset->isInToc()) {
4177 OutputParams np = runparams;
4178 np.local_font = &font;
4179 // If the paragraph has size 1, then we are in the "special
4180 // case" where we do not output the containing paragraph info
4181 if (!inset->getLayout().htmlisblock() && size() != 1)
4182 np.html_in_par = true;
4183 retval += inset->xhtml(xs, np);
4186 char_type c = getUChar(buf.masterBuffer()->params(),
4188 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4189 xs << XMLStream::ESCAPE_NONE << " ";
4191 xs << XMLStream::ESCAPE_NONE << "’";
4195 font_old = font.fontInfo();
4199 // I'm worried about what happens if a branch, say, is itself
4200 // wrapped in some font stuff. I think that will not work.
4202 if (close_paragraph)
4209 bool Paragraph::isHfill(pos_type pos) const
4211 Inset const * inset = getInset(pos);
4212 return inset && inset->isHfill();
4216 bool Paragraph::isNewline(pos_type pos) const
4218 // U+2028 LINE SEPARATOR
4219 // U+2029 PARAGRAPH SEPARATOR
4220 char_type const c = d->text_[pos];
4221 if (c == 0x2028 || c == 0x2029)
4223 Inset const * inset = getInset(pos);
4224 return inset && inset->lyxCode() == NEWLINE_CODE;
4228 bool Paragraph::isEnvSeparator(pos_type pos) const
4230 Inset const * inset = getInset(pos);
4231 return inset && inset->lyxCode() == SEPARATOR_CODE;
4235 bool Paragraph::isLineSeparator(pos_type pos) const
4237 char_type const c = d->text_[pos];
4238 if (isLineSeparatorChar(c))
4240 Inset const * inset = getInset(pos);
4241 return inset && inset->isLineSeparator();
4245 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4249 if (ignore_deleted && isDeleted(pos))
4251 if (Inset const * inset = getInset(pos))
4252 return !inset->isLetter();
4253 // if we have a hard hyphen (no en- or emdash) or apostrophe
4254 // we pass this to the spell checker
4255 // FIXME: this method is subject to change, visit
4256 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4257 // to get an impression how complex this is.
4258 if (isHardHyphenOrApostrophe(pos))
4260 char_type const c = d->text_[pos];
4261 // We want to pass the escape chars to the spellchecker
4262 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4263 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4267 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4269 pos_type const psize = size();
4272 char_type const c = d->text_[pos];
4273 if (c != '-' && c != '\'')
4275 pos_type nextpos = pos + 1;
4276 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4277 if ((nextpos == psize || isSpace(nextpos))
4278 && (pos == 0 || isSpace(prevpos)))
4284 bool Paragraph::needsCProtection(bool const fragile) const
4286 // first check the layout of the paragraph, but only in insets
4287 // and not in tables
4288 InsetText const * textinset = inInset().asInsetText();
4289 bool const maintext = textinset
4290 ? textinset->text().isMainText() || inInset().lyxCode() == CELL_CODE
4293 if (!maintext && layout().needcprotect) {
4294 // Environments need cprotection regardless the content
4295 if (layout().latextype == LATEX_ENVIRONMENT)
4298 // Commands need cprotection if they contain specific chars
4299 int const nchars_escape = 9;
4300 static char_type const chars_escape[nchars_escape] = {
4301 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4303 docstring const pars = asString();
4304 for (int k = 0; k < nchars_escape; k++) {
4305 if (contains(pars, chars_escape[k]))
4310 // now check whether we have insets that need cprotection
4311 for (auto const & icit : d->insetlist_) {
4312 Inset const * ins = icit.inset;
4315 if (ins->needsCProtection(maintext, fragile))
4323 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4325 return d->speller_state_.getRange(pos);
4329 bool Paragraph::isChar(pos_type pos) const
4331 if (Inset const * inset = getInset(pos))
4332 return inset->isChar();
4333 char_type const c = d->text_[pos];
4334 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4338 bool Paragraph::isSpace(pos_type pos) const
4340 if (Inset const * inset = getInset(pos))
4341 return inset->isSpace();
4342 char_type const c = d->text_[pos];
4343 return lyx::isSpace(c);
4348 Paragraph::getParLanguage(BufferParams const & bparams) const
4351 return getFirstFontSettings(bparams).language();
4352 // FIXME: we should check the prev par as well (Lgb)
4353 return bparams.language;
4357 bool Paragraph::isRTL(BufferParams const & bparams) const
4359 return getParLanguage(bparams)->rightToLeft()
4360 && !inInset().getLayout().forceLTR();
4364 void Paragraph::changeLanguage(BufferParams const & bparams,
4365 Language const * from, Language const * to)
4367 // change language including dummy font change at the end
4368 for (pos_type i = 0; i <= size(); ++i) {
4369 Font font = getFontSettings(bparams, i);
4370 if (font.language() == from) {
4371 font.setLanguage(to);
4373 d->requestSpellCheck(i);
4379 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4381 Language const * doc_language = bparams.language;
4382 for (auto const & f : d->fontlist_)
4383 if (f.font().language() != ignore_language &&
4384 f.font().language() != latex_language &&
4385 f.font().language() != doc_language)
4391 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4393 for (auto const & f : d->fontlist_) {
4394 Language const * lang = f.font().language();
4395 if (lang != ignore_language &&
4396 lang != latex_language)
4402 docstring Paragraph::asString(int options) const
4404 return asString(0, size(), options);
4408 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4410 odocstringstream os;
4413 && options & AS_STR_LABEL
4414 && d->layout_->labeltype != LABEL_MANUAL
4415 && !d->params_.labelString().empty())
4416 os << d->params_.labelString() << ' ';
4418 for (pos_type i = beg; i < end; ++i) {
4419 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4421 char_type const c = d->text_[i];
4422 if (isPrintable(c) || c == '\t'
4423 || (c == '\n' && (options & AS_STR_NEWLINES)))
4425 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4426 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4427 LASSERT(runparams != nullptr, return docstring());
4428 if (runparams->find_effective() && getInset(i)->findUsesToString())
4429 getInset(i)->toString(os);
4431 getInset(i)->plaintext(os, *runparams);
4432 } else if (c == META_INSET && (options & AS_STR_MATHED)
4433 && getInset(i)->lyxCode() == REF_CODE) {
4434 Buffer const & buf = getInset(i)->buffer();
4435 OutputParams rp(&buf.params().encoding());
4436 Font const font(inherit_font, buf.params().language);
4437 rp.local_font = &font;
4439 getInset(i)->latex(ots, rp);
4441 getInset(i)->toString(os);
4450 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4451 bool const shorten, bool const label) const
4453 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4454 if (label && !labelString().empty())
4455 os += labelString() + ' ';
4456 if (!layout().isTocCaption())
4458 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4461 char_type const c = d->text_[i];
4464 else if (c == META_INSET)
4465 getInset(i)->forOutliner(os, tmplen, false);
4468 Text::shortenForOutliner(os, maxlen);
4472 void Paragraph::setInsetOwner(Inset const * inset)
4474 d->inset_owner_ = inset;
4478 int Paragraph::id() const
4484 void Paragraph::setId(int id)
4490 Layout const & Paragraph::layout() const
4496 void Paragraph::setLayout(Layout const & layout)
4498 d->layout_ = &layout;
4502 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4504 setLayout(tc.defaultLayout());
4508 void Paragraph::setPlainLayout(DocumentClass const & tc)
4510 setLayout(tc.plainLayout());
4514 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4516 if (usePlainLayout())
4519 setDefaultLayout(tc);
4523 Inset const & Paragraph::inInset() const
4525 LBUFERR(d->inset_owner_);
4526 return *d->inset_owner_;
4530 ParagraphParameters & Paragraph::params()
4536 ParagraphParameters const & Paragraph::params() const
4542 bool Paragraph::isFreeSpacing() const
4544 if (d->layout_->free_spacing)
4546 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4550 bool Paragraph::allowEmpty() const
4552 if (d->layout_->keepempty)
4554 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4558 int Paragraph::getInsetPos(InsetCode const code, int startpos,
4559 bool ignore_deleted) const
4561 while (startpos != -1) {
4562 int found_pos = d->insetlist_.find(code, startpos);
4563 if (found_pos == -1)
4566 if (isDeleted(found_pos) && ignore_deleted) {
4567 // we're not interested in deleted insets
4568 if (found_pos + 1 == size())
4570 startpos = found_pos + 1;
4579 bool Paragraph::brokenBiblio() const
4581 // There is a problem if there is no bibitem at position 0 in
4582 // paragraphs that need one, if there is another bibitem in the
4583 // paragraph or if this paragraph is not supposed to have
4584 // a bibitem inset at all.
4585 return ((d->layout_->labeltype == LABEL_BIBLIO
4586 && (getInsetPos(BIBITEM_CODE, 0, true) != 0
4587 || getInsetPos(BIBITEM_CODE, 1, true) > 0))
4588 || (d->layout_->labeltype != LABEL_BIBLIO
4589 && getInsetPos(BIBITEM_CODE, 0, true) != -1));
4593 int Paragraph::fixBiblio(Buffer const & buffer)
4595 // FIXME: when there was already an inset at 0, the return value is 1,
4596 // which does not tell whether another inset has been removed; the
4597 // cursor cannot be correctly updated.
4599 bool const track_changes = buffer.params().track_changes;
4600 int bibitem_pos = getInsetPos(BIBITEM_CODE, 0, true);
4602 // The case where paragraph is not BIBLIO
4603 if (d->layout_->labeltype != LABEL_BIBLIO) {
4604 if (bibitem_pos == -1)
4605 // No InsetBibitem => OK
4607 // There is an InsetBibitem: remove it!
4608 d->insetlist_.release(bibitem_pos);
4609 eraseChar(bibitem_pos, track_changes);
4610 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4613 bool const hasbibitem0 = bibitem_pos == 0;
4615 bibitem_pos = getInsetPos(BIBITEM_CODE, 0, true);
4616 // There was an InsetBibitem at pos 0,
4617 // and no other one => OK
4618 if (bibitem_pos == -1)
4620 // there is a bibitem at the 0 position, but since
4621 // there is a second one, we copy the second on the
4622 // first. We're assuming there are at most two of
4623 // these, which there should be.
4624 // FIXME: why does it make sense to do that rather
4625 // than keep the first? (JMarc)
4626 Inset * inset = releaseInset(bibitem_pos);
4627 d->insetlist_.begin()->inset = inset;
4628 // This needs to be done to update the counter (#8499)
4629 buffer.updateBuffer();
4630 return -bibitem_pos;
4633 // We need to create an inset at the beginning
4634 Inset * inset = nullptr;
4635 if (bibitem_pos > 0) {
4636 // There was one somewhere in the paragraph, let's move it
4637 // * With change tracking, we use a clone
4638 // and leave the old inset at its position
4640 // * Without change tracking, we release the inset
4641 // from its previous InsetList position
4642 inset = track_changes
4643 ? new InsetBibitem(const_cast<Buffer *>(&buffer),
4644 getInset(bibitem_pos)->asInsetCommand()->params())
4645 : d->insetlist_.release(bibitem_pos);
4646 eraseChar(bibitem_pos, track_changes);
4648 // No inset found -- make a fresh one
4649 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4650 InsetCommandParams(BIBITEM_CODE));
4652 Font font(inherit_font, buffer.params().language);
4653 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4654 : Change::UNCHANGED));
4656 // This is needed to get the counters right
4657 buffer.updateBuffer();
4662 void Paragraph::checkAuthors(AuthorList const & authorList)
4664 d->changes_.checkAuthors(authorList);
4668 bool Paragraph::isChanged(pos_type pos) const
4670 return lookupChange(pos).changed();
4674 bool Paragraph::isInserted(pos_type pos) const
4676 return lookupChange(pos).inserted();
4680 bool Paragraph::isDeleted(pos_type pos) const
4682 return lookupChange(pos).deleted();
4686 InsetList const & Paragraph::insetList() const
4688 return d->insetlist_;
4692 void Paragraph::setInsetBuffers(Buffer & b)
4694 d->insetlist_.setBuffer(b);
4698 void Paragraph::resetBuffer()
4700 d->insetlist_.resetBuffer();
4704 Inset * Paragraph::releaseInset(pos_type pos)
4706 Inset * inset = d->insetlist_.release(pos);
4707 /// does not honour change tracking!
4708 eraseChar(pos, false);
4713 Inset * Paragraph::getInset(pos_type pos)
4715 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4716 ? d->insetlist_.get(pos) : nullptr;
4720 Inset const * Paragraph::getInset(pos_type pos) const
4722 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4723 ? d->insetlist_.get(pos) : nullptr;
4727 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4728 pos_type & right, TextCase action)
4730 // process sequences of modified characters; in change
4731 // tracking mode, this approach results in much better
4732 // usability than changing case on a char-by-char basis
4733 // We also need to track the current font, since font
4734 // changes within sequences can occur.
4735 vector<pair<char_type, Font> > changes;
4737 bool const trackChanges = bparams.track_changes;
4739 bool capitalize = true;
4741 for (; pos < right; ++pos) {
4742 char_type oldChar = d->text_[pos];
4743 char_type newChar = oldChar;
4745 // ignore insets and don't play with deleted text!
4746 if (oldChar != META_INSET && !isDeleted(pos)) {
4748 case text_lowercase:
4749 newChar = lowercase(oldChar);
4751 case text_capitalization:
4753 newChar = uppercase(oldChar);
4757 case text_uppercase:
4758 newChar = uppercase(oldChar);
4763 if (isWordSeparator(pos) || isDeleted(pos)) {
4764 // permit capitalization again
4768 if (oldChar != newChar) {
4769 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4770 if (pos != right - 1)
4772 // step behind the changing area
4776 int erasePos = pos - changes.size();
4777 for (auto const & change : changes) {
4778 insertChar(pos, change.first, change.second, trackChanges);
4779 if (!eraseChar(erasePos, trackChanges)) {
4782 ++right; // expand selection
4789 int Paragraph::find(docstring const & str, bool cs, bool mw,
4790 pos_type start_pos, bool del) const
4792 pos_type pos = start_pos;
4793 int const strsize = str.length();
4795 pos_type const parsize = d->text_.size();
4796 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4797 // ignore deleted matter
4798 if (!del && isDeleted(pos)) {
4799 if (pos == parsize - 1)
4805 // Ignore "invisible" letters such as ligature breaks
4806 // and hyphenation chars while searching
4807 bool nonmatch = false;
4808 while (pos < parsize && isInset(pos)) {
4809 Inset const * inset = getInset(pos);
4810 if (!inset->isLetter() && !inset->isChar())
4812 odocstringstream os;
4813 if (inset->lyxCode() == lyx::QUOTE_CODE || inset->lyxCode() == lyx::SPACE_CODE) {
4815 op.find_set_feature(OutputParams::SearchQuick);
4816 inset->plaintext(os, op);
4819 inset->toString(os);
4821 docstring const insetstring = os.str();
4822 if (!insetstring.empty()) {
4823 int const insetstringsize = insetstring.length();
4824 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4825 if ((cs && str[i] != insetstring[j])
4826 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4834 if (nonmatch || i == strsize)
4836 char_type dp = d->text_[pos];
4837 if (cs && str[i] != dp)
4839 if (!cs && uppercase(str[i]) != uppercase(dp))
4846 // if necessary, check whether string matches word
4848 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4851 && !isWordSeparator(pos))
4855 return pos - start_pos;
4859 char_type Paragraph::getChar(pos_type pos) const
4861 return d->text_[pos];
4865 pos_type Paragraph::size() const
4867 return d->text_.size();
4871 bool Paragraph::empty() const
4873 return d->text_.empty();
4877 bool Paragraph::isInset(pos_type pos) const
4879 return d->text_[pos] == META_INSET;
4883 bool Paragraph::isSeparator(pos_type pos) const
4885 //FIXME: Are we sure this can be the only separator?
4886 return d->text_[pos] == ' ';
4890 void Paragraph::deregisterWords()
4892 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4893 Private::LangWordsMap::const_iterator ite = d->words_.end();
4894 for (; itl != ite; ++itl) {
4895 WordList & wl = theWordList(itl->first);
4896 Private::Words::const_iterator it = (itl->second).begin();
4897 Private::Words::const_iterator et = (itl->second).end();
4898 for (; it != et; ++it)
4905 void Paragraph::locateWord(pos_type & from, pos_type & to,
4906 word_location const loc, bool const ignore_deleted) const
4909 case WHOLE_WORD_STRICT:
4910 if (from == 0 || from == size()
4911 || isWordSeparator(from, ignore_deleted)
4912 || isWordSeparator(from - 1, ignore_deleted)) {
4919 // If we are already at the beginning of a word, do nothing
4920 if (!from || isWordSeparator(from - 1, ignore_deleted))
4925 // always move the cursor to the beginning of previous word
4926 while (from && !isWordSeparator(from - 1, ignore_deleted))
4930 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4933 // no need to move the 'from' cursor
4937 while (to < size() && !isWordSeparator(to, ignore_deleted))
4942 void Paragraph::collectWords()
4944 for (pos_type pos = 0; pos < size(); ++pos) {
4945 if (isWordSeparator(pos))
4947 pos_type from = pos;
4948 locateWord(from, pos, WHOLE_WORD);
4949 // Work around MSVC warning: The statement
4950 // if (pos < from + lyxrc.completion_minlength)
4951 // triggers a signed vs. unsigned warning.
4952 // I don't know why this happens, it could be a MSVC bug, or
4953 // related to LLP64 (windows) vs. LP64 (unix) programming
4954 // model, or the C++ standard might be ambigous in the section
4955 // defining the "usual arithmetic conversions". However, using
4956 // a temporary variable is safe and works on all compilers.
4957 pos_type const endpos = from + lyxrc.completion_minlength;
4960 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4961 if (cit == d->fontlist_.end())
4963 Language const * lang = cit->font().language();
4964 docstring const word = asString(from, pos, AS_STR_NONE);
4965 d->words_[lang->lang()].insert(word);
4970 void Paragraph::registerWords()
4972 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4973 Private::LangWordsMap::const_iterator ite = d->words_.end();
4974 for (; itl != ite; ++itl) {
4975 WordList & wl = theWordList(itl->first);
4976 Private::Words::const_iterator it = (itl->second).begin();
4977 Private::Words::const_iterator et = (itl->second).end();
4978 for (; it != et; ++it)
4984 void Paragraph::updateWords()
4992 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4994 SkipPositionsIterator begin = skips.begin();
4995 SkipPositions::iterator end = skips.end();
4996 if (pos > 0 && begin < end) {
4998 if (end->last == pos - 1) {
5003 skips.insert(end, FontSpan(pos, pos));
5007 Language * Paragraph::Private::locateSpellRange(
5008 pos_type & from, pos_type & to,
5009 SkipPositions & skips) const
5011 // skip leading white space
5012 while (from < to && owner_->isWordSeparator(from))
5014 // don't check empty range
5017 // get current language
5018 Language * lang = getSpellLanguage(from);
5019 pos_type last = from;
5020 bool samelang = true;
5021 bool sameinset = true;
5022 while (last < to && samelang && sameinset) {
5023 // hop to end of word
5024 while (last < to && !owner_->isWordSeparator(last)) {
5025 Inset const * inset = owner_->getInset(last);
5026 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
5027 // check for "invisible" letters such as ligature breaks
5028 odocstringstream os;
5029 inset->toString(os);
5030 if (os.str().length() != 0) {
5031 // avoid spell check of visible special char insets
5032 // stop the loop in front of the special char inset
5037 appendSkipPosition(skips, last);
5038 } else if (owner_->isDeleted(last)) {
5039 appendSkipPosition(skips, last);
5043 // hop to next word while checking for insets
5044 while (sameinset && last < to && owner_->isWordSeparator(last)) {
5045 if (Inset const * inset = owner_->getInset(last))
5046 sameinset = inset->isChar() && inset->isLetter();
5047 if (sameinset && owner_->isDeleted(last)) {
5048 appendSkipPosition(skips, last);
5053 if (sameinset && last < to) {
5054 // now check for language change
5055 samelang = lang == getSpellLanguage(last);
5058 // if language change detected backstep is needed
5066 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
5069 const_cast<Language *>(owner_->getFontSettings(
5070 inset_owner_->buffer().params(), from).language());
5071 if (lang == inset_owner_->buffer().params().language
5072 && !lyxrc.spellchecker_alt_lang.empty()) {
5074 string const lang_variety =
5075 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
5076 lang->setCode(lang_code);
5077 lang->setVariety(lang_variety);
5083 void Paragraph::requestSpellCheck(pos_type pos)
5085 d->requestSpellCheck(pos);
5087 // Also request spellcheck within (text) insets
5088 for (auto const & insets : insetList()) {
5089 if (!insets.inset->asInsetText())
5091 ParagraphList & inset_pars =
5092 insets.inset->asInsetText()->paragraphs();
5093 ParagraphList::iterator pit = inset_pars.begin();
5094 ParagraphList::iterator pend = inset_pars.end();
5095 for (; pit != pend; ++pit)
5096 pit->requestSpellCheck();
5102 bool Paragraph::needsSpellCheck() const
5104 SpellChecker::ChangeNumber speller_change_number = 0;
5105 if (theSpellChecker())
5106 speller_change_number = theSpellChecker()->changeNumber();
5107 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
5108 d->speller_state_.needsCompleteRefresh(speller_change_number);
5110 return d->needsSpellCheck();
5114 bool Paragraph::Private::ignoreWord(docstring const & word) const
5116 // Ignore words with digits
5117 // FIXME: make this customizable
5118 // (note that some checkers ignore words with digits by default)
5119 docstring::const_iterator cit = word.begin();
5120 docstring::const_iterator const end = word.end();
5121 for (; cit != end; ++cit) {
5122 if (isNumber((*cit)))
5129 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
5130 WordLangTuple & wl, docstring_list & suggestions,
5131 bool do_suggestion, bool check_learned) const
5133 SpellChecker::Result result = SpellChecker::WORD_OK;
5134 SpellChecker * speller = theSpellChecker();
5138 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
5141 locateWord(from, to, WHOLE_WORD, true);
5142 if (from == to || from >= size())
5145 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5146 Language * lang = d->getSpellLanguage(from);
5148 BufferParams const & bparams = d->inset_owner_->buffer().params();
5150 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5153 wl = WordLangTuple(word, lang);
5158 if (needsSpellCheck() || check_learned) {
5160 if (!d->ignoreWord(word)) {
5161 bool const trailing_dot = to < size() && d->text_[to] == '.';
5162 result = speller->check(wl, bparams.spellignore());
5163 if (SpellChecker::misspelled(result) && trailing_dot) {
5164 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5165 result = speller->check(wl, bparams.spellignore());
5166 if (!SpellChecker::misspelled(result)) {
5167 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5169 from << ".." << to << "]");
5171 // spell check with dot appended failed too
5172 // restore original word/lang value
5173 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5174 wl = WordLangTuple(word, lang);
5178 if (!SpellChecker::misspelled(result)) {
5179 // area up to the begin of the next word is not misspelled
5180 while (end < size() && isWordSeparator(end))
5183 d->setMisspelled(from, end, result);
5185 result = d->speller_state_.getState(from);
5189 suggestions.clear();
5191 if (SpellChecker::misspelled(result)) {
5192 LYXERR(Debug::GUI, "misspelled word: \"" <<
5194 from << ".." << to << "]");
5196 speller->suggest(wl, suggestions);
5202 void Paragraph::anonymize()
5204 // This is a very crude anonymization for now
5205 for (char_type & c : d->text_)
5206 if (isLetterChar(c) || isNumber(c))
5211 void Paragraph::Private::markMisspelledWords(
5212 Language const * lang,
5213 pos_type const & first, pos_type const & last,
5214 SpellChecker::Result result,
5215 docstring const & word,
5216 SkipPositions const & skips)
5218 if (!SpellChecker::misspelled(result)) {
5219 setMisspelled(first, last, SpellChecker::WORD_OK);
5223 SpellChecker * speller = theSpellChecker();
5224 // locate and enumerate the error positions
5225 int nerrors = speller->numMisspelledWords();
5227 SkipPositionsIterator it = skips.begin();
5228 SkipPositionsIterator et = skips.end();
5229 for (int index = 0; index < nerrors; ++index) {
5232 speller->misspelledWord(index, wstart, wlen);
5233 /// should not happen if speller supports range checks
5236 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5237 wstart += first + numskipped;
5238 if (snext < wstart) {
5239 /// mark the range of correct spelling
5240 numskipped += countSkips(it, et, wstart);
5241 setMisspelled(snext,
5242 wstart - 1, SpellChecker::WORD_OK);
5244 snext = wstart + wlen;
5245 // Check whether the candidate is in the document's local dict
5246 SpellChecker::Result actresult = result;
5247 if (inset_owner_->buffer().params().spellignored(candidate))
5248 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5249 numskipped += countSkips(it, et, snext);
5250 /// mark the range of misspelling
5251 setMisspelled(wstart, snext, actresult);
5252 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5253 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5254 candidate.word() << "\" [" <<
5255 wstart << ".." << (snext-1) << "]");
5257 LYXERR(Debug::GUI, "misspelled word: \"" <<
5258 candidate.word() << "\" [" <<
5259 wstart << ".." << (snext-1) << "]");
5262 if (snext <= last) {
5263 /// mark the range of correct spelling at end
5264 setMisspelled(snext, last, SpellChecker::WORD_OK);
5269 void Paragraph::spellCheck() const
5271 SpellChecker * speller = theSpellChecker();
5272 if (!speller || empty() ||!needsSpellCheck())
5276 d->rangeOfSpellCheck(start, endpos);
5277 if (speller->canCheckParagraph()) {
5278 // loop until we leave the range
5279 for (pos_type first = start; first < endpos; ) {
5280 pos_type last = endpos;
5281 Private::SkipPositions skips;
5282 Language * lang = d->locateSpellRange(first, last, skips);
5283 if (first >= endpos)
5285 // start the spell checker on the unit of meaning
5286 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5287 WordLangTuple wl = WordLangTuple(word, lang);
5288 BufferParams const & bparams = d->inset_owner_->buffer().params();
5289 SpellChecker::Result result = !word.empty() ?
5290 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5291 d->markMisspelledWords(lang, first, last, result, word, skips);
5295 static docstring_list suggestions;
5296 pos_type to = endpos;
5297 while (start < endpos) {
5299 spellCheck(start, to, wl, suggestions, false);
5303 d->readySpellCheck();
5307 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5309 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5310 if (result || pos <= 0 || pos > size())
5312 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5313 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5318 string Paragraph::magicLabel() const
5321 ss << "magicparlabel-" << id();