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"
40 #include "SpellChecker.h"
41 #include "texstream.h"
44 #include "TextClass.h"
45 #include "WordLangTuple.h"
48 #include "frontends/alert.h"
50 #include "insets/InsetArgument.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
54 #include "insets/InsetText.h"
56 #include "mathed/InsetMathHull.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
71 using namespace lyx::support;
73 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
74 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
75 #define THREAD_LOCAL_STATIC static __thread
76 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
77 #define THREAD_LOCAL_STATIC static __declspec(thread)
79 #define THREAD_LOCAL_STATIC thread_local static
84 /////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////
90 class SpellResultRange {
92 SpellResultRange(FontSpan range, SpellChecker::Result result)
93 : range_(range), result_(result)
96 FontSpan const & range() const { return range_; }
98 void range(FontSpan const & r) { range_ = r; }
100 SpellChecker::Result result() const { return result_; }
102 void result(SpellChecker::Result r) { result_ = r; }
104 bool contains(pos_type pos) const { return range_.contains(pos); }
106 bool covered(FontSpan const & r) const
108 // 1. first of new range inside current range or
109 // 2. last of new range inside current range or
110 // 3. first of current range inside new range or
111 // 4. last of current range inside new range
112 //FIXME: is this the same as !range_.intersect(r).empty() ?
113 return range_.contains(r.first) || range_.contains(r.last) ||
114 r.contains(range_.first) || r.contains(range_.last);
117 void shift(pos_type pos, int offset)
119 if (range_.first > pos) {
120 range_.first += offset;
121 range_.last += offset;
122 } else if (range_.last >= pos) {
123 range_.last += offset;
128 SpellChecker::Result result_ ;
132 /////////////////////////////////////////////////////////////////////
136 /////////////////////////////////////////////////////////////////////
138 class SpellCheckerState {
142 needs_refresh_ = true;
143 current_change_number_ = 0;
146 void setRange(FontSpan const & fp, SpellChecker::Result state)
149 RangesIterator et = ranges_.end();
150 RangesIterator it = ranges_.begin();
151 for (; it != et; ++it) {
152 if (!it->covered(fp))
153 result.push_back(SpellResultRange(it->range(), it->result()));
154 else if (state == SpellChecker::WORD_OK) {
155 // trim or split the current misspelled range
156 // store misspelled ranges only
157 FontSpan range = it->range();
158 if (fp.first > range.first) {
159 // misspelled area in front of WORD_OK
160 range.last = fp.first - 1;
161 result.push_back(SpellResultRange(range, it->result()));
164 if (fp.last < range.last) {
165 // misspelled area after WORD_OK range
166 range.first = fp.last + 1;
167 result.push_back(SpellResultRange(range, it->result()));
172 if (state != SpellChecker::WORD_OK)
173 ranges_.push_back(SpellResultRange(fp, state));
176 void increasePosAfterPos(pos_type pos)
178 correctRangesAfterPos(pos, 1);
182 void decreasePosAfterPos(pos_type pos)
184 correctRangesAfterPos(pos, -1);
188 void refreshLast(pos_type pos)
190 if (pos < refresh_.last)
194 SpellChecker::Result getState(pos_type pos) const
196 SpellChecker::Result result = SpellChecker::WORD_OK;
197 RangesIterator et = ranges_.end();
198 RangesIterator it = ranges_.begin();
199 for (; it != et; ++it) {
200 if(it->contains(pos)) {
207 FontSpan const & getRange(pos_type pos) const
209 /// empty span to indicate mismatch
210 static FontSpan empty_;
211 RangesIterator et = ranges_.end();
212 RangesIterator it = ranges_.begin();
213 for (; it != et; ++it) {
214 if(it->contains(pos)) {
221 bool needsRefresh() const
223 return needs_refresh_;
226 SpellChecker::ChangeNumber currentChangeNumber() const
228 return current_change_number_;
231 void refreshRange(pos_type & first, pos_type & last) const
233 first = refresh_.first;
234 last = refresh_.last;
237 void needsRefresh(pos_type pos)
239 if (needs_refresh_ && pos != -1) {
240 if (pos < refresh_.first)
241 refresh_.first = pos;
242 if (pos > refresh_.last)
244 } else if (pos != -1) {
245 // init request check for neighbour positions too
246 refresh_.first = pos > 0 ? pos - 1 : 0;
247 // no need for special end of paragraph check
248 refresh_.last = pos + 1;
250 needs_refresh_ = pos != -1;
253 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
255 needs_refresh_ = true;
258 current_change_number_ = change_number;
261 typedef vector<SpellResultRange> Ranges;
262 typedef Ranges::const_iterator RangesIterator;
264 /// the area of the paragraph with pending spell check
266 /// spell state cache version number
267 SpellChecker::ChangeNumber current_change_number_;
271 void correctRangesAfterPos(pos_type pos, int offset)
273 RangesIterator et = ranges_.end();
274 Ranges::iterator it = ranges_.begin();
275 for (; it != et; ++it) {
276 it->shift(pos, offset);
282 /////////////////////////////////////////////////////////////////////
284 // Paragraph::Private
286 /////////////////////////////////////////////////////////////////////
288 class Paragraph::Private
290 // Enforce our own "copy" constructor
291 Private(Private const &) = delete;
292 Private & operator=(Private const &) = delete;
293 // Unique ID generator
294 static int make_id();
297 Private(Paragraph * owner, Layout const & layout);
298 /// "Copy constructor"
299 Private(Private const &, Paragraph * owner);
300 /// Copy constructor from \p beg to \p end
301 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
304 void insertChar(pos_type pos, char_type c, Change const & change);
306 /// Output the surrogate pair formed by \p c and \p next to \p os.
307 /// \return the number of characters written.
308 int latexSurrogatePair(BufferParams const &, otexstream & os,
309 char_type c, char_type next,
310 OutputParams const &);
312 /// Output a space in appropriate formatting (or a surrogate pair
313 /// if the next character is a combining character).
314 /// \return whether a surrogate pair was output.
315 bool simpleTeXBlanks(BufferParams const &,
316 OutputParams const &,
319 unsigned int & column,
321 Layout const & style);
323 /// This could go to ParagraphParameters if we want to.
324 int startTeXParParams(BufferParams const &, otexstream &,
325 OutputParams const &) const;
327 /// This could go to ParagraphParameters if we want to.
328 bool endTeXParParams(BufferParams const &, otexstream &,
329 OutputParams const &) const;
332 void latexInset(BufferParams const &,
337 Font const & outerfont,
339 Change & running_change,
340 Layout const & style,
342 unsigned int & column,
343 bool const fontswitch_inset,
344 bool const closeLanguage,
345 bool const lang_switched_at_inset);
348 void latexSpecialChar(
350 BufferParams const & bparams,
351 OutputParams const & runparams,
352 Font const & running_font,
353 string & alien_script,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column) const;
370 unsigned int & column) const;
376 unsigned int & column) const;
379 void validate(LaTeXFeatures & features) const;
381 /// Checks if the paragraph contains only text and no inset or font change.
382 bool onlyText(Buffer const & buf, Font const & outerfont,
383 pos_type initial) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD, true);
445 owner_->locateWord(last, endpos, WHOLE_WORD, true);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 long skip = it->last - it->first + 1;
463 void markMisspelledWords(Language const * lang,
464 pos_type const & first, pos_type const & last,
465 SpellChecker::Result result,
466 docstring const & word,
467 SkipPositions const & skips,
468 vector<WordLangTuple> const & docdict);
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);
839 bool Paragraph::insertInset(pos_type pos, Inset * inset,
840 Font const & font, Change const & change)
842 LASSERT(inset, return false);
843 LASSERT(pos >= 0 && pos <= size(), return false);
845 // Make sure that Buffer::hasChangesPresent is updated
846 ChangesMonitor cm(*this);
848 // Paragraph::insertInset() can be used in cut/copy/paste operation where
849 // d->inset_owner_ is not set yet.
850 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
853 d->insertChar(pos, META_INSET, change);
854 LASSERT(d->text_[pos] == META_INSET, return false);
856 // Add a new entry in the insetlist_.
857 d->insetlist_.insert(inset, pos);
859 // Some insets require run of spell checker
860 requestSpellCheck(pos);
866 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
868 LASSERT(pos >= 0 && pos <= size(), return false);
870 // Make sure that Buffer::hasChangesPresent is updated
871 ChangesMonitor cm(*this);
873 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
876 Change change = d->changes_.lookup(pos);
878 // set the character to DELETED if
879 // a) it was previously unchanged or
880 // b) it was inserted by a co-author
882 if (!change.changed() ||
883 (change.inserted() && !change.currentAuthor())) {
884 setChange(pos, Change(Change::DELETED));
885 // request run of spell checker
886 requestSpellCheck(pos);
890 if (change.deleted())
894 // Don't physically access the imaginary end-of-paragraph character.
895 // eraseChar() can only mark it as DELETED. A physical deletion of
896 // end-of-par must be handled externally.
902 d->changes_.erase(pos);
904 // if it is an inset, delete the inset entry
905 if (d->text_[pos] == META_INSET)
906 d->insetlist_.erase(pos);
908 d->text_.erase(d->text_.begin() + pos);
910 // Update the fontlist_
911 d->fontlist_.erase(pos);
913 // Update the insetlist_
914 d->insetlist_.decreasePosAfterPos(pos);
916 // Update list of misspelled positions
917 d->speller_state_.decreasePosAfterPos(pos);
918 d->speller_state_.refreshLast(size());
924 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
926 LASSERT(start >= 0 && start <= size(), return 0);
927 LASSERT(end >= start && end <= size() + 1, return 0);
930 for (pos_type count = end - start; count; --count) {
931 if (!eraseChar(i, trackChanges))
938 // Handle combining characters
939 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
940 otexstream & os, char_type c, char_type next,
941 OutputParams const & runparams)
943 // Writing next here may circumvent a possible font change between
944 // c and next. Since next is only output if it forms a surrogate pair
945 // with c we can ignore this:
946 // A font change inside a surrogate pair does not make sense and is
947 // hopefully impossible to input.
948 // FIXME: change tracking
949 // Is this correct WRT change tracking?
950 Encoding const & encoding = *(runparams.encoding);
951 docstring latex1 = encoding.latexChar(next).first;
952 if (runparams.inIPA) {
953 string const tipashortcut = Encodings::TIPAShortcut(next);
954 if (!tipashortcut.empty()) {
955 latex1 = from_ascii(tipashortcut);
958 docstring latex2 = encoding.latexChar(c).first;
960 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
961 // Encoding supports the combination:
962 // output as is (combining char after base char).
963 os << latex2 << latex1;
964 return latex1.length() + latex2.length();
967 os << latex1 << "{" << latex2 << "}";
968 return latex1.length() + latex2.length() + 2;
972 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
973 OutputParams const & runparams,
976 unsigned int & column,
978 Layout const & style)
980 if (style.pass_thru || runparams.pass_thru)
983 if (i + 1 < int(text_.size())) {
984 char_type next = text_[i + 1];
985 if (Encodings::isCombiningChar(next)) {
986 // This space has an accent, so we must always output it.
987 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
992 if (runparams.linelen > 0
993 && column > runparams.linelen
995 && text_[i - 1] != ' '
996 && (i + 1 < int(text_.size()))
997 // same in FreeSpacing mode
998 && !owner_->isFreeSpacing()
999 // In typewriter mode, we want to avoid
1000 // ! . ? : at the end of a line
1001 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1002 && (text_[i - 1] == '.'
1003 || text_[i - 1] == '?'
1004 || text_[i - 1] == ':'
1005 || text_[i - 1] == '!'))) {
1007 os.texrow().start(owner_->id(), i + 1);
1009 } else if (style.free_spacing) {
1018 void Paragraph::Private::latexInset(BufferParams const & bparams,
1020 OutputParams & runparams,
1021 Font & running_font,
1023 Font const & outerfont,
1025 Change & running_change,
1026 Layout const & style,
1028 unsigned int & column,
1029 bool const fontswitch_inset,
1030 bool const closeLanguage,
1031 bool const lang_switched_at_inset)
1033 Inset * inset = owner_->getInset(i);
1036 if (style.pass_thru) {
1037 odocstringstream ods;
1038 inset->plaintext(ods, runparams);
1043 // FIXME: move this to InsetNewline::latex
1044 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1045 // newlines are handled differently here than
1046 // the default in simpleTeXSpecialChars().
1047 if (!style.newline_allowed) {
1051 bool needPar = false;
1052 column += running_font.latexWriteEndChanges(
1053 os, bparams, runparams,
1054 basefont, basefont, needPar);
1058 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1061 basefont = owner_->getLayoutFont(bparams, outerfont);
1062 running_font = basefont;
1064 if (runparams.moving_arg)
1068 os.texrow().start(owner_->id(), i + 1);
1072 if (owner_->isDeleted(i)) {
1073 if( ++runparams.inDeletedInset == 1)
1074 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1077 if (inset->canTrackChanges()) {
1078 column += Changes::latexMarkChange(os, bparams, running_change,
1079 Change(Change::UNCHANGED), runparams);
1080 running_change = Change(Change::UNCHANGED);
1084 odocstream::pos_type const len = os.os().tellp();
1086 if (inset->forceLTR(runparams)
1087 && running_font.isRightToLeft()
1088 // ERT is an exception, it should be output with no
1089 // decorations at all
1090 && inset->lyxCode() != ERT_CODE) {
1091 if (runparams.use_polyglossia) {
1093 } else if (running_font.language()->lang() == "farsi"
1094 || running_font.language()->lang() == "arabic_arabi")
1095 os << "\\textLR{" << termcmd;
1101 if (open_font && fontswitch_inset) {
1102 bool lang_closed = false;
1103 // Close language if needed
1104 if (closeLanguage && !lang_switched_at_inset) {
1105 // We need prev_font here as language changes directly at inset
1106 // will only be started inside the inset.
1107 Font const prev_font = (i > 0) ?
1108 owner_->getFont(bparams, i - 1, outerfont)
1110 Font tmpfont(basefont);
1111 tmpfont.setLanguage(prev_font.language());
1112 bool needPar = false;
1113 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1115 needPar, closeLanguage);
1117 lang_closed = count > 0;
1119 // Update the running_font, making sure, however,
1120 // to leave the language as it was.
1121 // FIXME: probably a better way to keep track of the old
1122 // language, than copying the entire font?
1123 Font const copy_font(running_font);
1124 basefont = owner_->getLayoutFont(bparams, outerfont);
1125 running_font = basefont;
1127 running_font.setLanguage(copy_font.language());
1128 OutputParams rp = runparams;
1129 rp.encoding = basefont.language()->encoding();
1130 // For these, we use switches, so they should be taken as
1131 // base inside the inset.
1132 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1133 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1134 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1135 // Now re-do font changes in a way needed here
1136 // (using switches with multi-par insets)
1137 InsetText const * textinset = inset->asInsetText();
1138 bool const cprotect = textinset
1139 ? textinset->hasCProtectContent(runparams.moving_arg)
1140 && !textinset->text().isMainText()
1142 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1148 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1152 runparams.local_font = &basefont;
1155 if (fontswitch_inset && !closeLanguage) {
1156 // The directionality has been switched at inset.
1157 // Force markup inside.
1158 runparams.local_font = &basefont;
1161 size_t const previous_row_count = os.texrow().rows();
1164 runparams.lastid = id_;
1165 runparams.lastpos = i;
1166 inset->latex(os, runparams);
1167 } catch (EncodingException & e) {
1168 // add location information and throw again.
1177 if (os.texrow().rows() > previous_row_count) {
1178 os.texrow().start(owner_->id(), i + 1);
1181 column += (unsigned int)(os.os().tellp() - len);
1184 if (owner_->isDeleted(i))
1185 --runparams.inDeletedInset;
1189 void Paragraph::Private::latexSpecialChar(otexstream & os,
1190 BufferParams const & bparams,
1191 OutputParams const & runparams,
1192 Font const & running_font,
1193 string & alien_script,
1194 Layout const & style,
1197 unsigned int & column)
1199 char_type const c = owner_->getUChar(bparams, runparams, i);
1201 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1202 || contains(style.pass_thru_chars, c)
1203 || contains(runparams.pass_thru_chars, c)) {
1204 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1208 os << "\\braceleft ";
1210 os << "\\braceright ";
1214 else if (c != '\0') {
1215 Encoding const * const enc = runparams.encoding;
1216 if (enc && !enc->encodable(c))
1217 throw EncodingException(c);
1223 // TIPA uses its own T3 encoding
1224 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1226 // If T1 font encoding is used, use the special
1227 // characters it provides.
1228 // NOTE: Some languages reset the font encoding internally to a
1229 // non-standard font encoding. If we are using such a language,
1230 // we do not output special T1 chars.
1231 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1232 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1233 && latexSpecialT1(c, os, i, column))
1235 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1236 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1237 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1240 // Otherwise, we use what LaTeX provides us.
1243 os << "\\textbackslash" << termcmd;
1247 os << "\\textless" << termcmd;
1251 os << "\\textgreater" << termcmd;
1255 os << "\\textbar" << termcmd;
1260 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1261 (end_pos == -1 || i + 1 < end_pos) &&
1262 text_[i+1] == '-') {
1263 // Prevent "--" becoming an en dash and "---" an em dash.
1264 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1270 os << "\\textquotedbl" << termcmd;
1275 case '%': case '#': case '{':
1283 os << "\\textasciitilde" << termcmd;
1288 os << "\\textasciicircum" << termcmd;
1295 // avoid being mistaken for optional arguments
1303 // Blanks are printed before font switching.
1304 // Sure? I am not! (try nice-latex)
1305 // I am sure it's correct. LyX might be smarter
1306 // in the future, but for now, nothing wrong is
1312 // XeTeX's dash behaviour is determined via a global setting
1313 if (bparams.use_dash_ligatures
1314 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1316 // TODO #10961: && not in inset Flex Code
1317 // TODO #10961: && not in layout LyXCode
1318 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1335 Encoding const & encoding = *(runparams.encoding);
1336 char_type next = '\0';
1337 if (i + 1 < int(text_.size())) {
1338 next = text_[i + 1];
1339 if (Encodings::isCombiningChar(next)) {
1340 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1345 pair<docstring, bool> latex = encoding.latexChar(c);
1346 docstring nextlatex;
1347 bool nexttipas = false;
1348 string nexttipashortcut;
1349 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1350 nextlatex = encoding.latexChar(next).first;
1351 if (runparams.inIPA) {
1352 nexttipashortcut = Encodings::TIPAShortcut(next);
1353 nexttipas = !nexttipashortcut.empty();
1357 if (runparams.inIPA) {
1358 string const tipashortcut = Encodings::TIPAShortcut(c);
1359 if (!tipashortcut.empty()) {
1360 latex.first = from_ascii(tipashortcut);
1361 latex.second = false;
1365 // eventually close "script wrapper" command (see `Paragraph::latex`)
1366 if (!alien_script.empty()
1367 && alien_script != Encodings::isKnownScriptChar(next)) {
1368 column += latex.first.length();
1369 alien_script.clear();
1370 os << latex.first << "}";
1374 && ((!prefixIs(nextlatex, '\\')
1375 && !prefixIs(nextlatex, '{')
1376 && !prefixIs(nextlatex, '}'))
1378 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1380 // Prevent eating of a following space or command corruption by
1381 // following characters
1382 if (next == ' ' || next == '\0') {
1383 column += latex.first.length() + 1;
1384 os << latex.first << "{}";
1386 column += latex.first.length();
1387 os << latex.first << " ";
1390 column += latex.first.length() - 1;
1398 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1399 pos_type i, unsigned int & column) const
1405 // In T1 encoding, these characters exist
1406 // but we should avoid ligatures
1407 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1409 os << "\\textcompwordmark" << termcmd;
1416 // soul.sty breaks with \char`\"
1417 os << "\\textquotedbl" << termcmd;
1426 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1427 pos_type i, unsigned int & column) const
1429 // TU encoding is currently on par with T1.
1430 return latexSpecialT1(c, os, i, column);
1434 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1435 pos_type /*i*/, unsigned int & column) const
1445 os << "\\textvertline" << termcmd;
1454 void Paragraph::Private::validate(LaTeXFeatures & features) const
1456 if (layout_->inpreamble && inset_owner_) {
1457 // FIXME: Using a string stream here circumvents the encoding
1458 // switching machinery of odocstream. Therefore the
1459 // output is wrong if this paragraph contains content
1460 // that needs to switch encoding.
1461 Buffer const & buf = inset_owner_->buffer();
1462 otexstringstream os;
1463 os << layout_->preamble();
1464 size_t const length = os.length();
1465 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1466 buf.getParFromID(owner_->id()).pit(), os,
1467 features.runparams(), string(), 0, -1, true);
1468 if (os.length() > length)
1469 features.addPreambleSnippet(os.release(), true);
1472 if (features.runparams().flavor == Flavor::Html
1473 && layout_->htmltitle()) {
1474 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1477 // check the params.
1478 if (!params_.spacing().isDefault())
1479 features.require("setspace");
1482 features.useLayout(layout_->name());
1485 fontlist_.validate(features);
1487 // then the indentation
1488 if (!params_.leftIndent().zero())
1489 features.require("ParagraphLeftIndent");
1492 InsetList::const_iterator icit = insetlist_.begin();
1493 InsetList::const_iterator iend = insetlist_.end();
1494 for (; icit != iend; ++icit) {
1496 features.inDeletedInset(owner_->isDeleted(icit->pos));
1497 if (icit->inset->lyxCode() == FOOT_CODE) {
1498 // FIXME: an item inset would make things much easier.
1499 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1500 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1501 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1502 && (icit->pos < begin_of_body_
1503 || (icit->pos == begin_of_body_
1504 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1505 features.saveNoteEnv("description");
1507 icit->inset->validate(features);
1508 features.inDeletedInset(false);
1509 if (layout_->needprotect &&
1510 icit->inset->lyxCode() == FOOT_CODE)
1511 features.require("NeedLyXFootnoteCode");
1515 // then the contents
1516 BufferParams const bp = features.runparams().is_child
1517 ? features.buffer().masterParams() : features.buffer().params();
1518 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1519 char_type c = text_[i];
1520 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1522 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1523 features.require("textquotedblp");
1524 else if (bp.main_font_encoding() != "T1"
1525 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1526 features.require("textquotedbl");
1527 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1528 // features that depend on the font or input encoding
1529 string feats = ci.textpreamble();
1530 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1531 if (fontenc.empty())
1532 fontenc = features.runparams().main_fontenc;
1533 while (!feats.empty()) {
1535 feats = split(feats, feat, ',');
1536 if (contains(feat, "!=")) {
1537 // a feature that is required except for the spcified
1538 // font or input encodings
1540 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1541 // multiple encodings are separated by semicolon
1542 vector<string> context = getVectorFromString(contexts, ";");
1543 // require feature if the context matches neither current font
1544 // nor input encoding
1545 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1546 && std::find(context.begin(), context.end(),
1547 features.runparams().encoding->name()) == context.end())
1548 features.require(realfeature);
1549 } else if (contains(feat, '=')) {
1550 // a feature that is required only for the spcified
1551 // font or input encodings
1553 string const contexts = split(feat, realfeature, '=');
1554 // multiple encodings are separated by semicolon
1555 vector<string> context = getVectorFromString(contexts, ";");
1556 // require feature if the context matches either current font
1557 // or input encoding
1558 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1559 || std::find(context.begin(), context.end(),
1560 features.runparams().encoding->name()) != context.end())
1561 features.require(realfeature);
1564 } else if (!bp.use_dash_ligatures
1565 && (c == 0x2013 || c == 0x2014)
1566 && bp.useNonTeXFonts
1567 && features.runparams().flavor == Flavor::XeTeX)
1568 // XeTeX's dash behaviour is determined via a global setting
1569 features.require("xetexdashbreakstate");
1570 BufferEncodings::validate(c, features);
1574 /////////////////////////////////////////////////////////////////////
1578 /////////////////////////////////////////////////////////////////////
1581 Layout const emptyParagraphLayout;
1584 Paragraph::Paragraph()
1585 : d(new Paragraph::Private(this, emptyParagraphLayout))
1592 Paragraph::Paragraph(Paragraph const & par)
1593 : itemdepth(par.itemdepth),
1594 d(new Paragraph::Private(*par.d, this))
1600 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1601 : itemdepth(par.itemdepth),
1602 d(new Paragraph::Private(*par.d, this, beg, end))
1608 Paragraph & Paragraph::operator=(Paragraph const & par)
1610 // needed as we will destroy the private part before copying it
1612 itemdepth = par.itemdepth;
1616 d = new Private(*par.d, this);
1623 Paragraph::~Paragraph()
1632 // this shall be called just before every "os << ..." action.
1633 void flushString(ostream & os, docstring & s)
1642 void Paragraph::write(ostream & os, BufferParams const & bparams,
1643 depth_type & depth) const
1645 // The beginning or end of a deeper (i.e. nested) area?
1646 if (depth != d->params_.depth()) {
1647 if (d->params_.depth() > depth) {
1648 while (d->params_.depth() > depth) {
1649 os << "\n\\begin_deeper";
1653 while (d->params_.depth() < depth) {
1654 os << "\n\\end_deeper";
1660 // First write the layout
1661 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1663 d->params_.write(os);
1665 Font font1(inherit_font, bparams.language);
1667 Change running_change = Change(Change::UNCHANGED);
1669 // this string is used as a buffer to avoid repetitive calls
1670 // to to_utf8(), which turn out to be expensive (JMarc)
1671 docstring write_buffer;
1674 for (pos_type i = 0; i <= size(); ++i) {
1676 Change const & change = lookupChange(i);
1677 if (change != running_change)
1678 flushString(os, write_buffer);
1679 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1680 running_change = change;
1685 // Write font changes
1686 Font font2 = getFontSettings(bparams, i);
1687 if (font2 != font1) {
1688 flushString(os, write_buffer);
1689 font2.lyxWriteChanges(font1, os);
1694 char_type const c = d->text_[i];
1697 if (Inset const * inset = getInset(i)) {
1698 flushString(os, write_buffer);
1699 if (inset->directWrite()) {
1700 // international char, let it write
1701 // code directly so it's shorter in
1707 os << "\\begin_inset ";
1709 os << "\n\\end_inset\n\n";
1712 // FIXME This can be removed again once the mystery
1713 // crash has been resolved.
1718 flushString(os, write_buffer);
1719 os << "\n\\backslash\n";
1723 flushString(os, write_buffer);
1724 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1731 if ((column > 70 && c == ' ')
1733 flushString(os, write_buffer);
1737 // this check is to amend a bug. LyX sometimes
1738 // inserts '\0' this could cause problems.
1740 write_buffer.push_back(c);
1742 LYXERR0("NUL char in structure.");
1748 flushString(os, write_buffer);
1749 os << "\n\\end_layout\n";
1750 // FIXME This can be removed again once the mystery
1751 // crash has been resolved.
1756 void Paragraph::validate(LaTeXFeatures & features) const
1758 d->validate(features);
1759 bool fragile = features.runparams().moving_arg;
1760 fragile |= layout().needprotect;
1761 if (inInset().getLayout().isNeedProtect())
1763 if (needsCProtection(fragile))
1764 features.require("cprotect");
1768 void Paragraph::insert(pos_type pos, docstring const & str,
1769 Font const & font, Change const & change)
1771 for (size_t i = 0, n = str.size(); i != n ; ++i)
1772 insertChar(pos + i, str[i], font, change);
1776 void Paragraph::appendChar(char_type c, Font const & font,
1777 Change const & change)
1779 // Make sure that Buffer::hasChangesPresent is updated
1780 ChangesMonitor cm(*this);
1783 d->changes_.insert(change, d->text_.size());
1784 // when appending characters, no need to update tables
1785 d->text_.push_back(c);
1786 setFont(d->text_.size() - 1, font);
1787 d->requestSpellCheck(d->text_.size() - 1);
1791 void Paragraph::appendString(docstring const & s, Font const & font,
1792 Change const & change)
1794 // Make sure that Buffer::hasChangesPresent is updated
1795 ChangesMonitor cm(*this);
1797 pos_type end = s.size();
1798 size_t oldsize = d->text_.size();
1799 size_t newsize = oldsize + end;
1800 size_t capacity = d->text_.capacity();
1801 if (newsize >= capacity)
1802 d->text_.reserve(max(capacity + 100, newsize));
1804 // when appending characters, no need to update tables
1807 // FIXME: Optimize this!
1808 for (size_t i = oldsize; i != newsize; ++i) {
1810 d->changes_.insert(change, i);
1811 d->requestSpellCheck(i);
1813 d->fontlist_.set(oldsize, font);
1814 d->fontlist_.set(newsize - 1, font);
1818 void Paragraph::insertChar(pos_type pos, char_type c,
1821 d->insertChar(pos, c, Change(trackChanges ?
1822 Change::INSERTED : Change::UNCHANGED));
1826 void Paragraph::insertChar(pos_type pos, char_type c,
1827 Font const & font, bool trackChanges)
1829 d->insertChar(pos, c, Change(trackChanges ?
1830 Change::INSERTED : Change::UNCHANGED));
1835 void Paragraph::insertChar(pos_type pos, char_type c,
1836 Font const & font, Change const & change)
1838 d->insertChar(pos, c, change);
1843 void Paragraph::resetFonts(Font const & font)
1845 d->fontlist_.clear();
1846 d->fontlist_.set(0, font);
1847 d->fontlist_.set(d->text_.size() - 1, font);
1850 // Gets uninstantiated font setting at position.
1851 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1855 LYXERR0("pos: " << pos << " size: " << size());
1859 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1860 if (cit != d->fontlist_.end())
1863 if (pos == size() && !empty())
1864 return getFontSettings(bparams, pos - 1);
1866 // Optimisation: avoid a full font instantiation if there is no
1867 // language change from previous call.
1868 static Font previous_font;
1869 static Language const * previous_lang = nullptr;
1870 Language const * lang = getParLanguage(bparams);
1871 if (lang != previous_lang) {
1872 previous_lang = lang;
1873 previous_font = Font(inherit_font, lang);
1875 return previous_font;
1879 FontSpan Paragraph::fontSpan(pos_type pos) const
1881 LBUFERR(pos <= size());
1884 return FontSpan(pos, pos);
1887 FontList::const_iterator cit = d->fontlist_.begin();
1888 FontList::const_iterator end = d->fontlist_.end();
1889 for (; cit != end; ++cit) {
1890 if (cit->pos() >= pos) {
1891 if (pos >= beginOfBody())
1892 return FontSpan(max(start, beginOfBody()),
1895 return FontSpan(start,
1896 min(beginOfBody() - 1,
1899 start = cit->pos() + 1;
1902 // This should not happen, but if so, we take no chances.
1903 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1904 LASSERT(false, return FontSpan(pos, pos));
1908 // Gets uninstantiated font setting at position 0
1909 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1911 if (!empty() && !d->fontlist_.empty())
1912 return d->fontlist_.begin()->font();
1914 // Optimisation: avoid a full font instantiation if there is no
1915 // language change from previous call.
1916 static Font previous_font;
1917 static Language const * previous_lang = nullptr;
1918 if (bparams.language != previous_lang) {
1919 previous_lang = bparams.language;
1920 previous_font = Font(inherit_font, bparams.language);
1923 return previous_font;
1927 // Gets the fully instantiated font at a given position in a paragraph
1928 // This is basically the same function as Text::GetFont() in text2.cpp.
1929 // The difference is that this one is used for generating the LaTeX file,
1930 // and thus cosmetic "improvements" are disallowed: This has to deliver
1931 // the true picture of the buffer. (Asger)
1932 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1933 Font const & outerfont) const
1937 Font font = getFontSettings(bparams, pos);
1939 pos_type const body_pos = beginOfBody();
1940 FontInfo & fi = font.fontInfo();
1942 fi.realize(d->layout_->labelfont);
1944 fi.realize(d->layout_->font);
1946 fi.realize(outerfont.fontInfo());
1947 fi.realize(bparams.getFont().fontInfo());
1953 Font const Paragraph::getLabelFont
1954 (BufferParams const & bparams, Font const & outerfont) const
1956 FontInfo tmpfont = d->layout_->labelfont;
1957 tmpfont.realize(outerfont.fontInfo());
1958 tmpfont.realize(bparams.getFont().fontInfo());
1959 return Font(tmpfont, getParLanguage(bparams));
1963 Font const Paragraph::getLayoutFont
1964 (BufferParams const & bparams, Font const & outerfont) const
1966 FontInfo tmpfont = d->layout_->font;
1967 tmpfont.realize(outerfont.fontInfo());
1968 tmpfont.realize(bparams.getFont().fontInfo());
1969 return Font(tmpfont, getParLanguage(bparams));
1973 char_type Paragraph::getUChar(BufferParams const & bparams,
1974 OutputParams const & rp,
1977 char_type c = d->text_[pos];
1979 // Return unchanged character in LTR languages
1980 // or if we use poylglossia/bidi (XeTeX).
1981 if (rp.useBidiPackage()
1982 || !getFontSettings(bparams, pos).isRightToLeft())
1985 // Without polyglossia/bidi, we need to account for some special cases.
1986 // FIXME This needs to be audited!
1988 // * The input is as expected for all delimiters
1989 // => checked for Hebrew!
1990 // * The output matches the display in the LyX workarea
1991 // => checked for Hebrew!
1992 // * The special cases below are really necessary
1993 // => checked for Hebrew!
1994 // * In arabic_arabi, brackets are transformed to Arabic
1995 // Ornate Parentheses. Is this is really wanted?
1997 string const & lang = getFontSettings(bparams, pos).language()->lang();
2000 // 1. In the following languages, parentheses need to be reversed.
2001 // Also with polyglodia/luabidi
2002 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2004 // 2. In the following languages, brackets don't need to be reversed.
2005 bool const reversebrackets = lang != "arabic_arabtex"
2006 && lang != "arabic_arabi"
2009 // Now swap delimiters if needed.
2020 if (reversebrackets)
2024 if (reversebrackets)
2045 void Paragraph::setFont(pos_type pos, Font const & font)
2047 LASSERT(pos <= size(), return);
2049 // First, reduce font against layout/label font
2050 // Update: The setCharFont() routine in text2.cpp already
2051 // reduces font, so we don't need to do that here. (Asger)
2053 d->fontlist_.set(pos, font);
2057 void Paragraph::makeSameLayout(Paragraph const & par)
2059 d->layout_ = par.d->layout_;
2060 d->params_ = par.d->params_;
2064 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2066 if (isFreeSpacing())
2072 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2073 if (eraseChar(pos, trackChanges))
2079 return count > 0 || pos > 0;
2083 bool Paragraph::hasSameLayout(Paragraph const & par) const
2085 return par.d->layout_ == d->layout_
2086 && d->params_.sameLayout(par.d->params_);
2090 depth_type Paragraph::getDepth() const
2092 return d->params_.depth();
2096 depth_type Paragraph::getMaxDepthAfter() const
2098 if (d->layout_->isEnvironment())
2099 return d->params_.depth() + 1;
2101 return d->params_.depth();
2105 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2107 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2108 return getDefaultAlign(bparams);
2110 return d->params_.align();
2114 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2116 LyXAlignment res = layout().align;
2117 if (isRTL(bparams)) {
2119 if (res == LYX_ALIGN_LEFT)
2120 res = LYX_ALIGN_RIGHT;
2121 else if (res == LYX_ALIGN_RIGHT)
2122 res = LYX_ALIGN_LEFT;
2128 docstring const & Paragraph::labelString() const
2130 return d->params_.labelString();
2134 // the next two functions are for the manual labels
2135 docstring const Paragraph::getLabelWidthString() const
2137 if (d->layout_->margintype == MARGIN_MANUAL
2138 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2139 return d->params_.labelWidthString();
2141 return _("Senseless with this layout!");
2145 void Paragraph::setLabelWidthString(docstring const & s)
2147 d->params_.labelWidthString(s);
2151 docstring Paragraph::expandLabel(Layout const & layout,
2152 BufferParams const & bparams) const
2154 return expandParagraphLabel(layout, bparams, true);
2158 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2159 BufferParams const & bparams, bool process_appendix) const
2161 DocumentClass const & tclass = bparams.documentClass();
2162 string const & lang = getParLanguage(bparams)->code();
2163 bool const in_appendix = process_appendix && d->params_.appendix();
2164 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2166 if (fmt.empty() && !layout.counter.empty())
2167 return tclass.counters().theCounter(layout.counter, lang);
2169 // handle 'inherited level parts' in 'fmt',
2170 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2171 size_t const i = fmt.find('@', 0);
2172 if (i != docstring::npos) {
2173 size_t const j = fmt.find('@', i + 1);
2174 if (j != docstring::npos) {
2175 docstring parent(fmt, i + 1, j - i - 1);
2176 docstring label = from_ascii("??");
2177 if (tclass.hasLayout(parent))
2178 label = expandParagraphLabel(tclass[parent], bparams,
2180 fmt = docstring(fmt, 0, i) + label
2181 + docstring(fmt, j + 1, docstring::npos);
2185 return tclass.counters().counterLabel(fmt, lang);
2189 void Paragraph::applyLayout(Layout const & new_layout)
2191 d->layout_ = &new_layout;
2192 LyXAlignment const oldAlign = d->params_.align();
2194 if (!(oldAlign & d->layout_->alignpossible)) {
2195 frontend::Alert::warning(_("Alignment not permitted"),
2196 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2197 d->params_.align(LYX_ALIGN_LAYOUT);
2202 pos_type Paragraph::beginOfBody() const
2204 return d->begin_of_body_;
2208 void Paragraph::setBeginOfBody()
2210 if (d->layout_->labeltype != LABEL_MANUAL) {
2211 d->begin_of_body_ = 0;
2215 // Unroll the first two cycles of the loop
2216 // and remember the previous character to
2217 // remove unnecessary getChar() calls
2219 pos_type end = size();
2220 bool prev_char_deleted = false;
2221 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2224 char_type previous_char = d->text_[i];
2225 if (!(isNewline(i) || isEnvSeparator(i))) {
2227 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2228 char_type temp = d->text_[i];
2229 prev_char_deleted = isDeleted(i);
2230 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2233 previous_char = temp;
2239 d->begin_of_body_ = i;
2243 bool Paragraph::allowParagraphCustomization() const
2245 return inInset().allowParagraphCustomization();
2249 bool Paragraph::usePlainLayout() const
2251 return inInset().usePlainLayout();
2255 bool Paragraph::isPassThru() const
2257 return inInset().isPassThru() || d->layout_->pass_thru;
2262 // paragraphs inside floats need different alignment tags to avoid
2265 bool noTrivlistCentering(InsetCode code)
2267 return code == FLOAT_CODE
2268 || code == WRAP_CODE
2269 || code == CELL_CODE;
2273 string correction(string const & orig)
2275 if (orig == "flushleft")
2276 return "raggedright";
2277 if (orig == "flushright")
2278 return "raggedleft";
2279 if (orig == "center")
2285 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2286 InsetCode code, bool const lastpar, int & col)
2288 string macro = suffix + "{";
2289 if (noTrivlistCentering(code)) {
2291 // the last paragraph in non-trivlist-aligned
2292 // context is special (to avoid unwanted whitespace)
2293 if (suffix == "\\begin") {
2294 macro = "\\" + correction(env) + "{}";
2295 os << from_ascii(macro);
2296 col += macro.size();
2301 macro += correction(env);
2305 if (suffix == "\\par\\end") {
2309 os << from_ascii(macro);
2310 col += macro.size();
2311 if (suffix == "\\begin") {
2321 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2322 otexstream & os, OutputParams const & runparams) const
2327 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2328 (layout_->toggle_indent != ITOGGLE_NEVER) :
2329 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2331 if (canindent && params_.noindent() && !layout_->pass_thru) {
2332 os << "\\noindent ";
2336 LyXAlignment const curAlign = params_.align();
2338 if (curAlign == layout_->align)
2342 case LYX_ALIGN_NONE:
2343 case LYX_ALIGN_BLOCK:
2344 case LYX_ALIGN_LAYOUT:
2345 case LYX_ALIGN_SPECIAL:
2346 case LYX_ALIGN_DECIMAL:
2348 case LYX_ALIGN_LEFT:
2349 case LYX_ALIGN_RIGHT:
2350 case LYX_ALIGN_CENTER:
2351 if (runparams.moving_arg) {
2358 string const begin_tag = "\\begin";
2359 InsetCode code = ownerCode();
2360 bool const lastpar = runparams.isLastPar;
2361 // RTL in classic (PDF)LaTeX (without the Bidi package)
2362 // Luabibdi (used by LuaTeX) behaves like classic
2363 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2364 && !runparams.useBidiPackage();
2367 case LYX_ALIGN_NONE:
2368 case LYX_ALIGN_BLOCK:
2369 case LYX_ALIGN_LAYOUT:
2370 case LYX_ALIGN_SPECIAL:
2371 case LYX_ALIGN_DECIMAL:
2373 case LYX_ALIGN_LEFT: {
2375 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2376 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2378 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2380 } case LYX_ALIGN_RIGHT: {
2382 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2383 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2385 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2387 } case LYX_ALIGN_CENTER: {
2388 corrected_env(os, begin_tag, "center", code, lastpar, column);
2397 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2398 otexstream & os, OutputParams const & runparams) const
2400 LyXAlignment const curAlign = params_.align();
2402 if (curAlign == layout_->align)
2406 case LYX_ALIGN_NONE:
2407 case LYX_ALIGN_BLOCK:
2408 case LYX_ALIGN_LAYOUT:
2409 case LYX_ALIGN_SPECIAL:
2410 case LYX_ALIGN_DECIMAL:
2412 case LYX_ALIGN_LEFT:
2413 case LYX_ALIGN_RIGHT:
2414 case LYX_ALIGN_CENTER:
2415 if (runparams.moving_arg)
2420 bool output = false;
2422 string const end_tag = "\\par\\end";
2423 InsetCode code = ownerCode();
2424 bool const lastpar = runparams.isLastPar;
2425 // RTL in classic (PDF)LaTeX (without the Bidi package)
2426 // Luabibdi (used by LuaTeX) behaves like classic
2427 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2428 && !runparams.useBidiPackage();
2431 case LYX_ALIGN_NONE:
2432 case LYX_ALIGN_BLOCK:
2433 case LYX_ALIGN_LAYOUT:
2434 case LYX_ALIGN_SPECIAL:
2435 case LYX_ALIGN_DECIMAL:
2437 case LYX_ALIGN_LEFT: {
2439 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2440 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2442 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2444 } case LYX_ALIGN_RIGHT: {
2446 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2447 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2449 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2451 } case LYX_ALIGN_CENTER: {
2452 corrected_env(os, end_tag, "center", code, lastpar, col);
2457 return output || lastpar;
2461 // This one spits out the text of the paragraph
2462 void Paragraph::latex(BufferParams const & bparams,
2463 Font const & outerfont,
2465 OutputParams const & runparams,
2466 int start_pos, int end_pos, bool force) const
2468 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2470 // FIXME This check should not be needed. Perhaps issue an
2471 // error if it triggers.
2472 Layout const & style = inInset().forcePlainLayout() ?
2473 bparams.documentClass().plainLayout() : *d->layout_;
2475 if (!force && style.inpreamble)
2478 bool const allowcust = allowParagraphCustomization();
2480 // Current base font for all inherited font changes, without any
2481 // change caused by an individual character, except for the language:
2482 // It is set to the language of the first character.
2483 // As long as we are in the label, this font is the base font of the
2484 // label. Before the first body character it is set to the base font
2488 // If there is an open font-encoding changing command (script wrapper),
2489 // alien_script is set to its name
2490 string alien_script;
2493 // Maybe we have to create a optional argument.
2494 pos_type body_pos = beginOfBody();
2495 unsigned int column = 0;
2497 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2498 Font const real_outerfont = (!inInset().inheritFont()
2499 && runparams.local_font != nullptr)
2500 ? Font(runparams.local_font->fontInfo()) : outerfont;
2503 // the optional argument is kept in curly brackets in
2504 // case it contains a ']'
2505 // This is not strictly needed, but if this is changed it
2506 // would be a file format change, and tex2lyx would need
2507 // to be adjusted, since it unconditionally removes the
2508 // braces when it parses \item.
2511 basefont = getLabelFont(bparams, real_outerfont);
2513 basefont = getLayoutFont(bparams, real_outerfont);
2516 // Which font is currently active?
2517 Font running_font(basefont);
2518 // Do we have an open font change?
2519 bool open_font = false;
2521 Change runningChange =
2522 runparams.inDeletedInset && !inInset().canTrackChanges()
2523 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2525 Encoding const * const prev_encoding = runparams.encoding;
2527 os.texrow().start(id(), 0);
2529 // if the paragraph is empty, the loop will not be entered at all
2531 // For InTitle commands, we have already opened a group
2532 // in output_latex::TeXOnePar.
2533 if (style.isCommand() && !style.intitle) {
2537 if (!style.leftdelim().empty()) {
2538 os << style.leftdelim();
2539 column += style.leftdelim().size();
2542 column += d->startTeXParParams(bparams, os, runparams);
2545 // Whether a \par can be issued for insets typeset inline with text.
2546 // Yes if greater than 0. This has to be static.
2547 THREAD_LOCAL_STATIC int parInline = 0;
2549 for (pos_type i = 0; i < size(); ++i) {
2550 // First char in paragraph or after label?
2551 if (i == body_pos) {
2554 bool needPar = false;
2555 column += running_font.latexWriteEndChanges(
2556 os, bparams, runparams,
2557 basefont, basefont, needPar);
2560 basefont = getLayoutFont(bparams, real_outerfont);
2561 running_font = basefont;
2563 column += Changes::latexMarkChange(os, bparams,
2564 runningChange, Change(Change::UNCHANGED),
2566 runningChange = Change(Change::UNCHANGED);
2568 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2571 // For InTitle commands, we have already opened a group
2572 // in output_latex::TeXOnePar.
2573 if (style.isCommand() && !style.intitle) {
2578 if (!style.leftdelim().empty()) {
2579 os << style.leftdelim();
2580 column += style.leftdelim().size();
2584 column += d->startTeXParParams(bparams, os,
2588 runparams.wasDisplayMath = runparams.inDisplayMath;
2589 runparams.inDisplayMath = false;
2590 bool deleted_display_math = false;
2591 Change const & change = runparams.inDeletedInset
2592 ? runparams.changeOfDeletedInset : lookupChange(i);
2594 char_type const c = d->text_[i];
2596 // Check whether a display math inset follows
2597 bool output_changes;
2598 if (runparams.for_searchAdv == OutputParams::NoSearch)
2599 output_changes = bparams.output_changes;
2601 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2603 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2605 runparams.ctObject = getInset(i)->getCtObject(runparams);
2607 InsetMath const * im = getInset(i)->asInsetMath();
2608 if (im && im->asHullInset()
2609 && im->asHullInset()->outerDisplay()) {
2610 runparams.inDisplayMath = true;
2611 // runparams.inDeletedInset will be set by
2612 // latexInset later, but we need this info
2613 // before it is called. On the other hand, we
2614 // cannot set it here because it is a counter.
2615 deleted_display_math = isDeleted(i);
2617 if (output_changes && deleted_display_math
2618 && runningChange == change
2619 && change.type == Change::DELETED
2620 && !os.afterParbreak()) {
2621 // A display math in the same paragraph follows.
2622 // We have to close and then reopen \lyxdeleted,
2623 // otherwise the math will be shifted up.
2624 OutputParams rp = runparams;
2626 bool needPar = false;
2627 column += running_font.latexWriteEndChanges(
2628 os, bparams, rp, basefont,
2632 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2633 : getLayoutFont(bparams, real_outerfont);
2634 running_font = basefont;
2635 column += Changes::latexMarkChange(os, bparams,
2636 Change(Change::INSERTED), change, rp);
2640 if (output_changes && runningChange != change) {
2641 if (!alien_script.empty()) {
2644 alien_script.clear();
2647 bool needPar = false;
2648 column += running_font.latexWriteEndChanges(
2649 os, bparams, runparams,
2650 basefont, basefont, needPar);
2653 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2654 : getLayoutFont(bparams, real_outerfont);
2655 running_font = basefont;
2656 column += Changes::latexMarkChange(os, bparams, runningChange,
2658 runningChange = change;
2661 // do not output text which is marked deleted
2662 // if change tracking output is disabled
2663 if (!output_changes && change.deleted()) {
2669 // Fully instantiated font
2670 Font current_font = getFont(bparams, i, outerfont);
2672 Font const prev_font = (i > 0) ?
2673 getFont(bparams, i - 1, outerfont)
2676 Font const last_font = running_font;
2677 bool const in_ct_deletion = (output_changes
2678 && runningChange == change
2679 && change.type == Change::DELETED
2680 && !os.afterParbreak());
2681 // Insets where font switches are used (rather than font commands)
2682 bool const fontswitch_inset =
2685 && getInset(i)->allowMultiPar()
2686 && getInset(i)->lyxCode() != ERT_CODE
2687 && getInset(i)->producesOutput();
2689 bool closeLanguage = false;
2690 bool lang_switched_at_inset = false;
2691 if (fontswitch_inset) {
2692 // Some insets cannot be inside a font change command.
2693 // However, even such insets *can* be placed in \L or \R
2694 // or their equivalents (for RTL language switches),
2695 // so we don't close the language in those cases
2696 // (= differing isRightToLeft()).
2697 // ArabTeX, though, doesn't seem to handle this special behavior.
2698 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2699 || basefont.language()->lang() == "arabic_arabtex"
2700 || current_font.language()->lang() == "arabic_arabtex";
2701 // We need to check prev_font as language changes directly at inset
2702 // will only be started inside the inset.
2703 lang_switched_at_inset = prev_font.language() != current_font.language();
2706 // Do we need to close the previous font?
2707 bool langClosed = false;
2709 ((current_font != running_font
2710 || current_font.language() != running_font.language())
2711 || (fontswitch_inset
2712 && (current_font == prev_font))))
2714 // ensure there is no open script-wrapper
2715 if (!alien_script.empty()) {
2718 alien_script.clear();
2720 if (in_ct_deletion) {
2721 // We have to close and then reopen \lyxdeleted,
2722 // as strikeout needs to be on lowest level.
2727 // Force language closing
2728 current_font.setLanguage(basefont.language());
2729 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2730 bool needPar = false;
2731 column += running_font.latexWriteEndChanges(
2732 os, bparams, runparams, basefont,
2734 if (in_ct_deletion) {
2735 // We have to close and then reopen \lyxdeleted,
2736 // as strikeout needs to be on lowest level.
2737 OutputParams rp = runparams;
2738 column += Changes::latexMarkChange(os, bparams,
2739 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2742 // Has the language been closed in the latexWriteEndChanges() call above?
2743 langClosed = running_font.language() != basefont.language()
2744 && running_font.language() != nextfont.language()
2745 && (running_font.language()->encoding()->package() != Encoding::CJK);
2746 running_font = basefont;
2749 // if necessary, close language environment before opening CJK
2750 string const running_lang = running_font.language()->babel();
2751 string const lang_end_command = lyxrc.language_command_end;
2752 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2753 && !running_lang.empty()
2754 && running_lang == openLanguageName()
2755 && current_font.language()->encoding()->package() == Encoding::CJK) {
2756 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2757 os << from_ascii(end_tag);
2758 column += end_tag.length();
2762 // Switch file encoding if necessary (and allowed)
2763 if ((!fontswitch_inset || closeLanguage)
2764 && !runparams.pass_thru && !style.pass_thru &&
2765 runparams.encoding->package() != Encoding::none &&
2766 current_font.language()->encoding()->package() != Encoding::none) {
2767 pair<bool, int> const enc_switch =
2768 switchEncoding(os.os(), bparams, runparams,
2769 *(current_font.language()->encoding()));
2770 if (enc_switch.first) {
2771 column += enc_switch.second;
2772 runparams.encoding = current_font.language()->encoding();
2776 // A display math inset inside an ulem command will be output
2777 // as a box of width \linewidth, so we have to either disable
2778 // indentation if the inset starts a paragraph, or start a new
2779 // line to accommodate such box. This has to be done before
2780 // writing any font changing commands.
2781 if (runparams.inDisplayMath && !deleted_display_math
2782 && runparams.inulemcmd) {
2783 if (os.afterParbreak())
2789 // Do we need to change font?
2790 if ((current_font != running_font ||
2791 current_font.language() != running_font.language())
2792 && i != body_pos - 1)
2794 if (!fontswitch_inset) {
2795 if (in_ct_deletion) {
2796 // We have to close and then reopen \lyxdeleted,
2797 // as strikeout needs to be on lowest level.
2798 OutputParams rp = runparams;
2799 bool needPar = false;
2800 column += running_font.latexWriteEndChanges(
2801 os, bparams, rp, basefont,
2806 otexstringstream ots;
2807 InsetText const * textinset = inInset().asInsetText();
2808 bool const cprotect = textinset
2809 ? textinset->hasCProtectContent(runparams.moving_arg)
2810 && !textinset->text().isMainText()
2812 column += current_font.latexWriteStartChanges(ots, bparams,
2813 runparams, basefont, last_font, false,
2815 // Check again for display math in ulem commands as a
2816 // font change may also occur just before a math inset.
2817 if (runparams.inDisplayMath && !deleted_display_math
2818 && runparams.inulemcmd) {
2819 if (os.afterParbreak())
2824 running_font = current_font;
2826 docstring fontchange = ots.str();
2828 // check whether the fontchange ends with a \\textcolor
2829 // modifier and the text starts with a space. If so we
2830 // need to add } in order to prevent \\textcolor from gobbling
2831 // the space (bug 4473).
2832 docstring const last_modifier = rsplit(fontchange, '\\');
2833 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2834 os << from_ascii("{}");
2835 else if (ots.terminateCommand())
2837 if (in_ct_deletion) {
2838 // We have to close and then reopen \lyxdeleted,
2839 // as strikeout needs to be on lowest level.
2840 OutputParams rp = runparams;
2841 column += Changes::latexMarkChange(os, bparams,
2842 Change(Change::UNCHANGED), change, rp);
2845 running_font = current_font;
2846 open_font = !langClosed;
2850 // FIXME: think about end_pos implementation...
2851 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2852 // FIXME: integrate this case in latexSpecialChar
2853 // Do not print the separation of the optional argument
2854 // if style.pass_thru is false. This works because
2855 // latexSpecialChar ignores spaces if
2856 // style.pass_thru is false.
2857 if (i != body_pos - 1) {
2858 if (d->simpleTeXBlanks(bparams, runparams, os,
2859 i, column, current_font, style)) {
2860 // A surrogate pair was output. We
2861 // must not call latexSpecialChar
2862 // in this iteration, since it would output
2863 // the combining character again.
2870 OutputParams rp = runparams;
2871 rp.free_spacing = style.free_spacing;
2872 rp.local_font = ¤t_font;
2873 rp.intitle = style.intitle;
2875 // Two major modes: LaTeX or plain
2876 // Handle here those cases common to both modes
2877 // and then split to handle the two modes separately.
2878 if (c == META_INSET) {
2879 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2880 // Greyedout notes and, in general, all insets
2881 // with InsetLayout::isDisplay() == false,
2882 // are typeset inline with the text. So, we
2883 // can add a \par to the last paragraph of
2884 // such insets only if nothing else follows.
2885 bool incremented = false;
2886 Inset const * inset = getInset(i);
2887 InsetText const * textinset = inset
2888 ? inset->asInsetText()
2890 if (i + 1 == size() && textinset
2891 && !inset->getLayout().isDisplay()) {
2892 ParagraphList const & pars =
2893 textinset->text().paragraphs();
2894 pit_type const pit = pars.size() - 1;
2895 Font const lastfont =
2896 pit < 0 || pars[pit].empty()
2897 ? pars[pit].getLayoutFont(
2900 : pars[pit].getFont(bparams,
2901 pars[pit].size() - 1,
2903 if (lastfont.fontInfo().size() !=
2904 basefont.fontInfo().size()) {
2909 // We need to restore parts of this after insets with
2910 // allowMultiPar() true
2911 Font const save_basefont = basefont;
2912 d->latexInset(bparams, os, rp, running_font,
2913 basefont, real_outerfont, open_font,
2914 runningChange, style, i, column, fontswitch_inset,
2915 closeLanguage, lang_switched_at_inset);
2916 if (fontswitch_inset) {
2918 bool needPar = false;
2919 column += running_font.latexWriteEndChanges(
2920 os, bparams, runparams,
2921 basefont, basefont, needPar);
2924 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2925 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2926 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2931 if (runparams.ctObject == CtObject::DisplayObject
2932 || runparams.ctObject == CtObject::UDisplayObject) {
2933 // Close \lyx*deleted and force its
2934 // reopening (if needed)
2937 runningChange = Change(Change::UNCHANGED);
2938 runparams.ctObject = CtObject::Normal;
2941 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2942 if (!bparams.useNonTeXFonts)
2943 script = Encodings::isKnownScriptChar(c);
2944 if (script != alien_script) {
2945 if (!alien_script.empty()) {
2947 alien_script.clear();
2949 string fontenc = running_font.language()->fontenc(bparams);
2951 && !Encodings::fontencSupportsScript(fontenc, script)) {
2952 column += script.length() + 2;
2953 os << "\\" << script << "{";
2954 alien_script = script;
2958 d->latexSpecialChar(os, bparams, rp, running_font,
2959 alien_script, style, i, end_pos, column);
2960 } catch (EncodingException & e) {
2961 if (runparams.dryrun) {
2962 os << "<" << _("LyX Warning: ")
2963 << _("uncodable character") << " '";
2967 // add location information and throw again.
2975 // Set the encoding to that returned from latexSpecialChar (see
2976 // comment for encoding member in OutputParams.h)
2977 runparams.encoding = rp.encoding;
2979 // Also carry on the info on a closed ulem command for insets
2980 // such as Note that do not produce any output, so that no
2981 // command is ever executed but its opening was recorded.
2982 runparams.inulemcmd = rp.inulemcmd;
2984 // These need to be passed upstream as well
2985 runparams.need_maketitle = rp.need_maketitle;
2986 runparams.have_maketitle = rp.have_maketitle;
2988 // And finally, pass the post_macros upstream
2989 runparams.post_macro = rp.post_macro;
2992 // Close wrapper for alien script
2993 if (!alien_script.empty()) {
2995 alien_script.clear();
2998 Font const font = empty()
2999 ? getLayoutFont(bparams, real_outerfont)
3000 : getFont(bparams, size() - 1, real_outerfont);
3002 InsetText const * textinset = inInset().asInsetText();
3004 bool const maintext = textinset
3005 ? textinset->text().isMainText()
3008 size_t const numpars = textinset
3009 ? textinset->text().paragraphs().size()
3012 bool needPar = false;
3014 if (style.resfont.size() != font.fontInfo().size()
3015 && (!runparams.isLastPar || maintext
3016 || (numpars > 1 && d->ownerCode() != CELL_CODE
3017 && (inInset().getLayout().isDisplay()
3019 && !style.isCommand()) {
3023 // If we have an open font definition, we have to close it
3025 // Make sure that \\par is done with the font of the last
3026 // character if this has another size as the default.
3027 // This is necessary because LaTeX (and LyX on the screen)
3028 // calculates the space between the baselines according
3029 // to this font. (Matthias)
3031 // We must not change the font for the last paragraph
3032 // of non-multipar insets, tabular cells or commands,
3033 // since this produces unwanted whitespace.
3034 #ifdef FIXED_LANGUAGE_END_DETECTION
3036 running_font.latexWriteEndChanges(os, bparams,
3037 runparams, basefont,
3038 next_->getFont(bparams, 0, outerfont),
3041 running_font.latexWriteEndChanges(os, bparams,
3042 runparams, basefont, basefont, needPar);
3045 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3046 //FIXME: there as we start another \selectlanguage with the next paragraph if
3047 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3048 running_font.latexWriteEndChanges(os, bparams, runparams,
3049 basefont, basefont, needPar);
3053 // The \par could not be inserted at the same nesting
3054 // level of the font size change, so do it now.
3055 os << "{\\" << font.latexSize() << "\\par}";
3058 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3059 column += Changes::latexMarkChange(os, bparams, runningChange,
3060 Change(Change::UNCHANGED), runparams);
3062 // Needed if there is an optional argument but no contents.
3063 if (body_pos > 0 && body_pos == size()) {
3067 if (!style.rightdelim().empty()) {
3068 os << style.rightdelim();
3069 column += style.rightdelim().size();
3072 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3073 && runparams.encoding != prev_encoding) {
3074 runparams.encoding = prev_encoding;
3075 os << setEncoding(prev_encoding->iconvName());
3078 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3082 bool Paragraph::emptyTag() const
3084 for (pos_type i = 0; i < size(); ++i) {
3085 if (Inset const * inset = getInset(i)) {
3086 InsetCode lyx_code = inset->lyxCode();
3087 // FIXME testing like that is wrong. What is
3089 if (lyx_code != TOC_CODE &&
3090 lyx_code != INCLUDE_CODE &&
3091 lyx_code != GRAPHICS_CODE &&
3092 lyx_code != ERT_CODE &&
3093 lyx_code != LISTINGS_CODE &&
3094 lyx_code != FLOAT_CODE &&
3095 lyx_code != TABULAR_CODE) {
3099 char_type c = d->text_[i];
3100 if (c != ' ' && c != '\t')
3108 string Paragraph::getID(Buffer const &, OutputParams const &)
3111 for (pos_type i = 0; i < size(); ++i) {
3112 if (Inset const * inset = getInset(i)) {
3113 InsetCode lyx_code = inset->lyxCode();
3114 if (lyx_code == LABEL_CODE) {
3115 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3116 docstring const & id = il->getParam("name");
3117 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3125 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3128 for (i = 0; i < size(); ++i) {
3129 if (Inset const * inset = getInset(i)) {
3130 inset->docbook(xs, runparams);
3132 char_type c = d->text_[i];
3142 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3146 for (i = 0; i < size(); ++i) {
3147 if (Inset const * inset = getInset(i)) {
3148 inset->xhtml(xs, runparams);
3150 char_type c = d->text_[i];
3160 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3163 pos_type size = text_.size();
3164 for (pos_type i = initial; i < size; ++i) {
3165 Font font = owner_->getFont(buf.params(), i, outerfont);
3166 if (text_[i] == META_INSET)
3168 if (i != initial && font != font_old)
3179 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3180 vector<xml::EndFontTag> & tagsToClose,
3181 bool & flag, FontState curstate, xml::FontTypes type)
3183 if (curstate == FONT_ON) {
3184 tagsToOpen.push_back(docbookStartFontTag(type));
3187 tagsToClose.push_back(docbookEndFontTag(type));
3192 class OptionalFontType {
3197 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3198 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3201 OptionalFontType fontShapeToXml(FontShape fs)
3205 return {xml::FT_ITALIC};
3207 return {xml::FT_SLANTED};
3208 case SMALLCAPS_SHAPE:
3209 return {xml::FT_SMALLCAPS};
3214 // the other tags are for internal use
3220 OptionalFontType fontFamilyToXml(FontFamily fm)
3224 return {xml::FT_ROMAN};
3226 return {xml::FT_SANS};
3227 case TYPEWRITER_FAMILY:
3228 return {xml::FT_TYPE};
3229 case INHERIT_FAMILY:
3232 // the other tags are for internal use
3238 OptionalFontType fontSizeToXml(FontSize fs)
3242 return {xml::FT_SIZE_TINY};
3244 return {xml::FT_SIZE_SCRIPT};
3246 return {xml::FT_SIZE_FOOTNOTE};
3248 return {xml::FT_SIZE_SMALL};
3250 return {xml::FT_SIZE_LARGE};
3252 return {xml::FT_SIZE_LARGER};
3254 return {xml::FT_SIZE_LARGEST};
3256 return {xml::FT_SIZE_HUGE};
3258 return {xml::FT_SIZE_HUGER};
3260 return {xml::FT_SIZE_INCREASE};
3262 return {xml::FT_SIZE_DECREASE};
3267 // the other tags are for internal use
3273 struct DocBookFontState
3275 FontShape curr_fs = INHERIT_SHAPE;
3276 FontFamily curr_fam = INHERIT_FAMILY;
3277 FontSize curr_size = INHERIT_SIZE;
3279 // track whether we have opened these tags
3280 bool emph_flag = false;
3281 bool bold_flag = false;
3282 bool noun_flag = false;
3283 bool ubar_flag = false;
3284 bool dbar_flag = false;
3285 bool sout_flag = false;
3286 bool xout_flag = false;
3287 bool wave_flag = false;
3289 bool shap_flag = false;
3291 bool faml_flag = false;
3293 bool size_flag = false;
3296 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3298 std::string const & default_family,
3299 DocBookFontState & fs)
3301 vector<xml::FontTag> tagsToOpen;
3302 vector<xml::EndFontTag> tagsToClose;
3305 FontState curstate = font.fontInfo().emph();
3306 if (font_old.emph() != curstate)
3307 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3310 curstate = font.fontInfo().noun();
3311 if (font_old.noun() != curstate)
3312 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3315 curstate = font.fontInfo().underbar();
3316 if (font_old.underbar() != curstate)
3317 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3320 curstate = font.fontInfo().strikeout();
3321 if (font_old.strikeout() != curstate)
3322 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3325 curstate = font.fontInfo().xout();
3326 if (font_old.xout() != curstate)
3327 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3330 curstate = font.fontInfo().uuline();
3331 if (font_old.uuline() != curstate)
3332 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3335 curstate = font.fontInfo().uwave();
3336 if (font_old.uwave() != curstate)
3337 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3340 // a little hackish, but allows us to reuse what we have.
3341 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3342 if (font_old.series() != font.fontInfo().series())
3343 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3346 fs.curr_fs = font.fontInfo().shape();
3347 FontShape old_fs = font_old.shape();
3348 if (old_fs != fs.curr_fs) {
3350 OptionalFontType tag = fontShapeToXml(old_fs);
3352 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3353 fs.shap_flag = false;
3356 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3358 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3362 fs.curr_fam = font.fontInfo().family();
3363 FontFamily old_fam = font_old.family();
3364 if (old_fam != fs.curr_fam) {
3366 OptionalFontType tag = fontFamilyToXml(old_fam);
3368 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3369 fs.faml_flag = false;
3371 switch (fs.curr_fam) {
3373 // we will treat a "default" font family as roman, since we have
3374 // no other idea what to do.
3375 if (default_family != "rmdefault" && default_family != "default") {
3376 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3377 fs.faml_flag = true;
3381 if (default_family != "sfdefault") {
3382 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3383 fs.faml_flag = true;
3386 case TYPEWRITER_FAMILY:
3387 if (default_family != "ttdefault") {
3388 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3389 fs.faml_flag = true;
3392 case INHERIT_FAMILY:
3395 // the other tags are for internal use
3402 fs.curr_size = font.fontInfo().size();
3403 FontSize old_size = font_old.size();
3404 if (old_size != fs.curr_size) {
3406 OptionalFontType tag = fontSizeToXml(old_size);
3408 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3409 fs.size_flag = false;
3412 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3413 if (tag.has_value) {
3414 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3415 fs.size_flag = true;
3419 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3422 } // anonymous namespace
3425 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3426 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3427 OutputParams const & runparams,
3428 Font const & outerfont,
3431 bool ignore_fonts) const
3433 std::vector<docstring> prependedParagraphs;
3434 std::vector<docstring> generatedParagraphs;
3435 std::vector<docstring> appendedParagraphs;
3436 odocstringstream os;
3438 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3439 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3441 OutputParams rp = runparams;
3442 for (pos_type i = initial; i < size(); ++i) {
3443 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3444 const InsetArgument * arg = getInset(i)->asInsetArgument();
3445 if (arg->docbookargumentbeforemaintag()) {
3446 auto xs_local = XMLStream(os);
3447 arg->docbook(xs_local, rp);
3449 prependedParagraphs.push_back(os.str());
3450 os.str(from_ascii(""));
3452 rp.docbook_prepended_arguments.insert(arg);
3453 } else if (arg->docbookargumentaftermaintag()) {
3454 rp.docbook_appended_arguments.insert(arg);
3459 // State variables for the main loop.
3460 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3461 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3462 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3463 // This requires to store delayed characters at some point.
3465 DocBookFontState fs; // Track whether we have opened font tags
3466 DocBookFontState old_fs = fs;
3468 Layout const & style = *d->layout_;
3469 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3470 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3472 vector<xml::FontTag> tagsToOpen;
3473 vector<xml::EndFontTag> tagsToClose;
3475 // Parsing main loop.
3476 for (pos_type i = initial; i < size(); ++i) {
3477 bool ignore_fonts_i = ignore_fonts
3478 || style.docbooknofontinside()
3479 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3481 // Don't show deleted material in the output.
3485 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3487 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3488 if (!ignore_fonts_i)
3489 xs->closeFontTags();
3491 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3492 generatedParagraphs.push_back(os.str());
3494 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3495 // that the string stream must be reset.
3496 os.str(from_ascii(""));
3498 xs = new XMLStream(os);
3500 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3501 if (!ignore_fonts_i) {
3502 font_old = outerfont.fontInfo();
3507 // Determine which tags should be opened or closed regarding fonts.
3508 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3509 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3511 if (!ignore_fonts_i) {
3512 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3513 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3514 for (; cit != cen; ++cit)
3518 // Deal with the delayed characters *after* closing font tags.
3519 if (!delayedChars.empty()) {
3520 for (char_type c: delayedChars)
3522 delayedChars.clear();
3525 if (!ignore_fonts_i) {
3526 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3527 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3528 for (; sit != sen; ++sit)
3531 tagsToClose.clear();
3535 // Finally, write the next character or inset.
3536 if (Inset const * inset = getInset(i)) {
3537 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3538 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3539 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3541 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3542 // Arguments may need to be output
3543 OutputParams np = rp;
3544 np.local_font = &font;
3546 // TODO: special case will bite here.
3547 np.docbook_in_par = true;
3548 inset->docbook(*xs, np);
3551 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3552 if (lyx::isSpace(c) && !ignore_fonts)
3553 delayedChars.push_back(c);
3557 font_old = font.fontInfo();
3560 // FIXME, this code is just imported from XHTML
3561 // I'm worried about what happens if a branch, say, is itself
3562 // wrapped in some font stuff. I think that will not work.
3564 xs->closeFontTags();
3566 // Deal with the delayed characters *after* closing font tags.
3567 if (!delayedChars.empty())
3568 for (char_type c: delayedChars)
3571 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3572 // last line to get a clean output.
3573 if (rp.docbook_in_listing && !is_last_par)
3576 // Finalise the last (and most likely only) paragraph.
3577 generatedParagraphs.push_back(os.str());
3578 os.str(from_ascii(""));
3581 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3582 for (pos_type i = initial; i < size(); ++i) {
3583 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3584 const InsetArgument * arg = getInset(i)->asInsetArgument();
3585 if (arg->docbookargumentaftermaintag()) {
3586 // Don't use rp, as this argument would not generate anything.
3587 auto xs_local = XMLStream(os);
3588 arg->docbook(xs_local, runparams);
3590 appendedParagraphs.push_back(os.str());
3591 os.str(from_ascii(""));
3596 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3602 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3603 vector<xml::EndFontTag> & tagsToClose,
3604 bool & flag, FontState curstate, xml::FontTypes type)
3606 if (curstate == FONT_ON) {
3607 tagsToOpen.push_back(xhtmlStartFontTag(type));
3610 tagsToClose.push_back(xhtmlEndFontTag(type));
3615 } // anonymous namespace
3618 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3620 OutputParams const & runparams,
3621 Font const & outerfont,
3622 bool start_paragraph, bool close_paragraph,
3623 pos_type initial) const
3627 // track whether we have opened these tags
3628 bool emph_flag = false;
3629 bool bold_flag = false;
3630 bool noun_flag = false;
3631 bool ubar_flag = false;
3632 bool dbar_flag = false;
3633 bool sout_flag = false;
3634 bool xout_flag = false;
3635 bool wave_flag = false;
3637 bool shap_flag = false;
3639 bool faml_flag = false;
3641 bool size_flag = false;
3643 Layout const & style = *d->layout_;
3645 if (start_paragraph)
3646 xs.startDivision(allowEmpty());
3649 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3651 FontShape curr_fs = INHERIT_SHAPE;
3652 FontFamily curr_fam = INHERIT_FAMILY;
3653 FontSize curr_size = INHERIT_SIZE;
3655 string const default_family =
3656 buf.masterBuffer()->params().fonts_default_family;
3658 vector<xml::FontTag> tagsToOpen;
3659 vector<xml::EndFontTag> tagsToClose;
3661 // parsing main loop
3662 for (pos_type i = initial; i < size(); ++i) {
3663 // let's not show deleted material in the output
3667 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3670 FontState curstate = font.fontInfo().emph();
3671 if (font_old.emph() != curstate)
3672 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3675 curstate = font.fontInfo().noun();
3676 if (font_old.noun() != curstate)
3677 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3680 curstate = font.fontInfo().underbar();
3681 if (font_old.underbar() != curstate)
3682 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3685 curstate = font.fontInfo().strikeout();
3686 if (font_old.strikeout() != curstate)
3687 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3690 curstate = font.fontInfo().xout();
3691 if (font_old.xout() != curstate)
3692 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3695 curstate = font.fontInfo().uuline();
3696 if (font_old.uuline() != curstate)
3697 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3700 curstate = font.fontInfo().uwave();
3701 if (font_old.uwave() != curstate)
3702 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3705 // a little hackish, but allows us to reuse what we have.
3706 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3707 if (font_old.series() != font.fontInfo().series())
3708 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3711 curr_fs = font.fontInfo().shape();
3712 FontShape old_fs = font_old.shape();
3713 if (old_fs != curr_fs) {
3717 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3720 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3722 case SMALLCAPS_SHAPE:
3723 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3729 // the other tags are for internal use
3737 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3741 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3744 case SMALLCAPS_SHAPE:
3745 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3752 // the other tags are for internal use
3759 curr_fam = font.fontInfo().family();
3760 FontFamily old_fam = font_old.family();
3761 if (old_fam != curr_fam) {
3765 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3768 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3770 case TYPEWRITER_FAMILY:
3771 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3773 case INHERIT_FAMILY:
3776 // the other tags are for internal use
3784 // we will treat a "default" font family as roman, since we have
3785 // no other idea what to do.
3786 if (default_family != "rmdefault" && default_family != "default") {
3787 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3792 if (default_family != "sfdefault") {
3793 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3797 case TYPEWRITER_FAMILY:
3798 if (default_family != "ttdefault") {
3799 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3803 case INHERIT_FAMILY:
3806 // the other tags are for internal use
3813 curr_size = font.fontInfo().size();
3814 FontSize old_size = font_old.size();
3815 if (old_size != curr_size) {
3819 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3822 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3825 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3828 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3831 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3834 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3837 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3840 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3843 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3846 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3849 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3855 // the other tags are for internal use
3861 switch (curr_size) {
3863 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3867 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3871 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3875 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3879 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3883 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3887 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3891 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3895 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3899 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3903 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3910 // the other tags are for internal use
3917 // Other such tags? What about the other text ranges?
3919 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3920 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3921 for (; cit != cen; ++cit)
3924 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3925 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3926 for (; sit != sen; ++sit)
3929 tagsToClose.clear();
3932 Inset const * inset = getInset(i);
3934 if (!runparams.for_toc || inset->isInToc()) {
3935 OutputParams np = runparams;
3936 np.local_font = &font;
3937 // If the paragraph has size 1, then we are in the "special
3938 // case" where we do not output the containing paragraph info
3939 if (!inset->getLayout().htmlisblock() && size() != 1)
3940 np.html_in_par = true;
3941 retval += inset->xhtml(xs, np);
3944 char_type c = getUChar(buf.masterBuffer()->params(),
3946 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3947 xs << XMLStream::ESCAPE_NONE << " ";
3951 font_old = font.fontInfo();
3955 // I'm worried about what happens if a branch, say, is itself
3956 // wrapped in some font stuff. I think that will not work.
3958 if (close_paragraph)
3965 bool Paragraph::isHfill(pos_type pos) const
3967 Inset const * inset = getInset(pos);
3968 return inset && inset->isHfill();
3972 bool Paragraph::isNewline(pos_type pos) const
3974 // U+2028 LINE SEPARATOR
3975 // U+2029 PARAGRAPH SEPARATOR
3976 char_type const c = d->text_[pos];
3977 if (c == 0x2028 || c == 0x2029)
3979 Inset const * inset = getInset(pos);
3980 return inset && inset->lyxCode() == NEWLINE_CODE;
3984 bool Paragraph::isEnvSeparator(pos_type pos) const
3986 Inset const * inset = getInset(pos);
3987 return inset && inset->lyxCode() == SEPARATOR_CODE;
3991 bool Paragraph::isLineSeparator(pos_type pos) const
3993 char_type const c = d->text_[pos];
3994 if (isLineSeparatorChar(c))
3996 Inset const * inset = getInset(pos);
3997 return inset && inset->isLineSeparator();
4001 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4005 if (ignore_deleted && isDeleted(pos))
4007 if (Inset const * inset = getInset(pos))
4008 return !inset->isLetter();
4009 // if we have a hard hyphen (no en- or emdash) or apostrophe
4010 // we pass this to the spell checker
4011 // FIXME: this method is subject to change, visit
4012 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4013 // to get an impression how complex this is.
4014 if (isHardHyphenOrApostrophe(pos))
4016 char_type const c = d->text_[pos];
4017 // We want to pass the escape chars to the spellchecker
4018 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4019 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4023 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4025 pos_type const psize = size();
4028 char_type const c = d->text_[pos];
4029 if (c != '-' && c != '\'')
4031 pos_type nextpos = pos + 1;
4032 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4033 if ((nextpos == psize || isSpace(nextpos))
4034 && (pos == 0 || isSpace(prevpos)))
4040 bool Paragraph::needsCProtection(bool const fragile) const
4042 // first check the layout of the paragraph, but only in insets
4043 InsetText const * textinset = inInset().asInsetText();
4044 bool const maintext = textinset
4045 ? textinset->text().isMainText()
4048 if (!maintext && layout().needcprotect) {
4049 // Environments need cprotection regardless the content
4050 if (layout().latextype == LATEX_ENVIRONMENT)
4053 // Commands need cprotection if they contain specific chars
4054 int const nchars_escape = 9;
4055 static char_type const chars_escape[nchars_escape] = {
4056 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4058 docstring const pars = asString();
4059 for (int k = 0; k < nchars_escape; k++) {
4060 if (contains(pars, chars_escape[k]))
4065 // now check whether we have insets that need cprotection
4066 pos_type size = pos_type(d->text_.size());
4067 for (pos_type i = 0; i < size; ++i) {
4070 Inset const * ins = getInset(i);
4071 if (ins->needsCProtection(maintext, fragile))
4073 // Now check math environments
4074 InsetMath const * im = getInset(i)->asInsetMath();
4075 if (!im || im->cell(0).empty())
4077 switch(im->cell(0)[0]->lyxCode()) {
4078 case MATH_AMSARRAY_CODE:
4079 case MATH_SUBSTACK_CODE:
4081 case MATH_XYMATRIX_CODE:
4082 // these need cprotection
4093 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4095 return d->speller_state_.getRange(pos);
4099 bool Paragraph::isChar(pos_type pos) const
4101 if (Inset const * inset = getInset(pos))
4102 return inset->isChar();
4103 char_type const c = d->text_[pos];
4104 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4108 bool Paragraph::isSpace(pos_type pos) const
4110 if (Inset const * inset = getInset(pos))
4111 return inset->isSpace();
4112 char_type const c = d->text_[pos];
4113 return lyx::isSpace(c);
4118 Paragraph::getParLanguage(BufferParams const & bparams) const
4121 return getFirstFontSettings(bparams).language();
4122 // FIXME: we should check the prev par as well (Lgb)
4123 return bparams.language;
4127 bool Paragraph::isRTL(BufferParams const & bparams) const
4129 return getParLanguage(bparams)->rightToLeft()
4130 && !inInset().getLayout().forceLTR();
4134 void Paragraph::changeLanguage(BufferParams const & bparams,
4135 Language const * from, Language const * to)
4137 // change language including dummy font change at the end
4138 for (pos_type i = 0; i <= size(); ++i) {
4139 Font font = getFontSettings(bparams, i);
4140 if (font.language() == from) {
4141 font.setLanguage(to);
4143 d->requestSpellCheck(i);
4149 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4151 Language const * doc_language = bparams.language;
4152 for (auto const & f : d->fontlist_)
4153 if (f.font().language() != ignore_language &&
4154 f.font().language() != latex_language &&
4155 f.font().language() != doc_language)
4161 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4163 for (auto const & f : d->fontlist_) {
4164 Language const * lang = f.font().language();
4165 if (lang != ignore_language &&
4166 lang != latex_language)
4172 docstring Paragraph::asString(int options) const
4174 return asString(0, size(), options);
4178 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4180 odocstringstream os;
4183 && options & AS_STR_LABEL
4184 && !d->params_.labelString().empty())
4185 os << d->params_.labelString() << ' ';
4187 for (pos_type i = beg; i < end; ++i) {
4188 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4190 char_type const c = d->text_[i];
4191 if (isPrintable(c) || c == '\t'
4192 || (c == '\n' && (options & AS_STR_NEWLINES)))
4194 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4195 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4196 LASSERT(runparams != nullptr, return docstring());
4197 getInset(i)->plaintext(os, *runparams);
4198 } else if (c == META_INSET && (options & AS_STR_MATHED)
4199 && getInset(i)->lyxCode() == REF_CODE) {
4200 Buffer const & buf = getInset(i)->buffer();
4201 OutputParams rp(&buf.params().encoding());
4202 Font const font(inherit_font, buf.params().language);
4203 rp.local_font = &font;
4205 getInset(i)->latex(ots, rp);
4207 getInset(i)->toString(os);
4216 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4217 bool const shorten, bool const label) const
4219 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4220 if (label && !labelString().empty())
4221 os += labelString() + ' ';
4222 if (!layout().isTocCaption())
4224 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4227 char_type const c = d->text_[i];
4230 else if (c == META_INSET)
4231 getInset(i)->forOutliner(os, tmplen, false);
4234 Text::shortenForOutliner(os, maxlen);
4238 void Paragraph::setInsetOwner(Inset const * inset)
4240 d->inset_owner_ = inset;
4244 int Paragraph::id() const
4250 void Paragraph::setId(int id)
4256 Layout const & Paragraph::layout() const
4262 void Paragraph::setLayout(Layout const & layout)
4264 d->layout_ = &layout;
4268 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4270 setLayout(tc.defaultLayout());
4274 void Paragraph::setPlainLayout(DocumentClass const & tc)
4276 setLayout(tc.plainLayout());
4280 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4282 if (usePlainLayout())
4285 setDefaultLayout(tc);
4289 Inset const & Paragraph::inInset() const
4291 LBUFERR(d->inset_owner_);
4292 return *d->inset_owner_;
4296 ParagraphParameters & Paragraph::params()
4302 ParagraphParameters const & Paragraph::params() const
4308 bool Paragraph::isFreeSpacing() const
4310 if (d->layout_->free_spacing)
4312 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4316 bool Paragraph::allowEmpty() const
4318 if (d->layout_->keepempty)
4320 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4324 bool Paragraph::brokenBiblio() const
4326 // There is a problem if there is no bibitem at position 0 in
4327 // paragraphs that need one, if there is another bibitem in the
4328 // paragraph or if this paragraph is not supposed to have
4329 // a bibitem inset at all.
4330 return ((d->layout_->labeltype == LABEL_BIBLIO
4331 && (d->insetlist_.find(BIBITEM_CODE) != 0
4332 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4333 || (d->layout_->labeltype != LABEL_BIBLIO
4334 && d->insetlist_.find(BIBITEM_CODE) != -1));
4338 int Paragraph::fixBiblio(Buffer const & buffer)
4340 // FIXME: when there was already an inset at 0, the return value is 1,
4341 // which does not tell whether another inset has been removed; the
4342 // cursor cannot be correctly updated.
4344 bool const track_changes = buffer.params().track_changes;
4345 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4347 // The case where paragraph is not BIBLIO
4348 if (d->layout_->labeltype != LABEL_BIBLIO) {
4349 if (bibitem_pos == -1)
4350 // No InsetBibitem => OK
4352 // There is an InsetBibitem: remove it!
4353 d->insetlist_.release(bibitem_pos);
4354 eraseChar(bibitem_pos, track_changes);
4355 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4358 bool const hasbibitem0 = bibitem_pos == 0;
4360 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4361 // There was an InsetBibitem at pos 0,
4362 // and no other one => OK
4363 if (bibitem_pos == -1)
4365 // there is a bibitem at the 0 position, but since
4366 // there is a second one, we copy the second on the
4367 // first. We're assuming there are at most two of
4368 // these, which there should be.
4369 // FIXME: why does it make sense to do that rather
4370 // than keep the first? (JMarc)
4371 Inset * inset = releaseInset(bibitem_pos);
4372 d->insetlist_.begin()->inset = inset;
4373 // This needs to be done to update the counter (#8499)
4374 buffer.updateBuffer();
4375 return -bibitem_pos;
4378 // We need to create an inset at the beginning
4379 Inset * inset = nullptr;
4380 if (bibitem_pos > 0) {
4381 // there was one somewhere in the paragraph, let's move it
4382 inset = d->insetlist_.release(bibitem_pos);
4383 eraseChar(bibitem_pos, track_changes);
4386 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4387 InsetCommandParams(BIBITEM_CODE));
4389 Font font(inherit_font, buffer.params().language);
4390 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4391 : Change::UNCHANGED));
4393 // This is needed to get the counters right
4394 buffer.updateBuffer();
4399 void Paragraph::checkAuthors(AuthorList const & authorList)
4401 d->changes_.checkAuthors(authorList);
4405 bool Paragraph::isChanged(pos_type pos) const
4407 return lookupChange(pos).changed();
4411 bool Paragraph::isInserted(pos_type pos) const
4413 return lookupChange(pos).inserted();
4417 bool Paragraph::isDeleted(pos_type pos) const
4419 return lookupChange(pos).deleted();
4423 InsetList const & Paragraph::insetList() const
4425 return d->insetlist_;
4429 void Paragraph::setInsetBuffers(Buffer & b)
4431 d->insetlist_.setBuffer(b);
4435 void Paragraph::resetBuffer()
4437 d->insetlist_.resetBuffer();
4441 Inset * Paragraph::releaseInset(pos_type pos)
4443 Inset * inset = d->insetlist_.release(pos);
4444 /// does not honour change tracking!
4445 eraseChar(pos, false);
4450 Inset * Paragraph::getInset(pos_type pos)
4452 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4453 ? d->insetlist_.get(pos) : nullptr;
4457 Inset const * Paragraph::getInset(pos_type pos) const
4459 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4460 ? d->insetlist_.get(pos) : nullptr;
4464 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4465 pos_type & right, TextCase action)
4467 // process sequences of modified characters; in change
4468 // tracking mode, this approach results in much better
4469 // usability than changing case on a char-by-char basis
4470 // We also need to track the current font, since font
4471 // changes within sequences can occur.
4472 vector<pair<char_type, Font> > changes;
4474 bool const trackChanges = bparams.track_changes;
4476 bool capitalize = true;
4478 for (; pos < right; ++pos) {
4479 char_type oldChar = d->text_[pos];
4480 char_type newChar = oldChar;
4482 // ignore insets and don't play with deleted text!
4483 if (oldChar != META_INSET && !isDeleted(pos)) {
4485 case text_lowercase:
4486 newChar = lowercase(oldChar);
4488 case text_capitalization:
4490 newChar = uppercase(oldChar);
4494 case text_uppercase:
4495 newChar = uppercase(oldChar);
4500 if (isWordSeparator(pos) || isDeleted(pos)) {
4501 // permit capitalization again
4505 if (oldChar != newChar) {
4506 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4507 if (pos != right - 1)
4509 // step behind the changing area
4513 int erasePos = pos - changes.size();
4514 for (auto const & change : changes) {
4515 insertChar(pos, change.first, change.second, trackChanges);
4516 if (!eraseChar(erasePos, trackChanges)) {
4519 ++right; // expand selection
4527 int Paragraph::find(docstring const & str, bool cs, bool mw,
4528 pos_type start_pos, bool del) const
4530 pos_type pos = start_pos;
4531 int const strsize = str.length();
4533 pos_type const parsize = d->text_.size();
4534 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4535 // ignore deleted matter
4536 if (!del && isDeleted(pos)) {
4537 if (pos == parsize - 1)
4543 // Ignore "invisible" letters such as ligature breaks
4544 // and hyphenation chars while searching
4545 bool nonmatch = false;
4546 while (pos < parsize && isInset(pos)) {
4547 Inset const * inset = getInset(pos);
4548 if (!inset->isLetter() && !inset->isChar())
4550 odocstringstream os;
4551 inset->toString(os);
4552 docstring const insetstring = os.str();
4553 if (!insetstring.empty()) {
4554 int const insetstringsize = insetstring.length();
4555 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4556 if ((cs && str[i] != insetstring[j])
4557 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4565 if (nonmatch || i == strsize)
4567 if (cs && str[i] != d->text_[pos])
4569 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4576 // if necessary, check whether string matches word
4578 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4581 && !isWordSeparator(pos))
4585 return pos - start_pos;
4589 char_type Paragraph::getChar(pos_type pos) const
4591 return d->text_[pos];
4595 pos_type Paragraph::size() const
4597 return d->text_.size();
4601 bool Paragraph::empty() const
4603 return d->text_.empty();
4607 bool Paragraph::isInset(pos_type pos) const
4609 return d->text_[pos] == META_INSET;
4613 bool Paragraph::isSeparator(pos_type pos) const
4615 //FIXME: Are we sure this can be the only separator?
4616 return d->text_[pos] == ' ';
4620 void Paragraph::deregisterWords()
4622 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4623 Private::LangWordsMap::const_iterator ite = d->words_.end();
4624 for (; itl != ite; ++itl) {
4625 WordList & wl = theWordList(itl->first);
4626 Private::Words::const_iterator it = (itl->second).begin();
4627 Private::Words::const_iterator et = (itl->second).end();
4628 for (; it != et; ++it)
4635 void Paragraph::locateWord(pos_type & from, pos_type & to,
4636 word_location const loc, bool const ignore_deleted) const
4639 case WHOLE_WORD_STRICT:
4640 if (from == 0 || from == size()
4641 || isWordSeparator(from, ignore_deleted)
4642 || isWordSeparator(from - 1, ignore_deleted)) {
4649 // If we are already at the beginning of a word, do nothing
4650 if (!from || isWordSeparator(from - 1, ignore_deleted))
4655 // always move the cursor to the beginning of previous word
4656 while (from && !isWordSeparator(from - 1, ignore_deleted))
4660 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4663 // no need to move the 'from' cursor
4667 while (to < size() && !isWordSeparator(to, ignore_deleted))
4672 void Paragraph::collectWords()
4674 for (pos_type pos = 0; pos < size(); ++pos) {
4675 if (isWordSeparator(pos))
4677 pos_type from = pos;
4678 locateWord(from, pos, WHOLE_WORD);
4679 // Work around MSVC warning: The statement
4680 // if (pos < from + lyxrc.completion_minlength)
4681 // triggers a signed vs. unsigned warning.
4682 // I don't know why this happens, it could be a MSVC bug, or
4683 // related to LLP64 (windows) vs. LP64 (unix) programming
4684 // model, or the C++ standard might be ambigous in the section
4685 // defining the "usual arithmetic conversions". However, using
4686 // a temporary variable is safe and works on all compilers.
4687 pos_type const endpos = from + lyxrc.completion_minlength;
4690 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4691 if (cit == d->fontlist_.end())
4693 Language const * lang = cit->font().language();
4694 docstring const word = asString(from, pos, AS_STR_NONE);
4695 d->words_[lang->lang()].insert(word);
4700 void Paragraph::registerWords()
4702 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4703 Private::LangWordsMap::const_iterator ite = d->words_.end();
4704 for (; itl != ite; ++itl) {
4705 WordList & wl = theWordList(itl->first);
4706 Private::Words::const_iterator it = (itl->second).begin();
4707 Private::Words::const_iterator et = (itl->second).end();
4708 for (; it != et; ++it)
4714 void Paragraph::updateWords()
4722 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4724 SkipPositionsIterator begin = skips.begin();
4725 SkipPositions::iterator end = skips.end();
4726 if (pos > 0 && begin < end) {
4728 if (end->last == pos - 1) {
4733 skips.insert(end, FontSpan(pos, pos));
4737 Language * Paragraph::Private::locateSpellRange(
4738 pos_type & from, pos_type & to,
4739 SkipPositions & skips) const
4741 // skip leading white space
4742 while (from < to && owner_->isWordSeparator(from))
4744 // don't check empty range
4747 // get current language
4748 Language * lang = getSpellLanguage(from);
4749 pos_type last = from;
4750 bool samelang = true;
4751 bool sameinset = true;
4752 while (last < to && samelang && sameinset) {
4753 // hop to end of word
4754 while (last < to && !owner_->isWordSeparator(last)) {
4755 Inset const * inset = owner_->getInset(last);
4756 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4757 // check for "invisible" letters such as ligature breaks
4758 odocstringstream os;
4759 inset->toString(os);
4760 if (os.str().length() != 0) {
4761 // avoid spell check of visible special char insets
4762 // stop the loop in front of the special char inset
4767 appendSkipPosition(skips, last);
4768 } else if (owner_->isDeleted(last)) {
4769 appendSkipPosition(skips, last);
4773 // hop to next word while checking for insets
4774 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4775 if (Inset const * inset = owner_->getInset(last))
4776 sameinset = inset->isChar() && inset->isLetter();
4777 if (sameinset && owner_->isDeleted(last)) {
4778 appendSkipPosition(skips, last);
4783 if (sameinset && last < to) {
4784 // now check for language change
4785 samelang = lang == getSpellLanguage(last);
4788 // if language change detected backstep is needed
4796 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4799 const_cast<Language *>(owner_->getFontSettings(
4800 inset_owner_->buffer().params(), from).language());
4801 if (lang == inset_owner_->buffer().params().language
4802 && !lyxrc.spellchecker_alt_lang.empty()) {
4804 string const lang_variety =
4805 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4806 lang->setCode(lang_code);
4807 lang->setVariety(lang_variety);
4813 void Paragraph::requestSpellCheck(pos_type pos)
4815 d->requestSpellCheck(pos);
4819 bool Paragraph::needsSpellCheck() const
4821 SpellChecker::ChangeNumber speller_change_number = 0;
4822 if (theSpellChecker())
4823 speller_change_number = theSpellChecker()->changeNumber();
4824 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4825 d->speller_state_.needsCompleteRefresh(speller_change_number);
4827 return d->needsSpellCheck();
4831 bool Paragraph::Private::ignoreWord(docstring const & word) const
4833 // Ignore words with digits
4834 // FIXME: make this customizable
4835 // (note that some checkers ignore words with digits by default)
4836 docstring::const_iterator cit = word.begin();
4837 docstring::const_iterator const end = word.end();
4838 for (; cit != end; ++cit) {
4839 if (isNumber((*cit)))
4846 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4847 WordLangTuple & wl, docstring_list & suggestions,
4848 bool do_suggestion, bool check_learned) const
4850 SpellChecker::Result result = SpellChecker::WORD_OK;
4851 SpellChecker * speller = theSpellChecker();
4855 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4858 locateWord(from, to, WHOLE_WORD, true);
4859 if (from == to || from >= size())
4862 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4863 Language * lang = d->getSpellLanguage(from);
4865 BufferParams const & bparams = d->inset_owner_->buffer().params();
4867 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4870 wl = WordLangTuple(word, lang);
4875 if (needsSpellCheck() || check_learned) {
4877 if (!d->ignoreWord(word)) {
4878 bool const trailing_dot = to < size() && d->text_[to] == '.';
4879 result = speller->check(wl, bparams.spellignore());
4880 if (SpellChecker::misspelled(result) && trailing_dot) {
4881 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4882 result = speller->check(wl, bparams.spellignore());
4883 if (!SpellChecker::misspelled(result)) {
4884 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4886 from << ".." << to << "]");
4888 // spell check with dot appended failed too
4889 // restore original word/lang value
4890 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4891 wl = WordLangTuple(word, lang);
4895 if (!SpellChecker::misspelled(result)) {
4896 // area up to the begin of the next word is not misspelled
4897 while (end < size() && isWordSeparator(end))
4900 d->setMisspelled(from, end, result);
4902 result = d->speller_state_.getState(from);
4906 suggestions.clear();
4908 if (SpellChecker::misspelled(result)) {
4909 LYXERR(Debug::GUI, "misspelled word: \"" <<
4911 from << ".." << to << "]");
4913 speller->suggest(wl, suggestions);
4919 void Paragraph::anonymize()
4921 // This is a very crude anonymization for now
4922 for (char_type & c : d->text_)
4923 if (isLetterChar(c) || isNumber(c))
4928 void Paragraph::Private::markMisspelledWords(
4929 Language const * lang,
4930 pos_type const & first, pos_type const & last,
4931 SpellChecker::Result result,
4932 docstring const & word,
4933 SkipPositions const & skips,
4934 vector<WordLangTuple> const & docdict)
4936 if (!SpellChecker::misspelled(result)) {
4937 setMisspelled(first, last, SpellChecker::WORD_OK);
4941 SpellChecker * speller = theSpellChecker();
4942 // locate and enumerate the error positions
4943 int nerrors = speller->numMisspelledWords();
4945 SkipPositionsIterator it = skips.begin();
4946 SkipPositionsIterator et = skips.end();
4947 for (int index = 0; index < nerrors; ++index) {
4950 speller->misspelledWord(index, wstart, wlen);
4951 /// should not happen if speller supports range checks
4954 docstring const candidate = word.substr(wstart, wlen);
4955 wstart += first + numskipped;
4956 if (snext < wstart) {
4957 /// mark the range of correct spelling
4958 numskipped += countSkips(it, et, wstart);
4959 setMisspelled(snext,
4960 wstart - 1, SpellChecker::WORD_OK);
4962 snext = wstart + wlen;
4963 // Check whether the candidate is in the document's local dict
4964 vector<WordLangTuple>::const_iterator iit = docdict.begin();
4965 SpellChecker::Result actresult = result;
4966 for (; iit != docdict.end(); ++iit) {
4967 if (iit->lang()->code() != lang->code())
4969 if (iit->word() == candidate) {
4970 actresult = SpellChecker::WORD_OK;
4974 numskipped += countSkips(it, et, snext);
4975 /// mark the range of misspelling
4976 setMisspelled(wstart, snext, actresult);
4977 if (actresult == SpellChecker::WORD_OK)
4978 LYXERR(Debug::GUI, "local dictionary word: \"" <<
4979 candidate << "\" [" <<
4980 wstart << ".." << (snext-1) << "]");
4982 LYXERR(Debug::GUI, "misspelled word: \"" <<
4983 candidate << "\" [" <<
4984 wstart << ".." << (snext-1) << "]");
4987 if (snext <= last) {
4988 /// mark the range of correct spelling at end
4989 setMisspelled(snext, last, SpellChecker::WORD_OK);
4994 void Paragraph::spellCheck() const
4996 SpellChecker * speller = theSpellChecker();
4997 if (!speller || empty() ||!needsSpellCheck())
5001 d->rangeOfSpellCheck(start, endpos);
5002 if (speller->canCheckParagraph()) {
5003 // loop until we leave the range
5004 for (pos_type first = start; first < endpos; ) {
5005 pos_type last = endpos;
5006 Private::SkipPositions skips;
5007 Language * lang = d->locateSpellRange(first, last, skips);
5008 if (first >= endpos)
5010 // start the spell checker on the unit of meaning
5011 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5012 WordLangTuple wl = WordLangTuple(word, lang);
5013 BufferParams const & bparams = d->inset_owner_->buffer().params();
5014 SpellChecker::Result result = !word.empty() ?
5015 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5016 d->markMisspelledWords(lang, first, last, result, word, skips,
5017 bparams.spellignore());
5021 static docstring_list suggestions;
5022 pos_type to = endpos;
5023 while (start < endpos) {
5025 spellCheck(start, to, wl, suggestions, false);
5029 d->readySpellCheck();
5033 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5035 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5036 if (result || pos <= 0 || pos > size())
5038 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5039 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5044 string Paragraph::magicLabel() const
5047 ss << "magicparlabel-" << id();