3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Kimberly Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
24 #include "BufferParams.h"
25 #include "BufferEncodings.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "output_xhtml.h"
38 #include "output_docbook.h"
39 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "texstream.h"
45 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetArgument.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
85 /////////////////////////////////////////////////////////////////////
89 /////////////////////////////////////////////////////////////////////
91 class SpellResultRange {
93 SpellResultRange(FontSpan range, SpellChecker::Result result)
94 : range_(range), result_(result)
97 FontSpan const & range() const { return range_; }
99 void range(FontSpan const & r) { range_ = r; }
101 SpellChecker::Result result() const { return result_; }
103 void result(SpellChecker::Result r) { result_ = r; }
105 bool contains(pos_type pos) const { return range_.contains(pos); }
107 bool covered(FontSpan const & r) const
109 // 1. first of new range inside current range or
110 // 2. last of new range inside current range or
111 // 3. first of current range inside new range or
112 // 4. last of current range inside new range
113 //FIXME: is this the same as !range_.intersect(r).empty() ?
114 return range_.contains(r.first) || range_.contains(r.last) ||
115 r.contains(range_.first) || r.contains(range_.last);
118 void shift(pos_type pos, int offset)
120 if (range_.first > pos) {
121 range_.first += offset;
122 range_.last += offset;
123 } else if (range_.last >= pos) {
124 range_.last += offset;
129 SpellChecker::Result result_ ;
133 /////////////////////////////////////////////////////////////////////
137 /////////////////////////////////////////////////////////////////////
139 class SpellCheckerState {
143 needs_refresh_ = true;
144 current_change_number_ = 0;
147 void setRange(FontSpan const & fp, SpellChecker::Result state)
150 RangesIterator et = ranges_.end();
151 RangesIterator it = ranges_.begin();
152 for (; it != et; ++it) {
153 if (!it->covered(fp))
154 result.push_back(SpellResultRange(it->range(), it->result()));
155 else if (state == SpellChecker::WORD_OK) {
156 // trim or split the current misspelled range
157 // store misspelled ranges only
158 FontSpan range = it->range();
159 if (fp.first > range.first) {
160 // misspelled area in front of WORD_OK
161 range.last = fp.first - 1;
162 result.push_back(SpellResultRange(range, it->result()));
165 if (fp.last < range.last) {
166 // misspelled area after WORD_OK range
167 range.first = fp.last + 1;
168 result.push_back(SpellResultRange(range, it->result()));
173 if (state != SpellChecker::WORD_OK)
174 ranges_.push_back(SpellResultRange(fp, state));
177 void increasePosAfterPos(pos_type pos)
179 correctRangesAfterPos(pos, 1);
183 void decreasePosAfterPos(pos_type pos)
185 correctRangesAfterPos(pos, -1);
189 void refreshLast(pos_type pos)
191 if (pos < refresh_.last)
195 SpellChecker::Result getState(pos_type pos) const
197 SpellChecker::Result result = SpellChecker::WORD_OK;
198 RangesIterator et = ranges_.end();
199 RangesIterator it = ranges_.begin();
200 for (; it != et; ++it) {
201 if(it->contains(pos)) {
208 FontSpan const & getRange(pos_type pos) const
210 /// empty span to indicate mismatch
211 static FontSpan empty_;
212 RangesIterator et = ranges_.end();
213 RangesIterator it = ranges_.begin();
214 for (; it != et; ++it) {
215 if(it->contains(pos)) {
222 bool needsRefresh() const
224 return needs_refresh_;
227 SpellChecker::ChangeNumber currentChangeNumber() const
229 return current_change_number_;
232 void refreshRange(pos_type & first, pos_type & last) const
234 first = refresh_.first;
235 last = refresh_.last;
238 void needsRefresh(pos_type pos)
240 if (needs_refresh_ && pos != -1) {
241 if (pos < refresh_.first)
242 refresh_.first = pos;
243 if (pos > refresh_.last)
245 } else if (pos != -1) {
246 // init request check for neighbour positions too
247 refresh_.first = pos > 0 ? pos - 1 : 0;
248 // no need for special end of paragraph check
249 refresh_.last = pos + 1;
251 needs_refresh_ = pos != -1;
254 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
256 needs_refresh_ = true;
259 current_change_number_ = change_number;
262 typedef vector<SpellResultRange> Ranges;
263 typedef Ranges::const_iterator RangesIterator;
265 /// the area of the paragraph with pending spell check
267 /// spell state cache version number
268 SpellChecker::ChangeNumber current_change_number_;
272 void correctRangesAfterPos(pos_type pos, int offset)
274 RangesIterator et = ranges_.end();
275 Ranges::iterator it = ranges_.begin();
276 for (; it != et; ++it) {
277 it->shift(pos, offset);
283 /////////////////////////////////////////////////////////////////////
285 // Paragraph::Private
287 /////////////////////////////////////////////////////////////////////
289 class Paragraph::Private
291 // Enforce our own "copy" constructor
292 Private(Private const &) = delete;
293 Private & operator=(Private const &) = delete;
294 // Unique ID generator
295 static int make_id();
298 Private(Paragraph * owner, Layout const & layout);
299 /// "Copy constructor"
300 Private(Private const &, Paragraph * owner);
301 /// Copy constructor from \p beg to \p end
302 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
305 void insertChar(pos_type pos, char_type c, Change const & change);
307 /// Output the surrogate pair formed by \p c and \p next to \p os.
308 /// \return the number of characters written.
309 int latexSurrogatePair(BufferParams const &, otexstream & os,
310 char_type c, char_type next,
311 OutputParams const &) const;
313 /// Output a space in appropriate formatting (or a surrogate pair
314 /// if the next character is a combining character).
315 /// \return whether a surrogate pair was output.
316 bool simpleTeXBlanks(BufferParams const &,
317 OutputParams const &,
320 unsigned int & column,
322 Layout const & style) const;
324 /// This could go to ParagraphParameters if we want to.
325 int startTeXParParams(BufferParams const &, otexstream &,
326 OutputParams const &) const;
328 /// This could go to ParagraphParameters if we want to.
329 bool endTeXParParams(BufferParams const &, otexstream &,
330 OutputParams const &) const;
333 void latexInset(BufferParams const &,
338 Font const & outerfont,
340 Change & running_change,
341 Layout const & style,
343 unsigned int & column,
344 bool const fontswitch_inset,
345 bool const closeLanguage,
346 bool const lang_switched_at_inset) const;
349 void latexSpecialChar(
351 BufferParams const & bparams,
352 OutputParams const & runparams,
353 Font const & running_font,
354 string & alien_script,
355 Layout const & style,
358 unsigned int & column) const;
365 unsigned int & column) const;
371 unsigned int & column) const;
377 unsigned int & column) const;
380 void validate(LaTeXFeatures & features) const;
382 /// Checks if the paragraph contains only text and no inset or font change.
383 bool onlyText(Buffer const & buf, Font const & outerfont,
384 pos_type initial) const;
386 /// a vector of speller skip positions
387 typedef vector<FontSpan> SkipPositions;
388 typedef SkipPositions::const_iterator SkipPositionsIterator;
390 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
392 Language * getSpellLanguage(pos_type const from) const;
394 Language * locateSpellRange(pos_type & from, pos_type & to,
395 SkipPositions & skips) const;
397 bool hasSpellerChange() const
399 SpellChecker::ChangeNumber speller_change_number = 0;
400 if (theSpellChecker())
401 speller_change_number = theSpellChecker()->changeNumber();
402 return speller_change_number > speller_state_.currentChangeNumber();
405 bool ignoreWord(docstring const & word) const;
407 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
409 pos_type textsize = owner_->size();
410 // check for sane arguments
411 if (to <= from || from >= textsize)
413 FontSpan fp = FontSpan(from, to - 1);
414 speller_state_.setRange(fp, state);
417 void requestSpellCheck(pos_type pos)
420 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
422 speller_state_.needsRefresh(pos);
425 void readySpellCheck()
427 speller_state_.needsRefresh(-1);
430 bool needsSpellCheck() const
432 return speller_state_.needsRefresh();
435 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
437 speller_state_.refreshRange(first, last);
439 last = owner_->size();
442 pos_type endpos = last;
443 owner_->locateWord(first, endpos, WHOLE_WORD, true);
446 owner_->locateWord(last, endpos, WHOLE_WORD, true);
451 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
455 while (it != et && it->first < start) {
456 long skip = it->last - it->first + 1;
464 void markMisspelledWords(Language const * lang,
465 pos_type const & first, pos_type const & last,
466 SpellChecker::Result result,
467 docstring const & word,
468 SkipPositions const & skips);
470 InsetCode ownerCode() const
472 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
475 /// Which Paragraph owns us?
479 Inset const * inset_owner_;
485 ParagraphParameters params_;
487 /// for recording and looking up changes
491 InsetList insetlist_;
494 pos_type begin_of_body_;
496 typedef docstring TextContainer;
500 typedef set<docstring> Words;
501 typedef map<string, Words> LangWordsMap;
505 Layout const * layout_;
507 SpellCheckerState speller_state_;
513 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
514 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
521 int Paragraph::Private::make_id()
523 // The id is unique per session across buffers because it is used in
524 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
527 static int next_id(0);
532 Paragraph::Private::Private(Private const & p, Paragraph * owner)
533 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
534 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
535 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
536 layout_(p.layout_), id_(make_id())
538 requestSpellCheck(p.text_.size());
542 Paragraph::Private::Private(Private const & p, Paragraph * owner,
543 pos_type beg, pos_type end)
544 : owner_(owner), inset_owner_(p.inset_owner_),
545 params_(p.params_), changes_(p.changes_),
546 insetlist_(p.insetlist_, beg, end),
547 begin_of_body_(p.begin_of_body_), words_(p.words_),
548 layout_(p.layout_), id_(make_id())
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 /////////////////////////////////////////////////////////////////////
575 /////////////////////////////////////////////////////////////////////
579 /** This helper class should be instantiated at the start of methods
580 * that can create or merge changes. If as a result the value of
581 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
584 struct ChangesMonitor {
586 ChangesMonitor(Paragraph & par)
587 : par_(par), was_changed_(par.isChanged()) {}
591 /* We may need to run updateBuffer to check whether the buffer
592 * contains changes (and toggle the changes toolbar). We do it
594 * 1. the `changedness' of the paragraph has changed,
595 * 2. and we are not in the situation where the buffer has changes
596 * and new changes are added to the paragraph.
599 if (par_.isChanged() != was_changed_
600 && par_.inInset().isBufferValid()
601 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
602 par_.inInset().buffer().forceUpdate();
603 } catch(support::ExceptionMessage const &) {}
608 Paragraph const & par_;
615 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
616 bool output_active, TocBackend & backend) const
618 d->changes_.addToToc(cdit, buf, output_active, backend);
622 bool Paragraph::isDeleted(pos_type start, pos_type end) const
624 LASSERT(start >= 0 && start <= size(), return false);
625 LASSERT(end > start && end <= size() + 1, return false);
627 return d->changes_.isDeleted(start, end);
631 bool Paragraph::isChanged(pos_type start, pos_type end) const
633 LASSERT(start >= 0 && start <= size(), return false);
634 LASSERT(end > start && end <= size() + 1, return false);
636 return d->changes_.isChanged(start, end);
639 // FIXME: Ideally the diverse isChanged() methods should account for that!
640 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
642 LASSERT(start >= 0 && start <= size(), return false);
643 LASSERT(end > start && end <= size() + 1, return false);
645 for (auto const & icit : d->insetlist_) {
646 if (icit.pos < start)
650 if (icit.inset && icit.inset->isChanged())
656 bool Paragraph::isChanged() const
658 return d->changes_.isChanged();
662 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
664 // keep the logic here in sync with the logic of eraseChars()
668 Change const & change = d->changes_.lookup(size());
669 return change.inserted() && change.currentAuthor();
672 Change Paragraph::parEndChange() const
674 return d->changes_.lookup(size());
678 void Paragraph::setChange(Change const & change)
680 // Make sure that Buffer::hasChangesPresent is updated
681 ChangesMonitor cm(*this);
683 // beware of the imaginary end-of-par character!
684 d->changes_.set(change, 0, size() + 1);
687 * Propagate the change recursively - but not in case of DELETED!
689 * Imagine that your co-author makes changes in an existing inset. He
690 * sends your document to you and you come to the conclusion that the
691 * inset should go completely. If you erase it, LyX must not delete all
692 * text within the inset. Otherwise, the change tracked insertions of
693 * your co-author get lost and there is no way to restore them later.
695 * Conclusion: An inset's content should remain untouched if you delete it
698 if (!change.deleted()) {
699 for (pos_type pos = 0; pos < size(); ++pos) {
700 if (Inset * inset = getInset(pos))
701 inset->setChange(change);
707 void Paragraph::setChange(pos_type pos, Change const & change)
709 // Make sure that Buffer::hasChangesPresent is updated
710 ChangesMonitor cm(*this);
712 LASSERT(pos >= 0 && pos <= size(), return);
713 d->changes_.set(change, pos);
715 // see comment in setChange(Change const &) above
716 if (!change.deleted() && pos < size())
717 if (Inset * inset = getInset(pos))
718 inset->setChange(change);
722 Change const & Paragraph::lookupChange(pos_type pos) const
724 LBUFERR(pos >= 0 && pos <= size());
725 return d->changes_.lookup(pos);
729 void Paragraph::acceptChanges(pos_type start, pos_type end)
731 // Make sure that Buffer::hasChangesPresent is updated
732 ChangesMonitor cm(*this);
734 LASSERT(start >= 0 && start <= size(), return);
735 LASSERT(end > start && end <= size() + 1, return);
737 for (pos_type pos = start; pos < end; ++pos) {
738 switch (lookupChange(pos).type) {
739 case Change::UNCHANGED:
740 // accept changes in nested inset
741 if (Inset * inset = getInset(pos))
742 inset->acceptChanges();
745 case Change::INSERTED:
746 d->changes_.set(Change(Change::UNCHANGED), pos);
747 // also accept changes in nested inset
748 if (Inset * inset = getInset(pos))
749 inset->acceptChanges();
752 case Change::DELETED:
753 // Suppress access to non-existent
754 // "end-of-paragraph char"
756 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 Xe/LuaTeX does not need a switch
1101 // and \L is not defined there.
1102 && (!runparams.isFullUnicode() || !runparams.use_babel)
1103 && running_font.isRightToLeft()) {
1104 if (runparams.use_polyglossia) {
1106 // Displayed environments go in an LTR environment
1108 os << "\\begin{LTR}";
1111 if (runparams.flavor == Flavor::LuaTeX) {
1112 // luabidi's \LRE needs extra grouping
1113 // (possibly a LuaTeX bug)
1120 } else if (running_font.language()->lang() == "farsi"
1121 || running_font.language()->lang() == "arabic_arabi") {
1122 os << "\\textLR{" << termcmd;
1133 if (open_font && fontswitch_inset) {
1134 bool lang_closed = false;
1135 // Close language if needed
1136 if (closeLanguage && !lang_switched_at_inset) {
1137 // We need prev_font here as language changes directly at inset
1138 // will only be started inside the inset.
1139 Font const prev_font = (i > 0) ?
1140 owner_->getFont(bparams, i - 1, outerfont)
1142 Font tmpfont(basefont);
1143 tmpfont.setLanguage(prev_font.language());
1144 bool needPar = false;
1145 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1147 needPar, closeLanguage);
1149 lang_closed = count > 0;
1151 // Update the running_font, making sure, however,
1152 // to leave the language as it was.
1153 // FIXME: probably a better way to keep track of the old
1154 // language, than copying the entire font?
1155 Font const copy_font(running_font);
1156 basefont = owner_->getLayoutFont(bparams, outerfont);
1157 running_font = basefont;
1159 running_font.setLanguage(copy_font.language());
1160 OutputParams rp = runparams;
1161 rp.encoding = basefont.language()->encoding();
1162 // For these, we use switches, so they should be taken as
1163 // base inside the inset.
1164 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1165 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1166 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1167 // Now re-do font changes in a way needed here
1168 // (using switches with multi-par insets)
1169 InsetText const * textinset = inset->asInsetText();
1170 bool const cprotect = textinset
1171 ? textinset->hasCProtectContent(runparams.moving_arg)
1172 && !textinset->text().isMainText()
1173 && inset->lyxCode() != BRANCH_CODE
1175 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1181 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1185 runparams.local_font = &basefont;
1188 if (fontswitch_inset && !closeLanguage) {
1189 // The directionality has been switched at inset.
1190 // Force markup inside.
1191 runparams.local_font = &basefont;
1194 size_t const previous_row_count = os.texrow().rows();
1197 runparams.lastid = id_;
1198 runparams.lastpos = i;
1199 inset->latex(os, runparams);
1200 } catch (EncodingException & e) {
1201 // add location information and throw again.
1207 if (!close_env.empty())
1208 os << "\\end{" << close_env << "}";
1210 if (close_brace > 0) {
1211 for (unsigned i = 0; i < close_brace; ++i)
1217 if (os.texrow().rows() > previous_row_count) {
1218 os.texrow().start(owner_->id(), i + 1);
1221 column += (unsigned int)(os.os().tellp() - len);
1224 if (owner_->isDeleted(i))
1225 --runparams.inDeletedInset;
1229 void Paragraph::Private::latexSpecialChar(otexstream & os,
1230 BufferParams const & bparams,
1231 OutputParams const & runparams,
1232 Font const & running_font,
1233 string & alien_script,
1234 Layout const & style,
1237 unsigned int & column) const
1239 char_type const c = owner_->getUChar(bparams, runparams, i);
1241 if (style.pass_thru || runparams.pass_thru || runparams.find_effective()
1242 || contains(style.pass_thru_chars, c)
1243 || contains(runparams.pass_thru_chars, c)) {
1244 if (runparams.find_effective()) {
1250 os << "\\braceleft ";
1253 os << "\\braceright ";
1256 os << "\\lyxdollar ";
1259 os << "\\lyxtilde ";
1269 else if (c != '\0') {
1270 Encoding const * const enc = runparams.encoding;
1271 if (enc && !enc->encodable(c))
1272 throw EncodingException(c);
1278 // TIPA uses its own T3 encoding
1279 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1281 // If T1 font encoding is used, use the special
1282 // characters it provides.
1283 // NOTE: Some languages reset the font encoding internally to a
1284 // non-standard font encoding. If we are using such a language,
1285 // we do not output special T1 chars.
1286 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1287 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1288 && latexSpecialT1(c, os, i, column))
1290 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1291 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1292 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1295 // Otherwise, we use what LaTeX provides us.
1298 os << "\\textbackslash" << termcmd;
1302 os << "\\textless" << termcmd;
1306 os << "\\textgreater" << termcmd;
1310 os << "\\textbar" << termcmd;
1315 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1316 (end_pos == -1 || i + 1 < end_pos) &&
1317 text_[i+1] == '-') {
1318 // Prevent "--" becoming an en dash and "---" an em dash.
1319 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1325 os << "\\textquotedbl" << termcmd;
1330 case '%': case '#': case '{':
1338 os << "\\textasciitilde" << termcmd;
1343 os << "\\textasciicircum" << termcmd;
1350 // avoid being mistaken for optional arguments
1358 // Blanks are printed before font switching.
1359 // Sure? I am not! (try nice-latex)
1360 // I am sure it's correct. LyX might be smarter
1361 // in the future, but for now, nothing wrong is
1367 // XeTeX's dash behaviour is determined via a global setting
1368 if (bparams.use_dash_ligatures
1369 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1371 // TODO #10961: && not in inset Flex Code
1372 // TODO #10961: && not in layout LyXCode
1373 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1390 Encoding const & encoding = *(runparams.encoding);
1391 char_type next = '\0';
1392 if (i + 1 < int(text_.size())) {
1393 next = text_[i + 1];
1394 if (Encodings::isCombiningChar(next)) {
1395 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1400 pair<docstring, bool> latex = encoding.latexChar(c);
1401 docstring nextlatex;
1402 bool nexttipas = false;
1403 string nexttipashortcut;
1404 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1405 nextlatex = encoding.latexChar(next).first;
1406 if (runparams.inIPA) {
1407 nexttipashortcut = Encodings::TIPAShortcut(next);
1408 nexttipas = !nexttipashortcut.empty();
1412 if (runparams.inIPA) {
1413 string const tipashortcut = Encodings::TIPAShortcut(c);
1414 if (!tipashortcut.empty()) {
1415 latex.first = from_ascii(tipashortcut);
1416 latex.second = false;
1420 // eventually close "script wrapper" command (see `Paragraph::latex`)
1421 if (!alien_script.empty()
1422 && alien_script != Encodings::isKnownScriptChar(next)) {
1423 column += latex.first.length();
1424 alien_script.clear();
1425 os << latex.first << "}";
1429 && ((!prefixIs(nextlatex, '\\')
1430 && !prefixIs(nextlatex, '{')
1431 && !prefixIs(nextlatex, '}'))
1433 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1435 // Prevent eating of a following space or command corruption by
1436 // following characters
1437 if (next == ' ' || next == '\0') {
1438 column += latex.first.length() + 1;
1439 os << latex.first << "{}";
1441 column += latex.first.length();
1442 os << latex.first << " ";
1445 column += latex.first.length() - 1;
1453 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1454 pos_type i, unsigned int & column) const
1460 // In T1 encoding, these characters exist
1461 // but we should avoid ligatures
1462 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1464 os << "\\textcompwordmark" << termcmd;
1471 // soul.sty breaks with \char`\"
1472 os << "\\textquotedbl" << termcmd;
1481 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1482 pos_type i, unsigned int & column) const
1484 // TU encoding is currently on par with T1.
1485 return latexSpecialT1(c, os, i, column);
1489 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1490 pos_type /*i*/, unsigned int & column) const
1500 os << "\\textvertline" << termcmd;
1509 void Paragraph::Private::validate(LaTeXFeatures & features) const
1511 if (layout_->inpreamble && inset_owner_) {
1512 // FIXME: Using a string stream here circumvents the encoding
1513 // switching machinery of odocstream. Therefore the
1514 // output is wrong if this paragraph contains content
1515 // that needs to switch encoding.
1516 Buffer const & buf = inset_owner_->buffer();
1517 otexstringstream os;
1518 os << layout_->preamble();
1519 size_t const length = os.length();
1520 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1521 buf.getParFromID(owner_->id()).pit(), os,
1522 features.runparams(), string(), 0, -1, true);
1523 if (os.length() > length)
1524 features.addPreambleSnippet(os.release(), true);
1527 if (features.runparams().flavor == Flavor::Html
1528 && layout_->htmltitle()) {
1529 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1532 // check the params.
1533 if (!params_.spacing().isDefault())
1534 features.require("setspace");
1537 features.useLayout(layout_->name());
1540 fontlist_.validate(features);
1542 // then the indentation
1543 if (!params_.leftIndent().zero())
1544 features.require("ParagraphLeftIndent");
1547 InsetList::const_iterator icit = insetlist_.begin();
1548 InsetList::const_iterator iend = insetlist_.end();
1549 for (; icit != iend; ++icit) {
1551 features.inDeletedInset(owner_->isDeleted(icit->pos));
1552 if (icit->inset->lyxCode() == FOOT_CODE) {
1553 // FIXME: an item inset would make things much easier.
1554 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1555 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1556 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1557 && (icit->pos < begin_of_body_
1558 || (icit->pos == begin_of_body_
1559 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1560 features.saveNoteEnv("description");
1562 icit->inset->validate(features);
1563 features.inDeletedInset(false);
1564 if (layout_->needprotect &&
1565 icit->inset->lyxCode() == FOOT_CODE)
1566 features.require("NeedLyXFootnoteCode");
1570 // then the contents
1571 BufferParams const bp = features.runparams().is_child
1572 ? features.buffer().masterParams() : features.buffer().params();
1573 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1574 char_type c = text_[i];
1575 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1577 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1578 features.require("textquotedblp");
1579 else if (features.runparams().main_fontenc != "T1"
1580 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1581 features.require("textquotedbl");
1582 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1583 // features that depend on the font or input encoding
1584 string feats = ci.textPreamble();
1585 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1586 if (fontenc.empty())
1587 fontenc = features.runparams().main_fontenc;
1588 while (!feats.empty()) {
1590 feats = split(feats, feat, ',');
1591 if (contains(feat, "!=")) {
1592 // a feature that is required except for the spcified
1593 // font or input encodings
1595 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1596 // multiple encodings are separated by semicolon
1597 vector<string> context = getVectorFromString(contexts, ";");
1598 // require feature if the context matches neither current font
1599 // nor input encoding
1600 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1601 && std::find(context.begin(), context.end(),
1602 features.runparams().encoding->name()) == context.end())
1603 features.require(realfeature);
1604 } else if (contains(feat, '=')) {
1605 // a feature that is required only for the spcified
1606 // font or input encodings
1608 string const contexts = split(feat, realfeature, '=');
1609 // multiple encodings are separated by semicolon
1610 vector<string> context = getVectorFromString(contexts, ";");
1611 // require feature if the context matches either current font
1612 // or input encoding
1613 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1614 || std::find(context.begin(), context.end(),
1615 features.runparams().encoding->name()) != context.end())
1616 features.require(realfeature);
1619 } else if (!bp.use_dash_ligatures
1620 && (c == 0x2013 || c == 0x2014)
1621 && bp.useNonTeXFonts
1622 && features.runparams().flavor == Flavor::XeTeX)
1623 // XeTeX's dash behaviour is determined via a global setting
1624 features.require("xetexdashbreakstate");
1625 BufferEncodings::validate(c, features);
1629 /////////////////////////////////////////////////////////////////////
1633 /////////////////////////////////////////////////////////////////////
1636 Layout const emptyParagraphLayout;
1639 Paragraph::Paragraph()
1640 : d(new Paragraph::Private(this, emptyParagraphLayout))
1647 Paragraph::Paragraph(Paragraph const & par)
1648 : itemdepth(par.itemdepth),
1649 d(new Paragraph::Private(*par.d, this))
1655 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1656 : itemdepth(par.itemdepth),
1657 d(new Paragraph::Private(*par.d, this, beg, end))
1663 Paragraph & Paragraph::operator=(Paragraph const & par)
1665 // needed as we will destroy the private part before copying it
1667 itemdepth = par.itemdepth;
1671 d = new Private(*par.d, this);
1678 Paragraph::~Paragraph()
1687 // this shall be called just before every "os << ..." action.
1688 void flushString(ostream & os, docstring & s)
1697 void Paragraph::write(ostream & os, BufferParams const & bparams,
1698 depth_type & depth) const
1700 // The beginning or end of a deeper (i.e. nested) area?
1701 if (depth != d->params_.depth()) {
1702 if (d->params_.depth() > depth) {
1703 while (d->params_.depth() > depth) {
1704 os << "\n\\begin_deeper";
1708 while (d->params_.depth() < depth) {
1709 os << "\n\\end_deeper";
1715 // First write the layout
1716 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1718 d->params_.write(os);
1720 Font font1(inherit_font, bparams.language);
1722 Change running_change = Change(Change::UNCHANGED);
1724 // this string is used as a buffer to avoid repetitive calls
1725 // to to_utf8(), which turn out to be expensive (JMarc)
1726 docstring write_buffer;
1729 for (pos_type i = 0; i <= size(); ++i) {
1731 Change const & change = lookupChange(i);
1732 if (change != running_change)
1733 flushString(os, write_buffer);
1734 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1735 running_change = change;
1740 // Write font changes
1741 Font font2 = getFontSettings(bparams, i);
1742 if (font2 != font1) {
1743 flushString(os, write_buffer);
1744 font2.lyxWriteChanges(font1, os);
1749 char_type const c = d->text_[i];
1752 if (Inset const * inset = getInset(i)) {
1753 flushString(os, write_buffer);
1754 if (inset->directWrite()) {
1755 // international char, let it write
1756 // code directly so it's shorter in
1762 os << "\\begin_inset ";
1764 os << "\n\\end_inset\n\n";
1767 // FIXME This can be removed again once the mystery
1768 // crash has been resolved.
1773 flushString(os, write_buffer);
1774 os << "\n\\backslash\n";
1783 case 0x061F: // ؟ U+061F ARABIC QUESTION MARK
1784 case 0x061B: // ؛ U+061B ARABIC SEMICOLON
1785 case 0x060C: // ، U+060C ARABIC COMMA
1786 flushString(os, write_buffer);
1787 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1788 os << to_utf8(docstring(1, c)) << '\n';
1791 os << to_utf8(docstring(1, c));
1793 case 0x2014: // — U+2014 EM DASH
1794 case 0x3002: // 。 U+3002 IDEOGRAPHIC FULL STOP
1795 case 0xFF01: // ! U+FF01 FULLWIDTH EXCLAMATION MARK
1796 case 0xFF1F: // ? U+FF1F FULLWIDTH QUESTION MARK
1797 case 0xFF1A: // : U+FF1A FULLWIDTH COLON
1798 case 0xFF1B: // ; U+FF1B FULLWIDTH SEMICOLON
1799 case 0xFF0C: // , U+FF0C FULLWIDTH COMMA
1800 flushString(os, write_buffer);
1801 os << to_utf8(docstring(1, c)) << '\n';
1806 flushString(os, write_buffer);
1810 // this check is to amend a bug. LyX sometimes
1811 // inserts '\0' this could cause problems.
1813 write_buffer.push_back(c);
1815 LYXERR0("NUL char in structure.");
1821 flushString(os, write_buffer);
1822 os << "\n\\end_layout\n";
1823 // FIXME This can be removed again once the mystery
1824 // crash has been resolved.
1829 void Paragraph::validate(LaTeXFeatures & features) const
1831 d->validate(features);
1832 bool fragile = features.runparams().moving_arg;
1833 fragile |= layout().needprotect;
1834 if (inInset().getLayout().isNeedProtect())
1836 if (needsCProtection(fragile))
1837 features.require("cprotect");
1841 void Paragraph::insert(pos_type pos, docstring const & str,
1842 Font const & font, Change const & change)
1844 for (size_t i = 0, n = str.size(); i != n ; ++i)
1845 insertChar(pos + i, str[i], font, change);
1849 void Paragraph::appendChar(char_type c, Font const & font,
1850 Change const & change)
1852 // Make sure that Buffer::hasChangesPresent is updated
1853 ChangesMonitor cm(*this);
1856 d->changes_.insert(change, d->text_.size());
1857 // when appending characters, no need to update tables
1858 d->text_.push_back(c);
1859 setFont(d->text_.size() - 1, font);
1860 d->requestSpellCheck(d->text_.size() - 1);
1864 void Paragraph::appendString(docstring const & s, Font const & font,
1865 Change const & change)
1867 // Make sure that Buffer::hasChangesPresent is updated
1868 ChangesMonitor cm(*this);
1870 pos_type end = s.size();
1871 size_t oldsize = d->text_.size();
1872 size_t newsize = oldsize + end;
1873 size_t capacity = d->text_.capacity();
1874 if (newsize >= capacity)
1875 d->text_.reserve(max(capacity + 100, newsize));
1877 // when appending characters, no need to update tables
1880 // FIXME: Optimize this!
1881 for (size_t i = oldsize; i != newsize; ++i) {
1883 d->changes_.insert(change, i);
1884 d->requestSpellCheck(i);
1886 d->fontlist_.set(oldsize, font);
1887 d->fontlist_.set(newsize - 1, font);
1891 void Paragraph::insertChar(pos_type pos, char_type c,
1894 d->insertChar(pos, c, Change(trackChanges ?
1895 Change::INSERTED : Change::UNCHANGED));
1899 void Paragraph::insertChar(pos_type pos, char_type c,
1900 Font const & font, bool trackChanges)
1902 d->insertChar(pos, c, Change(trackChanges ?
1903 Change::INSERTED : Change::UNCHANGED));
1908 void Paragraph::insertChar(pos_type pos, char_type c,
1909 Font const & font, Change const & change)
1911 d->insertChar(pos, c, change);
1916 void Paragraph::resetFonts(Font const & font)
1918 d->fontlist_.clear();
1919 d->fontlist_.set(0, font);
1920 d->fontlist_.set(d->text_.size() - 1, font);
1923 // Gets uninstantiated font setting at position.
1924 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1928 LYXERR0("pos: " << pos << " size: " << size());
1932 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1933 if (cit != d->fontlist_.end())
1936 if (pos == size() && !empty())
1937 return getFontSettings(bparams, pos - 1);
1939 // Optimisation: avoid a full font instantiation if there is no
1940 // language change from previous call.
1941 static Font previous_font;
1942 static Language const * previous_lang = nullptr;
1943 Language const * lang = getParLanguage(bparams);
1944 if (lang != previous_lang) {
1945 previous_lang = lang;
1946 previous_font = Font(inherit_font, lang);
1948 return previous_font;
1952 FontSpan Paragraph::fontSpan(pos_type pos) const
1954 LBUFERR(pos <= size());
1957 return FontSpan(pos, pos);
1960 FontList::const_iterator cit = d->fontlist_.begin();
1961 FontList::const_iterator end = d->fontlist_.end();
1962 for (; cit != end; ++cit) {
1963 if (cit->pos() >= pos) {
1964 if (pos >= beginOfBody())
1965 return FontSpan(max(start, beginOfBody()),
1968 return FontSpan(start,
1969 min(beginOfBody() - 1,
1972 start = cit->pos() + 1;
1975 // This should not happen, but if so, we take no chances.
1976 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1977 LASSERT(false, /**/);
1978 return FontSpan(pos, pos);
1982 // Gets uninstantiated font setting at position 0
1983 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1985 if (!empty() && !d->fontlist_.empty())
1986 return d->fontlist_.begin()->font();
1988 // Optimisation: avoid a full font instantiation if there is no
1989 // language change from previous call.
1990 static Font previous_font;
1991 static Language const * previous_lang = nullptr;
1992 if (bparams.language != previous_lang) {
1993 previous_lang = bparams.language;
1994 previous_font = Font(inherit_font, bparams.language);
1997 return previous_font;
2001 // Gets the fully instantiated font at a given position in a paragraph
2002 // This is basically the same function as TextMetrics::displayFont().
2003 // The difference is that this one is used for generating the LaTeX file,
2004 // and thus cosmetic "improvements" are disallowed: This has to deliver
2005 // the true picture of the buffer. (Asger)
2006 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
2007 Font const & outerfont) const
2011 Font font = getFontSettings(bparams, pos);
2013 pos_type const body_pos = beginOfBody();
2014 FontInfo & fi = font.fontInfo();
2016 fi.realize(d->layout_->labelfont);
2018 fi.realize(d->layout_->font);
2020 fi.realize(outerfont.fontInfo());
2021 fi.realize(bparams.getFont().fontInfo());
2027 Font const Paragraph::getLabelFont
2028 (BufferParams const & bparams, Font const & outerfont) const
2030 FontInfo tmpfont = d->layout_->labelfont;
2031 tmpfont.realize(outerfont.fontInfo());
2032 tmpfont.realize(bparams.getFont().fontInfo());
2033 return Font(tmpfont, getParLanguage(bparams));
2037 Font const Paragraph::getLayoutFont
2038 (BufferParams const & bparams, Font const & outerfont) const
2040 FontInfo tmpfont = d->layout_->font;
2041 tmpfont.realize(outerfont.fontInfo());
2042 tmpfont.realize(bparams.getFont().fontInfo());
2043 return Font(tmpfont, getParLanguage(bparams));
2047 char_type Paragraph::getUChar(BufferParams const & bparams,
2048 OutputParams const & rp,
2051 char_type c = d->text_[pos];
2053 // Return unchanged character in LTR languages
2054 // or if we use poylglossia/bidi (XeTeX)
2055 // or with babel and Xe/LuaTeX.
2056 if (!getFontSettings(bparams, pos).isRightToLeft()
2057 || rp.useBidiPackage()
2058 || (rp.use_babel && rp.isFullUnicode()))
2061 // Without polyglossia/bidi, we need to account for some special cases.
2062 // FIXME This needs to be audited!
2064 // * The input is as expected for all delimiters
2065 // => checked for Hebrew!
2066 // * The output matches the display in the LyX workarea
2067 // => checked for Hebrew!
2068 // * The special cases below are really necessary
2069 // => checked for Hebrew!
2070 // * In arabic_arabi, brackets are transformed to Arabic
2071 // Ornate Parentheses. Is this is really wanted?
2073 string const & lang = getFontSettings(bparams, pos).language()->lang();
2076 // 1. In the following languages, parentheses need to be reversed.
2077 // Also with polyglodia/luabidi
2078 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2080 // 2. In the following languages, brackets don't need to be reversed.
2081 bool const reversebrackets = lang != "arabic_arabtex"
2082 && lang != "arabic_arabi"
2085 // Now swap delimiters if needed.
2096 if (reversebrackets)
2100 if (reversebrackets)
2121 void Paragraph::setFont(pos_type pos, Font const & font)
2123 LASSERT(pos <= size(), return);
2125 // Text::setCharFont() already reduces font against layout/label
2126 // font, so we don't need to do that here. (Asger)
2127 d->fontlist_.set(pos, font);
2131 void Paragraph::makeSameLayout(Paragraph const & par)
2133 d->layout_ = par.d->layout_;
2134 d->params_ = par.d->params_;
2138 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2140 if (isFreeSpacing())
2146 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2147 if (eraseChar(pos, trackChanges))
2153 return count > 0 || pos > 0;
2157 bool Paragraph::hasSameLayout(Paragraph const & par) const
2159 return par.d->layout_ == d->layout_
2160 && d->params_.sameLayout(par.d->params_);
2164 depth_type Paragraph::getDepth() const
2166 return d->params_.depth();
2170 depth_type Paragraph::getMaxDepthAfter() const
2172 if (d->layout_->isEnvironment())
2173 return d->params_.depth() + 1;
2175 return d->params_.depth();
2179 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2181 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2182 return getDefaultAlign(bparams);
2184 return d->params_.align();
2188 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2190 LyXAlignment res = layout().align;
2191 if (isRTL(bparams)) {
2193 if (res == LYX_ALIGN_LEFT)
2194 res = LYX_ALIGN_RIGHT;
2195 else if (res == LYX_ALIGN_RIGHT)
2196 res = LYX_ALIGN_LEFT;
2202 docstring const & Paragraph::labelString() const
2204 return d->params_.labelString();
2208 // the next two functions are for the manual labels
2209 docstring const Paragraph::getLabelWidthString() const
2211 if (d->layout_->margintype == MARGIN_MANUAL
2212 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2213 return d->params_.labelWidthString();
2215 return _("Senseless with this layout!");
2219 void Paragraph::setLabelWidthString(docstring const & s)
2221 d->params_.labelWidthString(s);
2225 docstring Paragraph::expandLabel(Layout const & layout,
2226 BufferParams const & bparams) const
2228 return expandParagraphLabel(layout, bparams, true);
2232 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2233 BufferParams const & bparams, bool process_appendix) const
2235 DocumentClass const & tclass = bparams.documentClass();
2236 string const & lang = getParLanguage(bparams)->code();
2237 bool const in_appendix = process_appendix && d->params_.appendix();
2238 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2240 if (fmt.empty() && !layout.counter.empty())
2241 return tclass.counters().theCounter(layout.counter, lang);
2243 // handle 'inherited level parts' in 'fmt',
2244 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2245 size_t const i = fmt.find('@', 0);
2246 if (i != docstring::npos) {
2247 size_t const j = fmt.find('@', i + 1);
2248 if (j != docstring::npos) {
2249 docstring parent(fmt, i + 1, j - i - 1);
2250 docstring label = from_ascii("??");
2251 if (tclass.hasLayout(parent))
2252 label = expandParagraphLabel(tclass[parent], bparams,
2254 fmt = docstring(fmt, 0, i) + label
2255 + docstring(fmt, j + 1, docstring::npos);
2259 return tclass.counters().counterLabel(fmt, lang);
2263 void Paragraph::applyLayout(Layout const & new_layout)
2265 d->layout_ = &new_layout;
2266 LyXAlignment const oldAlign = d->params_.align();
2268 if (!(oldAlign & d->layout_->alignpossible)) {
2269 frontend::Alert::warning(_("Alignment not permitted"),
2270 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2271 d->params_.align(LYX_ALIGN_LAYOUT);
2276 pos_type Paragraph::beginOfBody() const
2278 return d->begin_of_body_;
2282 void Paragraph::setBeginOfBody()
2284 if (d->layout_->labeltype != LABEL_MANUAL) {
2285 d->begin_of_body_ = 0;
2289 // Unroll the first two cycles of the loop
2290 // and remember the previous character to
2291 // remove unnecessary getChar() calls
2293 pos_type end = size();
2294 bool prev_char_deleted = false;
2295 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2298 char_type previous_char = d->text_[i];
2299 if (!(isNewline(i) || isEnvSeparator(i))) {
2301 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2302 char_type temp = d->text_[i];
2303 prev_char_deleted = isDeleted(i);
2304 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2307 previous_char = temp;
2313 d->begin_of_body_ = i;
2317 bool Paragraph::allowParagraphCustomization() const
2319 return inInset().allowParagraphCustomization();
2323 bool Paragraph::usePlainLayout() const
2325 return inInset().usePlainLayout();
2329 bool Paragraph::isPassThru() const
2331 return inInset().isPassThru() || d->layout_->pass_thru;
2335 bool Paragraph::parbreakIsNewline() const
2337 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2341 bool Paragraph::isPartOfTextSequence() const
2343 for (pos_type i = 0; i < size(); ++i) {
2344 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2352 // paragraphs inside floats need different alignment tags to avoid
2355 bool noTrivlistCentering(InsetCode code)
2357 return code == FLOAT_CODE
2358 || code == WRAP_CODE
2359 || code == CELL_CODE;
2363 string correction(string const & orig)
2365 if (orig == "flushleft")
2366 return "raggedright";
2367 if (orig == "flushright")
2368 return "raggedleft";
2369 if (orig == "center")
2375 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2376 InsetCode code, bool const lastpar, int & col)
2378 string macro = suffix + "{";
2379 if (noTrivlistCentering(code)) {
2381 // the last paragraph in non-trivlist-aligned
2382 // context is special (to avoid unwanted whitespace)
2383 if (suffix == "\\begin") {
2384 macro = "\\" + correction(env) + "{}";
2385 os << from_ascii(macro);
2386 col += macro.size();
2391 macro += correction(env);
2395 if (suffix == "\\par\\end") {
2399 os << from_ascii(macro);
2400 col += macro.size();
2401 if (suffix == "\\begin") {
2411 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2412 otexstream & os, OutputParams const & runparams) const
2417 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2418 (layout_->toggle_indent != ITOGGLE_NEVER) :
2419 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2421 LyXAlignment const curAlign = params_.align();
2423 // Do not output \\noindent for paragraphs
2424 // 1. that cannot have indentation or are indented always,
2425 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2426 // 3. that are PassThru,
2427 // 4. or that are centered.
2428 if (canindent && params_.noindent()
2429 && owner_->isPartOfTextSequence()
2430 && !layout_->pass_thru
2431 && curAlign != LYX_ALIGN_CENTER) {
2432 if (!owner_->empty()
2433 && owner_->getInset(0)
2434 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2435 // If the paragraph starts with a vspace, the \\noindent
2436 // needs to come after that (as it leaves vmode).
2437 // If the paragraph consists only of the vspace,
2438 // \\noindent is not needed at all.
2439 runparams.need_noindent = owner_->size() > 1;
2441 os << "\\noindent" << termcmd;
2446 if (curAlign == layout_->align)
2450 case LYX_ALIGN_NONE:
2451 case LYX_ALIGN_BLOCK:
2452 case LYX_ALIGN_LAYOUT:
2453 case LYX_ALIGN_SPECIAL:
2454 case LYX_ALIGN_DECIMAL:
2456 case LYX_ALIGN_LEFT:
2457 case LYX_ALIGN_RIGHT:
2458 case LYX_ALIGN_CENTER:
2459 if (runparams.moving_arg) {
2466 string const begin_tag = "\\begin";
2467 InsetCode code = ownerCode();
2468 bool const lastpar = runparams.isLastPar;
2469 // RTL in classic (PDF)LaTeX (without the Bidi package)
2470 // Luabibdi (used by LuaTeX) behaves like classic
2471 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2472 && !runparams.useBidiPackage();
2475 case LYX_ALIGN_NONE:
2476 case LYX_ALIGN_BLOCK:
2477 case LYX_ALIGN_LAYOUT:
2478 case LYX_ALIGN_SPECIAL:
2479 case LYX_ALIGN_DECIMAL:
2481 case LYX_ALIGN_LEFT: {
2483 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2484 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2486 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2488 } case LYX_ALIGN_RIGHT: {
2490 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2491 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2493 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2495 } case LYX_ALIGN_CENTER: {
2496 corrected_env(os, begin_tag, "center", code, lastpar, column);
2505 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2506 otexstream & os, OutputParams const & runparams) const
2508 LyXAlignment const curAlign = params_.align();
2510 if (curAlign == layout_->align)
2514 case LYX_ALIGN_NONE:
2515 case LYX_ALIGN_BLOCK:
2516 case LYX_ALIGN_LAYOUT:
2517 case LYX_ALIGN_SPECIAL:
2518 case LYX_ALIGN_DECIMAL:
2520 case LYX_ALIGN_LEFT:
2521 case LYX_ALIGN_RIGHT:
2522 case LYX_ALIGN_CENTER:
2523 if (runparams.moving_arg)
2528 bool output = false;
2530 string const end_tag = "\\par\\end";
2531 InsetCode code = ownerCode();
2532 bool const lastpar = runparams.isLastPar;
2533 // RTL in classic (PDF)LaTeX (without the Bidi package)
2534 // Luabibdi (used by LuaTeX) behaves like classic
2535 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2536 && !runparams.useBidiPackage();
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: {
2547 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2548 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2550 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2552 } case LYX_ALIGN_RIGHT: {
2554 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2555 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2557 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2559 } case LYX_ALIGN_CENTER: {
2560 corrected_env(os, end_tag, "center", code, lastpar, col);
2565 return output || lastpar;
2569 // This one spits out the text of the paragraph
2570 void Paragraph::latex(BufferParams const & bparams,
2571 Font const & outerfont,
2573 OutputParams const & runparams,
2574 int start_pos, int end_pos, bool force) const
2576 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2578 // FIXME This check should not be needed. Perhaps issue an
2579 // error if it triggers.
2580 Layout const & style = inInset().forcePlainLayout() ?
2581 bparams.documentClass().plainLayout() : *d->layout_;
2583 if (!force && style.inpreamble)
2586 bool const allowcust = allowParagraphCustomization();
2588 // Current base font for all inherited font changes, without any
2589 // change caused by an individual character, except for the language:
2590 // It is set to the language of the first character.
2591 // As long as we are in the label, this font is the base font of the
2592 // label. Before the first body character it is set to the base font
2596 // If there is an open font-encoding changing command (script wrapper),
2597 // alien_script is set to its name
2598 string alien_script;
2601 // Maybe we have to create a optional argument.
2602 pos_type body_pos = beginOfBody();
2603 unsigned int column = 0;
2605 // If we are inside an non inheritFont() inset,
2606 // the outerfont is the buffer's main font
2607 Font const real_outerfont =
2608 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2611 // the optional argument is kept in curly brackets in
2612 // case it contains a ']'
2613 // This is not strictly needed, but if this is changed it
2614 // would be a file format change, and tex2lyx would need
2615 // to be adjusted, since it unconditionally removes the
2616 // braces when it parses \item.
2619 basefont = getLabelFont(bparams, real_outerfont);
2621 basefont = getLayoutFont(bparams, real_outerfont);
2624 // Which font is currently active?
2625 Font running_font(basefont);
2626 // Do we have an open font change?
2627 bool open_font = false;
2629 Change runningChange =
2630 runparams.inDeletedInset && !inInset().canTrackChanges()
2631 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2633 Encoding const * const prev_encoding = runparams.encoding;
2635 os.texrow().start(id(), 0);
2637 // if the paragraph is empty, the loop will not be entered at all
2639 // For InTitle commands, we have already opened a group
2640 // in output_latex::TeXOnePar.
2641 if (style.isCommand() && !style.intitle) {
2645 if (!style.leftdelim().empty()) {
2646 os << style.leftdelim();
2647 column += style.leftdelim().size();
2650 column += d->startTeXParParams(bparams, os, runparams);
2653 // Whether a \par can be issued for insets typeset inline with text.
2654 // Yes if greater than 0. This has to be static.
2655 THREAD_LOCAL_STATIC int parInline = 0;
2657 for (pos_type i = 0; i < size(); ++i) {
2658 // First char in paragraph or after label?
2659 if (i == body_pos) {
2662 bool needPar = false;
2663 column += running_font.latexWriteEndChanges(
2664 os, bparams, runparams,
2665 basefont, basefont, needPar);
2668 basefont = getLayoutFont(bparams, real_outerfont);
2669 running_font = basefont;
2671 column += Changes::latexMarkChange(os, bparams,
2672 runningChange, Change(Change::UNCHANGED),
2674 runningChange = Change(Change::UNCHANGED);
2676 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2679 // For InTitle commands, we have already opened a group
2680 // in output_latex::TeXOnePar.
2681 if (style.isCommand() && !style.intitle) {
2686 if (!style.leftdelim().empty()) {
2687 os << style.leftdelim();
2688 column += style.leftdelim().size();
2692 column += d->startTeXParParams(bparams, os,
2696 runparams.wasDisplayMath = runparams.inDisplayMath;
2697 runparams.inDisplayMath = false;
2698 bool deleted_display_math = false;
2699 Change const & change = runparams.inDeletedInset
2700 ? runparams.changeOfDeletedInset : lookupChange(i);
2702 char_type const c = d->text_[i];
2704 // Check whether a display math inset follows
2705 bool output_changes;
2706 if (!runparams.find_effective())
2707 output_changes = bparams.output_changes;
2709 output_changes = runparams.find_with_deleted();
2711 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2713 runparams.ctObject = getInset(i)->getCtObject(runparams);
2715 InsetMath const * im = getInset(i)->asInsetMath();
2716 if (im && im->asHullInset()
2717 && im->asHullInset()->outerDisplay()) {
2718 runparams.inDisplayMath = true;
2719 // runparams.inDeletedInset will be set by
2720 // latexInset later, but we need this info
2721 // before it is called. On the other hand, we
2722 // cannot set it here because it is a counter.
2723 deleted_display_math = isDeleted(i);
2725 if (output_changes && deleted_display_math
2726 && runningChange == change
2727 && change.type == Change::DELETED
2728 && !os.afterParbreak()) {
2729 // A display math in the same paragraph follows.
2730 // We have to close and then reopen \lyxdeleted,
2731 // otherwise the math will be shifted up.
2732 OutputParams rp = runparams;
2734 bool needPar = false;
2735 column += running_font.latexWriteEndChanges(
2736 os, bparams, rp, basefont,
2740 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2741 : getLayoutFont(bparams, real_outerfont);
2742 running_font = basefont;
2743 column += Changes::latexMarkChange(os, bparams,
2744 Change(Change::INSERTED), change, rp);
2748 if (output_changes && runningChange != change) {
2749 if (!alien_script.empty()) {
2752 alien_script.clear();
2755 bool needPar = false;
2756 column += running_font.latexWriteEndChanges(
2757 os, bparams, runparams,
2758 basefont, basefont, needPar);
2761 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2762 : getLayoutFont(bparams, real_outerfont);
2763 running_font = basefont;
2764 column += Changes::latexMarkChange(os, bparams, runningChange,
2766 runningChange = change;
2769 // do not output text which is marked deleted
2770 // if change tracking output is disabled
2771 if (!output_changes && change.deleted()) {
2777 // Fully instantiated font
2778 Font current_font = getFont(bparams, i, outerfont);
2780 Font const prev_font = (i > 0) ?
2781 getFont(bparams, i - 1, outerfont)
2784 Font const last_font = running_font;
2785 bool const in_ct_deletion = (output_changes
2786 && runningChange == change
2787 && change.type == Change::DELETED
2788 && !os.afterParbreak());
2789 // Insets where font switches are used (rather than font commands)
2790 bool const fontswitch_inset =
2793 && getInset(i)->allowMultiPar()
2794 && getInset(i)->lyxCode() != ERT_CODE
2795 && (getInset(i)->producesOutput()
2796 // FIXME Something more general?
2797 // Comments do not "produce output" but are still
2798 // part of the TeX source and require font switches
2799 // to be closed (otherwise LaTeX fails).
2800 || getInset(i)->layoutName() == "Note:Comment");
2802 bool closeLanguage = false;
2803 bool lang_switched_at_inset = false;
2804 if (fontswitch_inset) {
2805 // Some insets cannot be inside a font change command.
2806 // However, even such insets *can* be placed in \L or \R
2807 // or their equivalents (for RTL language switches),
2808 // so we don't close the language in those cases
2809 // (= differing isRightToLeft()).
2810 // ArabTeX, though, doesn't seem to handle this special behavior.
2811 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2812 || basefont.language()->lang() == "arabic_arabtex"
2813 || current_font.language()->lang() == "arabic_arabtex";
2814 // We need to check prev_font as language changes directly at inset
2815 // will only be started inside the inset.
2816 lang_switched_at_inset = prev_font.language() != current_font.language();
2819 // Do we need to close the previous font?
2820 bool langClosed = false;
2822 ((current_font != running_font
2823 || current_font.language() != running_font.language())
2824 || (fontswitch_inset
2825 && (current_font == prev_font))))
2827 // ensure there is no open script-wrapper
2828 if (!alien_script.empty()) {
2831 alien_script.clear();
2833 if (in_ct_deletion) {
2834 // We have to close and then reopen \lyxdeleted,
2835 // as strikeout needs to be on lowest level.
2839 if (closeLanguage) {
2840 // Force language closing
2841 current_font.setLanguage(basefont.language());
2844 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2845 bool needPar = false;
2846 column += running_font.latexWriteEndChanges(
2847 os, bparams, runparams, basefont,
2849 if (in_ct_deletion) {
2850 // We have to close and then reopen \lyxdeleted,
2851 // as strikeout needs to be on lowest level.
2852 OutputParams rp = runparams;
2853 column += Changes::latexMarkChange(os, bparams,
2854 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2856 // Has the language been closed in the latexWriteEndChanges() call above?
2857 langClosed |= running_font.language() != basefont.language()
2858 && running_font.language() != nextfont.language()
2859 && (running_font.language()->encoding()->package() != Encoding::CJK);
2860 running_font = basefont;
2861 open_font &= !langClosed;
2864 // if necessary, close language environment before opening CJK
2865 string const running_lang = running_font.language()->babel();
2866 string const lang_end_command = lyxrc.language_command_end;
2867 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2868 && !running_lang.empty()
2869 && running_lang == openLanguageName()
2870 && current_font.language()->encoding()->package() == Encoding::CJK) {
2871 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2872 os << from_ascii(end_tag);
2873 column += end_tag.length();
2874 if (!languageStackEmpty())
2878 // Switch file encoding if necessary (and allowed)
2879 if ((!fontswitch_inset || closeLanguage)
2880 && !runparams.pass_thru && !style.pass_thru &&
2881 runparams.encoding->package() != Encoding::none &&
2882 current_font.language()->encoding()->package() != Encoding::none) {
2883 pair<bool, int> const enc_switch =
2884 switchEncoding(os.os(), bparams, runparams,
2885 *(current_font.language()->encoding()));
2886 if (enc_switch.first) {
2887 column += enc_switch.second;
2888 runparams.encoding = current_font.language()->encoding();
2892 // A display math inset inside an ulem command will be output
2893 // as a box of width \linewidth, so we have to either disable
2894 // indentation if the inset starts a paragraph, or start a new
2895 // line to accommodate such box. This has to be done before
2896 // writing any font changing commands.
2897 if (runparams.inDisplayMath && !deleted_display_math
2898 && runparams.inulemcmd) {
2899 if (os.afterParbreak())
2905 // Do we need to change font?
2906 if ((current_font != running_font ||
2907 current_font.language() != running_font.language())
2908 && i != body_pos - 1)
2910 if (!fontswitch_inset) {
2911 if (in_ct_deletion) {
2912 // We have to close and then reopen \lyxdeleted,
2913 // as strikeout needs to be on lowest level.
2914 OutputParams rp = runparams;
2915 bool needPar = false;
2916 column += running_font.latexWriteEndChanges(
2917 os, bparams, rp, basefont,
2922 otexstringstream ots;
2923 InsetText const * textinset = inInset().asInsetText();
2924 bool const cprotect = textinset
2925 ? textinset->hasCProtectContent(runparams.moving_arg)
2926 && !textinset->text().isMainText()
2927 && inInset().lyxCode() != BRANCH_CODE
2929 column += current_font.latexWriteStartChanges(ots, bparams,
2930 runparams, basefont, last_font, false,
2932 // Check again for display math in ulem commands as a
2933 // font change may also occur just before a math inset.
2934 if (runparams.inDisplayMath && !deleted_display_math
2935 && runparams.inulemcmd) {
2936 if (os.afterParbreak())
2941 running_font = current_font;
2943 docstring fontchange = ots.str();
2945 // check whether the fontchange ends with a \\textcolor
2946 // modifier and the text starts with a space. If so we
2947 // need to add } in order to prevent \\textcolor from gobbling
2948 // the space (bug 4473).
2949 docstring const last_modifier = rsplit(fontchange, '\\');
2950 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2951 os << from_ascii("{}");
2952 else if (ots.terminateCommand())
2954 if (in_ct_deletion) {
2955 // We have to close and then reopen \lyxdeleted,
2956 // as strikeout needs to be on lowest level.
2957 OutputParams rp = runparams;
2958 column += Changes::latexMarkChange(os, bparams,
2959 Change(Change::UNCHANGED), change, rp);
2961 } else {// if fontswitch_inset
2962 if (current_font != running_font || !langClosed)
2963 // font is still open in fontswitch_insets if we have
2964 // a non-lang font difference or if the language
2965 // is the only difference but has not been forcedly
2968 running_font = current_font;
2972 // FIXME: think about end_pos implementation...
2973 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2974 // FIXME: integrate this case in latexSpecialChar
2975 // Do not print the separation of the optional argument
2976 // if style.pass_thru is false. This works because
2977 // latexSpecialChar ignores spaces if
2978 // style.pass_thru is false.
2979 if (i != body_pos - 1) {
2980 if (d->simpleTeXBlanks(bparams, runparams, os,
2981 i, column, current_font, style)) {
2982 // A surrogate pair was output. We
2983 // must not call latexSpecialChar
2984 // in this iteration, since it would output
2985 // the combining character again.
2992 OutputParams rp = runparams;
2993 rp.free_spacing = style.free_spacing;
2994 rp.local_font = ¤t_font;
2995 rp.intitle = style.intitle;
2997 // Two major modes: LaTeX or plain
2998 // Handle here those cases common to both modes
2999 // and then split to handle the two modes separately.
3000 if (c == META_INSET) {
3001 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3002 // Greyedout notes and, in general, all insets
3003 // with InsetLayout::isDisplay() == false,
3004 // are typeset inline with the text. So, we
3005 // can add a \par to the last paragraph of
3006 // such insets only if nothing else follows.
3007 bool incremented = false;
3008 Inset const * inset = getInset(i);
3009 InsetText const * textinset = inset
3010 ? inset->asInsetText()
3012 if (i + 1 == size() && textinset
3013 && !inset->getLayout().isDisplay()) {
3014 ParagraphList const & pars =
3015 textinset->text().paragraphs();
3016 pit_type const pit = pars.size() - 1;
3017 Font const lastfont =
3018 pit < 0 || pars[pit].empty()
3019 ? pars[pit].getLayoutFont(
3022 : pars[pit].getFont(bparams,
3023 pars[pit].size() - 1,
3025 if (lastfont.fontInfo().size() !=
3026 basefont.fontInfo().size()) {
3031 // We need to restore parts of this after insets with
3032 // allowMultiPar() true
3033 Font const save_basefont = basefont;
3034 d->latexInset(bparams, os, rp, running_font,
3035 basefont, real_outerfont, open_font,
3036 runningChange, style, i, column, fontswitch_inset,
3037 closeLanguage, (lang_switched_at_inset || langClosed));
3038 if (fontswitch_inset) {
3040 bool needPar = false;
3041 column += running_font.latexWriteEndChanges(
3042 os, bparams, runparams,
3043 basefont, basefont, needPar);
3046 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3047 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3048 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3053 if (runparams.ctObject == CtObject::DisplayObject
3054 || runparams.ctObject == CtObject::UDisplayObject) {
3055 // Close \lyx*deleted and force its
3056 // reopening (if needed)
3059 runningChange = Change(Change::UNCHANGED);
3060 runparams.ctObject = CtObject::Normal;
3063 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3064 if (!bparams.useNonTeXFonts)
3065 script = Encodings::isKnownScriptChar(c);
3066 if (script != alien_script) {
3067 if (!alien_script.empty()) {
3069 alien_script.clear();
3071 string fontenc = running_font.language()->fontenc(bparams);
3073 && !Encodings::fontencSupportsScript(fontenc, script)) {
3074 column += script.length() + 2;
3075 os << "\\" << script << "{";
3076 alien_script = script;
3080 d->latexSpecialChar(os, bparams, rp, running_font,
3081 alien_script, style, i, end_pos, column);
3082 } catch (EncodingException & e) {
3083 if (runparams.dryrun) {
3084 os << "<" << _("LyX Warning: ")
3085 << _("uncodable character") << " '";
3089 // add location information and throw again.
3097 // Set the encoding to that returned from latexSpecialChar (see
3098 // comment for encoding member in OutputParams.h)
3099 runparams.encoding = rp.encoding;
3101 // Also carry on the info on a closed ulem command for insets
3102 // such as Note that do not produce any output, so that no
3103 // command is ever executed but its opening was recorded.
3104 runparams.inulemcmd = rp.inulemcmd;
3106 // These need to be passed upstream as well
3107 runparams.need_maketitle = rp.need_maketitle;
3108 runparams.have_maketitle = rp.have_maketitle;
3110 // And finally, pass the post_macros upstream
3111 runparams.post_macro = rp.post_macro;
3114 // Close wrapper for alien script
3115 if (!alien_script.empty()) {
3117 alien_script.clear();
3120 Font const font = empty()
3121 ? getLayoutFont(bparams, real_outerfont)
3122 : getFont(bparams, size() - 1, real_outerfont);
3124 InsetText const * textinset = inInset().asInsetText();
3126 bool const maintext = textinset
3127 ? textinset->text().isMainText()
3130 size_t const numpars = textinset
3131 ? textinset->text().paragraphs().size()
3134 bool needPar = false;
3136 if (style.resfont.size() != font.fontInfo().size()
3137 && (!runparams.isLastPar || maintext
3138 || (numpars > 1 && d->ownerCode() != CELL_CODE
3139 && (inInset().getLayout().isDisplay()
3141 && !style.isCommand()) {
3145 // If we have an open font definition, we have to close it
3147 // Make sure that \\par is done with the font of the last
3148 // character if this has another size as the default.
3149 // This is necessary because LaTeX (and LyX on the screen)
3150 // calculates the space between the baselines according
3151 // to this font. (Matthias)
3153 // We must not change the font for the last paragraph
3154 // of non-multipar insets, tabular cells or commands,
3155 // since this produces unwanted whitespace.
3156 #ifdef FIXED_LANGUAGE_END_DETECTION
3158 running_font.latexWriteEndChanges(os, bparams,
3159 runparams, basefont,
3160 next_->getFont(bparams, 0, outerfont),
3163 running_font.latexWriteEndChanges(os, bparams,
3164 runparams, basefont, basefont, needPar);
3167 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3168 //FIXME: there as we start another \selectlanguage with the next paragraph if
3169 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3170 running_font.latexWriteEndChanges(os, bparams, runparams,
3171 basefont, basefont, needPar);
3175 // The \par could not be inserted at the same nesting
3176 // level of the font size change, so do it now.
3177 os << "{\\" << font.latexSize() << "\\par}";
3180 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3181 column += Changes::latexMarkChange(os, bparams, runningChange,
3182 Change(Change::UNCHANGED), runparams);
3184 // Needed if there is an optional argument but no contents.
3185 if (body_pos > 0 && body_pos == size()) {
3189 if (!style.rightdelim().empty()) {
3190 os << style.rightdelim();
3191 column += style.rightdelim().size();
3194 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3195 && runparams.encoding != prev_encoding) {
3196 runparams.encoding = prev_encoding;
3197 os << setEncoding(prev_encoding->iconvName());
3200 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3204 bool Paragraph::emptyTag() const
3206 for (pos_type i = 0; i < size(); ++i) {
3207 if (Inset const * inset = getInset(i)) {
3208 InsetCode lyx_code = inset->lyxCode();
3209 // FIXME testing like that is wrong. What is
3211 if (lyx_code != TOC_CODE &&
3212 lyx_code != INCLUDE_CODE &&
3213 lyx_code != GRAPHICS_CODE &&
3214 lyx_code != ERT_CODE &&
3215 lyx_code != LISTINGS_CODE &&
3216 lyx_code != FLOAT_CODE &&
3217 lyx_code != TABULAR_CODE) {
3221 char_type c = d->text_[i];
3222 if (c != ' ' && c != '\t')
3230 string Paragraph::getID(Buffer const &, OutputParams const &)
3233 for (pos_type i = 0; i < size(); ++i) {
3234 if (Inset const * inset = getInset(i)) {
3235 InsetCode lyx_code = inset->lyxCode();
3236 if (lyx_code == LABEL_CODE) {
3237 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3238 docstring const & id = il->getParam("name");
3239 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3247 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3250 for (i = 0; i < size(); ++i) {
3251 if (Inset const * inset = getInset(i)) {
3252 inset->docbook(xs, runparams);
3254 char_type c = d->text_[i];
3264 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3268 for (i = 0; i < size(); ++i) {
3269 if (Inset const * inset = getInset(i)) {
3270 inset->xhtml(xs, runparams);
3272 char_type c = d->text_[i];
3282 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3285 pos_type size = text_.size();
3286 for (pos_type i = initial; i < size; ++i) {
3287 Font font = owner_->getFont(buf.params(), i, outerfont);
3288 if (text_[i] == META_INSET)
3290 if (i != initial && font != font_old)
3301 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3302 vector<xml::EndFontTag> & tagsToClose,
3303 bool & flag, FontState curstate, xml::FontTypes type)
3305 if (curstate == FONT_ON) {
3306 tagsToOpen.push_back(docbookStartFontTag(type));
3309 tagsToClose.push_back(docbookEndFontTag(type));
3314 class OptionalFontType {
3319 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3320 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3323 OptionalFontType fontShapeToXml(FontShape fs)
3327 return {xml::FT_ITALIC};
3329 return {xml::FT_SLANTED};
3330 case SMALLCAPS_SHAPE:
3331 return {xml::FT_SMALLCAPS};
3336 // the other tags are for internal use
3342 OptionalFontType fontFamilyToXml(FontFamily fm)
3346 return {xml::FT_ROMAN};
3348 return {xml::FT_SANS};
3349 case TYPEWRITER_FAMILY:
3350 return {xml::FT_TYPE};
3351 case INHERIT_FAMILY:
3354 // the other tags are for internal use
3360 OptionalFontType fontSizeToXml(FontSize fs)
3364 return {xml::FT_SIZE_TINY};
3366 return {xml::FT_SIZE_SCRIPT};
3368 return {xml::FT_SIZE_FOOTNOTE};
3370 return {xml::FT_SIZE_SMALL};
3372 return {xml::FT_SIZE_LARGE};
3374 return {xml::FT_SIZE_LARGER};
3376 return {xml::FT_SIZE_LARGEST};
3378 return {xml::FT_SIZE_HUGE};
3380 return {xml::FT_SIZE_HUGER};
3382 return {xml::FT_SIZE_INCREASE};
3384 return {xml::FT_SIZE_DECREASE};
3389 // the other tags are for internal use
3395 struct DocBookFontState
3397 FontShape curr_fs = INHERIT_SHAPE;
3398 FontFamily curr_fam = INHERIT_FAMILY;
3399 FontSize curr_size = INHERIT_SIZE;
3401 // track whether we have opened these tags
3402 bool emph_flag = false;
3403 bool bold_flag = false;
3404 bool noun_flag = false;
3405 bool ubar_flag = false;
3406 bool dbar_flag = false;
3407 bool sout_flag = false;
3408 bool xout_flag = false;
3409 bool wave_flag = false;
3411 bool shap_flag = false;
3413 bool faml_flag = false;
3415 bool size_flag = false;
3418 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3420 std::string const & default_family,
3421 DocBookFontState & fs)
3423 vector<xml::FontTag> tagsToOpen;
3424 vector<xml::EndFontTag> tagsToClose;
3427 FontState curstate = font.fontInfo().emph();
3428 if (font_old.emph() != curstate)
3429 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3432 curstate = font.fontInfo().noun();
3433 if (font_old.noun() != curstate)
3434 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3437 curstate = font.fontInfo().underbar();
3438 if (font_old.underbar() != curstate)
3439 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3442 curstate = font.fontInfo().strikeout();
3443 if (font_old.strikeout() != curstate)
3444 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3447 curstate = font.fontInfo().xout();
3448 if (font_old.xout() != curstate)
3449 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3452 curstate = font.fontInfo().uuline();
3453 if (font_old.uuline() != curstate)
3454 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3457 curstate = font.fontInfo().uwave();
3458 if (font_old.uwave() != curstate)
3459 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3462 // a little hackish, but allows us to reuse what we have.
3463 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3464 if (font_old.series() != font.fontInfo().series())
3465 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3468 fs.curr_fs = font.fontInfo().shape();
3469 FontShape old_fs = font_old.shape();
3470 if (old_fs != fs.curr_fs) {
3472 OptionalFontType tag = fontShapeToXml(old_fs);
3474 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3475 fs.shap_flag = false;
3478 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3480 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3484 fs.curr_fam = font.fontInfo().family();
3485 FontFamily old_fam = font_old.family();
3486 if (old_fam != fs.curr_fam) {
3488 OptionalFontType tag = fontFamilyToXml(old_fam);
3490 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3491 fs.faml_flag = false;
3493 switch (fs.curr_fam) {
3495 // we will treat a "default" font family as roman, since we have
3496 // no other idea what to do.
3497 if (default_family != "rmdefault" && default_family != "default") {
3498 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3499 fs.faml_flag = true;
3503 if (default_family != "sfdefault") {
3504 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3505 fs.faml_flag = true;
3508 case TYPEWRITER_FAMILY:
3509 if (default_family != "ttdefault") {
3510 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3511 fs.faml_flag = true;
3514 case INHERIT_FAMILY:
3517 // the other tags are for internal use
3524 fs.curr_size = font.fontInfo().size();
3525 FontSize old_size = font_old.size();
3526 if (old_size != fs.curr_size) {
3528 OptionalFontType tag = fontSizeToXml(old_size);
3530 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3531 fs.size_flag = false;
3534 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3535 if (tag.has_value) {
3536 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3537 fs.size_flag = true;
3541 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3544 } // anonymous namespace
3547 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3548 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3549 OutputParams const & runparams,
3550 Font const & outerfont,
3553 bool ignore_fonts) const
3555 // Return values: segregation of the content of this paragraph.
3556 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3557 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3558 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3560 // Internal string stream to store the output before being added to one of the previous lists.
3561 odocstringstream os;
3563 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3564 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3566 OutputParams rp = runparams;
3567 for (pos_type i = initial; i < size(); ++i) {
3568 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3569 const InsetArgument * arg = getInset(i)->asInsetArgument();
3570 if (arg->docbookargumentbeforemaintag()) {
3571 auto xs_local = XMLStream(os);
3572 arg->docbook(xs_local, rp);
3574 prependedParagraphs.push_back(os.str());
3575 os.str(from_ascii(""));
3577 rp.docbook_prepended_arguments.insert(arg);
3578 } else if (arg->docbookargumentaftermaintag()) {
3579 rp.docbook_appended_arguments.insert(arg);
3584 // State variables for the main loop.
3585 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3586 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3587 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3588 // This requires to store delayed characters at some point.
3590 // Track whether we have opened font tags
3591 DocBookFontState fs;
3592 DocBookFontState old_fs = fs;
3594 Layout const & style = *d->layout_;
3596 // Conversion of the font opening/closing into DocBook tags.
3597 vector<xml::FontTag> tagsToOpen;
3598 vector<xml::EndFontTag> tagsToClose;
3600 // Parsing main loop.
3601 for (pos_type i = initial; i < size(); ++i) {
3602 bool ignore_fonts_i = ignore_fonts
3603 || style.docbooknofontinside()
3604 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3606 // Don't show deleted material in the output.
3610 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3612 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3613 if (!ignore_fonts_i)
3614 xs->closeFontTags();
3616 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3617 generatedParagraphs.push_back(os.str());
3619 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3620 // that the string stream must be reset.
3621 os.str(from_ascii(""));
3623 xs = new XMLStream(os);
3625 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3626 if (!ignore_fonts_i) {
3631 // Determine which tags should be opened or closed regarding fonts.
3632 FontInfo const font_old = (i == 0 ?
3633 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3634 getFont(buf.masterBuffer()->params(), i - 1, outerfont).fontInfo());
3635 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3636 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3637 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3639 if (!ignore_fonts_i) {
3640 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3641 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3642 for (; cit != cen; ++cit)
3646 // Deal with the delayed characters *after* closing font tags.
3647 if (!delayedChars.empty()) {
3648 for (const docstring& c: delayedChars)
3649 *xs << XMLStream::ESCAPE_NONE << c;
3650 delayedChars.clear();
3653 if (!ignore_fonts_i) {
3654 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3655 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3656 for (; sit != sen; ++sit)
3659 tagsToClose.clear();
3663 // Finally, write the next character or inset.
3664 if (Inset const * inset = getInset(i)) {
3665 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3666 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3667 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3669 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3670 // Arguments may need to be output
3671 OutputParams np = rp;
3672 np.local_font = &font;
3674 // TODO: special case will bite here.
3675 np.docbook_in_par = true;
3676 inset->docbook(*xs, np);
3679 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3680 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3681 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3682 delayedChars.push_back(from_ascii(" "));
3684 delayedChars.emplace_back(1, c);
3686 } else { // No need to delay the character.
3687 if (c == '\'' && !ignore_fonts)
3688 *xs << XMLStream::ESCAPE_NONE << "’";
3695 // FIXME, this code is just imported from XHTML
3696 // I'm worried about what happens if a branch, say, is itself
3697 // wrapped in some font stuff. I think that will not work.
3699 xs->closeFontTags();
3701 // Deal with the delayed characters *after* closing font tags.
3702 if (!delayedChars.empty()) {
3703 for (const docstring &c: delayedChars)
3704 *xs << XMLStream::ESCAPE_NONE << c;
3705 delayedChars.clear();
3708 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3709 // last line to get a clean output.
3710 if (rp.docbook_in_listing && !is_last_par)
3713 // Finalise the last (and most likely only) paragraph.
3714 generatedParagraphs.push_back(os.str());
3715 os.str(from_ascii(""));
3718 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3719 for (pos_type i = initial; i < size(); ++i) {
3720 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3721 const InsetArgument * arg = getInset(i)->asInsetArgument();
3722 if (arg->docbookargumentaftermaintag()) {
3723 // Don't use rp, as this argument would not generate anything.
3724 auto xs_local = XMLStream(os);
3725 arg->docbook(xs_local, runparams);
3727 appendedParagraphs.push_back(os.str());
3728 os.str(from_ascii(""));
3733 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3739 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3740 vector<xml::EndFontTag> & tagsToClose,
3741 bool & flag, FontState curstate, xml::FontTypes type)
3743 if (curstate == FONT_ON) {
3744 tagsToOpen.push_back(xhtmlStartFontTag(type));
3747 tagsToClose.push_back(xhtmlEndFontTag(type));
3752 } // anonymous namespace
3755 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3757 OutputParams const & runparams,
3758 Font const & outerfont,
3759 bool start_paragraph, bool close_paragraph,
3760 pos_type initial) const
3764 // track whether we have opened these tags
3765 bool emph_flag = false;
3766 bool bold_flag = false;
3767 bool noun_flag = false;
3768 bool ubar_flag = false;
3769 bool dbar_flag = false;
3770 bool sout_flag = false;
3771 bool xout_flag = false;
3772 bool wave_flag = false;
3774 bool shap_flag = false;
3776 bool faml_flag = false;
3778 bool size_flag = false;
3780 Layout const & style = *d->layout_;
3782 if (start_paragraph)
3783 xs.startDivision(allowEmpty());
3786 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3788 FontShape curr_fs = INHERIT_SHAPE;
3789 FontFamily curr_fam = INHERIT_FAMILY;
3790 FontSize curr_size = INHERIT_SIZE;
3792 string const default_family =
3793 buf.masterBuffer()->params().fonts_default_family;
3795 vector<xml::FontTag> tagsToOpen;
3796 vector<xml::EndFontTag> tagsToClose;
3798 // parsing main loop
3799 for (pos_type i = initial; i < size(); ++i) {
3800 // let's not show deleted material in the output
3804 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3807 FontState curstate = font.fontInfo().emph();
3808 if (font_old.emph() != curstate)
3809 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3812 curstate = font.fontInfo().noun();
3813 if (font_old.noun() != curstate)
3814 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3817 curstate = font.fontInfo().underbar();
3818 if (font_old.underbar() != curstate)
3819 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3822 curstate = font.fontInfo().strikeout();
3823 if (font_old.strikeout() != curstate)
3824 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3827 curstate = font.fontInfo().xout();
3828 if (font_old.xout() != curstate)
3829 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3832 curstate = font.fontInfo().uuline();
3833 if (font_old.uuline() != curstate)
3834 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3837 curstate = font.fontInfo().uwave();
3838 if (font_old.uwave() != curstate)
3839 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3842 // a little hackish, but allows us to reuse what we have.
3843 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3844 if (font_old.series() != font.fontInfo().series())
3845 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3848 curr_fs = font.fontInfo().shape();
3849 FontShape old_fs = font_old.shape();
3850 if (old_fs != curr_fs) {
3854 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3857 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3859 case SMALLCAPS_SHAPE:
3860 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3866 // the other tags are for internal use
3874 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3878 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3881 case SMALLCAPS_SHAPE:
3882 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3889 // the other tags are for internal use
3896 curr_fam = font.fontInfo().family();
3897 FontFamily old_fam = font_old.family();
3898 if (old_fam != curr_fam) {
3902 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3905 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3907 case TYPEWRITER_FAMILY:
3908 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3910 case INHERIT_FAMILY:
3913 // the other tags are for internal use
3921 // we will treat a "default" font family as roman, since we have
3922 // no other idea what to do.
3923 if (default_family != "rmdefault" && default_family != "default") {
3924 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3929 if (default_family != "sfdefault") {
3930 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3934 case TYPEWRITER_FAMILY:
3935 if (default_family != "ttdefault") {
3936 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3940 case INHERIT_FAMILY:
3943 // the other tags are for internal use
3950 curr_size = font.fontInfo().size();
3951 FontSize old_size = font_old.size();
3952 if (old_size != curr_size) {
3956 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3959 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3962 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3965 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3968 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3971 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3974 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3977 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3980 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3983 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3986 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3992 // the other tags are for internal use
3998 switch (curr_size) {
4000 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4004 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4008 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4012 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4016 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4020 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4024 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4028 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4032 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4036 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4040 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4047 // the other tags are for internal use
4054 // Other such tags? What about the other text ranges?
4056 for (auto const & t : tagsToClose)
4058 for (auto const & t : tagsToOpen)
4060 tagsToClose.clear();
4063 Inset const * inset = getInset(i);
4065 if (!runparams.for_toc || inset->isInToc()) {
4066 OutputParams np = runparams;
4067 np.local_font = &font;
4068 // If the paragraph has size 1, then we are in the "special
4069 // case" where we do not output the containing paragraph info
4070 if (!inset->getLayout().htmlisblock() && size() != 1)
4071 np.html_in_par = true;
4072 retval += inset->xhtml(xs, np);
4075 char_type c = getUChar(buf.masterBuffer()->params(),
4077 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4078 xs << XMLStream::ESCAPE_NONE << " ";
4080 xs << XMLStream::ESCAPE_NONE << "’";
4084 font_old = font.fontInfo();
4088 // I'm worried about what happens if a branch, say, is itself
4089 // wrapped in some font stuff. I think that will not work.
4091 if (close_paragraph)
4098 bool Paragraph::isHfill(pos_type pos) const
4100 Inset const * inset = getInset(pos);
4101 return inset && inset->isHfill();
4105 bool Paragraph::isNewline(pos_type pos) const
4107 // U+2028 LINE SEPARATOR
4108 // U+2029 PARAGRAPH SEPARATOR
4109 char_type const c = d->text_[pos];
4110 if (c == 0x2028 || c == 0x2029)
4112 Inset const * inset = getInset(pos);
4113 return inset && inset->lyxCode() == NEWLINE_CODE;
4117 bool Paragraph::isEnvSeparator(pos_type pos) const
4119 Inset const * inset = getInset(pos);
4120 return inset && inset->lyxCode() == SEPARATOR_CODE;
4124 bool Paragraph::isLineSeparator(pos_type pos) const
4126 char_type const c = d->text_[pos];
4127 if (isLineSeparatorChar(c))
4129 Inset const * inset = getInset(pos);
4130 return inset && inset->isLineSeparator();
4134 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4138 if (ignore_deleted && isDeleted(pos))
4140 if (Inset const * inset = getInset(pos))
4141 return !inset->isLetter();
4142 // if we have a hard hyphen (no en- or emdash) or apostrophe
4143 // we pass this to the spell checker
4144 // FIXME: this method is subject to change, visit
4145 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4146 // to get an impression how complex this is.
4147 if (isHardHyphenOrApostrophe(pos))
4149 char_type const c = d->text_[pos];
4150 // We want to pass the escape chars to the spellchecker
4151 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4152 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4156 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4158 pos_type const psize = size();
4161 char_type const c = d->text_[pos];
4162 if (c != '-' && c != '\'')
4164 pos_type nextpos = pos + 1;
4165 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4166 if ((nextpos == psize || isSpace(nextpos))
4167 && (pos == 0 || isSpace(prevpos)))
4173 bool Paragraph::needsCProtection(bool const fragile) const
4175 // first check the layout of the paragraph, but only in insets
4176 InsetText const * textinset = inInset().asInsetText();
4177 bool const maintext = textinset
4178 ? textinset->text().isMainText()
4181 if (!maintext && layout().needcprotect) {
4182 // Environments need cprotection regardless the content
4183 if (layout().latextype == LATEX_ENVIRONMENT)
4186 // Commands need cprotection if they contain specific chars
4187 int const nchars_escape = 9;
4188 static char_type const chars_escape[nchars_escape] = {
4189 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4191 docstring const pars = asString();
4192 for (int k = 0; k < nchars_escape; k++) {
4193 if (contains(pars, chars_escape[k]))
4198 // now check whether we have insets that need cprotection
4199 for (auto const & icit : d->insetlist_) {
4200 Inset const * ins = icit.inset;
4203 if (ins->needsCProtection(maintext, fragile))
4211 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4213 return d->speller_state_.getRange(pos);
4217 bool Paragraph::isChar(pos_type pos) const
4219 if (Inset const * inset = getInset(pos))
4220 return inset->isChar();
4221 char_type const c = d->text_[pos];
4222 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4226 bool Paragraph::isSpace(pos_type pos) const
4228 if (Inset const * inset = getInset(pos))
4229 return inset->isSpace();
4230 char_type const c = d->text_[pos];
4231 return lyx::isSpace(c);
4236 Paragraph::getParLanguage(BufferParams const & bparams) const
4239 return getFirstFontSettings(bparams).language();
4240 // FIXME: we should check the prev par as well (Lgb)
4241 return bparams.language;
4245 bool Paragraph::isRTL(BufferParams const & bparams) const
4247 return getParLanguage(bparams)->rightToLeft()
4248 && !inInset().getLayout().forceLTR();
4252 void Paragraph::changeLanguage(BufferParams const & bparams,
4253 Language const * from, Language const * to)
4255 // change language including dummy font change at the end
4256 for (pos_type i = 0; i <= size(); ++i) {
4257 Font font = getFontSettings(bparams, i);
4258 if (font.language() == from) {
4259 font.setLanguage(to);
4261 d->requestSpellCheck(i);
4267 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4269 Language const * doc_language = bparams.language;
4270 for (auto const & f : d->fontlist_)
4271 if (f.font().language() != ignore_language &&
4272 f.font().language() != latex_language &&
4273 f.font().language() != doc_language)
4279 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4281 for (auto const & f : d->fontlist_) {
4282 Language const * lang = f.font().language();
4283 if (lang != ignore_language &&
4284 lang != latex_language)
4290 docstring Paragraph::asString(int options) const
4292 return asString(0, size(), options);
4296 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4298 odocstringstream os;
4301 && options & AS_STR_LABEL
4302 && !d->params_.labelString().empty())
4303 os << d->params_.labelString() << ' ';
4305 for (pos_type i = beg; i < end; ++i) {
4306 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4308 char_type const c = d->text_[i];
4309 if (isPrintable(c) || c == '\t'
4310 || (c == '\n' && (options & AS_STR_NEWLINES)))
4312 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4313 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4314 LASSERT(runparams != nullptr, return docstring());
4315 if (runparams->find_effective() && getInset(i)->hasToString())
4316 getInset(i)->toString(os);
4318 getInset(i)->plaintext(os, *runparams);
4319 } else if (c == META_INSET && (options & AS_STR_MATHED)
4320 && getInset(i)->lyxCode() == REF_CODE) {
4321 Buffer const & buf = getInset(i)->buffer();
4322 OutputParams rp(&buf.params().encoding());
4323 Font const font(inherit_font, buf.params().language);
4324 rp.local_font = &font;
4326 getInset(i)->latex(ots, rp);
4328 getInset(i)->toString(os);
4337 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4338 bool const shorten, bool const label) const
4340 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4341 if (label && !labelString().empty())
4342 os += labelString() + ' ';
4343 if (!layout().isTocCaption())
4345 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4348 char_type const c = d->text_[i];
4351 else if (c == META_INSET)
4352 getInset(i)->forOutliner(os, tmplen, false);
4355 Text::shortenForOutliner(os, maxlen);
4359 void Paragraph::setInsetOwner(Inset const * inset)
4361 d->inset_owner_ = inset;
4365 int Paragraph::id() const
4371 void Paragraph::setId(int id)
4377 Layout const & Paragraph::layout() const
4383 void Paragraph::setLayout(Layout const & layout)
4385 d->layout_ = &layout;
4389 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4391 setLayout(tc.defaultLayout());
4395 void Paragraph::setPlainLayout(DocumentClass const & tc)
4397 setLayout(tc.plainLayout());
4401 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4403 if (usePlainLayout())
4406 setDefaultLayout(tc);
4410 Inset const & Paragraph::inInset() const
4412 LBUFERR(d->inset_owner_);
4413 return *d->inset_owner_;
4417 ParagraphParameters & Paragraph::params()
4423 ParagraphParameters const & Paragraph::params() const
4429 bool Paragraph::isFreeSpacing() const
4431 if (d->layout_->free_spacing)
4433 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4437 bool Paragraph::allowEmpty() const
4439 if (d->layout_->keepempty)
4441 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4445 bool Paragraph::brokenBiblio() const
4447 // There is a problem if there is no bibitem at position 0 in
4448 // paragraphs that need one, if there is another bibitem in the
4449 // paragraph or if this paragraph is not supposed to have
4450 // a bibitem inset at all.
4451 return ((d->layout_->labeltype == LABEL_BIBLIO
4452 && (d->insetlist_.find(BIBITEM_CODE) != 0
4453 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4454 || (d->layout_->labeltype != LABEL_BIBLIO
4455 && d->insetlist_.find(BIBITEM_CODE) != -1));
4459 int Paragraph::fixBiblio(Buffer const & buffer)
4461 // FIXME: when there was already an inset at 0, the return value is 1,
4462 // which does not tell whether another inset has been removed; the
4463 // cursor cannot be correctly updated.
4465 bool const track_changes = buffer.params().track_changes;
4466 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4468 // The case where paragraph is not BIBLIO
4469 if (d->layout_->labeltype != LABEL_BIBLIO) {
4470 if (bibitem_pos == -1)
4471 // No InsetBibitem => OK
4473 // There is an InsetBibitem: remove it!
4474 d->insetlist_.release(bibitem_pos);
4475 eraseChar(bibitem_pos, track_changes);
4476 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4479 bool const hasbibitem0 = bibitem_pos == 0;
4481 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4482 // There was an InsetBibitem at pos 0,
4483 // and no other one => OK
4484 if (bibitem_pos == -1)
4486 // there is a bibitem at the 0 position, but since
4487 // there is a second one, we copy the second on the
4488 // first. We're assuming there are at most two of
4489 // these, which there should be.
4490 // FIXME: why does it make sense to do that rather
4491 // than keep the first? (JMarc)
4492 Inset * inset = releaseInset(bibitem_pos);
4493 d->insetlist_.begin()->inset = inset;
4494 // This needs to be done to update the counter (#8499)
4495 buffer.updateBuffer();
4496 return -bibitem_pos;
4499 // We need to create an inset at the beginning
4500 Inset * inset = nullptr;
4501 if (bibitem_pos > 0) {
4502 // there was one somewhere in the paragraph, let's move it
4503 inset = d->insetlist_.release(bibitem_pos);
4504 eraseChar(bibitem_pos, track_changes);
4507 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4508 InsetCommandParams(BIBITEM_CODE));
4510 Font font(inherit_font, buffer.params().language);
4511 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4512 : Change::UNCHANGED));
4514 // This is needed to get the counters right
4515 buffer.updateBuffer();
4520 void Paragraph::checkAuthors(AuthorList const & authorList)
4522 d->changes_.checkAuthors(authorList);
4526 bool Paragraph::isChanged(pos_type pos) const
4528 return lookupChange(pos).changed();
4532 bool Paragraph::isInserted(pos_type pos) const
4534 return lookupChange(pos).inserted();
4538 bool Paragraph::isDeleted(pos_type pos) const
4540 return lookupChange(pos).deleted();
4544 InsetList const & Paragraph::insetList() const
4546 return d->insetlist_;
4550 void Paragraph::setInsetBuffers(Buffer & b)
4552 d->insetlist_.setBuffer(b);
4556 void Paragraph::resetBuffer()
4558 d->insetlist_.resetBuffer();
4562 Inset * Paragraph::releaseInset(pos_type pos)
4564 Inset * inset = d->insetlist_.release(pos);
4565 /// does not honour change tracking!
4566 eraseChar(pos, false);
4571 Inset * Paragraph::getInset(pos_type pos)
4573 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4574 ? d->insetlist_.get(pos) : nullptr;
4578 Inset const * Paragraph::getInset(pos_type pos) const
4580 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4581 ? d->insetlist_.get(pos) : nullptr;
4585 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4586 pos_type & right, TextCase action)
4588 // process sequences of modified characters; in change
4589 // tracking mode, this approach results in much better
4590 // usability than changing case on a char-by-char basis
4591 // We also need to track the current font, since font
4592 // changes within sequences can occur.
4593 vector<pair<char_type, Font> > changes;
4595 bool const trackChanges = bparams.track_changes;
4597 bool capitalize = true;
4599 for (; pos < right; ++pos) {
4600 char_type oldChar = d->text_[pos];
4601 char_type newChar = oldChar;
4603 // ignore insets and don't play with deleted text!
4604 if (oldChar != META_INSET && !isDeleted(pos)) {
4606 case text_lowercase:
4607 newChar = lowercase(oldChar);
4609 case text_capitalization:
4611 newChar = uppercase(oldChar);
4615 case text_uppercase:
4616 newChar = uppercase(oldChar);
4621 if (isWordSeparator(pos) || isDeleted(pos)) {
4622 // permit capitalization again
4626 if (oldChar != newChar) {
4627 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4628 if (pos != right - 1)
4630 // step behind the changing area
4634 int erasePos = pos - changes.size();
4635 for (auto const & change : changes) {
4636 insertChar(pos, change.first, change.second, trackChanges);
4637 if (!eraseChar(erasePos, trackChanges)) {
4640 ++right; // expand selection
4647 int Paragraph::find(docstring const & str, bool cs, bool mw,
4648 pos_type start_pos, bool del) const
4650 pos_type pos = start_pos;
4651 int const strsize = str.length();
4653 pos_type const parsize = d->text_.size();
4654 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4655 // ignore deleted matter
4656 if (!del && isDeleted(pos)) {
4657 if (pos == parsize - 1)
4663 // Ignore "invisible" letters such as ligature breaks
4664 // and hyphenation chars while searching
4665 bool nonmatch = false;
4666 while (pos < parsize && isInset(pos)) {
4667 Inset const * inset = getInset(pos);
4668 if (!inset->isLetter() && !inset->isChar())
4670 odocstringstream os;
4671 if (inset->lyxCode() == lyx::QUOTE_CODE) {
4673 op.find_set_feature(OutputParams::SearchQuick);
4674 inset->plaintext(os, op);
4677 inset->toString(os);
4679 docstring const insetstring = os.str();
4680 if (!insetstring.empty()) {
4681 int const insetstringsize = insetstring.length();
4682 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4683 if ((cs && str[i] != insetstring[j])
4684 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4692 if (nonmatch || i == strsize)
4694 char_type dp = d->text_[pos];
4695 if (cs && str[i] != dp)
4697 if (!cs && uppercase(str[i]) != uppercase(dp))
4704 // if necessary, check whether string matches word
4706 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4709 && !isWordSeparator(pos))
4713 return pos - start_pos;
4717 char_type Paragraph::getChar(pos_type pos) const
4719 return d->text_[pos];
4723 pos_type Paragraph::size() const
4725 return d->text_.size();
4729 bool Paragraph::empty() const
4731 return d->text_.empty();
4735 bool Paragraph::isInset(pos_type pos) const
4737 return d->text_[pos] == META_INSET;
4741 bool Paragraph::isSeparator(pos_type pos) const
4743 //FIXME: Are we sure this can be the only separator?
4744 return d->text_[pos] == ' ';
4748 void Paragraph::deregisterWords()
4750 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4751 Private::LangWordsMap::const_iterator ite = d->words_.end();
4752 for (; itl != ite; ++itl) {
4753 WordList & wl = theWordList(itl->first);
4754 Private::Words::const_iterator it = (itl->second).begin();
4755 Private::Words::const_iterator et = (itl->second).end();
4756 for (; it != et; ++it)
4763 void Paragraph::locateWord(pos_type & from, pos_type & to,
4764 word_location const loc, bool const ignore_deleted) const
4767 case WHOLE_WORD_STRICT:
4768 if (from == 0 || from == size()
4769 || isWordSeparator(from, ignore_deleted)
4770 || isWordSeparator(from - 1, ignore_deleted)) {
4777 // If we are already at the beginning of a word, do nothing
4778 if (!from || isWordSeparator(from - 1, ignore_deleted))
4783 // always move the cursor to the beginning of previous word
4784 while (from && !isWordSeparator(from - 1, ignore_deleted))
4788 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4791 // no need to move the 'from' cursor
4795 while (to < size() && !isWordSeparator(to, ignore_deleted))
4800 void Paragraph::collectWords()
4802 for (pos_type pos = 0; pos < size(); ++pos) {
4803 if (isWordSeparator(pos))
4805 pos_type from = pos;
4806 locateWord(from, pos, WHOLE_WORD);
4807 // Work around MSVC warning: The statement
4808 // if (pos < from + lyxrc.completion_minlength)
4809 // triggers a signed vs. unsigned warning.
4810 // I don't know why this happens, it could be a MSVC bug, or
4811 // related to LLP64 (windows) vs. LP64 (unix) programming
4812 // model, or the C++ standard might be ambigous in the section
4813 // defining the "usual arithmetic conversions". However, using
4814 // a temporary variable is safe and works on all compilers.
4815 pos_type const endpos = from + lyxrc.completion_minlength;
4818 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4819 if (cit == d->fontlist_.end())
4821 Language const * lang = cit->font().language();
4822 docstring const word = asString(from, pos, AS_STR_NONE);
4823 d->words_[lang->lang()].insert(word);
4828 void Paragraph::registerWords()
4830 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4831 Private::LangWordsMap::const_iterator ite = d->words_.end();
4832 for (; itl != ite; ++itl) {
4833 WordList & wl = theWordList(itl->first);
4834 Private::Words::const_iterator it = (itl->second).begin();
4835 Private::Words::const_iterator et = (itl->second).end();
4836 for (; it != et; ++it)
4842 void Paragraph::updateWords()
4850 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4852 SkipPositionsIterator begin = skips.begin();
4853 SkipPositions::iterator end = skips.end();
4854 if (pos > 0 && begin < end) {
4856 if (end->last == pos - 1) {
4861 skips.insert(end, FontSpan(pos, pos));
4865 Language * Paragraph::Private::locateSpellRange(
4866 pos_type & from, pos_type & to,
4867 SkipPositions & skips) const
4869 // skip leading white space
4870 while (from < to && owner_->isWordSeparator(from))
4872 // don't check empty range
4875 // get current language
4876 Language * lang = getSpellLanguage(from);
4877 pos_type last = from;
4878 bool samelang = true;
4879 bool sameinset = true;
4880 while (last < to && samelang && sameinset) {
4881 // hop to end of word
4882 while (last < to && !owner_->isWordSeparator(last)) {
4883 Inset const * inset = owner_->getInset(last);
4884 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4885 // check for "invisible" letters such as ligature breaks
4886 odocstringstream os;
4887 inset->toString(os);
4888 if (os.str().length() != 0) {
4889 // avoid spell check of visible special char insets
4890 // stop the loop in front of the special char inset
4895 appendSkipPosition(skips, last);
4896 } else if (owner_->isDeleted(last)) {
4897 appendSkipPosition(skips, last);
4901 // hop to next word while checking for insets
4902 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4903 if (Inset const * inset = owner_->getInset(last))
4904 sameinset = inset->isChar() && inset->isLetter();
4905 if (sameinset && owner_->isDeleted(last)) {
4906 appendSkipPosition(skips, last);
4911 if (sameinset && last < to) {
4912 // now check for language change
4913 samelang = lang == getSpellLanguage(last);
4916 // if language change detected backstep is needed
4924 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4927 const_cast<Language *>(owner_->getFontSettings(
4928 inset_owner_->buffer().params(), from).language());
4929 if (lang == inset_owner_->buffer().params().language
4930 && !lyxrc.spellchecker_alt_lang.empty()) {
4932 string const lang_variety =
4933 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4934 lang->setCode(lang_code);
4935 lang->setVariety(lang_variety);
4941 void Paragraph::requestSpellCheck(pos_type pos)
4943 d->requestSpellCheck(pos);
4945 // Also request spellcheck within (text) insets
4946 for (auto const & insets : insetList()) {
4947 if (!insets.inset->asInsetText())
4949 ParagraphList & inset_pars =
4950 insets.inset->asInsetText()->paragraphs();
4951 ParagraphList::iterator pit = inset_pars.begin();
4952 ParagraphList::iterator pend = inset_pars.end();
4953 for (; pit != pend; ++pit)
4954 pit->requestSpellCheck();
4960 bool Paragraph::needsSpellCheck() const
4962 SpellChecker::ChangeNumber speller_change_number = 0;
4963 if (theSpellChecker())
4964 speller_change_number = theSpellChecker()->changeNumber();
4965 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4966 d->speller_state_.needsCompleteRefresh(speller_change_number);
4968 return d->needsSpellCheck();
4972 bool Paragraph::Private::ignoreWord(docstring const & word) const
4974 // Ignore words with digits
4975 // FIXME: make this customizable
4976 // (note that some checkers ignore words with digits by default)
4977 docstring::const_iterator cit = word.begin();
4978 docstring::const_iterator const end = word.end();
4979 for (; cit != end; ++cit) {
4980 if (isNumber((*cit)))
4987 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4988 WordLangTuple & wl, docstring_list & suggestions,
4989 bool do_suggestion, bool check_learned) const
4991 SpellChecker::Result result = SpellChecker::WORD_OK;
4992 SpellChecker * speller = theSpellChecker();
4996 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4999 locateWord(from, to, WHOLE_WORD, true);
5000 if (from == to || from >= size())
5003 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5004 Language * lang = d->getSpellLanguage(from);
5006 BufferParams const & bparams = d->inset_owner_->buffer().params();
5008 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5011 wl = WordLangTuple(word, lang);
5016 if (needsSpellCheck() || check_learned) {
5018 if (!d->ignoreWord(word)) {
5019 bool const trailing_dot = to < size() && d->text_[to] == '.';
5020 result = speller->check(wl, bparams.spellignore());
5021 if (SpellChecker::misspelled(result) && trailing_dot) {
5022 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5023 result = speller->check(wl, bparams.spellignore());
5024 if (!SpellChecker::misspelled(result)) {
5025 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5027 from << ".." << to << "]");
5029 // spell check with dot appended failed too
5030 // restore original word/lang value
5031 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5032 wl = WordLangTuple(word, lang);
5036 if (!SpellChecker::misspelled(result)) {
5037 // area up to the begin of the next word is not misspelled
5038 while (end < size() && isWordSeparator(end))
5041 d->setMisspelled(from, end, result);
5043 result = d->speller_state_.getState(from);
5047 suggestions.clear();
5049 if (SpellChecker::misspelled(result)) {
5050 LYXERR(Debug::GUI, "misspelled word: \"" <<
5052 from << ".." << to << "]");
5054 speller->suggest(wl, suggestions);
5060 void Paragraph::anonymize()
5062 // This is a very crude anonymization for now
5063 for (char_type & c : d->text_)
5064 if (isLetterChar(c) || isNumber(c))
5069 void Paragraph::Private::markMisspelledWords(
5070 Language const * lang,
5071 pos_type const & first, pos_type const & last,
5072 SpellChecker::Result result,
5073 docstring const & word,
5074 SkipPositions const & skips)
5076 if (!SpellChecker::misspelled(result)) {
5077 setMisspelled(first, last, SpellChecker::WORD_OK);
5081 SpellChecker * speller = theSpellChecker();
5082 // locate and enumerate the error positions
5083 int nerrors = speller->numMisspelledWords();
5085 SkipPositionsIterator it = skips.begin();
5086 SkipPositionsIterator et = skips.end();
5087 for (int index = 0; index < nerrors; ++index) {
5090 speller->misspelledWord(index, wstart, wlen);
5091 /// should not happen if speller supports range checks
5094 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5095 wstart += first + numskipped;
5096 if (snext < wstart) {
5097 /// mark the range of correct spelling
5098 numskipped += countSkips(it, et, wstart);
5099 setMisspelled(snext,
5100 wstart - 1, SpellChecker::WORD_OK);
5102 snext = wstart + wlen;
5103 // Check whether the candidate is in the document's local dict
5104 SpellChecker::Result actresult = result;
5105 if (inset_owner_->buffer().params().spellignored(candidate))
5106 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5107 numskipped += countSkips(it, et, snext);
5108 /// mark the range of misspelling
5109 setMisspelled(wstart, snext, actresult);
5110 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5111 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5112 candidate.word() << "\" [" <<
5113 wstart << ".." << (snext-1) << "]");
5115 LYXERR(Debug::GUI, "misspelled word: \"" <<
5116 candidate.word() << "\" [" <<
5117 wstart << ".." << (snext-1) << "]");
5120 if (snext <= last) {
5121 /// mark the range of correct spelling at end
5122 setMisspelled(snext, last, SpellChecker::WORD_OK);
5127 void Paragraph::spellCheck() const
5129 SpellChecker * speller = theSpellChecker();
5130 if (!speller || empty() ||!needsSpellCheck())
5134 d->rangeOfSpellCheck(start, endpos);
5135 if (speller->canCheckParagraph()) {
5136 // loop until we leave the range
5137 for (pos_type first = start; first < endpos; ) {
5138 pos_type last = endpos;
5139 Private::SkipPositions skips;
5140 Language * lang = d->locateSpellRange(first, last, skips);
5141 if (first >= endpos)
5143 // start the spell checker on the unit of meaning
5144 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5145 WordLangTuple wl = WordLangTuple(word, lang);
5146 BufferParams const & bparams = d->inset_owner_->buffer().params();
5147 SpellChecker::Result result = !word.empty() ?
5148 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5149 d->markMisspelledWords(lang, first, last, result, word, skips);
5153 static docstring_list suggestions;
5154 pos_type to = endpos;
5155 while (start < endpos) {
5157 spellCheck(start, to, wl, suggestions, false);
5161 d->readySpellCheck();
5165 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5167 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5168 if (result || pos <= 0 || pos > size())
5170 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5171 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5176 string Paragraph::magicLabel() const
5179 ss << "magicparlabel-" << id();