3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Kimberly Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
24 #include "BufferParams.h"
25 #include "BufferEncodings.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "output_xhtml.h"
38 #include "output_docbook.h"
39 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "texstream.h"
45 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetArgument.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
85 /////////////////////////////////////////////////////////////////////
89 /////////////////////////////////////////////////////////////////////
91 class SpellResultRange {
93 SpellResultRange(FontSpan range, SpellChecker::Result result)
94 : range_(range), result_(result)
97 FontSpan const & range() const { return range_; }
99 void range(FontSpan const & r) { range_ = r; }
101 SpellChecker::Result result() const { return result_; }
103 void result(SpellChecker::Result r) { result_ = r; }
105 bool contains(pos_type pos) const { return range_.contains(pos); }
107 bool covered(FontSpan const & r) const
109 // 1. first of new range inside current range or
110 // 2. last of new range inside current range or
111 // 3. first of current range inside new range or
112 // 4. last of current range inside new range
113 //FIXME: is this the same as !range_.intersect(r).empty() ?
114 return range_.contains(r.first) || range_.contains(r.last) ||
115 r.contains(range_.first) || r.contains(range_.last);
118 void shift(pos_type pos, int offset)
120 if (range_.first > pos) {
121 range_.first += offset;
122 range_.last += offset;
123 } else if (range_.last >= pos) {
124 range_.last += offset;
129 SpellChecker::Result result_ ;
133 /////////////////////////////////////////////////////////////////////
137 /////////////////////////////////////////////////////////////////////
139 class SpellCheckerState {
143 needs_refresh_ = true;
144 current_change_number_ = 0;
147 void setRange(FontSpan const & fp, SpellChecker::Result state)
150 RangesIterator et = ranges_.end();
151 RangesIterator it = ranges_.begin();
152 for (; it != et; ++it) {
153 if (!it->covered(fp))
154 result.push_back(SpellResultRange(it->range(), it->result()));
155 else if (state == SpellChecker::WORD_OK) {
156 // trim or split the current misspelled range
157 // store misspelled ranges only
158 FontSpan range = it->range();
159 if (fp.first > range.first) {
160 // misspelled area in front of WORD_OK
161 range.last = fp.first - 1;
162 result.push_back(SpellResultRange(range, it->result()));
165 if (fp.last < range.last) {
166 // misspelled area after WORD_OK range
167 range.first = fp.last + 1;
168 result.push_back(SpellResultRange(range, it->result()));
173 if (state != SpellChecker::WORD_OK)
174 ranges_.push_back(SpellResultRange(fp, state));
177 void increasePosAfterPos(pos_type pos)
179 correctRangesAfterPos(pos, 1);
183 void decreasePosAfterPos(pos_type pos)
185 correctRangesAfterPos(pos, -1);
189 void refreshLast(pos_type pos)
191 if (pos < refresh_.last)
195 SpellChecker::Result getState(pos_type pos) const
197 SpellChecker::Result result = SpellChecker::WORD_OK;
198 RangesIterator et = ranges_.end();
199 RangesIterator it = ranges_.begin();
200 for (; it != et; ++it) {
201 if(it->contains(pos)) {
208 FontSpan const & getRange(pos_type pos) const
210 /// empty span to indicate mismatch
211 static FontSpan empty_;
212 RangesIterator et = ranges_.end();
213 RangesIterator it = ranges_.begin();
214 for (; it != et; ++it) {
215 if(it->contains(pos)) {
222 bool needsRefresh() const
224 return needs_refresh_;
227 SpellChecker::ChangeNumber currentChangeNumber() const
229 return current_change_number_;
232 void refreshRange(pos_type & first, pos_type & last) const
234 first = refresh_.first;
235 last = refresh_.last;
238 void needsRefresh(pos_type pos)
240 if (needs_refresh_ && pos != -1) {
241 if (pos < refresh_.first)
242 refresh_.first = pos;
243 if (pos > refresh_.last)
245 } else if (pos != -1) {
246 // init request check for neighbour positions too
247 refresh_.first = pos > 0 ? pos - 1 : 0;
248 // no need for special end of paragraph check
249 refresh_.last = pos + 1;
251 needs_refresh_ = pos != -1;
254 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
256 needs_refresh_ = true;
259 current_change_number_ = change_number;
262 typedef vector<SpellResultRange> Ranges;
263 typedef Ranges::const_iterator RangesIterator;
265 /// the area of the paragraph with pending spell check
267 /// spell state cache version number
268 SpellChecker::ChangeNumber current_change_number_;
272 void correctRangesAfterPos(pos_type pos, int offset)
274 RangesIterator et = ranges_.end();
275 Ranges::iterator it = ranges_.begin();
276 for (; it != et; ++it) {
277 it->shift(pos, offset);
283 /////////////////////////////////////////////////////////////////////
285 // Paragraph::Private
287 /////////////////////////////////////////////////////////////////////
289 class Paragraph::Private
291 // Enforce our own "copy" constructor
292 Private(Private const &) = delete;
293 Private & operator=(Private const &) = delete;
294 // Unique ID generator
295 static int make_id();
298 Private(Paragraph * owner, Layout const & layout);
299 /// "Copy constructor"
300 Private(Private const &, Paragraph * owner);
301 /// Copy constructor from \p beg to \p end
302 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
305 void insertChar(pos_type pos, char_type c, Change const & change);
307 /// Output the surrogate pair formed by \p c and \p next to \p os.
308 /// \return the number of characters written.
309 int latexSurrogatePair(BufferParams const &, otexstream & os,
310 char_type c, char_type next,
311 OutputParams const &) const;
313 /// Output a space in appropriate formatting (or a surrogate pair
314 /// if the next character is a combining character).
315 /// \return whether a surrogate pair was output.
316 bool simpleTeXBlanks(BufferParams const &,
317 OutputParams const &,
320 unsigned int & column,
322 Layout const & style) const;
324 /// This could go to ParagraphParameters if we want to.
325 int startTeXParParams(BufferParams const &, otexstream &,
326 OutputParams const &) const;
328 /// This could go to ParagraphParameters if we want to.
329 bool endTeXParParams(BufferParams const &, otexstream &,
330 OutputParams const &) const;
333 void latexInset(BufferParams const &,
338 Font const & outerfont,
340 Change & running_change,
341 Layout const & style,
343 unsigned int & column,
344 bool const fontswitch_inset,
345 bool const closeLanguage,
346 bool const lang_switched_at_inset) const;
349 void latexSpecialChar(
351 BufferParams const & bparams,
352 OutputParams const & runparams,
353 Font const & running_font,
354 string & alien_script,
355 Layout const & style,
358 unsigned int & column) const;
365 unsigned int & column) const;
371 unsigned int & column) const;
377 unsigned int & column) const;
380 void validate(LaTeXFeatures & features) const;
382 /// Checks if the paragraph contains only text and no inset or font change.
383 bool onlyText(Buffer const & buf, Font const & outerfont,
384 pos_type initial) const;
386 /// a vector of speller skip positions
387 typedef vector<FontSpan> SkipPositions;
388 typedef SkipPositions::const_iterator SkipPositionsIterator;
390 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
392 Language * getSpellLanguage(pos_type const from) const;
394 Language * locateSpellRange(pos_type & from, pos_type & to,
395 SkipPositions & skips) const;
397 bool hasSpellerChange() const
399 SpellChecker::ChangeNumber speller_change_number = 0;
400 if (theSpellChecker())
401 speller_change_number = theSpellChecker()->changeNumber();
402 return speller_change_number > speller_state_.currentChangeNumber();
405 bool ignoreWord(docstring const & word) const;
407 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
409 pos_type textsize = owner_->size();
410 // check for sane arguments
411 if (to <= from || from >= textsize)
413 FontSpan fp = FontSpan(from, to - 1);
414 speller_state_.setRange(fp, state);
417 void requestSpellCheck(pos_type pos)
420 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
422 speller_state_.needsRefresh(pos);
425 void readySpellCheck()
427 speller_state_.needsRefresh(-1);
430 bool needsSpellCheck() const
432 return speller_state_.needsRefresh();
435 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
437 speller_state_.refreshRange(first, last);
439 last = owner_->size();
442 pos_type endpos = last;
443 owner_->locateWord(first, endpos, WHOLE_WORD, true);
446 owner_->locateWord(last, endpos, WHOLE_WORD, true);
451 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
455 while (it != et && it->first < start) {
456 long skip = it->last - it->first + 1;
464 void markMisspelledWords(Language const * lang,
465 pos_type const & first, pos_type const & last,
466 SpellChecker::Result result,
467 docstring const & word,
468 SkipPositions const & skips);
470 InsetCode ownerCode() const
472 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
475 /// Which Paragraph owns us?
479 Inset const * inset_owner_;
485 ParagraphParameters params_;
487 /// for recording and looking up changes
491 InsetList insetlist_;
494 pos_type begin_of_body_;
496 typedef docstring TextContainer;
500 typedef set<docstring> Words;
501 typedef map<string, Words> LangWordsMap;
505 Layout const * layout_;
507 SpellCheckerState speller_state_;
513 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
514 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
521 int Paragraph::Private::make_id()
523 // The id is unique per session across buffers because it is used in
524 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
527 static int next_id(0);
532 Paragraph::Private::Private(Private const & p, Paragraph * owner)
533 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
534 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
535 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
536 layout_(p.layout_), id_(make_id())
538 requestSpellCheck(p.text_.size());
542 Paragraph::Private::Private(Private const & p, Paragraph * owner,
543 pos_type beg, pos_type end)
544 : owner_(owner), inset_owner_(p.inset_owner_),
545 params_(p.params_), changes_(p.changes_),
546 insetlist_(p.insetlist_, beg, end),
547 begin_of_body_(p.begin_of_body_), words_(p.words_),
548 layout_(p.layout_), id_(make_id())
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 /////////////////////////////////////////////////////////////////////
575 /////////////////////////////////////////////////////////////////////
579 /** This helper class should be instantiated at the start of methods
580 * that can create or merge changes. If as a result the value of
581 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
584 struct ChangesMonitor {
586 ChangesMonitor(Paragraph & par)
587 : par_(par), was_changed_(par.isChanged()) {}
591 /* We may need to run updateBuffer to check whether the buffer
592 * contains changes (and toggle the changes toolbar). We do it
594 * 1. the `changedness' of the paragraph has changed,
595 * 2. and we are not in the situation where the buffer has changes
596 * and new changes are added to the paragraph.
599 if (par_.isChanged() != was_changed_
600 && par_.inInset().isBufferValid()
601 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
602 par_.inInset().buffer().forceUpdate();
603 } catch(support::ExceptionMessage const &) {}
608 Paragraph const & par_;
615 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
616 bool output_active, TocBackend & backend) const
618 d->changes_.addToToc(cdit, buf, output_active, backend);
622 bool Paragraph::isDeleted(pos_type start, pos_type end) const
624 LASSERT(start >= 0 && start <= size(), return false);
625 LASSERT(end > start && end <= size() + 1, return false);
627 return d->changes_.isDeleted(start, end);
631 bool Paragraph::isChanged(pos_type start, pos_type end) const
633 LASSERT(start >= 0 && start <= size(), return false);
634 LASSERT(end > start && end <= size() + 1, return false);
636 return d->changes_.isChanged(start, end);
639 // FIXME: Ideally the diverse isChanged() methods should account for that!
640 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
642 LASSERT(start >= 0 && start <= size(), return false);
643 LASSERT(end > start && end <= size() + 1, return false);
645 for (auto const & icit : d->insetlist_) {
646 if (icit.pos < start)
650 if (icit.inset && icit.inset->isChanged())
656 bool Paragraph::isChanged() const
658 return d->changes_.isChanged();
662 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
664 // keep the logic here in sync with the logic of eraseChars()
668 Change const & change = d->changes_.lookup(size());
669 return change.inserted() && change.currentAuthor();
672 Change Paragraph::parEndChange() const
674 return d->changes_.lookup(size());
678 void Paragraph::setChange(Change const & change)
680 // Make sure that Buffer::hasChangesPresent is updated
681 ChangesMonitor cm(*this);
683 // beware of the imaginary end-of-par character!
684 d->changes_.set(change, 0, size() + 1);
687 * Propagate the change recursively - but not in case of DELETED!
689 * Imagine that your co-author makes changes in an existing inset. He
690 * sends your document to you and you come to the conclusion that the
691 * inset should go completely. If you erase it, LyX must not delete all
692 * text within the inset. Otherwise, the change tracked insertions of
693 * your co-author get lost and there is no way to restore them later.
695 * Conclusion: An inset's content should remain untouched if you delete it
698 if (!change.deleted()) {
699 for (pos_type pos = 0; pos < size(); ++pos) {
700 if (Inset * inset = getInset(pos))
701 inset->setChange(change);
707 void Paragraph::setChange(pos_type pos, Change const & change)
709 // Make sure that Buffer::hasChangesPresent is updated
710 ChangesMonitor cm(*this);
712 LASSERT(pos >= 0 && pos <= size(), return);
713 d->changes_.set(change, pos);
715 // see comment in setChange(Change const &) above
716 if (!change.deleted() && pos < size())
717 if (Inset * inset = getInset(pos))
718 inset->setChange(change);
722 Change const & Paragraph::lookupChange(pos_type pos) const
724 LBUFERR(pos >= 0 && pos <= size());
725 return d->changes_.lookup(pos);
729 void Paragraph::acceptChanges(pos_type start, pos_type end)
731 // Make sure that Buffer::hasChangesPresent is updated
732 ChangesMonitor cm(*this);
734 LASSERT(start >= 0 && start <= size(), return);
735 LASSERT(end > start && end <= size() + 1, return);
737 for (pos_type pos = start; pos < end; ++pos) {
738 switch (lookupChange(pos).type) {
739 case Change::UNCHANGED:
740 // accept changes in nested inset
741 if (Inset * inset = getInset(pos))
742 inset->acceptChanges();
745 case Change::INSERTED:
746 d->changes_.set(Change(Change::UNCHANGED), pos);
747 // also accept changes in nested inset
748 if (Inset * inset = getInset(pos))
749 inset->acceptChanges();
752 case Change::DELETED:
753 // Suppress access to non-existent
754 // "end-of-paragraph char"
756 eraseChar(pos, false);
767 void Paragraph::rejectChanges(pos_type start, pos_type end)
769 LASSERT(start >= 0 && start <= size(), return);
770 LASSERT(end > start && end <= size() + 1, return);
772 // Make sure that Buffer::hasChangesPresent is updated
773 ChangesMonitor cm(*this);
775 for (pos_type pos = start; pos < end; ++pos) {
776 switch (lookupChange(pos).type) {
777 case Change::UNCHANGED:
778 // reject changes in nested inset
779 if (Inset * inset = getInset(pos))
780 inset->rejectChanges();
783 case Change::INSERTED:
784 // Suppress access to non-existent
785 // "end-of-paragraph char"
787 eraseChar(pos, false);
793 case Change::DELETED:
794 d->changes_.set(Change(Change::UNCHANGED), pos);
796 // Do NOT reject changes within a deleted inset!
797 // There may be insertions of a co-author inside of it!
805 void Paragraph::Private::insertChar(pos_type pos, char_type c,
806 Change const & change)
808 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
810 // Make sure that Buffer::hasChangesPresent is updated
811 ChangesMonitor cm(*owner_);
814 changes_.insert(change, pos);
816 // This is actually very common when parsing buffers (and
817 // maybe inserting ascii text)
818 if (pos == pos_type(text_.size())) {
819 // when appending characters, no need to update tables
821 // but we want spell checking
822 requestSpellCheck(pos);
826 text_.insert(text_.begin() + pos, c);
828 // Update the font table.
829 fontlist_.increasePosAfterPos(pos);
832 insetlist_.increasePosAfterPos(pos);
834 // Update list of misspelled positions
835 speller_state_.increasePosAfterPos(pos);
838 if (inset_owner_ && inset_owner_->isBufferValid())
839 theSession().bookmarks().adjustPosAfterPos(inset_owner_->buffer().fileName(),
844 bool Paragraph::insertInset(pos_type pos, Inset * inset,
845 Font const & font, Change const & change)
847 LASSERT(inset, return false);
848 LASSERT(pos >= 0 && pos <= size(), return false);
850 // Make sure that Buffer::hasChangesPresent is updated
851 ChangesMonitor cm(*this);
853 // Paragraph::insertInset() can be used in cut/copy/paste operation where
854 // d->inset_owner_ is not set yet.
855 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
858 d->insertChar(pos, META_INSET, change);
859 LASSERT(d->text_[pos] == META_INSET, return false);
861 // Add a new entry in the insetlist_.
862 d->insetlist_.insert(inset, pos);
864 // Some insets require run of spell checker
865 requestSpellCheck(pos);
871 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
873 LASSERT(pos >= 0 && pos <= size(), return false);
875 // Make sure that Buffer::hasChangesPresent is updated
876 ChangesMonitor cm(*this);
878 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
881 Change change = d->changes_.lookup(pos);
883 // set the character to DELETED if
884 // a) it was previously unchanged or
885 // b) it was inserted by a co-author
887 if (!change.changed() ||
888 (change.inserted() && !change.currentAuthor())) {
889 setChange(pos, Change(Change::DELETED));
890 // request run of spell checker
891 requestSpellCheck(pos);
895 if (change.deleted())
899 // Don't physically access the imaginary end-of-paragraph character.
900 // eraseChar() can only mark it as DELETED. A physical deletion of
901 // end-of-par must be handled externally.
907 d->changes_.erase(pos);
909 // if it is an inset, delete the inset entry
910 if (d->text_[pos] == META_INSET)
911 d->insetlist_.erase(pos);
913 d->text_.erase(d->text_.begin() + pos);
915 // Update the fontlist_
916 d->fontlist_.erase(pos);
918 // Update the insetlist_
919 d->insetlist_.decreasePosAfterPos(pos);
921 // Update list of misspelled positions
922 d->speller_state_.decreasePosAfterPos(pos);
923 d->speller_state_.refreshLast(size());
926 if (d->inset_owner_ && d->inset_owner_->isBufferValid())
927 theSession().bookmarks().adjustPosAfterPos(d->inset_owner_->buffer().fileName(),
934 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
936 LASSERT(start >= 0 && start <= size(), return 0);
937 LASSERT(end >= start && end <= size() + 1, return 0);
940 for (pos_type count = end - start; count; --count) {
941 if (!eraseChar(i, trackChanges))
948 // Handle combining characters
949 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
950 otexstream & os, char_type c, char_type next,
951 OutputParams const & runparams) const
953 // Writing next here may circumvent a possible font change between
954 // c and next. Since next is only output if it forms a surrogate pair
955 // with c we can ignore this:
956 // A font change inside a surrogate pair does not make sense and is
957 // hopefully impossible to input.
958 // FIXME: change tracking
959 // Is this correct WRT change tracking?
960 Encoding const & encoding = *(runparams.encoding);
961 docstring latex1 = encoding.latexChar(next).first;
962 if (runparams.inIPA) {
963 string const tipashortcut = Encodings::TIPAShortcut(next);
964 if (!tipashortcut.empty()) {
965 latex1 = from_ascii(tipashortcut);
968 docstring latex2 = encoding.latexChar(c).first;
970 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
971 // Encoding supports the combination:
972 // output as is (combining char after base char).
973 os << latex2 << latex1;
974 return latex1.length() + latex2.length();
977 os << latex1 << "{" << latex2 << "}";
978 return latex1.length() + latex2.length() + 2;
982 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
983 OutputParams const & runparams,
986 unsigned int & column,
988 Layout const & style) const
990 if (style.pass_thru || runparams.pass_thru)
993 if (i + 1 < int(text_.size())) {
994 char_type next = text_[i + 1];
995 if (Encodings::isCombiningChar(next)) {
996 // This space has an accent, so we must always output it.
997 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
1002 if (runparams.linelen > 0
1003 && column > runparams.linelen
1005 && text_[i - 1] != ' '
1006 && (i + 1 < int(text_.size()))
1007 // same in FreeSpacing mode
1008 && !owner_->isFreeSpacing()
1009 // In typewriter mode, we want to avoid
1010 // ! . ? : at the end of a line
1011 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1012 && (text_[i - 1] == '.'
1013 || text_[i - 1] == '?'
1014 || text_[i - 1] == ':'
1015 || text_[i - 1] == '!'))) {
1017 os.texrow().start(owner_->id(), i + 1);
1019 } else if (style.free_spacing) {
1028 void Paragraph::Private::latexInset(BufferParams const & bparams,
1030 OutputParams & runparams,
1031 Font & running_font,
1033 Font const & outerfont,
1035 Change & running_change,
1036 Layout const & style,
1038 unsigned int & column,
1039 bool const fontswitch_inset,
1040 bool const closeLanguage,
1041 bool const lang_switched_at_inset) const
1043 Inset * inset = owner_->getInset(i);
1046 if (style.pass_thru) {
1047 odocstringstream ods;
1048 inset->plaintext(ods, runparams);
1053 // FIXME: move this to InsetNewline::latex
1054 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1055 // newlines are handled differently here than
1056 // the default in simpleTeXSpecialChars().
1057 if (!style.newline_allowed) {
1061 bool needPar = false;
1062 column += running_font.latexWriteEndChanges(
1063 os, bparams, runparams,
1064 basefont, basefont, needPar);
1068 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1071 basefont = owner_->getLayoutFont(bparams, outerfont);
1072 running_font = basefont;
1074 if (runparams.moving_arg)
1078 os.texrow().start(owner_->id(), i + 1);
1082 if (owner_->isDeleted(i)) {
1083 if( ++runparams.inDeletedInset == 1)
1084 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1087 if (inset->canTrackChanges()) {
1088 column += Changes::latexMarkChange(os, bparams, running_change,
1089 Change(Change::UNCHANGED), runparams);
1090 running_change = Change(Change::UNCHANGED);
1094 odocstream::pos_type const len = os.os().tellp();
1096 if (inset->forceLTR(runparams)
1097 && running_font.isRightToLeft()
1098 // ERT is an exception, it should be output with no
1099 // decorations at all
1100 && inset->lyxCode() != ERT_CODE) {
1101 if (runparams.use_polyglossia) {
1103 } else if (running_font.language()->lang() == "farsi"
1104 || running_font.language()->lang() == "arabic_arabi")
1105 os << "\\textLR{" << termcmd;
1111 if (open_font && fontswitch_inset) {
1112 bool lang_closed = false;
1113 // Close language if needed
1114 if (closeLanguage && !lang_switched_at_inset) {
1115 // We need prev_font here as language changes directly at inset
1116 // will only be started inside the inset.
1117 Font const prev_font = (i > 0) ?
1118 owner_->getFont(bparams, i - 1, outerfont)
1120 Font tmpfont(basefont);
1121 tmpfont.setLanguage(prev_font.language());
1122 bool needPar = false;
1123 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1125 needPar, closeLanguage);
1127 lang_closed = count > 0;
1129 // Update the running_font, making sure, however,
1130 // to leave the language as it was.
1131 // FIXME: probably a better way to keep track of the old
1132 // language, than copying the entire font?
1133 Font const copy_font(running_font);
1134 basefont = owner_->getLayoutFont(bparams, outerfont);
1135 running_font = basefont;
1137 running_font.setLanguage(copy_font.language());
1138 OutputParams rp = runparams;
1139 rp.encoding = basefont.language()->encoding();
1140 // For these, we use switches, so they should be taken as
1141 // base inside the inset.
1142 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1143 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1144 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1145 // Now re-do font changes in a way needed here
1146 // (using switches with multi-par insets)
1147 InsetText const * textinset = inset->asInsetText();
1148 bool const cprotect = textinset
1149 ? textinset->hasCProtectContent(runparams.moving_arg)
1150 && !textinset->text().isMainText()
1151 && inset->lyxCode() != BRANCH_CODE
1153 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1159 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1163 runparams.local_font = &basefont;
1166 if (fontswitch_inset && !closeLanguage) {
1167 // The directionality has been switched at inset.
1168 // Force markup inside.
1169 runparams.local_font = &basefont;
1172 size_t const previous_row_count = os.texrow().rows();
1175 runparams.lastid = id_;
1176 runparams.lastpos = i;
1177 inset->latex(os, runparams);
1178 } catch (EncodingException & e) {
1179 // add location information and throw again.
1188 if (os.texrow().rows() > previous_row_count) {
1189 os.texrow().start(owner_->id(), i + 1);
1192 column += (unsigned int)(os.os().tellp() - len);
1195 if (owner_->isDeleted(i))
1196 --runparams.inDeletedInset;
1200 void Paragraph::Private::latexSpecialChar(otexstream & os,
1201 BufferParams const & bparams,
1202 OutputParams const & runparams,
1203 Font const & running_font,
1204 string & alien_script,
1205 Layout const & style,
1208 unsigned int & column) const
1210 char_type const c = owner_->getUChar(bparams, runparams, i);
1212 if (style.pass_thru || runparams.pass_thru || runparams.find_effective()
1213 || contains(style.pass_thru_chars, c)
1214 || contains(runparams.pass_thru_chars, c)) {
1215 if (runparams.find_effective()) {
1221 os << "\\braceleft ";
1224 os << "\\braceright ";
1227 os << "\\lyxdollar ";
1230 os << "\\lyxtilde ";
1240 else if (c != '\0') {
1241 Encoding const * const enc = runparams.encoding;
1242 if (enc && !enc->encodable(c))
1243 throw EncodingException(c);
1249 // TIPA uses its own T3 encoding
1250 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1252 // If T1 font encoding is used, use the special
1253 // characters it provides.
1254 // NOTE: Some languages reset the font encoding internally to a
1255 // non-standard font encoding. If we are using such a language,
1256 // we do not output special T1 chars.
1257 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1258 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1259 && latexSpecialT1(c, os, i, column))
1261 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1262 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1263 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1266 // Otherwise, we use what LaTeX provides us.
1269 os << "\\textbackslash" << termcmd;
1273 os << "\\textless" << termcmd;
1277 os << "\\textgreater" << termcmd;
1281 os << "\\textbar" << termcmd;
1286 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1287 (end_pos == -1 || i + 1 < end_pos) &&
1288 text_[i+1] == '-') {
1289 // Prevent "--" becoming an en dash and "---" an em dash.
1290 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1296 os << "\\textquotedbl" << termcmd;
1301 case '%': case '#': case '{':
1309 os << "\\textasciitilde" << termcmd;
1314 os << "\\textasciicircum" << termcmd;
1321 // avoid being mistaken for optional arguments
1329 // Blanks are printed before font switching.
1330 // Sure? I am not! (try nice-latex)
1331 // I am sure it's correct. LyX might be smarter
1332 // in the future, but for now, nothing wrong is
1338 // XeTeX's dash behaviour is determined via a global setting
1339 if (bparams.use_dash_ligatures
1340 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1342 // TODO #10961: && not in inset Flex Code
1343 // TODO #10961: && not in layout LyXCode
1344 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1361 Encoding const & encoding = *(runparams.encoding);
1362 char_type next = '\0';
1363 if (i + 1 < int(text_.size())) {
1364 next = text_[i + 1];
1365 if (Encodings::isCombiningChar(next)) {
1366 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1371 pair<docstring, bool> latex = encoding.latexChar(c);
1372 docstring nextlatex;
1373 bool nexttipas = false;
1374 string nexttipashortcut;
1375 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1376 nextlatex = encoding.latexChar(next).first;
1377 if (runparams.inIPA) {
1378 nexttipashortcut = Encodings::TIPAShortcut(next);
1379 nexttipas = !nexttipashortcut.empty();
1383 if (runparams.inIPA) {
1384 string const tipashortcut = Encodings::TIPAShortcut(c);
1385 if (!tipashortcut.empty()) {
1386 latex.first = from_ascii(tipashortcut);
1387 latex.second = false;
1391 // eventually close "script wrapper" command (see `Paragraph::latex`)
1392 if (!alien_script.empty()
1393 && alien_script != Encodings::isKnownScriptChar(next)) {
1394 column += latex.first.length();
1395 alien_script.clear();
1396 os << latex.first << "}";
1400 && ((!prefixIs(nextlatex, '\\')
1401 && !prefixIs(nextlatex, '{')
1402 && !prefixIs(nextlatex, '}'))
1404 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1406 // Prevent eating of a following space or command corruption by
1407 // following characters
1408 if (next == ' ' || next == '\0') {
1409 column += latex.first.length() + 1;
1410 os << latex.first << "{}";
1412 column += latex.first.length();
1413 os << latex.first << " ";
1416 column += latex.first.length() - 1;
1424 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1425 pos_type i, unsigned int & column) const
1431 // In T1 encoding, these characters exist
1432 // but we should avoid ligatures
1433 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1435 os << "\\textcompwordmark" << termcmd;
1442 // soul.sty breaks with \char`\"
1443 os << "\\textquotedbl" << termcmd;
1452 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1453 pos_type i, unsigned int & column) const
1455 // TU encoding is currently on par with T1.
1456 return latexSpecialT1(c, os, i, column);
1460 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1461 pos_type /*i*/, unsigned int & column) const
1471 os << "\\textvertline" << termcmd;
1480 void Paragraph::Private::validate(LaTeXFeatures & features) const
1482 if (layout_->inpreamble && inset_owner_) {
1483 // FIXME: Using a string stream here circumvents the encoding
1484 // switching machinery of odocstream. Therefore the
1485 // output is wrong if this paragraph contains content
1486 // that needs to switch encoding.
1487 Buffer const & buf = inset_owner_->buffer();
1488 otexstringstream os;
1489 os << layout_->preamble();
1490 size_t const length = os.length();
1491 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1492 buf.getParFromID(owner_->id()).pit(), os,
1493 features.runparams(), string(), 0, -1, true);
1494 if (os.length() > length)
1495 features.addPreambleSnippet(os.release(), true);
1498 if (features.runparams().flavor == Flavor::Html
1499 && layout_->htmltitle()) {
1500 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1503 // check the params.
1504 if (!params_.spacing().isDefault())
1505 features.require("setspace");
1508 features.useLayout(layout_->name());
1511 fontlist_.validate(features);
1513 // then the indentation
1514 if (!params_.leftIndent().zero())
1515 features.require("ParagraphLeftIndent");
1518 InsetList::const_iterator icit = insetlist_.begin();
1519 InsetList::const_iterator iend = insetlist_.end();
1520 for (; icit != iend; ++icit) {
1522 features.inDeletedInset(owner_->isDeleted(icit->pos));
1523 if (icit->inset->lyxCode() == FOOT_CODE) {
1524 // FIXME: an item inset would make things much easier.
1525 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1526 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1527 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1528 && (icit->pos < begin_of_body_
1529 || (icit->pos == begin_of_body_
1530 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1531 features.saveNoteEnv("description");
1533 icit->inset->validate(features);
1534 features.inDeletedInset(false);
1535 if (layout_->needprotect &&
1536 icit->inset->lyxCode() == FOOT_CODE)
1537 features.require("NeedLyXFootnoteCode");
1541 // then the contents
1542 BufferParams const bp = features.runparams().is_child
1543 ? features.buffer().masterParams() : features.buffer().params();
1544 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1545 char_type c = text_[i];
1546 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1548 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1549 features.require("textquotedblp");
1550 else if (features.runparams().main_fontenc != "T1"
1551 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1552 features.require("textquotedbl");
1553 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1554 // features that depend on the font or input encoding
1555 string feats = ci.textPreamble();
1556 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1557 if (fontenc.empty())
1558 fontenc = features.runparams().main_fontenc;
1559 while (!feats.empty()) {
1561 feats = split(feats, feat, ',');
1562 if (contains(feat, "!=")) {
1563 // a feature that is required except for the spcified
1564 // font or input encodings
1566 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1567 // multiple encodings are separated by semicolon
1568 vector<string> context = getVectorFromString(contexts, ";");
1569 // require feature if the context matches neither current font
1570 // nor input encoding
1571 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1572 && std::find(context.begin(), context.end(),
1573 features.runparams().encoding->name()) == context.end())
1574 features.require(realfeature);
1575 } else if (contains(feat, '=')) {
1576 // a feature that is required only for the spcified
1577 // font or input encodings
1579 string const contexts = split(feat, realfeature, '=');
1580 // multiple encodings are separated by semicolon
1581 vector<string> context = getVectorFromString(contexts, ";");
1582 // require feature if the context matches either current font
1583 // or input encoding
1584 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1585 || std::find(context.begin(), context.end(),
1586 features.runparams().encoding->name()) != context.end())
1587 features.require(realfeature);
1590 } else if (!bp.use_dash_ligatures
1591 && (c == 0x2013 || c == 0x2014)
1592 && bp.useNonTeXFonts
1593 && features.runparams().flavor == Flavor::XeTeX)
1594 // XeTeX's dash behaviour is determined via a global setting
1595 features.require("xetexdashbreakstate");
1596 BufferEncodings::validate(c, features);
1600 /////////////////////////////////////////////////////////////////////
1604 /////////////////////////////////////////////////////////////////////
1607 Layout const emptyParagraphLayout;
1610 Paragraph::Paragraph()
1611 : d(new Paragraph::Private(this, emptyParagraphLayout))
1618 Paragraph::Paragraph(Paragraph const & par)
1619 : itemdepth(par.itemdepth),
1620 d(new Paragraph::Private(*par.d, this))
1626 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1627 : itemdepth(par.itemdepth),
1628 d(new Paragraph::Private(*par.d, this, beg, end))
1634 Paragraph & Paragraph::operator=(Paragraph const & par)
1636 // needed as we will destroy the private part before copying it
1638 itemdepth = par.itemdepth;
1642 d = new Private(*par.d, this);
1649 Paragraph::~Paragraph()
1658 // this shall be called just before every "os << ..." action.
1659 void flushString(ostream & os, docstring & s)
1668 void Paragraph::write(ostream & os, BufferParams const & bparams,
1669 depth_type & depth) const
1671 // The beginning or end of a deeper (i.e. nested) area?
1672 if (depth != d->params_.depth()) {
1673 if (d->params_.depth() > depth) {
1674 while (d->params_.depth() > depth) {
1675 os << "\n\\begin_deeper";
1679 while (d->params_.depth() < depth) {
1680 os << "\n\\end_deeper";
1686 // First write the layout
1687 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1689 d->params_.write(os);
1691 Font font1(inherit_font, bparams.language);
1693 Change running_change = Change(Change::UNCHANGED);
1695 // this string is used as a buffer to avoid repetitive calls
1696 // to to_utf8(), which turn out to be expensive (JMarc)
1697 docstring write_buffer;
1700 for (pos_type i = 0; i <= size(); ++i) {
1702 Change const & change = lookupChange(i);
1703 if (change != running_change)
1704 flushString(os, write_buffer);
1705 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1706 running_change = change;
1711 // Write font changes
1712 Font font2 = getFontSettings(bparams, i);
1713 if (font2 != font1) {
1714 flushString(os, write_buffer);
1715 font2.lyxWriteChanges(font1, os);
1720 char_type const c = d->text_[i];
1723 if (Inset const * inset = getInset(i)) {
1724 flushString(os, write_buffer);
1725 if (inset->directWrite()) {
1726 // international char, let it write
1727 // code directly so it's shorter in
1733 os << "\\begin_inset ";
1735 os << "\n\\end_inset\n\n";
1738 // FIXME This can be removed again once the mystery
1739 // crash has been resolved.
1744 flushString(os, write_buffer);
1745 os << "\n\\backslash\n";
1749 flushString(os, write_buffer);
1750 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1757 if ((column > 70 && c == ' ')
1759 flushString(os, write_buffer);
1763 // this check is to amend a bug. LyX sometimes
1764 // inserts '\0' this could cause problems.
1766 write_buffer.push_back(c);
1768 LYXERR0("NUL char in structure.");
1774 flushString(os, write_buffer);
1775 os << "\n\\end_layout\n";
1776 // FIXME This can be removed again once the mystery
1777 // crash has been resolved.
1782 void Paragraph::validate(LaTeXFeatures & features) const
1784 d->validate(features);
1785 bool fragile = features.runparams().moving_arg;
1786 fragile |= layout().needprotect;
1787 if (inInset().getLayout().isNeedProtect())
1789 if (needsCProtection(fragile))
1790 features.require("cprotect");
1794 void Paragraph::insert(pos_type pos, docstring const & str,
1795 Font const & font, Change const & change)
1797 for (size_t i = 0, n = str.size(); i != n ; ++i)
1798 insertChar(pos + i, str[i], font, change);
1802 void Paragraph::appendChar(char_type c, Font const & font,
1803 Change const & change)
1805 // Make sure that Buffer::hasChangesPresent is updated
1806 ChangesMonitor cm(*this);
1809 d->changes_.insert(change, d->text_.size());
1810 // when appending characters, no need to update tables
1811 d->text_.push_back(c);
1812 setFont(d->text_.size() - 1, font);
1813 d->requestSpellCheck(d->text_.size() - 1);
1817 void Paragraph::appendString(docstring const & s, Font const & font,
1818 Change const & change)
1820 // Make sure that Buffer::hasChangesPresent is updated
1821 ChangesMonitor cm(*this);
1823 pos_type end = s.size();
1824 size_t oldsize = d->text_.size();
1825 size_t newsize = oldsize + end;
1826 size_t capacity = d->text_.capacity();
1827 if (newsize >= capacity)
1828 d->text_.reserve(max(capacity + 100, newsize));
1830 // when appending characters, no need to update tables
1833 // FIXME: Optimize this!
1834 for (size_t i = oldsize; i != newsize; ++i) {
1836 d->changes_.insert(change, i);
1837 d->requestSpellCheck(i);
1839 d->fontlist_.set(oldsize, font);
1840 d->fontlist_.set(newsize - 1, font);
1844 void Paragraph::insertChar(pos_type pos, char_type c,
1847 d->insertChar(pos, c, Change(trackChanges ?
1848 Change::INSERTED : Change::UNCHANGED));
1852 void Paragraph::insertChar(pos_type pos, char_type c,
1853 Font const & font, bool trackChanges)
1855 d->insertChar(pos, c, Change(trackChanges ?
1856 Change::INSERTED : Change::UNCHANGED));
1861 void Paragraph::insertChar(pos_type pos, char_type c,
1862 Font const & font, Change const & change)
1864 d->insertChar(pos, c, change);
1869 void Paragraph::resetFonts(Font const & font)
1871 d->fontlist_.clear();
1872 d->fontlist_.set(0, font);
1873 d->fontlist_.set(d->text_.size() - 1, font);
1876 // Gets uninstantiated font setting at position.
1877 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1881 LYXERR0("pos: " << pos << " size: " << size());
1885 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1886 if (cit != d->fontlist_.end())
1889 if (pos == size() && !empty())
1890 return getFontSettings(bparams, pos - 1);
1892 // Optimisation: avoid a full font instantiation if there is no
1893 // language change from previous call.
1894 static Font previous_font;
1895 static Language const * previous_lang = nullptr;
1896 Language const * lang = getParLanguage(bparams);
1897 if (lang != previous_lang) {
1898 previous_lang = lang;
1899 previous_font = Font(inherit_font, lang);
1901 return previous_font;
1905 FontSpan Paragraph::fontSpan(pos_type pos) const
1907 LBUFERR(pos <= size());
1910 return FontSpan(pos, pos);
1913 FontList::const_iterator cit = d->fontlist_.begin();
1914 FontList::const_iterator end = d->fontlist_.end();
1915 for (; cit != end; ++cit) {
1916 if (cit->pos() >= pos) {
1917 if (pos >= beginOfBody())
1918 return FontSpan(max(start, beginOfBody()),
1921 return FontSpan(start,
1922 min(beginOfBody() - 1,
1925 start = cit->pos() + 1;
1928 // This should not happen, but if so, we take no chances.
1929 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1930 LASSERT(false, return FontSpan(pos, pos));
1934 // Gets uninstantiated font setting at position 0
1935 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1937 if (!empty() && !d->fontlist_.empty())
1938 return d->fontlist_.begin()->font();
1940 // Optimisation: avoid a full font instantiation if there is no
1941 // language change from previous call.
1942 static Font previous_font;
1943 static Language const * previous_lang = nullptr;
1944 if (bparams.language != previous_lang) {
1945 previous_lang = bparams.language;
1946 previous_font = Font(inherit_font, bparams.language);
1949 return previous_font;
1953 // Gets the fully instantiated font at a given position in a paragraph
1954 // This is basically the same function as Text::GetFont() in text2.cpp.
1955 // The difference is that this one is used for generating the LaTeX file,
1956 // and thus cosmetic "improvements" are disallowed: This has to deliver
1957 // the true picture of the buffer. (Asger)
1958 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1959 Font const & outerfont) const
1963 Font font = getFontSettings(bparams, pos);
1965 pos_type const body_pos = beginOfBody();
1966 FontInfo & fi = font.fontInfo();
1968 fi.realize(d->layout_->labelfont);
1970 fi.realize(d->layout_->font);
1972 fi.realize(outerfont.fontInfo());
1973 fi.realize(bparams.getFont().fontInfo());
1979 Font const Paragraph::getLabelFont
1980 (BufferParams const & bparams, Font const & outerfont) const
1982 FontInfo tmpfont = d->layout_->labelfont;
1983 tmpfont.realize(outerfont.fontInfo());
1984 tmpfont.realize(bparams.getFont().fontInfo());
1985 return Font(tmpfont, getParLanguage(bparams));
1989 Font const Paragraph::getLayoutFont
1990 (BufferParams const & bparams, Font const & outerfont) const
1992 FontInfo tmpfont = d->layout_->font;
1993 tmpfont.realize(outerfont.fontInfo());
1994 tmpfont.realize(bparams.getFont().fontInfo());
1995 return Font(tmpfont, getParLanguage(bparams));
1999 char_type Paragraph::getUChar(BufferParams const & bparams,
2000 OutputParams const & rp,
2003 char_type c = d->text_[pos];
2005 // Return unchanged character in LTR languages
2006 // or if we use poylglossia/bidi (XeTeX).
2007 if (rp.useBidiPackage()
2008 || !getFontSettings(bparams, pos).isRightToLeft())
2011 // Without polyglossia/bidi, we need to account for some special cases.
2012 // FIXME This needs to be audited!
2014 // * The input is as expected for all delimiters
2015 // => checked for Hebrew!
2016 // * The output matches the display in the LyX workarea
2017 // => checked for Hebrew!
2018 // * The special cases below are really necessary
2019 // => checked for Hebrew!
2020 // * In arabic_arabi, brackets are transformed to Arabic
2021 // Ornate Parentheses. Is this is really wanted?
2023 string const & lang = getFontSettings(bparams, pos).language()->lang();
2026 // 1. In the following languages, parentheses need to be reversed.
2027 // Also with polyglodia/luabidi
2028 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2030 // 2. In the following languages, brackets don't need to be reversed.
2031 bool const reversebrackets = lang != "arabic_arabtex"
2032 && lang != "arabic_arabi"
2035 // Now swap delimiters if needed.
2046 if (reversebrackets)
2050 if (reversebrackets)
2071 void Paragraph::setFont(pos_type pos, Font const & font)
2073 LASSERT(pos <= size(), return);
2075 // First, reduce font against layout/label font
2076 // Update: The setCharFont() routine in text2.cpp already
2077 // reduces font, so we don't need to do that here. (Asger)
2079 d->fontlist_.set(pos, font);
2083 void Paragraph::makeSameLayout(Paragraph const & par)
2085 d->layout_ = par.d->layout_;
2086 d->params_ = par.d->params_;
2090 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2092 if (isFreeSpacing())
2098 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2099 if (eraseChar(pos, trackChanges))
2105 return count > 0 || pos > 0;
2109 bool Paragraph::hasSameLayout(Paragraph const & par) const
2111 return par.d->layout_ == d->layout_
2112 && d->params_.sameLayout(par.d->params_);
2116 depth_type Paragraph::getDepth() const
2118 return d->params_.depth();
2122 depth_type Paragraph::getMaxDepthAfter() const
2124 if (d->layout_->isEnvironment())
2125 return d->params_.depth() + 1;
2127 return d->params_.depth();
2131 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2133 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2134 return getDefaultAlign(bparams);
2136 return d->params_.align();
2140 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2142 LyXAlignment res = layout().align;
2143 if (isRTL(bparams)) {
2145 if (res == LYX_ALIGN_LEFT)
2146 res = LYX_ALIGN_RIGHT;
2147 else if (res == LYX_ALIGN_RIGHT)
2148 res = LYX_ALIGN_LEFT;
2154 docstring const & Paragraph::labelString() const
2156 return d->params_.labelString();
2160 // the next two functions are for the manual labels
2161 docstring const Paragraph::getLabelWidthString() const
2163 if (d->layout_->margintype == MARGIN_MANUAL
2164 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2165 return d->params_.labelWidthString();
2167 return _("Senseless with this layout!");
2171 void Paragraph::setLabelWidthString(docstring const & s)
2173 d->params_.labelWidthString(s);
2177 docstring Paragraph::expandLabel(Layout const & layout,
2178 BufferParams const & bparams) const
2180 return expandParagraphLabel(layout, bparams, true);
2184 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2185 BufferParams const & bparams, bool process_appendix) const
2187 DocumentClass const & tclass = bparams.documentClass();
2188 string const & lang = getParLanguage(bparams)->code();
2189 bool const in_appendix = process_appendix && d->params_.appendix();
2190 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2192 if (fmt.empty() && !layout.counter.empty())
2193 return tclass.counters().theCounter(layout.counter, lang);
2195 // handle 'inherited level parts' in 'fmt',
2196 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2197 size_t const i = fmt.find('@', 0);
2198 if (i != docstring::npos) {
2199 size_t const j = fmt.find('@', i + 1);
2200 if (j != docstring::npos) {
2201 docstring parent(fmt, i + 1, j - i - 1);
2202 docstring label = from_ascii("??");
2203 if (tclass.hasLayout(parent))
2204 label = expandParagraphLabel(tclass[parent], bparams,
2206 fmt = docstring(fmt, 0, i) + label
2207 + docstring(fmt, j + 1, docstring::npos);
2211 return tclass.counters().counterLabel(fmt, lang);
2215 void Paragraph::applyLayout(Layout const & new_layout)
2217 d->layout_ = &new_layout;
2218 LyXAlignment const oldAlign = d->params_.align();
2220 if (!(oldAlign & d->layout_->alignpossible)) {
2221 frontend::Alert::warning(_("Alignment not permitted"),
2222 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2223 d->params_.align(LYX_ALIGN_LAYOUT);
2228 pos_type Paragraph::beginOfBody() const
2230 return d->begin_of_body_;
2234 void Paragraph::setBeginOfBody()
2236 if (d->layout_->labeltype != LABEL_MANUAL) {
2237 d->begin_of_body_ = 0;
2241 // Unroll the first two cycles of the loop
2242 // and remember the previous character to
2243 // remove unnecessary getChar() calls
2245 pos_type end = size();
2246 bool prev_char_deleted = false;
2247 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2250 char_type previous_char = d->text_[i];
2251 if (!(isNewline(i) || isEnvSeparator(i))) {
2253 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2254 char_type temp = d->text_[i];
2255 prev_char_deleted = isDeleted(i);
2256 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2259 previous_char = temp;
2265 d->begin_of_body_ = i;
2269 bool Paragraph::allowParagraphCustomization() const
2271 return inInset().allowParagraphCustomization();
2275 bool Paragraph::usePlainLayout() const
2277 return inInset().usePlainLayout();
2281 bool Paragraph::isPassThru() const
2283 return inInset().isPassThru() || d->layout_->pass_thru;
2287 bool Paragraph::parbreakIsNewline() const
2289 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2293 bool Paragraph::isPartOfTextSequence() const
2295 for (pos_type i = 0; i < size(); ++i) {
2296 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2304 // paragraphs inside floats need different alignment tags to avoid
2307 bool noTrivlistCentering(InsetCode code)
2309 return code == FLOAT_CODE
2310 || code == WRAP_CODE
2311 || code == CELL_CODE;
2315 string correction(string const & orig)
2317 if (orig == "flushleft")
2318 return "raggedright";
2319 if (orig == "flushright")
2320 return "raggedleft";
2321 if (orig == "center")
2327 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2328 InsetCode code, bool const lastpar, int & col)
2330 string macro = suffix + "{";
2331 if (noTrivlistCentering(code)) {
2333 // the last paragraph in non-trivlist-aligned
2334 // context is special (to avoid unwanted whitespace)
2335 if (suffix == "\\begin") {
2336 macro = "\\" + correction(env) + "{}";
2337 os << from_ascii(macro);
2338 col += macro.size();
2343 macro += correction(env);
2347 if (suffix == "\\par\\end") {
2351 os << from_ascii(macro);
2352 col += macro.size();
2353 if (suffix == "\\begin") {
2363 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2364 otexstream & os, OutputParams const & runparams) const
2369 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2370 (layout_->toggle_indent != ITOGGLE_NEVER) :
2371 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2373 LyXAlignment const curAlign = params_.align();
2375 // Do not output \\noindent for paragraphs
2376 // 1. that cannot have indentation or are indented always,
2377 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2378 // 3. that are PassThru,
2379 // 4. or that are centered.
2380 if (canindent && params_.noindent()
2381 && owner_->isPartOfTextSequence()
2382 && !layout_->pass_thru
2383 && curAlign != LYX_ALIGN_CENTER) {
2384 if (!owner_->empty()
2385 && owner_->getInset(0)
2386 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2387 // If the paragraph starts with a vspace, the \\noindent
2388 // needs to come after that (as it leaves vmode).
2389 // If the paragraph consists only of the vspace,
2390 // \\noindent is not needed at all.
2391 runparams.need_noindent = owner_->size() > 1;
2393 os << "\\noindent" << termcmd;
2398 if (curAlign == layout_->align)
2402 case LYX_ALIGN_NONE:
2403 case LYX_ALIGN_BLOCK:
2404 case LYX_ALIGN_LAYOUT:
2405 case LYX_ALIGN_SPECIAL:
2406 case LYX_ALIGN_DECIMAL:
2408 case LYX_ALIGN_LEFT:
2409 case LYX_ALIGN_RIGHT:
2410 case LYX_ALIGN_CENTER:
2411 if (runparams.moving_arg) {
2418 string const begin_tag = "\\begin";
2419 InsetCode code = ownerCode();
2420 bool const lastpar = runparams.isLastPar;
2421 // RTL in classic (PDF)LaTeX (without the Bidi package)
2422 // Luabibdi (used by LuaTeX) behaves like classic
2423 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2424 && !runparams.useBidiPackage();
2427 case LYX_ALIGN_NONE:
2428 case LYX_ALIGN_BLOCK:
2429 case LYX_ALIGN_LAYOUT:
2430 case LYX_ALIGN_SPECIAL:
2431 case LYX_ALIGN_DECIMAL:
2433 case LYX_ALIGN_LEFT: {
2435 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2436 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2438 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2440 } case LYX_ALIGN_RIGHT: {
2442 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2443 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2445 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2447 } case LYX_ALIGN_CENTER: {
2448 corrected_env(os, begin_tag, "center", code, lastpar, column);
2457 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2458 otexstream & os, OutputParams const & runparams) const
2460 LyXAlignment const curAlign = params_.align();
2462 if (curAlign == layout_->align)
2466 case LYX_ALIGN_NONE:
2467 case LYX_ALIGN_BLOCK:
2468 case LYX_ALIGN_LAYOUT:
2469 case LYX_ALIGN_SPECIAL:
2470 case LYX_ALIGN_DECIMAL:
2472 case LYX_ALIGN_LEFT:
2473 case LYX_ALIGN_RIGHT:
2474 case LYX_ALIGN_CENTER:
2475 if (runparams.moving_arg)
2480 bool output = false;
2482 string const end_tag = "\\par\\end";
2483 InsetCode code = ownerCode();
2484 bool const lastpar = runparams.isLastPar;
2485 // RTL in classic (PDF)LaTeX (without the Bidi package)
2486 // Luabibdi (used by LuaTeX) behaves like classic
2487 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2488 && !runparams.useBidiPackage();
2491 case LYX_ALIGN_NONE:
2492 case LYX_ALIGN_BLOCK:
2493 case LYX_ALIGN_LAYOUT:
2494 case LYX_ALIGN_SPECIAL:
2495 case LYX_ALIGN_DECIMAL:
2497 case LYX_ALIGN_LEFT: {
2499 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2500 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2502 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2504 } case LYX_ALIGN_RIGHT: {
2506 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2507 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2509 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2511 } case LYX_ALIGN_CENTER: {
2512 corrected_env(os, end_tag, "center", code, lastpar, col);
2517 return output || lastpar;
2521 // This one spits out the text of the paragraph
2522 void Paragraph::latex(BufferParams const & bparams,
2523 Font const & outerfont,
2525 OutputParams const & runparams,
2526 int start_pos, int end_pos, bool force) const
2528 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2530 // FIXME This check should not be needed. Perhaps issue an
2531 // error if it triggers.
2532 Layout const & style = inInset().forcePlainLayout() ?
2533 bparams.documentClass().plainLayout() : *d->layout_;
2535 if (!force && style.inpreamble)
2538 bool const allowcust = allowParagraphCustomization();
2540 // Current base font for all inherited font changes, without any
2541 // change caused by an individual character, except for the language:
2542 // It is set to the language of the first character.
2543 // As long as we are in the label, this font is the base font of the
2544 // label. Before the first body character it is set to the base font
2548 // If there is an open font-encoding changing command (script wrapper),
2549 // alien_script is set to its name
2550 string alien_script;
2553 // Maybe we have to create a optional argument.
2554 pos_type body_pos = beginOfBody();
2555 unsigned int column = 0;
2557 // If we are inside an non inheritFont() inset,
2558 // the outerfont is the buffer's main font
2559 Font const real_outerfont =
2560 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2563 // the optional argument is kept in curly brackets in
2564 // case it contains a ']'
2565 // This is not strictly needed, but if this is changed it
2566 // would be a file format change, and tex2lyx would need
2567 // to be adjusted, since it unconditionally removes the
2568 // braces when it parses \item.
2571 basefont = getLabelFont(bparams, real_outerfont);
2573 basefont = getLayoutFont(bparams, real_outerfont);
2576 // Which font is currently active?
2577 Font running_font(basefont);
2578 // Do we have an open font change?
2579 bool open_font = false;
2581 Change runningChange =
2582 runparams.inDeletedInset && !inInset().canTrackChanges()
2583 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2585 Encoding const * const prev_encoding = runparams.encoding;
2587 os.texrow().start(id(), 0);
2589 // if the paragraph is empty, the loop will not be entered at all
2591 // For InTitle commands, we have already opened a group
2592 // in output_latex::TeXOnePar.
2593 if (style.isCommand() && !style.intitle) {
2597 if (!style.leftdelim().empty()) {
2598 os << style.leftdelim();
2599 column += style.leftdelim().size();
2602 column += d->startTeXParParams(bparams, os, runparams);
2605 // Whether a \par can be issued for insets typeset inline with text.
2606 // Yes if greater than 0. This has to be static.
2607 THREAD_LOCAL_STATIC int parInline = 0;
2609 for (pos_type i = 0; i < size(); ++i) {
2610 // First char in paragraph or after label?
2611 if (i == body_pos) {
2614 bool needPar = false;
2615 column += running_font.latexWriteEndChanges(
2616 os, bparams, runparams,
2617 basefont, basefont, needPar);
2620 basefont = getLayoutFont(bparams, real_outerfont);
2621 running_font = basefont;
2623 column += Changes::latexMarkChange(os, bparams,
2624 runningChange, Change(Change::UNCHANGED),
2626 runningChange = Change(Change::UNCHANGED);
2628 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2631 // For InTitle commands, we have already opened a group
2632 // in output_latex::TeXOnePar.
2633 if (style.isCommand() && !style.intitle) {
2638 if (!style.leftdelim().empty()) {
2639 os << style.leftdelim();
2640 column += style.leftdelim().size();
2644 column += d->startTeXParParams(bparams, os,
2648 runparams.wasDisplayMath = runparams.inDisplayMath;
2649 runparams.inDisplayMath = false;
2650 bool deleted_display_math = false;
2651 Change const & change = runparams.inDeletedInset
2652 ? runparams.changeOfDeletedInset : lookupChange(i);
2654 char_type const c = d->text_[i];
2656 // Check whether a display math inset follows
2657 bool output_changes;
2658 if (!runparams.find_effective())
2659 output_changes = bparams.output_changes;
2661 output_changes = runparams.find_with_deleted();
2663 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2665 runparams.ctObject = getInset(i)->getCtObject(runparams);
2667 InsetMath const * im = getInset(i)->asInsetMath();
2668 if (im && im->asHullInset()
2669 && im->asHullInset()->outerDisplay()) {
2670 runparams.inDisplayMath = true;
2671 // runparams.inDeletedInset will be set by
2672 // latexInset later, but we need this info
2673 // before it is called. On the other hand, we
2674 // cannot set it here because it is a counter.
2675 deleted_display_math = isDeleted(i);
2677 if (output_changes && deleted_display_math
2678 && runningChange == change
2679 && change.type == Change::DELETED
2680 && !os.afterParbreak()) {
2681 // A display math in the same paragraph follows.
2682 // We have to close and then reopen \lyxdeleted,
2683 // otherwise the math will be shifted up.
2684 OutputParams rp = runparams;
2686 bool needPar = false;
2687 column += running_font.latexWriteEndChanges(
2688 os, bparams, rp, basefont,
2692 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2693 : getLayoutFont(bparams, real_outerfont);
2694 running_font = basefont;
2695 column += Changes::latexMarkChange(os, bparams,
2696 Change(Change::INSERTED), change, rp);
2700 if (output_changes && runningChange != change) {
2701 if (!alien_script.empty()) {
2704 alien_script.clear();
2707 bool needPar = false;
2708 column += running_font.latexWriteEndChanges(
2709 os, bparams, runparams,
2710 basefont, basefont, needPar);
2713 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2714 : getLayoutFont(bparams, real_outerfont);
2715 running_font = basefont;
2716 column += Changes::latexMarkChange(os, bparams, runningChange,
2718 runningChange = change;
2721 // do not output text which is marked deleted
2722 // if change tracking output is disabled
2723 if (!output_changes && change.deleted()) {
2729 // Fully instantiated font
2730 Font current_font = getFont(bparams, i, outerfont);
2732 Font const prev_font = (i > 0) ?
2733 getFont(bparams, i - 1, outerfont)
2736 Font const last_font = running_font;
2737 bool const in_ct_deletion = (output_changes
2738 && runningChange == change
2739 && change.type == Change::DELETED
2740 && !os.afterParbreak());
2741 // Insets where font switches are used (rather than font commands)
2742 bool const fontswitch_inset =
2745 && getInset(i)->allowMultiPar()
2746 && getInset(i)->lyxCode() != ERT_CODE
2747 && (getInset(i)->producesOutput()
2748 // FIXME Something more general?
2749 // Comments do not "produce output" but are still
2750 // part of the TeX source and require font switches
2751 // to be closed (otherwise LaTeX fails).
2752 || getInset(i)->layoutName() == "Note:Comment");
2754 bool closeLanguage = false;
2755 bool lang_switched_at_inset = false;
2756 if (fontswitch_inset) {
2757 // Some insets cannot be inside a font change command.
2758 // However, even such insets *can* be placed in \L or \R
2759 // or their equivalents (for RTL language switches),
2760 // so we don't close the language in those cases
2761 // (= differing isRightToLeft()).
2762 // ArabTeX, though, doesn't seem to handle this special behavior.
2763 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2764 || basefont.language()->lang() == "arabic_arabtex"
2765 || current_font.language()->lang() == "arabic_arabtex";
2766 // We need to check prev_font as language changes directly at inset
2767 // will only be started inside the inset.
2768 lang_switched_at_inset = prev_font.language() != current_font.language();
2771 // Do we need to close the previous font?
2772 bool langClosed = false;
2774 ((current_font != running_font
2775 || current_font.language() != running_font.language())
2776 || (fontswitch_inset
2777 && (current_font == prev_font))))
2779 // ensure there is no open script-wrapper
2780 if (!alien_script.empty()) {
2783 alien_script.clear();
2785 if (in_ct_deletion) {
2786 // We have to close and then reopen \lyxdeleted,
2787 // as strikeout needs to be on lowest level.
2792 // Force language closing
2793 current_font.setLanguage(basefont.language());
2794 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2795 bool needPar = false;
2796 column += running_font.latexWriteEndChanges(
2797 os, bparams, runparams, basefont,
2799 if (in_ct_deletion) {
2800 // We have to close and then reopen \lyxdeleted,
2801 // as strikeout needs to be on lowest level.
2802 OutputParams rp = runparams;
2803 column += Changes::latexMarkChange(os, bparams,
2804 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2806 // Has the language been closed in the latexWriteEndChanges() call above?
2807 langClosed = running_font.language() != basefont.language()
2808 && running_font.language() != nextfont.language()
2809 && (running_font.language()->encoding()->package() != Encoding::CJK);
2810 running_font = basefont;
2811 open_font &= !langClosed;
2814 // if necessary, close language environment before opening CJK
2815 string const running_lang = running_font.language()->babel();
2816 string const lang_end_command = lyxrc.language_command_end;
2817 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2818 && !running_lang.empty()
2819 && running_lang == openLanguageName()
2820 && current_font.language()->encoding()->package() == Encoding::CJK) {
2821 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2822 os << from_ascii(end_tag);
2823 column += end_tag.length();
2824 if (!languageStackEmpty())
2828 // Switch file encoding if necessary (and allowed)
2829 if ((!fontswitch_inset || closeLanguage)
2830 && !runparams.pass_thru && !style.pass_thru &&
2831 runparams.encoding->package() != Encoding::none &&
2832 current_font.language()->encoding()->package() != Encoding::none) {
2833 pair<bool, int> const enc_switch =
2834 switchEncoding(os.os(), bparams, runparams,
2835 *(current_font.language()->encoding()));
2836 if (enc_switch.first) {
2837 column += enc_switch.second;
2838 runparams.encoding = current_font.language()->encoding();
2842 // A display math inset inside an ulem command will be output
2843 // as a box of width \linewidth, so we have to either disable
2844 // indentation if the inset starts a paragraph, or start a new
2845 // line to accommodate such box. This has to be done before
2846 // writing any font changing commands.
2847 if (runparams.inDisplayMath && !deleted_display_math
2848 && runparams.inulemcmd) {
2849 if (os.afterParbreak())
2855 // Do we need to change font?
2856 if ((current_font != running_font ||
2857 current_font.language() != running_font.language())
2858 && i != body_pos - 1)
2860 if (!fontswitch_inset) {
2861 if (in_ct_deletion) {
2862 // We have to close and then reopen \lyxdeleted,
2863 // as strikeout needs to be on lowest level.
2864 OutputParams rp = runparams;
2865 bool needPar = false;
2866 column += running_font.latexWriteEndChanges(
2867 os, bparams, rp, basefont,
2872 otexstringstream ots;
2873 InsetText const * textinset = inInset().asInsetText();
2874 bool const cprotect = textinset
2875 ? textinset->hasCProtectContent(runparams.moving_arg)
2876 && !textinset->text().isMainText()
2877 && inInset().lyxCode() != BRANCH_CODE
2879 column += current_font.latexWriteStartChanges(ots, bparams,
2880 runparams, basefont, last_font, false,
2882 // Check again for display math in ulem commands as a
2883 // font change may also occur just before a math inset.
2884 if (runparams.inDisplayMath && !deleted_display_math
2885 && runparams.inulemcmd) {
2886 if (os.afterParbreak())
2891 running_font = current_font;
2893 docstring fontchange = ots.str();
2895 // check whether the fontchange ends with a \\textcolor
2896 // modifier and the text starts with a space. If so we
2897 // need to add } in order to prevent \\textcolor from gobbling
2898 // the space (bug 4473).
2899 docstring const last_modifier = rsplit(fontchange, '\\');
2900 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2901 os << from_ascii("{}");
2902 else if (ots.terminateCommand())
2904 if (in_ct_deletion) {
2905 // We have to close and then reopen \lyxdeleted,
2906 // as strikeout needs to be on lowest level.
2907 OutputParams rp = runparams;
2908 column += Changes::latexMarkChange(os, bparams,
2909 Change(Change::UNCHANGED), change, rp);
2911 } else {// if fontswitch_inset
2912 if (current_font != running_font || !langClosed)
2913 // font is still open in fontswitch_insets if we have
2914 // a non-lang font difference or if the language
2915 // is the only difference but has not been forcedly
2918 running_font = current_font;
2922 // FIXME: think about end_pos implementation...
2923 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2924 // FIXME: integrate this case in latexSpecialChar
2925 // Do not print the separation of the optional argument
2926 // if style.pass_thru is false. This works because
2927 // latexSpecialChar ignores spaces if
2928 // style.pass_thru is false.
2929 if (i != body_pos - 1) {
2930 if (d->simpleTeXBlanks(bparams, runparams, os,
2931 i, column, current_font, style)) {
2932 // A surrogate pair was output. We
2933 // must not call latexSpecialChar
2934 // in this iteration, since it would output
2935 // the combining character again.
2942 OutputParams rp = runparams;
2943 rp.free_spacing = style.free_spacing;
2944 rp.local_font = ¤t_font;
2945 rp.intitle = style.intitle;
2947 // Two major modes: LaTeX or plain
2948 // Handle here those cases common to both modes
2949 // and then split to handle the two modes separately.
2950 if (c == META_INSET) {
2951 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2952 // Greyedout notes and, in general, all insets
2953 // with InsetLayout::isDisplay() == false,
2954 // are typeset inline with the text. So, we
2955 // can add a \par to the last paragraph of
2956 // such insets only if nothing else follows.
2957 bool incremented = false;
2958 Inset const * inset = getInset(i);
2959 InsetText const * textinset = inset
2960 ? inset->asInsetText()
2962 if (i + 1 == size() && textinset
2963 && !inset->getLayout().isDisplay()) {
2964 ParagraphList const & pars =
2965 textinset->text().paragraphs();
2966 pit_type const pit = pars.size() - 1;
2967 Font const lastfont =
2968 pit < 0 || pars[pit].empty()
2969 ? pars[pit].getLayoutFont(
2972 : pars[pit].getFont(bparams,
2973 pars[pit].size() - 1,
2975 if (lastfont.fontInfo().size() !=
2976 basefont.fontInfo().size()) {
2981 // We need to restore parts of this after insets with
2982 // allowMultiPar() true
2983 Font const save_basefont = basefont;
2984 d->latexInset(bparams, os, rp, running_font,
2985 basefont, real_outerfont, open_font,
2986 runningChange, style, i, column, fontswitch_inset,
2987 closeLanguage, lang_switched_at_inset);
2988 if (fontswitch_inset) {
2990 bool needPar = false;
2991 column += running_font.latexWriteEndChanges(
2992 os, bparams, runparams,
2993 basefont, basefont, needPar);
2996 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2997 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2998 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3003 if (runparams.ctObject == CtObject::DisplayObject
3004 || runparams.ctObject == CtObject::UDisplayObject) {
3005 // Close \lyx*deleted and force its
3006 // reopening (if needed)
3009 runningChange = Change(Change::UNCHANGED);
3010 runparams.ctObject = CtObject::Normal;
3013 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3014 if (!bparams.useNonTeXFonts)
3015 script = Encodings::isKnownScriptChar(c);
3016 if (script != alien_script) {
3017 if (!alien_script.empty()) {
3019 alien_script.clear();
3021 string fontenc = running_font.language()->fontenc(bparams);
3023 && !Encodings::fontencSupportsScript(fontenc, script)) {
3024 column += script.length() + 2;
3025 os << "\\" << script << "{";
3026 alien_script = script;
3030 d->latexSpecialChar(os, bparams, rp, running_font,
3031 alien_script, style, i, end_pos, column);
3032 } catch (EncodingException & e) {
3033 if (runparams.dryrun) {
3034 os << "<" << _("LyX Warning: ")
3035 << _("uncodable character") << " '";
3039 // add location information and throw again.
3047 // Set the encoding to that returned from latexSpecialChar (see
3048 // comment for encoding member in OutputParams.h)
3049 runparams.encoding = rp.encoding;
3051 // Also carry on the info on a closed ulem command for insets
3052 // such as Note that do not produce any output, so that no
3053 // command is ever executed but its opening was recorded.
3054 runparams.inulemcmd = rp.inulemcmd;
3056 // These need to be passed upstream as well
3057 runparams.need_maketitle = rp.need_maketitle;
3058 runparams.have_maketitle = rp.have_maketitle;
3060 // And finally, pass the post_macros upstream
3061 runparams.post_macro = rp.post_macro;
3064 // Close wrapper for alien script
3065 if (!alien_script.empty()) {
3067 alien_script.clear();
3070 Font const font = empty()
3071 ? getLayoutFont(bparams, real_outerfont)
3072 : getFont(bparams, size() - 1, real_outerfont);
3074 InsetText const * textinset = inInset().asInsetText();
3076 bool const maintext = textinset
3077 ? textinset->text().isMainText()
3080 size_t const numpars = textinset
3081 ? textinset->text().paragraphs().size()
3084 bool needPar = false;
3086 if (style.resfont.size() != font.fontInfo().size()
3087 && (!runparams.isLastPar || maintext
3088 || (numpars > 1 && d->ownerCode() != CELL_CODE
3089 && (inInset().getLayout().isDisplay()
3091 && !style.isCommand()) {
3095 // If we have an open font definition, we have to close it
3097 // Make sure that \\par is done with the font of the last
3098 // character if this has another size as the default.
3099 // This is necessary because LaTeX (and LyX on the screen)
3100 // calculates the space between the baselines according
3101 // to this font. (Matthias)
3103 // We must not change the font for the last paragraph
3104 // of non-multipar insets, tabular cells or commands,
3105 // since this produces unwanted whitespace.
3106 #ifdef FIXED_LANGUAGE_END_DETECTION
3108 running_font.latexWriteEndChanges(os, bparams,
3109 runparams, basefont,
3110 next_->getFont(bparams, 0, outerfont),
3113 running_font.latexWriteEndChanges(os, bparams,
3114 runparams, basefont, basefont, needPar);
3117 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3118 //FIXME: there as we start another \selectlanguage with the next paragraph if
3119 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3120 running_font.latexWriteEndChanges(os, bparams, runparams,
3121 basefont, basefont, needPar);
3125 // The \par could not be inserted at the same nesting
3126 // level of the font size change, so do it now.
3127 os << "{\\" << font.latexSize() << "\\par}";
3130 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3131 column += Changes::latexMarkChange(os, bparams, runningChange,
3132 Change(Change::UNCHANGED), runparams);
3134 // Needed if there is an optional argument but no contents.
3135 if (body_pos > 0 && body_pos == size()) {
3139 if (!style.rightdelim().empty()) {
3140 os << style.rightdelim();
3141 column += style.rightdelim().size();
3144 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3145 && runparams.encoding != prev_encoding) {
3146 runparams.encoding = prev_encoding;
3147 os << setEncoding(prev_encoding->iconvName());
3150 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3154 bool Paragraph::emptyTag() const
3156 for (pos_type i = 0; i < size(); ++i) {
3157 if (Inset const * inset = getInset(i)) {
3158 InsetCode lyx_code = inset->lyxCode();
3159 // FIXME testing like that is wrong. What is
3161 if (lyx_code != TOC_CODE &&
3162 lyx_code != INCLUDE_CODE &&
3163 lyx_code != GRAPHICS_CODE &&
3164 lyx_code != ERT_CODE &&
3165 lyx_code != LISTINGS_CODE &&
3166 lyx_code != FLOAT_CODE &&
3167 lyx_code != TABULAR_CODE) {
3171 char_type c = d->text_[i];
3172 if (c != ' ' && c != '\t')
3180 string Paragraph::getID(Buffer const &, OutputParams const &)
3183 for (pos_type i = 0; i < size(); ++i) {
3184 if (Inset const * inset = getInset(i)) {
3185 InsetCode lyx_code = inset->lyxCode();
3186 if (lyx_code == LABEL_CODE) {
3187 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3188 docstring const & id = il->getParam("name");
3189 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3197 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3200 for (i = 0; i < size(); ++i) {
3201 if (Inset const * inset = getInset(i)) {
3202 inset->docbook(xs, runparams);
3204 char_type c = d->text_[i];
3214 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3218 for (i = 0; i < size(); ++i) {
3219 if (Inset const * inset = getInset(i)) {
3220 inset->xhtml(xs, runparams);
3222 char_type c = d->text_[i];
3232 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3235 pos_type size = text_.size();
3236 for (pos_type i = initial; i < size; ++i) {
3237 Font font = owner_->getFont(buf.params(), i, outerfont);
3238 if (text_[i] == META_INSET)
3240 if (i != initial && font != font_old)
3251 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3252 vector<xml::EndFontTag> & tagsToClose,
3253 bool & flag, FontState curstate, xml::FontTypes type)
3255 if (curstate == FONT_ON) {
3256 tagsToOpen.push_back(docbookStartFontTag(type));
3259 tagsToClose.push_back(docbookEndFontTag(type));
3264 class OptionalFontType {
3269 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3270 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3273 OptionalFontType fontShapeToXml(FontShape fs)
3277 return {xml::FT_ITALIC};
3279 return {xml::FT_SLANTED};
3280 case SMALLCAPS_SHAPE:
3281 return {xml::FT_SMALLCAPS};
3286 // the other tags are for internal use
3292 OptionalFontType fontFamilyToXml(FontFamily fm)
3296 return {xml::FT_ROMAN};
3298 return {xml::FT_SANS};
3299 case TYPEWRITER_FAMILY:
3300 return {xml::FT_TYPE};
3301 case INHERIT_FAMILY:
3304 // the other tags are for internal use
3310 OptionalFontType fontSizeToXml(FontSize fs)
3314 return {xml::FT_SIZE_TINY};
3316 return {xml::FT_SIZE_SCRIPT};
3318 return {xml::FT_SIZE_FOOTNOTE};
3320 return {xml::FT_SIZE_SMALL};
3322 return {xml::FT_SIZE_LARGE};
3324 return {xml::FT_SIZE_LARGER};
3326 return {xml::FT_SIZE_LARGEST};
3328 return {xml::FT_SIZE_HUGE};
3330 return {xml::FT_SIZE_HUGER};
3332 return {xml::FT_SIZE_INCREASE};
3334 return {xml::FT_SIZE_DECREASE};
3339 // the other tags are for internal use
3345 struct DocBookFontState
3347 FontShape curr_fs = INHERIT_SHAPE;
3348 FontFamily curr_fam = INHERIT_FAMILY;
3349 FontSize curr_size = INHERIT_SIZE;
3351 // track whether we have opened these tags
3352 bool emph_flag = false;
3353 bool bold_flag = false;
3354 bool noun_flag = false;
3355 bool ubar_flag = false;
3356 bool dbar_flag = false;
3357 bool sout_flag = false;
3358 bool xout_flag = false;
3359 bool wave_flag = false;
3361 bool shap_flag = false;
3363 bool faml_flag = false;
3365 bool size_flag = false;
3368 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3370 std::string const & default_family,
3371 DocBookFontState & fs)
3373 vector<xml::FontTag> tagsToOpen;
3374 vector<xml::EndFontTag> tagsToClose;
3377 FontState curstate = font.fontInfo().emph();
3378 if (font_old.emph() != curstate)
3379 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3382 curstate = font.fontInfo().noun();
3383 if (font_old.noun() != curstate)
3384 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3387 curstate = font.fontInfo().underbar();
3388 if (font_old.underbar() != curstate)
3389 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3392 curstate = font.fontInfo().strikeout();
3393 if (font_old.strikeout() != curstate)
3394 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3397 curstate = font.fontInfo().xout();
3398 if (font_old.xout() != curstate)
3399 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3402 curstate = font.fontInfo().uuline();
3403 if (font_old.uuline() != curstate)
3404 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3407 curstate = font.fontInfo().uwave();
3408 if (font_old.uwave() != curstate)
3409 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3412 // a little hackish, but allows us to reuse what we have.
3413 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3414 if (font_old.series() != font.fontInfo().series())
3415 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3418 fs.curr_fs = font.fontInfo().shape();
3419 FontShape old_fs = font_old.shape();
3420 if (old_fs != fs.curr_fs) {
3422 OptionalFontType tag = fontShapeToXml(old_fs);
3424 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3425 fs.shap_flag = false;
3428 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3430 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3434 fs.curr_fam = font.fontInfo().family();
3435 FontFamily old_fam = font_old.family();
3436 if (old_fam != fs.curr_fam) {
3438 OptionalFontType tag = fontFamilyToXml(old_fam);
3440 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3441 fs.faml_flag = false;
3443 switch (fs.curr_fam) {
3445 // we will treat a "default" font family as roman, since we have
3446 // no other idea what to do.
3447 if (default_family != "rmdefault" && default_family != "default") {
3448 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3449 fs.faml_flag = true;
3453 if (default_family != "sfdefault") {
3454 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3455 fs.faml_flag = true;
3458 case TYPEWRITER_FAMILY:
3459 if (default_family != "ttdefault") {
3460 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3461 fs.faml_flag = true;
3464 case INHERIT_FAMILY:
3467 // the other tags are for internal use
3474 fs.curr_size = font.fontInfo().size();
3475 FontSize old_size = font_old.size();
3476 if (old_size != fs.curr_size) {
3478 OptionalFontType tag = fontSizeToXml(old_size);
3480 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3481 fs.size_flag = false;
3484 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3485 if (tag.has_value) {
3486 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3487 fs.size_flag = true;
3491 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3494 } // anonymous namespace
3497 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3498 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3499 OutputParams const & runparams,
3500 Font const & outerfont,
3503 bool ignore_fonts) const
3505 std::vector<docstring> prependedParagraphs;
3506 std::vector<docstring> generatedParagraphs;
3507 std::vector<docstring> appendedParagraphs;
3508 odocstringstream os;
3510 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3511 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3513 OutputParams rp = runparams;
3514 for (pos_type i = initial; i < size(); ++i) {
3515 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3516 const InsetArgument * arg = getInset(i)->asInsetArgument();
3517 if (arg->docbookargumentbeforemaintag()) {
3518 auto xs_local = XMLStream(os);
3519 arg->docbook(xs_local, rp);
3521 prependedParagraphs.push_back(os.str());
3522 os.str(from_ascii(""));
3524 rp.docbook_prepended_arguments.insert(arg);
3525 } else if (arg->docbookargumentaftermaintag()) {
3526 rp.docbook_appended_arguments.insert(arg);
3531 // State variables for the main loop.
3532 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3533 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3534 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3535 // This requires to store delayed characters at some point.
3537 DocBookFontState fs; // Track whether we have opened font tags
3538 DocBookFontState old_fs = fs;
3540 Layout const & style = *d->layout_;
3541 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3542 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3544 vector<xml::FontTag> tagsToOpen;
3545 vector<xml::EndFontTag> tagsToClose;
3547 // Parsing main loop.
3548 for (pos_type i = initial; i < size(); ++i) {
3549 bool ignore_fonts_i = ignore_fonts
3550 || style.docbooknofontinside()
3551 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3553 // Don't show deleted material in the output.
3557 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3559 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3560 if (!ignore_fonts_i)
3561 xs->closeFontTags();
3563 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3564 generatedParagraphs.push_back(os.str());
3566 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3567 // that the string stream must be reset.
3568 os.str(from_ascii(""));
3570 xs = new XMLStream(os);
3572 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3573 if (!ignore_fonts_i) {
3574 font_old = outerfont.fontInfo();
3579 // Determine which tags should be opened or closed regarding fonts.
3580 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3581 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3583 if (!ignore_fonts_i) {
3584 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3585 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3586 for (; cit != cen; ++cit)
3590 // Deal with the delayed characters *after* closing font tags.
3591 if (!delayedChars.empty()) {
3592 for (char_type c: delayedChars)
3594 delayedChars.clear();
3597 if (!ignore_fonts_i) {
3598 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3599 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3600 for (; sit != sen; ++sit)
3603 tagsToClose.clear();
3607 // Finally, write the next character or inset.
3608 if (Inset const * inset = getInset(i)) {
3609 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3610 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3611 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3613 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3614 // Arguments may need to be output
3615 OutputParams np = rp;
3616 np.local_font = &font;
3618 // TODO: special case will bite here.
3619 np.docbook_in_par = true;
3620 inset->docbook(*xs, np);
3623 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3624 if (lyx::isSpace(c) && !ignore_fonts)
3625 delayedChars.push_back(c);
3629 font_old = font.fontInfo();
3632 // FIXME, this code is just imported from XHTML
3633 // I'm worried about what happens if a branch, say, is itself
3634 // wrapped in some font stuff. I think that will not work.
3636 xs->closeFontTags();
3638 // Deal with the delayed characters *after* closing font tags.
3639 if (!delayedChars.empty())
3640 for (char_type c: delayedChars)
3643 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3644 // last line to get a clean output.
3645 if (rp.docbook_in_listing && !is_last_par)
3648 // Finalise the last (and most likely only) paragraph.
3649 generatedParagraphs.push_back(os.str());
3650 os.str(from_ascii(""));
3653 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3654 for (pos_type i = initial; i < size(); ++i) {
3655 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3656 const InsetArgument * arg = getInset(i)->asInsetArgument();
3657 if (arg->docbookargumentaftermaintag()) {
3658 // Don't use rp, as this argument would not generate anything.
3659 auto xs_local = XMLStream(os);
3660 arg->docbook(xs_local, runparams);
3662 appendedParagraphs.push_back(os.str());
3663 os.str(from_ascii(""));
3668 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3674 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3675 vector<xml::EndFontTag> & tagsToClose,
3676 bool & flag, FontState curstate, xml::FontTypes type)
3678 if (curstate == FONT_ON) {
3679 tagsToOpen.push_back(xhtmlStartFontTag(type));
3682 tagsToClose.push_back(xhtmlEndFontTag(type));
3687 } // anonymous namespace
3690 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3692 OutputParams const & runparams,
3693 Font const & outerfont,
3694 bool start_paragraph, bool close_paragraph,
3695 pos_type initial) const
3699 // track whether we have opened these tags
3700 bool emph_flag = false;
3701 bool bold_flag = false;
3702 bool noun_flag = false;
3703 bool ubar_flag = false;
3704 bool dbar_flag = false;
3705 bool sout_flag = false;
3706 bool xout_flag = false;
3707 bool wave_flag = false;
3709 bool shap_flag = false;
3711 bool faml_flag = false;
3713 bool size_flag = false;
3715 Layout const & style = *d->layout_;
3717 if (start_paragraph)
3718 xs.startDivision(allowEmpty());
3721 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3723 FontShape curr_fs = INHERIT_SHAPE;
3724 FontFamily curr_fam = INHERIT_FAMILY;
3725 FontSize curr_size = INHERIT_SIZE;
3727 string const default_family =
3728 buf.masterBuffer()->params().fonts_default_family;
3730 vector<xml::FontTag> tagsToOpen;
3731 vector<xml::EndFontTag> tagsToClose;
3733 // parsing main loop
3734 for (pos_type i = initial; i < size(); ++i) {
3735 // let's not show deleted material in the output
3739 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3742 FontState curstate = font.fontInfo().emph();
3743 if (font_old.emph() != curstate)
3744 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3747 curstate = font.fontInfo().noun();
3748 if (font_old.noun() != curstate)
3749 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3752 curstate = font.fontInfo().underbar();
3753 if (font_old.underbar() != curstate)
3754 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3757 curstate = font.fontInfo().strikeout();
3758 if (font_old.strikeout() != curstate)
3759 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3762 curstate = font.fontInfo().xout();
3763 if (font_old.xout() != curstate)
3764 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3767 curstate = font.fontInfo().uuline();
3768 if (font_old.uuline() != curstate)
3769 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3772 curstate = font.fontInfo().uwave();
3773 if (font_old.uwave() != curstate)
3774 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3777 // a little hackish, but allows us to reuse what we have.
3778 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3779 if (font_old.series() != font.fontInfo().series())
3780 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3783 curr_fs = font.fontInfo().shape();
3784 FontShape old_fs = font_old.shape();
3785 if (old_fs != curr_fs) {
3789 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3792 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3794 case SMALLCAPS_SHAPE:
3795 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3801 // the other tags are for internal use
3809 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3813 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3816 case SMALLCAPS_SHAPE:
3817 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3824 // the other tags are for internal use
3831 curr_fam = font.fontInfo().family();
3832 FontFamily old_fam = font_old.family();
3833 if (old_fam != curr_fam) {
3837 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3840 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3842 case TYPEWRITER_FAMILY:
3843 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3845 case INHERIT_FAMILY:
3848 // the other tags are for internal use
3856 // we will treat a "default" font family as roman, since we have
3857 // no other idea what to do.
3858 if (default_family != "rmdefault" && default_family != "default") {
3859 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3864 if (default_family != "sfdefault") {
3865 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3869 case TYPEWRITER_FAMILY:
3870 if (default_family != "ttdefault") {
3871 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3875 case INHERIT_FAMILY:
3878 // the other tags are for internal use
3885 curr_size = font.fontInfo().size();
3886 FontSize old_size = font_old.size();
3887 if (old_size != curr_size) {
3891 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3894 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3897 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3900 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3903 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3906 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3909 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3912 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3915 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3918 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3921 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3927 // the other tags are for internal use
3933 switch (curr_size) {
3935 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3939 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3943 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3947 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3951 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3955 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3959 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3963 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3967 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3971 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3975 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3982 // the other tags are for internal use
3989 // Other such tags? What about the other text ranges?
3991 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3992 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3993 for (; cit != cen; ++cit)
3996 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3997 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3998 for (; sit != sen; ++sit)
4001 tagsToClose.clear();
4004 Inset const * inset = getInset(i);
4006 if (!runparams.for_toc || inset->isInToc()) {
4007 OutputParams np = runparams;
4008 np.local_font = &font;
4009 // If the paragraph has size 1, then we are in the "special
4010 // case" where we do not output the containing paragraph info
4011 if (!inset->getLayout().htmlisblock() && size() != 1)
4012 np.html_in_par = true;
4013 retval += inset->xhtml(xs, np);
4016 char_type c = getUChar(buf.masterBuffer()->params(),
4018 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4019 xs << XMLStream::ESCAPE_NONE << " ";
4021 xs << XMLStream::ESCAPE_NONE << "’";
4025 font_old = font.fontInfo();
4029 // I'm worried about what happens if a branch, say, is itself
4030 // wrapped in some font stuff. I think that will not work.
4032 if (close_paragraph)
4039 bool Paragraph::isHfill(pos_type pos) const
4041 Inset const * inset = getInset(pos);
4042 return inset && inset->isHfill();
4046 bool Paragraph::isNewline(pos_type pos) const
4048 // U+2028 LINE SEPARATOR
4049 // U+2029 PARAGRAPH SEPARATOR
4050 char_type const c = d->text_[pos];
4051 if (c == 0x2028 || c == 0x2029)
4053 Inset const * inset = getInset(pos);
4054 return inset && inset->lyxCode() == NEWLINE_CODE;
4058 bool Paragraph::isEnvSeparator(pos_type pos) const
4060 Inset const * inset = getInset(pos);
4061 return inset && inset->lyxCode() == SEPARATOR_CODE;
4065 bool Paragraph::isLineSeparator(pos_type pos) const
4067 char_type const c = d->text_[pos];
4068 if (isLineSeparatorChar(c))
4070 Inset const * inset = getInset(pos);
4071 return inset && inset->isLineSeparator();
4075 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4079 if (ignore_deleted && isDeleted(pos))
4081 if (Inset const * inset = getInset(pos))
4082 return !inset->isLetter();
4083 // if we have a hard hyphen (no en- or emdash) or apostrophe
4084 // we pass this to the spell checker
4085 // FIXME: this method is subject to change, visit
4086 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4087 // to get an impression how complex this is.
4088 if (isHardHyphenOrApostrophe(pos))
4090 char_type const c = d->text_[pos];
4091 // We want to pass the escape chars to the spellchecker
4092 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4093 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4097 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4099 pos_type const psize = size();
4102 char_type const c = d->text_[pos];
4103 if (c != '-' && c != '\'')
4105 pos_type nextpos = pos + 1;
4106 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4107 if ((nextpos == psize || isSpace(nextpos))
4108 && (pos == 0 || isSpace(prevpos)))
4114 bool Paragraph::needsCProtection(bool const fragile) const
4116 // first check the layout of the paragraph, but only in insets
4117 InsetText const * textinset = inInset().asInsetText();
4118 bool const maintext = textinset
4119 ? textinset->text().isMainText()
4122 if (!maintext && layout().needcprotect) {
4123 // Environments need cprotection regardless the content
4124 if (layout().latextype == LATEX_ENVIRONMENT)
4127 // Commands need cprotection if they contain specific chars
4128 int const nchars_escape = 9;
4129 static char_type const chars_escape[nchars_escape] = {
4130 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4132 docstring const pars = asString();
4133 for (int k = 0; k < nchars_escape; k++) {
4134 if (contains(pars, chars_escape[k]))
4139 // now check whether we have insets that need cprotection
4140 for (auto const & icit : d->insetlist_) {
4141 Inset const * ins = icit.inset;
4144 if (ins->needsCProtection(maintext, fragile))
4152 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4154 return d->speller_state_.getRange(pos);
4158 bool Paragraph::isChar(pos_type pos) const
4160 if (Inset const * inset = getInset(pos))
4161 return inset->isChar();
4162 char_type const c = d->text_[pos];
4163 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4167 bool Paragraph::isSpace(pos_type pos) const
4169 if (Inset const * inset = getInset(pos))
4170 return inset->isSpace();
4171 char_type const c = d->text_[pos];
4172 return lyx::isSpace(c);
4177 Paragraph::getParLanguage(BufferParams const & bparams) const
4180 return getFirstFontSettings(bparams).language();
4181 // FIXME: we should check the prev par as well (Lgb)
4182 return bparams.language;
4186 bool Paragraph::isRTL(BufferParams const & bparams) const
4188 return getParLanguage(bparams)->rightToLeft()
4189 && !inInset().getLayout().forceLTR();
4193 void Paragraph::changeLanguage(BufferParams const & bparams,
4194 Language const * from, Language const * to)
4196 // change language including dummy font change at the end
4197 for (pos_type i = 0; i <= size(); ++i) {
4198 Font font = getFontSettings(bparams, i);
4199 if (font.language() == from) {
4200 font.setLanguage(to);
4202 d->requestSpellCheck(i);
4208 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4210 Language const * doc_language = bparams.language;
4211 for (auto const & f : d->fontlist_)
4212 if (f.font().language() != ignore_language &&
4213 f.font().language() != latex_language &&
4214 f.font().language() != doc_language)
4220 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4222 for (auto const & f : d->fontlist_) {
4223 Language const * lang = f.font().language();
4224 if (lang != ignore_language &&
4225 lang != latex_language)
4231 docstring Paragraph::asString(int options) const
4233 return asString(0, size(), options);
4237 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4239 odocstringstream os;
4242 && options & AS_STR_LABEL
4243 && !d->params_.labelString().empty())
4244 os << d->params_.labelString() << ' ';
4246 for (pos_type i = beg; i < end; ++i) {
4247 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4249 char_type const c = d->text_[i];
4250 if (isPrintable(c) || c == '\t'
4251 || (c == '\n' && (options & AS_STR_NEWLINES)))
4253 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4254 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4255 LASSERT(runparams != nullptr, return docstring());
4256 getInset(i)->plaintext(os, *runparams);
4257 } else if (c == META_INSET && (options & AS_STR_MATHED)
4258 && getInset(i)->lyxCode() == REF_CODE) {
4259 Buffer const & buf = getInset(i)->buffer();
4260 OutputParams rp(&buf.params().encoding());
4261 Font const font(inherit_font, buf.params().language);
4262 rp.local_font = &font;
4264 getInset(i)->latex(ots, rp);
4266 getInset(i)->toString(os);
4275 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4276 bool const shorten, bool const label) const
4278 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4279 if (label && !labelString().empty())
4280 os += labelString() + ' ';
4281 if (!layout().isTocCaption())
4283 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4286 char_type const c = d->text_[i];
4289 else if (c == META_INSET)
4290 getInset(i)->forOutliner(os, tmplen, false);
4293 Text::shortenForOutliner(os, maxlen);
4297 void Paragraph::setInsetOwner(Inset const * inset)
4299 d->inset_owner_ = inset;
4303 int Paragraph::id() const
4309 void Paragraph::setId(int id)
4315 Layout const & Paragraph::layout() const
4321 void Paragraph::setLayout(Layout const & layout)
4323 d->layout_ = &layout;
4327 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4329 setLayout(tc.defaultLayout());
4333 void Paragraph::setPlainLayout(DocumentClass const & tc)
4335 setLayout(tc.plainLayout());
4339 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4341 if (usePlainLayout())
4344 setDefaultLayout(tc);
4348 Inset const & Paragraph::inInset() const
4350 LBUFERR(d->inset_owner_);
4351 return *d->inset_owner_;
4355 ParagraphParameters & Paragraph::params()
4361 ParagraphParameters const & Paragraph::params() const
4367 bool Paragraph::isFreeSpacing() const
4369 if (d->layout_->free_spacing)
4371 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4375 bool Paragraph::allowEmpty() const
4377 if (d->layout_->keepempty)
4379 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4383 bool Paragraph::brokenBiblio() const
4385 // There is a problem if there is no bibitem at position 0 in
4386 // paragraphs that need one, if there is another bibitem in the
4387 // paragraph or if this paragraph is not supposed to have
4388 // a bibitem inset at all.
4389 return ((d->layout_->labeltype == LABEL_BIBLIO
4390 && (d->insetlist_.find(BIBITEM_CODE) != 0
4391 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4392 || (d->layout_->labeltype != LABEL_BIBLIO
4393 && d->insetlist_.find(BIBITEM_CODE) != -1));
4397 int Paragraph::fixBiblio(Buffer const & buffer)
4399 // FIXME: when there was already an inset at 0, the return value is 1,
4400 // which does not tell whether another inset has been removed; the
4401 // cursor cannot be correctly updated.
4403 bool const track_changes = buffer.params().track_changes;
4404 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4406 // The case where paragraph is not BIBLIO
4407 if (d->layout_->labeltype != LABEL_BIBLIO) {
4408 if (bibitem_pos == -1)
4409 // No InsetBibitem => OK
4411 // There is an InsetBibitem: remove it!
4412 d->insetlist_.release(bibitem_pos);
4413 eraseChar(bibitem_pos, track_changes);
4414 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4417 bool const hasbibitem0 = bibitem_pos == 0;
4419 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4420 // There was an InsetBibitem at pos 0,
4421 // and no other one => OK
4422 if (bibitem_pos == -1)
4424 // there is a bibitem at the 0 position, but since
4425 // there is a second one, we copy the second on the
4426 // first. We're assuming there are at most two of
4427 // these, which there should be.
4428 // FIXME: why does it make sense to do that rather
4429 // than keep the first? (JMarc)
4430 Inset * inset = releaseInset(bibitem_pos);
4431 d->insetlist_.begin()->inset = inset;
4432 // This needs to be done to update the counter (#8499)
4433 buffer.updateBuffer();
4434 return -bibitem_pos;
4437 // We need to create an inset at the beginning
4438 Inset * inset = nullptr;
4439 if (bibitem_pos > 0) {
4440 // there was one somewhere in the paragraph, let's move it
4441 inset = d->insetlist_.release(bibitem_pos);
4442 eraseChar(bibitem_pos, track_changes);
4445 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4446 InsetCommandParams(BIBITEM_CODE));
4448 Font font(inherit_font, buffer.params().language);
4449 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4450 : Change::UNCHANGED));
4452 // This is needed to get the counters right
4453 buffer.updateBuffer();
4458 void Paragraph::checkAuthors(AuthorList const & authorList)
4460 d->changes_.checkAuthors(authorList);
4464 bool Paragraph::isChanged(pos_type pos) const
4466 return lookupChange(pos).changed();
4470 bool Paragraph::isInserted(pos_type pos) const
4472 return lookupChange(pos).inserted();
4476 bool Paragraph::isDeleted(pos_type pos) const
4478 return lookupChange(pos).deleted();
4482 InsetList const & Paragraph::insetList() const
4484 return d->insetlist_;
4488 void Paragraph::setInsetBuffers(Buffer & b)
4490 d->insetlist_.setBuffer(b);
4494 void Paragraph::resetBuffer()
4496 d->insetlist_.resetBuffer();
4500 Inset * Paragraph::releaseInset(pos_type pos)
4502 Inset * inset = d->insetlist_.release(pos);
4503 /// does not honour change tracking!
4504 eraseChar(pos, false);
4509 Inset * Paragraph::getInset(pos_type pos)
4511 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4512 ? d->insetlist_.get(pos) : nullptr;
4516 Inset const * Paragraph::getInset(pos_type pos) const
4518 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4519 ? d->insetlist_.get(pos) : nullptr;
4523 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4524 pos_type & right, TextCase action)
4526 // process sequences of modified characters; in change
4527 // tracking mode, this approach results in much better
4528 // usability than changing case on a char-by-char basis
4529 // We also need to track the current font, since font
4530 // changes within sequences can occur.
4531 vector<pair<char_type, Font> > changes;
4533 bool const trackChanges = bparams.track_changes;
4535 bool capitalize = true;
4537 for (; pos < right; ++pos) {
4538 char_type oldChar = d->text_[pos];
4539 char_type newChar = oldChar;
4541 // ignore insets and don't play with deleted text!
4542 if (oldChar != META_INSET && !isDeleted(pos)) {
4544 case text_lowercase:
4545 newChar = lowercase(oldChar);
4547 case text_capitalization:
4549 newChar = uppercase(oldChar);
4553 case text_uppercase:
4554 newChar = uppercase(oldChar);
4559 if (isWordSeparator(pos) || isDeleted(pos)) {
4560 // permit capitalization again
4564 if (oldChar != newChar) {
4565 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4566 if (pos != right - 1)
4568 // step behind the changing area
4572 int erasePos = pos - changes.size();
4573 for (auto const & change : changes) {
4574 insertChar(pos, change.first, change.second, trackChanges);
4575 if (!eraseChar(erasePos, trackChanges)) {
4578 ++right; // expand selection
4585 int Paragraph::find(docstring const & str, bool cs, bool mw,
4586 pos_type start_pos, bool del) const
4588 pos_type pos = start_pos;
4589 int const strsize = str.length();
4591 pos_type const parsize = d->text_.size();
4592 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4593 // ignore deleted matter
4594 if (!del && isDeleted(pos)) {
4595 if (pos == parsize - 1)
4601 // Ignore "invisible" letters such as ligature breaks
4602 // and hyphenation chars while searching
4603 bool nonmatch = false;
4604 while (pos < parsize && isInset(pos)) {
4605 Inset const * inset = getInset(pos);
4606 if (!inset->isLetter() && !inset->isChar())
4608 odocstringstream os;
4609 if (inset->lyxCode() == lyx::QUOTE_CODE) {
4611 op.find_set_feature(OutputParams::SearchQuick);
4612 inset->plaintext(os, op);
4615 inset->toString(os);
4617 docstring const insetstring = os.str();
4618 if (!insetstring.empty()) {
4619 int const insetstringsize = insetstring.length();
4620 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4621 if ((cs && str[i] != insetstring[j])
4622 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4630 if (nonmatch || i == strsize)
4632 char_type dp = d->text_[pos];
4633 if (cs && str[i] != dp)
4635 if (!cs && uppercase(str[i]) != uppercase(dp))
4642 // if necessary, check whether string matches word
4644 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4647 && !isWordSeparator(pos))
4651 return pos - start_pos;
4655 char_type Paragraph::getChar(pos_type pos) const
4657 return d->text_[pos];
4661 pos_type Paragraph::size() const
4663 return d->text_.size();
4667 bool Paragraph::empty() const
4669 return d->text_.empty();
4673 bool Paragraph::isInset(pos_type pos) const
4675 return d->text_[pos] == META_INSET;
4679 bool Paragraph::isSeparator(pos_type pos) const
4681 //FIXME: Are we sure this can be the only separator?
4682 return d->text_[pos] == ' ';
4686 void Paragraph::deregisterWords()
4688 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4689 Private::LangWordsMap::const_iterator ite = d->words_.end();
4690 for (; itl != ite; ++itl) {
4691 WordList & wl = theWordList(itl->first);
4692 Private::Words::const_iterator it = (itl->second).begin();
4693 Private::Words::const_iterator et = (itl->second).end();
4694 for (; it != et; ++it)
4701 void Paragraph::locateWord(pos_type & from, pos_type & to,
4702 word_location const loc, bool const ignore_deleted) const
4705 case WHOLE_WORD_STRICT:
4706 if (from == 0 || from == size()
4707 || isWordSeparator(from, ignore_deleted)
4708 || isWordSeparator(from - 1, ignore_deleted)) {
4715 // If we are already at the beginning of a word, do nothing
4716 if (!from || isWordSeparator(from - 1, ignore_deleted))
4721 // always move the cursor to the beginning of previous word
4722 while (from && !isWordSeparator(from - 1, ignore_deleted))
4726 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4729 // no need to move the 'from' cursor
4733 while (to < size() && !isWordSeparator(to, ignore_deleted))
4738 void Paragraph::collectWords()
4740 for (pos_type pos = 0; pos < size(); ++pos) {
4741 if (isWordSeparator(pos))
4743 pos_type from = pos;
4744 locateWord(from, pos, WHOLE_WORD);
4745 // Work around MSVC warning: The statement
4746 // if (pos < from + lyxrc.completion_minlength)
4747 // triggers a signed vs. unsigned warning.
4748 // I don't know why this happens, it could be a MSVC bug, or
4749 // related to LLP64 (windows) vs. LP64 (unix) programming
4750 // model, or the C++ standard might be ambigous in the section
4751 // defining the "usual arithmetic conversions". However, using
4752 // a temporary variable is safe and works on all compilers.
4753 pos_type const endpos = from + lyxrc.completion_minlength;
4756 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4757 if (cit == d->fontlist_.end())
4759 Language const * lang = cit->font().language();
4760 docstring const word = asString(from, pos, AS_STR_NONE);
4761 d->words_[lang->lang()].insert(word);
4766 void Paragraph::registerWords()
4768 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4769 Private::LangWordsMap::const_iterator ite = d->words_.end();
4770 for (; itl != ite; ++itl) {
4771 WordList & wl = theWordList(itl->first);
4772 Private::Words::const_iterator it = (itl->second).begin();
4773 Private::Words::const_iterator et = (itl->second).end();
4774 for (; it != et; ++it)
4780 void Paragraph::updateWords()
4788 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4790 SkipPositionsIterator begin = skips.begin();
4791 SkipPositions::iterator end = skips.end();
4792 if (pos > 0 && begin < end) {
4794 if (end->last == pos - 1) {
4799 skips.insert(end, FontSpan(pos, pos));
4803 Language * Paragraph::Private::locateSpellRange(
4804 pos_type & from, pos_type & to,
4805 SkipPositions & skips) const
4807 // skip leading white space
4808 while (from < to && owner_->isWordSeparator(from))
4810 // don't check empty range
4813 // get current language
4814 Language * lang = getSpellLanguage(from);
4815 pos_type last = from;
4816 bool samelang = true;
4817 bool sameinset = true;
4818 while (last < to && samelang && sameinset) {
4819 // hop to end of word
4820 while (last < to && !owner_->isWordSeparator(last)) {
4821 Inset const * inset = owner_->getInset(last);
4822 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4823 // check for "invisible" letters such as ligature breaks
4824 odocstringstream os;
4825 inset->toString(os);
4826 if (os.str().length() != 0) {
4827 // avoid spell check of visible special char insets
4828 // stop the loop in front of the special char inset
4833 appendSkipPosition(skips, last);
4834 } else if (owner_->isDeleted(last)) {
4835 appendSkipPosition(skips, last);
4839 // hop to next word while checking for insets
4840 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4841 if (Inset const * inset = owner_->getInset(last))
4842 sameinset = inset->isChar() && inset->isLetter();
4843 if (sameinset && owner_->isDeleted(last)) {
4844 appendSkipPosition(skips, last);
4849 if (sameinset && last < to) {
4850 // now check for language change
4851 samelang = lang == getSpellLanguage(last);
4854 // if language change detected backstep is needed
4862 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4865 const_cast<Language *>(owner_->getFontSettings(
4866 inset_owner_->buffer().params(), from).language());
4867 if (lang == inset_owner_->buffer().params().language
4868 && !lyxrc.spellchecker_alt_lang.empty()) {
4870 string const lang_variety =
4871 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4872 lang->setCode(lang_code);
4873 lang->setVariety(lang_variety);
4879 void Paragraph::requestSpellCheck(pos_type pos)
4881 d->requestSpellCheck(pos);
4883 // Also request spellcheck within (text) insets
4884 for (auto const & insets : insetList()) {
4885 if (!insets.inset->asInsetText())
4887 ParagraphList & inset_pars =
4888 insets.inset->asInsetText()->paragraphs();
4889 ParagraphList::iterator pit = inset_pars.begin();
4890 ParagraphList::iterator pend = inset_pars.end();
4891 for (; pit != pend; ++pit)
4892 pit->requestSpellCheck();
4898 bool Paragraph::needsSpellCheck() const
4900 SpellChecker::ChangeNumber speller_change_number = 0;
4901 if (theSpellChecker())
4902 speller_change_number = theSpellChecker()->changeNumber();
4903 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4904 d->speller_state_.needsCompleteRefresh(speller_change_number);
4906 return d->needsSpellCheck();
4910 bool Paragraph::Private::ignoreWord(docstring const & word) const
4912 // Ignore words with digits
4913 // FIXME: make this customizable
4914 // (note that some checkers ignore words with digits by default)
4915 docstring::const_iterator cit = word.begin();
4916 docstring::const_iterator const end = word.end();
4917 for (; cit != end; ++cit) {
4918 if (isNumber((*cit)))
4925 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4926 WordLangTuple & wl, docstring_list & suggestions,
4927 bool do_suggestion, bool check_learned) const
4929 SpellChecker::Result result = SpellChecker::WORD_OK;
4930 SpellChecker * speller = theSpellChecker();
4934 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4937 locateWord(from, to, WHOLE_WORD, true);
4938 if (from == to || from >= size())
4941 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4942 Language * lang = d->getSpellLanguage(from);
4944 BufferParams const & bparams = d->inset_owner_->buffer().params();
4946 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4949 wl = WordLangTuple(word, lang);
4954 if (needsSpellCheck() || check_learned) {
4956 if (!d->ignoreWord(word)) {
4957 bool const trailing_dot = to < size() && d->text_[to] == '.';
4958 result = speller->check(wl, bparams.spellignore());
4959 if (SpellChecker::misspelled(result) && trailing_dot) {
4960 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4961 result = speller->check(wl, bparams.spellignore());
4962 if (!SpellChecker::misspelled(result)) {
4963 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4965 from << ".." << to << "]");
4967 // spell check with dot appended failed too
4968 // restore original word/lang value
4969 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4970 wl = WordLangTuple(word, lang);
4974 if (!SpellChecker::misspelled(result)) {
4975 // area up to the begin of the next word is not misspelled
4976 while (end < size() && isWordSeparator(end))
4979 d->setMisspelled(from, end, result);
4981 result = d->speller_state_.getState(from);
4985 suggestions.clear();
4987 if (SpellChecker::misspelled(result)) {
4988 LYXERR(Debug::GUI, "misspelled word: \"" <<
4990 from << ".." << to << "]");
4992 speller->suggest(wl, suggestions);
4998 void Paragraph::anonymize()
5000 // This is a very crude anonymization for now
5001 for (char_type & c : d->text_)
5002 if (isLetterChar(c) || isNumber(c))
5007 void Paragraph::Private::markMisspelledWords(
5008 Language const * lang,
5009 pos_type const & first, pos_type const & last,
5010 SpellChecker::Result result,
5011 docstring const & word,
5012 SkipPositions const & skips)
5014 if (!SpellChecker::misspelled(result)) {
5015 setMisspelled(first, last, SpellChecker::WORD_OK);
5019 SpellChecker * speller = theSpellChecker();
5020 // locate and enumerate the error positions
5021 int nerrors = speller->numMisspelledWords();
5023 SkipPositionsIterator it = skips.begin();
5024 SkipPositionsIterator et = skips.end();
5025 for (int index = 0; index < nerrors; ++index) {
5028 speller->misspelledWord(index, wstart, wlen);
5029 /// should not happen if speller supports range checks
5032 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5033 wstart += first + numskipped;
5034 if (snext < wstart) {
5035 /// mark the range of correct spelling
5036 numskipped += countSkips(it, et, wstart);
5037 setMisspelled(snext,
5038 wstart - 1, SpellChecker::WORD_OK);
5040 snext = wstart + wlen;
5041 // Check whether the candidate is in the document's local dict
5042 SpellChecker::Result actresult = result;
5043 if (inset_owner_->buffer().params().spellignored(candidate))
5044 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5045 numskipped += countSkips(it, et, snext);
5046 /// mark the range of misspelling
5047 setMisspelled(wstart, snext, actresult);
5048 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5049 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5050 candidate.word() << "\" [" <<
5051 wstart << ".." << (snext-1) << "]");
5053 LYXERR(Debug::GUI, "misspelled word: \"" <<
5054 candidate.word() << "\" [" <<
5055 wstart << ".." << (snext-1) << "]");
5058 if (snext <= last) {
5059 /// mark the range of correct spelling at end
5060 setMisspelled(snext, last, SpellChecker::WORD_OK);
5065 void Paragraph::spellCheck() const
5067 SpellChecker * speller = theSpellChecker();
5068 if (!speller || empty() ||!needsSpellCheck())
5072 d->rangeOfSpellCheck(start, endpos);
5073 if (speller->canCheckParagraph()) {
5074 // loop until we leave the range
5075 for (pos_type first = start; first < endpos; ) {
5076 pos_type last = endpos;
5077 Private::SkipPositions skips;
5078 Language * lang = d->locateSpellRange(first, last, skips);
5079 if (first >= endpos)
5081 // start the spell checker on the unit of meaning
5082 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5083 WordLangTuple wl = WordLangTuple(word, lang);
5084 BufferParams const & bparams = d->inset_owner_->buffer().params();
5085 SpellChecker::Result result = !word.empty() ?
5086 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5087 d->markMisspelledWords(lang, first, last, result, word, skips);
5091 static docstring_list suggestions;
5092 pos_type to = endpos;
5093 while (start < endpos) {
5095 spellCheck(start, to, wl, suggestions, false);
5099 d->readySpellCheck();
5103 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5105 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5106 if (result || pos <= 0 || pos > size())
5108 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5109 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5114 string Paragraph::magicLabel() const
5117 ss << "magicparlabel-" << id();