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);
1094 odocstream::pos_type const len = os.os().tellp();
1096 if (inset->forceLTR(runparams)
1097 && running_font.isRightToLeft()
1098 // ERT is an exception, it should be output with no
1099 // decorations at all
1100 && inset->lyxCode() != ERT_CODE) {
1101 if (runparams.use_polyglossia) {
1103 } else if (running_font.language()->lang() == "farsi"
1104 || running_font.language()->lang() == "arabic_arabi")
1105 os << "\\textLR{" << termcmd;
1111 if (open_font && fontswitch_inset) {
1112 bool lang_closed = false;
1113 // Close language if needed
1114 if (closeLanguage && !lang_switched_at_inset) {
1115 // We need prev_font here as language changes directly at inset
1116 // will only be started inside the inset.
1117 Font const prev_font = (i > 0) ?
1118 owner_->getFont(bparams, i - 1, outerfont)
1120 Font tmpfont(basefont);
1121 tmpfont.setLanguage(prev_font.language());
1122 bool needPar = false;
1123 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1125 needPar, closeLanguage);
1127 lang_closed = count > 0;
1129 // Update the running_font, making sure, however,
1130 // to leave the language as it was.
1131 // FIXME: probably a better way to keep track of the old
1132 // language, than copying the entire font?
1133 Font const copy_font(running_font);
1134 basefont = owner_->getLayoutFont(bparams, outerfont);
1135 running_font = basefont;
1137 running_font.setLanguage(copy_font.language());
1138 OutputParams rp = runparams;
1139 rp.encoding = basefont.language()->encoding();
1140 // For these, we use switches, so they should be taken as
1141 // base inside the inset.
1142 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1143 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1144 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1145 // Now re-do font changes in a way needed here
1146 // (using switches with multi-par insets)
1147 InsetText const * textinset = inset->asInsetText();
1148 bool const cprotect = textinset
1149 ? textinset->hasCProtectContent(runparams.moving_arg)
1150 && !textinset->text().isMainText()
1151 && inset->lyxCode() != BRANCH_CODE
1153 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1159 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1163 runparams.local_font = &basefont;
1166 if (fontswitch_inset && !closeLanguage) {
1167 // The directionality has been switched at inset.
1168 // Force markup inside.
1169 runparams.local_font = &basefont;
1172 size_t const previous_row_count = os.texrow().rows();
1175 runparams.lastid = id_;
1176 runparams.lastpos = i;
1177 inset->latex(os, runparams);
1178 } catch (EncodingException & e) {
1179 // add location information and throw again.
1188 if (os.texrow().rows() > previous_row_count) {
1189 os.texrow().start(owner_->id(), i + 1);
1192 column += (unsigned int)(os.os().tellp() - len);
1195 if (owner_->isDeleted(i))
1196 --runparams.inDeletedInset;
1200 void Paragraph::Private::latexSpecialChar(otexstream & os,
1201 BufferParams const & bparams,
1202 OutputParams const & runparams,
1203 Font const & running_font,
1204 string & alien_script,
1205 Layout const & style,
1208 unsigned int & column) const
1210 char_type const c = owner_->getUChar(bparams, runparams, i);
1212 if (style.pass_thru || runparams.pass_thru || (runparams.for_search != OutputParams::NoSearch)
1213 || contains(style.pass_thru_chars, c)
1214 || contains(runparams.pass_thru_chars, c)) {
1215 if (runparams.for_search != OutputParams::NoSearch) {
1221 os << "\\braceleft ";
1224 os << "\\braceright ";
1234 else if (c != '\0') {
1235 Encoding const * const enc = runparams.encoding;
1236 if (enc && !enc->encodable(c))
1237 throw EncodingException(c);
1243 // TIPA uses its own T3 encoding
1244 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1246 // If T1 font encoding is used, use the special
1247 // characters it provides.
1248 // NOTE: Some languages reset the font encoding internally to a
1249 // non-standard font encoding. If we are using such a language,
1250 // we do not output special T1 chars.
1251 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1252 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1253 && latexSpecialT1(c, os, i, column))
1255 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1256 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1257 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1260 // Otherwise, we use what LaTeX provides us.
1263 os << "\\textbackslash" << termcmd;
1267 os << "\\textless" << termcmd;
1271 os << "\\textgreater" << termcmd;
1275 os << "\\textbar" << termcmd;
1280 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1281 (end_pos == -1 || i + 1 < end_pos) &&
1282 text_[i+1] == '-') {
1283 // Prevent "--" becoming an en dash and "---" an em dash.
1284 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1290 os << "\\textquotedbl" << termcmd;
1295 case '%': case '#': case '{':
1303 os << "\\textasciitilde" << termcmd;
1308 os << "\\textasciicircum" << termcmd;
1315 // avoid being mistaken for optional arguments
1323 // Blanks are printed before font switching.
1324 // Sure? I am not! (try nice-latex)
1325 // I am sure it's correct. LyX might be smarter
1326 // in the future, but for now, nothing wrong is
1332 // XeTeX's dash behaviour is determined via a global setting
1333 if (bparams.use_dash_ligatures
1334 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1336 // TODO #10961: && not in inset Flex Code
1337 // TODO #10961: && not in layout LyXCode
1338 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1355 Encoding const & encoding = *(runparams.encoding);
1356 char_type next = '\0';
1357 if (i + 1 < int(text_.size())) {
1358 next = text_[i + 1];
1359 if (Encodings::isCombiningChar(next)) {
1360 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1365 pair<docstring, bool> latex = encoding.latexChar(c);
1366 docstring nextlatex;
1367 bool nexttipas = false;
1368 string nexttipashortcut;
1369 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1370 nextlatex = encoding.latexChar(next).first;
1371 if (runparams.inIPA) {
1372 nexttipashortcut = Encodings::TIPAShortcut(next);
1373 nexttipas = !nexttipashortcut.empty();
1377 if (runparams.inIPA) {
1378 string const tipashortcut = Encodings::TIPAShortcut(c);
1379 if (!tipashortcut.empty()) {
1380 latex.first = from_ascii(tipashortcut);
1381 latex.second = false;
1385 // eventually close "script wrapper" command (see `Paragraph::latex`)
1386 if (!alien_script.empty()
1387 && alien_script != Encodings::isKnownScriptChar(next)) {
1388 column += latex.first.length();
1389 alien_script.clear();
1390 os << latex.first << "}";
1394 && ((!prefixIs(nextlatex, '\\')
1395 && !prefixIs(nextlatex, '{')
1396 && !prefixIs(nextlatex, '}'))
1398 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1400 // Prevent eating of a following space or command corruption by
1401 // following characters
1402 if (next == ' ' || next == '\0') {
1403 column += latex.first.length() + 1;
1404 os << latex.first << "{}";
1406 column += latex.first.length();
1407 os << latex.first << " ";
1410 column += latex.first.length() - 1;
1418 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1419 pos_type i, unsigned int & column) const
1425 // In T1 encoding, these characters exist
1426 // but we should avoid ligatures
1427 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1429 os << "\\textcompwordmark" << termcmd;
1436 // soul.sty breaks with \char`\"
1437 os << "\\textquotedbl" << termcmd;
1446 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1447 pos_type i, unsigned int & column) const
1449 // TU encoding is currently on par with T1.
1450 return latexSpecialT1(c, os, i, column);
1454 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1455 pos_type /*i*/, unsigned int & column) const
1465 os << "\\textvertline" << termcmd;
1474 void Paragraph::Private::validate(LaTeXFeatures & features) const
1476 if (layout_->inpreamble && inset_owner_) {
1477 // FIXME: Using a string stream here circumvents the encoding
1478 // switching machinery of odocstream. Therefore the
1479 // output is wrong if this paragraph contains content
1480 // that needs to switch encoding.
1481 Buffer const & buf = inset_owner_->buffer();
1482 otexstringstream os;
1483 os << layout_->preamble();
1484 size_t const length = os.length();
1485 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1486 buf.getParFromID(owner_->id()).pit(), os,
1487 features.runparams(), string(), 0, -1, true);
1488 if (os.length() > length)
1489 features.addPreambleSnippet(os.release(), true);
1492 if (features.runparams().flavor == Flavor::Html
1493 && layout_->htmltitle()) {
1494 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1497 // check the params.
1498 if (!params_.spacing().isDefault())
1499 features.require("setspace");
1502 features.useLayout(layout_->name());
1505 fontlist_.validate(features);
1507 // then the indentation
1508 if (!params_.leftIndent().zero())
1509 features.require("ParagraphLeftIndent");
1512 InsetList::const_iterator icit = insetlist_.begin();
1513 InsetList::const_iterator iend = insetlist_.end();
1514 for (; icit != iend; ++icit) {
1516 features.inDeletedInset(owner_->isDeleted(icit->pos));
1517 if (icit->inset->lyxCode() == FOOT_CODE) {
1518 // FIXME: an item inset would make things much easier.
1519 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1520 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1521 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1522 && (icit->pos < begin_of_body_
1523 || (icit->pos == begin_of_body_
1524 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1525 features.saveNoteEnv("description");
1527 icit->inset->validate(features);
1528 features.inDeletedInset(false);
1529 if (layout_->needprotect &&
1530 icit->inset->lyxCode() == FOOT_CODE)
1531 features.require("NeedLyXFootnoteCode");
1535 // then the contents
1536 BufferParams const bp = features.runparams().is_child
1537 ? features.buffer().masterParams() : features.buffer().params();
1538 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1539 char_type c = text_[i];
1540 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1542 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1543 features.require("textquotedblp");
1544 else if (features.runparams().main_fontenc != "T1"
1545 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1546 features.require("textquotedbl");
1547 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1548 // features that depend on the font or input encoding
1549 string feats = ci.textPreamble();
1550 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1551 if (fontenc.empty())
1552 fontenc = features.runparams().main_fontenc;
1553 while (!feats.empty()) {
1555 feats = split(feats, feat, ',');
1556 if (contains(feat, "!=")) {
1557 // a feature that is required except for the spcified
1558 // font or input encodings
1560 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1561 // multiple encodings are separated by semicolon
1562 vector<string> context = getVectorFromString(contexts, ";");
1563 // require feature if the context matches neither current font
1564 // nor input encoding
1565 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1566 && std::find(context.begin(), context.end(),
1567 features.runparams().encoding->name()) == context.end())
1568 features.require(realfeature);
1569 } else if (contains(feat, '=')) {
1570 // a feature that is required only for the spcified
1571 // font or input encodings
1573 string const contexts = split(feat, realfeature, '=');
1574 // multiple encodings are separated by semicolon
1575 vector<string> context = getVectorFromString(contexts, ";");
1576 // require feature if the context matches either current font
1577 // or input encoding
1578 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1579 || std::find(context.begin(), context.end(),
1580 features.runparams().encoding->name()) != context.end())
1581 features.require(realfeature);
1584 } else if (!bp.use_dash_ligatures
1585 && (c == 0x2013 || c == 0x2014)
1586 && bp.useNonTeXFonts
1587 && features.runparams().flavor == Flavor::XeTeX)
1588 // XeTeX's dash behaviour is determined via a global setting
1589 features.require("xetexdashbreakstate");
1590 BufferEncodings::validate(c, features);
1594 /////////////////////////////////////////////////////////////////////
1598 /////////////////////////////////////////////////////////////////////
1601 Layout const emptyParagraphLayout;
1604 Paragraph::Paragraph()
1605 : d(new Paragraph::Private(this, emptyParagraphLayout))
1612 Paragraph::Paragraph(Paragraph const & par)
1613 : itemdepth(par.itemdepth),
1614 d(new Paragraph::Private(*par.d, this))
1620 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1621 : itemdepth(par.itemdepth),
1622 d(new Paragraph::Private(*par.d, this, beg, end))
1628 Paragraph & Paragraph::operator=(Paragraph const & par)
1630 // needed as we will destroy the private part before copying it
1632 itemdepth = par.itemdepth;
1636 d = new Private(*par.d, this);
1643 Paragraph::~Paragraph()
1652 // this shall be called just before every "os << ..." action.
1653 void flushString(ostream & os, docstring & s)
1662 void Paragraph::write(ostream & os, BufferParams const & bparams,
1663 depth_type & depth) const
1665 // The beginning or end of a deeper (i.e. nested) area?
1666 if (depth != d->params_.depth()) {
1667 if (d->params_.depth() > depth) {
1668 while (d->params_.depth() > depth) {
1669 os << "\n\\begin_deeper";
1673 while (d->params_.depth() < depth) {
1674 os << "\n\\end_deeper";
1680 // First write the layout
1681 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1683 d->params_.write(os);
1685 Font font1(inherit_font, bparams.language);
1687 Change running_change = Change(Change::UNCHANGED);
1689 // this string is used as a buffer to avoid repetitive calls
1690 // to to_utf8(), which turn out to be expensive (JMarc)
1691 docstring write_buffer;
1694 for (pos_type i = 0; i <= size(); ++i) {
1696 Change const & change = lookupChange(i);
1697 if (change != running_change)
1698 flushString(os, write_buffer);
1699 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1700 running_change = change;
1705 // Write font changes
1706 Font font2 = getFontSettings(bparams, i);
1707 if (font2 != font1) {
1708 flushString(os, write_buffer);
1709 font2.lyxWriteChanges(font1, os);
1714 char_type const c = d->text_[i];
1717 if (Inset const * inset = getInset(i)) {
1718 flushString(os, write_buffer);
1719 if (inset->directWrite()) {
1720 // international char, let it write
1721 // code directly so it's shorter in
1727 os << "\\begin_inset ";
1729 os << "\n\\end_inset\n\n";
1732 // FIXME This can be removed again once the mystery
1733 // crash has been resolved.
1738 flushString(os, write_buffer);
1739 os << "\n\\backslash\n";
1743 flushString(os, write_buffer);
1744 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1751 if ((column > 70 && c == ' ')
1753 flushString(os, write_buffer);
1757 // this check is to amend a bug. LyX sometimes
1758 // inserts '\0' this could cause problems.
1760 write_buffer.push_back(c);
1762 LYXERR0("NUL char in structure.");
1768 flushString(os, write_buffer);
1769 os << "\n\\end_layout\n";
1770 // FIXME This can be removed again once the mystery
1771 // crash has been resolved.
1776 void Paragraph::validate(LaTeXFeatures & features) const
1778 d->validate(features);
1779 bool fragile = features.runparams().moving_arg;
1780 fragile |= layout().needprotect;
1781 if (inInset().getLayout().isNeedProtect())
1783 if (needsCProtection(fragile))
1784 features.require("cprotect");
1788 void Paragraph::insert(pos_type pos, docstring const & str,
1789 Font const & font, Change const & change)
1791 for (size_t i = 0, n = str.size(); i != n ; ++i)
1792 insertChar(pos + i, str[i], font, change);
1796 void Paragraph::appendChar(char_type c, Font const & font,
1797 Change const & change)
1799 // Make sure that Buffer::hasChangesPresent is updated
1800 ChangesMonitor cm(*this);
1803 d->changes_.insert(change, d->text_.size());
1804 // when appending characters, no need to update tables
1805 d->text_.push_back(c);
1806 setFont(d->text_.size() - 1, font);
1807 d->requestSpellCheck(d->text_.size() - 1);
1811 void Paragraph::appendString(docstring const & s, Font const & font,
1812 Change const & change)
1814 // Make sure that Buffer::hasChangesPresent is updated
1815 ChangesMonitor cm(*this);
1817 pos_type end = s.size();
1818 size_t oldsize = d->text_.size();
1819 size_t newsize = oldsize + end;
1820 size_t capacity = d->text_.capacity();
1821 if (newsize >= capacity)
1822 d->text_.reserve(max(capacity + 100, newsize));
1824 // when appending characters, no need to update tables
1827 // FIXME: Optimize this!
1828 for (size_t i = oldsize; i != newsize; ++i) {
1830 d->changes_.insert(change, i);
1831 d->requestSpellCheck(i);
1833 d->fontlist_.set(oldsize, font);
1834 d->fontlist_.set(newsize - 1, font);
1838 void Paragraph::insertChar(pos_type pos, char_type c,
1841 d->insertChar(pos, c, Change(trackChanges ?
1842 Change::INSERTED : Change::UNCHANGED));
1846 void Paragraph::insertChar(pos_type pos, char_type c,
1847 Font const & font, bool trackChanges)
1849 d->insertChar(pos, c, Change(trackChanges ?
1850 Change::INSERTED : Change::UNCHANGED));
1855 void Paragraph::insertChar(pos_type pos, char_type c,
1856 Font const & font, Change const & change)
1858 d->insertChar(pos, c, change);
1863 void Paragraph::resetFonts(Font const & font)
1865 d->fontlist_.clear();
1866 d->fontlist_.set(0, font);
1867 d->fontlist_.set(d->text_.size() - 1, font);
1870 // Gets uninstantiated font setting at position.
1871 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1875 LYXERR0("pos: " << pos << " size: " << size());
1879 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1880 if (cit != d->fontlist_.end())
1883 if (pos == size() && !empty())
1884 return getFontSettings(bparams, pos - 1);
1886 // Optimisation: avoid a full font instantiation if there is no
1887 // language change from previous call.
1888 static Font previous_font;
1889 static Language const * previous_lang = nullptr;
1890 Language const * lang = getParLanguage(bparams);
1891 if (lang != previous_lang) {
1892 previous_lang = lang;
1893 previous_font = Font(inherit_font, lang);
1895 return previous_font;
1899 FontSpan Paragraph::fontSpan(pos_type pos) const
1901 LBUFERR(pos <= size());
1904 return FontSpan(pos, pos);
1907 FontList::const_iterator cit = d->fontlist_.begin();
1908 FontList::const_iterator end = d->fontlist_.end();
1909 for (; cit != end; ++cit) {
1910 if (cit->pos() >= pos) {
1911 if (pos >= beginOfBody())
1912 return FontSpan(max(start, beginOfBody()),
1915 return FontSpan(start,
1916 min(beginOfBody() - 1,
1919 start = cit->pos() + 1;
1922 // This should not happen, but if so, we take no chances.
1923 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1924 LASSERT(false, return FontSpan(pos, pos));
1928 // Gets uninstantiated font setting at position 0
1929 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1931 if (!empty() && !d->fontlist_.empty())
1932 return d->fontlist_.begin()->font();
1934 // Optimisation: avoid a full font instantiation if there is no
1935 // language change from previous call.
1936 static Font previous_font;
1937 static Language const * previous_lang = nullptr;
1938 if (bparams.language != previous_lang) {
1939 previous_lang = bparams.language;
1940 previous_font = Font(inherit_font, bparams.language);
1943 return previous_font;
1947 // Gets the fully instantiated font at a given position in a paragraph
1948 // This is basically the same function as Text::GetFont() in text2.cpp.
1949 // The difference is that this one is used for generating the LaTeX file,
1950 // and thus cosmetic "improvements" are disallowed: This has to deliver
1951 // the true picture of the buffer. (Asger)
1952 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1953 Font const & outerfont) const
1957 Font font = getFontSettings(bparams, pos);
1959 pos_type const body_pos = beginOfBody();
1960 FontInfo & fi = font.fontInfo();
1962 fi.realize(d->layout_->labelfont);
1964 fi.realize(d->layout_->font);
1966 fi.realize(outerfont.fontInfo());
1967 fi.realize(bparams.getFont().fontInfo());
1973 Font const Paragraph::getLabelFont
1974 (BufferParams const & bparams, Font const & outerfont) const
1976 FontInfo tmpfont = d->layout_->labelfont;
1977 tmpfont.realize(outerfont.fontInfo());
1978 tmpfont.realize(bparams.getFont().fontInfo());
1979 return Font(tmpfont, getParLanguage(bparams));
1983 Font const Paragraph::getLayoutFont
1984 (BufferParams const & bparams, Font const & outerfont) const
1986 FontInfo tmpfont = d->layout_->font;
1987 tmpfont.realize(outerfont.fontInfo());
1988 tmpfont.realize(bparams.getFont().fontInfo());
1989 return Font(tmpfont, getParLanguage(bparams));
1993 char_type Paragraph::getUChar(BufferParams const & bparams,
1994 OutputParams const & rp,
1997 char_type c = d->text_[pos];
1999 // Return unchanged character in LTR languages
2000 // or if we use poylglossia/bidi (XeTeX).
2001 if (rp.useBidiPackage()
2002 || !getFontSettings(bparams, pos).isRightToLeft())
2005 // Without polyglossia/bidi, we need to account for some special cases.
2006 // FIXME This needs to be audited!
2008 // * The input is as expected for all delimiters
2009 // => checked for Hebrew!
2010 // * The output matches the display in the LyX workarea
2011 // => checked for Hebrew!
2012 // * The special cases below are really necessary
2013 // => checked for Hebrew!
2014 // * In arabic_arabi, brackets are transformed to Arabic
2015 // Ornate Parentheses. Is this is really wanted?
2017 string const & lang = getFontSettings(bparams, pos).language()->lang();
2020 // 1. In the following languages, parentheses need to be reversed.
2021 // Also with polyglodia/luabidi
2022 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2024 // 2. In the following languages, brackets don't need to be reversed.
2025 bool const reversebrackets = lang != "arabic_arabtex"
2026 && lang != "arabic_arabi"
2029 // Now swap delimiters if needed.
2040 if (reversebrackets)
2044 if (reversebrackets)
2065 void Paragraph::setFont(pos_type pos, Font const & font)
2067 LASSERT(pos <= size(), return);
2069 // First, reduce font against layout/label font
2070 // Update: The setCharFont() routine in text2.cpp already
2071 // reduces font, so we don't need to do that here. (Asger)
2073 d->fontlist_.set(pos, font);
2077 void Paragraph::makeSameLayout(Paragraph const & par)
2079 d->layout_ = par.d->layout_;
2080 d->params_ = par.d->params_;
2084 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2086 if (isFreeSpacing())
2092 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2093 if (eraseChar(pos, trackChanges))
2099 return count > 0 || pos > 0;
2103 bool Paragraph::hasSameLayout(Paragraph const & par) const
2105 return par.d->layout_ == d->layout_
2106 && d->params_.sameLayout(par.d->params_);
2110 depth_type Paragraph::getDepth() const
2112 return d->params_.depth();
2116 depth_type Paragraph::getMaxDepthAfter() const
2118 if (d->layout_->isEnvironment())
2119 return d->params_.depth() + 1;
2121 return d->params_.depth();
2125 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2127 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2128 return getDefaultAlign(bparams);
2130 return d->params_.align();
2134 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2136 LyXAlignment res = layout().align;
2137 if (isRTL(bparams)) {
2139 if (res == LYX_ALIGN_LEFT)
2140 res = LYX_ALIGN_RIGHT;
2141 else if (res == LYX_ALIGN_RIGHT)
2142 res = LYX_ALIGN_LEFT;
2148 docstring const & Paragraph::labelString() const
2150 return d->params_.labelString();
2154 // the next two functions are for the manual labels
2155 docstring const Paragraph::getLabelWidthString() const
2157 if (d->layout_->margintype == MARGIN_MANUAL
2158 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2159 return d->params_.labelWidthString();
2161 return _("Senseless with this layout!");
2165 void Paragraph::setLabelWidthString(docstring const & s)
2167 d->params_.labelWidthString(s);
2171 docstring Paragraph::expandLabel(Layout const & layout,
2172 BufferParams const & bparams) const
2174 return expandParagraphLabel(layout, bparams, true);
2178 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2179 BufferParams const & bparams, bool process_appendix) const
2181 DocumentClass const & tclass = bparams.documentClass();
2182 string const & lang = getParLanguage(bparams)->code();
2183 bool const in_appendix = process_appendix && d->params_.appendix();
2184 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2186 if (fmt.empty() && !layout.counter.empty())
2187 return tclass.counters().theCounter(layout.counter, lang);
2189 // handle 'inherited level parts' in 'fmt',
2190 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2191 size_t const i = fmt.find('@', 0);
2192 if (i != docstring::npos) {
2193 size_t const j = fmt.find('@', i + 1);
2194 if (j != docstring::npos) {
2195 docstring parent(fmt, i + 1, j - i - 1);
2196 docstring label = from_ascii("??");
2197 if (tclass.hasLayout(parent))
2198 label = expandParagraphLabel(tclass[parent], bparams,
2200 fmt = docstring(fmt, 0, i) + label
2201 + docstring(fmt, j + 1, docstring::npos);
2205 return tclass.counters().counterLabel(fmt, lang);
2209 void Paragraph::applyLayout(Layout const & new_layout)
2211 d->layout_ = &new_layout;
2212 LyXAlignment const oldAlign = d->params_.align();
2214 if (!(oldAlign & d->layout_->alignpossible)) {
2215 frontend::Alert::warning(_("Alignment not permitted"),
2216 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2217 d->params_.align(LYX_ALIGN_LAYOUT);
2222 pos_type Paragraph::beginOfBody() const
2224 return d->begin_of_body_;
2228 void Paragraph::setBeginOfBody()
2230 if (d->layout_->labeltype != LABEL_MANUAL) {
2231 d->begin_of_body_ = 0;
2235 // Unroll the first two cycles of the loop
2236 // and remember the previous character to
2237 // remove unnecessary getChar() calls
2239 pos_type end = size();
2240 bool prev_char_deleted = false;
2241 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2244 char_type previous_char = d->text_[i];
2245 if (!(isNewline(i) || isEnvSeparator(i))) {
2247 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2248 char_type temp = d->text_[i];
2249 prev_char_deleted = isDeleted(i);
2250 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2253 previous_char = temp;
2259 d->begin_of_body_ = i;
2263 bool Paragraph::allowParagraphCustomization() const
2265 return inInset().allowParagraphCustomization();
2269 bool Paragraph::usePlainLayout() const
2271 return inInset().usePlainLayout();
2275 bool Paragraph::isPassThru() const
2277 return inInset().isPassThru() || d->layout_->pass_thru;
2281 bool Paragraph::parbreakIsNewline() const
2283 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2287 bool Paragraph::isPartOfTextSequence() const
2289 for (pos_type i = 0; i < size(); ++i) {
2290 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2298 // paragraphs inside floats need different alignment tags to avoid
2301 bool noTrivlistCentering(InsetCode code)
2303 return code == FLOAT_CODE
2304 || code == WRAP_CODE
2305 || code == CELL_CODE;
2309 string correction(string const & orig)
2311 if (orig == "flushleft")
2312 return "raggedright";
2313 if (orig == "flushright")
2314 return "raggedleft";
2315 if (orig == "center")
2321 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2322 InsetCode code, bool const lastpar, int & col)
2324 string macro = suffix + "{";
2325 if (noTrivlistCentering(code)) {
2327 // the last paragraph in non-trivlist-aligned
2328 // context is special (to avoid unwanted whitespace)
2329 if (suffix == "\\begin") {
2330 macro = "\\" + correction(env) + "{}";
2331 os << from_ascii(macro);
2332 col += macro.size();
2337 macro += correction(env);
2341 if (suffix == "\\par\\end") {
2345 os << from_ascii(macro);
2346 col += macro.size();
2347 if (suffix == "\\begin") {
2357 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2358 otexstream & os, OutputParams const & runparams) const
2363 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2364 (layout_->toggle_indent != ITOGGLE_NEVER) :
2365 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2367 LyXAlignment const curAlign = params_.align();
2369 // Do not output \\noindent for paragraphs
2370 // 1. that cannot have indentation or are indented always,
2371 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2372 // 3. that are PassThru,
2373 // 4. or that are centered.
2374 if (canindent && params_.noindent()
2375 && owner_->isPartOfTextSequence()
2376 && !layout_->pass_thru
2377 && curAlign != LYX_ALIGN_CENTER) {
2378 if (!owner_->empty()
2379 && owner_->getInset(0)
2380 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2381 // If the paragraph starts with a vspace, the \\noindent
2382 // needs to come after that (as it leaves vmode).
2383 // If the paragraph consists only of the vspace,
2384 // \\noindent is not needed at all.
2385 runparams.need_noindent = owner_->size() > 1;
2387 os << "\\noindent" << termcmd;
2392 if (curAlign == layout_->align)
2396 case LYX_ALIGN_NONE:
2397 case LYX_ALIGN_BLOCK:
2398 case LYX_ALIGN_LAYOUT:
2399 case LYX_ALIGN_SPECIAL:
2400 case LYX_ALIGN_DECIMAL:
2402 case LYX_ALIGN_LEFT:
2403 case LYX_ALIGN_RIGHT:
2404 case LYX_ALIGN_CENTER:
2405 if (runparams.moving_arg) {
2412 string const begin_tag = "\\begin";
2413 InsetCode code = ownerCode();
2414 bool const lastpar = runparams.isLastPar;
2415 // RTL in classic (PDF)LaTeX (without the Bidi package)
2416 // Luabibdi (used by LuaTeX) behaves like classic
2417 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2418 && !runparams.useBidiPackage();
2421 case LYX_ALIGN_NONE:
2422 case LYX_ALIGN_BLOCK:
2423 case LYX_ALIGN_LAYOUT:
2424 case LYX_ALIGN_SPECIAL:
2425 case LYX_ALIGN_DECIMAL:
2427 case LYX_ALIGN_LEFT: {
2429 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2430 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2432 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2434 } case LYX_ALIGN_RIGHT: {
2436 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2437 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2439 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2441 } case LYX_ALIGN_CENTER: {
2442 corrected_env(os, begin_tag, "center", code, lastpar, column);
2451 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2452 otexstream & os, OutputParams const & runparams) const
2454 LyXAlignment const curAlign = params_.align();
2456 if (curAlign == layout_->align)
2460 case LYX_ALIGN_NONE:
2461 case LYX_ALIGN_BLOCK:
2462 case LYX_ALIGN_LAYOUT:
2463 case LYX_ALIGN_SPECIAL:
2464 case LYX_ALIGN_DECIMAL:
2466 case LYX_ALIGN_LEFT:
2467 case LYX_ALIGN_RIGHT:
2468 case LYX_ALIGN_CENTER:
2469 if (runparams.moving_arg)
2474 bool output = false;
2476 string const end_tag = "\\par\\end";
2477 InsetCode code = ownerCode();
2478 bool const lastpar = runparams.isLastPar;
2479 // RTL in classic (PDF)LaTeX (without the Bidi package)
2480 // Luabibdi (used by LuaTeX) behaves like classic
2481 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2482 && !runparams.useBidiPackage();
2485 case LYX_ALIGN_NONE:
2486 case LYX_ALIGN_BLOCK:
2487 case LYX_ALIGN_LAYOUT:
2488 case LYX_ALIGN_SPECIAL:
2489 case LYX_ALIGN_DECIMAL:
2491 case LYX_ALIGN_LEFT: {
2493 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2494 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2496 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2498 } case LYX_ALIGN_RIGHT: {
2500 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2501 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2503 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2505 } case LYX_ALIGN_CENTER: {
2506 corrected_env(os, end_tag, "center", code, lastpar, col);
2511 return output || lastpar;
2515 // This one spits out the text of the paragraph
2516 void Paragraph::latex(BufferParams const & bparams,
2517 Font const & outerfont,
2519 OutputParams const & runparams,
2520 int start_pos, int end_pos, bool force) const
2522 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2524 // FIXME This check should not be needed. Perhaps issue an
2525 // error if it triggers.
2526 Layout const & style = inInset().forcePlainLayout() ?
2527 bparams.documentClass().plainLayout() : *d->layout_;
2529 if (!force && style.inpreamble)
2532 bool const allowcust = allowParagraphCustomization();
2534 // Current base font for all inherited font changes, without any
2535 // change caused by an individual character, except for the language:
2536 // It is set to the language of the first character.
2537 // As long as we are in the label, this font is the base font of the
2538 // label. Before the first body character it is set to the base font
2542 // If there is an open font-encoding changing command (script wrapper),
2543 // alien_script is set to its name
2544 string alien_script;
2547 // Maybe we have to create a optional argument.
2548 pos_type body_pos = beginOfBody();
2549 unsigned int column = 0;
2551 // If we are inside an non inheritFont() inset,
2552 // the outerfont is the buffer's main font
2553 Font const real_outerfont =
2554 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2557 // the optional argument is kept in curly brackets in
2558 // case it contains a ']'
2559 // This is not strictly needed, but if this is changed it
2560 // would be a file format change, and tex2lyx would need
2561 // to be adjusted, since it unconditionally removes the
2562 // braces when it parses \item.
2565 basefont = getLabelFont(bparams, real_outerfont);
2567 basefont = getLayoutFont(bparams, real_outerfont);
2570 // Which font is currently active?
2571 Font running_font(basefont);
2572 // Do we have an open font change?
2573 bool open_font = false;
2575 Change runningChange =
2576 runparams.inDeletedInset && !inInset().canTrackChanges()
2577 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2579 Encoding const * const prev_encoding = runparams.encoding;
2581 os.texrow().start(id(), 0);
2583 // if the paragraph is empty, the loop will not be entered at all
2585 // For InTitle commands, we have already opened a group
2586 // in output_latex::TeXOnePar.
2587 if (style.isCommand() && !style.intitle) {
2591 if (!style.leftdelim().empty()) {
2592 os << style.leftdelim();
2593 column += style.leftdelim().size();
2596 column += d->startTeXParParams(bparams, os, runparams);
2599 // Whether a \par can be issued for insets typeset inline with text.
2600 // Yes if greater than 0. This has to be static.
2601 THREAD_LOCAL_STATIC int parInline = 0;
2603 for (pos_type i = 0; i < size(); ++i) {
2604 // First char in paragraph or after label?
2605 if (i == body_pos) {
2608 bool needPar = false;
2609 column += running_font.latexWriteEndChanges(
2610 os, bparams, runparams,
2611 basefont, basefont, needPar);
2614 basefont = getLayoutFont(bparams, real_outerfont);
2615 running_font = basefont;
2617 column += Changes::latexMarkChange(os, bparams,
2618 runningChange, Change(Change::UNCHANGED),
2620 runningChange = Change(Change::UNCHANGED);
2622 os << ((isEnvSeparator(i) && (runparams.for_search == OutputParams::NoSearch)) ? "}]~" : "}] ");
2625 // For InTitle commands, we have already opened a group
2626 // in output_latex::TeXOnePar.
2627 if (style.isCommand() && !style.intitle) {
2632 if (!style.leftdelim().empty()) {
2633 os << style.leftdelim();
2634 column += style.leftdelim().size();
2638 column += d->startTeXParParams(bparams, os,
2642 runparams.wasDisplayMath = runparams.inDisplayMath;
2643 runparams.inDisplayMath = false;
2644 bool deleted_display_math = false;
2645 Change const & change = runparams.inDeletedInset
2646 ? runparams.changeOfDeletedInset : lookupChange(i);
2648 char_type const c = d->text_[i];
2650 // Check whether a display math inset follows
2651 bool output_changes;
2652 if (runparams.for_search == OutputParams::NoSearch)
2653 output_changes = bparams.output_changes;
2655 output_changes = ((runparams.for_search & OutputParams::SearchWithDeleted) != 0);
2657 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2659 runparams.ctObject = getInset(i)->getCtObject(runparams);
2661 InsetMath const * im = getInset(i)->asInsetMath();
2662 if (im && im->asHullInset()
2663 && im->asHullInset()->outerDisplay()) {
2664 runparams.inDisplayMath = true;
2665 // runparams.inDeletedInset will be set by
2666 // latexInset later, but we need this info
2667 // before it is called. On the other hand, we
2668 // cannot set it here because it is a counter.
2669 deleted_display_math = isDeleted(i);
2671 if (output_changes && deleted_display_math
2672 && runningChange == change
2673 && change.type == Change::DELETED
2674 && !os.afterParbreak()) {
2675 // A display math in the same paragraph follows.
2676 // We have to close and then reopen \lyxdeleted,
2677 // otherwise the math will be shifted up.
2678 OutputParams rp = runparams;
2680 bool needPar = false;
2681 column += running_font.latexWriteEndChanges(
2682 os, bparams, rp, basefont,
2686 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2687 : getLayoutFont(bparams, real_outerfont);
2688 running_font = basefont;
2689 column += Changes::latexMarkChange(os, bparams,
2690 Change(Change::INSERTED), change, rp);
2694 if (output_changes && runningChange != change) {
2695 if (!alien_script.empty()) {
2698 alien_script.clear();
2701 bool needPar = false;
2702 column += running_font.latexWriteEndChanges(
2703 os, bparams, runparams,
2704 basefont, basefont, needPar);
2707 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2708 : getLayoutFont(bparams, real_outerfont);
2709 running_font = basefont;
2710 column += Changes::latexMarkChange(os, bparams, runningChange,
2712 runningChange = change;
2715 // do not output text which is marked deleted
2716 // if change tracking output is disabled
2717 if (!output_changes && change.deleted()) {
2723 // Fully instantiated font
2724 Font current_font = getFont(bparams, i, outerfont);
2726 Font const prev_font = (i > 0) ?
2727 getFont(bparams, i - 1, outerfont)
2730 Font const last_font = running_font;
2731 bool const in_ct_deletion = (output_changes
2732 && runningChange == change
2733 && change.type == Change::DELETED
2734 && !os.afterParbreak());
2735 // Insets where font switches are used (rather than font commands)
2736 bool const fontswitch_inset =
2739 && getInset(i)->allowMultiPar()
2740 && getInset(i)->lyxCode() != ERT_CODE
2741 && (getInset(i)->producesOutput()
2742 // FIXME Something more general?
2743 // Comments do not "produce output" but are still
2744 // part of the TeX source and require font switches
2745 // to be closed (otherwise LaTeX fails).
2746 || getInset(i)->layoutName() == "Note:Comment");
2748 bool closeLanguage = false;
2749 bool lang_switched_at_inset = false;
2750 if (fontswitch_inset) {
2751 // Some insets cannot be inside a font change command.
2752 // However, even such insets *can* be placed in \L or \R
2753 // or their equivalents (for RTL language switches),
2754 // so we don't close the language in those cases
2755 // (= differing isRightToLeft()).
2756 // ArabTeX, though, doesn't seem to handle this special behavior.
2757 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2758 || basefont.language()->lang() == "arabic_arabtex"
2759 || current_font.language()->lang() == "arabic_arabtex";
2760 // We need to check prev_font as language changes directly at inset
2761 // will only be started inside the inset.
2762 lang_switched_at_inset = prev_font.language() != current_font.language();
2765 // Do we need to close the previous font?
2766 bool langClosed = false;
2768 ((current_font != running_font
2769 || current_font.language() != running_font.language())
2770 || (fontswitch_inset
2771 && (current_font == prev_font))))
2773 // ensure there is no open script-wrapper
2774 if (!alien_script.empty()) {
2777 alien_script.clear();
2779 if (in_ct_deletion) {
2780 // We have to close and then reopen \lyxdeleted,
2781 // as strikeout needs to be on lowest level.
2786 // Force language closing
2787 current_font.setLanguage(basefont.language());
2788 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2789 bool needPar = false;
2790 column += running_font.latexWriteEndChanges(
2791 os, bparams, runparams, basefont,
2793 if (in_ct_deletion) {
2794 // We have to close and then reopen \lyxdeleted,
2795 // as strikeout needs to be on lowest level.
2796 OutputParams rp = runparams;
2797 column += Changes::latexMarkChange(os, bparams,
2798 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2800 // Has the language been closed in the latexWriteEndChanges() call above?
2801 langClosed = running_font.language() != basefont.language()
2802 && running_font.language() != nextfont.language()
2803 && (running_font.language()->encoding()->package() != Encoding::CJK);
2804 running_font = basefont;
2805 open_font &= !langClosed;
2808 // if necessary, close language environment before opening CJK
2809 string const running_lang = running_font.language()->babel();
2810 string const lang_end_command = lyxrc.language_command_end;
2811 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2812 && !running_lang.empty()
2813 && running_lang == openLanguageName()
2814 && current_font.language()->encoding()->package() == Encoding::CJK) {
2815 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2816 os << from_ascii(end_tag);
2817 column += end_tag.length();
2818 if (!languageStackEmpty())
2822 // Switch file encoding if necessary (and allowed)
2823 if ((!fontswitch_inset || closeLanguage)
2824 && !runparams.pass_thru && !style.pass_thru &&
2825 runparams.encoding->package() != Encoding::none &&
2826 current_font.language()->encoding()->package() != Encoding::none) {
2827 pair<bool, int> const enc_switch =
2828 switchEncoding(os.os(), bparams, runparams,
2829 *(current_font.language()->encoding()));
2830 if (enc_switch.first) {
2831 column += enc_switch.second;
2832 runparams.encoding = current_font.language()->encoding();
2836 // A display math inset inside an ulem command will be output
2837 // as a box of width \linewidth, so we have to either disable
2838 // indentation if the inset starts a paragraph, or start a new
2839 // line to accommodate such box. This has to be done before
2840 // writing any font changing commands.
2841 if (runparams.inDisplayMath && !deleted_display_math
2842 && runparams.inulemcmd) {
2843 if (os.afterParbreak())
2849 // Do we need to change font?
2850 if ((current_font != running_font ||
2851 current_font.language() != running_font.language())
2852 && i != body_pos - 1)
2854 if (!fontswitch_inset) {
2855 if (in_ct_deletion) {
2856 // We have to close and then reopen \lyxdeleted,
2857 // as strikeout needs to be on lowest level.
2858 OutputParams rp = runparams;
2859 bool needPar = false;
2860 column += running_font.latexWriteEndChanges(
2861 os, bparams, rp, basefont,
2866 otexstringstream ots;
2867 InsetText const * textinset = inInset().asInsetText();
2868 bool const cprotect = textinset
2869 ? textinset->hasCProtectContent(runparams.moving_arg)
2870 && !textinset->text().isMainText()
2871 && inInset().lyxCode() != BRANCH_CODE
2873 column += current_font.latexWriteStartChanges(ots, bparams,
2874 runparams, basefont, last_font, false,
2876 // Check again for display math in ulem commands as a
2877 // font change may also occur just before a math inset.
2878 if (runparams.inDisplayMath && !deleted_display_math
2879 && runparams.inulemcmd) {
2880 if (os.afterParbreak())
2885 running_font = current_font;
2887 docstring fontchange = ots.str();
2889 // check whether the fontchange ends with a \\textcolor
2890 // modifier and the text starts with a space. If so we
2891 // need to add } in order to prevent \\textcolor from gobbling
2892 // the space (bug 4473).
2893 docstring const last_modifier = rsplit(fontchange, '\\');
2894 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2895 os << from_ascii("{}");
2896 else if (ots.terminateCommand())
2898 if (in_ct_deletion) {
2899 // We have to close and then reopen \lyxdeleted,
2900 // as strikeout needs to be on lowest level.
2901 OutputParams rp = runparams;
2902 column += Changes::latexMarkChange(os, bparams,
2903 Change(Change::UNCHANGED), change, rp);
2906 running_font = current_font;
2907 open_font &= !langClosed;
2911 // FIXME: think about end_pos implementation...
2912 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2913 // FIXME: integrate this case in latexSpecialChar
2914 // Do not print the separation of the optional argument
2915 // if style.pass_thru is false. This works because
2916 // latexSpecialChar ignores spaces if
2917 // style.pass_thru is false.
2918 if (i != body_pos - 1) {
2919 if (d->simpleTeXBlanks(bparams, runparams, os,
2920 i, column, current_font, style)) {
2921 // A surrogate pair was output. We
2922 // must not call latexSpecialChar
2923 // in this iteration, since it would output
2924 // the combining character again.
2931 OutputParams rp = runparams;
2932 rp.free_spacing = style.free_spacing;
2933 rp.local_font = ¤t_font;
2934 rp.intitle = style.intitle;
2936 // Two major modes: LaTeX or plain
2937 // Handle here those cases common to both modes
2938 // and then split to handle the two modes separately.
2939 if (c == META_INSET) {
2940 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2941 // Greyedout notes and, in general, all insets
2942 // with InsetLayout::isDisplay() == false,
2943 // are typeset inline with the text. So, we
2944 // can add a \par to the last paragraph of
2945 // such insets only if nothing else follows.
2946 bool incremented = false;
2947 Inset const * inset = getInset(i);
2948 InsetText const * textinset = inset
2949 ? inset->asInsetText()
2951 if (i + 1 == size() && textinset
2952 && !inset->getLayout().isDisplay()) {
2953 ParagraphList const & pars =
2954 textinset->text().paragraphs();
2955 pit_type const pit = pars.size() - 1;
2956 Font const lastfont =
2957 pit < 0 || pars[pit].empty()
2958 ? pars[pit].getLayoutFont(
2961 : pars[pit].getFont(bparams,
2962 pars[pit].size() - 1,
2964 if (lastfont.fontInfo().size() !=
2965 basefont.fontInfo().size()) {
2970 // We need to restore parts of this after insets with
2971 // allowMultiPar() true
2972 Font const save_basefont = basefont;
2973 d->latexInset(bparams, os, rp, running_font,
2974 basefont, real_outerfont, open_font,
2975 runningChange, style, i, column, fontswitch_inset,
2976 closeLanguage, lang_switched_at_inset);
2977 if (fontswitch_inset) {
2979 bool needPar = false;
2980 column += running_font.latexWriteEndChanges(
2981 os, bparams, runparams,
2982 basefont, basefont, needPar);
2985 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2986 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2987 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2992 if (runparams.ctObject == CtObject::DisplayObject
2993 || runparams.ctObject == CtObject::UDisplayObject) {
2994 // Close \lyx*deleted and force its
2995 // reopening (if needed)
2998 runningChange = Change(Change::UNCHANGED);
2999 runparams.ctObject = CtObject::Normal;
3002 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3003 if (!bparams.useNonTeXFonts)
3004 script = Encodings::isKnownScriptChar(c);
3005 if (script != alien_script) {
3006 if (!alien_script.empty()) {
3008 alien_script.clear();
3010 string fontenc = running_font.language()->fontenc(bparams);
3012 && !Encodings::fontencSupportsScript(fontenc, script)) {
3013 column += script.length() + 2;
3014 os << "\\" << script << "{";
3015 alien_script = script;
3019 d->latexSpecialChar(os, bparams, rp, running_font,
3020 alien_script, style, i, end_pos, column);
3021 } catch (EncodingException & e) {
3022 if (runparams.dryrun) {
3023 os << "<" << _("LyX Warning: ")
3024 << _("uncodable character") << " '";
3028 // add location information and throw again.
3036 // Set the encoding to that returned from latexSpecialChar (see
3037 // comment for encoding member in OutputParams.h)
3038 runparams.encoding = rp.encoding;
3040 // Also carry on the info on a closed ulem command for insets
3041 // such as Note that do not produce any output, so that no
3042 // command is ever executed but its opening was recorded.
3043 runparams.inulemcmd = rp.inulemcmd;
3045 // These need to be passed upstream as well
3046 runparams.need_maketitle = rp.need_maketitle;
3047 runparams.have_maketitle = rp.have_maketitle;
3049 // And finally, pass the post_macros upstream
3050 runparams.post_macro = rp.post_macro;
3053 // Close wrapper for alien script
3054 if (!alien_script.empty()) {
3056 alien_script.clear();
3059 Font const font = empty()
3060 ? getLayoutFont(bparams, real_outerfont)
3061 : getFont(bparams, size() - 1, real_outerfont);
3063 InsetText const * textinset = inInset().asInsetText();
3065 bool const maintext = textinset
3066 ? textinset->text().isMainText()
3069 size_t const numpars = textinset
3070 ? textinset->text().paragraphs().size()
3073 bool needPar = false;
3075 if (style.resfont.size() != font.fontInfo().size()
3076 && (!runparams.isLastPar || maintext
3077 || (numpars > 1 && d->ownerCode() != CELL_CODE
3078 && (inInset().getLayout().isDisplay()
3080 && !style.isCommand()) {
3084 // If we have an open font definition, we have to close it
3086 // Make sure that \\par is done with the font of the last
3087 // character if this has another size as the default.
3088 // This is necessary because LaTeX (and LyX on the screen)
3089 // calculates the space between the baselines according
3090 // to this font. (Matthias)
3092 // We must not change the font for the last paragraph
3093 // of non-multipar insets, tabular cells or commands,
3094 // since this produces unwanted whitespace.
3095 #ifdef FIXED_LANGUAGE_END_DETECTION
3097 running_font.latexWriteEndChanges(os, bparams,
3098 runparams, basefont,
3099 next_->getFont(bparams, 0, outerfont),
3102 running_font.latexWriteEndChanges(os, bparams,
3103 runparams, basefont, basefont, needPar);
3106 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3107 //FIXME: there as we start another \selectlanguage with the next paragraph if
3108 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3109 running_font.latexWriteEndChanges(os, bparams, runparams,
3110 basefont, basefont, needPar);
3114 // The \par could not be inserted at the same nesting
3115 // level of the font size change, so do it now.
3116 os << "{\\" << font.latexSize() << "\\par}";
3119 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3120 column += Changes::latexMarkChange(os, bparams, runningChange,
3121 Change(Change::UNCHANGED), runparams);
3123 // Needed if there is an optional argument but no contents.
3124 if (body_pos > 0 && body_pos == size()) {
3128 if (!style.rightdelim().empty()) {
3129 os << style.rightdelim();
3130 column += style.rightdelim().size();
3133 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3134 && runparams.encoding != prev_encoding) {
3135 runparams.encoding = prev_encoding;
3136 os << setEncoding(prev_encoding->iconvName());
3139 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3143 bool Paragraph::emptyTag() const
3145 for (pos_type i = 0; i < size(); ++i) {
3146 if (Inset const * inset = getInset(i)) {
3147 InsetCode lyx_code = inset->lyxCode();
3148 // FIXME testing like that is wrong. What is
3150 if (lyx_code != TOC_CODE &&
3151 lyx_code != INCLUDE_CODE &&
3152 lyx_code != GRAPHICS_CODE &&
3153 lyx_code != ERT_CODE &&
3154 lyx_code != LISTINGS_CODE &&
3155 lyx_code != FLOAT_CODE &&
3156 lyx_code != TABULAR_CODE) {
3160 char_type c = d->text_[i];
3161 if (c != ' ' && c != '\t')
3169 string Paragraph::getID(Buffer const &, OutputParams const &)
3172 for (pos_type i = 0; i < size(); ++i) {
3173 if (Inset const * inset = getInset(i)) {
3174 InsetCode lyx_code = inset->lyxCode();
3175 if (lyx_code == LABEL_CODE) {
3176 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3177 docstring const & id = il->getParam("name");
3178 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3186 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3189 for (i = 0; i < size(); ++i) {
3190 if (Inset const * inset = getInset(i)) {
3191 inset->docbook(xs, runparams);
3193 char_type c = d->text_[i];
3203 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3207 for (i = 0; i < size(); ++i) {
3208 if (Inset const * inset = getInset(i)) {
3209 inset->xhtml(xs, runparams);
3211 char_type c = d->text_[i];
3221 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3224 pos_type size = text_.size();
3225 for (pos_type i = initial; i < size; ++i) {
3226 Font font = owner_->getFont(buf.params(), i, outerfont);
3227 if (text_[i] == META_INSET)
3229 if (i != initial && font != font_old)
3240 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3241 vector<xml::EndFontTag> & tagsToClose,
3242 bool & flag, FontState curstate, xml::FontTypes type)
3244 if (curstate == FONT_ON) {
3245 tagsToOpen.push_back(docbookStartFontTag(type));
3248 tagsToClose.push_back(docbookEndFontTag(type));
3253 class OptionalFontType {
3258 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3259 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3262 OptionalFontType fontShapeToXml(FontShape fs)
3266 return {xml::FT_ITALIC};
3268 return {xml::FT_SLANTED};
3269 case SMALLCAPS_SHAPE:
3270 return {xml::FT_SMALLCAPS};
3275 // the other tags are for internal use
3281 OptionalFontType fontFamilyToXml(FontFamily fm)
3285 return {xml::FT_ROMAN};
3287 return {xml::FT_SANS};
3288 case TYPEWRITER_FAMILY:
3289 return {xml::FT_TYPE};
3290 case INHERIT_FAMILY:
3293 // the other tags are for internal use
3299 OptionalFontType fontSizeToXml(FontSize fs)
3303 return {xml::FT_SIZE_TINY};
3305 return {xml::FT_SIZE_SCRIPT};
3307 return {xml::FT_SIZE_FOOTNOTE};
3309 return {xml::FT_SIZE_SMALL};
3311 return {xml::FT_SIZE_LARGE};
3313 return {xml::FT_SIZE_LARGER};
3315 return {xml::FT_SIZE_LARGEST};
3317 return {xml::FT_SIZE_HUGE};
3319 return {xml::FT_SIZE_HUGER};
3321 return {xml::FT_SIZE_INCREASE};
3323 return {xml::FT_SIZE_DECREASE};
3328 // the other tags are for internal use
3334 struct DocBookFontState
3336 FontShape curr_fs = INHERIT_SHAPE;
3337 FontFamily curr_fam = INHERIT_FAMILY;
3338 FontSize curr_size = INHERIT_SIZE;
3340 // track whether we have opened these tags
3341 bool emph_flag = false;
3342 bool bold_flag = false;
3343 bool noun_flag = false;
3344 bool ubar_flag = false;
3345 bool dbar_flag = false;
3346 bool sout_flag = false;
3347 bool xout_flag = false;
3348 bool wave_flag = false;
3350 bool shap_flag = false;
3352 bool faml_flag = false;
3354 bool size_flag = false;
3357 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3359 std::string const & default_family,
3360 DocBookFontState & fs)
3362 vector<xml::FontTag> tagsToOpen;
3363 vector<xml::EndFontTag> tagsToClose;
3366 FontState curstate = font.fontInfo().emph();
3367 if (font_old.emph() != curstate)
3368 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3371 curstate = font.fontInfo().noun();
3372 if (font_old.noun() != curstate)
3373 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3376 curstate = font.fontInfo().underbar();
3377 if (font_old.underbar() != curstate)
3378 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3381 curstate = font.fontInfo().strikeout();
3382 if (font_old.strikeout() != curstate)
3383 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3386 curstate = font.fontInfo().xout();
3387 if (font_old.xout() != curstate)
3388 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3391 curstate = font.fontInfo().uuline();
3392 if (font_old.uuline() != curstate)
3393 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3396 curstate = font.fontInfo().uwave();
3397 if (font_old.uwave() != curstate)
3398 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3401 // a little hackish, but allows us to reuse what we have.
3402 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3403 if (font_old.series() != font.fontInfo().series())
3404 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3407 fs.curr_fs = font.fontInfo().shape();
3408 FontShape old_fs = font_old.shape();
3409 if (old_fs != fs.curr_fs) {
3411 OptionalFontType tag = fontShapeToXml(old_fs);
3413 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3414 fs.shap_flag = false;
3417 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3419 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3423 fs.curr_fam = font.fontInfo().family();
3424 FontFamily old_fam = font_old.family();
3425 if (old_fam != fs.curr_fam) {
3427 OptionalFontType tag = fontFamilyToXml(old_fam);
3429 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3430 fs.faml_flag = false;
3432 switch (fs.curr_fam) {
3434 // we will treat a "default" font family as roman, since we have
3435 // no other idea what to do.
3436 if (default_family != "rmdefault" && default_family != "default") {
3437 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3438 fs.faml_flag = true;
3442 if (default_family != "sfdefault") {
3443 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3444 fs.faml_flag = true;
3447 case TYPEWRITER_FAMILY:
3448 if (default_family != "ttdefault") {
3449 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3450 fs.faml_flag = true;
3453 case INHERIT_FAMILY:
3456 // the other tags are for internal use
3463 fs.curr_size = font.fontInfo().size();
3464 FontSize old_size = font_old.size();
3465 if (old_size != fs.curr_size) {
3467 OptionalFontType tag = fontSizeToXml(old_size);
3469 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3470 fs.size_flag = false;
3473 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3474 if (tag.has_value) {
3475 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3476 fs.size_flag = true;
3480 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3483 } // anonymous namespace
3486 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3487 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3488 OutputParams const & runparams,
3489 Font const & outerfont,
3492 bool ignore_fonts) const
3494 std::vector<docstring> prependedParagraphs;
3495 std::vector<docstring> generatedParagraphs;
3496 std::vector<docstring> appendedParagraphs;
3497 odocstringstream os;
3499 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3500 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3502 OutputParams rp = runparams;
3503 for (pos_type i = initial; i < size(); ++i) {
3504 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3505 const InsetArgument * arg = getInset(i)->asInsetArgument();
3506 if (arg->docbookargumentbeforemaintag()) {
3507 auto xs_local = XMLStream(os);
3508 arg->docbook(xs_local, rp);
3510 prependedParagraphs.push_back(os.str());
3511 os.str(from_ascii(""));
3513 rp.docbook_prepended_arguments.insert(arg);
3514 } else if (arg->docbookargumentaftermaintag()) {
3515 rp.docbook_appended_arguments.insert(arg);
3520 // State variables for the main loop.
3521 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3522 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3523 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3524 // This requires to store delayed characters at some point.
3526 DocBookFontState fs; // Track whether we have opened font tags
3527 DocBookFontState old_fs = fs;
3529 Layout const & style = *d->layout_;
3530 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3531 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3533 vector<xml::FontTag> tagsToOpen;
3534 vector<xml::EndFontTag> tagsToClose;
3536 // Parsing main loop.
3537 for (pos_type i = initial; i < size(); ++i) {
3538 bool ignore_fonts_i = ignore_fonts
3539 || style.docbooknofontinside()
3540 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3542 // Don't show deleted material in the output.
3546 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3548 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3549 if (!ignore_fonts_i)
3550 xs->closeFontTags();
3552 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3553 generatedParagraphs.push_back(os.str());
3555 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3556 // that the string stream must be reset.
3557 os.str(from_ascii(""));
3559 xs = new XMLStream(os);
3561 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3562 if (!ignore_fonts_i) {
3563 font_old = outerfont.fontInfo();
3568 // Determine which tags should be opened or closed regarding fonts.
3569 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3570 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3572 if (!ignore_fonts_i) {
3573 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3574 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3575 for (; cit != cen; ++cit)
3579 // Deal with the delayed characters *after* closing font tags.
3580 if (!delayedChars.empty()) {
3581 for (char_type c: delayedChars)
3583 delayedChars.clear();
3586 if (!ignore_fonts_i) {
3587 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3588 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3589 for (; sit != sen; ++sit)
3592 tagsToClose.clear();
3596 // Finally, write the next character or inset.
3597 if (Inset const * inset = getInset(i)) {
3598 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3599 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3600 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3602 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3603 // Arguments may need to be output
3604 OutputParams np = rp;
3605 np.local_font = &font;
3607 // TODO: special case will bite here.
3608 np.docbook_in_par = true;
3609 inset->docbook(*xs, np);
3612 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3613 if (lyx::isSpace(c) && !ignore_fonts)
3614 delayedChars.push_back(c);
3618 font_old = font.fontInfo();
3621 // FIXME, this code is just imported from XHTML
3622 // I'm worried about what happens if a branch, say, is itself
3623 // wrapped in some font stuff. I think that will not work.
3625 xs->closeFontTags();
3627 // Deal with the delayed characters *after* closing font tags.
3628 if (!delayedChars.empty())
3629 for (char_type c: delayedChars)
3632 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3633 // last line to get a clean output.
3634 if (rp.docbook_in_listing && !is_last_par)
3637 // Finalise the last (and most likely only) paragraph.
3638 generatedParagraphs.push_back(os.str());
3639 os.str(from_ascii(""));
3642 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3643 for (pos_type i = initial; i < size(); ++i) {
3644 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3645 const InsetArgument * arg = getInset(i)->asInsetArgument();
3646 if (arg->docbookargumentaftermaintag()) {
3647 // Don't use rp, as this argument would not generate anything.
3648 auto xs_local = XMLStream(os);
3649 arg->docbook(xs_local, runparams);
3651 appendedParagraphs.push_back(os.str());
3652 os.str(from_ascii(""));
3657 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3663 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3664 vector<xml::EndFontTag> & tagsToClose,
3665 bool & flag, FontState curstate, xml::FontTypes type)
3667 if (curstate == FONT_ON) {
3668 tagsToOpen.push_back(xhtmlStartFontTag(type));
3671 tagsToClose.push_back(xhtmlEndFontTag(type));
3676 } // anonymous namespace
3679 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3681 OutputParams const & runparams,
3682 Font const & outerfont,
3683 bool start_paragraph, bool close_paragraph,
3684 pos_type initial) const
3688 // track whether we have opened these tags
3689 bool emph_flag = false;
3690 bool bold_flag = false;
3691 bool noun_flag = false;
3692 bool ubar_flag = false;
3693 bool dbar_flag = false;
3694 bool sout_flag = false;
3695 bool xout_flag = false;
3696 bool wave_flag = false;
3698 bool shap_flag = false;
3700 bool faml_flag = false;
3702 bool size_flag = false;
3704 Layout const & style = *d->layout_;
3706 if (start_paragraph)
3707 xs.startDivision(allowEmpty());
3710 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3712 FontShape curr_fs = INHERIT_SHAPE;
3713 FontFamily curr_fam = INHERIT_FAMILY;
3714 FontSize curr_size = INHERIT_SIZE;
3716 string const default_family =
3717 buf.masterBuffer()->params().fonts_default_family;
3719 vector<xml::FontTag> tagsToOpen;
3720 vector<xml::EndFontTag> tagsToClose;
3722 // parsing main loop
3723 for (pos_type i = initial; i < size(); ++i) {
3724 // let's not show deleted material in the output
3728 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3731 FontState curstate = font.fontInfo().emph();
3732 if (font_old.emph() != curstate)
3733 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3736 curstate = font.fontInfo().noun();
3737 if (font_old.noun() != curstate)
3738 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3741 curstate = font.fontInfo().underbar();
3742 if (font_old.underbar() != curstate)
3743 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3746 curstate = font.fontInfo().strikeout();
3747 if (font_old.strikeout() != curstate)
3748 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3751 curstate = font.fontInfo().xout();
3752 if (font_old.xout() != curstate)
3753 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3756 curstate = font.fontInfo().uuline();
3757 if (font_old.uuline() != curstate)
3758 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3761 curstate = font.fontInfo().uwave();
3762 if (font_old.uwave() != curstate)
3763 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3766 // a little hackish, but allows us to reuse what we have.
3767 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3768 if (font_old.series() != font.fontInfo().series())
3769 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3772 curr_fs = font.fontInfo().shape();
3773 FontShape old_fs = font_old.shape();
3774 if (old_fs != curr_fs) {
3778 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3781 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3783 case SMALLCAPS_SHAPE:
3784 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3790 // the other tags are for internal use
3798 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3802 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3805 case SMALLCAPS_SHAPE:
3806 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3813 // the other tags are for internal use
3820 curr_fam = font.fontInfo().family();
3821 FontFamily old_fam = font_old.family();
3822 if (old_fam != curr_fam) {
3826 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3829 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3831 case TYPEWRITER_FAMILY:
3832 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3834 case INHERIT_FAMILY:
3837 // the other tags are for internal use
3845 // we will treat a "default" font family as roman, since we have
3846 // no other idea what to do.
3847 if (default_family != "rmdefault" && default_family != "default") {
3848 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3853 if (default_family != "sfdefault") {
3854 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3858 case TYPEWRITER_FAMILY:
3859 if (default_family != "ttdefault") {
3860 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3864 case INHERIT_FAMILY:
3867 // the other tags are for internal use
3874 curr_size = font.fontInfo().size();
3875 FontSize old_size = font_old.size();
3876 if (old_size != curr_size) {
3880 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3883 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3886 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3889 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3892 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3895 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3898 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3901 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3904 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3907 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3910 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3916 // the other tags are for internal use
3922 switch (curr_size) {
3924 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3928 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3932 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3936 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3940 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3944 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3948 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3952 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3956 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3960 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3964 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3971 // the other tags are for internal use
3978 // Other such tags? What about the other text ranges?
3980 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3981 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3982 for (; cit != cen; ++cit)
3985 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3986 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3987 for (; sit != sen; ++sit)
3990 tagsToClose.clear();
3993 Inset const * inset = getInset(i);
3995 if (!runparams.for_toc || inset->isInToc()) {
3996 OutputParams np = runparams;
3997 np.local_font = &font;
3998 // If the paragraph has size 1, then we are in the "special
3999 // case" where we do not output the containing paragraph info
4000 if (!inset->getLayout().htmlisblock() && size() != 1)
4001 np.html_in_par = true;
4002 retval += inset->xhtml(xs, np);
4005 char_type c = getUChar(buf.masterBuffer()->params(),
4007 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4008 xs << XMLStream::ESCAPE_NONE << " ";
4012 font_old = font.fontInfo();
4016 // I'm worried about what happens if a branch, say, is itself
4017 // wrapped in some font stuff. I think that will not work.
4019 if (close_paragraph)
4026 bool Paragraph::isHfill(pos_type pos) const
4028 Inset const * inset = getInset(pos);
4029 return inset && inset->isHfill();
4033 bool Paragraph::isNewline(pos_type pos) const
4035 // U+2028 LINE SEPARATOR
4036 // U+2029 PARAGRAPH SEPARATOR
4037 char_type const c = d->text_[pos];
4038 if (c == 0x2028 || c == 0x2029)
4040 Inset const * inset = getInset(pos);
4041 return inset && inset->lyxCode() == NEWLINE_CODE;
4045 bool Paragraph::isEnvSeparator(pos_type pos) const
4047 Inset const * inset = getInset(pos);
4048 return inset && inset->lyxCode() == SEPARATOR_CODE;
4052 bool Paragraph::isLineSeparator(pos_type pos) const
4054 char_type const c = d->text_[pos];
4055 if (isLineSeparatorChar(c))
4057 Inset const * inset = getInset(pos);
4058 return inset && inset->isLineSeparator();
4062 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4066 if (ignore_deleted && isDeleted(pos))
4068 if (Inset const * inset = getInset(pos))
4069 return !inset->isLetter();
4070 // if we have a hard hyphen (no en- or emdash) or apostrophe
4071 // we pass this to the spell checker
4072 // FIXME: this method is subject to change, visit
4073 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4074 // to get an impression how complex this is.
4075 if (isHardHyphenOrApostrophe(pos))
4077 char_type const c = d->text_[pos];
4078 // We want to pass the escape chars to the spellchecker
4079 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4080 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4084 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4086 pos_type const psize = size();
4089 char_type const c = d->text_[pos];
4090 if (c != '-' && c != '\'')
4092 pos_type nextpos = pos + 1;
4093 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4094 if ((nextpos == psize || isSpace(nextpos))
4095 && (pos == 0 || isSpace(prevpos)))
4101 bool Paragraph::needsCProtection(bool const fragile) const
4103 // first check the layout of the paragraph, but only in insets
4104 InsetText const * textinset = inInset().asInsetText();
4105 bool const maintext = textinset
4106 ? textinset->text().isMainText()
4109 if (!maintext && layout().needcprotect) {
4110 // Environments need cprotection regardless the content
4111 if (layout().latextype == LATEX_ENVIRONMENT)
4114 // Commands need cprotection if they contain specific chars
4115 int const nchars_escape = 9;
4116 static char_type const chars_escape[nchars_escape] = {
4117 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4119 docstring const pars = asString();
4120 for (int k = 0; k < nchars_escape; k++) {
4121 if (contains(pars, chars_escape[k]))
4126 // now check whether we have insets that need cprotection
4127 for (auto const & icit : d->insetlist_) {
4128 Inset const * ins = icit.inset;
4131 if (ins->needsCProtection(maintext, fragile))
4139 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4141 return d->speller_state_.getRange(pos);
4145 bool Paragraph::isChar(pos_type pos) const
4147 if (Inset const * inset = getInset(pos))
4148 return inset->isChar();
4149 char_type const c = d->text_[pos];
4150 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4154 bool Paragraph::isSpace(pos_type pos) const
4156 if (Inset const * inset = getInset(pos))
4157 return inset->isSpace();
4158 char_type const c = d->text_[pos];
4159 return lyx::isSpace(c);
4164 Paragraph::getParLanguage(BufferParams const & bparams) const
4167 return getFirstFontSettings(bparams).language();
4168 // FIXME: we should check the prev par as well (Lgb)
4169 return bparams.language;
4173 bool Paragraph::isRTL(BufferParams const & bparams) const
4175 return getParLanguage(bparams)->rightToLeft()
4176 && !inInset().getLayout().forceLTR();
4180 void Paragraph::changeLanguage(BufferParams const & bparams,
4181 Language const * from, Language const * to)
4183 // change language including dummy font change at the end
4184 for (pos_type i = 0; i <= size(); ++i) {
4185 Font font = getFontSettings(bparams, i);
4186 if (font.language() == from) {
4187 font.setLanguage(to);
4189 d->requestSpellCheck(i);
4195 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4197 Language const * doc_language = bparams.language;
4198 for (auto const & f : d->fontlist_)
4199 if (f.font().language() != ignore_language &&
4200 f.font().language() != latex_language &&
4201 f.font().language() != doc_language)
4207 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4209 for (auto const & f : d->fontlist_) {
4210 Language const * lang = f.font().language();
4211 if (lang != ignore_language &&
4212 lang != latex_language)
4218 docstring Paragraph::asString(int options) const
4220 return asString(0, size(), options);
4224 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4226 odocstringstream os;
4229 && options & AS_STR_LABEL
4230 && !d->params_.labelString().empty())
4231 os << d->params_.labelString() << ' ';
4233 for (pos_type i = beg; i < end; ++i) {
4234 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4236 char_type const c = d->text_[i];
4237 if (isPrintable(c) || c == '\t'
4238 || (c == '\n' && (options & AS_STR_NEWLINES)))
4240 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4241 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4242 LASSERT(runparams != nullptr, return docstring());
4243 getInset(i)->plaintext(os, *runparams);
4244 } else if (c == META_INSET && (options & AS_STR_MATHED)
4245 && getInset(i)->lyxCode() == REF_CODE) {
4246 Buffer const & buf = getInset(i)->buffer();
4247 OutputParams rp(&buf.params().encoding());
4248 Font const font(inherit_font, buf.params().language);
4249 rp.local_font = &font;
4251 getInset(i)->latex(ots, rp);
4253 getInset(i)->toString(os);
4262 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4263 bool const shorten, bool const label) const
4265 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4266 if (label && !labelString().empty())
4267 os += labelString() + ' ';
4268 if (!layout().isTocCaption())
4270 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4273 char_type const c = d->text_[i];
4276 else if (c == META_INSET)
4277 getInset(i)->forOutliner(os, tmplen, false);
4280 Text::shortenForOutliner(os, maxlen);
4284 void Paragraph::setInsetOwner(Inset const * inset)
4286 d->inset_owner_ = inset;
4290 int Paragraph::id() const
4296 void Paragraph::setId(int id)
4302 Layout const & Paragraph::layout() const
4308 void Paragraph::setLayout(Layout const & layout)
4310 d->layout_ = &layout;
4314 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4316 setLayout(tc.defaultLayout());
4320 void Paragraph::setPlainLayout(DocumentClass const & tc)
4322 setLayout(tc.plainLayout());
4326 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4328 if (usePlainLayout())
4331 setDefaultLayout(tc);
4335 Inset const & Paragraph::inInset() const
4337 LBUFERR(d->inset_owner_);
4338 return *d->inset_owner_;
4342 ParagraphParameters & Paragraph::params()
4348 ParagraphParameters const & Paragraph::params() const
4354 bool Paragraph::isFreeSpacing() const
4356 if (d->layout_->free_spacing)
4358 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4362 bool Paragraph::allowEmpty() const
4364 if (d->layout_->keepempty)
4366 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4370 bool Paragraph::brokenBiblio() const
4372 // There is a problem if there is no bibitem at position 0 in
4373 // paragraphs that need one, if there is another bibitem in the
4374 // paragraph or if this paragraph is not supposed to have
4375 // a bibitem inset at all.
4376 return ((d->layout_->labeltype == LABEL_BIBLIO
4377 && (d->insetlist_.find(BIBITEM_CODE) != 0
4378 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4379 || (d->layout_->labeltype != LABEL_BIBLIO
4380 && d->insetlist_.find(BIBITEM_CODE) != -1));
4384 int Paragraph::fixBiblio(Buffer const & buffer)
4386 // FIXME: when there was already an inset at 0, the return value is 1,
4387 // which does not tell whether another inset has been removed; the
4388 // cursor cannot be correctly updated.
4390 bool const track_changes = buffer.params().track_changes;
4391 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4393 // The case where paragraph is not BIBLIO
4394 if (d->layout_->labeltype != LABEL_BIBLIO) {
4395 if (bibitem_pos == -1)
4396 // No InsetBibitem => OK
4398 // There is an InsetBibitem: remove it!
4399 d->insetlist_.release(bibitem_pos);
4400 eraseChar(bibitem_pos, track_changes);
4401 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4404 bool const hasbibitem0 = bibitem_pos == 0;
4406 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4407 // There was an InsetBibitem at pos 0,
4408 // and no other one => OK
4409 if (bibitem_pos == -1)
4411 // there is a bibitem at the 0 position, but since
4412 // there is a second one, we copy the second on the
4413 // first. We're assuming there are at most two of
4414 // these, which there should be.
4415 // FIXME: why does it make sense to do that rather
4416 // than keep the first? (JMarc)
4417 Inset * inset = releaseInset(bibitem_pos);
4418 d->insetlist_.begin()->inset = inset;
4419 // This needs to be done to update the counter (#8499)
4420 buffer.updateBuffer();
4421 return -bibitem_pos;
4424 // We need to create an inset at the beginning
4425 Inset * inset = nullptr;
4426 if (bibitem_pos > 0) {
4427 // there was one somewhere in the paragraph, let's move it
4428 inset = d->insetlist_.release(bibitem_pos);
4429 eraseChar(bibitem_pos, track_changes);
4432 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4433 InsetCommandParams(BIBITEM_CODE));
4435 Font font(inherit_font, buffer.params().language);
4436 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4437 : Change::UNCHANGED));
4439 // This is needed to get the counters right
4440 buffer.updateBuffer();
4445 void Paragraph::checkAuthors(AuthorList const & authorList)
4447 d->changes_.checkAuthors(authorList);
4451 bool Paragraph::isChanged(pos_type pos) const
4453 return lookupChange(pos).changed();
4457 bool Paragraph::isInserted(pos_type pos) const
4459 return lookupChange(pos).inserted();
4463 bool Paragraph::isDeleted(pos_type pos) const
4465 return lookupChange(pos).deleted();
4469 InsetList const & Paragraph::insetList() const
4471 return d->insetlist_;
4475 void Paragraph::setInsetBuffers(Buffer & b)
4477 d->insetlist_.setBuffer(b);
4481 void Paragraph::resetBuffer()
4483 d->insetlist_.resetBuffer();
4487 Inset * Paragraph::releaseInset(pos_type pos)
4489 Inset * inset = d->insetlist_.release(pos);
4490 /// does not honour change tracking!
4491 eraseChar(pos, false);
4496 Inset * Paragraph::getInset(pos_type pos)
4498 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4499 ? d->insetlist_.get(pos) : nullptr;
4503 Inset const * Paragraph::getInset(pos_type pos) const
4505 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4506 ? d->insetlist_.get(pos) : nullptr;
4510 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4511 pos_type & right, TextCase action)
4513 // process sequences of modified characters; in change
4514 // tracking mode, this approach results in much better
4515 // usability than changing case on a char-by-char basis
4516 // We also need to track the current font, since font
4517 // changes within sequences can occur.
4518 vector<pair<char_type, Font> > changes;
4520 bool const trackChanges = bparams.track_changes;
4522 bool capitalize = true;
4524 for (; pos < right; ++pos) {
4525 char_type oldChar = d->text_[pos];
4526 char_type newChar = oldChar;
4528 // ignore insets and don't play with deleted text!
4529 if (oldChar != META_INSET && !isDeleted(pos)) {
4531 case text_lowercase:
4532 newChar = lowercase(oldChar);
4534 case text_capitalization:
4536 newChar = uppercase(oldChar);
4540 case text_uppercase:
4541 newChar = uppercase(oldChar);
4546 if (isWordSeparator(pos) || isDeleted(pos)) {
4547 // permit capitalization again
4551 if (oldChar != newChar) {
4552 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4553 if (pos != right - 1)
4555 // step behind the changing area
4559 int erasePos = pos - changes.size();
4560 for (auto const & change : changes) {
4561 insertChar(pos, change.first, change.second, trackChanges);
4562 if (!eraseChar(erasePos, trackChanges)) {
4565 ++right; // expand selection
4572 int Paragraph::find(docstring const & str, bool cs, bool mw,
4573 pos_type start_pos, bool del) const
4575 pos_type pos = start_pos;
4576 int const strsize = str.length();
4578 pos_type const parsize = d->text_.size();
4579 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4580 // ignore deleted matter
4581 if (!del && isDeleted(pos)) {
4582 if (pos == parsize - 1)
4588 // Ignore "invisible" letters such as ligature breaks
4589 // and hyphenation chars while searching
4590 bool nonmatch = false;
4591 while (pos < parsize && isInset(pos)) {
4592 Inset const * inset = getInset(pos);
4593 if (!inset->isLetter() && !inset->isChar())
4595 odocstringstream os;
4596 if (inset->lyxCode() == lyx::QUOTE_CODE) {
4598 op.for_search = OutputParams::SearchQuick;
4599 inset->plaintext(os, op);
4602 inset->toString(os);
4604 docstring const insetstring = os.str();
4605 if (!insetstring.empty()) {
4606 int const insetstringsize = insetstring.length();
4607 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4608 if ((cs && str[i] != insetstring[j])
4609 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4617 if (nonmatch || i == strsize)
4619 char_type dp = d->text_[pos];
4620 if (cs && str[i] != dp)
4622 if (!cs && uppercase(str[i]) != uppercase(dp))
4629 // if necessary, check whether string matches word
4631 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4634 && !isWordSeparator(pos))
4638 return pos - start_pos;
4642 char_type Paragraph::getChar(pos_type pos) const
4644 return d->text_[pos];
4648 pos_type Paragraph::size() const
4650 return d->text_.size();
4654 bool Paragraph::empty() const
4656 return d->text_.empty();
4660 bool Paragraph::isInset(pos_type pos) const
4662 return d->text_[pos] == META_INSET;
4666 bool Paragraph::isSeparator(pos_type pos) const
4668 //FIXME: Are we sure this can be the only separator?
4669 return d->text_[pos] == ' ';
4673 void Paragraph::deregisterWords()
4675 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4676 Private::LangWordsMap::const_iterator ite = d->words_.end();
4677 for (; itl != ite; ++itl) {
4678 WordList & wl = theWordList(itl->first);
4679 Private::Words::const_iterator it = (itl->second).begin();
4680 Private::Words::const_iterator et = (itl->second).end();
4681 for (; it != et; ++it)
4688 void Paragraph::locateWord(pos_type & from, pos_type & to,
4689 word_location const loc, bool const ignore_deleted) const
4692 case WHOLE_WORD_STRICT:
4693 if (from == 0 || from == size()
4694 || isWordSeparator(from, ignore_deleted)
4695 || isWordSeparator(from - 1, ignore_deleted)) {
4702 // If we are already at the beginning of a word, do nothing
4703 if (!from || isWordSeparator(from - 1, ignore_deleted))
4708 // always move the cursor to the beginning of previous word
4709 while (from && !isWordSeparator(from - 1, ignore_deleted))
4713 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4716 // no need to move the 'from' cursor
4720 while (to < size() && !isWordSeparator(to, ignore_deleted))
4725 void Paragraph::collectWords()
4727 for (pos_type pos = 0; pos < size(); ++pos) {
4728 if (isWordSeparator(pos))
4730 pos_type from = pos;
4731 locateWord(from, pos, WHOLE_WORD);
4732 // Work around MSVC warning: The statement
4733 // if (pos < from + lyxrc.completion_minlength)
4734 // triggers a signed vs. unsigned warning.
4735 // I don't know why this happens, it could be a MSVC bug, or
4736 // related to LLP64 (windows) vs. LP64 (unix) programming
4737 // model, or the C++ standard might be ambigous in the section
4738 // defining the "usual arithmetic conversions". However, using
4739 // a temporary variable is safe and works on all compilers.
4740 pos_type const endpos = from + lyxrc.completion_minlength;
4743 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4744 if (cit == d->fontlist_.end())
4746 Language const * lang = cit->font().language();
4747 docstring const word = asString(from, pos, AS_STR_NONE);
4748 d->words_[lang->lang()].insert(word);
4753 void Paragraph::registerWords()
4755 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4756 Private::LangWordsMap::const_iterator ite = d->words_.end();
4757 for (; itl != ite; ++itl) {
4758 WordList & wl = theWordList(itl->first);
4759 Private::Words::const_iterator it = (itl->second).begin();
4760 Private::Words::const_iterator et = (itl->second).end();
4761 for (; it != et; ++it)
4767 void Paragraph::updateWords()
4775 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4777 SkipPositionsIterator begin = skips.begin();
4778 SkipPositions::iterator end = skips.end();
4779 if (pos > 0 && begin < end) {
4781 if (end->last == pos - 1) {
4786 skips.insert(end, FontSpan(pos, pos));
4790 Language * Paragraph::Private::locateSpellRange(
4791 pos_type & from, pos_type & to,
4792 SkipPositions & skips) const
4794 // skip leading white space
4795 while (from < to && owner_->isWordSeparator(from))
4797 // don't check empty range
4800 // get current language
4801 Language * lang = getSpellLanguage(from);
4802 pos_type last = from;
4803 bool samelang = true;
4804 bool sameinset = true;
4805 while (last < to && samelang && sameinset) {
4806 // hop to end of word
4807 while (last < to && !owner_->isWordSeparator(last)) {
4808 Inset const * inset = owner_->getInset(last);
4809 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4810 // check for "invisible" letters such as ligature breaks
4811 odocstringstream os;
4812 inset->toString(os);
4813 if (os.str().length() != 0) {
4814 // avoid spell check of visible special char insets
4815 // stop the loop in front of the special char inset
4820 appendSkipPosition(skips, last);
4821 } else if (owner_->isDeleted(last)) {
4822 appendSkipPosition(skips, last);
4826 // hop to next word while checking for insets
4827 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4828 if (Inset const * inset = owner_->getInset(last))
4829 sameinset = inset->isChar() && inset->isLetter();
4830 if (sameinset && owner_->isDeleted(last)) {
4831 appendSkipPosition(skips, last);
4836 if (sameinset && last < to) {
4837 // now check for language change
4838 samelang = lang == getSpellLanguage(last);
4841 // if language change detected backstep is needed
4849 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4852 const_cast<Language *>(owner_->getFontSettings(
4853 inset_owner_->buffer().params(), from).language());
4854 if (lang == inset_owner_->buffer().params().language
4855 && !lyxrc.spellchecker_alt_lang.empty()) {
4857 string const lang_variety =
4858 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4859 lang->setCode(lang_code);
4860 lang->setVariety(lang_variety);
4866 void Paragraph::requestSpellCheck(pos_type pos)
4868 d->requestSpellCheck(pos);
4870 // Also request spellcheck within (text) insets
4871 for (auto const & insets : insetList()) {
4872 if (!insets.inset->asInsetText())
4874 ParagraphList & inset_pars =
4875 insets.inset->asInsetText()->paragraphs();
4876 ParagraphList::iterator pit = inset_pars.begin();
4877 ParagraphList::iterator pend = inset_pars.end();
4878 for (; pit != pend; ++pit)
4879 pit->requestSpellCheck();
4885 bool Paragraph::needsSpellCheck() const
4887 SpellChecker::ChangeNumber speller_change_number = 0;
4888 if (theSpellChecker())
4889 speller_change_number = theSpellChecker()->changeNumber();
4890 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4891 d->speller_state_.needsCompleteRefresh(speller_change_number);
4893 return d->needsSpellCheck();
4897 bool Paragraph::Private::ignoreWord(docstring const & word) const
4899 // Ignore words with digits
4900 // FIXME: make this customizable
4901 // (note that some checkers ignore words with digits by default)
4902 docstring::const_iterator cit = word.begin();
4903 docstring::const_iterator const end = word.end();
4904 for (; cit != end; ++cit) {
4905 if (isNumber((*cit)))
4912 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4913 WordLangTuple & wl, docstring_list & suggestions,
4914 bool do_suggestion, bool check_learned) const
4916 SpellChecker::Result result = SpellChecker::WORD_OK;
4917 SpellChecker * speller = theSpellChecker();
4921 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4924 locateWord(from, to, WHOLE_WORD, true);
4925 if (from == to || from >= size())
4928 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4929 Language * lang = d->getSpellLanguage(from);
4931 BufferParams const & bparams = d->inset_owner_->buffer().params();
4933 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4936 wl = WordLangTuple(word, lang);
4941 if (needsSpellCheck() || check_learned) {
4943 if (!d->ignoreWord(word)) {
4944 bool const trailing_dot = to < size() && d->text_[to] == '.';
4945 result = speller->check(wl, bparams.spellignore());
4946 if (SpellChecker::misspelled(result) && trailing_dot) {
4947 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4948 result = speller->check(wl, bparams.spellignore());
4949 if (!SpellChecker::misspelled(result)) {
4950 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4952 from << ".." << to << "]");
4954 // spell check with dot appended failed too
4955 // restore original word/lang value
4956 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4957 wl = WordLangTuple(word, lang);
4961 if (!SpellChecker::misspelled(result)) {
4962 // area up to the begin of the next word is not misspelled
4963 while (end < size() && isWordSeparator(end))
4966 d->setMisspelled(from, end, result);
4968 result = d->speller_state_.getState(from);
4972 suggestions.clear();
4974 if (SpellChecker::misspelled(result)) {
4975 LYXERR(Debug::GUI, "misspelled word: \"" <<
4977 from << ".." << to << "]");
4979 speller->suggest(wl, suggestions);
4985 void Paragraph::anonymize()
4987 // This is a very crude anonymization for now
4988 for (char_type & c : d->text_)
4989 if (isLetterChar(c) || isNumber(c))
4994 void Paragraph::Private::markMisspelledWords(
4995 Language const * lang,
4996 pos_type const & first, pos_type const & last,
4997 SpellChecker::Result result,
4998 docstring const & word,
4999 SkipPositions const & skips)
5001 if (!SpellChecker::misspelled(result)) {
5002 setMisspelled(first, last, SpellChecker::WORD_OK);
5006 SpellChecker * speller = theSpellChecker();
5007 // locate and enumerate the error positions
5008 int nerrors = speller->numMisspelledWords();
5010 SkipPositionsIterator it = skips.begin();
5011 SkipPositionsIterator et = skips.end();
5012 for (int index = 0; index < nerrors; ++index) {
5015 speller->misspelledWord(index, wstart, wlen);
5016 /// should not happen if speller supports range checks
5019 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5020 wstart += first + numskipped;
5021 if (snext < wstart) {
5022 /// mark the range of correct spelling
5023 numskipped += countSkips(it, et, wstart);
5024 setMisspelled(snext,
5025 wstart - 1, SpellChecker::WORD_OK);
5027 snext = wstart + wlen;
5028 // Check whether the candidate is in the document's local dict
5029 SpellChecker::Result actresult = result;
5030 if (inset_owner_->buffer().params().spellignored(candidate))
5031 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5032 numskipped += countSkips(it, et, snext);
5033 /// mark the range of misspelling
5034 setMisspelled(wstart, snext, actresult);
5035 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5036 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5037 candidate.word() << "\" [" <<
5038 wstart << ".." << (snext-1) << "]");
5040 LYXERR(Debug::GUI, "misspelled word: \"" <<
5041 candidate.word() << "\" [" <<
5042 wstart << ".." << (snext-1) << "]");
5045 if (snext <= last) {
5046 /// mark the range of correct spelling at end
5047 setMisspelled(snext, last, SpellChecker::WORD_OK);
5052 void Paragraph::spellCheck() const
5054 SpellChecker * speller = theSpellChecker();
5055 if (!speller || empty() ||!needsSpellCheck())
5059 d->rangeOfSpellCheck(start, endpos);
5060 if (speller->canCheckParagraph()) {
5061 // loop until we leave the range
5062 for (pos_type first = start; first < endpos; ) {
5063 pos_type last = endpos;
5064 Private::SkipPositions skips;
5065 Language * lang = d->locateSpellRange(first, last, skips);
5066 if (first >= endpos)
5068 // start the spell checker on the unit of meaning
5069 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5070 WordLangTuple wl = WordLangTuple(word, lang);
5071 BufferParams const & bparams = d->inset_owner_->buffer().params();
5072 SpellChecker::Result result = !word.empty() ?
5073 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5074 d->markMisspelledWords(lang, first, last, result, word, skips);
5078 static docstring_list suggestions;
5079 pos_type to = endpos;
5080 while (start < endpos) {
5082 spellCheck(start, to, wl, suggestions, false);
5086 d->readySpellCheck();
5090 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5092 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5093 if (result || pos <= 0 || pos > size())
5095 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5096 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5101 string Paragraph::magicLabel() const
5104 ss << "magicparlabel-" << id();