3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Kimberly Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
24 #include "BufferParams.h"
25 #include "BufferEncodings.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "output_xhtml.h"
38 #include "output_docbook.h"
39 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
42 #include "texstream.h"
45 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetArgument.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
85 /////////////////////////////////////////////////////////////////////
89 /////////////////////////////////////////////////////////////////////
91 class SpellResultRange {
93 SpellResultRange(FontSpan range, SpellChecker::Result result)
94 : range_(range), result_(result)
97 FontSpan const & range() const { return range_; }
99 void range(FontSpan const & r) { range_ = r; }
101 SpellChecker::Result result() const { return result_; }
103 void result(SpellChecker::Result r) { result_ = r; }
105 bool contains(pos_type pos) const { return range_.contains(pos); }
107 bool covered(FontSpan const & r) const
109 // 1. first of new range inside current range or
110 // 2. last of new range inside current range or
111 // 3. first of current range inside new range or
112 // 4. last of current range inside new range
113 //FIXME: is this the same as !range_.intersect(r).empty() ?
114 return range_.contains(r.first) || range_.contains(r.last) ||
115 r.contains(range_.first) || r.contains(range_.last);
118 void shift(pos_type pos, int offset)
120 if (range_.first > pos) {
121 range_.first += offset;
122 range_.last += offset;
123 } else if (range_.last >= pos) {
124 range_.last += offset;
129 SpellChecker::Result result_ ;
133 /////////////////////////////////////////////////////////////////////
137 /////////////////////////////////////////////////////////////////////
139 class SpellCheckerState {
143 needs_refresh_ = true;
144 current_change_number_ = 0;
147 void setRange(FontSpan const & fp, SpellChecker::Result state)
150 RangesIterator et = ranges_.end();
151 RangesIterator it = ranges_.begin();
152 for (; it != et; ++it) {
153 if (!it->covered(fp))
154 result.push_back(SpellResultRange(it->range(), it->result()));
155 else if (state == SpellChecker::WORD_OK) {
156 // trim or split the current misspelled range
157 // store misspelled ranges only
158 FontSpan range = it->range();
159 if (fp.first > range.first) {
160 // misspelled area in front of WORD_OK
161 range.last = fp.first - 1;
162 result.push_back(SpellResultRange(range, it->result()));
165 if (fp.last < range.last) {
166 // misspelled area after WORD_OK range
167 range.first = fp.last + 1;
168 result.push_back(SpellResultRange(range, it->result()));
173 if (state != SpellChecker::WORD_OK)
174 ranges_.push_back(SpellResultRange(fp, state));
177 void increasePosAfterPos(pos_type pos)
179 correctRangesAfterPos(pos, 1);
183 void decreasePosAfterPos(pos_type pos)
185 correctRangesAfterPos(pos, -1);
189 void refreshLast(pos_type pos)
191 if (pos < refresh_.last)
195 SpellChecker::Result getState(pos_type pos) const
197 SpellChecker::Result result = SpellChecker::WORD_OK;
198 RangesIterator et = ranges_.end();
199 RangesIterator it = ranges_.begin();
200 for (; it != et; ++it) {
201 if(it->contains(pos)) {
208 FontSpan const & getRange(pos_type pos) const
210 /// empty span to indicate mismatch
211 static FontSpan empty_;
212 RangesIterator et = ranges_.end();
213 RangesIterator it = ranges_.begin();
214 for (; it != et; ++it) {
215 if(it->contains(pos)) {
222 bool needsRefresh() const
224 return needs_refresh_;
227 SpellChecker::ChangeNumber currentChangeNumber() const
229 return current_change_number_;
232 void refreshRange(pos_type & first, pos_type & last) const
234 first = refresh_.first;
235 last = refresh_.last;
238 void needsRefresh(pos_type pos)
240 if (needs_refresh_ && pos != -1) {
241 if (pos < refresh_.first)
242 refresh_.first = pos;
243 if (pos > refresh_.last)
245 } else if (pos != -1) {
246 // init request check for neighbour positions too
247 refresh_.first = pos > 0 ? pos - 1 : 0;
248 // no need for special end of paragraph check
249 refresh_.last = pos + 1;
251 needs_refresh_ = pos != -1;
254 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
256 needs_refresh_ = true;
259 current_change_number_ = change_number;
262 typedef vector<SpellResultRange> Ranges;
263 typedef Ranges::const_iterator RangesIterator;
265 /// the area of the paragraph with pending spell check
267 /// spell state cache version number
268 SpellChecker::ChangeNumber current_change_number_;
272 void correctRangesAfterPos(pos_type pos, int offset)
274 RangesIterator et = ranges_.end();
275 Ranges::iterator it = ranges_.begin();
276 for (; it != et; ++it) {
277 it->shift(pos, offset);
283 /////////////////////////////////////////////////////////////////////
285 // Paragraph::Private
287 /////////////////////////////////////////////////////////////////////
289 class Paragraph::Private
291 // Enforce our own "copy" constructor
292 Private(Private const &) = delete;
293 Private & operator=(Private const &) = delete;
294 // Unique ID generator
295 static int make_id();
298 Private(Paragraph * owner, Layout const & layout);
299 /// "Copy constructor"
300 Private(Private const &, Paragraph * owner);
301 /// Copy constructor from \p beg to \p end
302 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
305 void insertChar(pos_type pos, char_type c, Change const & change);
307 /// Output the surrogate pair formed by \p c and \p next to \p os.
308 /// \return the number of characters written.
309 int latexSurrogatePair(BufferParams const &, otexstream & os,
310 char_type c, char_type next,
311 OutputParams const &) const;
313 /// Output a space in appropriate formatting (or a surrogate pair
314 /// if the next character is a combining character).
315 /// \return whether a surrogate pair was output.
316 bool simpleTeXBlanks(BufferParams const &,
317 OutputParams const &,
320 unsigned int & column,
322 Layout const & style) const;
324 /// This could go to ParagraphParameters if we want to.
325 int startTeXParParams(BufferParams const &, otexstream &,
326 OutputParams const &) const;
328 /// This could go to ParagraphParameters if we want to.
329 bool endTeXParParams(BufferParams const &, otexstream &,
330 OutputParams const &) const;
333 void latexInset(BufferParams const &,
338 Font const & outerfont,
340 Change & running_change,
341 Layout const & style,
343 unsigned int & column,
344 bool const fontswitch_inset,
345 bool const closeLanguage,
346 bool const lang_switched_at_inset) const;
349 void latexSpecialChar(
351 BufferParams const & bparams,
352 OutputParams const & runparams,
353 Font const & running_font,
354 string & alien_script,
355 Layout const & style,
358 unsigned int & column) const;
365 unsigned int & column) const;
371 unsigned int & column) const;
377 unsigned int & column) const;
380 void validate(LaTeXFeatures & features) const;
382 /// Checks if the paragraph contains only text and no inset or font change.
383 bool onlyText(Buffer const & buf, Font const & outerfont,
384 pos_type initial) const;
386 /// a vector of speller skip positions
387 typedef vector<FontSpan> SkipPositions;
388 typedef SkipPositions::const_iterator SkipPositionsIterator;
390 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
392 Language * getSpellLanguage(pos_type const from) const;
394 Language * locateSpellRange(pos_type & from, pos_type & to,
395 SkipPositions & skips) const;
397 bool hasSpellerChange() const
399 SpellChecker::ChangeNumber speller_change_number = 0;
400 if (theSpellChecker())
401 speller_change_number = theSpellChecker()->changeNumber();
402 return speller_change_number > speller_state_.currentChangeNumber();
405 bool ignoreWord(docstring const & word) const;
407 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
409 pos_type textsize = owner_->size();
410 // check for sane arguments
411 if (to <= from || from >= textsize)
413 FontSpan fp = FontSpan(from, to - 1);
414 speller_state_.setRange(fp, state);
417 void requestSpellCheck(pos_type pos)
420 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
422 speller_state_.needsRefresh(pos);
425 void readySpellCheck()
427 speller_state_.needsRefresh(-1);
430 bool needsSpellCheck() const
432 return speller_state_.needsRefresh();
435 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
437 speller_state_.refreshRange(first, last);
439 last = owner_->size();
442 pos_type endpos = last;
443 owner_->locateWord(first, endpos, WHOLE_WORD, true);
446 owner_->locateWord(last, endpos, WHOLE_WORD, true);
451 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
455 while (it != et && it->first < start) {
456 long skip = it->last - it->first + 1;
464 void markMisspelledWords(Language const * lang,
465 pos_type const & first, pos_type const & last,
466 SpellChecker::Result result,
467 docstring const & word,
468 SkipPositions const & skips);
470 InsetCode ownerCode() const
472 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
475 /// Which Paragraph owns us?
479 Inset const * inset_owner_;
485 ParagraphParameters params_;
487 /// for recording and looking up changes
491 InsetList insetlist_;
494 pos_type begin_of_body_;
496 typedef docstring TextContainer;
500 typedef set<docstring> Words;
501 typedef map<string, Words> LangWordsMap;
505 Layout const * layout_;
507 SpellCheckerState speller_state_;
513 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
514 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
521 int Paragraph::Private::make_id()
523 // The id is unique per session across buffers because it is used in
524 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
527 static int next_id(0);
532 Paragraph::Private::Private(Private const & p, Paragraph * owner)
533 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
534 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
535 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
536 layout_(p.layout_), id_(make_id())
538 requestSpellCheck(p.text_.size());
542 Paragraph::Private::Private(Private const & p, Paragraph * owner,
543 pos_type beg, pos_type end)
544 : owner_(owner), inset_owner_(p.inset_owner_),
545 params_(p.params_), changes_(p.changes_),
546 insetlist_(p.insetlist_, beg, end),
547 begin_of_body_(p.begin_of_body_), words_(p.words_),
548 layout_(p.layout_), id_(make_id())
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 /////////////////////////////////////////////////////////////////////
575 /////////////////////////////////////////////////////////////////////
579 /** This helper class should be instantiated at the start of methods
580 * that can create or merge changes. If as a result the value of
581 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
584 struct ChangesMonitor {
586 ChangesMonitor(Paragraph & par)
587 : par_(par), was_changed_(par.isChanged()) {}
591 /* We may need to run updateBuffer to check whether the buffer
592 * contains changes (and toggle the changes toolbar). We do it
594 * 1. the `changedness' of the paragraph has changed,
595 * 2. and we are not in the situation where the buffer has changes
596 * and new changes are added to the paragraph.
599 if (par_.isChanged() != was_changed_
600 && par_.inInset().isBufferValid()
601 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
602 par_.inInset().buffer().forceUpdate();
603 } catch(support::ExceptionMessage const &) {}
608 Paragraph const & par_;
615 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
616 bool output_active, TocBackend & backend) const
618 d->changes_.addToToc(cdit, buf, output_active, backend);
622 bool Paragraph::isDeleted(pos_type start, pos_type end) const
624 LASSERT(start >= 0 && start <= size(), return false);
625 LASSERT(end > start && end <= size() + 1, return false);
627 return d->changes_.isDeleted(start, end);
631 bool Paragraph::isChanged(pos_type start, pos_type end) const
633 LASSERT(start >= 0 && start <= size(), return false);
634 LASSERT(end > start && end <= size() + 1, return false);
636 return d->changes_.isChanged(start, end);
639 // FIXME: Ideally the diverse isChanged() methods should account for that!
640 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
642 LASSERT(start >= 0 && start <= size(), return false);
643 LASSERT(end > start && end <= size() + 1, return false);
645 for (auto const & icit : d->insetlist_) {
646 if (icit.pos < start)
650 if (icit.inset && icit.inset->isChanged())
656 bool Paragraph::isChanged() const
658 return d->changes_.isChanged();
662 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
664 // keep the logic here in sync with the logic of eraseChars()
668 Change const & change = d->changes_.lookup(size());
669 return change.inserted() && change.currentAuthor();
672 Change Paragraph::parEndChange() const
674 return d->changes_.lookup(size());
678 void Paragraph::setChange(Change const & change)
680 // Make sure that Buffer::hasChangesPresent is updated
681 ChangesMonitor cm(*this);
683 // beware of the imaginary end-of-par character!
684 d->changes_.set(change, 0, size() + 1);
687 * Propagate the change recursively - but not in case of DELETED!
689 * Imagine that your co-author makes changes in an existing inset. He
690 * sends your document to you and you come to the conclusion that the
691 * inset should go completely. If you erase it, LyX must not delete all
692 * text within the inset. Otherwise, the change tracked insertions of
693 * your co-author get lost and there is no way to restore them later.
695 * Conclusion: An inset's content should remain untouched if you delete it
698 if (!change.deleted()) {
699 for (pos_type pos = 0; pos < size(); ++pos) {
700 if (Inset * inset = getInset(pos))
701 inset->setChange(change);
707 void Paragraph::setChange(pos_type pos, Change const & change)
709 // Make sure that Buffer::hasChangesPresent is updated
710 ChangesMonitor cm(*this);
712 LASSERT(pos >= 0 && pos <= size(), return);
713 d->changes_.set(change, pos);
715 // see comment in setChange(Change const &) above
716 if (!change.deleted() && pos < size())
717 if (Inset * inset = getInset(pos))
718 inset->setChange(change);
722 Change const & Paragraph::lookupChange(pos_type pos) const
724 LBUFERR(pos >= 0 && pos <= size());
725 return d->changes_.lookup(pos);
729 void Paragraph::acceptChanges(pos_type start, pos_type end)
731 // Make sure that Buffer::hasChangesPresent is updated
732 ChangesMonitor cm(*this);
734 LASSERT(start >= 0 && start <= size(), return);
735 LASSERT(end > start && end <= size() + 1, return);
737 for (pos_type pos = start; pos < end; ++pos) {
738 switch (lookupChange(pos).type) {
739 case Change::UNCHANGED:
740 // accept changes in nested inset
741 if (Inset * inset = getInset(pos))
742 inset->acceptChanges();
745 case Change::INSERTED:
746 d->changes_.set(Change(Change::UNCHANGED), pos);
747 // also accept changes in nested inset
748 if (Inset * inset = getInset(pos))
749 inset->acceptChanges();
752 case Change::DELETED:
753 // Suppress access to non-existent
754 // "end-of-paragraph char"
756 eraseChar(pos, false);
767 void Paragraph::rejectChanges(pos_type start, pos_type end)
769 LASSERT(start >= 0 && start <= size(), return);
770 LASSERT(end > start && end <= size() + 1, return);
772 // Make sure that Buffer::hasChangesPresent is updated
773 ChangesMonitor cm(*this);
775 for (pos_type pos = start; pos < end; ++pos) {
776 switch (lookupChange(pos).type) {
777 case Change::UNCHANGED:
778 // reject changes in nested inset
779 if (Inset * inset = getInset(pos))
780 inset->rejectChanges();
783 case Change::INSERTED:
784 // Suppress access to non-existent
785 // "end-of-paragraph char"
787 eraseChar(pos, false);
793 case Change::DELETED:
794 d->changes_.set(Change(Change::UNCHANGED), pos);
796 // Do NOT reject changes within a deleted inset!
797 // There may be insertions of a co-author inside of it!
805 void Paragraph::Private::insertChar(pos_type pos, char_type c,
806 Change const & change)
808 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
810 // Make sure that Buffer::hasChangesPresent is updated
811 ChangesMonitor cm(*owner_);
814 changes_.insert(change, pos);
816 // This is actually very common when parsing buffers (and
817 // maybe inserting ascii text)
818 if (pos == pos_type(text_.size())) {
819 // when appending characters, no need to update tables
821 // but we want spell checking
822 requestSpellCheck(pos);
826 text_.insert(text_.begin() + pos, c);
828 // Update the font table.
829 fontlist_.increasePosAfterPos(pos);
832 insetlist_.increasePosAfterPos(pos);
834 // Update list of misspelled positions
835 speller_state_.increasePosAfterPos(pos);
838 if (inset_owner_ && inset_owner_->isBufferValid())
839 theSession().bookmarks().adjustPosAfterPos(inset_owner_->buffer().fileName(),
844 bool Paragraph::insertInset(pos_type pos, Inset * inset,
845 Font const & font, Change const & change)
847 LASSERT(inset, return false);
848 LASSERT(pos >= 0 && pos <= size(), return false);
850 // Make sure that Buffer::hasChangesPresent is updated
851 ChangesMonitor cm(*this);
853 // Paragraph::insertInset() can be used in cut/copy/paste operation where
854 // d->inset_owner_ is not set yet.
855 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
858 d->insertChar(pos, META_INSET, change);
859 LASSERT(d->text_[pos] == META_INSET, return false);
861 // Add a new entry in the insetlist_.
862 d->insetlist_.insert(inset, pos);
864 // Some insets require run of spell checker
865 requestSpellCheck(pos);
871 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
873 LASSERT(pos >= 0 && pos <= size(), return false);
875 // Make sure that Buffer::hasChangesPresent is updated
876 ChangesMonitor cm(*this);
878 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
881 Change change = d->changes_.lookup(pos);
883 // set the character to DELETED if
884 // a) it was previously unchanged or
885 // b) it was inserted by a co-author
887 if (!change.changed() ||
888 (change.inserted() && !change.currentAuthor())) {
889 setChange(pos, Change(Change::DELETED));
890 // request run of spell checker
891 requestSpellCheck(pos);
895 if (change.deleted())
899 // Don't physically access the imaginary end-of-paragraph character.
900 // eraseChar() can only mark it as DELETED. A physical deletion of
901 // end-of-par must be handled externally.
907 d->changes_.erase(pos);
909 // if it is an inset, delete the inset entry
910 if (d->text_[pos] == META_INSET)
911 d->insetlist_.erase(pos);
913 d->text_.erase(d->text_.begin() + pos);
915 // Update the fontlist_
916 d->fontlist_.erase(pos);
918 // Update the insetlist_
919 d->insetlist_.decreasePosAfterPos(pos);
921 // Update list of misspelled positions
922 d->speller_state_.decreasePosAfterPos(pos);
923 d->speller_state_.refreshLast(size());
926 if (d->inset_owner_ && d->inset_owner_->isBufferValid())
927 theSession().bookmarks().adjustPosAfterPos(d->inset_owner_->buffer().fileName(),
934 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
936 LASSERT(start >= 0 && start <= size(), return 0);
937 LASSERT(end >= start && end <= size() + 1, return 0);
940 for (pos_type count = end - start; count; --count) {
941 if (!eraseChar(i, trackChanges))
948 // Handle combining characters
949 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
950 otexstream & os, char_type c, char_type next,
951 OutputParams const & runparams) const
953 // Writing next here may circumvent a possible font change between
954 // c and next. Since next is only output if it forms a surrogate pair
955 // with c we can ignore this:
956 // A font change inside a surrogate pair does not make sense and is
957 // hopefully impossible to input.
958 // FIXME: change tracking
959 // Is this correct WRT change tracking?
960 Encoding const & encoding = *(runparams.encoding);
961 docstring latex1 = encoding.latexChar(next).first;
962 if (runparams.inIPA) {
963 string const tipashortcut = Encodings::TIPAShortcut(next);
964 if (!tipashortcut.empty()) {
965 latex1 = from_ascii(tipashortcut);
968 docstring latex2 = encoding.latexChar(c).first;
970 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
971 // Encoding supports the combination:
972 // output as is (combining char after base char).
973 os << latex2 << latex1;
974 return latex1.length() + latex2.length();
977 os << latex1 << "{" << latex2 << "}";
978 return latex1.length() + latex2.length() + 2;
982 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
983 OutputParams const & runparams,
986 unsigned int & column,
988 Layout const & style) const
990 if (style.pass_thru || runparams.pass_thru)
993 if (i + 1 < int(text_.size())) {
994 char_type next = text_[i + 1];
995 if (Encodings::isCombiningChar(next)) {
996 // This space has an accent, so we must always output it.
997 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
1002 if (runparams.linelen > 0
1003 && column > runparams.linelen
1005 && text_[i - 1] != ' '
1006 && (i + 1 < int(text_.size()))
1007 // same in FreeSpacing mode
1008 && !owner_->isFreeSpacing()
1009 // In typewriter mode, we want to avoid
1010 // ! . ? : at the end of a line
1011 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1012 && (text_[i - 1] == '.'
1013 || text_[i - 1] == '?'
1014 || text_[i - 1] == ':'
1015 || text_[i - 1] == '!'))) {
1017 os.texrow().start(owner_->id(), i + 1);
1019 } else if (style.free_spacing) {
1028 void Paragraph::Private::latexInset(BufferParams const & bparams,
1030 OutputParams & runparams,
1031 Font & running_font,
1033 Font const & outerfont,
1035 Change & running_change,
1036 Layout const & style,
1038 unsigned int & column,
1039 bool const fontswitch_inset,
1040 bool const closeLanguage,
1041 bool const lang_switched_at_inset) const
1043 Inset * inset = owner_->getInset(i);
1046 if (style.pass_thru) {
1047 odocstringstream ods;
1048 inset->plaintext(ods, runparams);
1053 // FIXME: move this to InsetNewline::latex
1054 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1055 // newlines are handled differently here than
1056 // the default in simpleTeXSpecialChars().
1057 if (!style.newline_allowed) {
1061 bool needPar = false;
1062 column += running_font.latexWriteEndChanges(
1063 os, bparams, runparams,
1064 basefont, basefont, needPar);
1068 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1071 basefont = owner_->getLayoutFont(bparams, outerfont);
1072 running_font = basefont;
1074 if (runparams.moving_arg)
1078 os.texrow().start(owner_->id(), i + 1);
1082 if (owner_->isDeleted(i)) {
1083 if( ++runparams.inDeletedInset == 1)
1084 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1087 if (inset->canTrackChanges()) {
1088 column += Changes::latexMarkChange(os, bparams, running_change,
1089 Change(Change::UNCHANGED), runparams);
1090 running_change = Change(Change::UNCHANGED);
1094 odocstream::pos_type const len = os.os().tellp();
1096 if (inset->forceLTR(runparams)
1097 && running_font.isRightToLeft()
1098 // ERT is an exception, it should be output with no
1099 // decorations at all
1100 && inset->lyxCode() != ERT_CODE) {
1101 if (runparams.use_polyglossia) {
1103 } else if (running_font.language()->lang() == "farsi"
1104 || running_font.language()->lang() == "arabic_arabi")
1105 os << "\\textLR{" << termcmd;
1111 if (open_font && fontswitch_inset) {
1112 bool lang_closed = false;
1113 // Close language if needed
1114 if (closeLanguage && !lang_switched_at_inset) {
1115 // We need prev_font here as language changes directly at inset
1116 // will only be started inside the inset.
1117 Font const prev_font = (i > 0) ?
1118 owner_->getFont(bparams, i - 1, outerfont)
1120 Font tmpfont(basefont);
1121 tmpfont.setLanguage(prev_font.language());
1122 bool needPar = false;
1123 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1125 needPar, closeLanguage);
1127 lang_closed = count > 0;
1129 // Update the running_font, making sure, however,
1130 // to leave the language as it was.
1131 // FIXME: probably a better way to keep track of the old
1132 // language, than copying the entire font?
1133 Font const copy_font(running_font);
1134 basefont = owner_->getLayoutFont(bparams, outerfont);
1135 running_font = basefont;
1137 running_font.setLanguage(copy_font.language());
1138 OutputParams rp = runparams;
1139 rp.encoding = basefont.language()->encoding();
1140 // For these, we use switches, so they should be taken as
1141 // base inside the inset.
1142 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1143 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1144 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1145 // Now re-do font changes in a way needed here
1146 // (using switches with multi-par insets)
1147 InsetText const * textinset = inset->asInsetText();
1148 bool const cprotect = textinset
1149 ? textinset->hasCProtectContent(runparams.moving_arg)
1150 && !textinset->text().isMainText()
1151 && inset->lyxCode() != BRANCH_CODE
1153 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1159 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1163 runparams.local_font = &basefont;
1166 if (fontswitch_inset && !closeLanguage) {
1167 // The directionality has been switched at inset.
1168 // Force markup inside.
1169 runparams.local_font = &basefont;
1172 size_t const previous_row_count = os.texrow().rows();
1175 runparams.lastid = id_;
1176 runparams.lastpos = i;
1177 inset->latex(os, runparams);
1178 } catch (EncodingException & e) {
1179 // add location information and throw again.
1188 if (os.texrow().rows() > previous_row_count) {
1189 os.texrow().start(owner_->id(), i + 1);
1192 column += (unsigned int)(os.os().tellp() - len);
1195 if (owner_->isDeleted(i))
1196 --runparams.inDeletedInset;
1200 void Paragraph::Private::latexSpecialChar(otexstream & os,
1201 BufferParams const & bparams,
1202 OutputParams const & runparams,
1203 Font const & running_font,
1204 string & alien_script,
1205 Layout const & style,
1208 unsigned int & column) const
1210 char_type const c = owner_->getUChar(bparams, runparams, i);
1212 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1213 || contains(style.pass_thru_chars, c)
1214 || contains(runparams.pass_thru_chars, c)) {
1215 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1219 os << "\\braceleft ";
1221 os << "\\braceright ";
1225 else if (c != '\0') {
1226 Encoding const * const enc = runparams.encoding;
1227 if (enc && !enc->encodable(c))
1228 throw EncodingException(c);
1234 // TIPA uses its own T3 encoding
1235 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1237 // If T1 font encoding is used, use the special
1238 // characters it provides.
1239 // NOTE: Some languages reset the font encoding internally to a
1240 // non-standard font encoding. If we are using such a language,
1241 // we do not output special T1 chars.
1242 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1243 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1244 && latexSpecialT1(c, os, i, column))
1246 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1247 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1248 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1251 // Otherwise, we use what LaTeX provides us.
1254 os << "\\textbackslash" << termcmd;
1258 os << "\\textless" << termcmd;
1262 os << "\\textgreater" << termcmd;
1266 os << "\\textbar" << termcmd;
1271 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1272 (end_pos == -1 || i + 1 < end_pos) &&
1273 text_[i+1] == '-') {
1274 // Prevent "--" becoming an en dash and "---" an em dash.
1275 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1281 os << "\\textquotedbl" << termcmd;
1286 case '%': case '#': case '{':
1294 os << "\\textasciitilde" << termcmd;
1299 os << "\\textasciicircum" << termcmd;
1306 // avoid being mistaken for optional arguments
1314 // Blanks are printed before font switching.
1315 // Sure? I am not! (try nice-latex)
1316 // I am sure it's correct. LyX might be smarter
1317 // in the future, but for now, nothing wrong is
1323 // XeTeX's dash behaviour is determined via a global setting
1324 if (bparams.use_dash_ligatures
1325 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1327 // TODO #10961: && not in inset Flex Code
1328 // TODO #10961: && not in layout LyXCode
1329 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1346 Encoding const & encoding = *(runparams.encoding);
1347 char_type next = '\0';
1348 if (i + 1 < int(text_.size())) {
1349 next = text_[i + 1];
1350 if (Encodings::isCombiningChar(next)) {
1351 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1356 pair<docstring, bool> latex = encoding.latexChar(c);
1357 docstring nextlatex;
1358 bool nexttipas = false;
1359 string nexttipashortcut;
1360 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1361 nextlatex = encoding.latexChar(next).first;
1362 if (runparams.inIPA) {
1363 nexttipashortcut = Encodings::TIPAShortcut(next);
1364 nexttipas = !nexttipashortcut.empty();
1368 if (runparams.inIPA) {
1369 string const tipashortcut = Encodings::TIPAShortcut(c);
1370 if (!tipashortcut.empty()) {
1371 latex.first = from_ascii(tipashortcut);
1372 latex.second = false;
1376 // eventually close "script wrapper" command (see `Paragraph::latex`)
1377 if (!alien_script.empty()
1378 && alien_script != Encodings::isKnownScriptChar(next)) {
1379 column += latex.first.length();
1380 alien_script.clear();
1381 os << latex.first << "}";
1385 && ((!prefixIs(nextlatex, '\\')
1386 && !prefixIs(nextlatex, '{')
1387 && !prefixIs(nextlatex, '}'))
1389 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1391 // Prevent eating of a following space or command corruption by
1392 // following characters
1393 if (next == ' ' || next == '\0') {
1394 column += latex.first.length() + 1;
1395 os << latex.first << "{}";
1397 column += latex.first.length();
1398 os << latex.first << " ";
1401 column += latex.first.length() - 1;
1409 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1410 pos_type i, unsigned int & column) const
1416 // In T1 encoding, these characters exist
1417 // but we should avoid ligatures
1418 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1420 os << "\\textcompwordmark" << termcmd;
1427 // soul.sty breaks with \char`\"
1428 os << "\\textquotedbl" << termcmd;
1437 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1438 pos_type i, unsigned int & column) const
1440 // TU encoding is currently on par with T1.
1441 return latexSpecialT1(c, os, i, column);
1445 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1446 pos_type /*i*/, unsigned int & column) const
1456 os << "\\textvertline" << termcmd;
1465 void Paragraph::Private::validate(LaTeXFeatures & features) const
1467 if (layout_->inpreamble && inset_owner_) {
1468 // FIXME: Using a string stream here circumvents the encoding
1469 // switching machinery of odocstream. Therefore the
1470 // output is wrong if this paragraph contains content
1471 // that needs to switch encoding.
1472 Buffer const & buf = inset_owner_->buffer();
1473 otexstringstream os;
1474 os << layout_->preamble();
1475 size_t const length = os.length();
1476 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1477 buf.getParFromID(owner_->id()).pit(), os,
1478 features.runparams(), string(), 0, -1, true);
1479 if (os.length() > length)
1480 features.addPreambleSnippet(os.release(), true);
1483 if (features.runparams().flavor == Flavor::Html
1484 && layout_->htmltitle()) {
1485 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1488 // check the params.
1489 if (!params_.spacing().isDefault())
1490 features.require("setspace");
1493 features.useLayout(layout_->name());
1496 fontlist_.validate(features);
1498 // then the indentation
1499 if (!params_.leftIndent().zero())
1500 features.require("ParagraphLeftIndent");
1503 InsetList::const_iterator icit = insetlist_.begin();
1504 InsetList::const_iterator iend = insetlist_.end();
1505 for (; icit != iend; ++icit) {
1507 features.inDeletedInset(owner_->isDeleted(icit->pos));
1508 if (icit->inset->lyxCode() == FOOT_CODE) {
1509 // FIXME: an item inset would make things much easier.
1510 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1511 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1512 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1513 && (icit->pos < begin_of_body_
1514 || (icit->pos == begin_of_body_
1515 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1516 features.saveNoteEnv("description");
1518 icit->inset->validate(features);
1519 features.inDeletedInset(false);
1520 if (layout_->needprotect &&
1521 icit->inset->lyxCode() == FOOT_CODE)
1522 features.require("NeedLyXFootnoteCode");
1526 // then the contents
1527 BufferParams const bp = features.runparams().is_child
1528 ? features.buffer().masterParams() : features.buffer().params();
1529 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1530 char_type c = text_[i];
1531 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1533 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1534 features.require("textquotedblp");
1535 else if (features.runparams().main_fontenc != "T1"
1536 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1537 features.require("textquotedbl");
1538 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1539 // features that depend on the font or input encoding
1540 string feats = ci.textpreamble();
1541 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1542 if (fontenc.empty())
1543 fontenc = features.runparams().main_fontenc;
1544 while (!feats.empty()) {
1546 feats = split(feats, feat, ',');
1547 if (contains(feat, "!=")) {
1548 // a feature that is required except for the spcified
1549 // font or input encodings
1551 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1552 // multiple encodings are separated by semicolon
1553 vector<string> context = getVectorFromString(contexts, ";");
1554 // require feature if the context matches neither current font
1555 // nor input encoding
1556 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1557 && std::find(context.begin(), context.end(),
1558 features.runparams().encoding->name()) == context.end())
1559 features.require(realfeature);
1560 } else if (contains(feat, '=')) {
1561 // a feature that is required only for the spcified
1562 // font or input encodings
1564 string const contexts = split(feat, realfeature, '=');
1565 // multiple encodings are separated by semicolon
1566 vector<string> context = getVectorFromString(contexts, ";");
1567 // require feature if the context matches either current font
1568 // or input encoding
1569 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1570 || std::find(context.begin(), context.end(),
1571 features.runparams().encoding->name()) != context.end())
1572 features.require(realfeature);
1575 } else if (!bp.use_dash_ligatures
1576 && (c == 0x2013 || c == 0x2014)
1577 && bp.useNonTeXFonts
1578 && features.runparams().flavor == Flavor::XeTeX)
1579 // XeTeX's dash behaviour is determined via a global setting
1580 features.require("xetexdashbreakstate");
1581 BufferEncodings::validate(c, features);
1585 /////////////////////////////////////////////////////////////////////
1589 /////////////////////////////////////////////////////////////////////
1592 Layout const emptyParagraphLayout;
1595 Paragraph::Paragraph()
1596 : d(new Paragraph::Private(this, emptyParagraphLayout))
1603 Paragraph::Paragraph(Paragraph const & par)
1604 : itemdepth(par.itemdepth),
1605 d(new Paragraph::Private(*par.d, this))
1611 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1612 : itemdepth(par.itemdepth),
1613 d(new Paragraph::Private(*par.d, this, beg, end))
1619 Paragraph & Paragraph::operator=(Paragraph const & par)
1621 // needed as we will destroy the private part before copying it
1623 itemdepth = par.itemdepth;
1627 d = new Private(*par.d, this);
1634 Paragraph::~Paragraph()
1643 // this shall be called just before every "os << ..." action.
1644 void flushString(ostream & os, docstring & s)
1653 void Paragraph::write(ostream & os, BufferParams const & bparams,
1654 depth_type & depth) const
1656 // The beginning or end of a deeper (i.e. nested) area?
1657 if (depth != d->params_.depth()) {
1658 if (d->params_.depth() > depth) {
1659 while (d->params_.depth() > depth) {
1660 os << "\n\\begin_deeper";
1664 while (d->params_.depth() < depth) {
1665 os << "\n\\end_deeper";
1671 // First write the layout
1672 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1674 d->params_.write(os);
1676 Font font1(inherit_font, bparams.language);
1678 Change running_change = Change(Change::UNCHANGED);
1680 // this string is used as a buffer to avoid repetitive calls
1681 // to to_utf8(), which turn out to be expensive (JMarc)
1682 docstring write_buffer;
1685 for (pos_type i = 0; i <= size(); ++i) {
1687 Change const & change = lookupChange(i);
1688 if (change != running_change)
1689 flushString(os, write_buffer);
1690 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1691 running_change = change;
1696 // Write font changes
1697 Font font2 = getFontSettings(bparams, i);
1698 if (font2 != font1) {
1699 flushString(os, write_buffer);
1700 font2.lyxWriteChanges(font1, os);
1705 char_type const c = d->text_[i];
1708 if (Inset const * inset = getInset(i)) {
1709 flushString(os, write_buffer);
1710 if (inset->directWrite()) {
1711 // international char, let it write
1712 // code directly so it's shorter in
1718 os << "\\begin_inset ";
1720 os << "\n\\end_inset\n\n";
1723 // FIXME This can be removed again once the mystery
1724 // crash has been resolved.
1729 flushString(os, write_buffer);
1730 os << "\n\\backslash\n";
1734 flushString(os, write_buffer);
1735 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1742 if ((column > 70 && c == ' ')
1744 flushString(os, write_buffer);
1748 // this check is to amend a bug. LyX sometimes
1749 // inserts '\0' this could cause problems.
1751 write_buffer.push_back(c);
1753 LYXERR0("NUL char in structure.");
1759 flushString(os, write_buffer);
1760 os << "\n\\end_layout\n";
1761 // FIXME This can be removed again once the mystery
1762 // crash has been resolved.
1767 void Paragraph::validate(LaTeXFeatures & features) const
1769 d->validate(features);
1770 bool fragile = features.runparams().moving_arg;
1771 fragile |= layout().needprotect;
1772 if (inInset().getLayout().isNeedProtect())
1774 if (needsCProtection(fragile))
1775 features.require("cprotect");
1779 void Paragraph::insert(pos_type pos, docstring const & str,
1780 Font const & font, Change const & change)
1782 for (size_t i = 0, n = str.size(); i != n ; ++i)
1783 insertChar(pos + i, str[i], font, change);
1787 void Paragraph::appendChar(char_type c, Font const & font,
1788 Change const & change)
1790 // Make sure that Buffer::hasChangesPresent is updated
1791 ChangesMonitor cm(*this);
1794 d->changes_.insert(change, d->text_.size());
1795 // when appending characters, no need to update tables
1796 d->text_.push_back(c);
1797 setFont(d->text_.size() - 1, font);
1798 d->requestSpellCheck(d->text_.size() - 1);
1802 void Paragraph::appendString(docstring const & s, Font const & font,
1803 Change const & change)
1805 // Make sure that Buffer::hasChangesPresent is updated
1806 ChangesMonitor cm(*this);
1808 pos_type end = s.size();
1809 size_t oldsize = d->text_.size();
1810 size_t newsize = oldsize + end;
1811 size_t capacity = d->text_.capacity();
1812 if (newsize >= capacity)
1813 d->text_.reserve(max(capacity + 100, newsize));
1815 // when appending characters, no need to update tables
1818 // FIXME: Optimize this!
1819 for (size_t i = oldsize; i != newsize; ++i) {
1821 d->changes_.insert(change, i);
1822 d->requestSpellCheck(i);
1824 d->fontlist_.set(oldsize, font);
1825 d->fontlist_.set(newsize - 1, font);
1829 void Paragraph::insertChar(pos_type pos, char_type c,
1832 d->insertChar(pos, c, Change(trackChanges ?
1833 Change::INSERTED : Change::UNCHANGED));
1837 void Paragraph::insertChar(pos_type pos, char_type c,
1838 Font const & font, bool trackChanges)
1840 d->insertChar(pos, c, Change(trackChanges ?
1841 Change::INSERTED : Change::UNCHANGED));
1846 void Paragraph::insertChar(pos_type pos, char_type c,
1847 Font const & font, Change const & change)
1849 d->insertChar(pos, c, change);
1854 void Paragraph::resetFonts(Font const & font)
1856 d->fontlist_.clear();
1857 d->fontlist_.set(0, font);
1858 d->fontlist_.set(d->text_.size() - 1, font);
1861 // Gets uninstantiated font setting at position.
1862 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1866 LYXERR0("pos: " << pos << " size: " << size());
1870 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1871 if (cit != d->fontlist_.end())
1874 if (pos == size() && !empty())
1875 return getFontSettings(bparams, pos - 1);
1877 // Optimisation: avoid a full font instantiation if there is no
1878 // language change from previous call.
1879 static Font previous_font;
1880 static Language const * previous_lang = nullptr;
1881 Language const * lang = getParLanguage(bparams);
1882 if (lang != previous_lang) {
1883 previous_lang = lang;
1884 previous_font = Font(inherit_font, lang);
1886 return previous_font;
1890 FontSpan Paragraph::fontSpan(pos_type pos) const
1892 LBUFERR(pos <= size());
1895 return FontSpan(pos, pos);
1898 FontList::const_iterator cit = d->fontlist_.begin();
1899 FontList::const_iterator end = d->fontlist_.end();
1900 for (; cit != end; ++cit) {
1901 if (cit->pos() >= pos) {
1902 if (pos >= beginOfBody())
1903 return FontSpan(max(start, beginOfBody()),
1906 return FontSpan(start,
1907 min(beginOfBody() - 1,
1910 start = cit->pos() + 1;
1913 // This should not happen, but if so, we take no chances.
1914 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1915 LASSERT(false, return FontSpan(pos, pos));
1919 // Gets uninstantiated font setting at position 0
1920 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1922 if (!empty() && !d->fontlist_.empty())
1923 return d->fontlist_.begin()->font();
1925 // Optimisation: avoid a full font instantiation if there is no
1926 // language change from previous call.
1927 static Font previous_font;
1928 static Language const * previous_lang = nullptr;
1929 if (bparams.language != previous_lang) {
1930 previous_lang = bparams.language;
1931 previous_font = Font(inherit_font, bparams.language);
1934 return previous_font;
1938 // Gets the fully instantiated font at a given position in a paragraph
1939 // This is basically the same function as Text::GetFont() in text2.cpp.
1940 // The difference is that this one is used for generating the LaTeX file,
1941 // and thus cosmetic "improvements" are disallowed: This has to deliver
1942 // the true picture of the buffer. (Asger)
1943 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1944 Font const & outerfont) const
1948 Font font = getFontSettings(bparams, pos);
1950 pos_type const body_pos = beginOfBody();
1951 FontInfo & fi = font.fontInfo();
1953 fi.realize(d->layout_->labelfont);
1955 fi.realize(d->layout_->font);
1957 fi.realize(outerfont.fontInfo());
1958 fi.realize(bparams.getFont().fontInfo());
1964 Font const Paragraph::getLabelFont
1965 (BufferParams const & bparams, Font const & outerfont) const
1967 FontInfo tmpfont = d->layout_->labelfont;
1968 tmpfont.realize(outerfont.fontInfo());
1969 tmpfont.realize(bparams.getFont().fontInfo());
1970 return Font(tmpfont, getParLanguage(bparams));
1974 Font const Paragraph::getLayoutFont
1975 (BufferParams const & bparams, Font const & outerfont) const
1977 FontInfo tmpfont = d->layout_->font;
1978 tmpfont.realize(outerfont.fontInfo());
1979 tmpfont.realize(bparams.getFont().fontInfo());
1980 return Font(tmpfont, getParLanguage(bparams));
1984 char_type Paragraph::getUChar(BufferParams const & bparams,
1985 OutputParams const & rp,
1988 char_type c = d->text_[pos];
1990 // Return unchanged character in LTR languages
1991 // or if we use poylglossia/bidi (XeTeX).
1992 if (rp.useBidiPackage()
1993 || !getFontSettings(bparams, pos).isRightToLeft())
1996 // Without polyglossia/bidi, we need to account for some special cases.
1997 // FIXME This needs to be audited!
1999 // * The input is as expected for all delimiters
2000 // => checked for Hebrew!
2001 // * The output matches the display in the LyX workarea
2002 // => checked for Hebrew!
2003 // * The special cases below are really necessary
2004 // => checked for Hebrew!
2005 // * In arabic_arabi, brackets are transformed to Arabic
2006 // Ornate Parentheses. Is this is really wanted?
2008 string const & lang = getFontSettings(bparams, pos).language()->lang();
2011 // 1. In the following languages, parentheses need to be reversed.
2012 // Also with polyglodia/luabidi
2013 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2015 // 2. In the following languages, brackets don't need to be reversed.
2016 bool const reversebrackets = lang != "arabic_arabtex"
2017 && lang != "arabic_arabi"
2020 // Now swap delimiters if needed.
2031 if (reversebrackets)
2035 if (reversebrackets)
2056 void Paragraph::setFont(pos_type pos, Font const & font)
2058 LASSERT(pos <= size(), return);
2060 // First, reduce font against layout/label font
2061 // Update: The setCharFont() routine in text2.cpp already
2062 // reduces font, so we don't need to do that here. (Asger)
2064 d->fontlist_.set(pos, font);
2068 void Paragraph::makeSameLayout(Paragraph const & par)
2070 d->layout_ = par.d->layout_;
2071 d->params_ = par.d->params_;
2075 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2077 if (isFreeSpacing())
2083 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2084 if (eraseChar(pos, trackChanges))
2090 return count > 0 || pos > 0;
2094 bool Paragraph::hasSameLayout(Paragraph const & par) const
2096 return par.d->layout_ == d->layout_
2097 && d->params_.sameLayout(par.d->params_);
2101 depth_type Paragraph::getDepth() const
2103 return d->params_.depth();
2107 depth_type Paragraph::getMaxDepthAfter() const
2109 if (d->layout_->isEnvironment())
2110 return d->params_.depth() + 1;
2112 return d->params_.depth();
2116 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2118 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2119 return getDefaultAlign(bparams);
2121 return d->params_.align();
2125 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2127 LyXAlignment res = layout().align;
2128 if (isRTL(bparams)) {
2130 if (res == LYX_ALIGN_LEFT)
2131 res = LYX_ALIGN_RIGHT;
2132 else if (res == LYX_ALIGN_RIGHT)
2133 res = LYX_ALIGN_LEFT;
2139 docstring const & Paragraph::labelString() const
2141 return d->params_.labelString();
2145 // the next two functions are for the manual labels
2146 docstring const Paragraph::getLabelWidthString() const
2148 if (d->layout_->margintype == MARGIN_MANUAL
2149 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2150 return d->params_.labelWidthString();
2152 return _("Senseless with this layout!");
2156 void Paragraph::setLabelWidthString(docstring const & s)
2158 d->params_.labelWidthString(s);
2162 docstring Paragraph::expandLabel(Layout const & layout,
2163 BufferParams const & bparams) const
2165 return expandParagraphLabel(layout, bparams, true);
2169 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2170 BufferParams const & bparams, bool process_appendix) const
2172 DocumentClass const & tclass = bparams.documentClass();
2173 string const & lang = getParLanguage(bparams)->code();
2174 bool const in_appendix = process_appendix && d->params_.appendix();
2175 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2177 if (fmt.empty() && !layout.counter.empty())
2178 return tclass.counters().theCounter(layout.counter, lang);
2180 // handle 'inherited level parts' in 'fmt',
2181 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2182 size_t const i = fmt.find('@', 0);
2183 if (i != docstring::npos) {
2184 size_t const j = fmt.find('@', i + 1);
2185 if (j != docstring::npos) {
2186 docstring parent(fmt, i + 1, j - i - 1);
2187 docstring label = from_ascii("??");
2188 if (tclass.hasLayout(parent))
2189 label = expandParagraphLabel(tclass[parent], bparams,
2191 fmt = docstring(fmt, 0, i) + label
2192 + docstring(fmt, j + 1, docstring::npos);
2196 return tclass.counters().counterLabel(fmt, lang);
2200 void Paragraph::applyLayout(Layout const & new_layout)
2202 d->layout_ = &new_layout;
2203 LyXAlignment const oldAlign = d->params_.align();
2205 if (!(oldAlign & d->layout_->alignpossible)) {
2206 frontend::Alert::warning(_("Alignment not permitted"),
2207 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2208 d->params_.align(LYX_ALIGN_LAYOUT);
2213 pos_type Paragraph::beginOfBody() const
2215 return d->begin_of_body_;
2219 void Paragraph::setBeginOfBody()
2221 if (d->layout_->labeltype != LABEL_MANUAL) {
2222 d->begin_of_body_ = 0;
2226 // Unroll the first two cycles of the loop
2227 // and remember the previous character to
2228 // remove unnecessary getChar() calls
2230 pos_type end = size();
2231 bool prev_char_deleted = false;
2232 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2235 char_type previous_char = d->text_[i];
2236 if (!(isNewline(i) || isEnvSeparator(i))) {
2238 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2239 char_type temp = d->text_[i];
2240 prev_char_deleted = isDeleted(i);
2241 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2244 previous_char = temp;
2250 d->begin_of_body_ = i;
2254 bool Paragraph::allowParagraphCustomization() const
2256 return inInset().allowParagraphCustomization();
2260 bool Paragraph::usePlainLayout() const
2262 return inInset().usePlainLayout();
2266 bool Paragraph::isPassThru() const
2268 return inInset().isPassThru() || d->layout_->pass_thru;
2272 bool Paragraph::parbreakIsNewline() const
2274 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2278 bool Paragraph::isPartOfTextSequence() const
2280 for (pos_type i = 0; i < size(); ++i) {
2281 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2289 // paragraphs inside floats need different alignment tags to avoid
2292 bool noTrivlistCentering(InsetCode code)
2294 return code == FLOAT_CODE
2295 || code == WRAP_CODE
2296 || code == CELL_CODE;
2300 string correction(string const & orig)
2302 if (orig == "flushleft")
2303 return "raggedright";
2304 if (orig == "flushright")
2305 return "raggedleft";
2306 if (orig == "center")
2312 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2313 InsetCode code, bool const lastpar, int & col)
2315 string macro = suffix + "{";
2316 if (noTrivlistCentering(code)) {
2318 // the last paragraph in non-trivlist-aligned
2319 // context is special (to avoid unwanted whitespace)
2320 if (suffix == "\\begin") {
2321 macro = "\\" + correction(env) + "{}";
2322 os << from_ascii(macro);
2323 col += macro.size();
2328 macro += correction(env);
2332 if (suffix == "\\par\\end") {
2336 os << from_ascii(macro);
2337 col += macro.size();
2338 if (suffix == "\\begin") {
2348 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2349 otexstream & os, OutputParams const & runparams) const
2354 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2355 (layout_->toggle_indent != ITOGGLE_NEVER) :
2356 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2358 LyXAlignment const curAlign = params_.align();
2360 // Do not output \\noindent for paragraphs
2361 // 1. that cannot have indentation or are indented always,
2362 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2363 // 3. that are PassThru,
2364 // 4. or that are centered.
2365 if (canindent && params_.noindent()
2366 && owner_->isPartOfTextSequence()
2367 && !layout_->pass_thru
2368 && curAlign != LYX_ALIGN_CENTER) {
2369 if (!owner_->empty()
2370 && (owner_->isInset(0)
2371 && owner_->getInset(0)->lyxCode() == VSPACE_CODE))
2372 // If the paragraph starts with a vspace, the \\noindent
2373 // needs to come after that (as it leaves vmode).
2374 // If the paragraph consists only of the vspace,
2375 // \\noindent is not needed at all.
2376 runparams.need_noindent = owner_->size() > 1;
2378 os << "\\noindent" << termcmd;
2383 if (curAlign == layout_->align)
2387 case LYX_ALIGN_NONE:
2388 case LYX_ALIGN_BLOCK:
2389 case LYX_ALIGN_LAYOUT:
2390 case LYX_ALIGN_SPECIAL:
2391 case LYX_ALIGN_DECIMAL:
2393 case LYX_ALIGN_LEFT:
2394 case LYX_ALIGN_RIGHT:
2395 case LYX_ALIGN_CENTER:
2396 if (runparams.moving_arg) {
2403 string const begin_tag = "\\begin";
2404 InsetCode code = ownerCode();
2405 bool const lastpar = runparams.isLastPar;
2406 // RTL in classic (PDF)LaTeX (without the Bidi package)
2407 // Luabibdi (used by LuaTeX) behaves like classic
2408 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2409 && !runparams.useBidiPackage();
2412 case LYX_ALIGN_NONE:
2413 case LYX_ALIGN_BLOCK:
2414 case LYX_ALIGN_LAYOUT:
2415 case LYX_ALIGN_SPECIAL:
2416 case LYX_ALIGN_DECIMAL:
2418 case LYX_ALIGN_LEFT: {
2420 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2421 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2423 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2425 } case LYX_ALIGN_RIGHT: {
2427 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2428 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2430 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2432 } case LYX_ALIGN_CENTER: {
2433 corrected_env(os, begin_tag, "center", code, lastpar, column);
2442 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2443 otexstream & os, OutputParams const & runparams) const
2445 LyXAlignment const curAlign = params_.align();
2447 if (curAlign == layout_->align)
2451 case LYX_ALIGN_NONE:
2452 case LYX_ALIGN_BLOCK:
2453 case LYX_ALIGN_LAYOUT:
2454 case LYX_ALIGN_SPECIAL:
2455 case LYX_ALIGN_DECIMAL:
2457 case LYX_ALIGN_LEFT:
2458 case LYX_ALIGN_RIGHT:
2459 case LYX_ALIGN_CENTER:
2460 if (runparams.moving_arg)
2465 bool output = false;
2467 string const end_tag = "\\par\\end";
2468 InsetCode code = ownerCode();
2469 bool const lastpar = runparams.isLastPar;
2470 // RTL in classic (PDF)LaTeX (without the Bidi package)
2471 // Luabibdi (used by LuaTeX) behaves like classic
2472 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2473 && !runparams.useBidiPackage();
2476 case LYX_ALIGN_NONE:
2477 case LYX_ALIGN_BLOCK:
2478 case LYX_ALIGN_LAYOUT:
2479 case LYX_ALIGN_SPECIAL:
2480 case LYX_ALIGN_DECIMAL:
2482 case LYX_ALIGN_LEFT: {
2484 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2485 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2487 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2489 } case LYX_ALIGN_RIGHT: {
2491 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2492 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2494 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2496 } case LYX_ALIGN_CENTER: {
2497 corrected_env(os, end_tag, "center", code, lastpar, col);
2502 return output || lastpar;
2506 // This one spits out the text of the paragraph
2507 void Paragraph::latex(BufferParams const & bparams,
2508 Font const & outerfont,
2510 OutputParams const & runparams,
2511 int start_pos, int end_pos, bool force) const
2513 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2515 // FIXME This check should not be needed. Perhaps issue an
2516 // error if it triggers.
2517 Layout const & style = inInset().forcePlainLayout() ?
2518 bparams.documentClass().plainLayout() : *d->layout_;
2520 if (!force && style.inpreamble)
2523 bool const allowcust = allowParagraphCustomization();
2525 // Current base font for all inherited font changes, without any
2526 // change caused by an individual character, except for the language:
2527 // It is set to the language of the first character.
2528 // As long as we are in the label, this font is the base font of the
2529 // label. Before the first body character it is set to the base font
2533 // If there is an open font-encoding changing command (script wrapper),
2534 // alien_script is set to its name
2535 string alien_script;
2538 // Maybe we have to create a optional argument.
2539 pos_type body_pos = beginOfBody();
2540 unsigned int column = 0;
2542 // If we are inside an non inheritFont() inset, the outerfont is the default font
2543 Font const real_outerfont =
2544 inInset().inheritFont() ? outerfont : Font(bparams.documentClass().defaultfont());
2547 // the optional argument is kept in curly brackets in
2548 // case it contains a ']'
2549 // This is not strictly needed, but if this is changed it
2550 // would be a file format change, and tex2lyx would need
2551 // to be adjusted, since it unconditionally removes the
2552 // braces when it parses \item.
2555 basefont = getLabelFont(bparams, real_outerfont);
2557 basefont = getLayoutFont(bparams, real_outerfont);
2560 // Which font is currently active?
2561 Font running_font(basefont);
2562 // Do we have an open font change?
2563 bool open_font = false;
2565 Change runningChange =
2566 runparams.inDeletedInset && !inInset().canTrackChanges()
2567 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2569 Encoding const * const prev_encoding = runparams.encoding;
2571 os.texrow().start(id(), 0);
2573 // if the paragraph is empty, the loop will not be entered at all
2575 // For InTitle commands, we have already opened a group
2576 // in output_latex::TeXOnePar.
2577 if (style.isCommand() && !style.intitle) {
2581 if (!style.leftdelim().empty()) {
2582 os << style.leftdelim();
2583 column += style.leftdelim().size();
2586 column += d->startTeXParParams(bparams, os, runparams);
2589 // Whether a \par can be issued for insets typeset inline with text.
2590 // Yes if greater than 0. This has to be static.
2591 THREAD_LOCAL_STATIC int parInline = 0;
2593 for (pos_type i = 0; i < size(); ++i) {
2594 // First char in paragraph or after label?
2595 if (i == body_pos) {
2598 bool needPar = false;
2599 column += running_font.latexWriteEndChanges(
2600 os, bparams, runparams,
2601 basefont, basefont, needPar);
2604 basefont = getLayoutFont(bparams, real_outerfont);
2605 running_font = basefont;
2607 column += Changes::latexMarkChange(os, bparams,
2608 runningChange, Change(Change::UNCHANGED),
2610 runningChange = Change(Change::UNCHANGED);
2612 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2615 // For InTitle commands, we have already opened a group
2616 // in output_latex::TeXOnePar.
2617 if (style.isCommand() && !style.intitle) {
2622 if (!style.leftdelim().empty()) {
2623 os << style.leftdelim();
2624 column += style.leftdelim().size();
2628 column += d->startTeXParParams(bparams, os,
2632 runparams.wasDisplayMath = runparams.inDisplayMath;
2633 runparams.inDisplayMath = false;
2634 bool deleted_display_math = false;
2635 Change const & change = runparams.inDeletedInset
2636 ? runparams.changeOfDeletedInset : lookupChange(i);
2638 char_type const c = d->text_[i];
2640 // Check whether a display math inset follows
2641 bool output_changes;
2642 if (runparams.for_searchAdv == OutputParams::NoSearch)
2643 output_changes = bparams.output_changes;
2645 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2647 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2649 runparams.ctObject = getInset(i)->getCtObject(runparams);
2651 InsetMath const * im = getInset(i)->asInsetMath();
2652 if (im && im->asHullInset()
2653 && im->asHullInset()->outerDisplay()) {
2654 runparams.inDisplayMath = true;
2655 // runparams.inDeletedInset will be set by
2656 // latexInset later, but we need this info
2657 // before it is called. On the other hand, we
2658 // cannot set it here because it is a counter.
2659 deleted_display_math = isDeleted(i);
2661 if (output_changes && deleted_display_math
2662 && runningChange == change
2663 && change.type == Change::DELETED
2664 && !os.afterParbreak()) {
2665 // A display math in the same paragraph follows.
2666 // We have to close and then reopen \lyxdeleted,
2667 // otherwise the math will be shifted up.
2668 OutputParams rp = runparams;
2670 bool needPar = false;
2671 column += running_font.latexWriteEndChanges(
2672 os, bparams, rp, basefont,
2676 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2677 : getLayoutFont(bparams, real_outerfont);
2678 running_font = basefont;
2679 column += Changes::latexMarkChange(os, bparams,
2680 Change(Change::INSERTED), change, rp);
2684 if (output_changes && runningChange != change) {
2685 if (!alien_script.empty()) {
2688 alien_script.clear();
2691 bool needPar = false;
2692 column += running_font.latexWriteEndChanges(
2693 os, bparams, runparams,
2694 basefont, basefont, needPar);
2697 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2698 : getLayoutFont(bparams, real_outerfont);
2699 running_font = basefont;
2700 column += Changes::latexMarkChange(os, bparams, runningChange,
2702 runningChange = change;
2705 // do not output text which is marked deleted
2706 // if change tracking output is disabled
2707 if (!output_changes && change.deleted()) {
2713 // Fully instantiated font
2714 Font current_font = getFont(bparams, i, outerfont);
2716 Font const prev_font = (i > 0) ?
2717 getFont(bparams, i - 1, outerfont)
2720 Font const last_font = running_font;
2721 bool const in_ct_deletion = (output_changes
2722 && runningChange == change
2723 && change.type == Change::DELETED
2724 && !os.afterParbreak());
2725 // Insets where font switches are used (rather than font commands)
2726 bool const fontswitch_inset =
2729 && getInset(i)->allowMultiPar()
2730 && getInset(i)->lyxCode() != ERT_CODE
2731 && (getInset(i)->producesOutput()
2732 // FIXME Something more general?
2733 // Comments do not "produce output" but are still
2734 // part of the TeX source and require font switches
2735 // to be closed (otherwise LaTeX fails).
2736 || getInset(i)->layoutName() == "Note:Comment");
2738 bool closeLanguage = false;
2739 bool lang_switched_at_inset = false;
2740 if (fontswitch_inset) {
2741 // Some insets cannot be inside a font change command.
2742 // However, even such insets *can* be placed in \L or \R
2743 // or their equivalents (for RTL language switches),
2744 // so we don't close the language in those cases
2745 // (= differing isRightToLeft()).
2746 // ArabTeX, though, doesn't seem to handle this special behavior.
2747 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2748 || basefont.language()->lang() == "arabic_arabtex"
2749 || current_font.language()->lang() == "arabic_arabtex";
2750 // We need to check prev_font as language changes directly at inset
2751 // will only be started inside the inset.
2752 lang_switched_at_inset = prev_font.language() != current_font.language();
2755 // Do we need to close the previous font?
2756 bool langClosed = false;
2758 ((current_font != running_font
2759 || current_font.language() != running_font.language())
2760 || (fontswitch_inset
2761 && (current_font == prev_font))))
2763 // ensure there is no open script-wrapper
2764 if (!alien_script.empty()) {
2767 alien_script.clear();
2769 if (in_ct_deletion) {
2770 // We have to close and then reopen \lyxdeleted,
2771 // as strikeout needs to be on lowest level.
2776 // Force language closing
2777 current_font.setLanguage(basefont.language());
2778 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2779 bool needPar = false;
2780 column += running_font.latexWriteEndChanges(
2781 os, bparams, runparams, basefont,
2783 if (in_ct_deletion) {
2784 // We have to close and then reopen \lyxdeleted,
2785 // as strikeout needs to be on lowest level.
2786 OutputParams rp = runparams;
2787 column += Changes::latexMarkChange(os, bparams,
2788 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2791 // Has the language been closed in the latexWriteEndChanges() call above?
2792 langClosed = running_font.language() != basefont.language()
2793 && running_font.language() != nextfont.language()
2794 && (running_font.language()->encoding()->package() != Encoding::CJK);
2795 running_font = basefont;
2798 // if necessary, close language environment before opening CJK
2799 string const running_lang = running_font.language()->babel();
2800 string const lang_end_command = lyxrc.language_command_end;
2801 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2802 && !running_lang.empty()
2803 && running_lang == openLanguageName()
2804 && current_font.language()->encoding()->package() == Encoding::CJK) {
2805 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2806 os << from_ascii(end_tag);
2807 column += end_tag.length();
2811 // Switch file encoding if necessary (and allowed)
2812 if ((!fontswitch_inset || closeLanguage)
2813 && !runparams.pass_thru && !style.pass_thru &&
2814 runparams.encoding->package() != Encoding::none &&
2815 current_font.language()->encoding()->package() != Encoding::none) {
2816 pair<bool, int> const enc_switch =
2817 switchEncoding(os.os(), bparams, runparams,
2818 *(current_font.language()->encoding()));
2819 if (enc_switch.first) {
2820 column += enc_switch.second;
2821 runparams.encoding = current_font.language()->encoding();
2825 // A display math inset inside an ulem command will be output
2826 // as a box of width \linewidth, so we have to either disable
2827 // indentation if the inset starts a paragraph, or start a new
2828 // line to accommodate such box. This has to be done before
2829 // writing any font changing commands.
2830 if (runparams.inDisplayMath && !deleted_display_math
2831 && runparams.inulemcmd) {
2832 if (os.afterParbreak())
2838 // Do we need to change font?
2839 if ((current_font != running_font ||
2840 current_font.language() != running_font.language())
2841 && i != body_pos - 1)
2843 if (!fontswitch_inset) {
2844 if (in_ct_deletion) {
2845 // We have to close and then reopen \lyxdeleted,
2846 // as strikeout needs to be on lowest level.
2847 OutputParams rp = runparams;
2848 bool needPar = false;
2849 column += running_font.latexWriteEndChanges(
2850 os, bparams, rp, basefont,
2855 otexstringstream ots;
2856 InsetText const * textinset = inInset().asInsetText();
2857 bool const cprotect = textinset
2858 ? textinset->hasCProtectContent(runparams.moving_arg)
2859 && !textinset->text().isMainText()
2860 && inInset().lyxCode() != BRANCH_CODE
2862 column += current_font.latexWriteStartChanges(ots, bparams,
2863 runparams, basefont, last_font, false,
2865 // Check again for display math in ulem commands as a
2866 // font change may also occur just before a math inset.
2867 if (runparams.inDisplayMath && !deleted_display_math
2868 && runparams.inulemcmd) {
2869 if (os.afterParbreak())
2874 running_font = current_font;
2876 docstring fontchange = ots.str();
2878 // check whether the fontchange ends with a \\textcolor
2879 // modifier and the text starts with a space. If so we
2880 // need to add } in order to prevent \\textcolor from gobbling
2881 // the space (bug 4473).
2882 docstring const last_modifier = rsplit(fontchange, '\\');
2883 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2884 os << from_ascii("{}");
2885 else if (ots.terminateCommand())
2887 if (in_ct_deletion) {
2888 // We have to close and then reopen \lyxdeleted,
2889 // as strikeout needs to be on lowest level.
2890 OutputParams rp = runparams;
2891 column += Changes::latexMarkChange(os, bparams,
2892 Change(Change::UNCHANGED), change, rp);
2895 running_font = current_font;
2896 open_font = !langClosed;
2900 // FIXME: think about end_pos implementation...
2901 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2902 // FIXME: integrate this case in latexSpecialChar
2903 // Do not print the separation of the optional argument
2904 // if style.pass_thru is false. This works because
2905 // latexSpecialChar ignores spaces if
2906 // style.pass_thru is false.
2907 if (i != body_pos - 1) {
2908 if (d->simpleTeXBlanks(bparams, runparams, os,
2909 i, column, current_font, style)) {
2910 // A surrogate pair was output. We
2911 // must not call latexSpecialChar
2912 // in this iteration, since it would output
2913 // the combining character again.
2920 OutputParams rp = runparams;
2921 rp.free_spacing = style.free_spacing;
2922 rp.local_font = ¤t_font;
2923 rp.intitle = style.intitle;
2925 // Two major modes: LaTeX or plain
2926 // Handle here those cases common to both modes
2927 // and then split to handle the two modes separately.
2928 if (c == META_INSET) {
2929 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2930 // Greyedout notes and, in general, all insets
2931 // with InsetLayout::isDisplay() == false,
2932 // are typeset inline with the text. So, we
2933 // can add a \par to the last paragraph of
2934 // such insets only if nothing else follows.
2935 bool incremented = false;
2936 Inset const * inset = getInset(i);
2937 InsetText const * textinset = inset
2938 ? inset->asInsetText()
2940 if (i + 1 == size() && textinset
2941 && !inset->getLayout().isDisplay()) {
2942 ParagraphList const & pars =
2943 textinset->text().paragraphs();
2944 pit_type const pit = pars.size() - 1;
2945 Font const lastfont =
2946 pit < 0 || pars[pit].empty()
2947 ? pars[pit].getLayoutFont(
2950 : pars[pit].getFont(bparams,
2951 pars[pit].size() - 1,
2953 if (lastfont.fontInfo().size() !=
2954 basefont.fontInfo().size()) {
2959 // We need to restore parts of this after insets with
2960 // allowMultiPar() true
2961 Font const save_basefont = basefont;
2962 d->latexInset(bparams, os, rp, running_font,
2963 basefont, real_outerfont, open_font,
2964 runningChange, style, i, column, fontswitch_inset,
2965 closeLanguage, lang_switched_at_inset);
2966 if (fontswitch_inset) {
2968 bool needPar = false;
2969 column += running_font.latexWriteEndChanges(
2970 os, bparams, runparams,
2971 basefont, basefont, needPar);
2974 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2975 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2976 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2981 if (runparams.ctObject == CtObject::DisplayObject
2982 || runparams.ctObject == CtObject::UDisplayObject) {
2983 // Close \lyx*deleted and force its
2984 // reopening (if needed)
2987 runningChange = Change(Change::UNCHANGED);
2988 runparams.ctObject = CtObject::Normal;
2991 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2992 if (!bparams.useNonTeXFonts)
2993 script = Encodings::isKnownScriptChar(c);
2994 if (script != alien_script) {
2995 if (!alien_script.empty()) {
2997 alien_script.clear();
2999 string fontenc = running_font.language()->fontenc(bparams);
3001 && !Encodings::fontencSupportsScript(fontenc, script)) {
3002 column += script.length() + 2;
3003 os << "\\" << script << "{";
3004 alien_script = script;
3008 d->latexSpecialChar(os, bparams, rp, running_font,
3009 alien_script, style, i, end_pos, column);
3010 } catch (EncodingException & e) {
3011 if (runparams.dryrun) {
3012 os << "<" << _("LyX Warning: ")
3013 << _("uncodable character") << " '";
3017 // add location information and throw again.
3025 // Set the encoding to that returned from latexSpecialChar (see
3026 // comment for encoding member in OutputParams.h)
3027 runparams.encoding = rp.encoding;
3029 // Also carry on the info on a closed ulem command for insets
3030 // such as Note that do not produce any output, so that no
3031 // command is ever executed but its opening was recorded.
3032 runparams.inulemcmd = rp.inulemcmd;
3034 // These need to be passed upstream as well
3035 runparams.need_maketitle = rp.need_maketitle;
3036 runparams.have_maketitle = rp.have_maketitle;
3038 // And finally, pass the post_macros upstream
3039 runparams.post_macro = rp.post_macro;
3042 // Close wrapper for alien script
3043 if (!alien_script.empty()) {
3045 alien_script.clear();
3048 Font const font = empty()
3049 ? getLayoutFont(bparams, real_outerfont)
3050 : getFont(bparams, size() - 1, real_outerfont);
3052 InsetText const * textinset = inInset().asInsetText();
3054 bool const maintext = textinset
3055 ? textinset->text().isMainText()
3058 size_t const numpars = textinset
3059 ? textinset->text().paragraphs().size()
3062 bool needPar = false;
3064 if (style.resfont.size() != font.fontInfo().size()
3065 && (!runparams.isLastPar || maintext
3066 || (numpars > 1 && d->ownerCode() != CELL_CODE
3067 && (inInset().getLayout().isDisplay()
3069 && !style.isCommand()) {
3073 // If we have an open font definition, we have to close it
3075 // Make sure that \\par is done with the font of the last
3076 // character if this has another size as the default.
3077 // This is necessary because LaTeX (and LyX on the screen)
3078 // calculates the space between the baselines according
3079 // to this font. (Matthias)
3081 // We must not change the font for the last paragraph
3082 // of non-multipar insets, tabular cells or commands,
3083 // since this produces unwanted whitespace.
3084 #ifdef FIXED_LANGUAGE_END_DETECTION
3086 running_font.latexWriteEndChanges(os, bparams,
3087 runparams, basefont,
3088 next_->getFont(bparams, 0, outerfont),
3091 running_font.latexWriteEndChanges(os, bparams,
3092 runparams, basefont, basefont, needPar);
3095 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3096 //FIXME: there as we start another \selectlanguage with the next paragraph if
3097 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3098 running_font.latexWriteEndChanges(os, bparams, runparams,
3099 basefont, basefont, needPar);
3103 // The \par could not be inserted at the same nesting
3104 // level of the font size change, so do it now.
3105 os << "{\\" << font.latexSize() << "\\par}";
3108 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3109 column += Changes::latexMarkChange(os, bparams, runningChange,
3110 Change(Change::UNCHANGED), runparams);
3112 // Needed if there is an optional argument but no contents.
3113 if (body_pos > 0 && body_pos == size()) {
3117 if (!style.rightdelim().empty()) {
3118 os << style.rightdelim();
3119 column += style.rightdelim().size();
3122 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3123 && runparams.encoding != prev_encoding) {
3124 runparams.encoding = prev_encoding;
3125 os << setEncoding(prev_encoding->iconvName());
3128 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3132 bool Paragraph::emptyTag() const
3134 for (pos_type i = 0; i < size(); ++i) {
3135 if (Inset const * inset = getInset(i)) {
3136 InsetCode lyx_code = inset->lyxCode();
3137 // FIXME testing like that is wrong. What is
3139 if (lyx_code != TOC_CODE &&
3140 lyx_code != INCLUDE_CODE &&
3141 lyx_code != GRAPHICS_CODE &&
3142 lyx_code != ERT_CODE &&
3143 lyx_code != LISTINGS_CODE &&
3144 lyx_code != FLOAT_CODE &&
3145 lyx_code != TABULAR_CODE) {
3149 char_type c = d->text_[i];
3150 if (c != ' ' && c != '\t')
3158 string Paragraph::getID(Buffer const &, OutputParams const &)
3161 for (pos_type i = 0; i < size(); ++i) {
3162 if (Inset const * inset = getInset(i)) {
3163 InsetCode lyx_code = inset->lyxCode();
3164 if (lyx_code == LABEL_CODE) {
3165 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3166 docstring const & id = il->getParam("name");
3167 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3175 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3178 for (i = 0; i < size(); ++i) {
3179 if (Inset const * inset = getInset(i)) {
3180 inset->docbook(xs, runparams);
3182 char_type c = d->text_[i];
3192 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3196 for (i = 0; i < size(); ++i) {
3197 if (Inset const * inset = getInset(i)) {
3198 inset->xhtml(xs, runparams);
3200 char_type c = d->text_[i];
3210 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3213 pos_type size = text_.size();
3214 for (pos_type i = initial; i < size; ++i) {
3215 Font font = owner_->getFont(buf.params(), i, outerfont);
3216 if (text_[i] == META_INSET)
3218 if (i != initial && font != font_old)
3229 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3230 vector<xml::EndFontTag> & tagsToClose,
3231 bool & flag, FontState curstate, xml::FontTypes type)
3233 if (curstate == FONT_ON) {
3234 tagsToOpen.push_back(docbookStartFontTag(type));
3237 tagsToClose.push_back(docbookEndFontTag(type));
3242 class OptionalFontType {
3247 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3248 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3251 OptionalFontType fontShapeToXml(FontShape fs)
3255 return {xml::FT_ITALIC};
3257 return {xml::FT_SLANTED};
3258 case SMALLCAPS_SHAPE:
3259 return {xml::FT_SMALLCAPS};
3264 // the other tags are for internal use
3270 OptionalFontType fontFamilyToXml(FontFamily fm)
3274 return {xml::FT_ROMAN};
3276 return {xml::FT_SANS};
3277 case TYPEWRITER_FAMILY:
3278 return {xml::FT_TYPE};
3279 case INHERIT_FAMILY:
3282 // the other tags are for internal use
3288 OptionalFontType fontSizeToXml(FontSize fs)
3292 return {xml::FT_SIZE_TINY};
3294 return {xml::FT_SIZE_SCRIPT};
3296 return {xml::FT_SIZE_FOOTNOTE};
3298 return {xml::FT_SIZE_SMALL};
3300 return {xml::FT_SIZE_LARGE};
3302 return {xml::FT_SIZE_LARGER};
3304 return {xml::FT_SIZE_LARGEST};
3306 return {xml::FT_SIZE_HUGE};
3308 return {xml::FT_SIZE_HUGER};
3310 return {xml::FT_SIZE_INCREASE};
3312 return {xml::FT_SIZE_DECREASE};
3317 // the other tags are for internal use
3323 struct DocBookFontState
3325 FontShape curr_fs = INHERIT_SHAPE;
3326 FontFamily curr_fam = INHERIT_FAMILY;
3327 FontSize curr_size = INHERIT_SIZE;
3329 // track whether we have opened these tags
3330 bool emph_flag = false;
3331 bool bold_flag = false;
3332 bool noun_flag = false;
3333 bool ubar_flag = false;
3334 bool dbar_flag = false;
3335 bool sout_flag = false;
3336 bool xout_flag = false;
3337 bool wave_flag = false;
3339 bool shap_flag = false;
3341 bool faml_flag = false;
3343 bool size_flag = false;
3346 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3348 std::string const & default_family,
3349 DocBookFontState & fs)
3351 vector<xml::FontTag> tagsToOpen;
3352 vector<xml::EndFontTag> tagsToClose;
3355 FontState curstate = font.fontInfo().emph();
3356 if (font_old.emph() != curstate)
3357 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3360 curstate = font.fontInfo().noun();
3361 if (font_old.noun() != curstate)
3362 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3365 curstate = font.fontInfo().underbar();
3366 if (font_old.underbar() != curstate)
3367 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3370 curstate = font.fontInfo().strikeout();
3371 if (font_old.strikeout() != curstate)
3372 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3375 curstate = font.fontInfo().xout();
3376 if (font_old.xout() != curstate)
3377 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3380 curstate = font.fontInfo().uuline();
3381 if (font_old.uuline() != curstate)
3382 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3385 curstate = font.fontInfo().uwave();
3386 if (font_old.uwave() != curstate)
3387 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3390 // a little hackish, but allows us to reuse what we have.
3391 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3392 if (font_old.series() != font.fontInfo().series())
3393 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3396 fs.curr_fs = font.fontInfo().shape();
3397 FontShape old_fs = font_old.shape();
3398 if (old_fs != fs.curr_fs) {
3400 OptionalFontType tag = fontShapeToXml(old_fs);
3402 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3403 fs.shap_flag = false;
3406 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3408 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3412 fs.curr_fam = font.fontInfo().family();
3413 FontFamily old_fam = font_old.family();
3414 if (old_fam != fs.curr_fam) {
3416 OptionalFontType tag = fontFamilyToXml(old_fam);
3418 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3419 fs.faml_flag = false;
3421 switch (fs.curr_fam) {
3423 // we will treat a "default" font family as roman, since we have
3424 // no other idea what to do.
3425 if (default_family != "rmdefault" && default_family != "default") {
3426 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3427 fs.faml_flag = true;
3431 if (default_family != "sfdefault") {
3432 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3433 fs.faml_flag = true;
3436 case TYPEWRITER_FAMILY:
3437 if (default_family != "ttdefault") {
3438 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3439 fs.faml_flag = true;
3442 case INHERIT_FAMILY:
3445 // the other tags are for internal use
3452 fs.curr_size = font.fontInfo().size();
3453 FontSize old_size = font_old.size();
3454 if (old_size != fs.curr_size) {
3456 OptionalFontType tag = fontSizeToXml(old_size);
3458 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3459 fs.size_flag = false;
3462 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3463 if (tag.has_value) {
3464 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3465 fs.size_flag = true;
3469 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3472 } // anonymous namespace
3475 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3476 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3477 OutputParams const & runparams,
3478 Font const & outerfont,
3481 bool ignore_fonts) const
3483 std::vector<docstring> prependedParagraphs;
3484 std::vector<docstring> generatedParagraphs;
3485 std::vector<docstring> appendedParagraphs;
3486 odocstringstream os;
3488 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3489 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3491 OutputParams rp = runparams;
3492 for (pos_type i = initial; i < size(); ++i) {
3493 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3494 const InsetArgument * arg = getInset(i)->asInsetArgument();
3495 if (arg->docbookargumentbeforemaintag()) {
3496 auto xs_local = XMLStream(os);
3497 arg->docbook(xs_local, rp);
3499 prependedParagraphs.push_back(os.str());
3500 os.str(from_ascii(""));
3502 rp.docbook_prepended_arguments.insert(arg);
3503 } else if (arg->docbookargumentaftermaintag()) {
3504 rp.docbook_appended_arguments.insert(arg);
3509 // State variables for the main loop.
3510 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3511 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3512 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3513 // This requires to store delayed characters at some point.
3515 DocBookFontState fs; // Track whether we have opened font tags
3516 DocBookFontState old_fs = fs;
3518 Layout const & style = *d->layout_;
3519 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3520 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3522 vector<xml::FontTag> tagsToOpen;
3523 vector<xml::EndFontTag> tagsToClose;
3525 // Parsing main loop.
3526 for (pos_type i = initial; i < size(); ++i) {
3527 bool ignore_fonts_i = ignore_fonts
3528 || style.docbooknofontinside()
3529 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3531 // Don't show deleted material in the output.
3535 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3537 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3538 if (!ignore_fonts_i)
3539 xs->closeFontTags();
3541 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3542 generatedParagraphs.push_back(os.str());
3544 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3545 // that the string stream must be reset.
3546 os.str(from_ascii(""));
3548 xs = new XMLStream(os);
3550 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3551 if (!ignore_fonts_i) {
3552 font_old = outerfont.fontInfo();
3557 // Determine which tags should be opened or closed regarding fonts.
3558 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3559 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3561 if (!ignore_fonts_i) {
3562 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3563 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3564 for (; cit != cen; ++cit)
3568 // Deal with the delayed characters *after* closing font tags.
3569 if (!delayedChars.empty()) {
3570 for (char_type c: delayedChars)
3572 delayedChars.clear();
3575 if (!ignore_fonts_i) {
3576 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3577 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3578 for (; sit != sen; ++sit)
3581 tagsToClose.clear();
3585 // Finally, write the next character or inset.
3586 if (Inset const * inset = getInset(i)) {
3587 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3588 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3589 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3591 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3592 // Arguments may need to be output
3593 OutputParams np = rp;
3594 np.local_font = &font;
3596 // TODO: special case will bite here.
3597 np.docbook_in_par = true;
3598 inset->docbook(*xs, np);
3601 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3602 if (lyx::isSpace(c) && !ignore_fonts)
3603 delayedChars.push_back(c);
3607 font_old = font.fontInfo();
3610 // FIXME, this code is just imported from XHTML
3611 // I'm worried about what happens if a branch, say, is itself
3612 // wrapped in some font stuff. I think that will not work.
3614 xs->closeFontTags();
3616 // Deal with the delayed characters *after* closing font tags.
3617 if (!delayedChars.empty())
3618 for (char_type c: delayedChars)
3621 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3622 // last line to get a clean output.
3623 if (rp.docbook_in_listing && !is_last_par)
3626 // Finalise the last (and most likely only) paragraph.
3627 generatedParagraphs.push_back(os.str());
3628 os.str(from_ascii(""));
3631 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3632 for (pos_type i = initial; i < size(); ++i) {
3633 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3634 const InsetArgument * arg = getInset(i)->asInsetArgument();
3635 if (arg->docbookargumentaftermaintag()) {
3636 // Don't use rp, as this argument would not generate anything.
3637 auto xs_local = XMLStream(os);
3638 arg->docbook(xs_local, runparams);
3640 appendedParagraphs.push_back(os.str());
3641 os.str(from_ascii(""));
3646 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3652 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3653 vector<xml::EndFontTag> & tagsToClose,
3654 bool & flag, FontState curstate, xml::FontTypes type)
3656 if (curstate == FONT_ON) {
3657 tagsToOpen.push_back(xhtmlStartFontTag(type));
3660 tagsToClose.push_back(xhtmlEndFontTag(type));
3665 } // anonymous namespace
3668 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3670 OutputParams const & runparams,
3671 Font const & outerfont,
3672 bool start_paragraph, bool close_paragraph,
3673 pos_type initial) const
3677 // track whether we have opened these tags
3678 bool emph_flag = false;
3679 bool bold_flag = false;
3680 bool noun_flag = false;
3681 bool ubar_flag = false;
3682 bool dbar_flag = false;
3683 bool sout_flag = false;
3684 bool xout_flag = false;
3685 bool wave_flag = false;
3687 bool shap_flag = false;
3689 bool faml_flag = false;
3691 bool size_flag = false;
3693 Layout const & style = *d->layout_;
3695 if (start_paragraph)
3696 xs.startDivision(allowEmpty());
3699 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3701 FontShape curr_fs = INHERIT_SHAPE;
3702 FontFamily curr_fam = INHERIT_FAMILY;
3703 FontSize curr_size = INHERIT_SIZE;
3705 string const default_family =
3706 buf.masterBuffer()->params().fonts_default_family;
3708 vector<xml::FontTag> tagsToOpen;
3709 vector<xml::EndFontTag> tagsToClose;
3711 // parsing main loop
3712 for (pos_type i = initial; i < size(); ++i) {
3713 // let's not show deleted material in the output
3717 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3720 FontState curstate = font.fontInfo().emph();
3721 if (font_old.emph() != curstate)
3722 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3725 curstate = font.fontInfo().noun();
3726 if (font_old.noun() != curstate)
3727 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3730 curstate = font.fontInfo().underbar();
3731 if (font_old.underbar() != curstate)
3732 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3735 curstate = font.fontInfo().strikeout();
3736 if (font_old.strikeout() != curstate)
3737 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3740 curstate = font.fontInfo().xout();
3741 if (font_old.xout() != curstate)
3742 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3745 curstate = font.fontInfo().uuline();
3746 if (font_old.uuline() != curstate)
3747 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3750 curstate = font.fontInfo().uwave();
3751 if (font_old.uwave() != curstate)
3752 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3755 // a little hackish, but allows us to reuse what we have.
3756 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3757 if (font_old.series() != font.fontInfo().series())
3758 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3761 curr_fs = font.fontInfo().shape();
3762 FontShape old_fs = font_old.shape();
3763 if (old_fs != curr_fs) {
3767 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3770 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3772 case SMALLCAPS_SHAPE:
3773 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3779 // the other tags are for internal use
3787 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3791 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3794 case SMALLCAPS_SHAPE:
3795 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3802 // the other tags are for internal use
3809 curr_fam = font.fontInfo().family();
3810 FontFamily old_fam = font_old.family();
3811 if (old_fam != curr_fam) {
3815 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3818 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3820 case TYPEWRITER_FAMILY:
3821 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3823 case INHERIT_FAMILY:
3826 // the other tags are for internal use
3834 // we will treat a "default" font family as roman, since we have
3835 // no other idea what to do.
3836 if (default_family != "rmdefault" && default_family != "default") {
3837 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3842 if (default_family != "sfdefault") {
3843 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3847 case TYPEWRITER_FAMILY:
3848 if (default_family != "ttdefault") {
3849 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3853 case INHERIT_FAMILY:
3856 // the other tags are for internal use
3863 curr_size = font.fontInfo().size();
3864 FontSize old_size = font_old.size();
3865 if (old_size != curr_size) {
3869 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3872 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3875 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3878 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3881 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3884 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3887 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3890 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3893 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3896 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3899 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3905 // the other tags are for internal use
3911 switch (curr_size) {
3913 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3917 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3921 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3925 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3929 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3933 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3937 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3941 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3945 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3949 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3953 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3960 // the other tags are for internal use
3967 // Other such tags? What about the other text ranges?
3969 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3970 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3971 for (; cit != cen; ++cit)
3974 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3975 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3976 for (; sit != sen; ++sit)
3979 tagsToClose.clear();
3982 Inset const * inset = getInset(i);
3984 if (!runparams.for_toc || inset->isInToc()) {
3985 OutputParams np = runparams;
3986 np.local_font = &font;
3987 // If the paragraph has size 1, then we are in the "special
3988 // case" where we do not output the containing paragraph info
3989 if (!inset->getLayout().htmlisblock() && size() != 1)
3990 np.html_in_par = true;
3991 retval += inset->xhtml(xs, np);
3994 char_type c = getUChar(buf.masterBuffer()->params(),
3996 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3997 xs << XMLStream::ESCAPE_NONE << " ";
4001 font_old = font.fontInfo();
4005 // I'm worried about what happens if a branch, say, is itself
4006 // wrapped in some font stuff. I think that will not work.
4008 if (close_paragraph)
4015 bool Paragraph::isHfill(pos_type pos) const
4017 Inset const * inset = getInset(pos);
4018 return inset && inset->isHfill();
4022 bool Paragraph::isNewline(pos_type pos) const
4024 // U+2028 LINE SEPARATOR
4025 // U+2029 PARAGRAPH SEPARATOR
4026 char_type const c = d->text_[pos];
4027 if (c == 0x2028 || c == 0x2029)
4029 Inset const * inset = getInset(pos);
4030 return inset && inset->lyxCode() == NEWLINE_CODE;
4034 bool Paragraph::isEnvSeparator(pos_type pos) const
4036 Inset const * inset = getInset(pos);
4037 return inset && inset->lyxCode() == SEPARATOR_CODE;
4041 bool Paragraph::isLineSeparator(pos_type pos) const
4043 char_type const c = d->text_[pos];
4044 if (isLineSeparatorChar(c))
4046 Inset const * inset = getInset(pos);
4047 return inset && inset->isLineSeparator();
4051 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4055 if (ignore_deleted && isDeleted(pos))
4057 if (Inset const * inset = getInset(pos))
4058 return !inset->isLetter();
4059 // if we have a hard hyphen (no en- or emdash) or apostrophe
4060 // we pass this to the spell checker
4061 // FIXME: this method is subject to change, visit
4062 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4063 // to get an impression how complex this is.
4064 if (isHardHyphenOrApostrophe(pos))
4066 char_type const c = d->text_[pos];
4067 // We want to pass the escape chars to the spellchecker
4068 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4069 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4073 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4075 pos_type const psize = size();
4078 char_type const c = d->text_[pos];
4079 if (c != '-' && c != '\'')
4081 pos_type nextpos = pos + 1;
4082 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4083 if ((nextpos == psize || isSpace(nextpos))
4084 && (pos == 0 || isSpace(prevpos)))
4090 bool Paragraph::needsCProtection(bool const fragile) const
4092 // first check the layout of the paragraph, but only in insets
4093 InsetText const * textinset = inInset().asInsetText();
4094 bool const maintext = textinset
4095 ? textinset->text().isMainText()
4098 if (!maintext && layout().needcprotect) {
4099 // Environments need cprotection regardless the content
4100 if (layout().latextype == LATEX_ENVIRONMENT)
4103 // Commands need cprotection if they contain specific chars
4104 int const nchars_escape = 9;
4105 static char_type const chars_escape[nchars_escape] = {
4106 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4108 docstring const pars = asString();
4109 for (int k = 0; k < nchars_escape; k++) {
4110 if (contains(pars, chars_escape[k]))
4115 // now check whether we have insets that need cprotection
4116 for (auto const & icit : d->insetlist_) {
4117 Inset const * ins = icit.inset;
4120 if (ins->needsCProtection(maintext, fragile))
4128 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4130 return d->speller_state_.getRange(pos);
4134 bool Paragraph::isChar(pos_type pos) const
4136 if (Inset const * inset = getInset(pos))
4137 return inset->isChar();
4138 char_type const c = d->text_[pos];
4139 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4143 bool Paragraph::isSpace(pos_type pos) const
4145 if (Inset const * inset = getInset(pos))
4146 return inset->isSpace();
4147 char_type const c = d->text_[pos];
4148 return lyx::isSpace(c);
4153 Paragraph::getParLanguage(BufferParams const & bparams) const
4156 return getFirstFontSettings(bparams).language();
4157 // FIXME: we should check the prev par as well (Lgb)
4158 return bparams.language;
4162 bool Paragraph::isRTL(BufferParams const & bparams) const
4164 return getParLanguage(bparams)->rightToLeft()
4165 && !inInset().getLayout().forceLTR();
4169 void Paragraph::changeLanguage(BufferParams const & bparams,
4170 Language const * from, Language const * to)
4172 // change language including dummy font change at the end
4173 for (pos_type i = 0; i <= size(); ++i) {
4174 Font font = getFontSettings(bparams, i);
4175 if (font.language() == from) {
4176 font.setLanguage(to);
4178 d->requestSpellCheck(i);
4184 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4186 Language const * doc_language = bparams.language;
4187 for (auto const & f : d->fontlist_)
4188 if (f.font().language() != ignore_language &&
4189 f.font().language() != latex_language &&
4190 f.font().language() != doc_language)
4196 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4198 for (auto const & f : d->fontlist_) {
4199 Language const * lang = f.font().language();
4200 if (lang != ignore_language &&
4201 lang != latex_language)
4207 docstring Paragraph::asString(int options) const
4209 return asString(0, size(), options);
4213 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4215 odocstringstream os;
4218 && options & AS_STR_LABEL
4219 && !d->params_.labelString().empty())
4220 os << d->params_.labelString() << ' ';
4222 for (pos_type i = beg; i < end; ++i) {
4223 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4225 char_type const c = d->text_[i];
4226 if (isPrintable(c) || c == '\t'
4227 || (c == '\n' && (options & AS_STR_NEWLINES)))
4229 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4230 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4231 LASSERT(runparams != nullptr, return docstring());
4232 getInset(i)->plaintext(os, *runparams);
4233 } else if (c == META_INSET && (options & AS_STR_MATHED)
4234 && getInset(i)->lyxCode() == REF_CODE) {
4235 Buffer const & buf = getInset(i)->buffer();
4236 OutputParams rp(&buf.params().encoding());
4237 Font const font(inherit_font, buf.params().language);
4238 rp.local_font = &font;
4240 getInset(i)->latex(ots, rp);
4242 getInset(i)->toString(os);
4251 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4252 bool const shorten, bool const label) const
4254 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4255 if (label && !labelString().empty())
4256 os += labelString() + ' ';
4257 if (!layout().isTocCaption())
4259 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4262 char_type const c = d->text_[i];
4265 else if (c == META_INSET)
4266 getInset(i)->forOutliner(os, tmplen, false);
4269 Text::shortenForOutliner(os, maxlen);
4273 void Paragraph::setInsetOwner(Inset const * inset)
4275 d->inset_owner_ = inset;
4279 int Paragraph::id() const
4285 void Paragraph::setId(int id)
4291 Layout const & Paragraph::layout() const
4297 void Paragraph::setLayout(Layout const & layout)
4299 d->layout_ = &layout;
4303 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4305 setLayout(tc.defaultLayout());
4309 void Paragraph::setPlainLayout(DocumentClass const & tc)
4311 setLayout(tc.plainLayout());
4315 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4317 if (usePlainLayout())
4320 setDefaultLayout(tc);
4324 Inset const & Paragraph::inInset() const
4326 LBUFERR(d->inset_owner_);
4327 return *d->inset_owner_;
4331 ParagraphParameters & Paragraph::params()
4337 ParagraphParameters const & Paragraph::params() const
4343 bool Paragraph::isFreeSpacing() const
4345 if (d->layout_->free_spacing)
4347 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4351 bool Paragraph::allowEmpty() const
4353 if (d->layout_->keepempty)
4355 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4359 bool Paragraph::brokenBiblio() const
4361 // There is a problem if there is no bibitem at position 0 in
4362 // paragraphs that need one, if there is another bibitem in the
4363 // paragraph or if this paragraph is not supposed to have
4364 // a bibitem inset at all.
4365 return ((d->layout_->labeltype == LABEL_BIBLIO
4366 && (d->insetlist_.find(BIBITEM_CODE) != 0
4367 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4368 || (d->layout_->labeltype != LABEL_BIBLIO
4369 && d->insetlist_.find(BIBITEM_CODE) != -1));
4373 int Paragraph::fixBiblio(Buffer const & buffer)
4375 // FIXME: when there was already an inset at 0, the return value is 1,
4376 // which does not tell whether another inset has been removed; the
4377 // cursor cannot be correctly updated.
4379 bool const track_changes = buffer.params().track_changes;
4380 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4382 // The case where paragraph is not BIBLIO
4383 if (d->layout_->labeltype != LABEL_BIBLIO) {
4384 if (bibitem_pos == -1)
4385 // No InsetBibitem => OK
4387 // There is an InsetBibitem: remove it!
4388 d->insetlist_.release(bibitem_pos);
4389 eraseChar(bibitem_pos, track_changes);
4390 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4393 bool const hasbibitem0 = bibitem_pos == 0;
4395 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4396 // There was an InsetBibitem at pos 0,
4397 // and no other one => OK
4398 if (bibitem_pos == -1)
4400 // there is a bibitem at the 0 position, but since
4401 // there is a second one, we copy the second on the
4402 // first. We're assuming there are at most two of
4403 // these, which there should be.
4404 // FIXME: why does it make sense to do that rather
4405 // than keep the first? (JMarc)
4406 Inset * inset = releaseInset(bibitem_pos);
4407 d->insetlist_.begin()->inset = inset;
4408 // This needs to be done to update the counter (#8499)
4409 buffer.updateBuffer();
4410 return -bibitem_pos;
4413 // We need to create an inset at the beginning
4414 Inset * inset = nullptr;
4415 if (bibitem_pos > 0) {
4416 // there was one somewhere in the paragraph, let's move it
4417 inset = d->insetlist_.release(bibitem_pos);
4418 eraseChar(bibitem_pos, track_changes);
4421 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4422 InsetCommandParams(BIBITEM_CODE));
4424 Font font(inherit_font, buffer.params().language);
4425 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4426 : Change::UNCHANGED));
4428 // This is needed to get the counters right
4429 buffer.updateBuffer();
4434 void Paragraph::checkAuthors(AuthorList const & authorList)
4436 d->changes_.checkAuthors(authorList);
4440 bool Paragraph::isChanged(pos_type pos) const
4442 return lookupChange(pos).changed();
4446 bool Paragraph::isInserted(pos_type pos) const
4448 return lookupChange(pos).inserted();
4452 bool Paragraph::isDeleted(pos_type pos) const
4454 return lookupChange(pos).deleted();
4458 InsetList const & Paragraph::insetList() const
4460 return d->insetlist_;
4464 void Paragraph::setInsetBuffers(Buffer & b)
4466 d->insetlist_.setBuffer(b);
4470 void Paragraph::resetBuffer()
4472 d->insetlist_.resetBuffer();
4476 Inset * Paragraph::releaseInset(pos_type pos)
4478 Inset * inset = d->insetlist_.release(pos);
4479 /// does not honour change tracking!
4480 eraseChar(pos, false);
4485 Inset * Paragraph::getInset(pos_type pos)
4487 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4488 ? d->insetlist_.get(pos) : nullptr;
4492 Inset const * Paragraph::getInset(pos_type pos) const
4494 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4495 ? d->insetlist_.get(pos) : nullptr;
4499 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4500 pos_type & right, TextCase action)
4502 // process sequences of modified characters; in change
4503 // tracking mode, this approach results in much better
4504 // usability than changing case on a char-by-char basis
4505 // We also need to track the current font, since font
4506 // changes within sequences can occur.
4507 vector<pair<char_type, Font> > changes;
4509 bool const trackChanges = bparams.track_changes;
4511 bool capitalize = true;
4513 for (; pos < right; ++pos) {
4514 char_type oldChar = d->text_[pos];
4515 char_type newChar = oldChar;
4517 // ignore insets and don't play with deleted text!
4518 if (oldChar != META_INSET && !isDeleted(pos)) {
4520 case text_lowercase:
4521 newChar = lowercase(oldChar);
4523 case text_capitalization:
4525 newChar = uppercase(oldChar);
4529 case text_uppercase:
4530 newChar = uppercase(oldChar);
4535 if (isWordSeparator(pos) || isDeleted(pos)) {
4536 // permit capitalization again
4540 if (oldChar != newChar) {
4541 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4542 if (pos != right - 1)
4544 // step behind the changing area
4548 int erasePos = pos - changes.size();
4549 for (auto const & change : changes) {
4550 insertChar(pos, change.first, change.second, trackChanges);
4551 if (!eraseChar(erasePos, trackChanges)) {
4554 ++right; // expand selection
4562 int Paragraph::find(docstring const & str, bool cs, bool mw,
4563 pos_type start_pos, bool del) const
4565 pos_type pos = start_pos;
4566 int const strsize = str.length();
4568 pos_type const parsize = d->text_.size();
4569 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4570 // ignore deleted matter
4571 if (!del && isDeleted(pos)) {
4572 if (pos == parsize - 1)
4578 // Ignore "invisible" letters such as ligature breaks
4579 // and hyphenation chars while searching
4580 bool nonmatch = false;
4581 while (pos < parsize && isInset(pos)) {
4582 Inset const * inset = getInset(pos);
4583 if (!inset->isLetter() && !inset->isChar())
4585 odocstringstream os;
4586 inset->toString(os);
4587 docstring const insetstring = os.str();
4588 if (!insetstring.empty()) {
4589 int const insetstringsize = insetstring.length();
4590 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4591 if ((cs && str[i] != insetstring[j])
4592 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4600 if (nonmatch || i == strsize)
4602 if (cs && str[i] != d->text_[pos])
4604 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4611 // if necessary, check whether string matches word
4613 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4616 && !isWordSeparator(pos))
4620 return pos - start_pos;
4624 char_type Paragraph::getChar(pos_type pos) const
4626 return d->text_[pos];
4630 pos_type Paragraph::size() const
4632 return d->text_.size();
4636 bool Paragraph::empty() const
4638 return d->text_.empty();
4642 bool Paragraph::isInset(pos_type pos) const
4644 return d->text_[pos] == META_INSET;
4648 bool Paragraph::isSeparator(pos_type pos) const
4650 //FIXME: Are we sure this can be the only separator?
4651 return d->text_[pos] == ' ';
4655 void Paragraph::deregisterWords()
4657 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4658 Private::LangWordsMap::const_iterator ite = d->words_.end();
4659 for (; itl != ite; ++itl) {
4660 WordList & wl = theWordList(itl->first);
4661 Private::Words::const_iterator it = (itl->second).begin();
4662 Private::Words::const_iterator et = (itl->second).end();
4663 for (; it != et; ++it)
4670 void Paragraph::locateWord(pos_type & from, pos_type & to,
4671 word_location const loc, bool const ignore_deleted) const
4674 case WHOLE_WORD_STRICT:
4675 if (from == 0 || from == size()
4676 || isWordSeparator(from, ignore_deleted)
4677 || isWordSeparator(from - 1, ignore_deleted)) {
4684 // If we are already at the beginning of a word, do nothing
4685 if (!from || isWordSeparator(from - 1, ignore_deleted))
4690 // always move the cursor to the beginning of previous word
4691 while (from && !isWordSeparator(from - 1, ignore_deleted))
4695 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4698 // no need to move the 'from' cursor
4702 while (to < size() && !isWordSeparator(to, ignore_deleted))
4707 void Paragraph::collectWords()
4709 for (pos_type pos = 0; pos < size(); ++pos) {
4710 if (isWordSeparator(pos))
4712 pos_type from = pos;
4713 locateWord(from, pos, WHOLE_WORD);
4714 // Work around MSVC warning: The statement
4715 // if (pos < from + lyxrc.completion_minlength)
4716 // triggers a signed vs. unsigned warning.
4717 // I don't know why this happens, it could be a MSVC bug, or
4718 // related to LLP64 (windows) vs. LP64 (unix) programming
4719 // model, or the C++ standard might be ambigous in the section
4720 // defining the "usual arithmetic conversions". However, using
4721 // a temporary variable is safe and works on all compilers.
4722 pos_type const endpos = from + lyxrc.completion_minlength;
4725 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4726 if (cit == d->fontlist_.end())
4728 Language const * lang = cit->font().language();
4729 docstring const word = asString(from, pos, AS_STR_NONE);
4730 d->words_[lang->lang()].insert(word);
4735 void Paragraph::registerWords()
4737 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4738 Private::LangWordsMap::const_iterator ite = d->words_.end();
4739 for (; itl != ite; ++itl) {
4740 WordList & wl = theWordList(itl->first);
4741 Private::Words::const_iterator it = (itl->second).begin();
4742 Private::Words::const_iterator et = (itl->second).end();
4743 for (; it != et; ++it)
4749 void Paragraph::updateWords()
4757 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4759 SkipPositionsIterator begin = skips.begin();
4760 SkipPositions::iterator end = skips.end();
4761 if (pos > 0 && begin < end) {
4763 if (end->last == pos - 1) {
4768 skips.insert(end, FontSpan(pos, pos));
4772 Language * Paragraph::Private::locateSpellRange(
4773 pos_type & from, pos_type & to,
4774 SkipPositions & skips) const
4776 // skip leading white space
4777 while (from < to && owner_->isWordSeparator(from))
4779 // don't check empty range
4782 // get current language
4783 Language * lang = getSpellLanguage(from);
4784 pos_type last = from;
4785 bool samelang = true;
4786 bool sameinset = true;
4787 while (last < to && samelang && sameinset) {
4788 // hop to end of word
4789 while (last < to && !owner_->isWordSeparator(last)) {
4790 Inset const * inset = owner_->getInset(last);
4791 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4792 // check for "invisible" letters such as ligature breaks
4793 odocstringstream os;
4794 inset->toString(os);
4795 if (os.str().length() != 0) {
4796 // avoid spell check of visible special char insets
4797 // stop the loop in front of the special char inset
4802 appendSkipPosition(skips, last);
4803 } else if (owner_->isDeleted(last)) {
4804 appendSkipPosition(skips, last);
4808 // hop to next word while checking for insets
4809 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4810 if (Inset const * inset = owner_->getInset(last))
4811 sameinset = inset->isChar() && inset->isLetter();
4812 if (sameinset && owner_->isDeleted(last)) {
4813 appendSkipPosition(skips, last);
4818 if (sameinset && last < to) {
4819 // now check for language change
4820 samelang = lang == getSpellLanguage(last);
4823 // if language change detected backstep is needed
4831 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4834 const_cast<Language *>(owner_->getFontSettings(
4835 inset_owner_->buffer().params(), from).language());
4836 if (lang == inset_owner_->buffer().params().language
4837 && !lyxrc.spellchecker_alt_lang.empty()) {
4839 string const lang_variety =
4840 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4841 lang->setCode(lang_code);
4842 lang->setVariety(lang_variety);
4848 void Paragraph::requestSpellCheck(pos_type pos)
4850 d->requestSpellCheck(pos);
4852 // Also request spellcheck within (text) insets
4853 for (auto const & insets : insetList()) {
4854 if (!insets.inset->asInsetText())
4856 ParagraphList & inset_pars =
4857 insets.inset->asInsetText()->paragraphs();
4858 ParagraphList::iterator pit = inset_pars.begin();
4859 ParagraphList::iterator pend = inset_pars.end();
4860 for (; pit != pend; ++pit)
4861 pit->requestSpellCheck();
4867 bool Paragraph::needsSpellCheck() const
4869 SpellChecker::ChangeNumber speller_change_number = 0;
4870 if (theSpellChecker())
4871 speller_change_number = theSpellChecker()->changeNumber();
4872 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4873 d->speller_state_.needsCompleteRefresh(speller_change_number);
4875 return d->needsSpellCheck();
4879 bool Paragraph::Private::ignoreWord(docstring const & word) const
4881 // Ignore words with digits
4882 // FIXME: make this customizable
4883 // (note that some checkers ignore words with digits by default)
4884 docstring::const_iterator cit = word.begin();
4885 docstring::const_iterator const end = word.end();
4886 for (; cit != end; ++cit) {
4887 if (isNumber((*cit)))
4894 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4895 WordLangTuple & wl, docstring_list & suggestions,
4896 bool do_suggestion, bool check_learned) const
4898 SpellChecker::Result result = SpellChecker::WORD_OK;
4899 SpellChecker * speller = theSpellChecker();
4903 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4906 locateWord(from, to, WHOLE_WORD, true);
4907 if (from == to || from >= size())
4910 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4911 Language * lang = d->getSpellLanguage(from);
4913 BufferParams const & bparams = d->inset_owner_->buffer().params();
4915 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4918 wl = WordLangTuple(word, lang);
4923 if (needsSpellCheck() || check_learned) {
4925 if (!d->ignoreWord(word)) {
4926 bool const trailing_dot = to < size() && d->text_[to] == '.';
4927 result = speller->check(wl, bparams.spellignore());
4928 if (SpellChecker::misspelled(result) && trailing_dot) {
4929 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4930 result = speller->check(wl, bparams.spellignore());
4931 if (!SpellChecker::misspelled(result)) {
4932 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4934 from << ".." << to << "]");
4936 // spell check with dot appended failed too
4937 // restore original word/lang value
4938 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4939 wl = WordLangTuple(word, lang);
4943 if (!SpellChecker::misspelled(result)) {
4944 // area up to the begin of the next word is not misspelled
4945 while (end < size() && isWordSeparator(end))
4948 d->setMisspelled(from, end, result);
4950 result = d->speller_state_.getState(from);
4954 suggestions.clear();
4956 if (SpellChecker::misspelled(result)) {
4957 LYXERR(Debug::GUI, "misspelled word: \"" <<
4959 from << ".." << to << "]");
4961 speller->suggest(wl, suggestions);
4967 void Paragraph::anonymize()
4969 // This is a very crude anonymization for now
4970 for (char_type & c : d->text_)
4971 if (isLetterChar(c) || isNumber(c))
4976 void Paragraph::Private::markMisspelledWords(
4977 Language const * lang,
4978 pos_type const & first, pos_type const & last,
4979 SpellChecker::Result result,
4980 docstring const & word,
4981 SkipPositions const & skips)
4983 if (!SpellChecker::misspelled(result)) {
4984 setMisspelled(first, last, SpellChecker::WORD_OK);
4988 SpellChecker * speller = theSpellChecker();
4989 // locate and enumerate the error positions
4990 int nerrors = speller->numMisspelledWords();
4992 SkipPositionsIterator it = skips.begin();
4993 SkipPositionsIterator et = skips.end();
4994 for (int index = 0; index < nerrors; ++index) {
4997 speller->misspelledWord(index, wstart, wlen);
4998 /// should not happen if speller supports range checks
5001 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5002 wstart += first + numskipped;
5003 if (snext < wstart) {
5004 /// mark the range of correct spelling
5005 numskipped += countSkips(it, et, wstart);
5006 setMisspelled(snext,
5007 wstart - 1, SpellChecker::WORD_OK);
5009 snext = wstart + wlen;
5010 // Check whether the candidate is in the document's local dict
5011 SpellChecker::Result actresult = result;
5012 if (inset_owner_->buffer().params().spellignored(candidate))
5013 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5014 numskipped += countSkips(it, et, snext);
5015 /// mark the range of misspelling
5016 setMisspelled(wstart, snext, actresult);
5017 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5018 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5019 candidate.word() << "\" [" <<
5020 wstart << ".." << (snext-1) << "]");
5022 LYXERR(Debug::GUI, "misspelled word: \"" <<
5023 candidate.word() << "\" [" <<
5024 wstart << ".." << (snext-1) << "]");
5027 if (snext <= last) {
5028 /// mark the range of correct spelling at end
5029 setMisspelled(snext, last, SpellChecker::WORD_OK);
5034 void Paragraph::spellCheck() const
5036 SpellChecker * speller = theSpellChecker();
5037 if (!speller || empty() ||!needsSpellCheck())
5041 d->rangeOfSpellCheck(start, endpos);
5042 if (speller->canCheckParagraph()) {
5043 // loop until we leave the range
5044 for (pos_type first = start; first < endpos; ) {
5045 pos_type last = endpos;
5046 Private::SkipPositions skips;
5047 Language * lang = d->locateSpellRange(first, last, skips);
5048 if (first >= endpos)
5050 // start the spell checker on the unit of meaning
5051 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5052 WordLangTuple wl = WordLangTuple(word, lang);
5053 BufferParams const & bparams = d->inset_owner_->buffer().params();
5054 SpellChecker::Result result = !word.empty() ?
5055 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5056 d->markMisspelledWords(lang, first, last, result, word, skips);
5060 static docstring_list suggestions;
5061 pos_type to = endpos;
5062 while (start < endpos) {
5064 spellCheck(start, to, wl, suggestions, false);
5068 d->readySpellCheck();
5072 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5074 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5075 if (result || pos <= 0 || pos > size())
5077 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5078 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5083 string Paragraph::magicLabel() const
5086 ss << "magicparlabel-" << id();