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()
1152 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1158 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1162 runparams.local_font = &basefont;
1165 if (fontswitch_inset && !closeLanguage) {
1166 // The directionality has been switched at inset.
1167 // Force markup inside.
1168 runparams.local_font = &basefont;
1171 size_t const previous_row_count = os.texrow().rows();
1174 runparams.lastid = id_;
1175 runparams.lastpos = i;
1176 inset->latex(os, runparams);
1177 } catch (EncodingException & e) {
1178 // add location information and throw again.
1187 if (os.texrow().rows() > previous_row_count) {
1188 os.texrow().start(owner_->id(), i + 1);
1191 column += (unsigned int)(os.os().tellp() - len);
1194 if (owner_->isDeleted(i))
1195 --runparams.inDeletedInset;
1199 void Paragraph::Private::latexSpecialChar(otexstream & os,
1200 BufferParams const & bparams,
1201 OutputParams const & runparams,
1202 Font const & running_font,
1203 string & alien_script,
1204 Layout const & style,
1207 unsigned int & column) const
1209 char_type const c = owner_->getUChar(bparams, runparams, i);
1211 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1212 || contains(style.pass_thru_chars, c)
1213 || contains(runparams.pass_thru_chars, c)) {
1214 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1218 os << "\\braceleft ";
1220 os << "\\braceright ";
1224 else if (c != '\0') {
1225 Encoding const * const enc = runparams.encoding;
1226 if (enc && !enc->encodable(c))
1227 throw EncodingException(c);
1233 // TIPA uses its own T3 encoding
1234 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1236 // If T1 font encoding is used, use the special
1237 // characters it provides.
1238 // NOTE: Some languages reset the font encoding internally to a
1239 // non-standard font encoding. If we are using such a language,
1240 // we do not output special T1 chars.
1241 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1242 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1243 && latexSpecialT1(c, os, i, column))
1245 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1246 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1247 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1250 // Otherwise, we use what LaTeX provides us.
1253 os << "\\textbackslash" << termcmd;
1257 os << "\\textless" << termcmd;
1261 os << "\\textgreater" << termcmd;
1265 os << "\\textbar" << termcmd;
1270 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1271 (end_pos == -1 || i + 1 < end_pos) &&
1272 text_[i+1] == '-') {
1273 // Prevent "--" becoming an en dash and "---" an em dash.
1274 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1280 os << "\\textquotedbl" << termcmd;
1285 case '%': case '#': case '{':
1293 os << "\\textasciitilde" << termcmd;
1298 os << "\\textasciicircum" << termcmd;
1305 // avoid being mistaken for optional arguments
1313 // Blanks are printed before font switching.
1314 // Sure? I am not! (try nice-latex)
1315 // I am sure it's correct. LyX might be smarter
1316 // in the future, but for now, nothing wrong is
1322 // XeTeX's dash behaviour is determined via a global setting
1323 if (bparams.use_dash_ligatures
1324 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1326 // TODO #10961: && not in inset Flex Code
1327 // TODO #10961: && not in layout LyXCode
1328 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1345 Encoding const & encoding = *(runparams.encoding);
1346 char_type next = '\0';
1347 if (i + 1 < int(text_.size())) {
1348 next = text_[i + 1];
1349 if (Encodings::isCombiningChar(next)) {
1350 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1355 pair<docstring, bool> latex = encoding.latexChar(c);
1356 docstring nextlatex;
1357 bool nexttipas = false;
1358 string nexttipashortcut;
1359 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1360 nextlatex = encoding.latexChar(next).first;
1361 if (runparams.inIPA) {
1362 nexttipashortcut = Encodings::TIPAShortcut(next);
1363 nexttipas = !nexttipashortcut.empty();
1367 if (runparams.inIPA) {
1368 string const tipashortcut = Encodings::TIPAShortcut(c);
1369 if (!tipashortcut.empty()) {
1370 latex.first = from_ascii(tipashortcut);
1371 latex.second = false;
1375 // eventually close "script wrapper" command (see `Paragraph::latex`)
1376 if (!alien_script.empty()
1377 && alien_script != Encodings::isKnownScriptChar(next)) {
1378 column += latex.first.length();
1379 alien_script.clear();
1380 os << latex.first << "}";
1384 && ((!prefixIs(nextlatex, '\\')
1385 && !prefixIs(nextlatex, '{')
1386 && !prefixIs(nextlatex, '}'))
1388 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1390 // Prevent eating of a following space or command corruption by
1391 // following characters
1392 if (next == ' ' || next == '\0') {
1393 column += latex.first.length() + 1;
1394 os << latex.first << "{}";
1396 column += latex.first.length();
1397 os << latex.first << " ";
1400 column += latex.first.length() - 1;
1408 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1409 pos_type i, unsigned int & column) const
1415 // In T1 encoding, these characters exist
1416 // but we should avoid ligatures
1417 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1419 os << "\\textcompwordmark" << termcmd;
1426 // soul.sty breaks with \char`\"
1427 os << "\\textquotedbl" << termcmd;
1436 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1437 pos_type i, unsigned int & column) const
1439 // TU encoding is currently on par with T1.
1440 return latexSpecialT1(c, os, i, column);
1444 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1445 pos_type /*i*/, unsigned int & column) const
1455 os << "\\textvertline" << termcmd;
1464 void Paragraph::Private::validate(LaTeXFeatures & features) const
1466 if (layout_->inpreamble && inset_owner_) {
1467 // FIXME: Using a string stream here circumvents the encoding
1468 // switching machinery of odocstream. Therefore the
1469 // output is wrong if this paragraph contains content
1470 // that needs to switch encoding.
1471 Buffer const & buf = inset_owner_->buffer();
1472 otexstringstream os;
1473 os << layout_->preamble();
1474 size_t const length = os.length();
1475 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1476 buf.getParFromID(owner_->id()).pit(), os,
1477 features.runparams(), string(), 0, -1, true);
1478 if (os.length() > length)
1479 features.addPreambleSnippet(os.release(), true);
1482 if (features.runparams().flavor == Flavor::Html
1483 && layout_->htmltitle()) {
1484 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1487 // check the params.
1488 if (!params_.spacing().isDefault())
1489 features.require("setspace");
1492 features.useLayout(layout_->name());
1495 fontlist_.validate(features);
1497 // then the indentation
1498 if (!params_.leftIndent().zero())
1499 features.require("ParagraphLeftIndent");
1502 InsetList::const_iterator icit = insetlist_.begin();
1503 InsetList::const_iterator iend = insetlist_.end();
1504 for (; icit != iend; ++icit) {
1506 features.inDeletedInset(owner_->isDeleted(icit->pos));
1507 if (icit->inset->lyxCode() == FOOT_CODE) {
1508 // FIXME: an item inset would make things much easier.
1509 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1510 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1511 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1512 && (icit->pos < begin_of_body_
1513 || (icit->pos == begin_of_body_
1514 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1515 features.saveNoteEnv("description");
1517 icit->inset->validate(features);
1518 features.inDeletedInset(false);
1519 if (layout_->needprotect &&
1520 icit->inset->lyxCode() == FOOT_CODE)
1521 features.require("NeedLyXFootnoteCode");
1525 // then the contents
1526 BufferParams const bp = features.runparams().is_child
1527 ? features.buffer().masterParams() : features.buffer().params();
1528 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1529 char_type c = text_[i];
1530 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1532 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1533 features.require("textquotedblp");
1534 else if (bp.main_font_encoding() != "T1"
1535 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1536 features.require("textquotedbl");
1537 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1538 // features that depend on the font or input encoding
1539 string feats = ci.textpreamble();
1540 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1541 if (fontenc.empty())
1542 fontenc = features.runparams().main_fontenc;
1543 while (!feats.empty()) {
1545 feats = split(feats, feat, ',');
1546 if (contains(feat, "!=")) {
1547 // a feature that is required except for the spcified
1548 // font or input encodings
1550 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1551 // multiple encodings are separated by semicolon
1552 vector<string> context = getVectorFromString(contexts, ";");
1553 // require feature if the context matches neither current font
1554 // nor input encoding
1555 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1556 && std::find(context.begin(), context.end(),
1557 features.runparams().encoding->name()) == context.end())
1558 features.require(realfeature);
1559 } else if (contains(feat, '=')) {
1560 // a feature that is required only for the spcified
1561 // font or input encodings
1563 string const contexts = split(feat, realfeature, '=');
1564 // multiple encodings are separated by semicolon
1565 vector<string> context = getVectorFromString(contexts, ";");
1566 // require feature if the context matches either current font
1567 // or input encoding
1568 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1569 || std::find(context.begin(), context.end(),
1570 features.runparams().encoding->name()) != context.end())
1571 features.require(realfeature);
1574 } else if (!bp.use_dash_ligatures
1575 && (c == 0x2013 || c == 0x2014)
1576 && bp.useNonTeXFonts
1577 && features.runparams().flavor == Flavor::XeTeX)
1578 // XeTeX's dash behaviour is determined via a global setting
1579 features.require("xetexdashbreakstate");
1580 BufferEncodings::validate(c, features);
1584 /////////////////////////////////////////////////////////////////////
1588 /////////////////////////////////////////////////////////////////////
1591 Layout const emptyParagraphLayout;
1594 Paragraph::Paragraph()
1595 : d(new Paragraph::Private(this, emptyParagraphLayout))
1602 Paragraph::Paragraph(Paragraph const & par)
1603 : itemdepth(par.itemdepth),
1604 d(new Paragraph::Private(*par.d, this))
1610 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1611 : itemdepth(par.itemdepth),
1612 d(new Paragraph::Private(*par.d, this, beg, end))
1618 Paragraph & Paragraph::operator=(Paragraph const & par)
1620 // needed as we will destroy the private part before copying it
1622 itemdepth = par.itemdepth;
1626 d = new Private(*par.d, this);
1633 Paragraph::~Paragraph()
1642 // this shall be called just before every "os << ..." action.
1643 void flushString(ostream & os, docstring & s)
1652 void Paragraph::write(ostream & os, BufferParams const & bparams,
1653 depth_type & depth) const
1655 // The beginning or end of a deeper (i.e. nested) area?
1656 if (depth != d->params_.depth()) {
1657 if (d->params_.depth() > depth) {
1658 while (d->params_.depth() > depth) {
1659 os << "\n\\begin_deeper";
1663 while (d->params_.depth() < depth) {
1664 os << "\n\\end_deeper";
1670 // First write the layout
1671 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1673 d->params_.write(os);
1675 Font font1(inherit_font, bparams.language);
1677 Change running_change = Change(Change::UNCHANGED);
1679 // this string is used as a buffer to avoid repetitive calls
1680 // to to_utf8(), which turn out to be expensive (JMarc)
1681 docstring write_buffer;
1684 for (pos_type i = 0; i <= size(); ++i) {
1686 Change const & change = lookupChange(i);
1687 if (change != running_change)
1688 flushString(os, write_buffer);
1689 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1690 running_change = change;
1695 // Write font changes
1696 Font font2 = getFontSettings(bparams, i);
1697 if (font2 != font1) {
1698 flushString(os, write_buffer);
1699 font2.lyxWriteChanges(font1, os);
1704 char_type const c = d->text_[i];
1707 if (Inset const * inset = getInset(i)) {
1708 flushString(os, write_buffer);
1709 if (inset->directWrite()) {
1710 // international char, let it write
1711 // code directly so it's shorter in
1717 os << "\\begin_inset ";
1719 os << "\n\\end_inset\n\n";
1722 // FIXME This can be removed again once the mystery
1723 // crash has been resolved.
1728 flushString(os, write_buffer);
1729 os << "\n\\backslash\n";
1733 flushString(os, write_buffer);
1734 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1741 if ((column > 70 && c == ' ')
1743 flushString(os, write_buffer);
1747 // this check is to amend a bug. LyX sometimes
1748 // inserts '\0' this could cause problems.
1750 write_buffer.push_back(c);
1752 LYXERR0("NUL char in structure.");
1758 flushString(os, write_buffer);
1759 os << "\n\\end_layout\n";
1760 // FIXME This can be removed again once the mystery
1761 // crash has been resolved.
1766 void Paragraph::validate(LaTeXFeatures & features) const
1768 d->validate(features);
1769 bool fragile = features.runparams().moving_arg;
1770 fragile |= layout().needprotect;
1771 if (inInset().getLayout().isNeedProtect())
1773 if (needsCProtection(fragile))
1774 features.require("cprotect");
1778 void Paragraph::insert(pos_type pos, docstring const & str,
1779 Font const & font, Change const & change)
1781 for (size_t i = 0, n = str.size(); i != n ; ++i)
1782 insertChar(pos + i, str[i], font, change);
1786 void Paragraph::appendChar(char_type c, Font const & font,
1787 Change const & change)
1789 // Make sure that Buffer::hasChangesPresent is updated
1790 ChangesMonitor cm(*this);
1793 d->changes_.insert(change, d->text_.size());
1794 // when appending characters, no need to update tables
1795 d->text_.push_back(c);
1796 setFont(d->text_.size() - 1, font);
1797 d->requestSpellCheck(d->text_.size() - 1);
1801 void Paragraph::appendString(docstring const & s, Font const & font,
1802 Change const & change)
1804 // Make sure that Buffer::hasChangesPresent is updated
1805 ChangesMonitor cm(*this);
1807 pos_type end = s.size();
1808 size_t oldsize = d->text_.size();
1809 size_t newsize = oldsize + end;
1810 size_t capacity = d->text_.capacity();
1811 if (newsize >= capacity)
1812 d->text_.reserve(max(capacity + 100, newsize));
1814 // when appending characters, no need to update tables
1817 // FIXME: Optimize this!
1818 for (size_t i = oldsize; i != newsize; ++i) {
1820 d->changes_.insert(change, i);
1821 d->requestSpellCheck(i);
1823 d->fontlist_.set(oldsize, font);
1824 d->fontlist_.set(newsize - 1, font);
1828 void Paragraph::insertChar(pos_type pos, char_type c,
1831 d->insertChar(pos, c, Change(trackChanges ?
1832 Change::INSERTED : Change::UNCHANGED));
1836 void Paragraph::insertChar(pos_type pos, char_type c,
1837 Font const & font, bool trackChanges)
1839 d->insertChar(pos, c, Change(trackChanges ?
1840 Change::INSERTED : Change::UNCHANGED));
1845 void Paragraph::insertChar(pos_type pos, char_type c,
1846 Font const & font, Change const & change)
1848 d->insertChar(pos, c, change);
1853 void Paragraph::resetFonts(Font const & font)
1855 d->fontlist_.clear();
1856 d->fontlist_.set(0, font);
1857 d->fontlist_.set(d->text_.size() - 1, font);
1860 // Gets uninstantiated font setting at position.
1861 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1865 LYXERR0("pos: " << pos << " size: " << size());
1869 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1870 if (cit != d->fontlist_.end())
1873 if (pos == size() && !empty())
1874 return getFontSettings(bparams, pos - 1);
1876 // Optimisation: avoid a full font instantiation if there is no
1877 // language change from previous call.
1878 static Font previous_font;
1879 static Language const * previous_lang = nullptr;
1880 Language const * lang = getParLanguage(bparams);
1881 if (lang != previous_lang) {
1882 previous_lang = lang;
1883 previous_font = Font(inherit_font, lang);
1885 return previous_font;
1889 FontSpan Paragraph::fontSpan(pos_type pos) const
1891 LBUFERR(pos <= size());
1894 return FontSpan(pos, pos);
1897 FontList::const_iterator cit = d->fontlist_.begin();
1898 FontList::const_iterator end = d->fontlist_.end();
1899 for (; cit != end; ++cit) {
1900 if (cit->pos() >= pos) {
1901 if (pos >= beginOfBody())
1902 return FontSpan(max(start, beginOfBody()),
1905 return FontSpan(start,
1906 min(beginOfBody() - 1,
1909 start = cit->pos() + 1;
1912 // This should not happen, but if so, we take no chances.
1913 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1914 LASSERT(false, return FontSpan(pos, pos));
1918 // Gets uninstantiated font setting at position 0
1919 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1921 if (!empty() && !d->fontlist_.empty())
1922 return d->fontlist_.begin()->font();
1924 // Optimisation: avoid a full font instantiation if there is no
1925 // language change from previous call.
1926 static Font previous_font;
1927 static Language const * previous_lang = nullptr;
1928 if (bparams.language != previous_lang) {
1929 previous_lang = bparams.language;
1930 previous_font = Font(inherit_font, bparams.language);
1933 return previous_font;
1937 // Gets the fully instantiated font at a given position in a paragraph
1938 // This is basically the same function as Text::GetFont() in text2.cpp.
1939 // The difference is that this one is used for generating the LaTeX file,
1940 // and thus cosmetic "improvements" are disallowed: This has to deliver
1941 // the true picture of the buffer. (Asger)
1942 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1943 Font const & outerfont) const
1947 Font font = getFontSettings(bparams, pos);
1949 pos_type const body_pos = beginOfBody();
1950 FontInfo & fi = font.fontInfo();
1952 fi.realize(d->layout_->labelfont);
1954 fi.realize(d->layout_->font);
1956 fi.realize(outerfont.fontInfo());
1957 fi.realize(bparams.getFont().fontInfo());
1963 Font const Paragraph::getLabelFont
1964 (BufferParams const & bparams, Font const & outerfont) const
1966 FontInfo tmpfont = d->layout_->labelfont;
1967 tmpfont.realize(outerfont.fontInfo());
1968 tmpfont.realize(bparams.getFont().fontInfo());
1969 return Font(tmpfont, getParLanguage(bparams));
1973 Font const Paragraph::getLayoutFont
1974 (BufferParams const & bparams, Font const & outerfont) const
1976 FontInfo tmpfont = d->layout_->font;
1977 tmpfont.realize(outerfont.fontInfo());
1978 tmpfont.realize(bparams.getFont().fontInfo());
1979 return Font(tmpfont, getParLanguage(bparams));
1983 char_type Paragraph::getUChar(BufferParams const & bparams,
1984 OutputParams const & rp,
1987 char_type c = d->text_[pos];
1989 // Return unchanged character in LTR languages
1990 // or if we use poylglossia/bidi (XeTeX).
1991 if (rp.useBidiPackage()
1992 || !getFontSettings(bparams, pos).isRightToLeft())
1995 // Without polyglossia/bidi, we need to account for some special cases.
1996 // FIXME This needs to be audited!
1998 // * The input is as expected for all delimiters
1999 // => checked for Hebrew!
2000 // * The output matches the display in the LyX workarea
2001 // => checked for Hebrew!
2002 // * The special cases below are really necessary
2003 // => checked for Hebrew!
2004 // * In arabic_arabi, brackets are transformed to Arabic
2005 // Ornate Parentheses. Is this is really wanted?
2007 string const & lang = getFontSettings(bparams, pos).language()->lang();
2010 // 1. In the following languages, parentheses need to be reversed.
2011 // Also with polyglodia/luabidi
2012 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2014 // 2. In the following languages, brackets don't need to be reversed.
2015 bool const reversebrackets = lang != "arabic_arabtex"
2016 && lang != "arabic_arabi"
2019 // Now swap delimiters if needed.
2030 if (reversebrackets)
2034 if (reversebrackets)
2055 void Paragraph::setFont(pos_type pos, Font const & font)
2057 LASSERT(pos <= size(), return);
2059 // First, reduce font against layout/label font
2060 // Update: The setCharFont() routine in text2.cpp already
2061 // reduces font, so we don't need to do that here. (Asger)
2063 d->fontlist_.set(pos, font);
2067 void Paragraph::makeSameLayout(Paragraph const & par)
2069 d->layout_ = par.d->layout_;
2070 d->params_ = par.d->params_;
2074 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2076 if (isFreeSpacing())
2082 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2083 if (eraseChar(pos, trackChanges))
2089 return count > 0 || pos > 0;
2093 bool Paragraph::hasSameLayout(Paragraph const & par) const
2095 return par.d->layout_ == d->layout_
2096 && d->params_.sameLayout(par.d->params_);
2100 depth_type Paragraph::getDepth() const
2102 return d->params_.depth();
2106 depth_type Paragraph::getMaxDepthAfter() const
2108 if (d->layout_->isEnvironment())
2109 return d->params_.depth() + 1;
2111 return d->params_.depth();
2115 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2117 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2118 return getDefaultAlign(bparams);
2120 return d->params_.align();
2124 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2126 LyXAlignment res = layout().align;
2127 if (isRTL(bparams)) {
2129 if (res == LYX_ALIGN_LEFT)
2130 res = LYX_ALIGN_RIGHT;
2131 else if (res == LYX_ALIGN_RIGHT)
2132 res = LYX_ALIGN_LEFT;
2138 docstring const & Paragraph::labelString() const
2140 return d->params_.labelString();
2144 // the next two functions are for the manual labels
2145 docstring const Paragraph::getLabelWidthString() const
2147 if (d->layout_->margintype == MARGIN_MANUAL
2148 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2149 return d->params_.labelWidthString();
2151 return _("Senseless with this layout!");
2155 void Paragraph::setLabelWidthString(docstring const & s)
2157 d->params_.labelWidthString(s);
2161 docstring Paragraph::expandLabel(Layout const & layout,
2162 BufferParams const & bparams) const
2164 return expandParagraphLabel(layout, bparams, true);
2168 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2169 BufferParams const & bparams, bool process_appendix) const
2171 DocumentClass const & tclass = bparams.documentClass();
2172 string const & lang = getParLanguage(bparams)->code();
2173 bool const in_appendix = process_appendix && d->params_.appendix();
2174 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2176 if (fmt.empty() && !layout.counter.empty())
2177 return tclass.counters().theCounter(layout.counter, lang);
2179 // handle 'inherited level parts' in 'fmt',
2180 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2181 size_t const i = fmt.find('@', 0);
2182 if (i != docstring::npos) {
2183 size_t const j = fmt.find('@', i + 1);
2184 if (j != docstring::npos) {
2185 docstring parent(fmt, i + 1, j - i - 1);
2186 docstring label = from_ascii("??");
2187 if (tclass.hasLayout(parent))
2188 label = expandParagraphLabel(tclass[parent], bparams,
2190 fmt = docstring(fmt, 0, i) + label
2191 + docstring(fmt, j + 1, docstring::npos);
2195 return tclass.counters().counterLabel(fmt, lang);
2199 void Paragraph::applyLayout(Layout const & new_layout)
2201 d->layout_ = &new_layout;
2202 LyXAlignment const oldAlign = d->params_.align();
2204 if (!(oldAlign & d->layout_->alignpossible)) {
2205 frontend::Alert::warning(_("Alignment not permitted"),
2206 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2207 d->params_.align(LYX_ALIGN_LAYOUT);
2212 pos_type Paragraph::beginOfBody() const
2214 return d->begin_of_body_;
2218 void Paragraph::setBeginOfBody()
2220 if (d->layout_->labeltype != LABEL_MANUAL) {
2221 d->begin_of_body_ = 0;
2225 // Unroll the first two cycles of the loop
2226 // and remember the previous character to
2227 // remove unnecessary getChar() calls
2229 pos_type end = size();
2230 bool prev_char_deleted = false;
2231 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2234 char_type previous_char = d->text_[i];
2235 if (!(isNewline(i) || isEnvSeparator(i))) {
2237 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2238 char_type temp = d->text_[i];
2239 prev_char_deleted = isDeleted(i);
2240 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2243 previous_char = temp;
2249 d->begin_of_body_ = i;
2253 bool Paragraph::allowParagraphCustomization() const
2255 return inInset().allowParagraphCustomization();
2259 bool Paragraph::usePlainLayout() const
2261 return inInset().usePlainLayout();
2265 bool Paragraph::isPassThru() const
2267 return inInset().isPassThru() || d->layout_->pass_thru;
2272 // paragraphs inside floats need different alignment tags to avoid
2275 bool noTrivlistCentering(InsetCode code)
2277 return code == FLOAT_CODE
2278 || code == WRAP_CODE
2279 || code == CELL_CODE;
2283 string correction(string const & orig)
2285 if (orig == "flushleft")
2286 return "raggedright";
2287 if (orig == "flushright")
2288 return "raggedleft";
2289 if (orig == "center")
2295 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2296 InsetCode code, bool const lastpar, int & col)
2298 string macro = suffix + "{";
2299 if (noTrivlistCentering(code)) {
2301 // the last paragraph in non-trivlist-aligned
2302 // context is special (to avoid unwanted whitespace)
2303 if (suffix == "\\begin") {
2304 macro = "\\" + correction(env) + "{}";
2305 os << from_ascii(macro);
2306 col += macro.size();
2311 macro += correction(env);
2315 if (suffix == "\\par\\end") {
2319 os << from_ascii(macro);
2320 col += macro.size();
2321 if (suffix == "\\begin") {
2331 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2332 otexstream & os, OutputParams const & runparams) const
2337 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2338 (layout_->toggle_indent != ITOGGLE_NEVER) :
2339 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2341 if (canindent && params_.noindent() && !layout_->pass_thru) {
2342 os << "\\noindent ";
2346 LyXAlignment const curAlign = params_.align();
2348 if (curAlign == layout_->align)
2352 case LYX_ALIGN_NONE:
2353 case LYX_ALIGN_BLOCK:
2354 case LYX_ALIGN_LAYOUT:
2355 case LYX_ALIGN_SPECIAL:
2356 case LYX_ALIGN_DECIMAL:
2358 case LYX_ALIGN_LEFT:
2359 case LYX_ALIGN_RIGHT:
2360 case LYX_ALIGN_CENTER:
2361 if (runparams.moving_arg) {
2368 string const begin_tag = "\\begin";
2369 InsetCode code = ownerCode();
2370 bool const lastpar = runparams.isLastPar;
2371 // RTL in classic (PDF)LaTeX (without the Bidi package)
2372 // Luabibdi (used by LuaTeX) behaves like classic
2373 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2374 && !runparams.useBidiPackage();
2377 case LYX_ALIGN_NONE:
2378 case LYX_ALIGN_BLOCK:
2379 case LYX_ALIGN_LAYOUT:
2380 case LYX_ALIGN_SPECIAL:
2381 case LYX_ALIGN_DECIMAL:
2383 case LYX_ALIGN_LEFT: {
2385 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2386 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2388 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2390 } case LYX_ALIGN_RIGHT: {
2392 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2393 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2395 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2397 } case LYX_ALIGN_CENTER: {
2398 corrected_env(os, begin_tag, "center", code, lastpar, column);
2407 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2408 otexstream & os, OutputParams const & runparams) const
2410 LyXAlignment const curAlign = params_.align();
2412 if (curAlign == layout_->align)
2416 case LYX_ALIGN_NONE:
2417 case LYX_ALIGN_BLOCK:
2418 case LYX_ALIGN_LAYOUT:
2419 case LYX_ALIGN_SPECIAL:
2420 case LYX_ALIGN_DECIMAL:
2422 case LYX_ALIGN_LEFT:
2423 case LYX_ALIGN_RIGHT:
2424 case LYX_ALIGN_CENTER:
2425 if (runparams.moving_arg)
2430 bool output = false;
2432 string const end_tag = "\\par\\end";
2433 InsetCode code = ownerCode();
2434 bool const lastpar = runparams.isLastPar;
2435 // RTL in classic (PDF)LaTeX (without the Bidi package)
2436 // Luabibdi (used by LuaTeX) behaves like classic
2437 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2438 && !runparams.useBidiPackage();
2441 case LYX_ALIGN_NONE:
2442 case LYX_ALIGN_BLOCK:
2443 case LYX_ALIGN_LAYOUT:
2444 case LYX_ALIGN_SPECIAL:
2445 case LYX_ALIGN_DECIMAL:
2447 case LYX_ALIGN_LEFT: {
2449 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2450 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2452 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2454 } case LYX_ALIGN_RIGHT: {
2456 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2457 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2459 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2461 } case LYX_ALIGN_CENTER: {
2462 corrected_env(os, end_tag, "center", code, lastpar, col);
2467 return output || lastpar;
2471 // This one spits out the text of the paragraph
2472 void Paragraph::latex(BufferParams const & bparams,
2473 Font const & outerfont,
2475 OutputParams const & runparams,
2476 int start_pos, int end_pos, bool force) const
2478 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2480 // FIXME This check should not be needed. Perhaps issue an
2481 // error if it triggers.
2482 Layout const & style = inInset().forcePlainLayout() ?
2483 bparams.documentClass().plainLayout() : *d->layout_;
2485 if (!force && style.inpreamble)
2488 bool const allowcust = allowParagraphCustomization();
2490 // Current base font for all inherited font changes, without any
2491 // change caused by an individual character, except for the language:
2492 // It is set to the language of the first character.
2493 // As long as we are in the label, this font is the base font of the
2494 // label. Before the first body character it is set to the base font
2498 // If there is an open font-encoding changing command (script wrapper),
2499 // alien_script is set to its name
2500 string alien_script;
2503 // Maybe we have to create a optional argument.
2504 pos_type body_pos = beginOfBody();
2505 unsigned int column = 0;
2507 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2508 Font const real_outerfont = (!inInset().inheritFont()
2509 && runparams.local_font != nullptr)
2510 ? Font(runparams.local_font->fontInfo()) : outerfont;
2513 // the optional argument is kept in curly brackets in
2514 // case it contains a ']'
2515 // This is not strictly needed, but if this is changed it
2516 // would be a file format change, and tex2lyx would need
2517 // to be adjusted, since it unconditionally removes the
2518 // braces when it parses \item.
2521 basefont = getLabelFont(bparams, real_outerfont);
2523 basefont = getLayoutFont(bparams, real_outerfont);
2526 // Which font is currently active?
2527 Font running_font(basefont);
2528 // Do we have an open font change?
2529 bool open_font = false;
2531 Change runningChange =
2532 runparams.inDeletedInset && !inInset().canTrackChanges()
2533 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2535 Encoding const * const prev_encoding = runparams.encoding;
2537 os.texrow().start(id(), 0);
2539 // if the paragraph is empty, the loop will not be entered at all
2541 // For InTitle commands, we have already opened a group
2542 // in output_latex::TeXOnePar.
2543 if (style.isCommand() && !style.intitle) {
2547 if (!style.leftdelim().empty()) {
2548 os << style.leftdelim();
2549 column += style.leftdelim().size();
2552 column += d->startTeXParParams(bparams, os, runparams);
2555 // Whether a \par can be issued for insets typeset inline with text.
2556 // Yes if greater than 0. This has to be static.
2557 THREAD_LOCAL_STATIC int parInline = 0;
2559 for (pos_type i = 0; i < size(); ++i) {
2560 // First char in paragraph or after label?
2561 if (i == body_pos) {
2564 bool needPar = false;
2565 column += running_font.latexWriteEndChanges(
2566 os, bparams, runparams,
2567 basefont, basefont, needPar);
2570 basefont = getLayoutFont(bparams, real_outerfont);
2571 running_font = basefont;
2573 column += Changes::latexMarkChange(os, bparams,
2574 runningChange, Change(Change::UNCHANGED),
2576 runningChange = Change(Change::UNCHANGED);
2578 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2581 // For InTitle commands, we have already opened a group
2582 // in output_latex::TeXOnePar.
2583 if (style.isCommand() && !style.intitle) {
2588 if (!style.leftdelim().empty()) {
2589 os << style.leftdelim();
2590 column += style.leftdelim().size();
2594 column += d->startTeXParParams(bparams, os,
2598 runparams.wasDisplayMath = runparams.inDisplayMath;
2599 runparams.inDisplayMath = false;
2600 bool deleted_display_math = false;
2601 Change const & change = runparams.inDeletedInset
2602 ? runparams.changeOfDeletedInset : lookupChange(i);
2604 char_type const c = d->text_[i];
2606 // Check whether a display math inset follows
2607 bool output_changes;
2608 if (runparams.for_searchAdv == OutputParams::NoSearch)
2609 output_changes = bparams.output_changes;
2611 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2613 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2615 runparams.ctObject = getInset(i)->getCtObject(runparams);
2617 InsetMath const * im = getInset(i)->asInsetMath();
2618 if (im && im->asHullInset()
2619 && im->asHullInset()->outerDisplay()) {
2620 runparams.inDisplayMath = true;
2621 // runparams.inDeletedInset will be set by
2622 // latexInset later, but we need this info
2623 // before it is called. On the other hand, we
2624 // cannot set it here because it is a counter.
2625 deleted_display_math = isDeleted(i);
2627 if (output_changes && deleted_display_math
2628 && runningChange == change
2629 && change.type == Change::DELETED
2630 && !os.afterParbreak()) {
2631 // A display math in the same paragraph follows.
2632 // We have to close and then reopen \lyxdeleted,
2633 // otherwise the math will be shifted up.
2634 OutputParams rp = runparams;
2636 bool needPar = false;
2637 column += running_font.latexWriteEndChanges(
2638 os, bparams, rp, basefont,
2642 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2643 : getLayoutFont(bparams, real_outerfont);
2644 running_font = basefont;
2645 column += Changes::latexMarkChange(os, bparams,
2646 Change(Change::INSERTED), change, rp);
2650 if (output_changes && runningChange != change) {
2651 if (!alien_script.empty()) {
2654 alien_script.clear();
2657 bool needPar = false;
2658 column += running_font.latexWriteEndChanges(
2659 os, bparams, runparams,
2660 basefont, basefont, needPar);
2663 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2664 : getLayoutFont(bparams, real_outerfont);
2665 running_font = basefont;
2666 column += Changes::latexMarkChange(os, bparams, runningChange,
2668 runningChange = change;
2671 // do not output text which is marked deleted
2672 // if change tracking output is disabled
2673 if (!output_changes && change.deleted()) {
2679 // Fully instantiated font
2680 Font current_font = getFont(bparams, i, outerfont);
2682 Font const prev_font = (i > 0) ?
2683 getFont(bparams, i - 1, outerfont)
2686 Font const last_font = running_font;
2687 bool const in_ct_deletion = (output_changes
2688 && runningChange == change
2689 && change.type == Change::DELETED
2690 && !os.afterParbreak());
2691 // Insets where font switches are used (rather than font commands)
2692 bool const fontswitch_inset =
2695 && getInset(i)->allowMultiPar()
2696 && getInset(i)->lyxCode() != ERT_CODE
2697 && getInset(i)->producesOutput();
2699 bool closeLanguage = false;
2700 bool lang_switched_at_inset = false;
2701 if (fontswitch_inset) {
2702 // Some insets cannot be inside a font change command.
2703 // However, even such insets *can* be placed in \L or \R
2704 // or their equivalents (for RTL language switches),
2705 // so we don't close the language in those cases
2706 // (= differing isRightToLeft()).
2707 // ArabTeX, though, doesn't seem to handle this special behavior.
2708 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2709 || basefont.language()->lang() == "arabic_arabtex"
2710 || current_font.language()->lang() == "arabic_arabtex";
2711 // We need to check prev_font as language changes directly at inset
2712 // will only be started inside the inset.
2713 lang_switched_at_inset = prev_font.language() != current_font.language();
2716 // Do we need to close the previous font?
2717 bool langClosed = false;
2719 ((current_font != running_font
2720 || current_font.language() != running_font.language())
2721 || (fontswitch_inset
2722 && (current_font == prev_font))))
2724 // ensure there is no open script-wrapper
2725 if (!alien_script.empty()) {
2728 alien_script.clear();
2730 if (in_ct_deletion) {
2731 // We have to close and then reopen \lyxdeleted,
2732 // as strikeout needs to be on lowest level.
2737 // Force language closing
2738 current_font.setLanguage(basefont.language());
2739 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2740 bool needPar = false;
2741 column += running_font.latexWriteEndChanges(
2742 os, bparams, runparams, basefont,
2744 if (in_ct_deletion) {
2745 // We have to close and then reopen \lyxdeleted,
2746 // as strikeout needs to be on lowest level.
2747 OutputParams rp = runparams;
2748 column += Changes::latexMarkChange(os, bparams,
2749 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2752 // Has the language been closed in the latexWriteEndChanges() call above?
2753 langClosed = running_font.language() != basefont.language()
2754 && running_font.language() != nextfont.language()
2755 && (running_font.language()->encoding()->package() != Encoding::CJK);
2756 running_font = basefont;
2759 // if necessary, close language environment before opening CJK
2760 string const running_lang = running_font.language()->babel();
2761 string const lang_end_command = lyxrc.language_command_end;
2762 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2763 && !running_lang.empty()
2764 && running_lang == openLanguageName()
2765 && current_font.language()->encoding()->package() == Encoding::CJK) {
2766 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2767 os << from_ascii(end_tag);
2768 column += end_tag.length();
2772 // Switch file encoding if necessary (and allowed)
2773 if ((!fontswitch_inset || closeLanguage)
2774 && !runparams.pass_thru && !style.pass_thru &&
2775 runparams.encoding->package() != Encoding::none &&
2776 current_font.language()->encoding()->package() != Encoding::none) {
2777 pair<bool, int> const enc_switch =
2778 switchEncoding(os.os(), bparams, runparams,
2779 *(current_font.language()->encoding()));
2780 if (enc_switch.first) {
2781 column += enc_switch.second;
2782 runparams.encoding = current_font.language()->encoding();
2786 // A display math inset inside an ulem command will be output
2787 // as a box of width \linewidth, so we have to either disable
2788 // indentation if the inset starts a paragraph, or start a new
2789 // line to accommodate such box. This has to be done before
2790 // writing any font changing commands.
2791 if (runparams.inDisplayMath && !deleted_display_math
2792 && runparams.inulemcmd) {
2793 if (os.afterParbreak())
2799 // Do we need to change font?
2800 if ((current_font != running_font ||
2801 current_font.language() != running_font.language())
2802 && i != body_pos - 1)
2804 if (!fontswitch_inset) {
2805 if (in_ct_deletion) {
2806 // We have to close and then reopen \lyxdeleted,
2807 // as strikeout needs to be on lowest level.
2808 OutputParams rp = runparams;
2809 bool needPar = false;
2810 column += running_font.latexWriteEndChanges(
2811 os, bparams, rp, basefont,
2816 otexstringstream ots;
2817 InsetText const * textinset = inInset().asInsetText();
2818 bool const cprotect = textinset
2819 ? textinset->hasCProtectContent(runparams.moving_arg)
2820 && !textinset->text().isMainText()
2822 column += current_font.latexWriteStartChanges(ots, bparams,
2823 runparams, basefont, last_font, false,
2825 // Check again for display math in ulem commands as a
2826 // font change may also occur just before a math inset.
2827 if (runparams.inDisplayMath && !deleted_display_math
2828 && runparams.inulemcmd) {
2829 if (os.afterParbreak())
2834 running_font = current_font;
2836 docstring fontchange = ots.str();
2838 // check whether the fontchange ends with a \\textcolor
2839 // modifier and the text starts with a space. If so we
2840 // need to add } in order to prevent \\textcolor from gobbling
2841 // the space (bug 4473).
2842 docstring const last_modifier = rsplit(fontchange, '\\');
2843 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2844 os << from_ascii("{}");
2845 else if (ots.terminateCommand())
2847 if (in_ct_deletion) {
2848 // We have to close and then reopen \lyxdeleted,
2849 // as strikeout needs to be on lowest level.
2850 OutputParams rp = runparams;
2851 column += Changes::latexMarkChange(os, bparams,
2852 Change(Change::UNCHANGED), change, rp);
2855 running_font = current_font;
2856 open_font = !langClosed;
2860 // FIXME: think about end_pos implementation...
2861 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2862 // FIXME: integrate this case in latexSpecialChar
2863 // Do not print the separation of the optional argument
2864 // if style.pass_thru is false. This works because
2865 // latexSpecialChar ignores spaces if
2866 // style.pass_thru is false.
2867 if (i != body_pos - 1) {
2868 if (d->simpleTeXBlanks(bparams, runparams, os,
2869 i, column, current_font, style)) {
2870 // A surrogate pair was output. We
2871 // must not call latexSpecialChar
2872 // in this iteration, since it would output
2873 // the combining character again.
2880 OutputParams rp = runparams;
2881 rp.free_spacing = style.free_spacing;
2882 rp.local_font = ¤t_font;
2883 rp.intitle = style.intitle;
2885 // Two major modes: LaTeX or plain
2886 // Handle here those cases common to both modes
2887 // and then split to handle the two modes separately.
2888 if (c == META_INSET) {
2889 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2890 // Greyedout notes and, in general, all insets
2891 // with InsetLayout::isDisplay() == false,
2892 // are typeset inline with the text. So, we
2893 // can add a \par to the last paragraph of
2894 // such insets only if nothing else follows.
2895 bool incremented = false;
2896 Inset const * inset = getInset(i);
2897 InsetText const * textinset = inset
2898 ? inset->asInsetText()
2900 if (i + 1 == size() && textinset
2901 && !inset->getLayout().isDisplay()) {
2902 ParagraphList const & pars =
2903 textinset->text().paragraphs();
2904 pit_type const pit = pars.size() - 1;
2905 Font const lastfont =
2906 pit < 0 || pars[pit].empty()
2907 ? pars[pit].getLayoutFont(
2910 : pars[pit].getFont(bparams,
2911 pars[pit].size() - 1,
2913 if (lastfont.fontInfo().size() !=
2914 basefont.fontInfo().size()) {
2919 // We need to restore parts of this after insets with
2920 // allowMultiPar() true
2921 Font const save_basefont = basefont;
2922 d->latexInset(bparams, os, rp, running_font,
2923 basefont, real_outerfont, open_font,
2924 runningChange, style, i, column, fontswitch_inset,
2925 closeLanguage, lang_switched_at_inset);
2926 if (fontswitch_inset) {
2928 bool needPar = false;
2929 column += running_font.latexWriteEndChanges(
2930 os, bparams, runparams,
2931 basefont, basefont, needPar);
2934 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2935 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2936 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2941 if (runparams.ctObject == CtObject::DisplayObject
2942 || runparams.ctObject == CtObject::UDisplayObject) {
2943 // Close \lyx*deleted and force its
2944 // reopening (if needed)
2947 runningChange = Change(Change::UNCHANGED);
2948 runparams.ctObject = CtObject::Normal;
2951 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2952 if (!bparams.useNonTeXFonts)
2953 script = Encodings::isKnownScriptChar(c);
2954 if (script != alien_script) {
2955 if (!alien_script.empty()) {
2957 alien_script.clear();
2959 string fontenc = running_font.language()->fontenc(bparams);
2961 && !Encodings::fontencSupportsScript(fontenc, script)) {
2962 column += script.length() + 2;
2963 os << "\\" << script << "{";
2964 alien_script = script;
2968 d->latexSpecialChar(os, bparams, rp, running_font,
2969 alien_script, style, i, end_pos, column);
2970 } catch (EncodingException & e) {
2971 if (runparams.dryrun) {
2972 os << "<" << _("LyX Warning: ")
2973 << _("uncodable character") << " '";
2977 // add location information and throw again.
2985 // Set the encoding to that returned from latexSpecialChar (see
2986 // comment for encoding member in OutputParams.h)
2987 runparams.encoding = rp.encoding;
2989 // Also carry on the info on a closed ulem command for insets
2990 // such as Note that do not produce any output, so that no
2991 // command is ever executed but its opening was recorded.
2992 runparams.inulemcmd = rp.inulemcmd;
2994 // These need to be passed upstream as well
2995 runparams.need_maketitle = rp.need_maketitle;
2996 runparams.have_maketitle = rp.have_maketitle;
2998 // And finally, pass the post_macros upstream
2999 runparams.post_macro = rp.post_macro;
3002 // Close wrapper for alien script
3003 if (!alien_script.empty()) {
3005 alien_script.clear();
3008 Font const font = empty()
3009 ? getLayoutFont(bparams, real_outerfont)
3010 : getFont(bparams, size() - 1, real_outerfont);
3012 InsetText const * textinset = inInset().asInsetText();
3014 bool const maintext = textinset
3015 ? textinset->text().isMainText()
3018 size_t const numpars = textinset
3019 ? textinset->text().paragraphs().size()
3022 bool needPar = false;
3024 if (style.resfont.size() != font.fontInfo().size()
3025 && (!runparams.isLastPar || maintext
3026 || (numpars > 1 && d->ownerCode() != CELL_CODE
3027 && (inInset().getLayout().isDisplay()
3029 && !style.isCommand()) {
3033 // If we have an open font definition, we have to close it
3035 // Make sure that \\par is done with the font of the last
3036 // character if this has another size as the default.
3037 // This is necessary because LaTeX (and LyX on the screen)
3038 // calculates the space between the baselines according
3039 // to this font. (Matthias)
3041 // We must not change the font for the last paragraph
3042 // of non-multipar insets, tabular cells or commands,
3043 // since this produces unwanted whitespace.
3044 #ifdef FIXED_LANGUAGE_END_DETECTION
3046 running_font.latexWriteEndChanges(os, bparams,
3047 runparams, basefont,
3048 next_->getFont(bparams, 0, outerfont),
3051 running_font.latexWriteEndChanges(os, bparams,
3052 runparams, basefont, basefont, needPar);
3055 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3056 //FIXME: there as we start another \selectlanguage with the next paragraph if
3057 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3058 running_font.latexWriteEndChanges(os, bparams, runparams,
3059 basefont, basefont, needPar);
3063 // The \par could not be inserted at the same nesting
3064 // level of the font size change, so do it now.
3065 os << "{\\" << font.latexSize() << "\\par}";
3068 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3069 column += Changes::latexMarkChange(os, bparams, runningChange,
3070 Change(Change::UNCHANGED), runparams);
3072 // Needed if there is an optional argument but no contents.
3073 if (body_pos > 0 && body_pos == size()) {
3077 if (!style.rightdelim().empty()) {
3078 os << style.rightdelim();
3079 column += style.rightdelim().size();
3082 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3083 && runparams.encoding != prev_encoding) {
3084 runparams.encoding = prev_encoding;
3085 os << setEncoding(prev_encoding->iconvName());
3088 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3092 bool Paragraph::emptyTag() const
3094 for (pos_type i = 0; i < size(); ++i) {
3095 if (Inset const * inset = getInset(i)) {
3096 InsetCode lyx_code = inset->lyxCode();
3097 // FIXME testing like that is wrong. What is
3099 if (lyx_code != TOC_CODE &&
3100 lyx_code != INCLUDE_CODE &&
3101 lyx_code != GRAPHICS_CODE &&
3102 lyx_code != ERT_CODE &&
3103 lyx_code != LISTINGS_CODE &&
3104 lyx_code != FLOAT_CODE &&
3105 lyx_code != TABULAR_CODE) {
3109 char_type c = d->text_[i];
3110 if (c != ' ' && c != '\t')
3118 string Paragraph::getID(Buffer const &, OutputParams const &)
3121 for (pos_type i = 0; i < size(); ++i) {
3122 if (Inset const * inset = getInset(i)) {
3123 InsetCode lyx_code = inset->lyxCode();
3124 if (lyx_code == LABEL_CODE) {
3125 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3126 docstring const & id = il->getParam("name");
3127 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3135 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3138 for (i = 0; i < size(); ++i) {
3139 if (Inset const * inset = getInset(i)) {
3140 inset->docbook(xs, runparams);
3142 char_type c = d->text_[i];
3152 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3156 for (i = 0; i < size(); ++i) {
3157 if (Inset const * inset = getInset(i)) {
3158 inset->xhtml(xs, runparams);
3160 char_type c = d->text_[i];
3170 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3173 pos_type size = text_.size();
3174 for (pos_type i = initial; i < size; ++i) {
3175 Font font = owner_->getFont(buf.params(), i, outerfont);
3176 if (text_[i] == META_INSET)
3178 if (i != initial && font != font_old)
3189 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3190 vector<xml::EndFontTag> & tagsToClose,
3191 bool & flag, FontState curstate, xml::FontTypes type)
3193 if (curstate == FONT_ON) {
3194 tagsToOpen.push_back(docbookStartFontTag(type));
3197 tagsToClose.push_back(docbookEndFontTag(type));
3202 class OptionalFontType {
3207 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3208 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3211 OptionalFontType fontShapeToXml(FontShape fs)
3215 return {xml::FT_ITALIC};
3217 return {xml::FT_SLANTED};
3218 case SMALLCAPS_SHAPE:
3219 return {xml::FT_SMALLCAPS};
3224 // the other tags are for internal use
3230 OptionalFontType fontFamilyToXml(FontFamily fm)
3234 return {xml::FT_ROMAN};
3236 return {xml::FT_SANS};
3237 case TYPEWRITER_FAMILY:
3238 return {xml::FT_TYPE};
3239 case INHERIT_FAMILY:
3242 // the other tags are for internal use
3248 OptionalFontType fontSizeToXml(FontSize fs)
3252 return {xml::FT_SIZE_TINY};
3254 return {xml::FT_SIZE_SCRIPT};
3256 return {xml::FT_SIZE_FOOTNOTE};
3258 return {xml::FT_SIZE_SMALL};
3260 return {xml::FT_SIZE_LARGE};
3262 return {xml::FT_SIZE_LARGER};
3264 return {xml::FT_SIZE_LARGEST};
3266 return {xml::FT_SIZE_HUGE};
3268 return {xml::FT_SIZE_HUGER};
3270 return {xml::FT_SIZE_INCREASE};
3272 return {xml::FT_SIZE_DECREASE};
3277 // the other tags are for internal use
3283 struct DocBookFontState
3285 FontShape curr_fs = INHERIT_SHAPE;
3286 FontFamily curr_fam = INHERIT_FAMILY;
3287 FontSize curr_size = INHERIT_SIZE;
3289 // track whether we have opened these tags
3290 bool emph_flag = false;
3291 bool bold_flag = false;
3292 bool noun_flag = false;
3293 bool ubar_flag = false;
3294 bool dbar_flag = false;
3295 bool sout_flag = false;
3296 bool xout_flag = false;
3297 bool wave_flag = false;
3299 bool shap_flag = false;
3301 bool faml_flag = false;
3303 bool size_flag = false;
3306 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3308 std::string const & default_family,
3309 DocBookFontState & fs)
3311 vector<xml::FontTag> tagsToOpen;
3312 vector<xml::EndFontTag> tagsToClose;
3315 FontState curstate = font.fontInfo().emph();
3316 if (font_old.emph() != curstate)
3317 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3320 curstate = font.fontInfo().noun();
3321 if (font_old.noun() != curstate)
3322 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3325 curstate = font.fontInfo().underbar();
3326 if (font_old.underbar() != curstate)
3327 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3330 curstate = font.fontInfo().strikeout();
3331 if (font_old.strikeout() != curstate)
3332 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3335 curstate = font.fontInfo().xout();
3336 if (font_old.xout() != curstate)
3337 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3340 curstate = font.fontInfo().uuline();
3341 if (font_old.uuline() != curstate)
3342 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3345 curstate = font.fontInfo().uwave();
3346 if (font_old.uwave() != curstate)
3347 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3350 // a little hackish, but allows us to reuse what we have.
3351 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3352 if (font_old.series() != font.fontInfo().series())
3353 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3356 fs.curr_fs = font.fontInfo().shape();
3357 FontShape old_fs = font_old.shape();
3358 if (old_fs != fs.curr_fs) {
3360 OptionalFontType tag = fontShapeToXml(old_fs);
3362 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3363 fs.shap_flag = false;
3366 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3368 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3372 fs.curr_fam = font.fontInfo().family();
3373 FontFamily old_fam = font_old.family();
3374 if (old_fam != fs.curr_fam) {
3376 OptionalFontType tag = fontFamilyToXml(old_fam);
3378 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3379 fs.faml_flag = false;
3381 switch (fs.curr_fam) {
3383 // we will treat a "default" font family as roman, since we have
3384 // no other idea what to do.
3385 if (default_family != "rmdefault" && default_family != "default") {
3386 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3387 fs.faml_flag = true;
3391 if (default_family != "sfdefault") {
3392 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3393 fs.faml_flag = true;
3396 case TYPEWRITER_FAMILY:
3397 if (default_family != "ttdefault") {
3398 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3399 fs.faml_flag = true;
3402 case INHERIT_FAMILY:
3405 // the other tags are for internal use
3412 fs.curr_size = font.fontInfo().size();
3413 FontSize old_size = font_old.size();
3414 if (old_size != fs.curr_size) {
3416 OptionalFontType tag = fontSizeToXml(old_size);
3418 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3419 fs.size_flag = false;
3422 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3423 if (tag.has_value) {
3424 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3425 fs.size_flag = true;
3429 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3432 } // anonymous namespace
3435 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3436 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3437 OutputParams const & runparams,
3438 Font const & outerfont,
3441 bool ignore_fonts) const
3443 std::vector<docstring> prependedParagraphs;
3444 std::vector<docstring> generatedParagraphs;
3445 std::vector<docstring> appendedParagraphs;
3446 odocstringstream os;
3448 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3449 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3451 OutputParams rp = runparams;
3452 for (pos_type i = initial; i < size(); ++i) {
3453 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3454 const InsetArgument * arg = getInset(i)->asInsetArgument();
3455 if (arg->docbookargumentbeforemaintag()) {
3456 auto xs_local = XMLStream(os);
3457 arg->docbook(xs_local, rp);
3459 prependedParagraphs.push_back(os.str());
3460 os.str(from_ascii(""));
3462 rp.docbook_prepended_arguments.insert(arg);
3463 } else if (arg->docbookargumentaftermaintag()) {
3464 rp.docbook_appended_arguments.insert(arg);
3469 // State variables for the main loop.
3470 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3471 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3472 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3473 // This requires to store delayed characters at some point.
3475 DocBookFontState fs; // Track whether we have opened font tags
3476 DocBookFontState old_fs = fs;
3478 Layout const & style = *d->layout_;
3479 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3480 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3482 vector<xml::FontTag> tagsToOpen;
3483 vector<xml::EndFontTag> tagsToClose;
3485 // Parsing main loop.
3486 for (pos_type i = initial; i < size(); ++i) {
3487 bool ignore_fonts_i = ignore_fonts
3488 || style.docbooknofontinside()
3489 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3491 // Don't show deleted material in the output.
3495 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3497 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3498 if (!ignore_fonts_i)
3499 xs->closeFontTags();
3501 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3502 generatedParagraphs.push_back(os.str());
3504 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3505 // that the string stream must be reset.
3506 os.str(from_ascii(""));
3508 xs = new XMLStream(os);
3510 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3511 if (!ignore_fonts_i) {
3512 font_old = outerfont.fontInfo();
3517 // Determine which tags should be opened or closed regarding fonts.
3518 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3519 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3521 if (!ignore_fonts_i) {
3522 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3523 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3524 for (; cit != cen; ++cit)
3528 // Deal with the delayed characters *after* closing font tags.
3529 if (!delayedChars.empty()) {
3530 for (char_type c: delayedChars)
3532 delayedChars.clear();
3535 if (!ignore_fonts_i) {
3536 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3537 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3538 for (; sit != sen; ++sit)
3541 tagsToClose.clear();
3545 // Finally, write the next character or inset.
3546 if (Inset const * inset = getInset(i)) {
3547 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3548 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3549 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3551 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3552 // Arguments may need to be output
3553 OutputParams np = rp;
3554 np.local_font = &font;
3556 // TODO: special case will bite here.
3557 np.docbook_in_par = true;
3558 inset->docbook(*xs, np);
3561 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3562 if (lyx::isSpace(c) && !ignore_fonts)
3563 delayedChars.push_back(c);
3567 font_old = font.fontInfo();
3570 // FIXME, this code is just imported from XHTML
3571 // I'm worried about what happens if a branch, say, is itself
3572 // wrapped in some font stuff. I think that will not work.
3574 xs->closeFontTags();
3576 // Deal with the delayed characters *after* closing font tags.
3577 if (!delayedChars.empty())
3578 for (char_type c: delayedChars)
3581 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3582 // last line to get a clean output.
3583 if (rp.docbook_in_listing && !is_last_par)
3586 // Finalise the last (and most likely only) paragraph.
3587 generatedParagraphs.push_back(os.str());
3588 os.str(from_ascii(""));
3591 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3592 for (pos_type i = initial; i < size(); ++i) {
3593 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3594 const InsetArgument * arg = getInset(i)->asInsetArgument();
3595 if (arg->docbookargumentaftermaintag()) {
3596 // Don't use rp, as this argument would not generate anything.
3597 auto xs_local = XMLStream(os);
3598 arg->docbook(xs_local, runparams);
3600 appendedParagraphs.push_back(os.str());
3601 os.str(from_ascii(""));
3606 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3612 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3613 vector<xml::EndFontTag> & tagsToClose,
3614 bool & flag, FontState curstate, xml::FontTypes type)
3616 if (curstate == FONT_ON) {
3617 tagsToOpen.push_back(xhtmlStartFontTag(type));
3620 tagsToClose.push_back(xhtmlEndFontTag(type));
3625 } // anonymous namespace
3628 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3630 OutputParams const & runparams,
3631 Font const & outerfont,
3632 bool start_paragraph, bool close_paragraph,
3633 pos_type initial) const
3637 // track whether we have opened these tags
3638 bool emph_flag = false;
3639 bool bold_flag = false;
3640 bool noun_flag = false;
3641 bool ubar_flag = false;
3642 bool dbar_flag = false;
3643 bool sout_flag = false;
3644 bool xout_flag = false;
3645 bool wave_flag = false;
3647 bool shap_flag = false;
3649 bool faml_flag = false;
3651 bool size_flag = false;
3653 Layout const & style = *d->layout_;
3655 if (start_paragraph)
3656 xs.startDivision(allowEmpty());
3659 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3661 FontShape curr_fs = INHERIT_SHAPE;
3662 FontFamily curr_fam = INHERIT_FAMILY;
3663 FontSize curr_size = INHERIT_SIZE;
3665 string const default_family =
3666 buf.masterBuffer()->params().fonts_default_family;
3668 vector<xml::FontTag> tagsToOpen;
3669 vector<xml::EndFontTag> tagsToClose;
3671 // parsing main loop
3672 for (pos_type i = initial; i < size(); ++i) {
3673 // let's not show deleted material in the output
3677 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3680 FontState curstate = font.fontInfo().emph();
3681 if (font_old.emph() != curstate)
3682 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3685 curstate = font.fontInfo().noun();
3686 if (font_old.noun() != curstate)
3687 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3690 curstate = font.fontInfo().underbar();
3691 if (font_old.underbar() != curstate)
3692 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3695 curstate = font.fontInfo().strikeout();
3696 if (font_old.strikeout() != curstate)
3697 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3700 curstate = font.fontInfo().xout();
3701 if (font_old.xout() != curstate)
3702 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3705 curstate = font.fontInfo().uuline();
3706 if (font_old.uuline() != curstate)
3707 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3710 curstate = font.fontInfo().uwave();
3711 if (font_old.uwave() != curstate)
3712 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3715 // a little hackish, but allows us to reuse what we have.
3716 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3717 if (font_old.series() != font.fontInfo().series())
3718 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3721 curr_fs = font.fontInfo().shape();
3722 FontShape old_fs = font_old.shape();
3723 if (old_fs != curr_fs) {
3727 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3730 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3732 case SMALLCAPS_SHAPE:
3733 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3739 // the other tags are for internal use
3747 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3751 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3754 case SMALLCAPS_SHAPE:
3755 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3762 // the other tags are for internal use
3769 curr_fam = font.fontInfo().family();
3770 FontFamily old_fam = font_old.family();
3771 if (old_fam != curr_fam) {
3775 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3778 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3780 case TYPEWRITER_FAMILY:
3781 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3783 case INHERIT_FAMILY:
3786 // the other tags are for internal use
3794 // we will treat a "default" font family as roman, since we have
3795 // no other idea what to do.
3796 if (default_family != "rmdefault" && default_family != "default") {
3797 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3802 if (default_family != "sfdefault") {
3803 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3807 case TYPEWRITER_FAMILY:
3808 if (default_family != "ttdefault") {
3809 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3813 case INHERIT_FAMILY:
3816 // the other tags are for internal use
3823 curr_size = font.fontInfo().size();
3824 FontSize old_size = font_old.size();
3825 if (old_size != curr_size) {
3829 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3832 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3835 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3838 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3841 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3844 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3847 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3850 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3853 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3856 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3859 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3865 // the other tags are for internal use
3871 switch (curr_size) {
3873 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3877 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3881 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3885 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3889 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3893 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3897 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3901 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3905 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3909 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3913 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3920 // the other tags are for internal use
3927 // Other such tags? What about the other text ranges?
3929 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3930 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3931 for (; cit != cen; ++cit)
3934 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3935 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3936 for (; sit != sen; ++sit)
3939 tagsToClose.clear();
3942 Inset const * inset = getInset(i);
3944 if (!runparams.for_toc || inset->isInToc()) {
3945 OutputParams np = runparams;
3946 np.local_font = &font;
3947 // If the paragraph has size 1, then we are in the "special
3948 // case" where we do not output the containing paragraph info
3949 if (!inset->getLayout().htmlisblock() && size() != 1)
3950 np.html_in_par = true;
3951 retval += inset->xhtml(xs, np);
3954 char_type c = getUChar(buf.masterBuffer()->params(),
3956 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3957 xs << XMLStream::ESCAPE_NONE << " ";
3961 font_old = font.fontInfo();
3965 // I'm worried about what happens if a branch, say, is itself
3966 // wrapped in some font stuff. I think that will not work.
3968 if (close_paragraph)
3975 bool Paragraph::isHfill(pos_type pos) const
3977 Inset const * inset = getInset(pos);
3978 return inset && inset->isHfill();
3982 bool Paragraph::isNewline(pos_type pos) const
3984 // U+2028 LINE SEPARATOR
3985 // U+2029 PARAGRAPH SEPARATOR
3986 char_type const c = d->text_[pos];
3987 if (c == 0x2028 || c == 0x2029)
3989 Inset const * inset = getInset(pos);
3990 return inset && inset->lyxCode() == NEWLINE_CODE;
3994 bool Paragraph::isEnvSeparator(pos_type pos) const
3996 Inset const * inset = getInset(pos);
3997 return inset && inset->lyxCode() == SEPARATOR_CODE;
4001 bool Paragraph::isLineSeparator(pos_type pos) const
4003 char_type const c = d->text_[pos];
4004 if (isLineSeparatorChar(c))
4006 Inset const * inset = getInset(pos);
4007 return inset && inset->isLineSeparator();
4011 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4015 if (ignore_deleted && isDeleted(pos))
4017 if (Inset const * inset = getInset(pos))
4018 return !inset->isLetter();
4019 // if we have a hard hyphen (no en- or emdash) or apostrophe
4020 // we pass this to the spell checker
4021 // FIXME: this method is subject to change, visit
4022 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4023 // to get an impression how complex this is.
4024 if (isHardHyphenOrApostrophe(pos))
4026 char_type const c = d->text_[pos];
4027 // We want to pass the escape chars to the spellchecker
4028 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4029 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4033 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4035 pos_type const psize = size();
4038 char_type const c = d->text_[pos];
4039 if (c != '-' && c != '\'')
4041 pos_type nextpos = pos + 1;
4042 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4043 if ((nextpos == psize || isSpace(nextpos))
4044 && (pos == 0 || isSpace(prevpos)))
4050 bool Paragraph::needsCProtection(bool const fragile) const
4052 // first check the layout of the paragraph, but only in insets
4053 InsetText const * textinset = inInset().asInsetText();
4054 bool const maintext = textinset
4055 ? textinset->text().isMainText()
4058 if (!maintext && layout().needcprotect) {
4059 // Environments need cprotection regardless the content
4060 if (layout().latextype == LATEX_ENVIRONMENT)
4063 // Commands need cprotection if they contain specific chars
4064 int const nchars_escape = 9;
4065 static char_type const chars_escape[nchars_escape] = {
4066 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4068 docstring const pars = asString();
4069 for (int k = 0; k < nchars_escape; k++) {
4070 if (contains(pars, chars_escape[k]))
4075 // now check whether we have insets that need cprotection
4076 pos_type size = pos_type(d->text_.size());
4077 for (pos_type i = 0; i < size; ++i) {
4080 Inset const * ins = getInset(i);
4081 if (ins->needsCProtection(maintext, fragile))
4083 // Now check math environments
4084 InsetMath const * im = getInset(i)->asInsetMath();
4085 if (!im || im->cell(0).empty())
4087 switch(im->cell(0)[0]->lyxCode()) {
4088 case MATH_AMSARRAY_CODE:
4089 case MATH_SUBSTACK_CODE:
4091 case MATH_XYMATRIX_CODE:
4092 // these need cprotection
4103 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4105 return d->speller_state_.getRange(pos);
4109 bool Paragraph::isChar(pos_type pos) const
4111 if (Inset const * inset = getInset(pos))
4112 return inset->isChar();
4113 char_type const c = d->text_[pos];
4114 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4118 bool Paragraph::isSpace(pos_type pos) const
4120 if (Inset const * inset = getInset(pos))
4121 return inset->isSpace();
4122 char_type const c = d->text_[pos];
4123 return lyx::isSpace(c);
4128 Paragraph::getParLanguage(BufferParams const & bparams) const
4131 return getFirstFontSettings(bparams).language();
4132 // FIXME: we should check the prev par as well (Lgb)
4133 return bparams.language;
4137 bool Paragraph::isRTL(BufferParams const & bparams) const
4139 return getParLanguage(bparams)->rightToLeft()
4140 && !inInset().getLayout().forceLTR();
4144 void Paragraph::changeLanguage(BufferParams const & bparams,
4145 Language const * from, Language const * to)
4147 // change language including dummy font change at the end
4148 for (pos_type i = 0; i <= size(); ++i) {
4149 Font font = getFontSettings(bparams, i);
4150 if (font.language() == from) {
4151 font.setLanguage(to);
4153 d->requestSpellCheck(i);
4159 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4161 Language const * doc_language = bparams.language;
4162 for (auto const & f : d->fontlist_)
4163 if (f.font().language() != ignore_language &&
4164 f.font().language() != latex_language &&
4165 f.font().language() != doc_language)
4171 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4173 for (auto const & f : d->fontlist_) {
4174 Language const * lang = f.font().language();
4175 if (lang != ignore_language &&
4176 lang != latex_language)
4182 docstring Paragraph::asString(int options) const
4184 return asString(0, size(), options);
4188 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4190 odocstringstream os;
4193 && options & AS_STR_LABEL
4194 && !d->params_.labelString().empty())
4195 os << d->params_.labelString() << ' ';
4197 for (pos_type i = beg; i < end; ++i) {
4198 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4200 char_type const c = d->text_[i];
4201 if (isPrintable(c) || c == '\t'
4202 || (c == '\n' && (options & AS_STR_NEWLINES)))
4204 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4205 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4206 LASSERT(runparams != nullptr, return docstring());
4207 getInset(i)->plaintext(os, *runparams);
4208 } else if (c == META_INSET && (options & AS_STR_MATHED)
4209 && getInset(i)->lyxCode() == REF_CODE) {
4210 Buffer const & buf = getInset(i)->buffer();
4211 OutputParams rp(&buf.params().encoding());
4212 Font const font(inherit_font, buf.params().language);
4213 rp.local_font = &font;
4215 getInset(i)->latex(ots, rp);
4217 getInset(i)->toString(os);
4226 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4227 bool const shorten, bool const label) const
4229 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4230 if (label && !labelString().empty())
4231 os += labelString() + ' ';
4232 if (!layout().isTocCaption())
4234 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4237 char_type const c = d->text_[i];
4240 else if (c == META_INSET)
4241 getInset(i)->forOutliner(os, tmplen, false);
4244 Text::shortenForOutliner(os, maxlen);
4248 void Paragraph::setInsetOwner(Inset const * inset)
4250 d->inset_owner_ = inset;
4254 int Paragraph::id() const
4260 void Paragraph::setId(int id)
4266 Layout const & Paragraph::layout() const
4272 void Paragraph::setLayout(Layout const & layout)
4274 d->layout_ = &layout;
4278 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4280 setLayout(tc.defaultLayout());
4284 void Paragraph::setPlainLayout(DocumentClass const & tc)
4286 setLayout(tc.plainLayout());
4290 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4292 if (usePlainLayout())
4295 setDefaultLayout(tc);
4299 Inset const & Paragraph::inInset() const
4301 LBUFERR(d->inset_owner_);
4302 return *d->inset_owner_;
4306 ParagraphParameters & Paragraph::params()
4312 ParagraphParameters const & Paragraph::params() const
4318 bool Paragraph::isFreeSpacing() const
4320 if (d->layout_->free_spacing)
4322 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4326 bool Paragraph::allowEmpty() const
4328 if (d->layout_->keepempty)
4330 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4334 bool Paragraph::brokenBiblio() const
4336 // There is a problem if there is no bibitem at position 0 in
4337 // paragraphs that need one, if there is another bibitem in the
4338 // paragraph or if this paragraph is not supposed to have
4339 // a bibitem inset at all.
4340 return ((d->layout_->labeltype == LABEL_BIBLIO
4341 && (d->insetlist_.find(BIBITEM_CODE) != 0
4342 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4343 || (d->layout_->labeltype != LABEL_BIBLIO
4344 && d->insetlist_.find(BIBITEM_CODE) != -1));
4348 int Paragraph::fixBiblio(Buffer const & buffer)
4350 // FIXME: when there was already an inset at 0, the return value is 1,
4351 // which does not tell whether another inset has been removed; the
4352 // cursor cannot be correctly updated.
4354 bool const track_changes = buffer.params().track_changes;
4355 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4357 // The case where paragraph is not BIBLIO
4358 if (d->layout_->labeltype != LABEL_BIBLIO) {
4359 if (bibitem_pos == -1)
4360 // No InsetBibitem => OK
4362 // There is an InsetBibitem: remove it!
4363 d->insetlist_.release(bibitem_pos);
4364 eraseChar(bibitem_pos, track_changes);
4365 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4368 bool const hasbibitem0 = bibitem_pos == 0;
4370 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4371 // There was an InsetBibitem at pos 0,
4372 // and no other one => OK
4373 if (bibitem_pos == -1)
4375 // there is a bibitem at the 0 position, but since
4376 // there is a second one, we copy the second on the
4377 // first. We're assuming there are at most two of
4378 // these, which there should be.
4379 // FIXME: why does it make sense to do that rather
4380 // than keep the first? (JMarc)
4381 Inset * inset = releaseInset(bibitem_pos);
4382 d->insetlist_.begin()->inset = inset;
4383 // This needs to be done to update the counter (#8499)
4384 buffer.updateBuffer();
4385 return -bibitem_pos;
4388 // We need to create an inset at the beginning
4389 Inset * inset = nullptr;
4390 if (bibitem_pos > 0) {
4391 // there was one somewhere in the paragraph, let's move it
4392 inset = d->insetlist_.release(bibitem_pos);
4393 eraseChar(bibitem_pos, track_changes);
4396 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4397 InsetCommandParams(BIBITEM_CODE));
4399 Font font(inherit_font, buffer.params().language);
4400 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4401 : Change::UNCHANGED));
4403 // This is needed to get the counters right
4404 buffer.updateBuffer();
4409 void Paragraph::checkAuthors(AuthorList const & authorList)
4411 d->changes_.checkAuthors(authorList);
4415 bool Paragraph::isChanged(pos_type pos) const
4417 return lookupChange(pos).changed();
4421 bool Paragraph::isInserted(pos_type pos) const
4423 return lookupChange(pos).inserted();
4427 bool Paragraph::isDeleted(pos_type pos) const
4429 return lookupChange(pos).deleted();
4433 InsetList const & Paragraph::insetList() const
4435 return d->insetlist_;
4439 void Paragraph::setInsetBuffers(Buffer & b)
4441 d->insetlist_.setBuffer(b);
4445 void Paragraph::resetBuffer()
4447 d->insetlist_.resetBuffer();
4451 Inset * Paragraph::releaseInset(pos_type pos)
4453 Inset * inset = d->insetlist_.release(pos);
4454 /// does not honour change tracking!
4455 eraseChar(pos, false);
4460 Inset * Paragraph::getInset(pos_type pos)
4462 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4463 ? d->insetlist_.get(pos) : nullptr;
4467 Inset const * Paragraph::getInset(pos_type pos) const
4469 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4470 ? d->insetlist_.get(pos) : nullptr;
4474 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4475 pos_type & right, TextCase action)
4477 // process sequences of modified characters; in change
4478 // tracking mode, this approach results in much better
4479 // usability than changing case on a char-by-char basis
4480 // We also need to track the current font, since font
4481 // changes within sequences can occur.
4482 vector<pair<char_type, Font> > changes;
4484 bool const trackChanges = bparams.track_changes;
4486 bool capitalize = true;
4488 for (; pos < right; ++pos) {
4489 char_type oldChar = d->text_[pos];
4490 char_type newChar = oldChar;
4492 // ignore insets and don't play with deleted text!
4493 if (oldChar != META_INSET && !isDeleted(pos)) {
4495 case text_lowercase:
4496 newChar = lowercase(oldChar);
4498 case text_capitalization:
4500 newChar = uppercase(oldChar);
4504 case text_uppercase:
4505 newChar = uppercase(oldChar);
4510 if (isWordSeparator(pos) || isDeleted(pos)) {
4511 // permit capitalization again
4515 if (oldChar != newChar) {
4516 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4517 if (pos != right - 1)
4519 // step behind the changing area
4523 int erasePos = pos - changes.size();
4524 for (auto const & change : changes) {
4525 insertChar(pos, change.first, change.second, trackChanges);
4526 if (!eraseChar(erasePos, trackChanges)) {
4529 ++right; // expand selection
4537 int Paragraph::find(docstring const & str, bool cs, bool mw,
4538 pos_type start_pos, bool del) const
4540 pos_type pos = start_pos;
4541 int const strsize = str.length();
4543 pos_type const parsize = d->text_.size();
4544 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4545 // ignore deleted matter
4546 if (!del && isDeleted(pos)) {
4547 if (pos == parsize - 1)
4553 // Ignore "invisible" letters such as ligature breaks
4554 // and hyphenation chars while searching
4555 bool nonmatch = false;
4556 while (pos < parsize && isInset(pos)) {
4557 Inset const * inset = getInset(pos);
4558 if (!inset->isLetter() && !inset->isChar())
4560 odocstringstream os;
4561 inset->toString(os);
4562 docstring const insetstring = os.str();
4563 if (!insetstring.empty()) {
4564 int const insetstringsize = insetstring.length();
4565 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4566 if ((cs && str[i] != insetstring[j])
4567 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4575 if (nonmatch || i == strsize)
4577 if (cs && str[i] != d->text_[pos])
4579 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4586 // if necessary, check whether string matches word
4588 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4591 && !isWordSeparator(pos))
4595 return pos - start_pos;
4599 char_type Paragraph::getChar(pos_type pos) const
4601 return d->text_[pos];
4605 pos_type Paragraph::size() const
4607 return d->text_.size();
4611 bool Paragraph::empty() const
4613 return d->text_.empty();
4617 bool Paragraph::isInset(pos_type pos) const
4619 return d->text_[pos] == META_INSET;
4623 bool Paragraph::isSeparator(pos_type pos) const
4625 //FIXME: Are we sure this can be the only separator?
4626 return d->text_[pos] == ' ';
4630 void Paragraph::deregisterWords()
4632 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4633 Private::LangWordsMap::const_iterator ite = d->words_.end();
4634 for (; itl != ite; ++itl) {
4635 WordList & wl = theWordList(itl->first);
4636 Private::Words::const_iterator it = (itl->second).begin();
4637 Private::Words::const_iterator et = (itl->second).end();
4638 for (; it != et; ++it)
4645 void Paragraph::locateWord(pos_type & from, pos_type & to,
4646 word_location const loc, bool const ignore_deleted) const
4649 case WHOLE_WORD_STRICT:
4650 if (from == 0 || from == size()
4651 || isWordSeparator(from, ignore_deleted)
4652 || isWordSeparator(from - 1, ignore_deleted)) {
4659 // If we are already at the beginning of a word, do nothing
4660 if (!from || isWordSeparator(from - 1, ignore_deleted))
4665 // always move the cursor to the beginning of previous word
4666 while (from && !isWordSeparator(from - 1, ignore_deleted))
4670 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4673 // no need to move the 'from' cursor
4677 while (to < size() && !isWordSeparator(to, ignore_deleted))
4682 void Paragraph::collectWords()
4684 for (pos_type pos = 0; pos < size(); ++pos) {
4685 if (isWordSeparator(pos))
4687 pos_type from = pos;
4688 locateWord(from, pos, WHOLE_WORD);
4689 // Work around MSVC warning: The statement
4690 // if (pos < from + lyxrc.completion_minlength)
4691 // triggers a signed vs. unsigned warning.
4692 // I don't know why this happens, it could be a MSVC bug, or
4693 // related to LLP64 (windows) vs. LP64 (unix) programming
4694 // model, or the C++ standard might be ambigous in the section
4695 // defining the "usual arithmetic conversions". However, using
4696 // a temporary variable is safe and works on all compilers.
4697 pos_type const endpos = from + lyxrc.completion_minlength;
4700 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4701 if (cit == d->fontlist_.end())
4703 Language const * lang = cit->font().language();
4704 docstring const word = asString(from, pos, AS_STR_NONE);
4705 d->words_[lang->lang()].insert(word);
4710 void Paragraph::registerWords()
4712 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4713 Private::LangWordsMap::const_iterator ite = d->words_.end();
4714 for (; itl != ite; ++itl) {
4715 WordList & wl = theWordList(itl->first);
4716 Private::Words::const_iterator it = (itl->second).begin();
4717 Private::Words::const_iterator et = (itl->second).end();
4718 for (; it != et; ++it)
4724 void Paragraph::updateWords()
4732 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4734 SkipPositionsIterator begin = skips.begin();
4735 SkipPositions::iterator end = skips.end();
4736 if (pos > 0 && begin < end) {
4738 if (end->last == pos - 1) {
4743 skips.insert(end, FontSpan(pos, pos));
4747 Language * Paragraph::Private::locateSpellRange(
4748 pos_type & from, pos_type & to,
4749 SkipPositions & skips) const
4751 // skip leading white space
4752 while (from < to && owner_->isWordSeparator(from))
4754 // don't check empty range
4757 // get current language
4758 Language * lang = getSpellLanguage(from);
4759 pos_type last = from;
4760 bool samelang = true;
4761 bool sameinset = true;
4762 while (last < to && samelang && sameinset) {
4763 // hop to end of word
4764 while (last < to && !owner_->isWordSeparator(last)) {
4765 Inset const * inset = owner_->getInset(last);
4766 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4767 // check for "invisible" letters such as ligature breaks
4768 odocstringstream os;
4769 inset->toString(os);
4770 if (os.str().length() != 0) {
4771 // avoid spell check of visible special char insets
4772 // stop the loop in front of the special char inset
4777 appendSkipPosition(skips, last);
4778 } else if (owner_->isDeleted(last)) {
4779 appendSkipPosition(skips, last);
4783 // hop to next word while checking for insets
4784 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4785 if (Inset const * inset = owner_->getInset(last))
4786 sameinset = inset->isChar() && inset->isLetter();
4787 if (sameinset && owner_->isDeleted(last)) {
4788 appendSkipPosition(skips, last);
4793 if (sameinset && last < to) {
4794 // now check for language change
4795 samelang = lang == getSpellLanguage(last);
4798 // if language change detected backstep is needed
4806 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4809 const_cast<Language *>(owner_->getFontSettings(
4810 inset_owner_->buffer().params(), from).language());
4811 if (lang == inset_owner_->buffer().params().language
4812 && !lyxrc.spellchecker_alt_lang.empty()) {
4814 string const lang_variety =
4815 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4816 lang->setCode(lang_code);
4817 lang->setVariety(lang_variety);
4823 void Paragraph::requestSpellCheck(pos_type pos)
4825 d->requestSpellCheck(pos);
4829 bool Paragraph::needsSpellCheck() const
4831 SpellChecker::ChangeNumber speller_change_number = 0;
4832 if (theSpellChecker())
4833 speller_change_number = theSpellChecker()->changeNumber();
4834 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4835 d->speller_state_.needsCompleteRefresh(speller_change_number);
4837 return d->needsSpellCheck();
4841 bool Paragraph::Private::ignoreWord(docstring const & word) const
4843 // Ignore words with digits
4844 // FIXME: make this customizable
4845 // (note that some checkers ignore words with digits by default)
4846 docstring::const_iterator cit = word.begin();
4847 docstring::const_iterator const end = word.end();
4848 for (; cit != end; ++cit) {
4849 if (isNumber((*cit)))
4856 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4857 WordLangTuple & wl, docstring_list & suggestions,
4858 bool do_suggestion, bool check_learned) const
4860 SpellChecker::Result result = SpellChecker::WORD_OK;
4861 SpellChecker * speller = theSpellChecker();
4865 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4868 locateWord(from, to, WHOLE_WORD, true);
4869 if (from == to || from >= size())
4872 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4873 Language * lang = d->getSpellLanguage(from);
4875 BufferParams const & bparams = d->inset_owner_->buffer().params();
4877 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4880 wl = WordLangTuple(word, lang);
4885 if (needsSpellCheck() || check_learned) {
4887 if (!d->ignoreWord(word)) {
4888 bool const trailing_dot = to < size() && d->text_[to] == '.';
4889 result = speller->check(wl, bparams.spellignore());
4890 if (SpellChecker::misspelled(result) && trailing_dot) {
4891 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4892 result = speller->check(wl, bparams.spellignore());
4893 if (!SpellChecker::misspelled(result)) {
4894 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4896 from << ".." << to << "]");
4898 // spell check with dot appended failed too
4899 // restore original word/lang value
4900 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4901 wl = WordLangTuple(word, lang);
4905 if (!SpellChecker::misspelled(result)) {
4906 // area up to the begin of the next word is not misspelled
4907 while (end < size() && isWordSeparator(end))
4910 d->setMisspelled(from, end, result);
4912 result = d->speller_state_.getState(from);
4916 suggestions.clear();
4918 if (SpellChecker::misspelled(result)) {
4919 LYXERR(Debug::GUI, "misspelled word: \"" <<
4921 from << ".." << to << "]");
4923 speller->suggest(wl, suggestions);
4929 void Paragraph::anonymize()
4931 // This is a very crude anonymization for now
4932 for (char_type & c : d->text_)
4933 if (isLetterChar(c) || isNumber(c))
4938 void Paragraph::Private::markMisspelledWords(
4939 Language const * lang,
4940 pos_type const & first, pos_type const & last,
4941 SpellChecker::Result result,
4942 docstring const & word,
4943 SkipPositions const & skips)
4945 if (!SpellChecker::misspelled(result)) {
4946 setMisspelled(first, last, SpellChecker::WORD_OK);
4950 SpellChecker * speller = theSpellChecker();
4951 // locate and enumerate the error positions
4952 int nerrors = speller->numMisspelledWords();
4954 SkipPositionsIterator it = skips.begin();
4955 SkipPositionsIterator et = skips.end();
4956 for (int index = 0; index < nerrors; ++index) {
4959 speller->misspelledWord(index, wstart, wlen);
4960 /// should not happen if speller supports range checks
4963 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
4964 wstart += first + numskipped;
4965 if (snext < wstart) {
4966 /// mark the range of correct spelling
4967 numskipped += countSkips(it, et, wstart);
4968 setMisspelled(snext,
4969 wstart - 1, SpellChecker::WORD_OK);
4971 snext = wstart + wlen;
4972 // Check whether the candidate is in the document's local dict
4973 SpellChecker::Result actresult = result;
4974 if (inset_owner_->buffer().params().spellignored(candidate))
4975 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
4976 numskipped += countSkips(it, et, snext);
4977 /// mark the range of misspelling
4978 setMisspelled(wstart, snext, actresult);
4979 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
4980 LYXERR(Debug::GUI, "local dictionary word: \"" <<
4981 candidate.word() << "\" [" <<
4982 wstart << ".." << (snext-1) << "]");
4984 LYXERR(Debug::GUI, "misspelled word: \"" <<
4985 candidate.word() << "\" [" <<
4986 wstart << ".." << (snext-1) << "]");
4989 if (snext <= last) {
4990 /// mark the range of correct spelling at end
4991 setMisspelled(snext, last, SpellChecker::WORD_OK);
4996 void Paragraph::spellCheck() const
4998 SpellChecker * speller = theSpellChecker();
4999 if (!speller || empty() ||!needsSpellCheck())
5003 d->rangeOfSpellCheck(start, endpos);
5004 if (speller->canCheckParagraph()) {
5005 // loop until we leave the range
5006 for (pos_type first = start; first < endpos; ) {
5007 pos_type last = endpos;
5008 Private::SkipPositions skips;
5009 Language * lang = d->locateSpellRange(first, last, skips);
5010 if (first >= endpos)
5012 // start the spell checker on the unit of meaning
5013 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5014 WordLangTuple wl = WordLangTuple(word, lang);
5015 BufferParams const & bparams = d->inset_owner_->buffer().params();
5016 SpellChecker::Result result = !word.empty() ?
5017 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5018 d->markMisspelledWords(lang, first, last, result, word, skips);
5022 static docstring_list suggestions;
5023 pos_type to = endpos;
5024 while (start < endpos) {
5026 spellCheck(start, to, wl, suggestions, false);
5030 d->readySpellCheck();
5034 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5036 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5037 if (result || pos <= 0 || pos > size())
5039 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5040 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5045 string Paragraph::magicLabel() const
5048 ss << "magicparlabel-" << id();