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 // babel with Xe/LuaTeX does not need a switch
1098 // and \L is not defined there.
1099 && (!runparams.isFullUnicode() || !runparams.use_babel)
1100 && running_font.isRightToLeft()
1101 // ERT is an exception, it should be output with no
1102 // decorations at all
1103 && inset->lyxCode() != ERT_CODE) {
1104 if (runparams.use_polyglossia)
1107 else if (running_font.language()->lang() == "farsi"
1108 || running_font.language()->lang() == "arabic_arabi")
1109 os << "\\textLR{" << termcmd;
1116 if (open_font && fontswitch_inset) {
1117 bool lang_closed = false;
1118 // Close language if needed
1119 if (closeLanguage && !lang_switched_at_inset) {
1120 // We need prev_font here as language changes directly at inset
1121 // will only be started inside the inset.
1122 Font const prev_font = (i > 0) ?
1123 owner_->getFont(bparams, i - 1, outerfont)
1125 Font tmpfont(basefont);
1126 tmpfont.setLanguage(prev_font.language());
1127 bool needPar = false;
1128 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1130 needPar, closeLanguage);
1132 lang_closed = count > 0;
1134 // Update the running_font, making sure, however,
1135 // to leave the language as it was.
1136 // FIXME: probably a better way to keep track of the old
1137 // language, than copying the entire font?
1138 Font const copy_font(running_font);
1139 basefont = owner_->getLayoutFont(bparams, outerfont);
1140 running_font = basefont;
1142 running_font.setLanguage(copy_font.language());
1143 OutputParams rp = runparams;
1144 rp.encoding = basefont.language()->encoding();
1145 // For these, we use switches, so they should be taken as
1146 // base inside the inset.
1147 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1148 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1149 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1150 // Now re-do font changes in a way needed here
1151 // (using switches with multi-par insets)
1152 InsetText const * textinset = inset->asInsetText();
1153 bool const cprotect = textinset
1154 ? textinset->hasCProtectContent(runparams.moving_arg)
1155 && !textinset->text().isMainText()
1156 && inset->lyxCode() != BRANCH_CODE
1158 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1164 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1168 runparams.local_font = &basefont;
1171 if (fontswitch_inset && !closeLanguage) {
1172 // The directionality has been switched at inset.
1173 // Force markup inside.
1174 runparams.local_font = &basefont;
1177 size_t const previous_row_count = os.texrow().rows();
1180 runparams.lastid = id_;
1181 runparams.lastpos = i;
1182 inset->latex(os, runparams);
1183 } catch (EncodingException & e) {
1184 // add location information and throw again.
1193 if (os.texrow().rows() > previous_row_count) {
1194 os.texrow().start(owner_->id(), i + 1);
1197 column += (unsigned int)(os.os().tellp() - len);
1200 if (owner_->isDeleted(i))
1201 --runparams.inDeletedInset;
1205 void Paragraph::Private::latexSpecialChar(otexstream & os,
1206 BufferParams const & bparams,
1207 OutputParams const & runparams,
1208 Font const & running_font,
1209 string & alien_script,
1210 Layout const & style,
1213 unsigned int & column) const
1215 char_type const c = owner_->getUChar(bparams, runparams, i);
1217 if (style.pass_thru || runparams.pass_thru || runparams.find_effective()
1218 || contains(style.pass_thru_chars, c)
1219 || contains(runparams.pass_thru_chars, c)) {
1220 if (runparams.find_effective()) {
1226 os << "\\braceleft ";
1229 os << "\\braceright ";
1232 os << "\\lyxdollar ";
1235 os << "\\lyxtilde ";
1245 else if (c != '\0') {
1246 Encoding const * const enc = runparams.encoding;
1247 if (enc && !enc->encodable(c))
1248 throw EncodingException(c);
1254 // TIPA uses its own T3 encoding
1255 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1257 // If T1 font encoding is used, use the special
1258 // characters it provides.
1259 // NOTE: Some languages reset the font encoding internally to a
1260 // non-standard font encoding. If we are using such a language,
1261 // we do not output special T1 chars.
1262 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1263 && !runparams.isFullUnicode() && runparams.main_fontenc == "T1"
1264 && latexSpecialT1(c, os, i, column))
1266 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1267 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1268 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1271 // Otherwise, we use what LaTeX provides us.
1274 os << "\\textbackslash" << termcmd;
1278 os << "\\textless" << termcmd;
1282 os << "\\textgreater" << termcmd;
1286 os << "\\textbar" << termcmd;
1291 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1292 (end_pos == -1 || i + 1 < end_pos) &&
1293 text_[i+1] == '-') {
1294 // Prevent "--" becoming an en dash and "---" an em dash.
1295 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1301 os << "\\textquotedbl" << termcmd;
1306 case '%': case '#': case '{':
1314 os << "\\textasciitilde" << termcmd;
1319 os << "\\textasciicircum" << termcmd;
1326 // avoid being mistaken for optional arguments
1334 // Blanks are printed before font switching.
1335 // Sure? I am not! (try nice-latex)
1336 // I am sure it's correct. LyX might be smarter
1337 // in the future, but for now, nothing wrong is
1343 // XeTeX's dash behaviour is determined via a global setting
1344 if (bparams.use_dash_ligatures
1345 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1347 // TODO #10961: && not in inset Flex Code
1348 // TODO #10961: && not in layout LyXCode
1349 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1366 Encoding const & encoding = *(runparams.encoding);
1367 char_type next = '\0';
1368 if (i + 1 < int(text_.size())) {
1369 next = text_[i + 1];
1370 if (Encodings::isCombiningChar(next)) {
1371 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1376 pair<docstring, bool> latex = encoding.latexChar(c);
1377 docstring nextlatex;
1378 bool nexttipas = false;
1379 string nexttipashortcut;
1380 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1381 nextlatex = encoding.latexChar(next).first;
1382 if (runparams.inIPA) {
1383 nexttipashortcut = Encodings::TIPAShortcut(next);
1384 nexttipas = !nexttipashortcut.empty();
1388 if (runparams.inIPA) {
1389 string const tipashortcut = Encodings::TIPAShortcut(c);
1390 if (!tipashortcut.empty()) {
1391 latex.first = from_ascii(tipashortcut);
1392 latex.second = false;
1396 // eventually close "script wrapper" command (see `Paragraph::latex`)
1397 if (!alien_script.empty()
1398 && alien_script != Encodings::isKnownScriptChar(next)) {
1399 column += latex.first.length();
1400 alien_script.clear();
1401 os << latex.first << "}";
1405 && ((!prefixIs(nextlatex, '\\')
1406 && !prefixIs(nextlatex, '{')
1407 && !prefixIs(nextlatex, '}'))
1409 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1411 // Prevent eating of a following space or command corruption by
1412 // following characters
1413 if (next == ' ' || next == '\0') {
1414 column += latex.first.length() + 1;
1415 os << latex.first << "{}";
1417 column += latex.first.length();
1418 os << latex.first << " ";
1421 column += latex.first.length() - 1;
1429 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1430 pos_type i, unsigned int & column) const
1436 // In T1 encoding, these characters exist
1437 // but we should avoid ligatures
1438 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1440 os << "\\textcompwordmark" << termcmd;
1447 // soul.sty breaks with \char`\"
1448 os << "\\textquotedbl" << termcmd;
1457 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1458 pos_type i, unsigned int & column) const
1460 // TU encoding is currently on par with T1.
1461 return latexSpecialT1(c, os, i, column);
1465 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1466 pos_type /*i*/, unsigned int & column) const
1476 os << "\\textvertline" << termcmd;
1485 void Paragraph::Private::validate(LaTeXFeatures & features) const
1487 if (layout_->inpreamble && inset_owner_) {
1488 // FIXME: Using a string stream here circumvents the encoding
1489 // switching machinery of odocstream. Therefore the
1490 // output is wrong if this paragraph contains content
1491 // that needs to switch encoding.
1492 Buffer const & buf = inset_owner_->buffer();
1493 otexstringstream os;
1494 os << layout_->preamble();
1495 size_t const length = os.length();
1496 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1497 buf.getParFromID(owner_->id()).pit(), os,
1498 features.runparams(), string(), 0, -1, true);
1499 if (os.length() > length)
1500 features.addPreambleSnippet(os.release(), true);
1503 if (features.runparams().flavor == Flavor::Html
1504 && layout_->htmltitle()) {
1505 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1508 // check the params.
1509 if (!params_.spacing().isDefault())
1510 features.require("setspace");
1513 features.useLayout(layout_->name());
1516 fontlist_.validate(features);
1518 // then the indentation
1519 if (!params_.leftIndent().zero())
1520 features.require("ParagraphLeftIndent");
1523 InsetList::const_iterator icit = insetlist_.begin();
1524 InsetList::const_iterator iend = insetlist_.end();
1525 for (; icit != iend; ++icit) {
1527 features.inDeletedInset(owner_->isDeleted(icit->pos));
1528 if (icit->inset->lyxCode() == FOOT_CODE) {
1529 // FIXME: an item inset would make things much easier.
1530 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1531 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1532 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1533 && (icit->pos < begin_of_body_
1534 || (icit->pos == begin_of_body_
1535 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1536 features.saveNoteEnv("description");
1538 icit->inset->validate(features);
1539 features.inDeletedInset(false);
1540 if (layout_->needprotect &&
1541 icit->inset->lyxCode() == FOOT_CODE)
1542 features.require("NeedLyXFootnoteCode");
1546 // then the contents
1547 BufferParams const bp = features.runparams().is_child
1548 ? features.buffer().masterParams() : features.buffer().params();
1549 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1550 char_type c = text_[i];
1551 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1553 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1554 features.require("textquotedblp");
1555 else if (features.runparams().main_fontenc != "T1"
1556 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1557 features.require("textquotedbl");
1558 } else if (ci.textFeature() && contains(ci.textPreamble(), '=')) {
1559 // features that depend on the font or input encoding
1560 string feats = ci.textPreamble();
1561 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1562 if (fontenc.empty())
1563 fontenc = features.runparams().main_fontenc;
1564 while (!feats.empty()) {
1566 feats = split(feats, feat, ',');
1567 if (contains(feat, "!=")) {
1568 // a feature that is required except for the spcified
1569 // font or input encodings
1571 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1572 // multiple encodings are separated by semicolon
1573 vector<string> context = getVectorFromString(contexts, ";");
1574 // require feature if the context matches neither current font
1575 // nor input encoding
1576 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1577 && std::find(context.begin(), context.end(),
1578 features.runparams().encoding->name()) == context.end())
1579 features.require(realfeature);
1580 } else if (contains(feat, '=')) {
1581 // a feature that is required only for the spcified
1582 // font or input encodings
1584 string const contexts = split(feat, realfeature, '=');
1585 // multiple encodings are separated by semicolon
1586 vector<string> context = getVectorFromString(contexts, ";");
1587 // require feature if the context matches either current font
1588 // or input encoding
1589 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1590 || std::find(context.begin(), context.end(),
1591 features.runparams().encoding->name()) != context.end())
1592 features.require(realfeature);
1595 } else if (!bp.use_dash_ligatures
1596 && (c == 0x2013 || c == 0x2014)
1597 && bp.useNonTeXFonts
1598 && features.runparams().flavor == Flavor::XeTeX)
1599 // XeTeX's dash behaviour is determined via a global setting
1600 features.require("xetexdashbreakstate");
1601 BufferEncodings::validate(c, features);
1605 /////////////////////////////////////////////////////////////////////
1609 /////////////////////////////////////////////////////////////////////
1612 Layout const emptyParagraphLayout;
1615 Paragraph::Paragraph()
1616 : d(new Paragraph::Private(this, emptyParagraphLayout))
1623 Paragraph::Paragraph(Paragraph const & par)
1624 : itemdepth(par.itemdepth),
1625 d(new Paragraph::Private(*par.d, this))
1631 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1632 : itemdepth(par.itemdepth),
1633 d(new Paragraph::Private(*par.d, this, beg, end))
1639 Paragraph & Paragraph::operator=(Paragraph const & par)
1641 // needed as we will destroy the private part before copying it
1643 itemdepth = par.itemdepth;
1647 d = new Private(*par.d, this);
1654 Paragraph::~Paragraph()
1663 // this shall be called just before every "os << ..." action.
1664 void flushString(ostream & os, docstring & s)
1673 void Paragraph::write(ostream & os, BufferParams const & bparams,
1674 depth_type & depth) const
1676 // The beginning or end of a deeper (i.e. nested) area?
1677 if (depth != d->params_.depth()) {
1678 if (d->params_.depth() > depth) {
1679 while (d->params_.depth() > depth) {
1680 os << "\n\\begin_deeper";
1684 while (d->params_.depth() < depth) {
1685 os << "\n\\end_deeper";
1691 // First write the layout
1692 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1694 d->params_.write(os);
1696 Font font1(inherit_font, bparams.language);
1698 Change running_change = Change(Change::UNCHANGED);
1700 // this string is used as a buffer to avoid repetitive calls
1701 // to to_utf8(), which turn out to be expensive (JMarc)
1702 docstring write_buffer;
1705 for (pos_type i = 0; i <= size(); ++i) {
1707 Change const & change = lookupChange(i);
1708 if (change != running_change)
1709 flushString(os, write_buffer);
1710 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1711 running_change = change;
1716 // Write font changes
1717 Font font2 = getFontSettings(bparams, i);
1718 if (font2 != font1) {
1719 flushString(os, write_buffer);
1720 font2.lyxWriteChanges(font1, os);
1725 char_type const c = d->text_[i];
1728 if (Inset const * inset = getInset(i)) {
1729 flushString(os, write_buffer);
1730 if (inset->directWrite()) {
1731 // international char, let it write
1732 // code directly so it's shorter in
1738 os << "\\begin_inset ";
1740 os << "\n\\end_inset\n\n";
1743 // FIXME This can be removed again once the mystery
1744 // crash has been resolved.
1749 flushString(os, write_buffer);
1750 os << "\n\\backslash\n";
1759 case 0x061F: // ؟ U+061F ARABIC QUESTION MARK
1760 case 0x061B: // ؛ U+061B ARABIC SEMICOLON
1761 case 0x060C: // ، U+060C ARABIC COMMA
1762 flushString(os, write_buffer);
1763 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1764 os << to_utf8(docstring(1, c)) << '\n';
1767 os << to_utf8(docstring(1, c));
1769 case 0x2014: // — U+2014 EM DASH
1770 case 0x3002: // 。 U+3002 IDEOGRAPHIC FULL STOP
1771 case 0xFF01: // ! U+FF01 FULLWIDTH EXCLAMATION MARK
1772 case 0xFF1F: // ? U+FF1F FULLWIDTH QUESTION MARK
1773 case 0xFF1A: // : U+FF1A FULLWIDTH COLON
1774 case 0xFF1B: // ; U+FF1B FULLWIDTH SEMICOLON
1775 case 0xFF0C: // , U+FF0C FULLWIDTH COMMA
1776 flushString(os, write_buffer);
1777 os << to_utf8(docstring(1, c)) << '\n';
1782 flushString(os, write_buffer);
1786 // this check is to amend a bug. LyX sometimes
1787 // inserts '\0' this could cause problems.
1789 write_buffer.push_back(c);
1791 LYXERR0("NUL char in structure.");
1797 flushString(os, write_buffer);
1798 os << "\n\\end_layout\n";
1799 // FIXME This can be removed again once the mystery
1800 // crash has been resolved.
1805 void Paragraph::validate(LaTeXFeatures & features) const
1807 d->validate(features);
1808 bool fragile = features.runparams().moving_arg;
1809 fragile |= layout().needprotect;
1810 if (inInset().getLayout().isNeedProtect())
1812 if (needsCProtection(fragile))
1813 features.require("cprotect");
1817 void Paragraph::insert(pos_type pos, docstring const & str,
1818 Font const & font, Change const & change)
1820 for (size_t i = 0, n = str.size(); i != n ; ++i)
1821 insertChar(pos + i, str[i], font, change);
1825 void Paragraph::appendChar(char_type c, Font const & font,
1826 Change const & change)
1828 // Make sure that Buffer::hasChangesPresent is updated
1829 ChangesMonitor cm(*this);
1832 d->changes_.insert(change, d->text_.size());
1833 // when appending characters, no need to update tables
1834 d->text_.push_back(c);
1835 setFont(d->text_.size() - 1, font);
1836 d->requestSpellCheck(d->text_.size() - 1);
1840 void Paragraph::appendString(docstring const & s, Font const & font,
1841 Change const & change)
1843 // Make sure that Buffer::hasChangesPresent is updated
1844 ChangesMonitor cm(*this);
1846 pos_type end = s.size();
1847 size_t oldsize = d->text_.size();
1848 size_t newsize = oldsize + end;
1849 size_t capacity = d->text_.capacity();
1850 if (newsize >= capacity)
1851 d->text_.reserve(max(capacity + 100, newsize));
1853 // when appending characters, no need to update tables
1856 // FIXME: Optimize this!
1857 for (size_t i = oldsize; i != newsize; ++i) {
1859 d->changes_.insert(change, i);
1860 d->requestSpellCheck(i);
1862 d->fontlist_.set(oldsize, font);
1863 d->fontlist_.set(newsize - 1, font);
1867 void Paragraph::insertChar(pos_type pos, char_type c,
1870 d->insertChar(pos, c, Change(trackChanges ?
1871 Change::INSERTED : Change::UNCHANGED));
1875 void Paragraph::insertChar(pos_type pos, char_type c,
1876 Font const & font, bool trackChanges)
1878 d->insertChar(pos, c, Change(trackChanges ?
1879 Change::INSERTED : Change::UNCHANGED));
1884 void Paragraph::insertChar(pos_type pos, char_type c,
1885 Font const & font, Change const & change)
1887 d->insertChar(pos, c, change);
1892 void Paragraph::resetFonts(Font const & font)
1894 d->fontlist_.clear();
1895 d->fontlist_.set(0, font);
1896 d->fontlist_.set(d->text_.size() - 1, font);
1899 // Gets uninstantiated font setting at position.
1900 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1904 LYXERR0("pos: " << pos << " size: " << size());
1908 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1909 if (cit != d->fontlist_.end())
1912 if (pos == size() && !empty())
1913 return getFontSettings(bparams, pos - 1);
1915 // Optimisation: avoid a full font instantiation if there is no
1916 // language change from previous call.
1917 static Font previous_font;
1918 static Language const * previous_lang = nullptr;
1919 Language const * lang = getParLanguage(bparams);
1920 if (lang != previous_lang) {
1921 previous_lang = lang;
1922 previous_font = Font(inherit_font, lang);
1924 return previous_font;
1928 FontSpan Paragraph::fontSpan(pos_type pos) const
1930 LBUFERR(pos <= size());
1933 return FontSpan(pos, pos);
1936 FontList::const_iterator cit = d->fontlist_.begin();
1937 FontList::const_iterator end = d->fontlist_.end();
1938 for (; cit != end; ++cit) {
1939 if (cit->pos() >= pos) {
1940 if (pos >= beginOfBody())
1941 return FontSpan(max(start, beginOfBody()),
1944 return FontSpan(start,
1945 min(beginOfBody() - 1,
1948 start = cit->pos() + 1;
1951 // This should not happen, but if so, we take no chances.
1952 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1953 LASSERT(false, /**/);
1954 return FontSpan(pos, pos);
1958 // Gets uninstantiated font setting at position 0
1959 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1961 if (!empty() && !d->fontlist_.empty())
1962 return d->fontlist_.begin()->font();
1964 // Optimisation: avoid a full font instantiation if there is no
1965 // language change from previous call.
1966 static Font previous_font;
1967 static Language const * previous_lang = nullptr;
1968 if (bparams.language != previous_lang) {
1969 previous_lang = bparams.language;
1970 previous_font = Font(inherit_font, bparams.language);
1973 return previous_font;
1977 // Gets the fully instantiated font at a given position in a paragraph
1978 // This is basically the same function as Text::GetFont() in text2.cpp.
1979 // The difference is that this one is used for generating the LaTeX file,
1980 // and thus cosmetic "improvements" are disallowed: This has to deliver
1981 // the true picture of the buffer. (Asger)
1982 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1983 Font const & outerfont) const
1987 Font font = getFontSettings(bparams, pos);
1989 pos_type const body_pos = beginOfBody();
1990 FontInfo & fi = font.fontInfo();
1992 fi.realize(d->layout_->labelfont);
1994 fi.realize(d->layout_->font);
1996 fi.realize(outerfont.fontInfo());
1997 fi.realize(bparams.getFont().fontInfo());
2003 Font const Paragraph::getLabelFont
2004 (BufferParams const & bparams, Font const & outerfont) const
2006 FontInfo tmpfont = d->layout_->labelfont;
2007 tmpfont.realize(outerfont.fontInfo());
2008 tmpfont.realize(bparams.getFont().fontInfo());
2009 return Font(tmpfont, getParLanguage(bparams));
2013 Font const Paragraph::getLayoutFont
2014 (BufferParams const & bparams, Font const & outerfont) const
2016 FontInfo tmpfont = d->layout_->font;
2017 tmpfont.realize(outerfont.fontInfo());
2018 tmpfont.realize(bparams.getFont().fontInfo());
2019 return Font(tmpfont, getParLanguage(bparams));
2023 char_type Paragraph::getUChar(BufferParams const & bparams,
2024 OutputParams const & rp,
2027 char_type c = d->text_[pos];
2029 // Return unchanged character in LTR languages
2030 // or if we use poylglossia/bidi (XeTeX).
2031 if (rp.useBidiPackage()
2032 || !getFontSettings(bparams, pos).isRightToLeft())
2035 // Without polyglossia/bidi, we need to account for some special cases.
2036 // FIXME This needs to be audited!
2038 // * The input is as expected for all delimiters
2039 // => checked for Hebrew!
2040 // * The output matches the display in the LyX workarea
2041 // => checked for Hebrew!
2042 // * The special cases below are really necessary
2043 // => checked for Hebrew!
2044 // * In arabic_arabi, brackets are transformed to Arabic
2045 // Ornate Parentheses. Is this is really wanted?
2047 string const & lang = getFontSettings(bparams, pos).language()->lang();
2050 // 1. In the following languages, parentheses need to be reversed.
2051 // Also with polyglodia/luabidi
2052 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2054 // 2. In the following languages, brackets don't need to be reversed.
2055 bool const reversebrackets = lang != "arabic_arabtex"
2056 && lang != "arabic_arabi"
2059 // Now swap delimiters if needed.
2070 if (reversebrackets)
2074 if (reversebrackets)
2095 void Paragraph::setFont(pos_type pos, Font const & font)
2097 LASSERT(pos <= size(), return);
2099 // First, reduce font against layout/label font
2100 // Update: The setCharFont() routine in text2.cpp already
2101 // reduces font, so we don't need to do that here. (Asger)
2103 d->fontlist_.set(pos, font);
2107 void Paragraph::makeSameLayout(Paragraph const & par)
2109 d->layout_ = par.d->layout_;
2110 d->params_ = par.d->params_;
2114 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2116 if (isFreeSpacing())
2122 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2123 if (eraseChar(pos, trackChanges))
2129 return count > 0 || pos > 0;
2133 bool Paragraph::hasSameLayout(Paragraph const & par) const
2135 return par.d->layout_ == d->layout_
2136 && d->params_.sameLayout(par.d->params_);
2140 depth_type Paragraph::getDepth() const
2142 return d->params_.depth();
2146 depth_type Paragraph::getMaxDepthAfter() const
2148 if (d->layout_->isEnvironment())
2149 return d->params_.depth() + 1;
2151 return d->params_.depth();
2155 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2157 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2158 return getDefaultAlign(bparams);
2160 return d->params_.align();
2164 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2166 LyXAlignment res = layout().align;
2167 if (isRTL(bparams)) {
2169 if (res == LYX_ALIGN_LEFT)
2170 res = LYX_ALIGN_RIGHT;
2171 else if (res == LYX_ALIGN_RIGHT)
2172 res = LYX_ALIGN_LEFT;
2178 docstring const & Paragraph::labelString() const
2180 return d->params_.labelString();
2184 // the next two functions are for the manual labels
2185 docstring const Paragraph::getLabelWidthString() const
2187 if (d->layout_->margintype == MARGIN_MANUAL
2188 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2189 return d->params_.labelWidthString();
2191 return _("Senseless with this layout!");
2195 void Paragraph::setLabelWidthString(docstring const & s)
2197 d->params_.labelWidthString(s);
2201 docstring Paragraph::expandLabel(Layout const & layout,
2202 BufferParams const & bparams) const
2204 return expandParagraphLabel(layout, bparams, true);
2208 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2209 BufferParams const & bparams, bool process_appendix) const
2211 DocumentClass const & tclass = bparams.documentClass();
2212 string const & lang = getParLanguage(bparams)->code();
2213 bool const in_appendix = process_appendix && d->params_.appendix();
2214 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2216 if (fmt.empty() && !layout.counter.empty())
2217 return tclass.counters().theCounter(layout.counter, lang);
2219 // handle 'inherited level parts' in 'fmt',
2220 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2221 size_t const i = fmt.find('@', 0);
2222 if (i != docstring::npos) {
2223 size_t const j = fmt.find('@', i + 1);
2224 if (j != docstring::npos) {
2225 docstring parent(fmt, i + 1, j - i - 1);
2226 docstring label = from_ascii("??");
2227 if (tclass.hasLayout(parent))
2228 label = expandParagraphLabel(tclass[parent], bparams,
2230 fmt = docstring(fmt, 0, i) + label
2231 + docstring(fmt, j + 1, docstring::npos);
2235 return tclass.counters().counterLabel(fmt, lang);
2239 void Paragraph::applyLayout(Layout const & new_layout)
2241 d->layout_ = &new_layout;
2242 LyXAlignment const oldAlign = d->params_.align();
2244 if (!(oldAlign & d->layout_->alignpossible)) {
2245 frontend::Alert::warning(_("Alignment not permitted"),
2246 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2247 d->params_.align(LYX_ALIGN_LAYOUT);
2252 pos_type Paragraph::beginOfBody() const
2254 return d->begin_of_body_;
2258 void Paragraph::setBeginOfBody()
2260 if (d->layout_->labeltype != LABEL_MANUAL) {
2261 d->begin_of_body_ = 0;
2265 // Unroll the first two cycles of the loop
2266 // and remember the previous character to
2267 // remove unnecessary getChar() calls
2269 pos_type end = size();
2270 bool prev_char_deleted = false;
2271 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2274 char_type previous_char = d->text_[i];
2275 if (!(isNewline(i) || isEnvSeparator(i))) {
2277 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2278 char_type temp = d->text_[i];
2279 prev_char_deleted = isDeleted(i);
2280 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2283 previous_char = temp;
2289 d->begin_of_body_ = i;
2293 bool Paragraph::allowParagraphCustomization() const
2295 return inInset().allowParagraphCustomization();
2299 bool Paragraph::usePlainLayout() const
2301 return inInset().usePlainLayout();
2305 bool Paragraph::isPassThru() const
2307 return inInset().isPassThru() || d->layout_->pass_thru;
2311 bool Paragraph::parbreakIsNewline() const
2313 return inInset().getLayout().parbreakIsNewline() || d->layout_->parbreak_is_newline;
2317 bool Paragraph::isPartOfTextSequence() const
2319 for (pos_type i = 0; i < size(); ++i) {
2320 if (!isInset(i) || getInset(i)->isPartOfTextSequence())
2328 // paragraphs inside floats need different alignment tags to avoid
2331 bool noTrivlistCentering(InsetCode code)
2333 return code == FLOAT_CODE
2334 || code == WRAP_CODE
2335 || code == CELL_CODE;
2339 string correction(string const & orig)
2341 if (orig == "flushleft")
2342 return "raggedright";
2343 if (orig == "flushright")
2344 return "raggedleft";
2345 if (orig == "center")
2351 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2352 InsetCode code, bool const lastpar, int & col)
2354 string macro = suffix + "{";
2355 if (noTrivlistCentering(code)) {
2357 // the last paragraph in non-trivlist-aligned
2358 // context is special (to avoid unwanted whitespace)
2359 if (suffix == "\\begin") {
2360 macro = "\\" + correction(env) + "{}";
2361 os << from_ascii(macro);
2362 col += macro.size();
2367 macro += correction(env);
2371 if (suffix == "\\par\\end") {
2375 os << from_ascii(macro);
2376 col += macro.size();
2377 if (suffix == "\\begin") {
2387 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2388 otexstream & os, OutputParams const & runparams) const
2393 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2394 (layout_->toggle_indent != ITOGGLE_NEVER) :
2395 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2397 LyXAlignment const curAlign = params_.align();
2399 // Do not output \\noindent for paragraphs
2400 // 1. that cannot have indentation or are indented always,
2401 // 2. that are not part of the immediate text sequence (e.g., contain only floats),
2402 // 3. that are PassThru,
2403 // 4. or that are centered.
2404 if (canindent && params_.noindent()
2405 && owner_->isPartOfTextSequence()
2406 && !layout_->pass_thru
2407 && curAlign != LYX_ALIGN_CENTER) {
2408 if (!owner_->empty()
2409 && owner_->getInset(0)
2410 && owner_->getInset(0)->lyxCode() == VSPACE_CODE)
2411 // If the paragraph starts with a vspace, the \\noindent
2412 // needs to come after that (as it leaves vmode).
2413 // If the paragraph consists only of the vspace,
2414 // \\noindent is not needed at all.
2415 runparams.need_noindent = owner_->size() > 1;
2417 os << "\\noindent" << termcmd;
2422 if (curAlign == layout_->align)
2426 case LYX_ALIGN_NONE:
2427 case LYX_ALIGN_BLOCK:
2428 case LYX_ALIGN_LAYOUT:
2429 case LYX_ALIGN_SPECIAL:
2430 case LYX_ALIGN_DECIMAL:
2432 case LYX_ALIGN_LEFT:
2433 case LYX_ALIGN_RIGHT:
2434 case LYX_ALIGN_CENTER:
2435 if (runparams.moving_arg) {
2442 string const begin_tag = "\\begin";
2443 InsetCode code = ownerCode();
2444 bool const lastpar = runparams.isLastPar;
2445 // RTL in classic (PDF)LaTeX (without the Bidi package)
2446 // Luabibdi (used by LuaTeX) behaves like classic
2447 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2448 && !runparams.useBidiPackage();
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: {
2459 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2460 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2462 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2464 } case LYX_ALIGN_RIGHT: {
2466 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2467 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2469 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2471 } case LYX_ALIGN_CENTER: {
2472 corrected_env(os, begin_tag, "center", code, lastpar, column);
2481 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2482 otexstream & os, OutputParams const & runparams) const
2484 LyXAlignment const curAlign = params_.align();
2486 if (curAlign == layout_->align)
2490 case LYX_ALIGN_NONE:
2491 case LYX_ALIGN_BLOCK:
2492 case LYX_ALIGN_LAYOUT:
2493 case LYX_ALIGN_SPECIAL:
2494 case LYX_ALIGN_DECIMAL:
2496 case LYX_ALIGN_LEFT:
2497 case LYX_ALIGN_RIGHT:
2498 case LYX_ALIGN_CENTER:
2499 if (runparams.moving_arg)
2504 bool output = false;
2506 string const end_tag = "\\par\\end";
2507 InsetCode code = ownerCode();
2508 bool const lastpar = runparams.isLastPar;
2509 // RTL in classic (PDF)LaTeX (without the Bidi package)
2510 // Luabibdi (used by LuaTeX) behaves like classic
2511 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2512 && !runparams.useBidiPackage();
2515 case LYX_ALIGN_NONE:
2516 case LYX_ALIGN_BLOCK:
2517 case LYX_ALIGN_LAYOUT:
2518 case LYX_ALIGN_SPECIAL:
2519 case LYX_ALIGN_DECIMAL:
2521 case LYX_ALIGN_LEFT: {
2523 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2524 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2526 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2528 } case LYX_ALIGN_RIGHT: {
2530 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2531 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2533 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2535 } case LYX_ALIGN_CENTER: {
2536 corrected_env(os, end_tag, "center", code, lastpar, col);
2541 return output || lastpar;
2545 // This one spits out the text of the paragraph
2546 void Paragraph::latex(BufferParams const & bparams,
2547 Font const & outerfont,
2549 OutputParams const & runparams,
2550 int start_pos, int end_pos, bool force) const
2552 LYXERR(Debug::OUTFILE, "Paragraph::latex... " << this);
2554 // FIXME This check should not be needed. Perhaps issue an
2555 // error if it triggers.
2556 Layout const & style = inInset().forcePlainLayout() ?
2557 bparams.documentClass().plainLayout() : *d->layout_;
2559 if (!force && style.inpreamble)
2562 bool const allowcust = allowParagraphCustomization();
2564 // Current base font for all inherited font changes, without any
2565 // change caused by an individual character, except for the language:
2566 // It is set to the language of the first character.
2567 // As long as we are in the label, this font is the base font of the
2568 // label. Before the first body character it is set to the base font
2572 // If there is an open font-encoding changing command (script wrapper),
2573 // alien_script is set to its name
2574 string alien_script;
2577 // Maybe we have to create a optional argument.
2578 pos_type body_pos = beginOfBody();
2579 unsigned int column = 0;
2581 // If we are inside an non inheritFont() inset,
2582 // the outerfont is the buffer's main font
2583 Font const real_outerfont =
2584 inInset().inheritFont() ? outerfont : Font(bparams.getFont());
2587 // the optional argument is kept in curly brackets in
2588 // case it contains a ']'
2589 // This is not strictly needed, but if this is changed it
2590 // would be a file format change, and tex2lyx would need
2591 // to be adjusted, since it unconditionally removes the
2592 // braces when it parses \item.
2595 basefont = getLabelFont(bparams, real_outerfont);
2597 basefont = getLayoutFont(bparams, real_outerfont);
2600 // Which font is currently active?
2601 Font running_font(basefont);
2602 // Do we have an open font change?
2603 bool open_font = false;
2605 Change runningChange =
2606 runparams.inDeletedInset && !inInset().canTrackChanges()
2607 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2609 Encoding const * const prev_encoding = runparams.encoding;
2611 os.texrow().start(id(), 0);
2613 // if the paragraph is empty, the loop will not be entered at all
2615 // For InTitle commands, we have already opened a group
2616 // in output_latex::TeXOnePar.
2617 if (style.isCommand() && !style.intitle) {
2621 if (!style.leftdelim().empty()) {
2622 os << style.leftdelim();
2623 column += style.leftdelim().size();
2626 column += d->startTeXParParams(bparams, os, runparams);
2629 // Whether a \par can be issued for insets typeset inline with text.
2630 // Yes if greater than 0. This has to be static.
2631 THREAD_LOCAL_STATIC int parInline = 0;
2633 for (pos_type i = 0; i < size(); ++i) {
2634 // First char in paragraph or after label?
2635 if (i == body_pos) {
2638 bool needPar = false;
2639 column += running_font.latexWriteEndChanges(
2640 os, bparams, runparams,
2641 basefont, basefont, needPar);
2644 basefont = getLayoutFont(bparams, real_outerfont);
2645 running_font = basefont;
2647 column += Changes::latexMarkChange(os, bparams,
2648 runningChange, Change(Change::UNCHANGED),
2650 runningChange = Change(Change::UNCHANGED);
2652 os << ((isEnvSeparator(i) && !runparams.find_effective()) ? "}]~" : "}] ");
2655 // For InTitle commands, we have already opened a group
2656 // in output_latex::TeXOnePar.
2657 if (style.isCommand() && !style.intitle) {
2662 if (!style.leftdelim().empty()) {
2663 os << style.leftdelim();
2664 column += style.leftdelim().size();
2668 column += d->startTeXParParams(bparams, os,
2672 runparams.wasDisplayMath = runparams.inDisplayMath;
2673 runparams.inDisplayMath = false;
2674 bool deleted_display_math = false;
2675 Change const & change = runparams.inDeletedInset
2676 ? runparams.changeOfDeletedInset : lookupChange(i);
2678 char_type const c = d->text_[i];
2680 // Check whether a display math inset follows
2681 bool output_changes;
2682 if (!runparams.find_effective())
2683 output_changes = bparams.output_changes;
2685 output_changes = runparams.find_with_deleted();
2687 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2689 runparams.ctObject = getInset(i)->getCtObject(runparams);
2691 InsetMath const * im = getInset(i)->asInsetMath();
2692 if (im && im->asHullInset()
2693 && im->asHullInset()->outerDisplay()) {
2694 runparams.inDisplayMath = true;
2695 // runparams.inDeletedInset will be set by
2696 // latexInset later, but we need this info
2697 // before it is called. On the other hand, we
2698 // cannot set it here because it is a counter.
2699 deleted_display_math = isDeleted(i);
2701 if (output_changes && deleted_display_math
2702 && runningChange == change
2703 && change.type == Change::DELETED
2704 && !os.afterParbreak()) {
2705 // A display math in the same paragraph follows.
2706 // We have to close and then reopen \lyxdeleted,
2707 // otherwise the math will be shifted up.
2708 OutputParams rp = runparams;
2710 bool needPar = false;
2711 column += running_font.latexWriteEndChanges(
2712 os, bparams, rp, basefont,
2716 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2717 : getLayoutFont(bparams, real_outerfont);
2718 running_font = basefont;
2719 column += Changes::latexMarkChange(os, bparams,
2720 Change(Change::INSERTED), change, rp);
2724 if (output_changes && runningChange != change) {
2725 if (!alien_script.empty()) {
2728 alien_script.clear();
2731 bool needPar = false;
2732 column += running_font.latexWriteEndChanges(
2733 os, bparams, runparams,
2734 basefont, basefont, needPar);
2737 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2738 : getLayoutFont(bparams, real_outerfont);
2739 running_font = basefont;
2740 column += Changes::latexMarkChange(os, bparams, runningChange,
2742 runningChange = change;
2745 // do not output text which is marked deleted
2746 // if change tracking output is disabled
2747 if (!output_changes && change.deleted()) {
2753 // Fully instantiated font
2754 Font current_font = getFont(bparams, i, outerfont);
2756 Font const prev_font = (i > 0) ?
2757 getFont(bparams, i - 1, outerfont)
2760 Font const last_font = running_font;
2761 bool const in_ct_deletion = (output_changes
2762 && runningChange == change
2763 && change.type == Change::DELETED
2764 && !os.afterParbreak());
2765 // Insets where font switches are used (rather than font commands)
2766 bool const fontswitch_inset =
2769 && getInset(i)->allowMultiPar()
2770 && getInset(i)->lyxCode() != ERT_CODE
2771 && (getInset(i)->producesOutput()
2772 // FIXME Something more general?
2773 // Comments do not "produce output" but are still
2774 // part of the TeX source and require font switches
2775 // to be closed (otherwise LaTeX fails).
2776 || getInset(i)->layoutName() == "Note:Comment");
2778 bool closeLanguage = false;
2779 bool lang_switched_at_inset = false;
2780 if (fontswitch_inset) {
2781 // Some insets cannot be inside a font change command.
2782 // However, even such insets *can* be placed in \L or \R
2783 // or their equivalents (for RTL language switches),
2784 // so we don't close the language in those cases
2785 // (= differing isRightToLeft()).
2786 // ArabTeX, though, doesn't seem to handle this special behavior.
2787 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2788 || basefont.language()->lang() == "arabic_arabtex"
2789 || current_font.language()->lang() == "arabic_arabtex";
2790 // We need to check prev_font as language changes directly at inset
2791 // will only be started inside the inset.
2792 lang_switched_at_inset = prev_font.language() != current_font.language();
2795 // Do we need to close the previous font?
2796 bool langClosed = false;
2798 ((current_font != running_font
2799 || current_font.language() != running_font.language())
2800 || (fontswitch_inset
2801 && (current_font == prev_font))))
2803 // ensure there is no open script-wrapper
2804 if (!alien_script.empty()) {
2807 alien_script.clear();
2809 if (in_ct_deletion) {
2810 // We have to close and then reopen \lyxdeleted,
2811 // as strikeout needs to be on lowest level.
2815 if (closeLanguage) {
2816 // Force language closing
2817 current_font.setLanguage(basefont.language());
2820 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2821 bool needPar = false;
2822 column += running_font.latexWriteEndChanges(
2823 os, bparams, runparams, basefont,
2825 if (in_ct_deletion) {
2826 // We have to close and then reopen \lyxdeleted,
2827 // as strikeout needs to be on lowest level.
2828 OutputParams rp = runparams;
2829 column += Changes::latexMarkChange(os, bparams,
2830 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2832 // Has the language been closed in the latexWriteEndChanges() call above?
2833 langClosed |= running_font.language() != basefont.language()
2834 && running_font.language() != nextfont.language()
2835 && (running_font.language()->encoding()->package() != Encoding::CJK);
2836 running_font = basefont;
2837 open_font &= !langClosed;
2840 // if necessary, close language environment before opening CJK
2841 string const running_lang = running_font.language()->babel();
2842 string const lang_end_command = lyxrc.language_command_end;
2843 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2844 && !running_lang.empty()
2845 && running_lang == openLanguageName()
2846 && current_font.language()->encoding()->package() == Encoding::CJK) {
2847 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2848 os << from_ascii(end_tag);
2849 column += end_tag.length();
2850 if (!languageStackEmpty())
2854 // Switch file encoding if necessary (and allowed)
2855 if ((!fontswitch_inset || closeLanguage)
2856 && !runparams.pass_thru && !style.pass_thru &&
2857 runparams.encoding->package() != Encoding::none &&
2858 current_font.language()->encoding()->package() != Encoding::none) {
2859 pair<bool, int> const enc_switch =
2860 switchEncoding(os.os(), bparams, runparams,
2861 *(current_font.language()->encoding()));
2862 if (enc_switch.first) {
2863 column += enc_switch.second;
2864 runparams.encoding = current_font.language()->encoding();
2868 // A display math inset inside an ulem command will be output
2869 // as a box of width \linewidth, so we have to either disable
2870 // indentation if the inset starts a paragraph, or start a new
2871 // line to accommodate such box. This has to be done before
2872 // writing any font changing commands.
2873 if (runparams.inDisplayMath && !deleted_display_math
2874 && runparams.inulemcmd) {
2875 if (os.afterParbreak())
2881 // Do we need to change font?
2882 if ((current_font != running_font ||
2883 current_font.language() != running_font.language())
2884 && i != body_pos - 1)
2886 if (!fontswitch_inset) {
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 bool needPar = false;
2892 column += running_font.latexWriteEndChanges(
2893 os, bparams, rp, basefont,
2898 otexstringstream ots;
2899 InsetText const * textinset = inInset().asInsetText();
2900 bool const cprotect = textinset
2901 ? textinset->hasCProtectContent(runparams.moving_arg)
2902 && !textinset->text().isMainText()
2903 && inInset().lyxCode() != BRANCH_CODE
2905 column += current_font.latexWriteStartChanges(ots, bparams,
2906 runparams, basefont, last_font, false,
2908 // Check again for display math in ulem commands as a
2909 // font change may also occur just before a math inset.
2910 if (runparams.inDisplayMath && !deleted_display_math
2911 && runparams.inulemcmd) {
2912 if (os.afterParbreak())
2917 running_font = current_font;
2919 docstring fontchange = ots.str();
2921 // check whether the fontchange ends with a \\textcolor
2922 // modifier and the text starts with a space. If so we
2923 // need to add } in order to prevent \\textcolor from gobbling
2924 // the space (bug 4473).
2925 docstring const last_modifier = rsplit(fontchange, '\\');
2926 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2927 os << from_ascii("{}");
2928 else if (ots.terminateCommand())
2930 if (in_ct_deletion) {
2931 // We have to close and then reopen \lyxdeleted,
2932 // as strikeout needs to be on lowest level.
2933 OutputParams rp = runparams;
2934 column += Changes::latexMarkChange(os, bparams,
2935 Change(Change::UNCHANGED), change, rp);
2937 } else {// if fontswitch_inset
2938 if (current_font != running_font || !langClosed)
2939 // font is still open in fontswitch_insets if we have
2940 // a non-lang font difference or if the language
2941 // is the only difference but has not been forcedly
2944 running_font = current_font;
2948 // FIXME: think about end_pos implementation...
2949 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2950 // FIXME: integrate this case in latexSpecialChar
2951 // Do not print the separation of the optional argument
2952 // if style.pass_thru is false. This works because
2953 // latexSpecialChar ignores spaces if
2954 // style.pass_thru is false.
2955 if (i != body_pos - 1) {
2956 if (d->simpleTeXBlanks(bparams, runparams, os,
2957 i, column, current_font, style)) {
2958 // A surrogate pair was output. We
2959 // must not call latexSpecialChar
2960 // in this iteration, since it would output
2961 // the combining character again.
2968 OutputParams rp = runparams;
2969 rp.free_spacing = style.free_spacing;
2970 rp.local_font = ¤t_font;
2971 rp.intitle = style.intitle;
2973 // Two major modes: LaTeX or plain
2974 // Handle here those cases common to both modes
2975 // and then split to handle the two modes separately.
2976 if (c == META_INSET) {
2977 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2978 // Greyedout notes and, in general, all insets
2979 // with InsetLayout::isDisplay() == false,
2980 // are typeset inline with the text. So, we
2981 // can add a \par to the last paragraph of
2982 // such insets only if nothing else follows.
2983 bool incremented = false;
2984 Inset const * inset = getInset(i);
2985 InsetText const * textinset = inset
2986 ? inset->asInsetText()
2988 if (i + 1 == size() && textinset
2989 && !inset->getLayout().isDisplay()) {
2990 ParagraphList const & pars =
2991 textinset->text().paragraphs();
2992 pit_type const pit = pars.size() - 1;
2993 Font const lastfont =
2994 pit < 0 || pars[pit].empty()
2995 ? pars[pit].getLayoutFont(
2998 : pars[pit].getFont(bparams,
2999 pars[pit].size() - 1,
3001 if (lastfont.fontInfo().size() !=
3002 basefont.fontInfo().size()) {
3007 // We need to restore parts of this after insets with
3008 // allowMultiPar() true
3009 Font const save_basefont = basefont;
3010 d->latexInset(bparams, os, rp, running_font,
3011 basefont, real_outerfont, open_font,
3012 runningChange, style, i, column, fontswitch_inset,
3013 closeLanguage, (lang_switched_at_inset || langClosed));
3014 if (fontswitch_inset) {
3016 bool needPar = false;
3017 column += running_font.latexWriteEndChanges(
3018 os, bparams, runparams,
3019 basefont, basefont, needPar);
3022 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
3023 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
3024 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
3029 if (runparams.ctObject == CtObject::DisplayObject
3030 || runparams.ctObject == CtObject::UDisplayObject) {
3031 // Close \lyx*deleted and force its
3032 // reopening (if needed)
3035 runningChange = Change(Change::UNCHANGED);
3036 runparams.ctObject = CtObject::Normal;
3039 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
3040 if (!bparams.useNonTeXFonts)
3041 script = Encodings::isKnownScriptChar(c);
3042 if (script != alien_script) {
3043 if (!alien_script.empty()) {
3045 alien_script.clear();
3047 string fontenc = running_font.language()->fontenc(bparams);
3049 && !Encodings::fontencSupportsScript(fontenc, script)) {
3050 column += script.length() + 2;
3051 os << "\\" << script << "{";
3052 alien_script = script;
3056 d->latexSpecialChar(os, bparams, rp, running_font,
3057 alien_script, style, i, end_pos, column);
3058 } catch (EncodingException & e) {
3059 if (runparams.dryrun) {
3060 os << "<" << _("LyX Warning: ")
3061 << _("uncodable character") << " '";
3065 // add location information and throw again.
3073 // Set the encoding to that returned from latexSpecialChar (see
3074 // comment for encoding member in OutputParams.h)
3075 runparams.encoding = rp.encoding;
3077 // Also carry on the info on a closed ulem command for insets
3078 // such as Note that do not produce any output, so that no
3079 // command is ever executed but its opening was recorded.
3080 runparams.inulemcmd = rp.inulemcmd;
3082 // These need to be passed upstream as well
3083 runparams.need_maketitle = rp.need_maketitle;
3084 runparams.have_maketitle = rp.have_maketitle;
3086 // And finally, pass the post_macros upstream
3087 runparams.post_macro = rp.post_macro;
3090 // Close wrapper for alien script
3091 if (!alien_script.empty()) {
3093 alien_script.clear();
3096 Font const font = empty()
3097 ? getLayoutFont(bparams, real_outerfont)
3098 : getFont(bparams, size() - 1, real_outerfont);
3100 InsetText const * textinset = inInset().asInsetText();
3102 bool const maintext = textinset
3103 ? textinset->text().isMainText()
3106 size_t const numpars = textinset
3107 ? textinset->text().paragraphs().size()
3110 bool needPar = false;
3112 if (style.resfont.size() != font.fontInfo().size()
3113 && (!runparams.isLastPar || maintext
3114 || (numpars > 1 && d->ownerCode() != CELL_CODE
3115 && (inInset().getLayout().isDisplay()
3117 && !style.isCommand()) {
3121 // If we have an open font definition, we have to close it
3123 // Make sure that \\par is done with the font of the last
3124 // character if this has another size as the default.
3125 // This is necessary because LaTeX (and LyX on the screen)
3126 // calculates the space between the baselines according
3127 // to this font. (Matthias)
3129 // We must not change the font for the last paragraph
3130 // of non-multipar insets, tabular cells or commands,
3131 // since this produces unwanted whitespace.
3132 #ifdef FIXED_LANGUAGE_END_DETECTION
3134 running_font.latexWriteEndChanges(os, bparams,
3135 runparams, basefont,
3136 next_->getFont(bparams, 0, outerfont),
3139 running_font.latexWriteEndChanges(os, bparams,
3140 runparams, basefont, basefont, needPar);
3143 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3144 //FIXME: there as we start another \selectlanguage with the next paragraph if
3145 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3146 running_font.latexWriteEndChanges(os, bparams, runparams,
3147 basefont, basefont, needPar);
3151 // The \par could not be inserted at the same nesting
3152 // level of the font size change, so do it now.
3153 os << "{\\" << font.latexSize() << "\\par}";
3156 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3157 column += Changes::latexMarkChange(os, bparams, runningChange,
3158 Change(Change::UNCHANGED), runparams);
3160 // Needed if there is an optional argument but no contents.
3161 if (body_pos > 0 && body_pos == size()) {
3165 if (!style.rightdelim().empty()) {
3166 os << style.rightdelim();
3167 column += style.rightdelim().size();
3170 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3171 && runparams.encoding != prev_encoding) {
3172 runparams.encoding = prev_encoding;
3173 os << setEncoding(prev_encoding->iconvName());
3176 LYXERR(Debug::OUTFILE, "Paragraph::latex... done " << this);
3180 bool Paragraph::emptyTag() const
3182 for (pos_type i = 0; i < size(); ++i) {
3183 if (Inset const * inset = getInset(i)) {
3184 InsetCode lyx_code = inset->lyxCode();
3185 // FIXME testing like that is wrong. What is
3187 if (lyx_code != TOC_CODE &&
3188 lyx_code != INCLUDE_CODE &&
3189 lyx_code != GRAPHICS_CODE &&
3190 lyx_code != ERT_CODE &&
3191 lyx_code != LISTINGS_CODE &&
3192 lyx_code != FLOAT_CODE &&
3193 lyx_code != TABULAR_CODE) {
3197 char_type c = d->text_[i];
3198 if (c != ' ' && c != '\t')
3206 string Paragraph::getID(Buffer const &, OutputParams const &)
3209 for (pos_type i = 0; i < size(); ++i) {
3210 if (Inset const * inset = getInset(i)) {
3211 InsetCode lyx_code = inset->lyxCode();
3212 if (lyx_code == LABEL_CODE) {
3213 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3214 docstring const & id = il->getParam("name");
3215 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3223 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3226 for (i = 0; i < size(); ++i) {
3227 if (Inset const * inset = getInset(i)) {
3228 inset->docbook(xs, runparams);
3230 char_type c = d->text_[i];
3240 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3244 for (i = 0; i < size(); ++i) {
3245 if (Inset const * inset = getInset(i)) {
3246 inset->xhtml(xs, runparams);
3248 char_type c = d->text_[i];
3258 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3261 pos_type size = text_.size();
3262 for (pos_type i = initial; i < size; ++i) {
3263 Font font = owner_->getFont(buf.params(), i, outerfont);
3264 if (text_[i] == META_INSET)
3266 if (i != initial && font != font_old)
3277 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3278 vector<xml::EndFontTag> & tagsToClose,
3279 bool & flag, FontState curstate, xml::FontTypes type)
3281 if (curstate == FONT_ON) {
3282 tagsToOpen.push_back(docbookStartFontTag(type));
3285 tagsToClose.push_back(docbookEndFontTag(type));
3290 class OptionalFontType {
3295 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3296 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3299 OptionalFontType fontShapeToXml(FontShape fs)
3303 return {xml::FT_ITALIC};
3305 return {xml::FT_SLANTED};
3306 case SMALLCAPS_SHAPE:
3307 return {xml::FT_SMALLCAPS};
3312 // the other tags are for internal use
3318 OptionalFontType fontFamilyToXml(FontFamily fm)
3322 return {xml::FT_ROMAN};
3324 return {xml::FT_SANS};
3325 case TYPEWRITER_FAMILY:
3326 return {xml::FT_TYPE};
3327 case INHERIT_FAMILY:
3330 // the other tags are for internal use
3336 OptionalFontType fontSizeToXml(FontSize fs)
3340 return {xml::FT_SIZE_TINY};
3342 return {xml::FT_SIZE_SCRIPT};
3344 return {xml::FT_SIZE_FOOTNOTE};
3346 return {xml::FT_SIZE_SMALL};
3348 return {xml::FT_SIZE_LARGE};
3350 return {xml::FT_SIZE_LARGER};
3352 return {xml::FT_SIZE_LARGEST};
3354 return {xml::FT_SIZE_HUGE};
3356 return {xml::FT_SIZE_HUGER};
3358 return {xml::FT_SIZE_INCREASE};
3360 return {xml::FT_SIZE_DECREASE};
3365 // the other tags are for internal use
3371 struct DocBookFontState
3373 FontShape curr_fs = INHERIT_SHAPE;
3374 FontFamily curr_fam = INHERIT_FAMILY;
3375 FontSize curr_size = INHERIT_SIZE;
3377 // track whether we have opened these tags
3378 bool emph_flag = false;
3379 bool bold_flag = false;
3380 bool noun_flag = false;
3381 bool ubar_flag = false;
3382 bool dbar_flag = false;
3383 bool sout_flag = false;
3384 bool xout_flag = false;
3385 bool wave_flag = false;
3387 bool shap_flag = false;
3389 bool faml_flag = false;
3391 bool size_flag = false;
3394 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3396 std::string const & default_family,
3397 DocBookFontState & fs)
3399 vector<xml::FontTag> tagsToOpen;
3400 vector<xml::EndFontTag> tagsToClose;
3403 FontState curstate = font.fontInfo().emph();
3404 if (font_old.emph() != curstate)
3405 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3408 curstate = font.fontInfo().noun();
3409 if (font_old.noun() != curstate)
3410 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3413 curstate = font.fontInfo().underbar();
3414 if (font_old.underbar() != curstate)
3415 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3418 curstate = font.fontInfo().strikeout();
3419 if (font_old.strikeout() != curstate)
3420 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3423 curstate = font.fontInfo().xout();
3424 if (font_old.xout() != curstate)
3425 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3428 curstate = font.fontInfo().uuline();
3429 if (font_old.uuline() != curstate)
3430 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3433 curstate = font.fontInfo().uwave();
3434 if (font_old.uwave() != curstate)
3435 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3438 // a little hackish, but allows us to reuse what we have.
3439 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3440 if (font_old.series() != font.fontInfo().series())
3441 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3444 fs.curr_fs = font.fontInfo().shape();
3445 FontShape old_fs = font_old.shape();
3446 if (old_fs != fs.curr_fs) {
3448 OptionalFontType tag = fontShapeToXml(old_fs);
3450 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3451 fs.shap_flag = false;
3454 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3456 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3460 fs.curr_fam = font.fontInfo().family();
3461 FontFamily old_fam = font_old.family();
3462 if (old_fam != fs.curr_fam) {
3464 OptionalFontType tag = fontFamilyToXml(old_fam);
3466 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3467 fs.faml_flag = false;
3469 switch (fs.curr_fam) {
3471 // we will treat a "default" font family as roman, since we have
3472 // no other idea what to do.
3473 if (default_family != "rmdefault" && default_family != "default") {
3474 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3475 fs.faml_flag = true;
3479 if (default_family != "sfdefault") {
3480 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3481 fs.faml_flag = true;
3484 case TYPEWRITER_FAMILY:
3485 if (default_family != "ttdefault") {
3486 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3487 fs.faml_flag = true;
3490 case INHERIT_FAMILY:
3493 // the other tags are for internal use
3500 fs.curr_size = font.fontInfo().size();
3501 FontSize old_size = font_old.size();
3502 if (old_size != fs.curr_size) {
3504 OptionalFontType tag = fontSizeToXml(old_size);
3506 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3507 fs.size_flag = false;
3510 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3511 if (tag.has_value) {
3512 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3513 fs.size_flag = true;
3517 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3520 } // anonymous namespace
3523 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3524 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3525 OutputParams const & runparams,
3526 Font const & outerfont,
3529 bool ignore_fonts) const
3531 // Return values: segregation of the content of this paragraph.
3532 std::vector<docstring> prependedParagraphs; // Anything that must be output before the main tag of this paragraph.
3533 std::vector<docstring> generatedParagraphs; // The main content of the paragraph.
3534 std::vector<docstring> appendedParagraphs; // Anything that must be output after the main tag of this paragraph.
3536 // Internal string stream to store the output before being added to one of the previous lists.
3537 odocstringstream os;
3539 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3540 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3542 OutputParams rp = runparams;
3543 for (pos_type i = initial; i < size(); ++i) {
3544 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3545 const InsetArgument * arg = getInset(i)->asInsetArgument();
3546 if (arg->docbookargumentbeforemaintag()) {
3547 auto xs_local = XMLStream(os);
3548 arg->docbook(xs_local, rp);
3550 prependedParagraphs.push_back(os.str());
3551 os.str(from_ascii(""));
3553 rp.docbook_prepended_arguments.insert(arg);
3554 } else if (arg->docbookargumentaftermaintag()) {
3555 rp.docbook_appended_arguments.insert(arg);
3560 // State variables for the main loop.
3561 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3562 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3563 std::vector<docstring> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3564 // This requires to store delayed characters at some point.
3566 // Track whether we have opened font tags
3567 DocBookFontState fs;
3568 DocBookFontState old_fs = fs;
3570 Layout const & style = *d->layout_;
3572 // Conversion of the font opening/closing into DocBook tags.
3573 vector<xml::FontTag> tagsToOpen;
3574 vector<xml::EndFontTag> tagsToClose;
3576 // Parsing main loop.
3577 for (pos_type i = initial; i < size(); ++i) {
3578 bool ignore_fonts_i = ignore_fonts
3579 || style.docbooknofontinside()
3580 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3582 // Don't show deleted material in the output.
3586 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3588 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3589 if (!ignore_fonts_i)
3590 xs->closeFontTags();
3592 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3593 generatedParagraphs.push_back(os.str());
3595 // Create a new XMLStream for the new paragraph, completely independent of the previous one. This implies
3596 // that the string stream must be reset.
3597 os.str(from_ascii(""));
3599 xs = new XMLStream(os);
3601 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3602 if (!ignore_fonts_i) {
3607 // Determine which tags should be opened or closed regarding fonts.
3608 FontInfo const font_old = (i == 0 ?
3609 (style.labeltype == LABEL_MANUAL ? style.labelfont : style.font) :
3610 getFont(buf.masterBuffer()->params(), i - 1, outerfont).fontInfo());
3611 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3612 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(
3613 font_old, font, buf.masterBuffer()->params().fonts_default_family, fs);
3615 if (!ignore_fonts_i) {
3616 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3617 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3618 for (; cit != cen; ++cit)
3622 // Deal with the delayed characters *after* closing font tags.
3623 if (!delayedChars.empty()) {
3624 for (const docstring& c: delayedChars)
3625 *xs << XMLStream::ESCAPE_NONE << c;
3626 delayedChars.clear();
3629 if (!ignore_fonts_i) {
3630 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3631 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3632 for (; sit != sen; ++sit)
3635 tagsToClose.clear();
3639 // Finally, write the next character or inset.
3640 if (Inset const * inset = getInset(i)) {
3641 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3642 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3643 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3645 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3646 // Arguments may need to be output
3647 OutputParams np = rp;
3648 np.local_font = &font;
3650 // TODO: special case will bite here.
3651 np.docbook_in_par = true;
3652 inset->docbook(*xs, np);
3655 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3656 if (lyx::isSpace(c) && !ignore_fonts) { // Delay spaces *after* the font-tag closure for cleaner output.
3657 if (c == ' ' && (style.free_spacing || rp.free_spacing)) {
3658 delayedChars.push_back(from_ascii(" "));
3660 delayedChars.emplace_back(1, c);
3662 } else { // No need to delay the character.
3663 if (c == '\'' && !ignore_fonts)
3664 *xs << XMLStream::ESCAPE_NONE << "’";
3671 // FIXME, this code is just imported from XHTML
3672 // I'm worried about what happens if a branch, say, is itself
3673 // wrapped in some font stuff. I think that will not work.
3675 xs->closeFontTags();
3677 // Deal with the delayed characters *after* closing font tags.
3678 if (!delayedChars.empty()) {
3679 for (const docstring &c: delayedChars)
3680 *xs << XMLStream::ESCAPE_NONE << c;
3681 delayedChars.clear();
3684 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3685 // last line to get a clean output.
3686 if (rp.docbook_in_listing && !is_last_par)
3689 // Finalise the last (and most likely only) paragraph.
3690 generatedParagraphs.push_back(os.str());
3691 os.str(from_ascii(""));
3694 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3695 for (pos_type i = initial; i < size(); ++i) {
3696 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3697 const InsetArgument * arg = getInset(i)->asInsetArgument();
3698 if (arg->docbookargumentaftermaintag()) {
3699 // Don't use rp, as this argument would not generate anything.
3700 auto xs_local = XMLStream(os);
3701 arg->docbook(xs_local, runparams);
3703 appendedParagraphs.push_back(os.str());
3704 os.str(from_ascii(""));
3709 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3715 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3716 vector<xml::EndFontTag> & tagsToClose,
3717 bool & flag, FontState curstate, xml::FontTypes type)
3719 if (curstate == FONT_ON) {
3720 tagsToOpen.push_back(xhtmlStartFontTag(type));
3723 tagsToClose.push_back(xhtmlEndFontTag(type));
3728 } // anonymous namespace
3731 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3733 OutputParams const & runparams,
3734 Font const & outerfont,
3735 bool start_paragraph, bool close_paragraph,
3736 pos_type initial) const
3740 // track whether we have opened these tags
3741 bool emph_flag = false;
3742 bool bold_flag = false;
3743 bool noun_flag = false;
3744 bool ubar_flag = false;
3745 bool dbar_flag = false;
3746 bool sout_flag = false;
3747 bool xout_flag = false;
3748 bool wave_flag = false;
3750 bool shap_flag = false;
3752 bool faml_flag = false;
3754 bool size_flag = false;
3756 Layout const & style = *d->layout_;
3758 if (start_paragraph)
3759 xs.startDivision(allowEmpty());
3762 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3764 FontShape curr_fs = INHERIT_SHAPE;
3765 FontFamily curr_fam = INHERIT_FAMILY;
3766 FontSize curr_size = INHERIT_SIZE;
3768 string const default_family =
3769 buf.masterBuffer()->params().fonts_default_family;
3771 vector<xml::FontTag> tagsToOpen;
3772 vector<xml::EndFontTag> tagsToClose;
3774 // parsing main loop
3775 for (pos_type i = initial; i < size(); ++i) {
3776 // let's not show deleted material in the output
3780 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3783 FontState curstate = font.fontInfo().emph();
3784 if (font_old.emph() != curstate)
3785 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3788 curstate = font.fontInfo().noun();
3789 if (font_old.noun() != curstate)
3790 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3793 curstate = font.fontInfo().underbar();
3794 if (font_old.underbar() != curstate)
3795 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3798 curstate = font.fontInfo().strikeout();
3799 if (font_old.strikeout() != curstate)
3800 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3803 curstate = font.fontInfo().xout();
3804 if (font_old.xout() != curstate)
3805 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3808 curstate = font.fontInfo().uuline();
3809 if (font_old.uuline() != curstate)
3810 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3813 curstate = font.fontInfo().uwave();
3814 if (font_old.uwave() != curstate)
3815 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3818 // a little hackish, but allows us to reuse what we have.
3819 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3820 if (font_old.series() != font.fontInfo().series())
3821 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3824 curr_fs = font.fontInfo().shape();
3825 FontShape old_fs = font_old.shape();
3826 if (old_fs != curr_fs) {
3830 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3833 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3835 case SMALLCAPS_SHAPE:
3836 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3842 // the other tags are for internal use
3850 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3854 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3857 case SMALLCAPS_SHAPE:
3858 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3865 // the other tags are for internal use
3872 curr_fam = font.fontInfo().family();
3873 FontFamily old_fam = font_old.family();
3874 if (old_fam != curr_fam) {
3878 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3881 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3883 case TYPEWRITER_FAMILY:
3884 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3886 case INHERIT_FAMILY:
3889 // the other tags are for internal use
3897 // we will treat a "default" font family as roman, since we have
3898 // no other idea what to do.
3899 if (default_family != "rmdefault" && default_family != "default") {
3900 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3905 if (default_family != "sfdefault") {
3906 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3910 case TYPEWRITER_FAMILY:
3911 if (default_family != "ttdefault") {
3912 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3916 case INHERIT_FAMILY:
3919 // the other tags are for internal use
3926 curr_size = font.fontInfo().size();
3927 FontSize old_size = font_old.size();
3928 if (old_size != curr_size) {
3932 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3935 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3938 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3941 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3944 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3947 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3950 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3953 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3956 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3959 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3962 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3968 // the other tags are for internal use
3974 switch (curr_size) {
3976 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3980 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3984 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3988 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3992 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3996 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
4000 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
4004 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
4008 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
4012 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
4016 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
4023 // the other tags are for internal use
4030 // Other such tags? What about the other text ranges?
4032 for (auto const & t : tagsToClose)
4034 for (auto const & t : tagsToOpen)
4036 tagsToClose.clear();
4039 Inset const * inset = getInset(i);
4041 if (!runparams.for_toc || inset->isInToc()) {
4042 OutputParams np = runparams;
4043 np.local_font = &font;
4044 // If the paragraph has size 1, then we are in the "special
4045 // case" where we do not output the containing paragraph info
4046 if (!inset->getLayout().htmlisblock() && size() != 1)
4047 np.html_in_par = true;
4048 retval += inset->xhtml(xs, np);
4051 char_type c = getUChar(buf.masterBuffer()->params(),
4053 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
4054 xs << XMLStream::ESCAPE_NONE << " ";
4056 xs << XMLStream::ESCAPE_NONE << "’";
4060 font_old = font.fontInfo();
4064 // I'm worried about what happens if a branch, say, is itself
4065 // wrapped in some font stuff. I think that will not work.
4067 if (close_paragraph)
4074 bool Paragraph::isHfill(pos_type pos) const
4076 Inset const * inset = getInset(pos);
4077 return inset && inset->isHfill();
4081 bool Paragraph::isNewline(pos_type pos) const
4083 // U+2028 LINE SEPARATOR
4084 // U+2029 PARAGRAPH SEPARATOR
4085 char_type const c = d->text_[pos];
4086 if (c == 0x2028 || c == 0x2029)
4088 Inset const * inset = getInset(pos);
4089 return inset && inset->lyxCode() == NEWLINE_CODE;
4093 bool Paragraph::isEnvSeparator(pos_type pos) const
4095 Inset const * inset = getInset(pos);
4096 return inset && inset->lyxCode() == SEPARATOR_CODE;
4100 bool Paragraph::isLineSeparator(pos_type pos) const
4102 char_type const c = d->text_[pos];
4103 if (isLineSeparatorChar(c))
4105 Inset const * inset = getInset(pos);
4106 return inset && inset->isLineSeparator();
4110 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4114 if (ignore_deleted && isDeleted(pos))
4116 if (Inset const * inset = getInset(pos))
4117 return !inset->isLetter();
4118 // if we have a hard hyphen (no en- or emdash) or apostrophe
4119 // we pass this to the spell checker
4120 // FIXME: this method is subject to change, visit
4121 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4122 // to get an impression how complex this is.
4123 if (isHardHyphenOrApostrophe(pos))
4125 char_type const c = d->text_[pos];
4126 // We want to pass the escape chars to the spellchecker
4127 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4128 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4132 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4134 pos_type const psize = size();
4137 char_type const c = d->text_[pos];
4138 if (c != '-' && c != '\'')
4140 pos_type nextpos = pos + 1;
4141 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4142 if ((nextpos == psize || isSpace(nextpos))
4143 && (pos == 0 || isSpace(prevpos)))
4149 bool Paragraph::needsCProtection(bool const fragile) const
4151 // first check the layout of the paragraph, but only in insets
4152 InsetText const * textinset = inInset().asInsetText();
4153 bool const maintext = textinset
4154 ? textinset->text().isMainText()
4157 if (!maintext && layout().needcprotect) {
4158 // Environments need cprotection regardless the content
4159 if (layout().latextype == LATEX_ENVIRONMENT)
4162 // Commands need cprotection if they contain specific chars
4163 int const nchars_escape = 9;
4164 static char_type const chars_escape[nchars_escape] = {
4165 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4167 docstring const pars = asString();
4168 for (int k = 0; k < nchars_escape; k++) {
4169 if (contains(pars, chars_escape[k]))
4174 // now check whether we have insets that need cprotection
4175 for (auto const & icit : d->insetlist_) {
4176 Inset const * ins = icit.inset;
4179 if (ins->needsCProtection(maintext, fragile))
4187 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4189 return d->speller_state_.getRange(pos);
4193 bool Paragraph::isChar(pos_type pos) const
4195 if (Inset const * inset = getInset(pos))
4196 return inset->isChar();
4197 char_type const c = d->text_[pos];
4198 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4202 bool Paragraph::isSpace(pos_type pos) const
4204 if (Inset const * inset = getInset(pos))
4205 return inset->isSpace();
4206 char_type const c = d->text_[pos];
4207 return lyx::isSpace(c);
4212 Paragraph::getParLanguage(BufferParams const & bparams) const
4215 return getFirstFontSettings(bparams).language();
4216 // FIXME: we should check the prev par as well (Lgb)
4217 return bparams.language;
4221 bool Paragraph::isRTL(BufferParams const & bparams) const
4223 return getParLanguage(bparams)->rightToLeft()
4224 && !inInset().getLayout().forceLTR();
4228 void Paragraph::changeLanguage(BufferParams const & bparams,
4229 Language const * from, Language const * to)
4231 // change language including dummy font change at the end
4232 for (pos_type i = 0; i <= size(); ++i) {
4233 Font font = getFontSettings(bparams, i);
4234 if (font.language() == from) {
4235 font.setLanguage(to);
4237 d->requestSpellCheck(i);
4243 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4245 Language const * doc_language = bparams.language;
4246 for (auto const & f : d->fontlist_)
4247 if (f.font().language() != ignore_language &&
4248 f.font().language() != latex_language &&
4249 f.font().language() != doc_language)
4255 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4257 for (auto const & f : d->fontlist_) {
4258 Language const * lang = f.font().language();
4259 if (lang != ignore_language &&
4260 lang != latex_language)
4266 docstring Paragraph::asString(int options) const
4268 return asString(0, size(), options);
4272 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4274 odocstringstream os;
4277 && options & AS_STR_LABEL
4278 && !d->params_.labelString().empty())
4279 os << d->params_.labelString() << ' ';
4281 for (pos_type i = beg; i < end; ++i) {
4282 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4284 char_type const c = d->text_[i];
4285 if (isPrintable(c) || c == '\t'
4286 || (c == '\n' && (options & AS_STR_NEWLINES)))
4288 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4289 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4290 LASSERT(runparams != nullptr, return docstring());
4291 if (runparams->find_effective())
4292 getInset(i)->toString(os);
4294 getInset(i)->plaintext(os, *runparams);
4295 } else if (c == META_INSET && (options & AS_STR_MATHED)
4296 && getInset(i)->lyxCode() == REF_CODE) {
4297 Buffer const & buf = getInset(i)->buffer();
4298 OutputParams rp(&buf.params().encoding());
4299 Font const font(inherit_font, buf.params().language);
4300 rp.local_font = &font;
4302 getInset(i)->latex(ots, rp);
4304 getInset(i)->toString(os);
4313 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4314 bool const shorten, bool const label) const
4316 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4317 if (label && !labelString().empty())
4318 os += labelString() + ' ';
4319 if (!layout().isTocCaption())
4321 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4324 char_type const c = d->text_[i];
4327 else if (c == META_INSET)
4328 getInset(i)->forOutliner(os, tmplen, false);
4331 Text::shortenForOutliner(os, maxlen);
4335 void Paragraph::setInsetOwner(Inset const * inset)
4337 d->inset_owner_ = inset;
4341 int Paragraph::id() const
4347 void Paragraph::setId(int id)
4353 Layout const & Paragraph::layout() const
4359 void Paragraph::setLayout(Layout const & layout)
4361 d->layout_ = &layout;
4365 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4367 setLayout(tc.defaultLayout());
4371 void Paragraph::setPlainLayout(DocumentClass const & tc)
4373 setLayout(tc.plainLayout());
4377 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4379 if (usePlainLayout())
4382 setDefaultLayout(tc);
4386 Inset const & Paragraph::inInset() const
4388 LBUFERR(d->inset_owner_);
4389 return *d->inset_owner_;
4393 ParagraphParameters & Paragraph::params()
4399 ParagraphParameters const & Paragraph::params() const
4405 bool Paragraph::isFreeSpacing() const
4407 if (d->layout_->free_spacing)
4409 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4413 bool Paragraph::allowEmpty() const
4415 if (d->layout_->keepempty)
4417 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4421 bool Paragraph::brokenBiblio() const
4423 // There is a problem if there is no bibitem at position 0 in
4424 // paragraphs that need one, if there is another bibitem in the
4425 // paragraph or if this paragraph is not supposed to have
4426 // a bibitem inset at all.
4427 return ((d->layout_->labeltype == LABEL_BIBLIO
4428 && (d->insetlist_.find(BIBITEM_CODE) != 0
4429 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4430 || (d->layout_->labeltype != LABEL_BIBLIO
4431 && d->insetlist_.find(BIBITEM_CODE) != -1));
4435 int Paragraph::fixBiblio(Buffer const & buffer)
4437 // FIXME: when there was already an inset at 0, the return value is 1,
4438 // which does not tell whether another inset has been removed; the
4439 // cursor cannot be correctly updated.
4441 bool const track_changes = buffer.params().track_changes;
4442 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4444 // The case where paragraph is not BIBLIO
4445 if (d->layout_->labeltype != LABEL_BIBLIO) {
4446 if (bibitem_pos == -1)
4447 // No InsetBibitem => OK
4449 // There is an InsetBibitem: remove it!
4450 d->insetlist_.release(bibitem_pos);
4451 eraseChar(bibitem_pos, track_changes);
4452 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4455 bool const hasbibitem0 = bibitem_pos == 0;
4457 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4458 // There was an InsetBibitem at pos 0,
4459 // and no other one => OK
4460 if (bibitem_pos == -1)
4462 // there is a bibitem at the 0 position, but since
4463 // there is a second one, we copy the second on the
4464 // first. We're assuming there are at most two of
4465 // these, which there should be.
4466 // FIXME: why does it make sense to do that rather
4467 // than keep the first? (JMarc)
4468 Inset * inset = releaseInset(bibitem_pos);
4469 d->insetlist_.begin()->inset = inset;
4470 // This needs to be done to update the counter (#8499)
4471 buffer.updateBuffer();
4472 return -bibitem_pos;
4475 // We need to create an inset at the beginning
4476 Inset * inset = nullptr;
4477 if (bibitem_pos > 0) {
4478 // there was one somewhere in the paragraph, let's move it
4479 inset = d->insetlist_.release(bibitem_pos);
4480 eraseChar(bibitem_pos, track_changes);
4483 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4484 InsetCommandParams(BIBITEM_CODE));
4486 Font font(inherit_font, buffer.params().language);
4487 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4488 : Change::UNCHANGED));
4490 // This is needed to get the counters right
4491 buffer.updateBuffer();
4496 void Paragraph::checkAuthors(AuthorList const & authorList)
4498 d->changes_.checkAuthors(authorList);
4502 bool Paragraph::isChanged(pos_type pos) const
4504 return lookupChange(pos).changed();
4508 bool Paragraph::isInserted(pos_type pos) const
4510 return lookupChange(pos).inserted();
4514 bool Paragraph::isDeleted(pos_type pos) const
4516 return lookupChange(pos).deleted();
4520 InsetList const & Paragraph::insetList() const
4522 return d->insetlist_;
4526 void Paragraph::setInsetBuffers(Buffer & b)
4528 d->insetlist_.setBuffer(b);
4532 void Paragraph::resetBuffer()
4534 d->insetlist_.resetBuffer();
4538 Inset * Paragraph::releaseInset(pos_type pos)
4540 Inset * inset = d->insetlist_.release(pos);
4541 /// does not honour change tracking!
4542 eraseChar(pos, false);
4547 Inset * Paragraph::getInset(pos_type pos)
4549 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4550 ? d->insetlist_.get(pos) : nullptr;
4554 Inset const * Paragraph::getInset(pos_type pos) const
4556 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4557 ? d->insetlist_.get(pos) : nullptr;
4561 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4562 pos_type & right, TextCase action)
4564 // process sequences of modified characters; in change
4565 // tracking mode, this approach results in much better
4566 // usability than changing case on a char-by-char basis
4567 // We also need to track the current font, since font
4568 // changes within sequences can occur.
4569 vector<pair<char_type, Font> > changes;
4571 bool const trackChanges = bparams.track_changes;
4573 bool capitalize = true;
4575 for (; pos < right; ++pos) {
4576 char_type oldChar = d->text_[pos];
4577 char_type newChar = oldChar;
4579 // ignore insets and don't play with deleted text!
4580 if (oldChar != META_INSET && !isDeleted(pos)) {
4582 case text_lowercase:
4583 newChar = lowercase(oldChar);
4585 case text_capitalization:
4587 newChar = uppercase(oldChar);
4591 case text_uppercase:
4592 newChar = uppercase(oldChar);
4597 if (isWordSeparator(pos) || isDeleted(pos)) {
4598 // permit capitalization again
4602 if (oldChar != newChar) {
4603 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4604 if (pos != right - 1)
4606 // step behind the changing area
4610 int erasePos = pos - changes.size();
4611 for (auto const & change : changes) {
4612 insertChar(pos, change.first, change.second, trackChanges);
4613 if (!eraseChar(erasePos, trackChanges)) {
4616 ++right; // expand selection
4623 int Paragraph::find(docstring const & str, bool cs, bool mw,
4624 pos_type start_pos, bool del) const
4626 pos_type pos = start_pos;
4627 int const strsize = str.length();
4629 pos_type const parsize = d->text_.size();
4630 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4631 // ignore deleted matter
4632 if (!del && isDeleted(pos)) {
4633 if (pos == parsize - 1)
4639 // Ignore "invisible" letters such as ligature breaks
4640 // and hyphenation chars while searching
4641 bool nonmatch = false;
4642 while (pos < parsize && isInset(pos)) {
4643 Inset const * inset = getInset(pos);
4644 if (!inset->isLetter() && !inset->isChar())
4646 odocstringstream os;
4647 if (inset->lyxCode() == lyx::QUOTE_CODE) {
4649 op.find_set_feature(OutputParams::SearchQuick);
4650 inset->plaintext(os, op);
4653 inset->toString(os);
4655 docstring const insetstring = os.str();
4656 if (!insetstring.empty()) {
4657 int const insetstringsize = insetstring.length();
4658 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4659 if ((cs && str[i] != insetstring[j])
4660 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4668 if (nonmatch || i == strsize)
4670 char_type dp = d->text_[pos];
4671 if (cs && str[i] != dp)
4673 if (!cs && uppercase(str[i]) != uppercase(dp))
4680 // if necessary, check whether string matches word
4682 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4685 && !isWordSeparator(pos))
4689 return pos - start_pos;
4693 char_type Paragraph::getChar(pos_type pos) const
4695 return d->text_[pos];
4699 pos_type Paragraph::size() const
4701 return d->text_.size();
4705 bool Paragraph::empty() const
4707 return d->text_.empty();
4711 bool Paragraph::isInset(pos_type pos) const
4713 return d->text_[pos] == META_INSET;
4717 bool Paragraph::isSeparator(pos_type pos) const
4719 //FIXME: Are we sure this can be the only separator?
4720 return d->text_[pos] == ' ';
4724 void Paragraph::deregisterWords()
4726 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4727 Private::LangWordsMap::const_iterator ite = d->words_.end();
4728 for (; itl != ite; ++itl) {
4729 WordList & wl = theWordList(itl->first);
4730 Private::Words::const_iterator it = (itl->second).begin();
4731 Private::Words::const_iterator et = (itl->second).end();
4732 for (; it != et; ++it)
4739 void Paragraph::locateWord(pos_type & from, pos_type & to,
4740 word_location const loc, bool const ignore_deleted) const
4743 case WHOLE_WORD_STRICT:
4744 if (from == 0 || from == size()
4745 || isWordSeparator(from, ignore_deleted)
4746 || isWordSeparator(from - 1, ignore_deleted)) {
4753 // If we are already at the beginning of a word, do nothing
4754 if (!from || isWordSeparator(from - 1, ignore_deleted))
4759 // always move the cursor to the beginning of previous word
4760 while (from && !isWordSeparator(from - 1, ignore_deleted))
4764 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4767 // no need to move the 'from' cursor
4771 while (to < size() && !isWordSeparator(to, ignore_deleted))
4776 void Paragraph::collectWords()
4778 for (pos_type pos = 0; pos < size(); ++pos) {
4779 if (isWordSeparator(pos))
4781 pos_type from = pos;
4782 locateWord(from, pos, WHOLE_WORD);
4783 // Work around MSVC warning: The statement
4784 // if (pos < from + lyxrc.completion_minlength)
4785 // triggers a signed vs. unsigned warning.
4786 // I don't know why this happens, it could be a MSVC bug, or
4787 // related to LLP64 (windows) vs. LP64 (unix) programming
4788 // model, or the C++ standard might be ambigous in the section
4789 // defining the "usual arithmetic conversions". However, using
4790 // a temporary variable is safe and works on all compilers.
4791 pos_type const endpos = from + lyxrc.completion_minlength;
4794 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4795 if (cit == d->fontlist_.end())
4797 Language const * lang = cit->font().language();
4798 docstring const word = asString(from, pos, AS_STR_NONE);
4799 d->words_[lang->lang()].insert(word);
4804 void Paragraph::registerWords()
4806 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4807 Private::LangWordsMap::const_iterator ite = d->words_.end();
4808 for (; itl != ite; ++itl) {
4809 WordList & wl = theWordList(itl->first);
4810 Private::Words::const_iterator it = (itl->second).begin();
4811 Private::Words::const_iterator et = (itl->second).end();
4812 for (; it != et; ++it)
4818 void Paragraph::updateWords()
4826 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4828 SkipPositionsIterator begin = skips.begin();
4829 SkipPositions::iterator end = skips.end();
4830 if (pos > 0 && begin < end) {
4832 if (end->last == pos - 1) {
4837 skips.insert(end, FontSpan(pos, pos));
4841 Language * Paragraph::Private::locateSpellRange(
4842 pos_type & from, pos_type & to,
4843 SkipPositions & skips) const
4845 // skip leading white space
4846 while (from < to && owner_->isWordSeparator(from))
4848 // don't check empty range
4851 // get current language
4852 Language * lang = getSpellLanguage(from);
4853 pos_type last = from;
4854 bool samelang = true;
4855 bool sameinset = true;
4856 while (last < to && samelang && sameinset) {
4857 // hop to end of word
4858 while (last < to && !owner_->isWordSeparator(last)) {
4859 Inset const * inset = owner_->getInset(last);
4860 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4861 // check for "invisible" letters such as ligature breaks
4862 odocstringstream os;
4863 inset->toString(os);
4864 if (os.str().length() != 0) {
4865 // avoid spell check of visible special char insets
4866 // stop the loop in front of the special char inset
4871 appendSkipPosition(skips, last);
4872 } else if (owner_->isDeleted(last)) {
4873 appendSkipPosition(skips, last);
4877 // hop to next word while checking for insets
4878 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4879 if (Inset const * inset = owner_->getInset(last))
4880 sameinset = inset->isChar() && inset->isLetter();
4881 if (sameinset && owner_->isDeleted(last)) {
4882 appendSkipPosition(skips, last);
4887 if (sameinset && last < to) {
4888 // now check for language change
4889 samelang = lang == getSpellLanguage(last);
4892 // if language change detected backstep is needed
4900 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4903 const_cast<Language *>(owner_->getFontSettings(
4904 inset_owner_->buffer().params(), from).language());
4905 if (lang == inset_owner_->buffer().params().language
4906 && !lyxrc.spellchecker_alt_lang.empty()) {
4908 string const lang_variety =
4909 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4910 lang->setCode(lang_code);
4911 lang->setVariety(lang_variety);
4917 void Paragraph::requestSpellCheck(pos_type pos)
4919 d->requestSpellCheck(pos);
4921 // Also request spellcheck within (text) insets
4922 for (auto const & insets : insetList()) {
4923 if (!insets.inset->asInsetText())
4925 ParagraphList & inset_pars =
4926 insets.inset->asInsetText()->paragraphs();
4927 ParagraphList::iterator pit = inset_pars.begin();
4928 ParagraphList::iterator pend = inset_pars.end();
4929 for (; pit != pend; ++pit)
4930 pit->requestSpellCheck();
4936 bool Paragraph::needsSpellCheck() const
4938 SpellChecker::ChangeNumber speller_change_number = 0;
4939 if (theSpellChecker())
4940 speller_change_number = theSpellChecker()->changeNumber();
4941 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4942 d->speller_state_.needsCompleteRefresh(speller_change_number);
4944 return d->needsSpellCheck();
4948 bool Paragraph::Private::ignoreWord(docstring const & word) const
4950 // Ignore words with digits
4951 // FIXME: make this customizable
4952 // (note that some checkers ignore words with digits by default)
4953 docstring::const_iterator cit = word.begin();
4954 docstring::const_iterator const end = word.end();
4955 for (; cit != end; ++cit) {
4956 if (isNumber((*cit)))
4963 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4964 WordLangTuple & wl, docstring_list & suggestions,
4965 bool do_suggestion, bool check_learned) const
4967 SpellChecker::Result result = SpellChecker::WORD_OK;
4968 SpellChecker * speller = theSpellChecker();
4972 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4975 locateWord(from, to, WHOLE_WORD, true);
4976 if (from == to || from >= size())
4979 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4980 Language * lang = d->getSpellLanguage(from);
4982 BufferParams const & bparams = d->inset_owner_->buffer().params();
4984 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4987 wl = WordLangTuple(word, lang);
4992 if (needsSpellCheck() || check_learned) {
4994 if (!d->ignoreWord(word)) {
4995 bool const trailing_dot = to < size() && d->text_[to] == '.';
4996 result = speller->check(wl, bparams.spellignore());
4997 if (SpellChecker::misspelled(result) && trailing_dot) {
4998 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4999 result = speller->check(wl, bparams.spellignore());
5000 if (!SpellChecker::misspelled(result)) {
5001 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
5003 from << ".." << to << "]");
5005 // spell check with dot appended failed too
5006 // restore original word/lang value
5007 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
5008 wl = WordLangTuple(word, lang);
5012 if (!SpellChecker::misspelled(result)) {
5013 // area up to the begin of the next word is not misspelled
5014 while (end < size() && isWordSeparator(end))
5017 d->setMisspelled(from, end, result);
5019 result = d->speller_state_.getState(from);
5023 suggestions.clear();
5025 if (SpellChecker::misspelled(result)) {
5026 LYXERR(Debug::GUI, "misspelled word: \"" <<
5028 from << ".." << to << "]");
5030 speller->suggest(wl, suggestions);
5036 void Paragraph::anonymize()
5038 // This is a very crude anonymization for now
5039 for (char_type & c : d->text_)
5040 if (isLetterChar(c) || isNumber(c))
5045 void Paragraph::Private::markMisspelledWords(
5046 Language const * lang,
5047 pos_type const & first, pos_type const & last,
5048 SpellChecker::Result result,
5049 docstring const & word,
5050 SkipPositions const & skips)
5052 if (!SpellChecker::misspelled(result)) {
5053 setMisspelled(first, last, SpellChecker::WORD_OK);
5057 SpellChecker * speller = theSpellChecker();
5058 // locate and enumerate the error positions
5059 int nerrors = speller->numMisspelledWords();
5061 SkipPositionsIterator it = skips.begin();
5062 SkipPositionsIterator et = skips.end();
5063 for (int index = 0; index < nerrors; ++index) {
5066 speller->misspelledWord(index, wstart, wlen);
5067 /// should not happen if speller supports range checks
5070 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
5071 wstart += first + numskipped;
5072 if (snext < wstart) {
5073 /// mark the range of correct spelling
5074 numskipped += countSkips(it, et, wstart);
5075 setMisspelled(snext,
5076 wstart - 1, SpellChecker::WORD_OK);
5078 snext = wstart + wlen;
5079 // Check whether the candidate is in the document's local dict
5080 SpellChecker::Result actresult = result;
5081 if (inset_owner_->buffer().params().spellignored(candidate))
5082 actresult = SpellChecker::DOCUMENT_LEARNED_WORD;
5083 numskipped += countSkips(it, et, snext);
5084 /// mark the range of misspelling
5085 setMisspelled(wstart, snext, actresult);
5086 if (actresult == SpellChecker::DOCUMENT_LEARNED_WORD)
5087 LYXERR(Debug::GUI, "local dictionary word: \"" <<
5088 candidate.word() << "\" [" <<
5089 wstart << ".." << (snext-1) << "]");
5091 LYXERR(Debug::GUI, "misspelled word: \"" <<
5092 candidate.word() << "\" [" <<
5093 wstart << ".." << (snext-1) << "]");
5096 if (snext <= last) {
5097 /// mark the range of correct spelling at end
5098 setMisspelled(snext, last, SpellChecker::WORD_OK);
5103 void Paragraph::spellCheck() const
5105 SpellChecker * speller = theSpellChecker();
5106 if (!speller || empty() ||!needsSpellCheck())
5110 d->rangeOfSpellCheck(start, endpos);
5111 if (speller->canCheckParagraph()) {
5112 // loop until we leave the range
5113 for (pos_type first = start; first < endpos; ) {
5114 pos_type last = endpos;
5115 Private::SkipPositions skips;
5116 Language * lang = d->locateSpellRange(first, last, skips);
5117 if (first >= endpos)
5119 // start the spell checker on the unit of meaning
5120 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5121 WordLangTuple wl = WordLangTuple(word, lang);
5122 BufferParams const & bparams = d->inset_owner_->buffer().params();
5123 SpellChecker::Result result = !word.empty() ?
5124 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5125 d->markMisspelledWords(lang, first, last, result, word, skips);
5129 static docstring_list suggestions;
5130 pos_type to = endpos;
5131 while (start < endpos) {
5133 spellCheck(start, to, wl, suggestions, false);
5137 d->readySpellCheck();
5141 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5143 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5144 if (result || pos <= 0 || pos > size())
5146 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5147 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5152 string Paragraph::magicLabel() const
5155 ss << "magicparlabel-" << id();