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 Text::GetFont() in text2.cpp.
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 // First, reduce font against layout/label font
2126 // Update: The setCharFont() routine in text2.cpp already
2127 // reduces font, so we don't need to do that here. (Asger)
2129 d->fontlist_.set(pos, font);
2133 void Paragraph::makeSameLayout(Paragraph const & par)
2135 d->layout_ = par.d->layout_;
2136 d->params_ = par.d->params_;
2140 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2142 if (isFreeSpacing())
2148 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2149 if (eraseChar(pos, trackChanges))
2155 return count > 0 || pos > 0;
2159 bool Paragraph::hasSameLayout(Paragraph const & par) const
2161 return par.d->layout_ == d->layout_
2162 && d->params_.sameLayout(par.d->params_);
2166 depth_type Paragraph::getDepth() const
2168 return d->params_.depth();
2172 depth_type Paragraph::getMaxDepthAfter() const
2174 if (d->layout_->isEnvironment())
2175 return d->params_.depth() + 1;
2177 return d->params_.depth();
2181 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2183 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2184 return getDefaultAlign(bparams);
2186 return d->params_.align();
2190 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2192 LyXAlignment res = layout().align;
2193 if (isRTL(bparams)) {
2195 if (res == LYX_ALIGN_LEFT)
2196 res = LYX_ALIGN_RIGHT;
2197 else if (res == LYX_ALIGN_RIGHT)
2198 res = LYX_ALIGN_LEFT;
2204 docstring const & Paragraph::labelString() const
2206 return d->params_.labelString();
2210 // the next two functions are for the manual labels
2211 docstring const Paragraph::getLabelWidthString() const
2213 if (d->layout_->margintype == MARGIN_MANUAL
2214 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2215 return d->params_.labelWidthString();
2217 return _("Senseless with this layout!");
2221 void Paragraph::setLabelWidthString(docstring const & s)
2223 d->params_.labelWidthString(s);
2227 docstring Paragraph::expandLabel(Layout const & layout,
2228 BufferParams const & bparams) const
2230 return expandParagraphLabel(layout, bparams, true);
2234 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2235 BufferParams const & bparams, bool process_appendix) const
2237 DocumentClass const & tclass = bparams.documentClass();
2238 string const & lang = getParLanguage(bparams)->code();
2239 bool const in_appendix = process_appendix && d->params_.appendix();
2240 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2242 if (fmt.empty() && !layout.counter.empty())
2243 return tclass.counters().theCounter(layout.counter, lang);
2245 // handle 'inherited level parts' in 'fmt',
2246 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2247 size_t const i = fmt.find('@', 0);
2248 if (i != docstring::npos) {
2249 size_t const j = fmt.find('@', i + 1);
2250 if (j != docstring::npos) {
2251 docstring parent(fmt, i + 1, j - i - 1);
2252 docstring label = from_ascii("??");
2253 if (tclass.hasLayout(parent))
2254 label = expandParagraphLabel(tclass[parent], bparams,
2256 fmt = docstring(fmt, 0, i) + label
2257 + docstring(fmt, j + 1, docstring::npos);
2261 return tclass.counters().counterLabel(fmt, lang);
2265 void Paragraph::applyLayout(Layout const & new_layout)
2267 d->layout_ = &new_layout;
2268 LyXAlignment const oldAlign = d->params_.align();
2270 if (!(oldAlign & d->layout_->alignpossible)) {
2271 frontend::Alert::warning(_("Alignment not permitted"),
2272 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2273 d->params_.align(LYX_ALIGN_LAYOUT);
2278 pos_type Paragraph::beginOfBody() const
2280 return d->begin_of_body_;
2284 void Paragraph::setBeginOfBody()
2286 if (d->layout_->labeltype != LABEL_MANUAL) {
2287 d->begin_of_body_ = 0;
2291 // Unroll the first two cycles of the loop
2292 // and remember the previous character to
2293 // remove unnecessary getChar() calls
2295 pos_type end = size();
2296 bool prev_char_deleted = false;
2297 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2300 char_type previous_char = d->text_[i];
2301 if (!(isNewline(i) || isEnvSeparator(i))) {
2303 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2304 char_type temp = d->text_[i];
2305 prev_char_deleted = isDeleted(i);
2306 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2309 previous_char = temp;
2315 d->begin_of_body_ = i;
2319 bool Paragraph::allowParagraphCustomization() const
2321 return inInset().allowParagraphCustomization();
2325 bool Paragraph::usePlainLayout() const
2327 return inInset().usePlainLayout();
2331 bool Paragraph::isPassThru() const
2333 return inInset().isPassThru() || d->layout_->pass_thru;
2337 bool Paragraph::parbreakIsNewline() const
2339 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2343 bool Paragraph::isPartOfTextSequence() const
2345 for (pos_type i = 0; i < size(); ++i) {
2346 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2354 // paragraphs inside floats need different alignment tags to avoid
2357 bool noTrivlistCentering(InsetCode code)
2359 return code == FLOAT_CODE
2360 || code == WRAP_CODE
2361 || code == CELL_CODE;
2365 string correction(string const & orig)
2367 if (orig == "flushleft")
2368 return "raggedright";
2369 if (orig == "flushright")
2370 return "raggedleft";
2371 if (orig == "center")
2377 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2378 InsetCode code, bool const lastpar, int & col)
2380 string macro = suffix + "{";
2381 if (noTrivlistCentering(code)) {
2383 // the last paragraph in non-trivlist-aligned
2384 // context is special (to avoid unwanted whitespace)
2385 if (suffix == "\\begin") {
2386 macro = "\\" + correction(env) + "{}";
2387 os << from_ascii(macro);
2388 col += macro.size();
2393 macro += correction(env);
2397 if (suffix == "\\par\\end") {
2401 os << from_ascii(macro);
2402 col += macro.size();
2403 if (suffix == "\\begin") {
2413 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2414 otexstream & os, OutputParams const & runparams) const
2419 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2420 (layout_->toggle_indent != ITOGGLE_NEVER) :
2421 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2423 LyXAlignment const curAlign = params_.align();
2425 // Do not output \\noindent for paragraphs
2426 // 1. that cannot have indentation or are indented always,
2427 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2428 // 3. that are PassThru,
2429 // 4. or that are centered.
2430 if (canindent && params_.noindent()
2431 && owner_->isPartOfTextSequence()
2432 && !layout_->pass_thru
2433 && curAlign != LYX_ALIGN_CENTER) {
2434 if (!owner_->empty()
2435 && owner_->getInset(0)
2436 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2437 // If the paragraph starts with a vspace, the \\noindent
2438 // needs to come after that (as it leaves vmode).
2439 // If the paragraph consists only of the vspace,
2440 // \\noindent is not needed at all.
2441 runparams.need_noindent = owner_->size() > 1;
2443 os << "\\noindent" << termcmd;
2448 if (curAlign == layout_->align)
2452 case LYX_ALIGN_NONE:
2453 case LYX_ALIGN_BLOCK:
2454 case LYX_ALIGN_LAYOUT:
2455 case LYX_ALIGN_SPECIAL:
2456 case LYX_ALIGN_DECIMAL:
2458 case LYX_ALIGN_LEFT:
2459 case LYX_ALIGN_RIGHT:
2460 case LYX_ALIGN_CENTER:
2461 if (runparams.moving_arg) {
2468 string const begin_tag = "\\begin";
2469 InsetCode code = ownerCode();
2470 bool const lastpar = runparams.isLastPar;
2471 // RTL in classic (PDF)LaTeX (without the Bidi package)
2472 // Luabibdi (used by LuaTeX) behaves like classic
2473 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2474 && !runparams.useBidiPackage();
2477 case LYX_ALIGN_NONE:
2478 case LYX_ALIGN_BLOCK:
2479 case LYX_ALIGN_LAYOUT:
2480 case LYX_ALIGN_SPECIAL:
2481 case LYX_ALIGN_DECIMAL:
2483 case LYX_ALIGN_LEFT: {
2485 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2486 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2488 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2490 } case LYX_ALIGN_RIGHT: {
2492 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2493 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2495 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2497 } case LYX_ALIGN_CENTER: {
2498 corrected_env(os, begin_tag, "center", code, lastpar, column);
2507 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2508 otexstream & os, OutputParams const & runparams) const
2510 LyXAlignment const curAlign = params_.align();
2512 if (curAlign == layout_->align)
2516 case LYX_ALIGN_NONE:
2517 case LYX_ALIGN_BLOCK:
2518 case LYX_ALIGN_LAYOUT:
2519 case LYX_ALIGN_SPECIAL:
2520 case LYX_ALIGN_DECIMAL:
2522 case LYX_ALIGN_LEFT:
2523 case LYX_ALIGN_RIGHT:
2524 case LYX_ALIGN_CENTER:
2525 if (runparams.moving_arg)
2530 bool output = false;
2532 string const end_tag = "\\par\\end";
2533 InsetCode code = ownerCode();
2534 bool const lastpar = runparams.isLastPar;
2535 // RTL in classic (PDF)LaTeX (without the Bidi package)
2536 // Luabibdi (used by LuaTeX) behaves like classic
2537 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2538 && !runparams.useBidiPackage();
2541 case LYX_ALIGN_NONE:
2542 case LYX_ALIGN_BLOCK:
2543 case LYX_ALIGN_LAYOUT:
2544 case LYX_ALIGN_SPECIAL:
2545 case LYX_ALIGN_DECIMAL:
2547 case LYX_ALIGN_LEFT: {
2549 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2550 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2552 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2554 } case LYX_ALIGN_RIGHT: {
2556 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2557 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2559 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2561 } case LYX_ALIGN_CENTER: {
2562 corrected_env(os, end_tag, "center", code, lastpar, col);
2567 return output || lastpar;
2571 // This one spits out the text of the paragraph
2572 void Paragraph::latex(BufferParams const & bparams,
2573 Font const & outerfont,
2575 OutputParams const & runparams,
2576 int start_pos, int end_pos, bool force) const
2578 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2580 // FIXME This check should not be needed. Perhaps issue an
2581 // error if it triggers.
2582 Layout const & style = inInset().forcePlainLayout() ?
2583 bparams.documentClass().plainLayout() : *d->layout_;
2585 if (!force && style.inpreamble)
2588 bool const allowcust = allowParagraphCustomization();
2590 // Current base font for all inherited font changes, without any
2591 // change caused by an individual character, except for the language:
2592 // It is set to the language of the first character.
2593 // As long as we are in the label, this font is the base font of the
2594 // label. Before the first body character it is set to the base font
2598 // If there is an open font-encoding changing command (script wrapper),
2599 // alien_script is set to its name
2600 string alien_script;
2603 // Maybe we have to create a optional argument.
2604 pos_type body_pos = beginOfBody();
2605 unsigned int column = 0;
2607 // If we are inside an non inheritFont() inset,
2608 // the outerfont is the buffer's main font
2609 Font const real_outerfont =
2610 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2613 // the optional argument is kept in curly brackets in
2614 // case it contains a ']'
2615 // This is not strictly needed, but if this is changed it
2616 // would be a file format change, and tex2lyx would need
2617 // to be adjusted, since it unconditionally removes the
2618 // braces when it parses \item.
2621 basefont = getLabelFont(bparams, real_outerfont);
2623 basefont = getLayoutFont(bparams, real_outerfont);
2626 // Which font is currently active?
2627 Font running_font(basefont);
2628 // Do we have an open font change?
2629 bool open_font = false;
2631 Change runningChange =
2632 runparams.inDeletedInset && !inInset().canTrackChanges()
2633 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2635 Encoding const * const prev_encoding = runparams.encoding;
2637 os.texrow().start(id(), 0);
2639 // if the paragraph is empty, the loop will not be entered at all
2641 // For InTitle commands, we have already opened a group
2642 // in output_latex::TeXOnePar.
2643 if (style.isCommand() && !style.intitle) {
2647 if (!style.leftdelim().empty()) {
2648 os << style.leftdelim();
2649 column += style.leftdelim().size();
2652 column += d->startTeXParParams(bparams, os, runparams);
2655 // Whether a \par can be issued for insets typeset inline with text.
2656 // Yes if greater than 0. This has to be static.
2657 THREAD_LOCAL_STATIC int parInline = 0;
2659 for (pos_type i = 0; i < size(); ++i) {
2660 // First char in paragraph or after label?
2661 if (i == body_pos) {
2664 bool needPar = false;
2665 column += running_font.latexWriteEndChanges(
2666 os, bparams, runparams,
2667 basefont, basefont, needPar);
2670 basefont = getLayoutFont(bparams, real_outerfont);
2671 running_font = basefont;
2673 column += Changes::latexMarkChange(os, bparams,
2674 runningChange, Change(Change::UNCHANGED),
2676 runningChange = Change(Change::UNCHANGED);
2678 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2681 // For InTitle commands, we have already opened a group
2682 // in output_latex::TeXOnePar.
2683 if (style.isCommand() && !style.intitle) {
2688 if (!style.leftdelim().empty()) {
2689 os << style.leftdelim();
2690 column += style.leftdelim().size();
2694 column += d->startTeXParParams(bparams, os,
2698 runparams.wasDisplayMath = runparams.inDisplayMath;
2699 runparams.inDisplayMath = false;
2700 bool deleted_display_math = false;
2701 Change const & change = runparams.inDeletedInset
2702 ? runparams.changeOfDeletedInset : lookupChange(i);
2704 char_type const c = d->text_[i];
2706 // Check whether a display math inset follows
2707 bool output_changes;
2708 if (!runparams.find_effective())
2709 output_changes = bparams.output_changes;
2711 output_changes = runparams.find_with_deleted();
2713 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2715 runparams.ctObject = getInset(i)->getCtObject(runparams);
2717 InsetMath const * im = getInset(i)->asInsetMath();
2718 if (im && im->asHullInset()
2719 && im->asHullInset()->outerDisplay()) {
2720 runparams.inDisplayMath = true;
2721 // runparams.inDeletedInset will be set by
2722 // latexInset later, but we need this info
2723 // before it is called. On the other hand, we
2724 // cannot set it here because it is a counter.
2725 deleted_display_math = isDeleted(i);
2727 if (output_changes && deleted_display_math
2728 && runningChange == change
2729 && change.type == Change::DELETED
2730 && !os.afterParbreak()) {
2731 // A display math in the same paragraph follows.
2732 // We have to close and then reopen \lyxdeleted,
2733 // otherwise the math will be shifted up.
2734 OutputParams rp = runparams;
2736 bool needPar = false;
2737 column += running_font.latexWriteEndChanges(
2738 os, bparams, rp, basefont,
2742 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2743 : getLayoutFont(bparams, real_outerfont);
2744 running_font = basefont;
2745 column += Changes::latexMarkChange(os, bparams,
2746 Change(Change::INSERTED), change, rp);
2750 if (output_changes && runningChange != change) {
2751 if (!alien_script.empty()) {
2754 alien_script.clear();
2757 bool needPar = false;
2758 column += running_font.latexWriteEndChanges(
2759 os, bparams, runparams,
2760 basefont, basefont, needPar);
2763 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2764 : getLayoutFont(bparams, real_outerfont);
2765 running_font = basefont;
2766 column += Changes::latexMarkChange(os, bparams, runningChange,
2768 runningChange = change;
2771 // do not output text which is marked deleted
2772 // if change tracking output is disabled
2773 if (!output_changes && change.deleted()) {
2779 // Fully instantiated font
2780 Font current_font = getFont(bparams, i, outerfont);
2782 Font const prev_font = (i > 0) ?
2783 getFont(bparams, i - 1, outerfont)
2786 Font const last_font = running_font;
2787 bool const in_ct_deletion = (output_changes
2788 && runningChange == change
2789 && change.type == Change::DELETED
2790 && !os.afterParbreak());
2791 // Insets where font switches are used (rather than font commands)
2792 bool const fontswitch_inset =
2795 && getInset(i)->allowMultiPar()
2796 && getInset(i)->lyxCode() != ERT_CODE
2797 && (getInset(i)->producesOutput()
2798 // FIXME Something more general?
2799 // Comments do not "produce output" but are still
2800 // part of the TeX source and require font switches
2801 // to be closed (otherwise LaTeX fails).
2802 || getInset(i)->layoutName() == "Note:Comment");
2804 bool closeLanguage = false;
2805 bool lang_switched_at_inset = false;
2806 if (fontswitch_inset) {
2807 // Some insets cannot be inside a font change command.
2808 // However, even such insets *can* be placed in \L or \R
2809 // or their equivalents (for RTL language switches),
2810 // so we don't close the language in those cases
2811 // (= differing isRightToLeft()).
2812 // ArabTeX, though, doesn't seem to handle this special behavior.
2813 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2814 || basefont.language()->lang() == "arabic_arabtex"
2815 || current_font.language()->lang() == "arabic_arabtex";
2816 // We need to check prev_font as language changes directly at inset
2817 // will only be started inside the inset.
2818 lang_switched_at_inset = prev_font.language() != current_font.language();
2821 // Do we need to close the previous font?
2822 bool langClosed = false;
2824 ((current_font != running_font
2825 || current_font.language() != running_font.language())
2826 || (fontswitch_inset
2827 && (current_font == prev_font))))
2829 // ensure there is no open script-wrapper
2830 if (!alien_script.empty()) {
2833 alien_script.clear();
2835 if (in_ct_deletion) {
2836 // We have to close and then reopen \lyxdeleted,
2837 // as strikeout needs to be on lowest level.
2841 if (closeLanguage) {
2842 // Force language closing
2843 current_font.setLanguage(basefont.language());
2846 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2847 bool needPar = false;
2848 column += running_font.latexWriteEndChanges(
2849 os, bparams, runparams, basefont,
2851 if (in_ct_deletion) {
2852 // We have to close and then reopen \lyxdeleted,
2853 // as strikeout needs to be on lowest level.
2854 OutputParams rp = runparams;
2855 column += Changes::latexMarkChange(os, bparams,
2856 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2858 // Has the language been closed in the latexWriteEndChanges() call above?
2859 langClosed |= running_font.language() != basefont.language()
2860 && running_font.language() != nextfont.language()
2861 && (running_font.language()->encoding()->package() != Encoding::CJK);
2862 running_font = basefont;
2863 open_font &= !langClosed;
2866 // if necessary, close language environment before opening CJK
2867 string const running_lang = running_font.language()->babel();
2868 string const lang_end_command = lyxrc.language_command_end;
2869 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2870 && !running_lang.empty()
2871 && running_lang == openLanguageName()
2872 && current_font.language()->encoding()->package() == Encoding::CJK) {
2873 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2874 os << from_ascii(end_tag);
2875 column += end_tag.length();
2876 if (!languageStackEmpty())
2880 // Switch file encoding if necessary (and allowed)
2881 if ((!fontswitch_inset || closeLanguage)
2882 && !runparams.pass_thru && !style.pass_thru &&
2883 runparams.encoding->package() != Encoding::none &&
2884 current_font.language()->encoding()->package() != Encoding::none) {
2885 pair<bool, int> const enc_switch =
2886 switchEncoding(os.os(), bparams, runparams,
2887 *(current_font.language()->encoding()));
2888 if (enc_switch.first) {
2889 column += enc_switch.second;
2890 runparams.encoding = current_font.language()->encoding();
2894 // A display math inset inside an ulem command will be output
2895 // as a box of width \linewidth, so we have to either disable
2896 // indentation if the inset starts a paragraph, or start a new
2897 // line to accommodate such box. This has to be done before
2898 // writing any font changing commands.
2899 if (runparams.inDisplayMath && !deleted_display_math
2900 && runparams.inulemcmd) {
2901 if (os.afterParbreak())
2907 // Do we need to change font?
2908 if ((current_font != running_font ||
2909 current_font.language() != running_font.language())
2910 && i != body_pos - 1)
2912 if (!fontswitch_inset) {
2913 if (in_ct_deletion) {
2914 // We have to close and then reopen \lyxdeleted,
2915 // as strikeout needs to be on lowest level.
2916 OutputParams rp = runparams;
2917 bool needPar = false;
2918 column += running_font.latexWriteEndChanges(
2919 os, bparams, rp, basefont,
2924 otexstringstream ots;
2925 InsetText const * textinset = inInset().asInsetText();
2926 bool const cprotect = textinset
2927 ? textinset->hasCProtectContent(runparams.moving_arg)
2928 && !textinset->text().isMainText()
2929 && inInset().lyxCode() != BRANCH_CODE
2931 column += current_font.latexWriteStartChanges(ots, bparams,
2932 runparams, basefont, last_font, false,
2934 // Check again for display math in ulem commands as a
2935 // font change may also occur just before a math inset.
2936 if (runparams.inDisplayMath && !deleted_display_math
2937 && runparams.inulemcmd) {
2938 if (os.afterParbreak())
2943 running_font = current_font;
2945 docstring fontchange = ots.str();
2947 // check whether the fontchange ends with a \\textcolor
2948 // modifier and the text starts with a space. If so we
2949 // need to add } in order to prevent \\textcolor from gobbling
2950 // the space (bug 4473).
2951 docstring const last_modifier = rsplit(fontchange, '\\');
2952 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2953 os << from_ascii("{}");
2954 else if (ots.terminateCommand())
2956 if (in_ct_deletion) {
2957 // We have to close and then reopen \lyxdeleted,
2958 // as strikeout needs to be on lowest level.
2959 OutputParams rp = runparams;
2960 column += Changes::latexMarkChange(os, bparams,
2961 Change(Change::UNCHANGED), change, rp);
2963 } else {// if fontswitch_inset
2964 if (current_font != running_font || !langClosed)
2965 // font is still open in fontswitch_insets if we have
2966 // a non-lang font difference or if the language
2967 // is the only difference but has not been forcedly
2970 running_font = current_font;
2974 // FIXME: think about end_pos implementation...
2975 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2976 // FIXME: integrate this case in latexSpecialChar
2977 // Do not print the separation of the optional argument
2978 // if style.pass_thru is false. This works because
2979 // latexSpecialChar ignores spaces if
2980 // style.pass_thru is false.
2981 if (i != body_pos - 1) {
2982 if (d->simpleTeXBlanks(bparams, runparams, os,
2983 i, column, current_font, style)) {
2984 // A surrogate pair was output. We
2985 // must not call latexSpecialChar
2986 // in this iteration, since it would output
2987 // the combining character again.
2994 OutputParams rp = runparams;
2995 rp.free_spacing = style.free_spacing;
2996 rp.local_font = ¤t_font;
2997 rp.intitle = style.intitle;
2999 // Two major modes: LaTeX or plain
3000 // Handle here those cases common to both modes
3001 // and then split to handle the two modes separately.
3002 if (c == META_INSET) {
3003 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3004 // Greyedout notes and, in general, all insets
3005 // with InsetLayout::isDisplay() == false,
3006 // are typeset inline with the text. So, we
3007 // can add a \par to the last paragraph of
3008 // such insets only if nothing else follows.
3009 bool incremented = false;
3010 Inset const * inset = getInset(i);
3011 InsetText const * textinset = inset
3012 ? inset->asInsetText()
3014 if (i + 1 == size() && textinset
3015 && !inset->getLayout().isDisplay()) {
3016 ParagraphList const & pars =
3017 textinset->text().paragraphs();
3018 pit_type const pit = pars.size() - 1;
3019 Font const lastfont =
3020 pit < 0 || pars[pit].empty()
3021 ? pars[pit].getLayoutFont(
3024 : pars[pit].getFont(bparams,
3025 pars[pit].size() - 1,
3027 if (lastfont.fontInfo().size() !=
3028 basefont.fontInfo().size()) {
3033 // We need to restore parts of this after insets with
3034 // allowMultiPar() true
3035 Font const save_basefont = basefont;
3036 d->latexInset(bparams, os, rp, running_font,
3037 basefont, real_outerfont, open_font,
3038 runningChange, style, i, column, fontswitch_inset,
3039 closeLanguage, (lang_switched_at_inset || langClosed));
3040 if (fontswitch_inset) {
3042 bool needPar = false;
3043 column += running_font.latexWriteEndChanges(
3044 os, bparams, runparams,
3045 basefont, basefont, needPar);
3048 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3049 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3050 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3055 if (runparams.ctObject == CtObject::DisplayObject
3056 || runparams.ctObject == CtObject::UDisplayObject) {
3057 // Close \lyx*deleted and force its
3058 // reopening (if needed)
3061 runningChange = Change(Change::UNCHANGED);
3062 runparams.ctObject = CtObject::Normal;
3065 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3066 if (!bparams.useNonTeXFonts)
3067 script = Encodings::isKnownScriptChar(c);
3068 if (script != alien_script) {
3069 if (!alien_script.empty()) {
3071 alien_script.clear();
3073 string fontenc = running_font.language()->fontenc(bparams);
3075 && !Encodings::fontencSupportsScript(fontenc, script)) {
3076 column += script.length() + 2;
3077 os << "\\" << script << "{";
3078 alien_script = script;
3082 d->latexSpecialChar(os, bparams, rp, running_font,
3083 alien_script, style, i, end_pos, column);
3084 } catch (EncodingException & e) {
3085 if (runparams.dryrun) {
3086 os << "<" << _("LyX Warning: ")
3087 << _("uncodable character") << " '";
3091 // add location information and throw again.
3099 // Set the encoding to that returned from latexSpecialChar (see
3100 // comment for encoding member in OutputParams.h)
3101 runparams.encoding = rp.encoding;
3103 // Also carry on the info on a closed ulem command for insets
3104 // such as Note that do not produce any output, so that no
3105 // command is ever executed but its opening was recorded.
3106 runparams.inulemcmd = rp.inulemcmd;
3108 // These need to be passed upstream as well
3109 runparams.need_maketitle = rp.need_maketitle;
3110 runparams.have_maketitle = rp.have_maketitle;
3112 // And finally, pass the post_macros upstream
3113 runparams.post_macro = rp.post_macro;
3116 // Close wrapper for alien script
3117 if (!alien_script.empty()) {
3119 alien_script.clear();
3122 Font const font = empty()
3123 ? getLayoutFont(bparams, real_outerfont)
3124 : getFont(bparams, size() - 1, real_outerfont);
3126 InsetText const * textinset = inInset().asInsetText();
3128 bool const maintext = textinset
3129 ? textinset->text().isMainText()
3132 size_t const numpars = textinset
3133 ? textinset->text().paragraphs().size()
3136 bool needPar = false;
3138 if (style.resfont.size() != font.fontInfo().size()
3139 && (!runparams.isLastPar || maintext
3140 || (numpars > 1 && d->ownerCode() != CELL_CODE
3141 && (inInset().getLayout().isDisplay()
3143 && !style.isCommand()) {
3147 // If we have an open font definition, we have to close it
3149 // Make sure that \\par is done with the font of the last
3150 // character if this has another size as the default.
3151 // This is necessary because LaTeX (and LyX on the screen)
3152 // calculates the space between the baselines according
3153 // to this font. (Matthias)
3155 // We must not change the font for the last paragraph
3156 // of non-multipar insets, tabular cells or commands,
3157 // since this produces unwanted whitespace.
3158 #ifdef FIXED_LANGUAGE_END_DETECTION
3160 running_font.latexWriteEndChanges(os, bparams,
3161 runparams, basefont,
3162 next_->getFont(bparams, 0, outerfont),
3165 running_font.latexWriteEndChanges(os, bparams,
3166 runparams, basefont, basefont, needPar);
3169 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3170 //FIXME: there as we start another \selectlanguage with the next paragraph if
3171 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3172 running_font.latexWriteEndChanges(os, bparams, runparams,
3173 basefont, basefont, needPar);
3177 // The \par could not be inserted at the same nesting
3178 // level of the font size change, so do it now.
3179 os << "{\\" << font.latexSize() << "\\par}";
3182 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3183 column += Changes::latexMarkChange(os, bparams, runningChange,
3184 Change(Change::UNCHANGED), runparams);
3186 // Needed if there is an optional argument but no contents.
3187 if (body_pos > 0 && body_pos == size()) {
3191 if (!style.rightdelim().empty()) {
3192 os << style.rightdelim();
3193 column += style.rightdelim().size();
3196 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3197 && runparams.encoding != prev_encoding) {
3198 runparams.encoding = prev_encoding;
3199 os << setEncoding(prev_encoding->iconvName());
3202 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3206 bool Paragraph::emptyTag() const
3208 for (pos_type i = 0; i < size(); ++i) {
3209 if (Inset const * inset = getInset(i)) {
3210 InsetCode lyx_code = inset->lyxCode();
3211 // FIXME testing like that is wrong. What is
3213 if (lyx_code != TOC_CODE &&
3214 lyx_code != INCLUDE_CODE &&
3215 lyx_code != GRAPHICS_CODE &&
3216 lyx_code != ERT_CODE &&
3217 lyx_code != LISTINGS_CODE &&
3218 lyx_code != FLOAT_CODE &&
3219 lyx_code != TABULAR_CODE) {
3223 char_type c = d->text_[i];
3224 if (c != ' ' && c != '\t')
3232 string Paragraph::getID(Buffer const &, OutputParams const &)
3235 for (pos_type i = 0; i < size(); ++i) {
3236 if (Inset const * inset = getInset(i)) {
3237 InsetCode lyx_code = inset->lyxCode();
3238 if (lyx_code == LABEL_CODE) {
3239 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3240 docstring const & id = il->getParam("name");
3241 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3249 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3252 for (i = 0; i < size(); ++i) {
3253 if (Inset const * inset = getInset(i)) {
3254 inset->docbook(xs, runparams);
3256 char_type c = d->text_[i];
3266 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3270 for (i = 0; i < size(); ++i) {
3271 if (Inset const * inset = getInset(i)) {
3272 inset->xhtml(xs, runparams);
3274 char_type c = d->text_[i];
3284 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3287 pos_type size = text_.size();
3288 for (pos_type i = initial; i < size; ++i) {
3289 Font font = owner_->getFont(buf.params(), i, outerfont);
3290 if (text_[i] == META_INSET)
3292 if (i != initial && font != font_old)
3303 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3304 vector<xml::EndFontTag> & tagsToClose,
3305 bool & flag, FontState curstate, xml::FontTypes type)
3307 if (curstate == FONT_ON) {
3308 tagsToOpen.push_back(docbookStartFontTag(type));
3311 tagsToClose.push_back(docbookEndFontTag(type));
3316 class OptionalFontType {
3321 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3322 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3325 OptionalFontType fontShapeToXml(FontShape fs)
3329 return {xml::FT_ITALIC};
3331 return {xml::FT_SLANTED};
3332 case SMALLCAPS_SHAPE:
3333 return {xml::FT_SMALLCAPS};
3338 // the other tags are for internal use
3344 OptionalFontType fontFamilyToXml(FontFamily fm)
3348 return {xml::FT_ROMAN};
3350 return {xml::FT_SANS};
3351 case TYPEWRITER_FAMILY:
3352 return {xml::FT_TYPE};
3353 case INHERIT_FAMILY:
3356 // the other tags are for internal use
3362 OptionalFontType fontSizeToXml(FontSize fs)
3366 return {xml::FT_SIZE_TINY};
3368 return {xml::FT_SIZE_SCRIPT};
3370 return {xml::FT_SIZE_FOOTNOTE};
3372 return {xml::FT_SIZE_SMALL};
3374 return {xml::FT_SIZE_LARGE};
3376 return {xml::FT_SIZE_LARGER};
3378 return {xml::FT_SIZE_LARGEST};
3380 return {xml::FT_SIZE_HUGE};
3382 return {xml::FT_SIZE_HUGER};
3384 return {xml::FT_SIZE_INCREASE};
3386 return {xml::FT_SIZE_DECREASE};
3391 // the other tags are for internal use
3397 struct DocBookFontState
3399 FontShape curr_fs = INHERIT_SHAPE;
3400 FontFamily curr_fam = INHERIT_FAMILY;
3401 FontSize curr_size = INHERIT_SIZE;
3403 // track whether we have opened these tags
3404 bool emph_flag = false;
3405 bool bold_flag = false;
3406 bool noun_flag = false;
3407 bool ubar_flag = false;
3408 bool dbar_flag = false;
3409 bool sout_flag = false;
3410 bool xout_flag = false;
3411 bool wave_flag = false;
3413 bool shap_flag = false;
3415 bool faml_flag = false;
3417 bool size_flag = false;
3420 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3422 std::string const & default_family,
3423 DocBookFontState & fs)
3425 vector<xml::FontTag> tagsToOpen;
3426 vector<xml::EndFontTag> tagsToClose;
3429 FontState curstate = font.fontInfo().emph();
3430 if (font_old.emph() != curstate)
3431 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3434 curstate = font.fontInfo().noun();
3435 if (font_old.noun() != curstate)
3436 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3439 curstate = font.fontInfo().underbar();
3440 if (font_old.underbar() != curstate)
3441 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3444 curstate = font.fontInfo().strikeout();
3445 if (font_old.strikeout() != curstate)
3446 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3449 curstate = font.fontInfo().xout();
3450 if (font_old.xout() != curstate)
3451 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3454 curstate = font.fontInfo().uuline();
3455 if (font_old.uuline() != curstate)
3456 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3459 curstate = font.fontInfo().uwave();
3460 if (font_old.uwave() != curstate)
3461 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3464 // a little hackish, but allows us to reuse what we have.
3465 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3466 if (font_old.series() != font.fontInfo().series())
3467 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3470 fs.curr_fs = font.fontInfo().shape();
3471 FontShape old_fs = font_old.shape();
3472 if (old_fs != fs.curr_fs) {
3474 OptionalFontType tag = fontShapeToXml(old_fs);
3476 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3477 fs.shap_flag = false;
3480 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3482 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3486 fs.curr_fam = font.fontInfo().family();
3487 FontFamily old_fam = font_old.family();
3488 if (old_fam != fs.curr_fam) {
3490 OptionalFontType tag = fontFamilyToXml(old_fam);
3492 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3493 fs.faml_flag = false;
3495 switch (fs.curr_fam) {
3497 // we will treat a "default" font family as roman, since we have
3498 // no other idea what to do.
3499 if (default_family != "rmdefault" && default_family != "default") {
3500 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3501 fs.faml_flag = true;
3505 if (default_family != "sfdefault") {
3506 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3507 fs.faml_flag = true;
3510 case TYPEWRITER_FAMILY:
3511 if (default_family != "ttdefault") {
3512 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3513 fs.faml_flag = true;
3516 case INHERIT_FAMILY:
3519 // the other tags are for internal use
3526 fs.curr_size = font.fontInfo().size();
3527 FontSize old_size = font_old.size();
3528 if (old_size != fs.curr_size) {
3530 OptionalFontType tag = fontSizeToXml(old_size);
3532 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3533 fs.size_flag = false;
3536 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3537 if (tag.has_value) {
3538 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3539 fs.size_flag = true;
3543 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3546 } // anonymous namespace
3549 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3550 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3551 OutputParams const & runparams,
3552 Font const & outerfont,
3555 bool ignore_fonts) const
3557 // Return values: segregation of the content of this paragraph.
3558 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3559 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3560 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3562 // Internal string stream to store the output before being added to one of the previous lists.
3563 odocstringstream os;
3565 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3566 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3568 OutputParams rp = runparams;
3569 for (pos_type i = initial; i < size(); ++i) {
3570 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3571 const InsetArgument * arg = getInset(i)->asInsetArgument();
3572 if (arg->docbookargumentbeforemaintag()) {
3573 auto xs_local = XMLStream(os);
3574 arg->docbook(xs_local, rp);
3576 prependedParagraphs.push_back(os.str());
3577 os.str(from_ascii(""));
3579 rp.docbook_prepended_arguments.insert(arg);
3580 } else if (arg->docbookargumentaftermaintag()) {
3581 rp.docbook_appended_arguments.insert(arg);
3586 // State variables for the main loop.
3587 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3588 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3589 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3590 // This requires to store delayed characters at some point.
3592 // Track whether we have opened font tags
3593 DocBookFontState fs;
3594 DocBookFontState old_fs = fs;
3596 Layout const & style = *d->layout_;
3598 // Conversion of the font opening/closing into DocBook tags.
3599 vector<xml::FontTag> tagsToOpen;
3600 vector<xml::EndFontTag> tagsToClose;
3602 // Parsing main loop.
3603 for (pos_type i = initial; i < size(); ++i) {
3604 bool ignore_fonts_i = ignore_fonts
3605 || style.docbooknofontinside()
3606 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3608 // Don't show deleted material in the output.
3612 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3614 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3615 if (!ignore_fonts_i)
3616 xs->closeFontTags();
3618 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3619 generatedParagraphs.push_back(os.str());
3621 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3622 // that the string stream must be reset.
3623 os.str(from_ascii(""));
3625 xs = new XMLStream(os);
3627 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3628 if (!ignore_fonts_i) {
3633 // Determine which tags should be opened or closed regarding fonts.
3634 FontInfo const font_old = (i == 0 ?
3635 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3636 getFont(buf.masterBuffer()->params(), i - 1, outerfont).fontInfo());
3637 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3638 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3639 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3641 if (!ignore_fonts_i) {
3642 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3643 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3644 for (; cit != cen; ++cit)
3648 // Deal with the delayed characters *after* closing font tags.
3649 if (!delayedChars.empty()) {
3650 for (const docstring& c: delayedChars)
3651 *xs << XMLStream::ESCAPE_NONE << c;
3652 delayedChars.clear();
3655 if (!ignore_fonts_i) {
3656 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3657 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3658 for (; sit != sen; ++sit)
3661 tagsToClose.clear();
3665 // Finally, write the next character or inset.
3666 if (Inset const * inset = getInset(i)) {
3667 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3668 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3669 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3671 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3672 // Arguments may need to be output
3673 OutputParams np = rp;
3674 np.local_font = &font;
3676 // TODO: special case will bite here.
3677 np.docbook_in_par = true;
3678 inset->docbook(*xs, np);
3681 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3682 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3683 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3684 delayedChars.push_back(from_ascii(" "));
3686 delayedChars.emplace_back(1, c);
3688 } else { // No need to delay the character.
3689 if (c == '\'' && !ignore_fonts)
3690 *xs << XMLStream::ESCAPE_NONE << "’";
3697 // FIXME, this code is just imported from XHTML
3698 // I'm worried about what happens if a branch, say, is itself
3699 // wrapped in some font stuff. I think that will not work.
3701 xs->closeFontTags();
3703 // Deal with the delayed characters *after* closing font tags.
3704 if (!delayedChars.empty()) {
3705 for (const docstring &c: delayedChars)
3706 *xs << XMLStream::ESCAPE_NONE << c;
3707 delayedChars.clear();
3710 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3711 // last line to get a clean output.
3712 if (rp.docbook_in_listing && !is_last_par)
3715 // Finalise the last (and most likely only) paragraph.
3716 generatedParagraphs.push_back(os.str());
3717 os.str(from_ascii(""));
3720 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3721 for (pos_type i = initial; i < size(); ++i) {
3722 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3723 const InsetArgument * arg = getInset(i)->asInsetArgument();
3724 if (arg->docbookargumentaftermaintag()) {
3725 // Don't use rp, as this argument would not generate anything.
3726 auto xs_local = XMLStream(os);
3727 arg->docbook(xs_local, runparams);
3729 appendedParagraphs.push_back(os.str());
3730 os.str(from_ascii(""));
3735 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3741 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3742 vector<xml::EndFontTag> & tagsToClose,
3743 bool & flag, FontState curstate, xml::FontTypes type)
3745 if (curstate == FONT_ON) {
3746 tagsToOpen.push_back(xhtmlStartFontTag(type));
3749 tagsToClose.push_back(xhtmlEndFontTag(type));
3754 } // anonymous namespace
3757 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3759 OutputParams const & runparams,
3760 Font const & outerfont,
3761 bool start_paragraph, bool close_paragraph,
3762 pos_type initial) const
3766 // track whether we have opened these tags
3767 bool emph_flag = false;
3768 bool bold_flag = false;
3769 bool noun_flag = false;
3770 bool ubar_flag = false;
3771 bool dbar_flag = false;
3772 bool sout_flag = false;
3773 bool xout_flag = false;
3774 bool wave_flag = false;
3776 bool shap_flag = false;
3778 bool faml_flag = false;
3780 bool size_flag = false;
3782 Layout const & style = *d->layout_;
3784 if (start_paragraph)
3785 xs.startDivision(allowEmpty());
3788 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3790 FontShape curr_fs = INHERIT_SHAPE;
3791 FontFamily curr_fam = INHERIT_FAMILY;
3792 FontSize curr_size = INHERIT_SIZE;
3794 string const default_family =
3795 buf.masterBuffer()->params().fonts_default_family;
3797 vector<xml::FontTag> tagsToOpen;
3798 vector<xml::EndFontTag> tagsToClose;
3800 // parsing main loop
3801 for (pos_type i = initial; i < size(); ++i) {
3802 // let's not show deleted material in the output
3806 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3809 FontState curstate = font.fontInfo().emph();
3810 if (font_old.emph() != curstate)
3811 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3814 curstate = font.fontInfo().noun();
3815 if (font_old.noun() != curstate)
3816 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3819 curstate = font.fontInfo().underbar();
3820 if (font_old.underbar() != curstate)
3821 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3824 curstate = font.fontInfo().strikeout();
3825 if (font_old.strikeout() != curstate)
3826 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3829 curstate = font.fontInfo().xout();
3830 if (font_old.xout() != curstate)
3831 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3834 curstate = font.fontInfo().uuline();
3835 if (font_old.uuline() != curstate)
3836 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3839 curstate = font.fontInfo().uwave();
3840 if (font_old.uwave() != curstate)
3841 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3844 // a little hackish, but allows us to reuse what we have.
3845 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3846 if (font_old.series() != font.fontInfo().series())
3847 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3850 curr_fs = font.fontInfo().shape();
3851 FontShape old_fs = font_old.shape();
3852 if (old_fs != curr_fs) {
3856 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3859 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3861 case SMALLCAPS_SHAPE:
3862 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3868 // the other tags are for internal use
3876 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3880 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3883 case SMALLCAPS_SHAPE:
3884 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3891 // the other tags are for internal use
3898 curr_fam = font.fontInfo().family();
3899 FontFamily old_fam = font_old.family();
3900 if (old_fam != curr_fam) {
3904 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3907 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3909 case TYPEWRITER_FAMILY:
3910 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3912 case INHERIT_FAMILY:
3915 // the other tags are for internal use
3923 // we will treat a "default" font family as roman, since we have
3924 // no other idea what to do.
3925 if (default_family != "rmdefault" && default_family != "default") {
3926 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3931 if (default_family != "sfdefault") {
3932 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3936 case TYPEWRITER_FAMILY:
3937 if (default_family != "ttdefault") {
3938 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3942 case INHERIT_FAMILY:
3945 // the other tags are for internal use
3952 curr_size = font.fontInfo().size();
3953 FontSize old_size = font_old.size();
3954 if (old_size != curr_size) {
3958 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3961 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3964 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3967 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3970 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3973 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3976 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3979 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3982 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3985 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3988 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3994 // the other tags are for internal use
4000 switch (curr_size) {
4002 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
4006 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
4010 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
4014 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
4018 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
4022 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4026 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4030 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4034 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4038 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4042 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4049 // the other tags are for internal use
4056 // Other such tags? What about the other text ranges?
4058 for (auto const & t : tagsToClose)
4060 for (auto const & t : tagsToOpen)
4062 tagsToClose.clear();
4065 Inset const * inset = getInset(i);
4067 if (!runparams.for_toc || inset->isInToc()) {
4068 OutputParams np = runparams;
4069 np.local_font = &font;
4070 // If the paragraph has size 1, then we are in the "special
4071 // case" where we do not output the containing paragraph info
4072 if (!inset->getLayout().htmlisblock() && size() != 1)
4073 np.html_in_par = true;
4074 retval += inset->xhtml(xs, np);
4077 char_type c = getUChar(buf.masterBuffer()->params(),
4079 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4080 xs << XMLStream::ESCAPE_NONE << " ";
4082 xs << XMLStream::ESCAPE_NONE << "’";
4086 font_old = font.fontInfo();
4090 // I'm worried about what happens if a branch, say, is itself
4091 // wrapped in some font stuff. I think that will not work.
4093 if (close_paragraph)
4100 bool Paragraph::isHfill(pos_type pos) const
4102 Inset const * inset = getInset(pos);
4103 return inset && inset->isHfill();
4107 bool Paragraph::isNewline(pos_type pos) const
4109 // U+2028 LINE SEPARATOR
4110 // U+2029 PARAGRAPH SEPARATOR
4111 char_type const c = d->text_[pos];
4112 if (c == 0x2028 || c == 0x2029)
4114 Inset const * inset = getInset(pos);
4115 return inset && inset->lyxCode() == NEWLINE_CODE;
4119 bool Paragraph::isEnvSeparator(pos_type pos) const
4121 Inset const * inset = getInset(pos);
4122 return inset && inset->lyxCode() == SEPARATOR_CODE;
4126 bool Paragraph::isLineSeparator(pos_type pos) const
4128 char_type const c = d->text_[pos];
4129 if (isLineSeparatorChar(c))
4131 Inset const * inset = getInset(pos);
4132 return inset && inset->isLineSeparator();
4136 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4140 if (ignore_deleted && isDeleted(pos))
4142 if (Inset const * inset = getInset(pos))
4143 return !inset->isLetter();
4144 // if we have a hard hyphen (no en- or emdash) or apostrophe
4145 // we pass this to the spell checker
4146 // FIXME: this method is subject to change, visit
4147 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4148 // to get an impression how complex this is.
4149 if (isHardHyphenOrApostrophe(pos))
4151 char_type const c = d->text_[pos];
4152 // We want to pass the escape chars to the spellchecker
4153 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4154 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4158 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4160 pos_type const psize = size();
4163 char_type const c = d->text_[pos];
4164 if (c != '-' && c != '\'')
4166 pos_type nextpos = pos + 1;
4167 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4168 if ((nextpos == psize || isSpace(nextpos))
4169 && (pos == 0 || isSpace(prevpos)))
4175 bool Paragraph::needsCProtection(bool const fragile) const
4177 // first check the layout of the paragraph, but only in insets
4178 InsetText const * textinset = inInset().asInsetText();
4179 bool const maintext = textinset
4180 ? textinset->text().isMainText()
4183 if (!maintext && layout().needcprotect) {
4184 // Environments need cprotection regardless the content
4185 if (layout().latextype == LATEX_ENVIRONMENT)
4188 // Commands need cprotection if they contain specific chars
4189 int const nchars_escape = 9;
4190 static char_type const chars_escape[nchars_escape] = {
4191 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4193 docstring const pars = asString();
4194 for (int k = 0; k < nchars_escape; k++) {
4195 if (contains(pars, chars_escape[k]))
4200 // now check whether we have insets that need cprotection
4201 for (auto const & icit : d->insetlist_) {
4202 Inset const * ins = icit.inset;
4205 if (ins->needsCProtection(maintext, fragile))
4213 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4215 return d->speller_state_.getRange(pos);
4219 bool Paragraph::isChar(pos_type pos) const
4221 if (Inset const * inset = getInset(pos))
4222 return inset->isChar();
4223 char_type const c = d->text_[pos];
4224 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4228 bool Paragraph::isSpace(pos_type pos) const
4230 if (Inset const * inset = getInset(pos))
4231 return inset->isSpace();
4232 char_type const c = d->text_[pos];
4233 return lyx::isSpace(c);
4238 Paragraph::getParLanguage(BufferParams const & bparams) const
4241 return getFirstFontSettings(bparams).language();
4242 // FIXME: we should check the prev par as well (Lgb)
4243 return bparams.language;
4247 bool Paragraph::isRTL(BufferParams const & bparams) const
4249 return getParLanguage(bparams)->rightToLeft()
4250 && !inInset().getLayout().forceLTR();
4254 void Paragraph::changeLanguage(BufferParams const & bparams,
4255 Language const * from, Language const * to)
4257 // change language including dummy font change at the end
4258 for (pos_type i = 0; i <= size(); ++i) {
4259 Font font = getFontSettings(bparams, i);
4260 if (font.language() == from) {
4261 font.setLanguage(to);
4263 d->requestSpellCheck(i);
4269 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4271 Language const * doc_language = bparams.language;
4272 for (auto const & f : d->fontlist_)
4273 if (f.font().language() != ignore_language &&
4274 f.font().language() != latex_language &&
4275 f.font().language() != doc_language)
4281 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4283 for (auto const & f : d->fontlist_) {
4284 Language const * lang = f.font().language();
4285 if (lang != ignore_language &&
4286 lang != latex_language)
4292 docstring Paragraph::asString(int options) const
4294 return asString(0, size(), options);
4298 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4300 odocstringstream os;
4303 && options & AS_STR_LABEL
4304 && !d->params_.labelString().empty())
4305 os << d->params_.labelString() << ' ';
4307 for (pos_type i = beg; i < end; ++i) {
4308 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4310 char_type const c = d->text_[i];
4311 if (isPrintable(c) || c == '\t'
4312 || (c == '\n' && (options & AS_STR_NEWLINES)))
4314 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4315 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4316 LASSERT(runparams != nullptr, return docstring());
4317 if (runparams->find_effective())
4318 getInset(i)->toString(os);
4320 getInset(i)->plaintext(os, *runparams);
4321 } else if (c == META_INSET && (options & AS_STR_MATHED)
4322 && getInset(i)->lyxCode() == REF_CODE) {
4323 Buffer const & buf = getInset(i)->buffer();
4324 OutputParams rp(&buf.params().encoding());
4325 Font const font(inherit_font, buf.params().language);
4326 rp.local_font = &font;
4328 getInset(i)->latex(ots, rp);
4330 getInset(i)->toString(os);
4339 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4340 bool const shorten, bool const label) const
4342 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4343 if (label && !labelString().empty())
4344 os += labelString() + ' ';
4345 if (!layout().isTocCaption())
4347 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4350 char_type const c = d->text_[i];
4353 else if (c == META_INSET)
4354 getInset(i)->forOutliner(os, tmplen, false);
4357 Text::shortenForOutliner(os, maxlen);
4361 void Paragraph::setInsetOwner(Inset const * inset)
4363 d->inset_owner_ = inset;
4367 int Paragraph::id() const
4373 void Paragraph::setId(int id)
4379 Layout const & Paragraph::layout() const
4385 void Paragraph::setLayout(Layout const & layout)
4387 d->layout_ = &layout;
4391 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4393 setLayout(tc.defaultLayout());
4397 void Paragraph::setPlainLayout(DocumentClass const & tc)
4399 setLayout(tc.plainLayout());
4403 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4405 if (usePlainLayout())
4408 setDefaultLayout(tc);
4412 Inset const & Paragraph::inInset() const
4414 LBUFERR(d->inset_owner_);
4415 return *d->inset_owner_;
4419 ParagraphParameters & Paragraph::params()
4425 ParagraphParameters const & Paragraph::params() const
4431 bool Paragraph::isFreeSpacing() const
4433 if (d->layout_->free_spacing)
4435 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4439 bool Paragraph::allowEmpty() const
4441 if (d->layout_->keepempty)
4443 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4447 bool Paragraph::brokenBiblio() const
4449 // There is a problem if there is no bibitem at position 0 in
4450 // paragraphs that need one, if there is another bibitem in the
4451 // paragraph or if this paragraph is not supposed to have
4452 // a bibitem inset at all.
4453 return ((d->layout_->labeltype == LABEL_BIBLIO
4454 && (d->insetlist_.find(BIBITEM_CODE) != 0
4455 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4456 || (d->layout_->labeltype != LABEL_BIBLIO
4457 && d->insetlist_.find(BIBITEM_CODE) != -1));
4461 int Paragraph::fixBiblio(Buffer const & buffer)
4463 // FIXME: when there was already an inset at 0, the return value is 1,
4464 // which does not tell whether another inset has been removed; the
4465 // cursor cannot be correctly updated.
4467 bool const track_changes = buffer.params().track_changes;
4468 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4470 // The case where paragraph is not BIBLIO
4471 if (d->layout_->labeltype != LABEL_BIBLIO) {
4472 if (bibitem_pos == -1)
4473 // No InsetBibitem => OK
4475 // There is an InsetBibitem: remove it!
4476 d->insetlist_.release(bibitem_pos);
4477 eraseChar(bibitem_pos, track_changes);
4478 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4481 bool const hasbibitem0 = bibitem_pos == 0;
4483 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4484 // There was an InsetBibitem at pos 0,
4485 // and no other one => OK
4486 if (bibitem_pos == -1)
4488 // there is a bibitem at the 0 position, but since
4489 // there is a second one, we copy the second on the
4490 // first. We're assuming there are at most two of
4491 // these, which there should be.
4492 // FIXME: why does it make sense to do that rather
4493 // than keep the first? (JMarc)
4494 Inset * inset = releaseInset(bibitem_pos);
4495 d->insetlist_.begin()->inset = inset;
4496 // This needs to be done to update the counter (#8499)
4497 buffer.updateBuffer();
4498 return -bibitem_pos;
4501 // We need to create an inset at the beginning
4502 Inset * inset = nullptr;
4503 if (bibitem_pos > 0) {
4504 // there was one somewhere in the paragraph, let's move it
4505 inset = d->insetlist_.release(bibitem_pos);
4506 eraseChar(bibitem_pos, track_changes);
4509 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4510 InsetCommandParams(BIBITEM_CODE));
4512 Font font(inherit_font, buffer.params().language);
4513 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4514 : Change::UNCHANGED));
4516 // This is needed to get the counters right
4517 buffer.updateBuffer();
4522 void Paragraph::checkAuthors(AuthorList const & authorList)
4524 d->changes_.checkAuthors(authorList);
4528 bool Paragraph::isChanged(pos_type pos) const
4530 return lookupChange(pos).changed();
4534 bool Paragraph::isInserted(pos_type pos) const
4536 return lookupChange(pos).inserted();
4540 bool Paragraph::isDeleted(pos_type pos) const
4542 return lookupChange(pos).deleted();
4546 InsetList const & Paragraph::insetList() const
4548 return d->insetlist_;
4552 void Paragraph::setInsetBuffers(Buffer & b)
4554 d->insetlist_.setBuffer(b);
4558 void Paragraph::resetBuffer()
4560 d->insetlist_.resetBuffer();
4564 Inset * Paragraph::releaseInset(pos_type pos)
4566 Inset * inset = d->insetlist_.release(pos);
4567 /// does not honour change tracking!
4568 eraseChar(pos, false);
4573 Inset * Paragraph::getInset(pos_type pos)
4575 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4576 ? d->insetlist_.get(pos) : nullptr;
4580 Inset const * Paragraph::getInset(pos_type pos) const
4582 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4583 ? d->insetlist_.get(pos) : nullptr;
4587 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4588 pos_type & right, TextCase action)
4590 // process sequences of modified characters; in change
4591 // tracking mode, this approach results in much better
4592 // usability than changing case on a char-by-char basis
4593 // We also need to track the current font, since font
4594 // changes within sequences can occur.
4595 vector<pair<char_type, Font> > changes;
4597 bool const trackChanges = bparams.track_changes;
4599 bool capitalize = true;
4601 for (; pos < right; ++pos) {
4602 char_type oldChar = d->text_[pos];
4603 char_type newChar = oldChar;
4605 // ignore insets and don't play with deleted text!
4606 if (oldChar != META_INSET && !isDeleted(pos)) {
4608 case text_lowercase:
4609 newChar = lowercase(oldChar);
4611 case text_capitalization:
4613 newChar = uppercase(oldChar);
4617 case text_uppercase:
4618 newChar = uppercase(oldChar);
4623 if (isWordSeparator(pos) || isDeleted(pos)) {
4624 // permit capitalization again
4628 if (oldChar != newChar) {
4629 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4630 if (pos != right - 1)
4632 // step behind the changing area
4636 int erasePos = pos - changes.size();
4637 for (auto const & change : changes) {
4638 insertChar(pos, change.first, change.second, trackChanges);
4639 if (!eraseChar(erasePos, trackChanges)) {
4642 ++right; // expand selection
4649 int Paragraph::find(docstring const & str, bool cs, bool mw,
4650 pos_type start_pos, bool del) const
4652 pos_type pos = start_pos;
4653 int const strsize = str.length();
4655 pos_type const parsize = d->text_.size();
4656 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4657 // ignore deleted matter
4658 if (!del && isDeleted(pos)) {
4659 if (pos == parsize - 1)
4665 // Ignore "invisible" letters such as ligature breaks
4666 // and hyphenation chars while searching
4667 bool nonmatch = false;
4668 while (pos < parsize && isInset(pos)) {
4669 Inset const * inset = getInset(pos);
4670 if (!inset->isLetter() && !inset->isChar())
4672 odocstringstream os;
4673 if (inset->lyxCode() == lyx::QUOTE_CODE) {
4675 op.find_set_feature(OutputParams::SearchQuick);
4676 inset->plaintext(os, op);
4679 inset->toString(os);
4681 docstring const insetstring = os.str();
4682 if (!insetstring.empty()) {
4683 int const insetstringsize = insetstring.length();
4684 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4685 if ((cs && str[i] != insetstring[j])
4686 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4694 if (nonmatch || i == strsize)
4696 char_type dp = d->text_[pos];
4697 if (cs && str[i] != dp)
4699 if (!cs && uppercase(str[i]) != uppercase(dp))
4706 // if necessary, check whether string matches word
4708 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4711 && !isWordSeparator(pos))
4715 return pos - start_pos;
4719 char_type Paragraph::getChar(pos_type pos) const
4721 return d->text_[pos];
4725 pos_type Paragraph::size() const
4727 return d->text_.size();
4731 bool Paragraph::empty() const
4733 return d->text_.empty();
4737 bool Paragraph::isInset(pos_type pos) const
4739 return d->text_[pos] == META_INSET;
4743 bool Paragraph::isSeparator(pos_type pos) const
4745 //FIXME: Are we sure this can be the only separator?
4746 return d->text_[pos] == ' ';
4750 void Paragraph::deregisterWords()
4752 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4753 Private::LangWordsMap::const_iterator ite = d->words_.end();
4754 for (; itl != ite; ++itl) {
4755 WordList & wl = theWordList(itl->first);
4756 Private::Words::const_iterator it = (itl->second).begin();
4757 Private::Words::const_iterator et = (itl->second).end();
4758 for (; it != et; ++it)
4765 void Paragraph::locateWord(pos_type & from, pos_type & to,
4766 word_location const loc, bool const ignore_deleted) const
4769 case WHOLE_WORD_STRICT:
4770 if (from == 0 || from == size()
4771 || isWordSeparator(from, ignore_deleted)
4772 || isWordSeparator(from - 1, ignore_deleted)) {
4779 // If we are already at the beginning of a word, do nothing
4780 if (!from || isWordSeparator(from - 1, ignore_deleted))
4785 // always move the cursor to the beginning of previous word
4786 while (from && !isWordSeparator(from - 1, ignore_deleted))
4790 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4793 // no need to move the 'from' cursor
4797 while (to < size() && !isWordSeparator(to, ignore_deleted))
4802 void Paragraph::collectWords()
4804 for (pos_type pos = 0; pos < size(); ++pos) {
4805 if (isWordSeparator(pos))
4807 pos_type from = pos;
4808 locateWord(from, pos, WHOLE_WORD);
4809 // Work around MSVC warning: The statement
4810 // if (pos < from + lyxrc.completion_minlength)
4811 // triggers a signed vs. unsigned warning.
4812 // I don't know why this happens, it could be a MSVC bug, or
4813 // related to LLP64 (windows) vs. LP64 (unix) programming
4814 // model, or the C++ standard might be ambigous in the section
4815 // defining the "usual arithmetic conversions". However, using
4816 // a temporary variable is safe and works on all compilers.
4817 pos_type const endpos = from + lyxrc.completion_minlength;
4820 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4821 if (cit == d->fontlist_.end())
4823 Language const * lang = cit->font().language();
4824 docstring const word = asString(from, pos, AS_STR_NONE);
4825 d->words_[lang->lang()].insert(word);
4830 void Paragraph::registerWords()
4832 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4833 Private::LangWordsMap::const_iterator ite = d->words_.end();
4834 for (; itl != ite; ++itl) {
4835 WordList & wl = theWordList(itl->first);
4836 Private::Words::const_iterator it = (itl->second).begin();
4837 Private::Words::const_iterator et = (itl->second).end();
4838 for (; it != et; ++it)
4844 void Paragraph::updateWords()
4852 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4854 SkipPositionsIterator begin = skips.begin();
4855 SkipPositions::iterator end = skips.end();
4856 if (pos > 0 && begin < end) {
4858 if (end->last == pos - 1) {
4863 skips.insert(end, FontSpan(pos, pos));
4867 Language * Paragraph::Private::locateSpellRange(
4868 pos_type & from, pos_type & to,
4869 SkipPositions & skips) const
4871 // skip leading white space
4872 while (from < to && owner_->isWordSeparator(from))
4874 // don't check empty range
4877 // get current language
4878 Language * lang = getSpellLanguage(from);
4879 pos_type last = from;
4880 bool samelang = true;
4881 bool sameinset = true;
4882 while (last < to && samelang && sameinset) {
4883 // hop to end of word
4884 while (last < to && !owner_->isWordSeparator(last)) {
4885 Inset const * inset = owner_->getInset(last);
4886 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4887 // check for "invisible" letters such as ligature breaks
4888 odocstringstream os;
4889 inset->toString(os);
4890 if (os.str().length() != 0) {
4891 // avoid spell check of visible special char insets
4892 // stop the loop in front of the special char inset
4897 appendSkipPosition(skips, last);
4898 } else if (owner_->isDeleted(last)) {
4899 appendSkipPosition(skips, last);
4903 // hop to next word while checking for insets
4904 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4905 if (Inset const * inset = owner_->getInset(last))
4906 sameinset = inset->isChar() && inset->isLetter();
4907 if (sameinset && owner_->isDeleted(last)) {
4908 appendSkipPosition(skips, last);
4913 if (sameinset && last < to) {
4914 // now check for language change
4915 samelang = lang == getSpellLanguage(last);
4918 // if language change detected backstep is needed
4926 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4929 const_cast<Language *>(owner_->getFontSettings(
4930 inset_owner_->buffer().params(), from).language());
4931 if (lang == inset_owner_->buffer().params().language
4932 && !lyxrc.spellchecker_alt_lang.empty()) {
4934 string const lang_variety =
4935 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4936 lang->setCode(lang_code);
4937 lang->setVariety(lang_variety);
4943 void Paragraph::requestSpellCheck(pos_type pos)
4945 d->requestSpellCheck(pos);
4947 // Also request spellcheck within (text) insets
4948 for (auto const & insets : insetList()) {
4949 if (!insets.inset->asInsetText())
4951 ParagraphList & inset_pars =
4952 insets.inset->asInsetText()->paragraphs();
4953 ParagraphList::iterator pit = inset_pars.begin();
4954 ParagraphList::iterator pend = inset_pars.end();
4955 for (; pit != pend; ++pit)
4956 pit->requestSpellCheck();
4962 bool Paragraph::needsSpellCheck() const
4964 SpellChecker::ChangeNumber speller_change_number = 0;
4965 if (theSpellChecker())
4966 speller_change_number = theSpellChecker()->changeNumber();
4967 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4968 d->speller_state_.needsCompleteRefresh(speller_change_number);
4970 return d->needsSpellCheck();
4974 bool Paragraph::Private::ignoreWord(docstring const & word) const
4976 // Ignore words with digits
4977 // FIXME: make this customizable
4978 // (note that some checkers ignore words with digits by default)
4979 docstring::const_iterator cit = word.begin();
4980 docstring::const_iterator const end = word.end();
4981 for (; cit != end; ++cit) {
4982 if (isNumber((*cit)))
4989 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4990 WordLangTuple & wl, docstring_list & suggestions,
4991 bool do_suggestion, bool check_learned) const
4993 SpellChecker::Result result = SpellChecker::WORD_OK;
4994 SpellChecker * speller = theSpellChecker();
4998 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
5001 locateWord(from, to, WHOLE_WORD, true);
5002 if (from == to || from >= size())
5005 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5006 Language * lang = d->getSpellLanguage(from);
5008 BufferParams const & bparams = d->inset_owner_->buffer().params();
5010 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
5013 wl = WordLangTuple(word, lang);
5018 if (needsSpellCheck() || check_learned) {
5020 if (!d->ignoreWord(word)) {
5021 bool const trailing_dot = to < size() && d->text_[to] == '.';
5022 result = speller->check(wl, bparams.spellignore());
5023 if (SpellChecker::misspelled(result) && trailing_dot) {
5024 wl = WordLangTuple(word.append(from_ascii(".")), lang);
5025 result = speller->check(wl, bparams.spellignore());
5026 if (!SpellChecker::misspelled(result)) {
5027 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5029 from << ".." << to << "]");
5031 // spell check with dot appended failed too
5032 // restore original word/lang value
5033 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5034 wl = WordLangTuple(word, lang);
5038 if (!SpellChecker::misspelled(result)) {
5039 // area up to the begin of the next word is not misspelled
5040 while (end < size() && isWordSeparator(end))
5043 d->setMisspelled(from, end, result);
5045 result = d->speller_state_.getState(from);
5049 suggestions.clear();
5051 if (SpellChecker::misspelled(result)) {
5052 LYXERR(Debug::GUI, "misspelled word: \"" <<
5054 from << ".." << to << "]");
5056 speller->suggest(wl, suggestions);
5062 void Paragraph::anonymize()
5064 // This is a very crude anonymization for now
5065 for (char_type & c : d->text_)
5066 if (isLetterChar(c) || isNumber(c))
5071 void Paragraph::Private::markMisspelledWords(
5072 Language const * lang,
5073 pos_type const & first, pos_type const & last,
5074 SpellChecker::Result result,
5075 docstring const & word,
5076 SkipPositions const & skips)
5078 if (!SpellChecker::misspelled(result)) {
5079 setMisspelled(first, last, SpellChecker::WORD_OK);
5083 SpellChecker * speller = theSpellChecker();
5084 // locate and enumerate the error positions
5085 int nerrors = speller->numMisspelledWords();
5087 SkipPositionsIterator it = skips.begin();
5088 SkipPositionsIterator et = skips.end();
5089 for (int index = 0; index < nerrors; ++index) {
5092 speller->misspelledWord(index, wstart, wlen);
5093 /// should not happen if speller supports range checks
5096 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5097 wstart += first + numskipped;
5098 if (snext < wstart) {
5099 /// mark the range of correct spelling
5100 numskipped += countSkips(it, et, wstart);
5101 setMisspelled(snext,
5102 wstart - 1, SpellChecker::WORD_OK);
5104 snext = wstart + wlen;
5105 // Check whether the candidate is in the document's local dict
5106 SpellChecker::Result actresult = result;
5107 if (inset_owner_->buffer().params().spellignored(candidate))
5108 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5109 numskipped += countSkips(it, et, snext);
5110 /// mark the range of misspelling
5111 setMisspelled(wstart, snext, actresult);
5112 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5113 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5114 candidate.word() << "\" [" <<
5115 wstart << ".." << (snext-1) << "]");
5117 LYXERR(Debug::GUI, "misspelled word: \"" <<
5118 candidate.word() << "\" [" <<
5119 wstart << ".." << (snext-1) << "]");
5122 if (snext <= last) {
5123 /// mark the range of correct spelling at end
5124 setMisspelled(snext, last, SpellChecker::WORD_OK);
5129 void Paragraph::spellCheck() const
5131 SpellChecker * speller = theSpellChecker();
5132 if (!speller || empty() ||!needsSpellCheck())
5136 d->rangeOfSpellCheck(start, endpos);
5137 if (speller->canCheckParagraph()) {
5138 // loop until we leave the range
5139 for (pos_type first = start; first < endpos; ) {
5140 pos_type last = endpos;
5141 Private::SkipPositions skips;
5142 Language * lang = d->locateSpellRange(first, last, skips);
5143 if (first >= endpos)
5145 // start the spell checker on the unit of meaning
5146 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5147 WordLangTuple wl = WordLangTuple(word, lang);
5148 BufferParams const & bparams = d->inset_owner_->buffer().params();
5149 SpellChecker::Result result = !word.empty() ?
5150 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5151 d->markMisspelledWords(lang, first, last, result, word, skips);
5155 static docstring_list suggestions;
5156 pos_type to = endpos;
5157 while (start < endpos) {
5159 spellCheck(start, to, wl, suggestions, false);
5163 d->readySpellCheck();
5167 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5169 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5170 if (result || pos <= 0 || pos > size())
5172 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5173 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5178 string Paragraph::magicLabel() const
5181 ss << "magicparlabel-" << id();