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);
469 InsetCode ownerCode() const
471 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
474 /// Which Paragraph owns us?
478 Inset const * inset_owner_;
484 ParagraphParameters params_;
486 /// for recording and looking up changes
490 InsetList insetlist_;
493 pos_type begin_of_body_;
495 typedef docstring TextContainer;
499 typedef set<docstring> Words;
500 typedef map<string, Words> LangWordsMap;
504 Layout const * layout_;
506 SpellCheckerState speller_state_;
512 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
513 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
520 int Paragraph::Private::make_id()
522 // The id is unique per session across buffers because it is used in
523 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
526 static int next_id(0);
531 Paragraph::Private::Private(Private const & p, Paragraph * owner)
532 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
533 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
534 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
535 layout_(p.layout_), id_(make_id())
537 requestSpellCheck(p.text_.size());
541 Paragraph::Private::Private(Private const & p, Paragraph * owner,
542 pos_type beg, pos_type end)
543 : owner_(owner), inset_owner_(p.inset_owner_),
544 params_(p.params_), changes_(p.changes_),
545 insetlist_(p.insetlist_, beg, end),
546 begin_of_body_(p.begin_of_body_), words_(p.words_),
547 layout_(p.layout_), id_(make_id())
549 if (beg >= pos_type(p.text_.size()))
551 text_ = p.text_.substr(beg, end - beg);
553 FontList::const_iterator fcit = fontlist_.begin();
554 FontList::const_iterator fend = fontlist_.end();
555 for (; fcit != fend; ++fcit) {
556 if (fcit->pos() < beg)
558 if (fcit->pos() >= end) {
559 // Add last entry in the fontlist_.
560 fontlist_.set(text_.size() - 1, fcit->font());
563 // Add a new entry in the fontlist_.
564 fontlist_.set(fcit->pos() - beg, fcit->font());
566 requestSpellCheck(p.text_.size());
570 /////////////////////////////////////////////////////////////////////
574 /////////////////////////////////////////////////////////////////////
578 /** This helper class should be instantiated at the start of methods
579 * that can create or merge changes. If as a result the value of
580 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
583 struct ChangesMonitor {
585 ChangesMonitor(Paragraph & par)
586 : par_(par), was_changed_(par.isChanged()) {}
590 /* We may need to run updateBuffer to check whether the buffer
591 * contains changes (and toggle the changes toolbar). We do it
593 * 1. the `changedness' of the paragraph has changed,
594 * 2. and we are not in the situation where the buffer has changes
595 * and new changes are added to the paragraph.
598 if (par_.isChanged() != was_changed_
599 && par_.inInset().isBufferValid()
600 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
601 par_.inInset().buffer().forceUpdate();
602 } catch(support::ExceptionMessage const &) {}
607 Paragraph const & par_;
614 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
615 bool output_active, TocBackend & backend) const
617 d->changes_.addToToc(cdit, buf, output_active, backend);
621 bool Paragraph::isDeleted(pos_type start, pos_type end) const
623 LASSERT(start >= 0 && start <= size(), return false);
624 LASSERT(end > start && end <= size() + 1, return false);
626 return d->changes_.isDeleted(start, end);
630 bool Paragraph::isChanged(pos_type start, pos_type end) const
632 LASSERT(start >= 0 && start <= size(), return false);
633 LASSERT(end > start && end <= size() + 1, return false);
635 return d->changes_.isChanged(start, end);
638 // FIXME: Ideally the diverse isChanged() methods should account for that!
639 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
641 LASSERT(start >= 0 && start <= size(), return false);
642 LASSERT(end > start && end <= size() + 1, return false);
644 for (auto const & icit : d->insetlist_) {
645 if (icit.pos < start)
649 if (icit.inset && icit.inset->isChanged())
655 bool Paragraph::isChanged() const
657 return d->changes_.isChanged();
661 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
663 // keep the logic here in sync with the logic of eraseChars()
667 Change const & change = d->changes_.lookup(size());
668 return change.inserted() && change.currentAuthor();
671 Change Paragraph::parEndChange() const
673 return d->changes_.lookup(size());
677 void Paragraph::setChange(Change const & change)
679 // Make sure that Buffer::hasChangesPresent is updated
680 ChangesMonitor cm(*this);
682 // beware of the imaginary end-of-par character!
683 d->changes_.set(change, 0, size() + 1);
686 * Propagate the change recursively - but not in case of DELETED!
688 * Imagine that your co-author makes changes in an existing inset. He
689 * sends your document to you and you come to the conclusion that the
690 * inset should go completely. If you erase it, LyX must not delete all
691 * text within the inset. Otherwise, the change tracked insertions of
692 * your co-author get lost and there is no way to restore them later.
694 * Conclusion: An inset's content should remain untouched if you delete it
697 if (!change.deleted()) {
698 for (pos_type pos = 0; pos < size(); ++pos) {
699 if (Inset * inset = getInset(pos))
700 inset->setChange(change);
706 void Paragraph::setChange(pos_type pos, Change const & change)
708 // Make sure that Buffer::hasChangesPresent is updated
709 ChangesMonitor cm(*this);
711 LASSERT(pos >= 0 && pos <= size(), return);
712 d->changes_.set(change, pos);
714 // see comment in setChange(Change const &) above
715 if (!change.deleted() && pos < size())
716 if (Inset * inset = getInset(pos))
717 inset->setChange(change);
721 Change const & Paragraph::lookupChange(pos_type pos) const
723 LBUFERR(pos >= 0 && pos <= size());
724 return d->changes_.lookup(pos);
728 void Paragraph::acceptChanges(pos_type start, pos_type end)
730 // Make sure that Buffer::hasChangesPresent is updated
731 ChangesMonitor cm(*this);
733 LASSERT(start >= 0 && start <= size(), return);
734 LASSERT(end > start && end <= size() + 1, return);
736 for (pos_type pos = start; pos < end; ++pos) {
737 switch (lookupChange(pos).type) {
738 case Change::UNCHANGED:
739 // accept changes in nested inset
740 if (Inset * inset = getInset(pos))
741 inset->acceptChanges();
744 case Change::INSERTED:
745 d->changes_.set(Change(Change::UNCHANGED), pos);
746 // also accept changes in nested inset
747 if (Inset * inset = getInset(pos))
748 inset->acceptChanges();
751 case Change::DELETED:
752 // Suppress access to non-existent
753 // "end-of-paragraph char"
755 eraseChar(pos, false);
766 void Paragraph::rejectChanges(pos_type start, pos_type end)
768 LASSERT(start >= 0 && start <= size(), return);
769 LASSERT(end > start && end <= size() + 1, return);
771 // Make sure that Buffer::hasChangesPresent is updated
772 ChangesMonitor cm(*this);
774 for (pos_type pos = start; pos < end; ++pos) {
775 switch (lookupChange(pos).type) {
776 case Change::UNCHANGED:
777 // reject changes in nested inset
778 if (Inset * inset = getInset(pos))
779 inset->rejectChanges();
782 case Change::INSERTED:
783 // Suppress access to non-existent
784 // "end-of-paragraph char"
786 eraseChar(pos, false);
792 case Change::DELETED:
793 d->changes_.set(Change(Change::UNCHANGED), pos);
795 // Do NOT reject changes within a deleted inset!
796 // There may be insertions of a co-author inside of it!
804 void Paragraph::Private::insertChar(pos_type pos, char_type c,
805 Change const & change)
807 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
809 // Make sure that Buffer::hasChangesPresent is updated
810 ChangesMonitor cm(*owner_);
813 changes_.insert(change, pos);
815 // This is actually very common when parsing buffers (and
816 // maybe inserting ascii text)
817 if (pos == pos_type(text_.size())) {
818 // when appending characters, no need to update tables
820 // but we want spell checking
821 requestSpellCheck(pos);
825 text_.insert(text_.begin() + pos, c);
827 // Update the font table.
828 fontlist_.increasePosAfterPos(pos);
831 insetlist_.increasePosAfterPos(pos);
833 // Update list of misspelled positions
834 speller_state_.increasePosAfterPos(pos);
838 bool Paragraph::insertInset(pos_type pos, Inset * inset,
839 Font const & font, Change const & change)
841 LASSERT(inset, return false);
842 LASSERT(pos >= 0 && pos <= size(), return false);
844 // Make sure that Buffer::hasChangesPresent is updated
845 ChangesMonitor cm(*this);
847 // Paragraph::insertInset() can be used in cut/copy/paste operation where
848 // d->inset_owner_ is not set yet.
849 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
852 d->insertChar(pos, META_INSET, change);
853 LASSERT(d->text_[pos] == META_INSET, return false);
855 // Add a new entry in the insetlist_.
856 d->insetlist_.insert(inset, pos);
858 // Some insets require run of spell checker
859 requestSpellCheck(pos);
865 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
867 LASSERT(pos >= 0 && pos <= size(), return false);
869 // Make sure that Buffer::hasChangesPresent is updated
870 ChangesMonitor cm(*this);
872 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
875 Change change = d->changes_.lookup(pos);
877 // set the character to DELETED if
878 // a) it was previously unchanged or
879 // b) it was inserted by a co-author
881 if (!change.changed() ||
882 (change.inserted() && !change.currentAuthor())) {
883 setChange(pos, Change(Change::DELETED));
884 // request run of spell checker
885 requestSpellCheck(pos);
889 if (change.deleted())
893 // Don't physically access the imaginary end-of-paragraph character.
894 // eraseChar() can only mark it as DELETED. A physical deletion of
895 // end-of-par must be handled externally.
901 d->changes_.erase(pos);
903 // if it is an inset, delete the inset entry
904 if (d->text_[pos] == META_INSET)
905 d->insetlist_.erase(pos);
907 d->text_.erase(d->text_.begin() + pos);
909 // Update the fontlist_
910 d->fontlist_.erase(pos);
912 // Update the insetlist_
913 d->insetlist_.decreasePosAfterPos(pos);
915 // Update list of misspelled positions
916 d->speller_state_.decreasePosAfterPos(pos);
917 d->speller_state_.refreshLast(size());
923 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
925 LASSERT(start >= 0 && start <= size(), return 0);
926 LASSERT(end >= start && end <= size() + 1, return 0);
929 for (pos_type count = end - start; count; --count) {
930 if (!eraseChar(i, trackChanges))
937 // Handle combining characters
938 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
939 otexstream & os, char_type c, char_type next,
940 OutputParams const & runparams)
942 // Writing next here may circumvent a possible font change between
943 // c and next. Since next is only output if it forms a surrogate pair
944 // with c we can ignore this:
945 // A font change inside a surrogate pair does not make sense and is
946 // hopefully impossible to input.
947 // FIXME: change tracking
948 // Is this correct WRT change tracking?
949 Encoding const & encoding = *(runparams.encoding);
950 docstring latex1 = encoding.latexChar(next).first;
951 if (runparams.inIPA) {
952 string const tipashortcut = Encodings::TIPAShortcut(next);
953 if (!tipashortcut.empty()) {
954 latex1 = from_ascii(tipashortcut);
957 docstring latex2 = encoding.latexChar(c).first;
959 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
960 // Encoding supports the combination:
961 // output as is (combining char after base char).
962 os << latex2 << latex1;
963 return latex1.length() + latex2.length();
966 os << latex1 << "{" << latex2 << "}";
967 return latex1.length() + latex2.length() + 2;
971 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
972 OutputParams const & runparams,
975 unsigned int & column,
977 Layout const & style)
979 if (style.pass_thru || runparams.pass_thru)
982 if (i + 1 < int(text_.size())) {
983 char_type next = text_[i + 1];
984 if (Encodings::isCombiningChar(next)) {
985 // This space has an accent, so we must always output it.
986 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
991 if (runparams.linelen > 0
992 && column > runparams.linelen
994 && text_[i - 1] != ' '
995 && (i + 1 < int(text_.size()))
996 // same in FreeSpacing mode
997 && !owner_->isFreeSpacing()
998 // In typewriter mode, we want to avoid
999 // ! . ? : at the end of a line
1000 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1001 && (text_[i - 1] == '.'
1002 || text_[i - 1] == '?'
1003 || text_[i - 1] == ':'
1004 || text_[i - 1] == '!'))) {
1006 os.texrow().start(owner_->id(), i + 1);
1008 } else if (style.free_spacing) {
1017 void Paragraph::Private::latexInset(BufferParams const & bparams,
1019 OutputParams & runparams,
1020 Font & running_font,
1022 Font const & outerfont,
1024 Change & running_change,
1025 Layout const & style,
1027 unsigned int & column,
1028 bool const fontswitch_inset,
1029 bool const closeLanguage,
1030 bool const lang_switched_at_inset)
1032 Inset * inset = owner_->getInset(i);
1035 if (style.pass_thru) {
1036 odocstringstream ods;
1037 inset->plaintext(ods, runparams);
1042 // FIXME: move this to InsetNewline::latex
1043 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1044 // newlines are handled differently here than
1045 // the default in simpleTeXSpecialChars().
1046 if (!style.newline_allowed) {
1050 bool needPar = false;
1051 column += running_font.latexWriteEndChanges(
1052 os, bparams, runparams,
1053 basefont, basefont, needPar);
1057 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1060 basefont = owner_->getLayoutFont(bparams, outerfont);
1061 running_font = basefont;
1063 if (runparams.moving_arg)
1067 os.texrow().start(owner_->id(), i + 1);
1071 if (owner_->isDeleted(i)) {
1072 if( ++runparams.inDeletedInset == 1)
1073 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1076 if (inset->canTrackChanges()) {
1077 column += Changes::latexMarkChange(os, bparams, running_change,
1078 Change(Change::UNCHANGED), runparams);
1079 running_change = Change(Change::UNCHANGED);
1083 odocstream::pos_type const len = os.os().tellp();
1085 if (inset->forceLTR(runparams)
1086 && running_font.isRightToLeft()
1087 // ERT is an exception, it should be output with no
1088 // decorations at all
1089 && inset->lyxCode() != ERT_CODE) {
1090 if (runparams.use_polyglossia) {
1092 } else if (running_font.language()->lang() == "farsi"
1093 || running_font.language()->lang() == "arabic_arabi")
1094 os << "\\textLR{" << termcmd;
1100 if (open_font && fontswitch_inset) {
1101 bool lang_closed = false;
1102 // Close language if needed
1103 if (closeLanguage && !lang_switched_at_inset) {
1104 // We need prev_font here as language changes directly at inset
1105 // will only be started inside the inset.
1106 Font const prev_font = (i > 0) ?
1107 owner_->getFont(bparams, i - 1, outerfont)
1109 Font tmpfont(basefont);
1110 tmpfont.setLanguage(prev_font.language());
1111 bool needPar = false;
1112 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1114 needPar, closeLanguage);
1116 lang_closed = count > 0;
1118 // Update the running_font, making sure, however,
1119 // to leave the language as it was.
1120 // FIXME: probably a better way to keep track of the old
1121 // language, than copying the entire font?
1122 Font const copy_font(running_font);
1123 basefont = owner_->getLayoutFont(bparams, outerfont);
1124 running_font = basefont;
1126 running_font.setLanguage(copy_font.language());
1127 OutputParams rp = runparams;
1128 rp.encoding = basefont.language()->encoding();
1129 // For these, we use switches, so they should be taken as
1130 // base inside the inset.
1131 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1132 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1133 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1134 // Now re-do font changes in a way needed here
1135 // (using switches with multi-par insets)
1136 InsetText const * textinset = inset->asInsetText();
1137 bool const cprotect = textinset
1138 ? textinset->hasCProtectContent(runparams.moving_arg)
1139 && !textinset->text().isMainText()
1141 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1147 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1151 runparams.local_font = &basefont;
1154 if (fontswitch_inset && !closeLanguage) {
1155 // The directionality has been switched at inset.
1156 // Force markup inside.
1157 runparams.local_font = &basefont;
1160 size_t const previous_row_count = os.texrow().rows();
1163 runparams.lastid = id_;
1164 runparams.lastpos = i;
1165 inset->latex(os, runparams);
1166 } catch (EncodingException & e) {
1167 // add location information and throw again.
1176 if (os.texrow().rows() > previous_row_count) {
1177 os.texrow().start(owner_->id(), i + 1);
1180 column += (unsigned int)(os.os().tellp() - len);
1183 if (owner_->isDeleted(i))
1184 --runparams.inDeletedInset;
1188 void Paragraph::Private::latexSpecialChar(otexstream & os,
1189 BufferParams const & bparams,
1190 OutputParams const & runparams,
1191 Font const & running_font,
1192 string & alien_script,
1193 Layout const & style,
1196 unsigned int & column)
1198 char_type const c = owner_->getUChar(bparams, runparams, i);
1200 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1201 || contains(style.pass_thru_chars, c)
1202 || contains(runparams.pass_thru_chars, c)) {
1203 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1207 os << "\\braceleft ";
1209 os << "\\braceright ";
1213 else if (c != '\0') {
1214 Encoding const * const enc = runparams.encoding;
1215 if (enc && !enc->encodable(c))
1216 throw EncodingException(c);
1222 // TIPA uses its own T3 encoding
1223 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1225 // If T1 font encoding is used, use the special
1226 // characters it provides.
1227 // NOTE: Some languages reset the font encoding internally to a
1228 // non-standard font encoding. If we are using such a language,
1229 // we do not output special T1 chars.
1230 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1231 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1232 && latexSpecialT1(c, os, i, column))
1234 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1235 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1236 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1239 // Otherwise, we use what LaTeX provides us.
1242 os << "\\textbackslash" << termcmd;
1246 os << "\\textless" << termcmd;
1250 os << "\\textgreater" << termcmd;
1254 os << "\\textbar" << termcmd;
1259 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1260 (end_pos == -1 || i + 1 < end_pos) &&
1261 text_[i+1] == '-') {
1262 // Prevent "--" becoming an en dash and "---" an em dash.
1263 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1269 os << "\\textquotedbl" << termcmd;
1274 case '%': case '#': case '{':
1282 os << "\\textasciitilde" << termcmd;
1287 os << "\\textasciicircum" << termcmd;
1294 // avoid being mistaken for optional arguments
1302 // Blanks are printed before font switching.
1303 // Sure? I am not! (try nice-latex)
1304 // I am sure it's correct. LyX might be smarter
1305 // in the future, but for now, nothing wrong is
1311 // XeTeX's dash behaviour is determined via a global setting
1312 if (bparams.use_dash_ligatures
1313 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1315 // TODO #10961: && not in inset Flex Code
1316 // TODO #10961: && not in layout LyXCode
1317 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1334 Encoding const & encoding = *(runparams.encoding);
1335 char_type next = '\0';
1336 if (i + 1 < int(text_.size())) {
1337 next = text_[i + 1];
1338 if (Encodings::isCombiningChar(next)) {
1339 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1344 pair<docstring, bool> latex = encoding.latexChar(c);
1345 docstring nextlatex;
1346 bool nexttipas = false;
1347 string nexttipashortcut;
1348 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1349 nextlatex = encoding.latexChar(next).first;
1350 if (runparams.inIPA) {
1351 nexttipashortcut = Encodings::TIPAShortcut(next);
1352 nexttipas = !nexttipashortcut.empty();
1356 if (runparams.inIPA) {
1357 string const tipashortcut = Encodings::TIPAShortcut(c);
1358 if (!tipashortcut.empty()) {
1359 latex.first = from_ascii(tipashortcut);
1360 latex.second = false;
1364 // eventually close "script wrapper" command (see `Paragraph::latex`)
1365 if (!alien_script.empty()
1366 && alien_script != Encodings::isKnownScriptChar(next)) {
1367 column += latex.first.length();
1368 alien_script.clear();
1369 os << latex.first << "}";
1373 && ((!prefixIs(nextlatex, '\\')
1374 && !prefixIs(nextlatex, '{')
1375 && !prefixIs(nextlatex, '}'))
1377 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1379 // Prevent eating of a following space or command corruption by
1380 // following characters
1381 if (next == ' ' || next == '\0') {
1382 column += latex.first.length() + 1;
1383 os << latex.first << "{}";
1385 column += latex.first.length();
1386 os << latex.first << " ";
1389 column += latex.first.length() - 1;
1397 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1398 pos_type i, unsigned int & column) const
1404 // In T1 encoding, these characters exist
1405 // but we should avoid ligatures
1406 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1408 os << "\\textcompwordmark" << termcmd;
1415 // soul.sty breaks with \char`\"
1416 os << "\\textquotedbl" << termcmd;
1425 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1426 pos_type i, unsigned int & column) const
1428 // TU encoding is currently on par with T1.
1429 return latexSpecialT1(c, os, i, column);
1433 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1434 pos_type /*i*/, unsigned int & column) const
1444 os << "\\textvertline" << termcmd;
1453 void Paragraph::Private::validate(LaTeXFeatures & features) const
1455 if (layout_->inpreamble && inset_owner_) {
1456 // FIXME: Using a string stream here circumvents the encoding
1457 // switching machinery of odocstream. Therefore the
1458 // output is wrong if this paragraph contains content
1459 // that needs to switch encoding.
1460 Buffer const & buf = inset_owner_->buffer();
1461 otexstringstream os;
1462 os << layout_->preamble();
1463 size_t const length = os.length();
1464 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1465 buf.getParFromID(owner_->id()).pit(), os,
1466 features.runparams(), string(), 0, -1, true);
1467 if (os.length() > length)
1468 features.addPreambleSnippet(os.release(), true);
1471 if (features.runparams().flavor == Flavor::Html
1472 && layout_->htmltitle()) {
1473 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1476 // check the params.
1477 if (!params_.spacing().isDefault())
1478 features.require("setspace");
1481 features.useLayout(layout_->name());
1484 fontlist_.validate(features);
1486 // then the indentation
1487 if (!params_.leftIndent().zero())
1488 features.require("ParagraphLeftIndent");
1491 InsetList::const_iterator icit = insetlist_.begin();
1492 InsetList::const_iterator iend = insetlist_.end();
1493 for (; icit != iend; ++icit) {
1495 features.inDeletedInset(owner_->isDeleted(icit->pos));
1496 if (icit->inset->lyxCode() == FOOT_CODE) {
1497 // FIXME: an item inset would make things much easier.
1498 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1499 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1500 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1501 && (icit->pos < begin_of_body_
1502 || (icit->pos == begin_of_body_
1503 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1504 features.saveNoteEnv("description");
1506 icit->inset->validate(features);
1507 features.inDeletedInset(false);
1508 if (layout_->needprotect &&
1509 icit->inset->lyxCode() == FOOT_CODE)
1510 features.require("NeedLyXFootnoteCode");
1514 // then the contents
1515 BufferParams const bp = features.runparams().is_child
1516 ? features.buffer().masterParams() : features.buffer().params();
1517 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1518 char_type c = text_[i];
1519 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1521 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1522 features.require("textquotedblp");
1523 else if (bp.main_font_encoding() != "T1"
1524 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1525 features.require("textquotedbl");
1526 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1527 // features that depend on the font or input encoding
1528 string feats = ci.textpreamble();
1529 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1530 if (fontenc.empty())
1531 fontenc = features.runparams().main_fontenc;
1532 while (!feats.empty()) {
1534 feats = split(feats, feat, ',');
1535 if (contains(feat, "!=")) {
1536 // a feature that is required except for the spcified
1537 // font or input encodings
1539 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1540 // multiple encodings are separated by semicolon
1541 vector<string> context = getVectorFromString(contexts, ";");
1542 // require feature if the context matches neither current font
1543 // nor input encoding
1544 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1545 && std::find(context.begin(), context.end(),
1546 features.runparams().encoding->name()) == context.end())
1547 features.require(realfeature);
1548 } else if (contains(feat, '=')) {
1549 // a feature that is required only for the spcified
1550 // font or input encodings
1552 string const contexts = split(feat, realfeature, '=');
1553 // multiple encodings are separated by semicolon
1554 vector<string> context = getVectorFromString(contexts, ";");
1555 // require feature if the context matches either current font
1556 // or input encoding
1557 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1558 || std::find(context.begin(), context.end(),
1559 features.runparams().encoding->name()) != context.end())
1560 features.require(realfeature);
1563 } else if (!bp.use_dash_ligatures
1564 && (c == 0x2013 || c == 0x2014)
1565 && bp.useNonTeXFonts
1566 && features.runparams().flavor == Flavor::XeTeX)
1567 // XeTeX's dash behaviour is determined via a global setting
1568 features.require("xetexdashbreakstate");
1569 BufferEncodings::validate(c, features);
1573 /////////////////////////////////////////////////////////////////////
1577 /////////////////////////////////////////////////////////////////////
1580 Layout const emptyParagraphLayout;
1583 Paragraph::Paragraph()
1584 : d(new Paragraph::Private(this, emptyParagraphLayout))
1591 Paragraph::Paragraph(Paragraph const & par)
1592 : itemdepth(par.itemdepth),
1593 d(new Paragraph::Private(*par.d, this))
1599 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1600 : itemdepth(par.itemdepth),
1601 d(new Paragraph::Private(*par.d, this, beg, end))
1607 Paragraph & Paragraph::operator=(Paragraph const & par)
1609 // needed as we will destroy the private part before copying it
1611 itemdepth = par.itemdepth;
1615 d = new Private(*par.d, this);
1622 Paragraph::~Paragraph()
1631 // this shall be called just before every "os << ..." action.
1632 void flushString(ostream & os, docstring & s)
1641 void Paragraph::write(ostream & os, BufferParams const & bparams,
1642 depth_type & depth) const
1644 // The beginning or end of a deeper (i.e. nested) area?
1645 if (depth != d->params_.depth()) {
1646 if (d->params_.depth() > depth) {
1647 while (d->params_.depth() > depth) {
1648 os << "\n\\begin_deeper";
1652 while (d->params_.depth() < depth) {
1653 os << "\n\\end_deeper";
1659 // First write the layout
1660 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1662 d->params_.write(os);
1664 Font font1(inherit_font, bparams.language);
1666 Change running_change = Change(Change::UNCHANGED);
1668 // this string is used as a buffer to avoid repetitive calls
1669 // to to_utf8(), which turn out to be expensive (JMarc)
1670 docstring write_buffer;
1673 for (pos_type i = 0; i <= size(); ++i) {
1675 Change const & change = lookupChange(i);
1676 if (change != running_change)
1677 flushString(os, write_buffer);
1678 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1679 running_change = change;
1684 // Write font changes
1685 Font font2 = getFontSettings(bparams, i);
1686 if (font2 != font1) {
1687 flushString(os, write_buffer);
1688 font2.lyxWriteChanges(font1, os);
1693 char_type const c = d->text_[i];
1696 if (Inset const * inset = getInset(i)) {
1697 flushString(os, write_buffer);
1698 if (inset->directWrite()) {
1699 // international char, let it write
1700 // code directly so it's shorter in
1706 os << "\\begin_inset ";
1708 os << "\n\\end_inset\n\n";
1711 // FIXME This can be removed again once the mystery
1712 // crash has been resolved.
1717 flushString(os, write_buffer);
1718 os << "\n\\backslash\n";
1722 flushString(os, write_buffer);
1723 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1730 if ((column > 70 && c == ' ')
1732 flushString(os, write_buffer);
1736 // this check is to amend a bug. LyX sometimes
1737 // inserts '\0' this could cause problems.
1739 write_buffer.push_back(c);
1741 LYXERR0("NUL char in structure.");
1747 flushString(os, write_buffer);
1748 os << "\n\\end_layout\n";
1749 // FIXME This can be removed again once the mystery
1750 // crash has been resolved.
1755 void Paragraph::validate(LaTeXFeatures & features) const
1757 d->validate(features);
1758 bool fragile = features.runparams().moving_arg;
1759 fragile |= layout().needprotect;
1760 if (inInset().getLayout().isNeedProtect())
1762 if (needsCProtection(fragile))
1763 features.require("cprotect");
1767 void Paragraph::insert(pos_type pos, docstring const & str,
1768 Font const & font, Change const & change)
1770 for (size_t i = 0, n = str.size(); i != n ; ++i)
1771 insertChar(pos + i, str[i], font, change);
1775 void Paragraph::appendChar(char_type c, Font const & font,
1776 Change const & change)
1778 // Make sure that Buffer::hasChangesPresent is updated
1779 ChangesMonitor cm(*this);
1782 d->changes_.insert(change, d->text_.size());
1783 // when appending characters, no need to update tables
1784 d->text_.push_back(c);
1785 setFont(d->text_.size() - 1, font);
1786 d->requestSpellCheck(d->text_.size() - 1);
1790 void Paragraph::appendString(docstring const & s, Font const & font,
1791 Change const & change)
1793 // Make sure that Buffer::hasChangesPresent is updated
1794 ChangesMonitor cm(*this);
1796 pos_type end = s.size();
1797 size_t oldsize = d->text_.size();
1798 size_t newsize = oldsize + end;
1799 size_t capacity = d->text_.capacity();
1800 if (newsize >= capacity)
1801 d->text_.reserve(max(capacity + 100, newsize));
1803 // when appending characters, no need to update tables
1806 // FIXME: Optimize this!
1807 for (size_t i = oldsize; i != newsize; ++i) {
1809 d->changes_.insert(change, i);
1810 d->requestSpellCheck(i);
1812 d->fontlist_.set(oldsize, font);
1813 d->fontlist_.set(newsize - 1, font);
1817 void Paragraph::insertChar(pos_type pos, char_type c,
1820 d->insertChar(pos, c, Change(trackChanges ?
1821 Change::INSERTED : Change::UNCHANGED));
1825 void Paragraph::insertChar(pos_type pos, char_type c,
1826 Font const & font, bool trackChanges)
1828 d->insertChar(pos, c, Change(trackChanges ?
1829 Change::INSERTED : Change::UNCHANGED));
1834 void Paragraph::insertChar(pos_type pos, char_type c,
1835 Font const & font, Change const & change)
1837 d->insertChar(pos, c, change);
1842 void Paragraph::resetFonts(Font const & font)
1844 d->fontlist_.clear();
1845 d->fontlist_.set(0, font);
1846 d->fontlist_.set(d->text_.size() - 1, font);
1849 // Gets uninstantiated font setting at position.
1850 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1854 LYXERR0("pos: " << pos << " size: " << size());
1858 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1859 if (cit != d->fontlist_.end())
1862 if (pos == size() && !empty())
1863 return getFontSettings(bparams, pos - 1);
1865 // Optimisation: avoid a full font instantiation if there is no
1866 // language change from previous call.
1867 static Font previous_font;
1868 static Language const * previous_lang = nullptr;
1869 Language const * lang = getParLanguage(bparams);
1870 if (lang != previous_lang) {
1871 previous_lang = lang;
1872 previous_font = Font(inherit_font, lang);
1874 return previous_font;
1878 FontSpan Paragraph::fontSpan(pos_type pos) const
1880 LBUFERR(pos <= size());
1883 return FontSpan(pos, pos);
1886 FontList::const_iterator cit = d->fontlist_.begin();
1887 FontList::const_iterator end = d->fontlist_.end();
1888 for (; cit != end; ++cit) {
1889 if (cit->pos() >= pos) {
1890 if (pos >= beginOfBody())
1891 return FontSpan(max(start, beginOfBody()),
1894 return FontSpan(start,
1895 min(beginOfBody() - 1,
1898 start = cit->pos() + 1;
1901 // This should not happen, but if so, we take no chances.
1902 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1903 LASSERT(false, return FontSpan(pos, pos));
1907 // Gets uninstantiated font setting at position 0
1908 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1910 if (!empty() && !d->fontlist_.empty())
1911 return d->fontlist_.begin()->font();
1913 // Optimisation: avoid a full font instantiation if there is no
1914 // language change from previous call.
1915 static Font previous_font;
1916 static Language const * previous_lang = nullptr;
1917 if (bparams.language != previous_lang) {
1918 previous_lang = bparams.language;
1919 previous_font = Font(inherit_font, bparams.language);
1922 return previous_font;
1926 // Gets the fully instantiated font at a given position in a paragraph
1927 // This is basically the same function as Text::GetFont() in text2.cpp.
1928 // The difference is that this one is used for generating the LaTeX file,
1929 // and thus cosmetic "improvements" are disallowed: This has to deliver
1930 // the true picture of the buffer. (Asger)
1931 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1932 Font const & outerfont) const
1936 Font font = getFontSettings(bparams, pos);
1938 pos_type const body_pos = beginOfBody();
1939 FontInfo & fi = font.fontInfo();
1941 fi.realize(d->layout_->labelfont);
1943 fi.realize(d->layout_->font);
1945 fi.realize(outerfont.fontInfo());
1946 fi.realize(bparams.getFont().fontInfo());
1952 Font const Paragraph::getLabelFont
1953 (BufferParams const & bparams, Font const & outerfont) const
1955 FontInfo tmpfont = d->layout_->labelfont;
1956 tmpfont.realize(outerfont.fontInfo());
1957 tmpfont.realize(bparams.getFont().fontInfo());
1958 return Font(tmpfont, getParLanguage(bparams));
1962 Font const Paragraph::getLayoutFont
1963 (BufferParams const & bparams, Font const & outerfont) const
1965 FontInfo tmpfont = d->layout_->font;
1966 tmpfont.realize(outerfont.fontInfo());
1967 tmpfont.realize(bparams.getFont().fontInfo());
1968 return Font(tmpfont, getParLanguage(bparams));
1972 char_type Paragraph::getUChar(BufferParams const & bparams,
1973 OutputParams const & rp,
1976 char_type c = d->text_[pos];
1978 // Return unchanged character in LTR languages
1979 // or if we use poylglossia/bidi (XeTeX).
1980 if (rp.useBidiPackage()
1981 || !getFontSettings(bparams, pos).isRightToLeft())
1984 // Without polyglossia/bidi, we need to account for some special cases.
1985 // FIXME This needs to be audited!
1987 // * The input is as expected for all delimiters
1988 // => checked for Hebrew!
1989 // * The output matches the display in the LyX workarea
1990 // => checked for Hebrew!
1991 // * The special cases below are really necessary
1992 // => checked for Hebrew!
1993 // * In arabic_arabi, brackets are transformed to Arabic
1994 // Ornate Parentheses. Is this is really wanted?
1996 string const & lang = getFontSettings(bparams, pos).language()->lang();
1999 // 1. In the following languages, parentheses need to be reversed.
2000 // Also with polyglodia/luabidi
2001 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2003 // 2. In the following languages, brackets don't need to be reversed.
2004 bool const reversebrackets = lang != "arabic_arabtex"
2005 && lang != "arabic_arabi"
2008 // Now swap delimiters if needed.
2019 if (reversebrackets)
2023 if (reversebrackets)
2044 void Paragraph::setFont(pos_type pos, Font const & font)
2046 LASSERT(pos <= size(), return);
2048 // First, reduce font against layout/label font
2049 // Update: The setCharFont() routine in text2.cpp already
2050 // reduces font, so we don't need to do that here. (Asger)
2052 d->fontlist_.set(pos, font);
2056 void Paragraph::makeSameLayout(Paragraph const & par)
2058 d->layout_ = par.d->layout_;
2059 d->params_ = par.d->params_;
2063 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2065 if (isFreeSpacing())
2071 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2072 if (eraseChar(pos, trackChanges))
2078 return count > 0 || pos > 0;
2082 bool Paragraph::hasSameLayout(Paragraph const & par) const
2084 return par.d->layout_ == d->layout_
2085 && d->params_.sameLayout(par.d->params_);
2089 depth_type Paragraph::getDepth() const
2091 return d->params_.depth();
2095 depth_type Paragraph::getMaxDepthAfter() const
2097 if (d->layout_->isEnvironment())
2098 return d->params_.depth() + 1;
2100 return d->params_.depth();
2104 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2106 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2107 return getDefaultAlign(bparams);
2109 return d->params_.align();
2113 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2115 LyXAlignment res = layout().align;
2116 if (isRTL(bparams)) {
2118 if (res == LYX_ALIGN_LEFT)
2119 res = LYX_ALIGN_RIGHT;
2120 else if (res == LYX_ALIGN_RIGHT)
2121 res = LYX_ALIGN_LEFT;
2127 docstring const & Paragraph::labelString() const
2129 return d->params_.labelString();
2133 // the next two functions are for the manual labels
2134 docstring const Paragraph::getLabelWidthString() const
2136 if (d->layout_->margintype == MARGIN_MANUAL
2137 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2138 return d->params_.labelWidthString();
2140 return _("Senseless with this layout!");
2144 void Paragraph::setLabelWidthString(docstring const & s)
2146 d->params_.labelWidthString(s);
2150 docstring Paragraph::expandLabel(Layout const & layout,
2151 BufferParams const & bparams) const
2153 return expandParagraphLabel(layout, bparams, true);
2157 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2158 BufferParams const & bparams, bool process_appendix) const
2160 DocumentClass const & tclass = bparams.documentClass();
2161 string const & lang = getParLanguage(bparams)->code();
2162 bool const in_appendix = process_appendix && d->params_.appendix();
2163 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2165 if (fmt.empty() && !layout.counter.empty())
2166 return tclass.counters().theCounter(layout.counter, lang);
2168 // handle 'inherited level parts' in 'fmt',
2169 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2170 size_t const i = fmt.find('@', 0);
2171 if (i != docstring::npos) {
2172 size_t const j = fmt.find('@', i + 1);
2173 if (j != docstring::npos) {
2174 docstring parent(fmt, i + 1, j - i - 1);
2175 docstring label = from_ascii("??");
2176 if (tclass.hasLayout(parent))
2177 label = expandParagraphLabel(tclass[parent], bparams,
2179 fmt = docstring(fmt, 0, i) + label
2180 + docstring(fmt, j + 1, docstring::npos);
2184 return tclass.counters().counterLabel(fmt, lang);
2188 void Paragraph::applyLayout(Layout const & new_layout)
2190 d->layout_ = &new_layout;
2191 LyXAlignment const oldAlign = d->params_.align();
2193 if (!(oldAlign & d->layout_->alignpossible)) {
2194 frontend::Alert::warning(_("Alignment not permitted"),
2195 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2196 d->params_.align(LYX_ALIGN_LAYOUT);
2201 pos_type Paragraph::beginOfBody() const
2203 return d->begin_of_body_;
2207 void Paragraph::setBeginOfBody()
2209 if (d->layout_->labeltype != LABEL_MANUAL) {
2210 d->begin_of_body_ = 0;
2214 // Unroll the first two cycles of the loop
2215 // and remember the previous character to
2216 // remove unnecessary getChar() calls
2218 pos_type end = size();
2219 bool prev_char_deleted = false;
2220 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2223 char_type previous_char = d->text_[i];
2224 if (!(isNewline(i) || isEnvSeparator(i))) {
2226 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2227 char_type temp = d->text_[i];
2228 prev_char_deleted = isDeleted(i);
2229 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2232 previous_char = temp;
2238 d->begin_of_body_ = i;
2242 bool Paragraph::allowParagraphCustomization() const
2244 return inInset().allowParagraphCustomization();
2248 bool Paragraph::usePlainLayout() const
2250 return inInset().usePlainLayout();
2254 bool Paragraph::isPassThru() const
2256 return inInset().isPassThru() || d->layout_->pass_thru;
2261 // paragraphs inside floats need different alignment tags to avoid
2264 bool noTrivlistCentering(InsetCode code)
2266 return code == FLOAT_CODE
2267 || code == WRAP_CODE
2268 || code == CELL_CODE;
2272 string correction(string const & orig)
2274 if (orig == "flushleft")
2275 return "raggedright";
2276 if (orig == "flushright")
2277 return "raggedleft";
2278 if (orig == "center")
2284 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2285 InsetCode code, bool const lastpar, int & col)
2287 string macro = suffix + "{";
2288 if (noTrivlistCentering(code)) {
2290 // the last paragraph in non-trivlist-aligned
2291 // context is special (to avoid unwanted whitespace)
2292 if (suffix == "\\begin") {
2293 macro = "\\" + correction(env) + "{}";
2294 os << from_ascii(macro);
2295 col += macro.size();
2300 macro += correction(env);
2304 if (suffix == "\\par\\end") {
2308 os << from_ascii(macro);
2309 col += macro.size();
2310 if (suffix == "\\begin") {
2320 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2321 otexstream & os, OutputParams const & runparams) const
2326 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2327 (layout_->toggle_indent != ITOGGLE_NEVER) :
2328 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2330 if (canindent && params_.noindent() && !layout_->pass_thru) {
2331 os << "\\noindent ";
2335 LyXAlignment const curAlign = params_.align();
2337 if (curAlign == layout_->align)
2341 case LYX_ALIGN_NONE:
2342 case LYX_ALIGN_BLOCK:
2343 case LYX_ALIGN_LAYOUT:
2344 case LYX_ALIGN_SPECIAL:
2345 case LYX_ALIGN_DECIMAL:
2347 case LYX_ALIGN_LEFT:
2348 case LYX_ALIGN_RIGHT:
2349 case LYX_ALIGN_CENTER:
2350 if (runparams.moving_arg) {
2357 string const begin_tag = "\\begin";
2358 InsetCode code = ownerCode();
2359 bool const lastpar = runparams.isLastPar;
2360 // RTL in classic (PDF)LaTeX (without the Bidi package)
2361 // Luabibdi (used by LuaTeX) behaves like classic
2362 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2363 && !runparams.useBidiPackage();
2366 case LYX_ALIGN_NONE:
2367 case LYX_ALIGN_BLOCK:
2368 case LYX_ALIGN_LAYOUT:
2369 case LYX_ALIGN_SPECIAL:
2370 case LYX_ALIGN_DECIMAL:
2372 case LYX_ALIGN_LEFT: {
2374 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2375 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2377 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2379 } case LYX_ALIGN_RIGHT: {
2381 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2382 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2384 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2386 } case LYX_ALIGN_CENTER: {
2387 corrected_env(os, begin_tag, "center", code, lastpar, column);
2396 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2397 otexstream & os, OutputParams const & runparams) const
2399 LyXAlignment const curAlign = params_.align();
2401 if (curAlign == layout_->align)
2405 case LYX_ALIGN_NONE:
2406 case LYX_ALIGN_BLOCK:
2407 case LYX_ALIGN_LAYOUT:
2408 case LYX_ALIGN_SPECIAL:
2409 case LYX_ALIGN_DECIMAL:
2411 case LYX_ALIGN_LEFT:
2412 case LYX_ALIGN_RIGHT:
2413 case LYX_ALIGN_CENTER:
2414 if (runparams.moving_arg)
2419 bool output = false;
2421 string const end_tag = "\\par\\end";
2422 InsetCode code = ownerCode();
2423 bool const lastpar = runparams.isLastPar;
2424 // RTL in classic (PDF)LaTeX (without the Bidi package)
2425 // Luabibdi (used by LuaTeX) behaves like classic
2426 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2427 && !runparams.useBidiPackage();
2430 case LYX_ALIGN_NONE:
2431 case LYX_ALIGN_BLOCK:
2432 case LYX_ALIGN_LAYOUT:
2433 case LYX_ALIGN_SPECIAL:
2434 case LYX_ALIGN_DECIMAL:
2436 case LYX_ALIGN_LEFT: {
2438 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2439 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2441 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2443 } case LYX_ALIGN_RIGHT: {
2445 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2446 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2448 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2450 } case LYX_ALIGN_CENTER: {
2451 corrected_env(os, end_tag, "center", code, lastpar, col);
2456 return output || lastpar;
2460 // This one spits out the text of the paragraph
2461 void Paragraph::latex(BufferParams const & bparams,
2462 Font const & outerfont,
2464 OutputParams const & runparams,
2465 int start_pos, int end_pos, bool force) const
2467 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2469 // FIXME This check should not be needed. Perhaps issue an
2470 // error if it triggers.
2471 Layout const & style = inInset().forcePlainLayout() ?
2472 bparams.documentClass().plainLayout() : *d->layout_;
2474 if (!force && style.inpreamble)
2477 bool const allowcust = allowParagraphCustomization();
2479 // Current base font for all inherited font changes, without any
2480 // change caused by an individual character, except for the language:
2481 // It is set to the language of the first character.
2482 // As long as we are in the label, this font is the base font of the
2483 // label. Before the first body character it is set to the base font
2487 // If there is an open font-encoding changing command (script wrapper),
2488 // alien_script is set to its name
2489 string alien_script;
2492 // Maybe we have to create a optional argument.
2493 pos_type body_pos = beginOfBody();
2494 unsigned int column = 0;
2496 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2497 Font const real_outerfont = (!inInset().inheritFont()
2498 && runparams.local_font != nullptr)
2499 ? Font(runparams.local_font->fontInfo()) : outerfont;
2502 // the optional argument is kept in curly brackets in
2503 // case it contains a ']'
2504 // This is not strictly needed, but if this is changed it
2505 // would be a file format change, and tex2lyx would need
2506 // to be adjusted, since it unconditionally removes the
2507 // braces when it parses \item.
2510 basefont = getLabelFont(bparams, real_outerfont);
2512 basefont = getLayoutFont(bparams, real_outerfont);
2515 // Which font is currently active?
2516 Font running_font(basefont);
2517 // Do we have an open font change?
2518 bool open_font = false;
2520 Change runningChange =
2521 runparams.inDeletedInset && !inInset().canTrackChanges()
2522 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2524 Encoding const * const prev_encoding = runparams.encoding;
2526 os.texrow().start(id(), 0);
2528 // if the paragraph is empty, the loop will not be entered at all
2530 // For InTitle commands, we have already opened a group
2531 // in output_latex::TeXOnePar.
2532 if (style.isCommand() && !style.intitle) {
2536 if (!style.leftdelim().empty()) {
2537 os << style.leftdelim();
2538 column += style.leftdelim().size();
2541 column += d->startTeXParParams(bparams, os, runparams);
2544 // Whether a \par can be issued for insets typeset inline with text.
2545 // Yes if greater than 0. This has to be static.
2546 THREAD_LOCAL_STATIC int parInline = 0;
2548 for (pos_type i = 0; i < size(); ++i) {
2549 // First char in paragraph or after label?
2550 if (i == body_pos) {
2553 bool needPar = false;
2554 column += running_font.latexWriteEndChanges(
2555 os, bparams, runparams,
2556 basefont, basefont, needPar);
2559 basefont = getLayoutFont(bparams, real_outerfont);
2560 running_font = basefont;
2562 column += Changes::latexMarkChange(os, bparams,
2563 runningChange, Change(Change::UNCHANGED),
2565 runningChange = Change(Change::UNCHANGED);
2567 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2570 // For InTitle commands, we have already opened a group
2571 // in output_latex::TeXOnePar.
2572 if (style.isCommand() && !style.intitle) {
2577 if (!style.leftdelim().empty()) {
2578 os << style.leftdelim();
2579 column += style.leftdelim().size();
2583 column += d->startTeXParParams(bparams, os,
2587 runparams.wasDisplayMath = runparams.inDisplayMath;
2588 runparams.inDisplayMath = false;
2589 bool deleted_display_math = false;
2590 Change const & change = runparams.inDeletedInset
2591 ? runparams.changeOfDeletedInset : lookupChange(i);
2593 char_type const c = d->text_[i];
2595 // Check whether a display math inset follows
2596 bool output_changes;
2597 if (runparams.for_searchAdv == OutputParams::NoSearch)
2598 output_changes = bparams.output_changes;
2600 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2602 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2604 runparams.ctObject = getInset(i)->getCtObject(runparams);
2606 InsetMath const * im = getInset(i)->asInsetMath();
2607 if (im && im->asHullInset()
2608 && im->asHullInset()->outerDisplay()) {
2609 runparams.inDisplayMath = true;
2610 // runparams.inDeletedInset will be set by
2611 // latexInset later, but we need this info
2612 // before it is called. On the other hand, we
2613 // cannot set it here because it is a counter.
2614 deleted_display_math = isDeleted(i);
2616 if (output_changes && deleted_display_math
2617 && runningChange == change
2618 && change.type == Change::DELETED
2619 && !os.afterParbreak()) {
2620 // A display math in the same paragraph follows.
2621 // We have to close and then reopen \lyxdeleted,
2622 // otherwise the math will be shifted up.
2623 OutputParams rp = runparams;
2625 bool needPar = false;
2626 column += running_font.latexWriteEndChanges(
2627 os, bparams, rp, basefont,
2631 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2632 : getLayoutFont(bparams, real_outerfont);
2633 running_font = basefont;
2634 column += Changes::latexMarkChange(os, bparams,
2635 Change(Change::INSERTED), change, rp);
2639 if (output_changes && runningChange != change) {
2640 if (!alien_script.empty()) {
2643 alien_script.clear();
2646 bool needPar = false;
2647 column += running_font.latexWriteEndChanges(
2648 os, bparams, runparams,
2649 basefont, basefont, needPar);
2652 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2653 : getLayoutFont(bparams, real_outerfont);
2654 running_font = basefont;
2655 column += Changes::latexMarkChange(os, bparams, runningChange,
2657 runningChange = change;
2660 // do not output text which is marked deleted
2661 // if change tracking output is disabled
2662 if (!output_changes && change.deleted()) {
2668 // Fully instantiated font
2669 Font current_font = getFont(bparams, i, outerfont);
2671 Font const prev_font = (i > 0) ?
2672 getFont(bparams, i - 1, outerfont)
2675 Font const last_font = running_font;
2676 bool const in_ct_deletion = (output_changes
2677 && runningChange == change
2678 && change.type == Change::DELETED
2679 && !os.afterParbreak());
2680 // Insets where font switches are used (rather than font commands)
2681 bool const fontswitch_inset =
2684 && getInset(i)->allowMultiPar()
2685 && getInset(i)->lyxCode() != ERT_CODE
2686 && getInset(i)->producesOutput();
2688 bool closeLanguage = false;
2689 bool lang_switched_at_inset = false;
2690 if (fontswitch_inset) {
2691 // Some insets cannot be inside a font change command.
2692 // However, even such insets *can* be placed in \L or \R
2693 // or their equivalents (for RTL language switches),
2694 // so we don't close the language in those cases
2695 // (= differing isRightToLeft()).
2696 // ArabTeX, though, doesn't seem to handle this special behavior.
2697 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2698 || basefont.language()->lang() == "arabic_arabtex"
2699 || current_font.language()->lang() == "arabic_arabtex";
2700 // We need to check prev_font as language changes directly at inset
2701 // will only be started inside the inset.
2702 lang_switched_at_inset = prev_font.language() != current_font.language();
2705 // Do we need to close the previous font?
2706 bool langClosed = false;
2708 ((current_font != running_font
2709 || current_font.language() != running_font.language())
2710 || (fontswitch_inset
2711 && (current_font == prev_font))))
2713 // ensure there is no open script-wrapper
2714 if (!alien_script.empty()) {
2717 alien_script.clear();
2719 if (in_ct_deletion) {
2720 // We have to close and then reopen \lyxdeleted,
2721 // as strikeout needs to be on lowest level.
2726 // Force language closing
2727 current_font.setLanguage(basefont.language());
2728 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2729 bool needPar = false;
2730 column += running_font.latexWriteEndChanges(
2731 os, bparams, runparams, basefont,
2733 if (in_ct_deletion) {
2734 // We have to close and then reopen \lyxdeleted,
2735 // as strikeout needs to be on lowest level.
2736 OutputParams rp = runparams;
2737 column += Changes::latexMarkChange(os, bparams,
2738 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2741 // Has the language been closed in the latexWriteEndChanges() call above?
2742 langClosed = running_font.language() != basefont.language()
2743 && running_font.language() != nextfont.language()
2744 && (running_font.language()->encoding()->package() != Encoding::CJK);
2745 running_font = basefont;
2748 // if necessary, close language environment before opening CJK
2749 string const running_lang = running_font.language()->babel();
2750 string const lang_end_command = lyxrc.language_command_end;
2751 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2752 && !running_lang.empty()
2753 && running_lang == openLanguageName()
2754 && current_font.language()->encoding()->package() == Encoding::CJK) {
2755 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2756 os << from_ascii(end_tag);
2757 column += end_tag.length();
2761 // Switch file encoding if necessary (and allowed)
2762 if ((!fontswitch_inset || closeLanguage)
2763 && !runparams.pass_thru && !style.pass_thru &&
2764 runparams.encoding->package() != Encoding::none &&
2765 current_font.language()->encoding()->package() != Encoding::none) {
2766 pair<bool, int> const enc_switch =
2767 switchEncoding(os.os(), bparams, runparams,
2768 *(current_font.language()->encoding()));
2769 if (enc_switch.first) {
2770 column += enc_switch.second;
2771 runparams.encoding = current_font.language()->encoding();
2775 // A display math inset inside an ulem command will be output
2776 // as a box of width \linewidth, so we have to either disable
2777 // indentation if the inset starts a paragraph, or start a new
2778 // line to accommodate such box. This has to be done before
2779 // writing any font changing commands.
2780 if (runparams.inDisplayMath && !deleted_display_math
2781 && runparams.inulemcmd) {
2782 if (os.afterParbreak())
2788 // Do we need to change font?
2789 if ((current_font != running_font ||
2790 current_font.language() != running_font.language())
2791 && i != body_pos - 1)
2793 if (!fontswitch_inset) {
2794 if (in_ct_deletion) {
2795 // We have to close and then reopen \lyxdeleted,
2796 // as strikeout needs to be on lowest level.
2797 OutputParams rp = runparams;
2798 bool needPar = false;
2799 column += running_font.latexWriteEndChanges(
2800 os, bparams, rp, basefont,
2805 otexstringstream ots;
2806 InsetText const * textinset = inInset().asInsetText();
2807 bool const cprotect = textinset
2808 ? textinset->hasCProtectContent(runparams.moving_arg)
2809 && !textinset->text().isMainText()
2811 column += current_font.latexWriteStartChanges(ots, bparams,
2812 runparams, basefont, last_font, false,
2814 // Check again for display math in ulem commands as a
2815 // font change may also occur just before a math inset.
2816 if (runparams.inDisplayMath && !deleted_display_math
2817 && runparams.inulemcmd) {
2818 if (os.afterParbreak())
2823 running_font = current_font;
2825 docstring fontchange = ots.str();
2827 // check whether the fontchange ends with a \\textcolor
2828 // modifier and the text starts with a space. If so we
2829 // need to add } in order to prevent \\textcolor from gobbling
2830 // the space (bug 4473).
2831 docstring const last_modifier = rsplit(fontchange, '\\');
2832 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2833 os << from_ascii("{}");
2834 else if (ots.terminateCommand())
2836 if (in_ct_deletion) {
2837 // We have to close and then reopen \lyxdeleted,
2838 // as strikeout needs to be on lowest level.
2839 OutputParams rp = runparams;
2840 column += Changes::latexMarkChange(os, bparams,
2841 Change(Change::UNCHANGED), change, rp);
2844 running_font = current_font;
2845 open_font = !langClosed;
2849 // FIXME: think about end_pos implementation...
2850 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2851 // FIXME: integrate this case in latexSpecialChar
2852 // Do not print the separation of the optional argument
2853 // if style.pass_thru is false. This works because
2854 // latexSpecialChar ignores spaces if
2855 // style.pass_thru is false.
2856 if (i != body_pos - 1) {
2857 if (d->simpleTeXBlanks(bparams, runparams, os,
2858 i, column, current_font, style)) {
2859 // A surrogate pair was output. We
2860 // must not call latexSpecialChar
2861 // in this iteration, since it would output
2862 // the combining character again.
2869 OutputParams rp = runparams;
2870 rp.free_spacing = style.free_spacing;
2871 rp.local_font = ¤t_font;
2872 rp.intitle = style.intitle;
2874 // Two major modes: LaTeX or plain
2875 // Handle here those cases common to both modes
2876 // and then split to handle the two modes separately.
2877 if (c == META_INSET) {
2878 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2879 // Greyedout notes and, in general, all insets
2880 // with InsetLayout::isDisplay() == false,
2881 // are typeset inline with the text. So, we
2882 // can add a \par to the last paragraph of
2883 // such insets only if nothing else follows.
2884 bool incremented = false;
2885 Inset const * inset = getInset(i);
2886 InsetText const * textinset = inset
2887 ? inset->asInsetText()
2889 if (i + 1 == size() && textinset
2890 && !inset->getLayout().isDisplay()) {
2891 ParagraphList const & pars =
2892 textinset->text().paragraphs();
2893 pit_type const pit = pars.size() - 1;
2894 Font const lastfont =
2895 pit < 0 || pars[pit].empty()
2896 ? pars[pit].getLayoutFont(
2899 : pars[pit].getFont(bparams,
2900 pars[pit].size() - 1,
2902 if (lastfont.fontInfo().size() !=
2903 basefont.fontInfo().size()) {
2908 // We need to restore parts of this after insets with
2909 // allowMultiPar() true
2910 Font const save_basefont = basefont;
2911 d->latexInset(bparams, os, rp, running_font,
2912 basefont, real_outerfont, open_font,
2913 runningChange, style, i, column, fontswitch_inset,
2914 closeLanguage, lang_switched_at_inset);
2915 if (fontswitch_inset) {
2917 bool needPar = false;
2918 column += running_font.latexWriteEndChanges(
2919 os, bparams, runparams,
2920 basefont, basefont, needPar);
2923 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2924 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2925 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2930 if (runparams.ctObject == CtObject::DisplayObject
2931 || runparams.ctObject == CtObject::UDisplayObject) {
2932 // Close \lyx*deleted and force its
2933 // reopening (if needed)
2936 runningChange = Change(Change::UNCHANGED);
2937 runparams.ctObject = CtObject::Normal;
2940 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2941 if (!bparams.useNonTeXFonts)
2942 script = Encodings::isKnownScriptChar(c);
2943 if (script != alien_script) {
2944 if (!alien_script.empty()) {
2946 alien_script.clear();
2948 string fontenc = running_font.language()->fontenc(bparams);
2950 && !Encodings::fontencSupportsScript(fontenc, script)) {
2951 column += script.length() + 2;
2952 os << "\\" << script << "{";
2953 alien_script = script;
2957 d->latexSpecialChar(os, bparams, rp, running_font,
2958 alien_script, style, i, end_pos, column);
2959 } catch (EncodingException & e) {
2960 if (runparams.dryrun) {
2961 os << "<" << _("LyX Warning: ")
2962 << _("uncodable character") << " '";
2966 // add location information and throw again.
2974 // Set the encoding to that returned from latexSpecialChar (see
2975 // comment for encoding member in OutputParams.h)
2976 runparams.encoding = rp.encoding;
2978 // Also carry on the info on a closed ulem command for insets
2979 // such as Note that do not produce any output, so that no
2980 // command is ever executed but its opening was recorded.
2981 runparams.inulemcmd = rp.inulemcmd;
2983 // These need to be passed upstream as well
2984 runparams.need_maketitle = rp.need_maketitle;
2985 runparams.have_maketitle = rp.have_maketitle;
2987 // And finally, pass the post_macros upstream
2988 runparams.post_macro = rp.post_macro;
2991 // Close wrapper for alien script
2992 if (!alien_script.empty()) {
2994 alien_script.clear();
2997 Font const font = empty()
2998 ? getLayoutFont(bparams, real_outerfont)
2999 : getFont(bparams, size() - 1, real_outerfont);
3001 InsetText const * textinset = inInset().asInsetText();
3003 bool const maintext = textinset
3004 ? textinset->text().isMainText()
3007 size_t const numpars = textinset
3008 ? textinset->text().paragraphs().size()
3011 bool needPar = false;
3013 if (style.resfont.size() != font.fontInfo().size()
3014 && (!runparams.isLastPar || maintext
3015 || (numpars > 1 && d->ownerCode() != CELL_CODE
3016 && (inInset().getLayout().isDisplay()
3018 && !style.isCommand()) {
3022 // If we have an open font definition, we have to close it
3024 // Make sure that \\par is done with the font of the last
3025 // character if this has another size as the default.
3026 // This is necessary because LaTeX (and LyX on the screen)
3027 // calculates the space between the baselines according
3028 // to this font. (Matthias)
3030 // We must not change the font for the last paragraph
3031 // of non-multipar insets, tabular cells or commands,
3032 // since this produces unwanted whitespace.
3033 #ifdef FIXED_LANGUAGE_END_DETECTION
3035 running_font.latexWriteEndChanges(os, bparams,
3036 runparams, basefont,
3037 next_->getFont(bparams, 0, outerfont),
3040 running_font.latexWriteEndChanges(os, bparams,
3041 runparams, basefont, basefont, needPar);
3044 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3045 //FIXME: there as we start another \selectlanguage with the next paragraph if
3046 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3047 running_font.latexWriteEndChanges(os, bparams, runparams,
3048 basefont, basefont, needPar);
3052 // The \par could not be inserted at the same nesting
3053 // level of the font size change, so do it now.
3054 os << "{\\" << font.latexSize() << "\\par}";
3057 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3058 column += Changes::latexMarkChange(os, bparams, runningChange,
3059 Change(Change::UNCHANGED), runparams);
3061 // Needed if there is an optional argument but no contents.
3062 if (body_pos > 0 && body_pos == size()) {
3066 if (!style.rightdelim().empty()) {
3067 os << style.rightdelim();
3068 column += style.rightdelim().size();
3071 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3072 && runparams.encoding != prev_encoding) {
3073 runparams.encoding = prev_encoding;
3074 os << setEncoding(prev_encoding->iconvName());
3077 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3081 bool Paragraph::emptyTag() const
3083 for (pos_type i = 0; i < size(); ++i) {
3084 if (Inset const * inset = getInset(i)) {
3085 InsetCode lyx_code = inset->lyxCode();
3086 // FIXME testing like that is wrong. What is
3088 if (lyx_code != TOC_CODE &&
3089 lyx_code != INCLUDE_CODE &&
3090 lyx_code != GRAPHICS_CODE &&
3091 lyx_code != ERT_CODE &&
3092 lyx_code != LISTINGS_CODE &&
3093 lyx_code != FLOAT_CODE &&
3094 lyx_code != TABULAR_CODE) {
3098 char_type c = d->text_[i];
3099 if (c != ' ' && c != '\t')
3107 string Paragraph::getID(Buffer const &, OutputParams const &)
3110 for (pos_type i = 0; i < size(); ++i) {
3111 if (Inset const * inset = getInset(i)) {
3112 InsetCode lyx_code = inset->lyxCode();
3113 if (lyx_code == LABEL_CODE) {
3114 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3115 docstring const & id = il->getParam("name");
3116 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3124 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3127 for (i = 0; i < size(); ++i) {
3128 if (Inset const * inset = getInset(i)) {
3129 inset->docbook(xs, runparams);
3131 char_type c = d->text_[i];
3141 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3145 for (i = 0; i < size(); ++i) {
3146 if (Inset const * inset = getInset(i)) {
3147 inset->xhtml(xs, runparams);
3149 char_type c = d->text_[i];
3159 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3162 pos_type size = text_.size();
3163 for (pos_type i = initial; i < size; ++i) {
3164 Font font = owner_->getFont(buf.params(), i, outerfont);
3165 if (text_[i] == META_INSET)
3167 if (i != initial && font != font_old)
3178 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3179 vector<xml::EndFontTag> & tagsToClose,
3180 bool & flag, FontState curstate, xml::FontTypes type)
3182 if (curstate == FONT_ON) {
3183 tagsToOpen.push_back(docbookStartFontTag(type));
3186 tagsToClose.push_back(docbookEndFontTag(type));
3191 class OptionalFontType {
3196 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3197 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3200 OptionalFontType fontShapeToXml(FontShape fs)
3204 return {xml::FT_ITALIC};
3206 return {xml::FT_SLANTED};
3207 case SMALLCAPS_SHAPE:
3208 return {xml::FT_SMALLCAPS};
3213 // the other tags are for internal use
3219 OptionalFontType fontFamilyToXml(FontFamily fm)
3223 return {xml::FT_ROMAN};
3225 return {xml::FT_SANS};
3226 case TYPEWRITER_FAMILY:
3227 return {xml::FT_TYPE};
3228 case INHERIT_FAMILY:
3231 // the other tags are for internal use
3237 OptionalFontType fontSizeToXml(FontSize fs)
3241 return {xml::FT_SIZE_TINY};
3243 return {xml::FT_SIZE_SCRIPT};
3245 return {xml::FT_SIZE_FOOTNOTE};
3247 return {xml::FT_SIZE_SMALL};
3249 return {xml::FT_SIZE_LARGE};
3251 return {xml::FT_SIZE_LARGER};
3253 return {xml::FT_SIZE_LARGEST};
3255 return {xml::FT_SIZE_HUGE};
3257 return {xml::FT_SIZE_HUGER};
3259 return {xml::FT_SIZE_INCREASE};
3261 return {xml::FT_SIZE_DECREASE};
3266 // the other tags are for internal use
3272 struct DocBookFontState
3274 FontShape curr_fs = INHERIT_SHAPE;
3275 FontFamily curr_fam = INHERIT_FAMILY;
3276 FontSize curr_size = INHERIT_SIZE;
3278 // track whether we have opened these tags
3279 bool emph_flag = false;
3280 bool bold_flag = false;
3281 bool noun_flag = false;
3282 bool ubar_flag = false;
3283 bool dbar_flag = false;
3284 bool sout_flag = false;
3285 bool xout_flag = false;
3286 bool wave_flag = false;
3288 bool shap_flag = false;
3290 bool faml_flag = false;
3292 bool size_flag = false;
3295 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3297 std::string const & default_family,
3298 DocBookFontState & fs)
3300 vector<xml::FontTag> tagsToOpen;
3301 vector<xml::EndFontTag> tagsToClose;
3304 FontState curstate = font.fontInfo().emph();
3305 if (font_old.emph() != curstate)
3306 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3309 curstate = font.fontInfo().noun();
3310 if (font_old.noun() != curstate)
3311 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3314 curstate = font.fontInfo().underbar();
3315 if (font_old.underbar() != curstate)
3316 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3319 curstate = font.fontInfo().strikeout();
3320 if (font_old.strikeout() != curstate)
3321 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3324 curstate = font.fontInfo().xout();
3325 if (font_old.xout() != curstate)
3326 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3329 curstate = font.fontInfo().uuline();
3330 if (font_old.uuline() != curstate)
3331 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3334 curstate = font.fontInfo().uwave();
3335 if (font_old.uwave() != curstate)
3336 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3339 // a little hackish, but allows us to reuse what we have.
3340 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3341 if (font_old.series() != font.fontInfo().series())
3342 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3345 fs.curr_fs = font.fontInfo().shape();
3346 FontShape old_fs = font_old.shape();
3347 if (old_fs != fs.curr_fs) {
3349 OptionalFontType tag = fontShapeToXml(old_fs);
3351 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3352 fs.shap_flag = false;
3355 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3357 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3361 fs.curr_fam = font.fontInfo().family();
3362 FontFamily old_fam = font_old.family();
3363 if (old_fam != fs.curr_fam) {
3365 OptionalFontType tag = fontFamilyToXml(old_fam);
3367 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3368 fs.faml_flag = false;
3370 switch (fs.curr_fam) {
3372 // we will treat a "default" font family as roman, since we have
3373 // no other idea what to do.
3374 if (default_family != "rmdefault" && default_family != "default") {
3375 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3376 fs.faml_flag = true;
3380 if (default_family != "sfdefault") {
3381 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3382 fs.faml_flag = true;
3385 case TYPEWRITER_FAMILY:
3386 if (default_family != "ttdefault") {
3387 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3388 fs.faml_flag = true;
3391 case INHERIT_FAMILY:
3394 // the other tags are for internal use
3401 fs.curr_size = font.fontInfo().size();
3402 FontSize old_size = font_old.size();
3403 if (old_size != fs.curr_size) {
3405 OptionalFontType tag = fontSizeToXml(old_size);
3407 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3408 fs.size_flag = false;
3411 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3412 if (tag.has_value) {
3413 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3414 fs.size_flag = true;
3418 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3421 } // anonymous namespace
3424 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3425 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3426 OutputParams const & runparams,
3427 Font const & outerfont,
3430 bool ignore_fonts) const
3432 std::vector<docstring> prependedParagraphs;
3433 std::vector<docstring> generatedParagraphs;
3434 std::vector<docstring> appendedParagraphs;
3435 odocstringstream os;
3437 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3438 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3440 OutputParams rp = runparams;
3441 for (pos_type i = initial; i < size(); ++i) {
3442 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3443 const InsetArgument * arg = getInset(i)->asInsetArgument();
3444 if (arg->docbookargumentbeforemaintag()) {
3445 auto xs_local = XMLStream(os);
3446 arg->docbook(xs_local, rp);
3448 prependedParagraphs.push_back(os.str());
3449 os.str(from_ascii(""));
3451 rp.docbook_prepended_arguments.insert(arg);
3452 } else if (arg->docbookargumentaftermaintag()) {
3453 rp.docbook_appended_arguments.insert(arg);
3458 // State variables for the main loop.
3459 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3460 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3461 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3462 // This requires to store delayed characters at some point.
3464 DocBookFontState fs; // Track whether we have opened font tags
3465 DocBookFontState old_fs = fs;
3467 Layout const & style = *d->layout_;
3468 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3469 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3471 vector<xml::FontTag> tagsToOpen;
3472 vector<xml::EndFontTag> tagsToClose;
3474 // Parsing main loop.
3475 for (pos_type i = initial; i < size(); ++i) {
3476 bool ignore_fonts_i = ignore_fonts
3477 || style.docbooknofontinside()
3478 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3480 // Don't show deleted material in the output.
3484 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3486 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3487 if (!ignore_fonts_i)
3488 xs->closeFontTags();
3490 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3491 generatedParagraphs.push_back(os.str());
3493 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3494 // that the string stream must be reset.
3495 os.str(from_ascii(""));
3497 xs = new XMLStream(os);
3499 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3500 if (!ignore_fonts_i) {
3501 font_old = outerfont.fontInfo();
3506 // Determine which tags should be opened or closed regarding fonts.
3507 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3508 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3510 if (!ignore_fonts_i) {
3511 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3512 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3513 for (; cit != cen; ++cit)
3517 // Deal with the delayed characters *after* closing font tags.
3518 if (!delayedChars.empty()) {
3519 for (char_type c: delayedChars)
3521 delayedChars.clear();
3524 if (!ignore_fonts_i) {
3525 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3526 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3527 for (; sit != sen; ++sit)
3530 tagsToClose.clear();
3534 // Finally, write the next character or inset.
3535 if (Inset const * inset = getInset(i)) {
3536 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3537 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3538 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3540 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3541 // Arguments may need to be output
3542 OutputParams np = rp;
3543 np.local_font = &font;
3545 // TODO: special case will bite here.
3546 np.docbook_in_par = true;
3547 inset->docbook(*xs, np);
3550 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3551 if (lyx::isSpace(c) && !ignore_fonts)
3552 delayedChars.push_back(c);
3556 font_old = font.fontInfo();
3559 // FIXME, this code is just imported from XHTML
3560 // I'm worried about what happens if a branch, say, is itself
3561 // wrapped in some font stuff. I think that will not work.
3563 xs->closeFontTags();
3565 // Deal with the delayed characters *after* closing font tags.
3566 if (!delayedChars.empty())
3567 for (char_type c: delayedChars)
3570 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3571 // last line to get a clean output.
3572 if (rp.docbook_in_listing && !is_last_par)
3575 // Finalise the last (and most likely only) paragraph.
3576 generatedParagraphs.push_back(os.str());
3577 os.str(from_ascii(""));
3580 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3581 for (pos_type i = initial; i < size(); ++i) {
3582 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3583 const InsetArgument * arg = getInset(i)->asInsetArgument();
3584 if (arg->docbookargumentaftermaintag()) {
3585 // Don't use rp, as this argument would not generate anything.
3586 auto xs_local = XMLStream(os);
3587 arg->docbook(xs_local, runparams);
3589 appendedParagraphs.push_back(os.str());
3590 os.str(from_ascii(""));
3595 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3601 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3602 vector<xml::EndFontTag> & tagsToClose,
3603 bool & flag, FontState curstate, xml::FontTypes type)
3605 if (curstate == FONT_ON) {
3606 tagsToOpen.push_back(xhtmlStartFontTag(type));
3609 tagsToClose.push_back(xhtmlEndFontTag(type));
3614 } // anonymous namespace
3617 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3619 OutputParams const & runparams,
3620 Font const & outerfont,
3621 bool start_paragraph, bool close_paragraph,
3622 pos_type initial) const
3626 // track whether we have opened these tags
3627 bool emph_flag = false;
3628 bool bold_flag = false;
3629 bool noun_flag = false;
3630 bool ubar_flag = false;
3631 bool dbar_flag = false;
3632 bool sout_flag = false;
3633 bool xout_flag = false;
3634 bool wave_flag = false;
3636 bool shap_flag = false;
3638 bool faml_flag = false;
3640 bool size_flag = false;
3642 Layout const & style = *d->layout_;
3644 if (start_paragraph)
3645 xs.startDivision(allowEmpty());
3648 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3650 FontShape curr_fs = INHERIT_SHAPE;
3651 FontFamily curr_fam = INHERIT_FAMILY;
3652 FontSize curr_size = INHERIT_SIZE;
3654 string const default_family =
3655 buf.masterBuffer()->params().fonts_default_family;
3657 vector<xml::FontTag> tagsToOpen;
3658 vector<xml::EndFontTag> tagsToClose;
3660 // parsing main loop
3661 for (pos_type i = initial; i < size(); ++i) {
3662 // let's not show deleted material in the output
3666 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3669 FontState curstate = font.fontInfo().emph();
3670 if (font_old.emph() != curstate)
3671 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3674 curstate = font.fontInfo().noun();
3675 if (font_old.noun() != curstate)
3676 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3679 curstate = font.fontInfo().underbar();
3680 if (font_old.underbar() != curstate)
3681 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3684 curstate = font.fontInfo().strikeout();
3685 if (font_old.strikeout() != curstate)
3686 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3689 curstate = font.fontInfo().xout();
3690 if (font_old.xout() != curstate)
3691 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3694 curstate = font.fontInfo().uuline();
3695 if (font_old.uuline() != curstate)
3696 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3699 curstate = font.fontInfo().uwave();
3700 if (font_old.uwave() != curstate)
3701 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3704 // a little hackish, but allows us to reuse what we have.
3705 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3706 if (font_old.series() != font.fontInfo().series())
3707 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3710 curr_fs = font.fontInfo().shape();
3711 FontShape old_fs = font_old.shape();
3712 if (old_fs != curr_fs) {
3716 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3719 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3721 case SMALLCAPS_SHAPE:
3722 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3728 // the other tags are for internal use
3736 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3740 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3743 case SMALLCAPS_SHAPE:
3744 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3751 // the other tags are for internal use
3758 curr_fam = font.fontInfo().family();
3759 FontFamily old_fam = font_old.family();
3760 if (old_fam != curr_fam) {
3764 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3767 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3769 case TYPEWRITER_FAMILY:
3770 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3772 case INHERIT_FAMILY:
3775 // the other tags are for internal use
3783 // we will treat a "default" font family as roman, since we have
3784 // no other idea what to do.
3785 if (default_family != "rmdefault" && default_family != "default") {
3786 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3791 if (default_family != "sfdefault") {
3792 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3796 case TYPEWRITER_FAMILY:
3797 if (default_family != "ttdefault") {
3798 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3802 case INHERIT_FAMILY:
3805 // the other tags are for internal use
3812 curr_size = font.fontInfo().size();
3813 FontSize old_size = font_old.size();
3814 if (old_size != curr_size) {
3818 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3821 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3824 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3827 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3830 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3833 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3836 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3839 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3842 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3845 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3848 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3854 // the other tags are for internal use
3860 switch (curr_size) {
3862 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3866 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3870 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3874 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3878 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3882 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3886 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3890 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3894 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3898 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3902 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3909 // the other tags are for internal use
3916 // Other such tags? What about the other text ranges?
3918 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3919 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3920 for (; cit != cen; ++cit)
3923 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3924 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3925 for (; sit != sen; ++sit)
3928 tagsToClose.clear();
3931 Inset const * inset = getInset(i);
3933 if (!runparams.for_toc || inset->isInToc()) {
3934 OutputParams np = runparams;
3935 np.local_font = &font;
3936 // If the paragraph has size 1, then we are in the "special
3937 // case" where we do not output the containing paragraph info
3938 if (!inset->getLayout().htmlisblock() && size() != 1)
3939 np.html_in_par = true;
3940 retval += inset->xhtml(xs, np);
3943 char_type c = getUChar(buf.masterBuffer()->params(),
3945 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3946 xs << XMLStream::ESCAPE_NONE << " ";
3950 font_old = font.fontInfo();
3954 // I'm worried about what happens if a branch, say, is itself
3955 // wrapped in some font stuff. I think that will not work.
3957 if (close_paragraph)
3964 bool Paragraph::isHfill(pos_type pos) const
3966 Inset const * inset = getInset(pos);
3967 return inset && inset->isHfill();
3971 bool Paragraph::isNewline(pos_type pos) const
3973 // U+2028 LINE SEPARATOR
3974 // U+2029 PARAGRAPH SEPARATOR
3975 char_type const c = d->text_[pos];
3976 if (c == 0x2028 || c == 0x2029)
3978 Inset const * inset = getInset(pos);
3979 return inset && inset->lyxCode() == NEWLINE_CODE;
3983 bool Paragraph::isEnvSeparator(pos_type pos) const
3985 Inset const * inset = getInset(pos);
3986 return inset && inset->lyxCode() == SEPARATOR_CODE;
3990 bool Paragraph::isLineSeparator(pos_type pos) const
3992 char_type const c = d->text_[pos];
3993 if (isLineSeparatorChar(c))
3995 Inset const * inset = getInset(pos);
3996 return inset && inset->isLineSeparator();
4000 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4004 if (ignore_deleted && isDeleted(pos))
4006 if (Inset const * inset = getInset(pos))
4007 return !inset->isLetter();
4008 // if we have a hard hyphen (no en- or emdash) or apostrophe
4009 // we pass this to the spell checker
4010 // FIXME: this method is subject to change, visit
4011 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4012 // to get an impression how complex this is.
4013 if (isHardHyphenOrApostrophe(pos))
4015 char_type const c = d->text_[pos];
4016 // We want to pass the escape chars to the spellchecker
4017 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4018 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4022 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4024 pos_type const psize = size();
4027 char_type const c = d->text_[pos];
4028 if (c != '-' && c != '\'')
4030 pos_type nextpos = pos + 1;
4031 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4032 if ((nextpos == psize || isSpace(nextpos))
4033 && (pos == 0 || isSpace(prevpos)))
4039 bool Paragraph::needsCProtection(bool const fragile) const
4041 // first check the layout of the paragraph, but only in insets
4042 InsetText const * textinset = inInset().asInsetText();
4043 bool const maintext = textinset
4044 ? textinset->text().isMainText()
4047 if (!maintext && layout().needcprotect) {
4048 // Environments need cprotection regardless the content
4049 if (layout().latextype == LATEX_ENVIRONMENT)
4052 // Commands need cprotection if they contain specific chars
4053 int const nchars_escape = 9;
4054 static char_type const chars_escape[nchars_escape] = {
4055 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4057 docstring const pars = asString();
4058 for (int k = 0; k < nchars_escape; k++) {
4059 if (contains(pars, chars_escape[k]))
4064 // now check whether we have insets that need cprotection
4065 pos_type size = pos_type(d->text_.size());
4066 for (pos_type i = 0; i < size; ++i) {
4069 Inset const * ins = getInset(i);
4070 if (ins->needsCProtection(maintext, fragile))
4072 // Now check math environments
4073 InsetMath const * im = getInset(i)->asInsetMath();
4074 if (!im || im->cell(0).empty())
4076 switch(im->cell(0)[0]->lyxCode()) {
4077 case MATH_AMSARRAY_CODE:
4078 case MATH_SUBSTACK_CODE:
4080 case MATH_XYMATRIX_CODE:
4081 // these need cprotection
4092 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4094 return d->speller_state_.getRange(pos);
4098 bool Paragraph::isChar(pos_type pos) const
4100 if (Inset const * inset = getInset(pos))
4101 return inset->isChar();
4102 char_type const c = d->text_[pos];
4103 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4107 bool Paragraph::isSpace(pos_type pos) const
4109 if (Inset const * inset = getInset(pos))
4110 return inset->isSpace();
4111 char_type const c = d->text_[pos];
4112 return lyx::isSpace(c);
4117 Paragraph::getParLanguage(BufferParams const & bparams) const
4120 return getFirstFontSettings(bparams).language();
4121 // FIXME: we should check the prev par as well (Lgb)
4122 return bparams.language;
4126 bool Paragraph::isRTL(BufferParams const & bparams) const
4128 return getParLanguage(bparams)->rightToLeft()
4129 && !inInset().getLayout().forceLTR();
4133 void Paragraph::changeLanguage(BufferParams const & bparams,
4134 Language const * from, Language const * to)
4136 // change language including dummy font change at the end
4137 for (pos_type i = 0; i <= size(); ++i) {
4138 Font font = getFontSettings(bparams, i);
4139 if (font.language() == from) {
4140 font.setLanguage(to);
4142 d->requestSpellCheck(i);
4148 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4150 Language const * doc_language = bparams.language;
4151 for (auto const & f : d->fontlist_)
4152 if (f.font().language() != ignore_language &&
4153 f.font().language() != latex_language &&
4154 f.font().language() != doc_language)
4160 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4162 for (auto const & f : d->fontlist_) {
4163 Language const * lang = f.font().language();
4164 if (lang != ignore_language &&
4165 lang != latex_language)
4171 docstring Paragraph::asString(int options) const
4173 return asString(0, size(), options);
4177 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4179 odocstringstream os;
4182 && options & AS_STR_LABEL
4183 && !d->params_.labelString().empty())
4184 os << d->params_.labelString() << ' ';
4186 for (pos_type i = beg; i < end; ++i) {
4187 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4189 char_type const c = d->text_[i];
4190 if (isPrintable(c) || c == '\t'
4191 || (c == '\n' && (options & AS_STR_NEWLINES)))
4193 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4194 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4195 LASSERT(runparams != nullptr, return docstring());
4196 getInset(i)->plaintext(os, *runparams);
4197 } else if (c == META_INSET && (options & AS_STR_MATHED)
4198 && getInset(i)->lyxCode() == REF_CODE) {
4199 Buffer const & buf = getInset(i)->buffer();
4200 OutputParams rp(&buf.params().encoding());
4201 Font const font(inherit_font, buf.params().language);
4202 rp.local_font = &font;
4204 getInset(i)->latex(ots, rp);
4206 getInset(i)->toString(os);
4215 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4216 bool const shorten, bool const label) const
4218 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4219 if (label && !labelString().empty())
4220 os += labelString() + ' ';
4221 if (!layout().isTocCaption())
4223 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4226 char_type const c = d->text_[i];
4229 else if (c == META_INSET)
4230 getInset(i)->forOutliner(os, tmplen, false);
4233 Text::shortenForOutliner(os, maxlen);
4237 void Paragraph::setInsetOwner(Inset const * inset)
4239 d->inset_owner_ = inset;
4243 int Paragraph::id() const
4249 void Paragraph::setId(int id)
4255 Layout const & Paragraph::layout() const
4261 void Paragraph::setLayout(Layout const & layout)
4263 d->layout_ = &layout;
4267 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4269 setLayout(tc.defaultLayout());
4273 void Paragraph::setPlainLayout(DocumentClass const & tc)
4275 setLayout(tc.plainLayout());
4279 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4281 if (usePlainLayout())
4284 setDefaultLayout(tc);
4288 Inset const & Paragraph::inInset() const
4290 LBUFERR(d->inset_owner_);
4291 return *d->inset_owner_;
4295 ParagraphParameters & Paragraph::params()
4301 ParagraphParameters const & Paragraph::params() const
4307 bool Paragraph::isFreeSpacing() const
4309 if (d->layout_->free_spacing)
4311 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4315 bool Paragraph::allowEmpty() const
4317 if (d->layout_->keepempty)
4319 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4323 bool Paragraph::brokenBiblio() const
4325 // There is a problem if there is no bibitem at position 0 in
4326 // paragraphs that need one, if there is another bibitem in the
4327 // paragraph or if this paragraph is not supposed to have
4328 // a bibitem inset at all.
4329 return ((d->layout_->labeltype == LABEL_BIBLIO
4330 && (d->insetlist_.find(BIBITEM_CODE) != 0
4331 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4332 || (d->layout_->labeltype != LABEL_BIBLIO
4333 && d->insetlist_.find(BIBITEM_CODE) != -1));
4337 int Paragraph::fixBiblio(Buffer const & buffer)
4339 // FIXME: when there was already an inset at 0, the return value is 1,
4340 // which does not tell whether another inset has been removed; the
4341 // cursor cannot be correctly updated.
4343 bool const track_changes = buffer.params().track_changes;
4344 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4346 // The case where paragraph is not BIBLIO
4347 if (d->layout_->labeltype != LABEL_BIBLIO) {
4348 if (bibitem_pos == -1)
4349 // No InsetBibitem => OK
4351 // There is an InsetBibitem: remove it!
4352 d->insetlist_.release(bibitem_pos);
4353 eraseChar(bibitem_pos, track_changes);
4354 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4357 bool const hasbibitem0 = bibitem_pos == 0;
4359 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4360 // There was an InsetBibitem at pos 0,
4361 // and no other one => OK
4362 if (bibitem_pos == -1)
4364 // there is a bibitem at the 0 position, but since
4365 // there is a second one, we copy the second on the
4366 // first. We're assuming there are at most two of
4367 // these, which there should be.
4368 // FIXME: why does it make sense to do that rather
4369 // than keep the first? (JMarc)
4370 Inset * inset = releaseInset(bibitem_pos);
4371 d->insetlist_.begin()->inset = inset;
4372 // This needs to be done to update the counter (#8499)
4373 buffer.updateBuffer();
4374 return -bibitem_pos;
4377 // We need to create an inset at the beginning
4378 Inset * inset = nullptr;
4379 if (bibitem_pos > 0) {
4380 // there was one somewhere in the paragraph, let's move it
4381 inset = d->insetlist_.release(bibitem_pos);
4382 eraseChar(bibitem_pos, track_changes);
4385 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4386 InsetCommandParams(BIBITEM_CODE));
4388 Font font(inherit_font, buffer.params().language);
4389 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4390 : Change::UNCHANGED));
4392 // This is needed to get the counters right
4393 buffer.updateBuffer();
4398 void Paragraph::checkAuthors(AuthorList const & authorList)
4400 d->changes_.checkAuthors(authorList);
4404 bool Paragraph::isChanged(pos_type pos) const
4406 return lookupChange(pos).changed();
4410 bool Paragraph::isInserted(pos_type pos) const
4412 return lookupChange(pos).inserted();
4416 bool Paragraph::isDeleted(pos_type pos) const
4418 return lookupChange(pos).deleted();
4422 InsetList const & Paragraph::insetList() const
4424 return d->insetlist_;
4428 void Paragraph::setInsetBuffers(Buffer & b)
4430 d->insetlist_.setBuffer(b);
4434 void Paragraph::resetBuffer()
4436 d->insetlist_.resetBuffer();
4440 Inset * Paragraph::releaseInset(pos_type pos)
4442 Inset * inset = d->insetlist_.release(pos);
4443 /// does not honour change tracking!
4444 eraseChar(pos, false);
4449 Inset * Paragraph::getInset(pos_type pos)
4451 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4452 ? d->insetlist_.get(pos) : nullptr;
4456 Inset const * Paragraph::getInset(pos_type pos) const
4458 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4459 ? d->insetlist_.get(pos) : nullptr;
4463 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4464 pos_type & right, TextCase action)
4466 // process sequences of modified characters; in change
4467 // tracking mode, this approach results in much better
4468 // usability than changing case on a char-by-char basis
4469 // We also need to track the current font, since font
4470 // changes within sequences can occur.
4471 vector<pair<char_type, Font> > changes;
4473 bool const trackChanges = bparams.track_changes;
4475 bool capitalize = true;
4477 for (; pos < right; ++pos) {
4478 char_type oldChar = d->text_[pos];
4479 char_type newChar = oldChar;
4481 // ignore insets and don't play with deleted text!
4482 if (oldChar != META_INSET && !isDeleted(pos)) {
4484 case text_lowercase:
4485 newChar = lowercase(oldChar);
4487 case text_capitalization:
4489 newChar = uppercase(oldChar);
4493 case text_uppercase:
4494 newChar = uppercase(oldChar);
4499 if (isWordSeparator(pos) || isDeleted(pos)) {
4500 // permit capitalization again
4504 if (oldChar != newChar) {
4505 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4506 if (pos != right - 1)
4508 // step behind the changing area
4512 int erasePos = pos - changes.size();
4513 for (auto const & change : changes) {
4514 insertChar(pos, change.first, change.second, trackChanges);
4515 if (!eraseChar(erasePos, trackChanges)) {
4518 ++right; // expand selection
4526 int Paragraph::find(docstring const & str, bool cs, bool mw,
4527 pos_type start_pos, bool del) const
4529 pos_type pos = start_pos;
4530 int const strsize = str.length();
4532 pos_type const parsize = d->text_.size();
4533 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4534 // ignore deleted matter
4535 if (!del && isDeleted(pos)) {
4536 if (pos == parsize - 1)
4542 // Ignore "invisible" letters such as ligature breaks
4543 // and hyphenation chars while searching
4544 bool nonmatch = false;
4545 while (pos < parsize && isInset(pos)) {
4546 Inset const * inset = getInset(pos);
4547 if (!inset->isLetter() && !inset->isChar())
4549 odocstringstream os;
4550 inset->toString(os);
4551 docstring const insetstring = os.str();
4552 if (!insetstring.empty()) {
4553 int const insetstringsize = insetstring.length();
4554 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4555 if ((cs && str[i] != insetstring[j])
4556 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4564 if (nonmatch || i == strsize)
4566 if (cs && str[i] != d->text_[pos])
4568 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4575 // if necessary, check whether string matches word
4577 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4580 && !isWordSeparator(pos))
4584 return pos - start_pos;
4588 char_type Paragraph::getChar(pos_type pos) const
4590 return d->text_[pos];
4594 pos_type Paragraph::size() const
4596 return d->text_.size();
4600 bool Paragraph::empty() const
4602 return d->text_.empty();
4606 bool Paragraph::isInset(pos_type pos) const
4608 return d->text_[pos] == META_INSET;
4612 bool Paragraph::isSeparator(pos_type pos) const
4614 //FIXME: Are we sure this can be the only separator?
4615 return d->text_[pos] == ' ';
4619 void Paragraph::deregisterWords()
4621 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4622 Private::LangWordsMap::const_iterator ite = d->words_.end();
4623 for (; itl != ite; ++itl) {
4624 WordList & wl = theWordList(itl->first);
4625 Private::Words::const_iterator it = (itl->second).begin();
4626 Private::Words::const_iterator et = (itl->second).end();
4627 for (; it != et; ++it)
4634 void Paragraph::locateWord(pos_type & from, pos_type & to,
4635 word_location const loc, bool const ignore_deleted) const
4638 case WHOLE_WORD_STRICT:
4639 if (from == 0 || from == size()
4640 || isWordSeparator(from, ignore_deleted)
4641 || isWordSeparator(from - 1, ignore_deleted)) {
4648 // If we are already at the beginning of a word, do nothing
4649 if (!from || isWordSeparator(from - 1, ignore_deleted))
4654 // always move the cursor to the beginning of previous word
4655 while (from && !isWordSeparator(from - 1, ignore_deleted))
4659 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4662 // no need to move the 'from' cursor
4666 while (to < size() && !isWordSeparator(to, ignore_deleted))
4671 void Paragraph::collectWords()
4673 for (pos_type pos = 0; pos < size(); ++pos) {
4674 if (isWordSeparator(pos))
4676 pos_type from = pos;
4677 locateWord(from, pos, WHOLE_WORD);
4678 // Work around MSVC warning: The statement
4679 // if (pos < from + lyxrc.completion_minlength)
4680 // triggers a signed vs. unsigned warning.
4681 // I don't know why this happens, it could be a MSVC bug, or
4682 // related to LLP64 (windows) vs. LP64 (unix) programming
4683 // model, or the C++ standard might be ambigous in the section
4684 // defining the "usual arithmetic conversions". However, using
4685 // a temporary variable is safe and works on all compilers.
4686 pos_type const endpos = from + lyxrc.completion_minlength;
4689 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4690 if (cit == d->fontlist_.end())
4692 Language const * lang = cit->font().language();
4693 docstring const word = asString(from, pos, AS_STR_NONE);
4694 d->words_[lang->lang()].insert(word);
4699 void Paragraph::registerWords()
4701 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4702 Private::LangWordsMap::const_iterator ite = d->words_.end();
4703 for (; itl != ite; ++itl) {
4704 WordList & wl = theWordList(itl->first);
4705 Private::Words::const_iterator it = (itl->second).begin();
4706 Private::Words::const_iterator et = (itl->second).end();
4707 for (; it != et; ++it)
4713 void Paragraph::updateWords()
4721 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4723 SkipPositionsIterator begin = skips.begin();
4724 SkipPositions::iterator end = skips.end();
4725 if (pos > 0 && begin < end) {
4727 if (end->last == pos - 1) {
4732 skips.insert(end, FontSpan(pos, pos));
4736 Language * Paragraph::Private::locateSpellRange(
4737 pos_type & from, pos_type & to,
4738 SkipPositions & skips) const
4740 // skip leading white space
4741 while (from < to && owner_->isWordSeparator(from))
4743 // don't check empty range
4746 // get current language
4747 Language * lang = getSpellLanguage(from);
4748 pos_type last = from;
4749 bool samelang = true;
4750 bool sameinset = true;
4751 while (last < to && samelang && sameinset) {
4752 // hop to end of word
4753 while (last < to && !owner_->isWordSeparator(last)) {
4754 Inset const * inset = owner_->getInset(last);
4755 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4756 // check for "invisible" letters such as ligature breaks
4757 odocstringstream os;
4758 inset->toString(os);
4759 if (os.str().length() != 0) {
4760 // avoid spell check of visible special char insets
4761 // stop the loop in front of the special char inset
4766 appendSkipPosition(skips, last);
4767 } else if (owner_->isDeleted(last)) {
4768 appendSkipPosition(skips, last);
4772 // hop to next word while checking for insets
4773 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4774 if (Inset const * inset = owner_->getInset(last))
4775 sameinset = inset->isChar() && inset->isLetter();
4776 if (sameinset && owner_->isDeleted(last)) {
4777 appendSkipPosition(skips, last);
4782 if (sameinset && last < to) {
4783 // now check for language change
4784 samelang = lang == getSpellLanguage(last);
4787 // if language change detected backstep is needed
4795 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4798 const_cast<Language *>(owner_->getFontSettings(
4799 inset_owner_->buffer().params(), from).language());
4800 if (lang == inset_owner_->buffer().params().language
4801 && !lyxrc.spellchecker_alt_lang.empty()) {
4803 string const lang_variety =
4804 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4805 lang->setCode(lang_code);
4806 lang->setVariety(lang_variety);
4812 void Paragraph::requestSpellCheck(pos_type pos)
4814 d->requestSpellCheck(pos);
4818 bool Paragraph::needsSpellCheck() const
4820 SpellChecker::ChangeNumber speller_change_number = 0;
4821 if (theSpellChecker())
4822 speller_change_number = theSpellChecker()->changeNumber();
4823 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4824 d->speller_state_.needsCompleteRefresh(speller_change_number);
4826 return d->needsSpellCheck();
4830 bool Paragraph::Private::ignoreWord(docstring const & word) const
4832 // Ignore words with digits
4833 // FIXME: make this customizable
4834 // (note that some checkers ignore words with digits by default)
4835 docstring::const_iterator cit = word.begin();
4836 docstring::const_iterator const end = word.end();
4837 for (; cit != end; ++cit) {
4838 if (isNumber((*cit)))
4845 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4846 WordLangTuple & wl, docstring_list & suggestions,
4847 bool do_suggestion, bool check_learned) const
4849 SpellChecker::Result result = SpellChecker::WORD_OK;
4850 SpellChecker * speller = theSpellChecker();
4854 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4857 locateWord(from, to, WHOLE_WORD, true);
4858 if (from == to || from >= size())
4861 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4862 Language * lang = d->getSpellLanguage(from);
4864 BufferParams const & bparams = d->inset_owner_->buffer().params();
4866 if (getFontSettings(bparams, from).fontInfo().nospellcheck() == FONT_ON)
4869 wl = WordLangTuple(word, lang);
4874 if (needsSpellCheck() || check_learned) {
4876 if (!d->ignoreWord(word)) {
4877 bool const trailing_dot = to < size() && d->text_[to] == '.';
4878 result = speller->check(wl, bparams.spellignore());
4879 if (SpellChecker::misspelled(result) && trailing_dot) {
4880 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4881 result = speller->check(wl, bparams.spellignore());
4882 if (!SpellChecker::misspelled(result)) {
4883 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4885 from << ".." << to << "]");
4887 // spell check with dot appended failed too
4888 // restore original word/lang value
4889 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4890 wl = WordLangTuple(word, lang);
4894 if (!SpellChecker::misspelled(result)) {
4895 // area up to the begin of the next word is not misspelled
4896 while (end < size() && isWordSeparator(end))
4899 d->setMisspelled(from, end, result);
4901 result = d->speller_state_.getState(from);
4905 suggestions.clear();
4907 if (SpellChecker::misspelled(result)) {
4908 LYXERR(Debug::GUI, "misspelled word: \"" <<
4910 from << ".." << to << "]");
4912 speller->suggest(wl, suggestions);
4918 void Paragraph::anonymize()
4920 // This is a very crude anonymization for now
4921 for (char_type & c : d->text_)
4922 if (isLetterChar(c) || isNumber(c))
4927 void Paragraph::Private::markMisspelledWords(
4928 Language const * lang,
4929 pos_type const & first, pos_type const & last,
4930 SpellChecker::Result result,
4931 docstring const & word,
4932 SkipPositions const & skips)
4934 if (!SpellChecker::misspelled(result)) {
4935 setMisspelled(first, last, SpellChecker::WORD_OK);
4939 SpellChecker * speller = theSpellChecker();
4940 // locate and enumerate the error positions
4941 int nerrors = speller->numMisspelledWords();
4943 SkipPositionsIterator it = skips.begin();
4944 SkipPositionsIterator et = skips.end();
4945 for (int index = 0; index < nerrors; ++index) {
4948 speller->misspelledWord(index, wstart, wlen);
4949 /// should not happen if speller supports range checks
4952 wstart += first + numskipped;
4953 if (snext < wstart) {
4954 /// mark the range of correct spelling
4955 numskipped += countSkips(it, et, wstart);
4956 setMisspelled(snext,
4957 wstart - 1, SpellChecker::WORD_OK);
4959 snext = wstart + wlen;
4960 // Check whether the candidate is in the document's local dict
4961 WordLangTuple const candidate(word.substr(wstart, wlen), lang);
4962 SpellChecker::Result actresult = result;
4963 if (inset_owner_->buffer().params().spellignored(candidate))
4964 actresult = SpellChecker::WORD_OK;
4965 numskipped += countSkips(it, et, snext);
4966 /// mark the range of misspelling
4967 setMisspelled(wstart, snext, actresult);
4968 if (actresult == SpellChecker::WORD_OK)
4969 LYXERR(Debug::GUI, "local dictionary word: \"" <<
4970 candidate.word() << "\" [" <<
4971 wstart << ".." << (snext-1) << "]");
4973 LYXERR(Debug::GUI, "misspelled word: \"" <<
4974 candidate.word() << "\" [" <<
4975 wstart << ".." << (snext-1) << "]");
4978 if (snext <= last) {
4979 /// mark the range of correct spelling at end
4980 setMisspelled(snext, last, SpellChecker::WORD_OK);
4985 void Paragraph::spellCheck() const
4987 SpellChecker * speller = theSpellChecker();
4988 if (!speller || empty() ||!needsSpellCheck())
4992 d->rangeOfSpellCheck(start, endpos);
4993 if (speller->canCheckParagraph()) {
4994 // loop until we leave the range
4995 for (pos_type first = start; first < endpos; ) {
4996 pos_type last = endpos;
4997 Private::SkipPositions skips;
4998 Language * lang = d->locateSpellRange(first, last, skips);
4999 if (first >= endpos)
5001 // start the spell checker on the unit of meaning
5002 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
5003 WordLangTuple wl = WordLangTuple(word, lang);
5004 BufferParams const & bparams = d->inset_owner_->buffer().params();
5005 SpellChecker::Result result = !word.empty() ?
5006 speller->check(wl, bparams.spellignore()) : SpellChecker::WORD_OK;
5007 d->markMisspelledWords(lang, first, last, result, word, skips);
5011 static docstring_list suggestions;
5012 pos_type to = endpos;
5013 while (start < endpos) {
5015 spellCheck(start, to, wl, suggestions, false);
5019 d->readySpellCheck();
5023 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5025 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5026 if (result || pos <= 0 || pos > size())
5028 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5029 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5034 string Paragraph::magicLabel() const
5037 ss << "magicparlabel-" << id();