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/InsetBibitem.h"
51 #include "insets/InsetLabel.h"
52 #include "insets/InsetSpecialChar.h"
53 #include "insets/InsetText.h"
55 #include "mathed/InsetMathHull.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
69 using namespace lyx::support;
71 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
72 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
73 #define THREAD_LOCAL_STATIC static __thread
74 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
75 #define THREAD_LOCAL_STATIC static __declspec(thread)
77 #define THREAD_LOCAL_STATIC thread_local static
82 /////////////////////////////////////////////////////////////////////
86 /////////////////////////////////////////////////////////////////////
88 class SpellResultRange {
90 SpellResultRange(FontSpan range, SpellChecker::Result result)
91 : range_(range), result_(result)
94 FontSpan const & range() const { return range_; }
96 void range(FontSpan const & r) { range_ = r; }
98 SpellChecker::Result result() const { return result_; }
100 void result(SpellChecker::Result r) { result_ = r; }
102 bool contains(pos_type pos) const { return range_.contains(pos); }
104 bool covered(FontSpan const & r) const
106 // 1. first of new range inside current range or
107 // 2. last of new range inside current range or
108 // 3. first of current range inside new range or
109 // 4. last of current range inside new range
110 //FIXME: is this the same as !range_.intersect(r).empty() ?
111 return range_.contains(r.first) || range_.contains(r.last) ||
112 r.contains(range_.first) || r.contains(range_.last);
115 void shift(pos_type pos, int offset)
117 if (range_.first > pos) {
118 range_.first += offset;
119 range_.last += offset;
120 } else if (range_.last >= pos) {
121 range_.last += offset;
126 SpellChecker::Result result_ ;
130 /////////////////////////////////////////////////////////////////////
134 /////////////////////////////////////////////////////////////////////
136 class SpellCheckerState {
140 needs_refresh_ = true;
141 current_change_number_ = 0;
144 void setRange(FontSpan const & fp, SpellChecker::Result state)
147 RangesIterator et = ranges_.end();
148 RangesIterator it = ranges_.begin();
149 for (; it != et; ++it) {
150 if (!it->covered(fp))
151 result.push_back(SpellResultRange(it->range(), it->result()));
152 else if (state == SpellChecker::WORD_OK) {
153 // trim or split the current misspelled range
154 // store misspelled ranges only
155 FontSpan range = it->range();
156 if (fp.first > range.first) {
157 // misspelled area in front of WORD_OK
158 range.last = fp.first - 1;
159 result.push_back(SpellResultRange(range, it->result()));
162 if (fp.last < range.last) {
163 // misspelled area after WORD_OK range
164 range.first = fp.last + 1;
165 result.push_back(SpellResultRange(range, it->result()));
170 if (state != SpellChecker::WORD_OK)
171 ranges_.push_back(SpellResultRange(fp, state));
174 void increasePosAfterPos(pos_type pos)
176 correctRangesAfterPos(pos, 1);
180 void decreasePosAfterPos(pos_type pos)
182 correctRangesAfterPos(pos, -1);
186 void refreshLast(pos_type pos)
188 if (pos < refresh_.last)
192 SpellChecker::Result getState(pos_type pos) const
194 SpellChecker::Result result = SpellChecker::WORD_OK;
195 RangesIterator et = ranges_.end();
196 RangesIterator it = ranges_.begin();
197 for (; it != et; ++it) {
198 if(it->contains(pos)) {
205 FontSpan const & getRange(pos_type pos) const
207 /// empty span to indicate mismatch
208 static FontSpan empty_;
209 RangesIterator et = ranges_.end();
210 RangesIterator it = ranges_.begin();
211 for (; it != et; ++it) {
212 if(it->contains(pos)) {
219 bool needsRefresh() const
221 return needs_refresh_;
224 SpellChecker::ChangeNumber currentChangeNumber() const
226 return current_change_number_;
229 void refreshRange(pos_type & first, pos_type & last) const
231 first = refresh_.first;
232 last = refresh_.last;
235 void needsRefresh(pos_type pos)
237 if (needs_refresh_ && pos != -1) {
238 if (pos < refresh_.first)
239 refresh_.first = pos;
240 if (pos > refresh_.last)
242 } else if (pos != -1) {
243 // init request check for neighbour positions too
244 refresh_.first = pos > 0 ? pos - 1 : 0;
245 // no need for special end of paragraph check
246 refresh_.last = pos + 1;
248 needs_refresh_ = pos != -1;
251 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
253 needs_refresh_ = true;
256 current_change_number_ = change_number;
259 typedef vector<SpellResultRange> Ranges;
260 typedef Ranges::const_iterator RangesIterator;
262 /// the area of the paragraph with pending spell check
264 /// spell state cache version number
265 SpellChecker::ChangeNumber current_change_number_;
269 void correctRangesAfterPos(pos_type pos, int offset)
271 RangesIterator et = ranges_.end();
272 Ranges::iterator it = ranges_.begin();
273 for (; it != et; ++it) {
274 it->shift(pos, offset);
280 /////////////////////////////////////////////////////////////////////
282 // Paragraph::Private
284 /////////////////////////////////////////////////////////////////////
286 class Paragraph::Private
288 // Enforce our own "copy" constructor
289 Private(Private const &) = delete;
290 Private & operator=(Private const &) = delete;
291 // Unique ID generator
292 static int make_id();
295 Private(Paragraph * owner, Layout const & layout);
296 /// "Copy constructor"
297 Private(Private const &, Paragraph * owner);
298 /// Copy constructor from \p beg to \p end
299 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
302 void insertChar(pos_type pos, char_type c, Change const & change);
304 /// Output the surrogate pair formed by \p c and \p next to \p os.
305 /// \return the number of characters written.
306 int latexSurrogatePair(BufferParams const &, otexstream & os,
307 char_type c, char_type next,
308 OutputParams const &);
310 /// Output a space in appropriate formatting (or a surrogate pair
311 /// if the next character is a combining character).
312 /// \return whether a surrogate pair was output.
313 bool simpleTeXBlanks(BufferParams const &,
314 OutputParams const &,
317 unsigned int & column,
319 Layout const & style);
321 /// This could go to ParagraphParameters if we want to.
322 int startTeXParParams(BufferParams const &, otexstream &,
323 OutputParams const &) const;
325 /// This could go to ParagraphParameters if we want to.
326 bool endTeXParParams(BufferParams const &, otexstream &,
327 OutputParams const &) const;
330 void latexInset(BufferParams const &,
335 Font const & outerfont,
337 Change & running_change,
338 Layout const & style,
340 unsigned int & column,
341 bool const fontswitch_inset,
342 bool const closeLanguage,
343 bool const lang_switched_at_inset);
346 void latexSpecialChar(
348 BufferParams const & bparams,
349 OutputParams const & runparams,
350 Font const & running_font,
351 string & alien_script,
352 Layout const & style,
355 unsigned int & column);
362 unsigned int & column) const;
368 unsigned int & column) const;
374 unsigned int & column) const;
377 void validate(LaTeXFeatures & features) const;
379 /// Checks if the paragraph contains only text and no inset or font change.
380 bool onlyText(Buffer const & buf, Font const & outerfont,
381 pos_type initial) const;
383 /// a vector of speller skip positions
384 typedef vector<FontSpan> SkipPositions;
385 typedef SkipPositions::const_iterator SkipPositionsIterator;
387 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
389 Language * getSpellLanguage(pos_type const from) const;
391 Language * locateSpellRange(pos_type & from, pos_type & to,
392 SkipPositions & skips) const;
394 bool hasSpellerChange() const
396 SpellChecker::ChangeNumber speller_change_number = 0;
397 if (theSpellChecker())
398 speller_change_number = theSpellChecker()->changeNumber();
399 return speller_change_number > speller_state_.currentChangeNumber();
402 bool ignoreWord(docstring const & word) const ;
404 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
406 pos_type textsize = owner_->size();
407 // check for sane arguments
408 if (to <= from || from >= textsize)
410 FontSpan fp = FontSpan(from, to - 1);
411 speller_state_.setRange(fp, state);
414 void requestSpellCheck(pos_type pos)
417 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
419 speller_state_.needsRefresh(pos);
422 void readySpellCheck()
424 speller_state_.needsRefresh(-1);
427 bool needsSpellCheck() const
429 return speller_state_.needsRefresh();
432 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
434 speller_state_.refreshRange(first, last);
436 last = owner_->size();
439 pos_type endpos = last;
440 owner_->locateWord(first, endpos, WHOLE_WORD, true);
443 owner_->locateWord(last, endpos, WHOLE_WORD, true);
448 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
452 while (it != et && it->first < start) {
453 long skip = it->last - it->first + 1;
461 void markMisspelledWords(pos_type const & first, pos_type const & last,
462 SpellChecker::Result result,
463 docstring const & word,
464 SkipPositions const & skips);
466 InsetCode ownerCode() const
468 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
471 /// Which Paragraph owns us?
475 Inset const * inset_owner_;
481 ParagraphParameters params_;
483 /// for recording and looking up changes
487 InsetList insetlist_;
490 pos_type begin_of_body_;
492 typedef docstring TextContainer;
496 typedef set<docstring> Words;
497 typedef map<string, Words> LangWordsMap;
501 Layout const * layout_;
503 SpellCheckerState speller_state_;
509 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
510 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
517 int Paragraph::Private::make_id()
519 // The id is unique per session across buffers because it is used in
520 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
523 static int next_id(0);
528 Paragraph::Private::Private(Private const & p, Paragraph * owner)
529 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
530 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
531 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
532 layout_(p.layout_), id_(make_id())
534 requestSpellCheck(p.text_.size());
538 Paragraph::Private::Private(Private const & p, Paragraph * owner,
539 pos_type beg, pos_type end)
540 : owner_(owner), inset_owner_(p.inset_owner_),
541 params_(p.params_), changes_(p.changes_),
542 insetlist_(p.insetlist_, beg, end),
543 begin_of_body_(p.begin_of_body_), words_(p.words_),
544 layout_(p.layout_), id_(make_id())
546 if (beg >= pos_type(p.text_.size()))
548 text_ = p.text_.substr(beg, end - beg);
550 FontList::const_iterator fcit = fontlist_.begin();
551 FontList::const_iterator fend = fontlist_.end();
552 for (; fcit != fend; ++fcit) {
553 if (fcit->pos() < beg)
555 if (fcit->pos() >= end) {
556 // Add last entry in the fontlist_.
557 fontlist_.set(text_.size() - 1, fcit->font());
560 // Add a new entry in the fontlist_.
561 fontlist_.set(fcit->pos() - beg, fcit->font());
563 requestSpellCheck(p.text_.size());
567 /////////////////////////////////////////////////////////////////////
571 /////////////////////////////////////////////////////////////////////
575 /** This helper class should be instantiated at the start of methods
576 * that can create or merge changes. If as a result the value of
577 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
580 struct ChangesMonitor {
582 ChangesMonitor(Paragraph & par)
583 : par_(par), was_changed_(par.isChanged()) {}
587 /* We may need to run updateBuffer to check whether the buffer
588 * contains changes (and toggle the changes toolbar). We do it
590 * 1. the `changedness' of the paragraph has changed,
591 * 2. and we are not in the situation where the buffer has changes
592 * and new changes are added to the paragraph.
594 if (par_.isChanged() != was_changed_
595 && par_.inInset().isBufferValid()
596 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
597 par_.inInset().buffer().forceUpdate();
602 Paragraph const & par_;
609 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
610 bool output_active, TocBackend & backend) const
612 d->changes_.addToToc(cdit, buf, output_active, backend);
616 bool Paragraph::isDeleted(pos_type start, pos_type end) const
618 LASSERT(start >= 0 && start <= size(), return false);
619 LASSERT(end > start && end <= size() + 1, return false);
621 return d->changes_.isDeleted(start, end);
625 bool Paragraph::isChanged(pos_type start, pos_type end) const
627 LASSERT(start >= 0 && start <= size(), return false);
628 LASSERT(end > start && end <= size() + 1, return false);
630 return d->changes_.isChanged(start, end);
633 // FIXME: Ideally the diverse isChanged() methods should account for that!
634 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
636 LASSERT(start >= 0 && start <= size(), return false);
637 LASSERT(end > start && end <= size() + 1, return false);
639 for (auto const & icit : d->insetlist_) {
640 if (icit.pos < start)
644 if (icit.inset && icit.inset->isChanged())
650 bool Paragraph::isChanged() const
652 return d->changes_.isChanged();
656 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
658 // keep the logic here in sync with the logic of eraseChars()
662 Change const & change = d->changes_.lookup(size());
663 return change.inserted() && change.currentAuthor();
666 Change Paragraph::parEndChange() const
668 return d->changes_.lookup(size());
672 void Paragraph::setChange(Change const & change)
674 // Make sure that Buffer::hasChangesPresent is updated
675 ChangesMonitor cm(*this);
677 // beware of the imaginary end-of-par character!
678 d->changes_.set(change, 0, size() + 1);
681 * Propagate the change recursively - but not in case of DELETED!
683 * Imagine that your co-author makes changes in an existing inset. He
684 * sends your document to you and you come to the conclusion that the
685 * inset should go completely. If you erase it, LyX must not delete all
686 * text within the inset. Otherwise, the change tracked insertions of
687 * your co-author get lost and there is no way to restore them later.
689 * Conclusion: An inset's content should remain untouched if you delete it
692 if (!change.deleted()) {
693 for (pos_type pos = 0; pos < size(); ++pos) {
694 if (Inset * inset = getInset(pos))
695 inset->setChange(change);
701 void Paragraph::setChange(pos_type pos, Change const & change)
703 // Make sure that Buffer::hasChangesPresent is updated
704 ChangesMonitor cm(*this);
706 LASSERT(pos >= 0 && pos <= size(), return);
707 d->changes_.set(change, pos);
709 // see comment in setChange(Change const &) above
710 if (!change.deleted() && pos < size())
711 if (Inset * inset = getInset(pos))
712 inset->setChange(change);
716 Change const & Paragraph::lookupChange(pos_type pos) const
718 LBUFERR(pos >= 0 && pos <= size());
719 return d->changes_.lookup(pos);
723 void Paragraph::acceptChanges(pos_type start, pos_type end)
725 // Make sure that Buffer::hasChangesPresent is updated
726 ChangesMonitor cm(*this);
728 LASSERT(start >= 0 && start <= size(), return);
729 LASSERT(end > start && end <= size() + 1, return);
731 for (pos_type pos = start; pos < end; ++pos) {
732 switch (lookupChange(pos).type) {
733 case Change::UNCHANGED:
734 // accept changes in nested inset
735 if (Inset * inset = getInset(pos))
736 inset->acceptChanges();
739 case Change::INSERTED:
740 d->changes_.set(Change(Change::UNCHANGED), pos);
741 // also accept changes in nested inset
742 if (Inset * inset = getInset(pos))
743 inset->acceptChanges();
746 case Change::DELETED:
747 // Suppress access to non-existent
748 // "end-of-paragraph char"
750 eraseChar(pos, false);
761 void Paragraph::rejectChanges(pos_type start, pos_type end)
763 LASSERT(start >= 0 && start <= size(), return);
764 LASSERT(end > start && end <= size() + 1, return);
766 // Make sure that Buffer::hasChangesPresent is updated
767 ChangesMonitor cm(*this);
769 for (pos_type pos = start; pos < end; ++pos) {
770 switch (lookupChange(pos).type) {
771 case Change::UNCHANGED:
772 // reject changes in nested inset
773 if (Inset * inset = getInset(pos))
774 inset->rejectChanges();
777 case Change::INSERTED:
778 // Suppress access to non-existent
779 // "end-of-paragraph char"
781 eraseChar(pos, false);
787 case Change::DELETED:
788 d->changes_.set(Change(Change::UNCHANGED), pos);
790 // Do NOT reject changes within a deleted inset!
791 // There may be insertions of a co-author inside of it!
799 void Paragraph::Private::insertChar(pos_type pos, char_type c,
800 Change const & change)
802 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
804 // Make sure that Buffer::hasChangesPresent is updated
805 ChangesMonitor cm(*owner_);
808 changes_.insert(change, pos);
810 // This is actually very common when parsing buffers (and
811 // maybe inserting ascii text)
812 if (pos == pos_type(text_.size())) {
813 // when appending characters, no need to update tables
815 // but we want spell checking
816 requestSpellCheck(pos);
820 text_.insert(text_.begin() + pos, c);
822 // Update the font table.
823 fontlist_.increasePosAfterPos(pos);
826 insetlist_.increasePosAfterPos(pos);
828 // Update list of misspelled positions
829 speller_state_.increasePosAfterPos(pos);
833 bool Paragraph::insertInset(pos_type pos, Inset * inset,
834 Font const & font, Change const & change)
836 LASSERT(inset, return false);
837 LASSERT(pos >= 0 && pos <= size(), return false);
839 // Make sure that Buffer::hasChangesPresent is updated
840 ChangesMonitor cm(*this);
842 // Paragraph::insertInset() can be used in cut/copy/paste operation where
843 // d->inset_owner_ is not set yet.
844 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
847 d->insertChar(pos, META_INSET, change);
848 LASSERT(d->text_[pos] == META_INSET, return false);
850 // Add a new entry in the insetlist_.
851 d->insetlist_.insert(inset, pos);
853 // Some insets require run of spell checker
854 requestSpellCheck(pos);
860 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
862 LASSERT(pos >= 0 && pos <= size(), return false);
864 // Make sure that Buffer::hasChangesPresent is updated
865 ChangesMonitor cm(*this);
867 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
870 Change change = d->changes_.lookup(pos);
872 // set the character to DELETED if
873 // a) it was previously unchanged or
874 // b) it was inserted by a co-author
876 if (!change.changed() ||
877 (change.inserted() && !change.currentAuthor())) {
878 setChange(pos, Change(Change::DELETED));
879 // request run of spell checker
880 requestSpellCheck(pos);
884 if (change.deleted())
888 // Don't physically access the imaginary end-of-paragraph character.
889 // eraseChar() can only mark it as DELETED. A physical deletion of
890 // end-of-par must be handled externally.
896 d->changes_.erase(pos);
898 // if it is an inset, delete the inset entry
899 if (d->text_[pos] == META_INSET)
900 d->insetlist_.erase(pos);
902 d->text_.erase(d->text_.begin() + pos);
904 // Update the fontlist_
905 d->fontlist_.erase(pos);
907 // Update the insetlist_
908 d->insetlist_.decreasePosAfterPos(pos);
910 // Update list of misspelled positions
911 d->speller_state_.decreasePosAfterPos(pos);
912 d->speller_state_.refreshLast(size());
918 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
920 LASSERT(start >= 0 && start <= size(), return 0);
921 LASSERT(end >= start && end <= size() + 1, return 0);
924 for (pos_type count = end - start; count; --count) {
925 if (!eraseChar(i, trackChanges))
932 // Handle combining characters
933 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
934 otexstream & os, char_type c, char_type next,
935 OutputParams const & runparams)
937 // Writing next here may circumvent a possible font change between
938 // c and next. Since next is only output if it forms a surrogate pair
939 // with c we can ignore this:
940 // A font change inside a surrogate pair does not make sense and is
941 // hopefully impossible to input.
942 // FIXME: change tracking
943 // Is this correct WRT change tracking?
944 Encoding const & encoding = *(runparams.encoding);
945 docstring latex1 = encoding.latexChar(next).first;
946 if (runparams.inIPA) {
947 string const tipashortcut = Encodings::TIPAShortcut(next);
948 if (!tipashortcut.empty()) {
949 latex1 = from_ascii(tipashortcut);
952 docstring latex2 = encoding.latexChar(c).first;
954 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
955 // Encoding supports the combination:
956 // output as is (combining char after base char).
957 os << latex2 << latex1;
958 return latex1.length() + latex2.length();
961 os << latex1 << "{" << latex2 << "}";
962 return latex1.length() + latex2.length() + 2;
966 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
967 OutputParams const & runparams,
970 unsigned int & column,
972 Layout const & style)
974 if (style.pass_thru || runparams.pass_thru)
977 if (i + 1 < int(text_.size())) {
978 char_type next = text_[i + 1];
979 if (Encodings::isCombiningChar(next)) {
980 // This space has an accent, so we must always output it.
981 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
986 if (runparams.linelen > 0
987 && column > runparams.linelen
989 && text_[i - 1] != ' '
990 && (i + 1 < int(text_.size()))
991 // same in FreeSpacing mode
992 && !owner_->isFreeSpacing()
993 // In typewriter mode, we want to avoid
994 // ! . ? : at the end of a line
995 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
996 && (text_[i - 1] == '.'
997 || text_[i - 1] == '?'
998 || text_[i - 1] == ':'
999 || text_[i - 1] == '!'))) {
1001 os.texrow().start(owner_->id(), i + 1);
1003 } else if (style.free_spacing) {
1012 void Paragraph::Private::latexInset(BufferParams const & bparams,
1014 OutputParams & runparams,
1015 Font & running_font,
1017 Font const & outerfont,
1019 Change & running_change,
1020 Layout const & style,
1022 unsigned int & column,
1023 bool const fontswitch_inset,
1024 bool const closeLanguage,
1025 bool const lang_switched_at_inset)
1027 Inset * inset = owner_->getInset(i);
1030 if (style.pass_thru) {
1031 odocstringstream ods;
1032 inset->plaintext(ods, runparams);
1037 // FIXME: move this to InsetNewline::latex
1038 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1039 // newlines are handled differently here than
1040 // the default in simpleTeXSpecialChars().
1041 if (!style.newline_allowed) {
1045 bool needPar = false;
1046 column += running_font.latexWriteEndChanges(
1047 os, bparams, runparams,
1048 basefont, basefont, needPar);
1052 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1055 basefont = owner_->getLayoutFont(bparams, outerfont);
1056 running_font = basefont;
1058 if (runparams.moving_arg)
1062 os.texrow().start(owner_->id(), i + 1);
1066 if (owner_->isDeleted(i)) {
1067 if( ++runparams.inDeletedInset == 1)
1068 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1071 if (inset->canTrackChanges()) {
1072 column += Changes::latexMarkChange(os, bparams, running_change,
1073 Change(Change::UNCHANGED), runparams);
1074 running_change = Change(Change::UNCHANGED);
1078 odocstream::pos_type const len = os.os().tellp();
1080 if (inset->forceLTR(runparams)
1081 && running_font.isRightToLeft()
1082 // ERT is an exception, it should be output with no
1083 // decorations at all
1084 && inset->lyxCode() != ERT_CODE) {
1085 if (runparams.use_polyglossia) {
1087 } else if (running_font.language()->lang() == "farsi"
1088 || running_font.language()->lang() == "arabic_arabi")
1089 os << "\\textLR{" << termcmd;
1095 if (open_font && fontswitch_inset) {
1096 bool lang_closed = false;
1097 // Close language if needed
1098 if (closeLanguage && !lang_switched_at_inset) {
1099 // We need prev_font here as language changes directly at inset
1100 // will only be started inside the inset.
1101 Font const prev_font = (i > 0) ?
1102 owner_->getFont(bparams, i - 1, outerfont)
1104 Font tmpfont(basefont);
1105 tmpfont.setLanguage(prev_font.language());
1106 bool needPar = false;
1107 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1109 needPar, closeLanguage);
1111 lang_closed = count > 0;
1113 // Update the running_font, making sure, however,
1114 // to leave the language as it was.
1115 // FIXME: probably a better way to keep track of the old
1116 // language, than copying the entire font?
1117 Font const copy_font(running_font);
1118 basefont = owner_->getLayoutFont(bparams, outerfont);
1119 running_font = basefont;
1121 running_font.setLanguage(copy_font.language());
1122 OutputParams rp = runparams;
1123 rp.encoding = basefont.language()->encoding();
1124 // For these, we use switches, so they should be taken as
1125 // base inside the inset.
1126 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1127 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1128 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1129 // Now re-do font changes in a way needed here
1130 // (using switches with multi-par insets)
1131 InsetText const * textinset = inset->asInsetText();
1132 bool const cprotect = textinset
1133 ? textinset->hasCProtectContent(runparams.moving_arg)
1134 && !textinset->text().isMainText()
1136 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1142 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1146 runparams.local_font = &basefont;
1149 if (fontswitch_inset && !closeLanguage) {
1150 // The directionality has been switched at inset.
1151 // Force markup inside.
1152 runparams.local_font = &basefont;
1155 size_t const previous_row_count = os.texrow().rows();
1158 runparams.lastid = id_;
1159 runparams.lastpos = i;
1160 inset->latex(os, runparams);
1161 } catch (EncodingException & e) {
1162 // add location information and throw again.
1171 if (os.texrow().rows() > previous_row_count) {
1172 os.texrow().start(owner_->id(), i + 1);
1175 column += (unsigned int)(os.os().tellp() - len);
1178 if (owner_->isDeleted(i))
1179 --runparams.inDeletedInset;
1183 void Paragraph::Private::latexSpecialChar(otexstream & os,
1184 BufferParams const & bparams,
1185 OutputParams const & runparams,
1186 Font const & running_font,
1187 string & alien_script,
1188 Layout const & style,
1191 unsigned int & column)
1193 char_type const c = owner_->getUChar(bparams, runparams, i);
1195 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1196 || contains(style.pass_thru_chars, c)
1197 || contains(runparams.pass_thru_chars, c)) {
1198 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1202 os << "\\braceleft ";
1204 os << "\\braceright ";
1208 else if (c != '\0') {
1209 Encoding const * const enc = runparams.encoding;
1210 if (enc && !enc->encodable(c))
1211 throw EncodingException(c);
1217 // TIPA uses its own T3 encoding
1218 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1220 // If T1 font encoding is used, use the special
1221 // characters it provides.
1222 // NOTE: Some languages reset the font encoding internally to a
1223 // non-standard font encoding. If we are using such a language,
1224 // we do not output special T1 chars.
1225 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1226 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1227 && latexSpecialT1(c, os, i, column))
1229 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1230 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1231 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1234 // Otherwise, we use what LaTeX provides us.
1237 os << "\\textbackslash" << termcmd;
1241 os << "\\textless" << termcmd;
1245 os << "\\textgreater" << termcmd;
1249 os << "\\textbar" << termcmd;
1254 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1255 (end_pos == -1 || i + 1 < end_pos) &&
1256 text_[i+1] == '-') {
1257 // Prevent "--" becoming an en dash and "---" an em dash.
1258 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1264 os << "\\textquotedbl" << termcmd;
1269 case '%': case '#': case '{':
1277 os << "\\textasciitilde" << termcmd;
1282 os << "\\textasciicircum" << termcmd;
1289 // avoid being mistaken for optional arguments
1297 // Blanks are printed before font switching.
1298 // Sure? I am not! (try nice-latex)
1299 // I am sure it's correct. LyX might be smarter
1300 // in the future, but for now, nothing wrong is
1306 // XeTeX's dash behaviour is determined via a global setting
1307 if (bparams.use_dash_ligatures
1308 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1310 // TODO #10961: && not in inset Flex Code
1311 // TODO #10961: && not in layout LyXCode
1312 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1329 Encoding const & encoding = *(runparams.encoding);
1330 char_type next = '\0';
1331 if (i + 1 < int(text_.size())) {
1332 next = text_[i + 1];
1333 if (Encodings::isCombiningChar(next)) {
1334 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1339 pair<docstring, bool> latex = encoding.latexChar(c);
1340 docstring nextlatex;
1341 bool nexttipas = false;
1342 string nexttipashortcut;
1343 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1344 nextlatex = encoding.latexChar(next).first;
1345 if (runparams.inIPA) {
1346 nexttipashortcut = Encodings::TIPAShortcut(next);
1347 nexttipas = !nexttipashortcut.empty();
1351 if (runparams.inIPA) {
1352 string const tipashortcut = Encodings::TIPAShortcut(c);
1353 if (!tipashortcut.empty()) {
1354 latex.first = from_ascii(tipashortcut);
1355 latex.second = false;
1359 // eventually close "script wrapper" command (see `Paragraph::latex`)
1360 if (!alien_script.empty()
1361 && alien_script != Encodings::isKnownScriptChar(next)) {
1362 column += latex.first.length();
1363 alien_script.clear();
1364 os << latex.first << "}";
1368 && ((!prefixIs(nextlatex, '\\')
1369 && !prefixIs(nextlatex, '{')
1370 && !prefixIs(nextlatex, '}'))
1372 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1374 // Prevent eating of a following space or command corruption by
1375 // following characters
1376 if (next == ' ' || next == '\0') {
1377 column += latex.first.length() + 1;
1378 os << latex.first << "{}";
1380 column += latex.first.length();
1381 os << latex.first << " ";
1384 column += latex.first.length() - 1;
1392 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1393 pos_type i, unsigned int & column) const
1399 // In T1 encoding, these characters exist
1400 // but we should avoid ligatures
1401 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1403 os << "\\textcompwordmark" << termcmd;
1410 // soul.sty breaks with \char`\"
1411 os << "\\textquotedbl" << termcmd;
1420 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1421 pos_type i, unsigned int & column) const
1423 // TU encoding is currently on par with T1.
1424 return latexSpecialT1(c, os, i, column);
1428 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1429 pos_type /*i*/, unsigned int & column) const
1439 os << "\\textvertline" << termcmd;
1448 void Paragraph::Private::validate(LaTeXFeatures & features) const
1450 if (layout_->inpreamble && inset_owner_) {
1451 // FIXME: Using a string stream here circumvents the encoding
1452 // switching machinery of odocstream. Therefore the
1453 // output is wrong if this paragraph contains content
1454 // that needs to switch encoding.
1455 Buffer const & buf = inset_owner_->buffer();
1456 otexstringstream os;
1457 os << layout_->preamble();
1458 size_t const length = os.length();
1459 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1460 buf.getParFromID(owner_->id()).pit(), os,
1461 features.runparams(), string(), 0, -1, true);
1462 if (os.length() > length)
1463 features.addPreambleSnippet(os.release(), true);
1466 if (features.runparams().flavor == Flavor::Html
1467 && layout_->htmltitle()) {
1468 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1471 // check the params.
1472 if (!params_.spacing().isDefault())
1473 features.require("setspace");
1476 features.useLayout(layout_->name());
1479 fontlist_.validate(features);
1481 // then the indentation
1482 if (!params_.leftIndent().zero())
1483 features.require("ParagraphLeftIndent");
1486 InsetList::const_iterator icit = insetlist_.begin();
1487 InsetList::const_iterator iend = insetlist_.end();
1488 for (; icit != iend; ++icit) {
1490 features.inDeletedInset(owner_->isDeleted(icit->pos));
1491 if (icit->inset->lyxCode() == FOOT_CODE) {
1492 // FIXME: an item inset would make things much easier.
1493 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1494 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1495 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1496 && (icit->pos < begin_of_body_
1497 || (icit->pos == begin_of_body_
1498 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1499 features.saveNoteEnv("description");
1501 icit->inset->validate(features);
1502 features.inDeletedInset(false);
1503 if (layout_->needprotect &&
1504 icit->inset->lyxCode() == FOOT_CODE)
1505 features.require("NeedLyXFootnoteCode");
1509 // then the contents
1510 BufferParams const bp = features.runparams().is_child
1511 ? features.buffer().masterParams() : features.buffer().params();
1512 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1513 char_type c = text_[i];
1514 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1516 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1517 features.require("textquotedblp");
1518 else if (bp.main_font_encoding() != "T1"
1519 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1520 features.require("textquotedbl");
1521 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1522 // features that depend on the font or input encoding
1523 string feats = ci.textpreamble();
1524 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1525 if (fontenc.empty())
1526 fontenc = features.runparams().main_fontenc;
1527 while (!feats.empty()) {
1529 feats = split(feats, feat, ',');
1530 if (contains(feat, "!=")) {
1531 // a feature that is required except for the spcified
1532 // font or input encodings
1534 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1535 // multiple encodings are separated by semicolon
1536 vector<string> context = getVectorFromString(contexts, ";");
1537 // require feature if the context matches neither current font
1538 // nor input encoding
1539 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1540 && std::find(context.begin(), context.end(),
1541 features.runparams().encoding->name()) == context.end())
1542 features.require(realfeature);
1543 } else if (contains(feat, '=')) {
1544 // a feature that is required only for the spcified
1545 // font or input encodings
1547 string const contexts = split(feat, realfeature, '=');
1548 // multiple encodings are separated by semicolon
1549 vector<string> context = getVectorFromString(contexts, ";");
1550 // require feature if the context matches either current font
1551 // or input encoding
1552 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1553 || std::find(context.begin(), context.end(),
1554 features.runparams().encoding->name()) != context.end())
1555 features.require(realfeature);
1558 } else if (!bp.use_dash_ligatures
1559 && (c == 0x2013 || c == 0x2014)
1560 && bp.useNonTeXFonts
1561 && features.runparams().flavor == Flavor::XeTeX)
1562 // XeTeX's dash behaviour is determined via a global setting
1563 features.require("xetexdashbreakstate");
1564 BufferEncodings::validate(c, features);
1568 /////////////////////////////////////////////////////////////////////
1572 /////////////////////////////////////////////////////////////////////
1575 Layout const emptyParagraphLayout;
1578 Paragraph::Paragraph()
1579 : d(new Paragraph::Private(this, emptyParagraphLayout))
1586 Paragraph::Paragraph(Paragraph const & par)
1587 : itemdepth(par.itemdepth),
1588 d(new Paragraph::Private(*par.d, this))
1594 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1595 : itemdepth(par.itemdepth),
1596 d(new Paragraph::Private(*par.d, this, beg, end))
1602 Paragraph & Paragraph::operator=(Paragraph const & par)
1604 // needed as we will destroy the private part before copying it
1606 itemdepth = par.itemdepth;
1610 d = new Private(*par.d, this);
1617 Paragraph::~Paragraph()
1626 // this shall be called just before every "os << ..." action.
1627 void flushString(ostream & os, docstring & s)
1636 void Paragraph::write(ostream & os, BufferParams const & bparams,
1637 depth_type & depth) const
1639 // The beginning or end of a deeper (i.e. nested) area?
1640 if (depth != d->params_.depth()) {
1641 if (d->params_.depth() > depth) {
1642 while (d->params_.depth() > depth) {
1643 os << "\n\\begin_deeper";
1647 while (d->params_.depth() < depth) {
1648 os << "\n\\end_deeper";
1654 // First write the layout
1655 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1657 d->params_.write(os);
1659 Font font1(inherit_font, bparams.language);
1661 Change running_change = Change(Change::UNCHANGED);
1663 // this string is used as a buffer to avoid repetitive calls
1664 // to to_utf8(), which turn out to be expensive (JMarc)
1665 docstring write_buffer;
1668 for (pos_type i = 0; i <= size(); ++i) {
1670 Change const & change = lookupChange(i);
1671 if (change != running_change)
1672 flushString(os, write_buffer);
1673 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1674 running_change = change;
1679 // Write font changes
1680 Font font2 = getFontSettings(bparams, i);
1681 if (font2 != font1) {
1682 flushString(os, write_buffer);
1683 font2.lyxWriteChanges(font1, os);
1688 char_type const c = d->text_[i];
1691 if (Inset const * inset = getInset(i)) {
1692 flushString(os, write_buffer);
1693 if (inset->directWrite()) {
1694 // international char, let it write
1695 // code directly so it's shorter in
1701 os << "\\begin_inset ";
1703 os << "\n\\end_inset\n\n";
1706 // FIXME This can be removed again once the mystery
1707 // crash has been resolved.
1712 flushString(os, write_buffer);
1713 os << "\n\\backslash\n";
1717 flushString(os, write_buffer);
1718 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1725 if ((column > 70 && c == ' ')
1727 flushString(os, write_buffer);
1731 // this check is to amend a bug. LyX sometimes
1732 // inserts '\0' this could cause problems.
1734 write_buffer.push_back(c);
1736 LYXERR0("NUL char in structure.");
1742 flushString(os, write_buffer);
1743 os << "\n\\end_layout\n";
1744 // FIXME This can be removed again once the mystery
1745 // crash has been resolved.
1750 void Paragraph::validate(LaTeXFeatures & features) const
1752 d->validate(features);
1753 bool fragile = features.runparams().moving_arg;
1754 fragile |= layout().needprotect;
1755 if (inInset().getLayout().isNeedProtect())
1757 if (needsCProtection(fragile))
1758 features.require("cprotect");
1762 void Paragraph::insert(pos_type pos, docstring const & str,
1763 Font const & font, Change const & change)
1765 for (size_t i = 0, n = str.size(); i != n ; ++i)
1766 insertChar(pos + i, str[i], font, change);
1770 void Paragraph::appendChar(char_type c, Font const & font,
1771 Change const & change)
1773 // Make sure that Buffer::hasChangesPresent is updated
1774 ChangesMonitor cm(*this);
1777 d->changes_.insert(change, d->text_.size());
1778 // when appending characters, no need to update tables
1779 d->text_.push_back(c);
1780 setFont(d->text_.size() - 1, font);
1781 d->requestSpellCheck(d->text_.size() - 1);
1785 void Paragraph::appendString(docstring const & s, Font const & font,
1786 Change const & change)
1788 // Make sure that Buffer::hasChangesPresent is updated
1789 ChangesMonitor cm(*this);
1791 pos_type end = s.size();
1792 size_t oldsize = d->text_.size();
1793 size_t newsize = oldsize + end;
1794 size_t capacity = d->text_.capacity();
1795 if (newsize >= capacity)
1796 d->text_.reserve(max(capacity + 100, newsize));
1798 // when appending characters, no need to update tables
1801 // FIXME: Optimize this!
1802 for (size_t i = oldsize; i != newsize; ++i) {
1804 d->changes_.insert(change, i);
1805 d->requestSpellCheck(i);
1807 d->fontlist_.set(oldsize, font);
1808 d->fontlist_.set(newsize - 1, font);
1812 void Paragraph::insertChar(pos_type pos, char_type c,
1815 d->insertChar(pos, c, Change(trackChanges ?
1816 Change::INSERTED : Change::UNCHANGED));
1820 void Paragraph::insertChar(pos_type pos, char_type c,
1821 Font const & font, bool trackChanges)
1823 d->insertChar(pos, c, Change(trackChanges ?
1824 Change::INSERTED : Change::UNCHANGED));
1829 void Paragraph::insertChar(pos_type pos, char_type c,
1830 Font const & font, Change const & change)
1832 d->insertChar(pos, c, change);
1837 void Paragraph::resetFonts(Font const & font)
1839 d->fontlist_.clear();
1840 d->fontlist_.set(0, font);
1841 d->fontlist_.set(d->text_.size() - 1, font);
1844 // Gets uninstantiated font setting at position.
1845 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1849 LYXERR0("pos: " << pos << " size: " << size());
1853 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1854 if (cit != d->fontlist_.end())
1857 if (pos == size() && !empty())
1858 return getFontSettings(bparams, pos - 1);
1860 // Optimisation: avoid a full font instantiation if there is no
1861 // language change from previous call.
1862 static Font previous_font;
1863 static Language const * previous_lang = nullptr;
1864 Language const * lang = getParLanguage(bparams);
1865 if (lang != previous_lang) {
1866 previous_lang = lang;
1867 previous_font = Font(inherit_font, lang);
1869 return previous_font;
1873 FontSpan Paragraph::fontSpan(pos_type pos) const
1875 LBUFERR(pos <= size());
1878 return FontSpan(pos, pos);
1881 FontList::const_iterator cit = d->fontlist_.begin();
1882 FontList::const_iterator end = d->fontlist_.end();
1883 for (; cit != end; ++cit) {
1884 if (cit->pos() >= pos) {
1885 if (pos >= beginOfBody())
1886 return FontSpan(max(start, beginOfBody()),
1889 return FontSpan(start,
1890 min(beginOfBody() - 1,
1893 start = cit->pos() + 1;
1896 // This should not happen, but if so, we take no chances.
1897 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1898 LASSERT(false, return FontSpan(pos, pos));
1902 // Gets uninstantiated font setting at position 0
1903 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1905 if (!empty() && !d->fontlist_.empty())
1906 return d->fontlist_.begin()->font();
1908 // Optimisation: avoid a full font instantiation if there is no
1909 // language change from previous call.
1910 static Font previous_font;
1911 static Language const * previous_lang = nullptr;
1912 if (bparams.language != previous_lang) {
1913 previous_lang = bparams.language;
1914 previous_font = Font(inherit_font, bparams.language);
1917 return previous_font;
1921 // Gets the fully instantiated font at a given position in a paragraph
1922 // This is basically the same function as Text::GetFont() in text2.cpp.
1923 // The difference is that this one is used for generating the LaTeX file,
1924 // and thus cosmetic "improvements" are disallowed: This has to deliver
1925 // the true picture of the buffer. (Asger)
1926 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1927 Font const & outerfont) const
1931 Font font = getFontSettings(bparams, pos);
1933 pos_type const body_pos = beginOfBody();
1934 FontInfo & fi = font.fontInfo();
1936 fi.realize(d->layout_->labelfont);
1938 fi.realize(d->layout_->font);
1940 fi.realize(outerfont.fontInfo());
1941 fi.realize(bparams.getFont().fontInfo());
1947 Font const Paragraph::getLabelFont
1948 (BufferParams const & bparams, Font const & outerfont) const
1950 FontInfo tmpfont = d->layout_->labelfont;
1951 tmpfont.realize(outerfont.fontInfo());
1952 tmpfont.realize(bparams.getFont().fontInfo());
1953 return Font(tmpfont, getParLanguage(bparams));
1957 Font const Paragraph::getLayoutFont
1958 (BufferParams const & bparams, Font const & outerfont) const
1960 FontInfo tmpfont = d->layout_->font;
1961 tmpfont.realize(outerfont.fontInfo());
1962 tmpfont.realize(bparams.getFont().fontInfo());
1963 return Font(tmpfont, getParLanguage(bparams));
1967 char_type Paragraph::getUChar(BufferParams const & bparams,
1968 OutputParams const & rp,
1971 char_type c = d->text_[pos];
1973 // Return unchanged character in LTR languages
1974 // or if we use poylglossia/bidi (XeTeX).
1975 if (rp.useBidiPackage()
1976 || !getFontSettings(bparams, pos).isRightToLeft())
1979 // Without polyglossia/bidi, we need to account for some special cases.
1980 // FIXME This needs to be audited!
1982 // * The input is as expected for all delimiters
1983 // => checked for Hebrew!
1984 // * The output matches the display in the LyX workarea
1985 // => checked for Hebrew!
1986 // * The special cases below are really necessary
1987 // => checked for Hebrew!
1988 // * In arabic_arabi, brackets are transformed to Arabic
1989 // Ornate Parentheses. Is this is really wanted?
1991 string const & lang = getFontSettings(bparams, pos).language()->lang();
1994 // 1. In the following languages, parentheses need to be reversed.
1995 // Also with polyglodia/luabidi
1996 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1998 // 2. In the following languages, brackets don't need to be reversed.
1999 bool const reversebrackets = lang != "arabic_arabtex"
2000 && lang != "arabic_arabi"
2003 // Now swap delimiters if needed.
2014 if (reversebrackets)
2018 if (reversebrackets)
2039 void Paragraph::setFont(pos_type pos, Font const & font)
2041 LASSERT(pos <= size(), return);
2043 // First, reduce font against layout/label font
2044 // Update: The setCharFont() routine in text2.cpp already
2045 // reduces font, so we don't need to do that here. (Asger)
2047 d->fontlist_.set(pos, font);
2051 void Paragraph::makeSameLayout(Paragraph const & par)
2053 d->layout_ = par.d->layout_;
2054 d->params_ = par.d->params_;
2058 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2060 if (isFreeSpacing())
2066 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2067 if (eraseChar(pos, trackChanges))
2073 return count > 0 || pos > 0;
2077 bool Paragraph::hasSameLayout(Paragraph const & par) const
2079 return par.d->layout_ == d->layout_
2080 && d->params_.sameLayout(par.d->params_);
2084 depth_type Paragraph::getDepth() const
2086 return d->params_.depth();
2090 depth_type Paragraph::getMaxDepthAfter() const
2092 if (d->layout_->isEnvironment())
2093 return d->params_.depth() + 1;
2095 return d->params_.depth();
2099 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2101 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2102 return getDefaultAlign(bparams);
2104 return d->params_.align();
2108 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2110 LyXAlignment res = layout().align;
2111 if (isRTL(bparams)) {
2113 if (res == LYX_ALIGN_LEFT)
2114 res = LYX_ALIGN_RIGHT;
2115 else if (res == LYX_ALIGN_RIGHT)
2116 res = LYX_ALIGN_LEFT;
2122 docstring const & Paragraph::labelString() const
2124 return d->params_.labelString();
2128 // the next two functions are for the manual labels
2129 docstring const Paragraph::getLabelWidthString() const
2131 if (d->layout_->margintype == MARGIN_MANUAL
2132 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2133 return d->params_.labelWidthString();
2135 return _("Senseless with this layout!");
2139 void Paragraph::setLabelWidthString(docstring const & s)
2141 d->params_.labelWidthString(s);
2145 docstring Paragraph::expandLabel(Layout const & layout,
2146 BufferParams const & bparams) const
2148 return expandParagraphLabel(layout, bparams, true);
2152 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2153 BufferParams const & bparams, bool process_appendix) const
2155 DocumentClass const & tclass = bparams.documentClass();
2156 string const & lang = getParLanguage(bparams)->code();
2157 bool const in_appendix = process_appendix && d->params_.appendix();
2158 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2160 if (fmt.empty() && !layout.counter.empty())
2161 return tclass.counters().theCounter(layout.counter, lang);
2163 // handle 'inherited level parts' in 'fmt',
2164 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2165 size_t const i = fmt.find('@', 0);
2166 if (i != docstring::npos) {
2167 size_t const j = fmt.find('@', i + 1);
2168 if (j != docstring::npos) {
2169 docstring parent(fmt, i + 1, j - i - 1);
2170 docstring label = from_ascii("??");
2171 if (tclass.hasLayout(parent))
2172 label = expandParagraphLabel(tclass[parent], bparams,
2174 fmt = docstring(fmt, 0, i) + label
2175 + docstring(fmt, j + 1, docstring::npos);
2179 return tclass.counters().counterLabel(fmt, lang);
2183 void Paragraph::applyLayout(Layout const & new_layout)
2185 d->layout_ = &new_layout;
2186 LyXAlignment const oldAlign = d->params_.align();
2188 if (!(oldAlign & d->layout_->alignpossible)) {
2189 frontend::Alert::warning(_("Alignment not permitted"),
2190 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2191 d->params_.align(LYX_ALIGN_LAYOUT);
2196 pos_type Paragraph::beginOfBody() const
2198 return d->begin_of_body_;
2202 void Paragraph::setBeginOfBody()
2204 if (d->layout_->labeltype != LABEL_MANUAL) {
2205 d->begin_of_body_ = 0;
2209 // Unroll the first two cycles of the loop
2210 // and remember the previous character to
2211 // remove unnecessary getChar() calls
2213 pos_type end = size();
2214 bool prev_char_deleted = false;
2215 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2218 char_type previous_char = d->text_[i];
2219 if (!(isNewline(i) || isEnvSeparator(i))) {
2221 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2222 char_type temp = d->text_[i];
2223 prev_char_deleted = isDeleted(i);
2224 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2227 previous_char = temp;
2233 d->begin_of_body_ = i;
2237 bool Paragraph::allowParagraphCustomization() const
2239 return inInset().allowParagraphCustomization();
2243 bool Paragraph::usePlainLayout() const
2245 return inInset().usePlainLayout();
2249 bool Paragraph::isPassThru() const
2251 return inInset().isPassThru() || d->layout_->pass_thru;
2256 // paragraphs inside floats need different alignment tags to avoid
2259 bool noTrivlistCentering(InsetCode code)
2261 return code == FLOAT_CODE
2262 || code == WRAP_CODE
2263 || code == CELL_CODE;
2267 string correction(string const & orig)
2269 if (orig == "flushleft")
2270 return "raggedright";
2271 if (orig == "flushright")
2272 return "raggedleft";
2273 if (orig == "center")
2279 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2280 InsetCode code, bool const lastpar, int & col)
2282 string macro = suffix + "{";
2283 if (noTrivlistCentering(code)) {
2285 // the last paragraph in non-trivlist-aligned
2286 // context is special (to avoid unwanted whitespace)
2287 if (suffix == "\\begin") {
2288 macro = "\\" + correction(env) + "{}";
2289 os << from_ascii(macro);
2290 col += macro.size();
2295 macro += correction(env);
2299 if (suffix == "\\par\\end") {
2303 os << from_ascii(macro);
2304 col += macro.size();
2305 if (suffix == "\\begin") {
2315 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2316 otexstream & os, OutputParams const & runparams) const
2321 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2322 (layout_->toggle_indent != ITOGGLE_NEVER) :
2323 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2325 if (canindent && params_.noindent() && !layout_->pass_thru) {
2326 os << "\\noindent ";
2330 LyXAlignment const curAlign = params_.align();
2332 if (curAlign == layout_->align)
2336 case LYX_ALIGN_NONE:
2337 case LYX_ALIGN_BLOCK:
2338 case LYX_ALIGN_LAYOUT:
2339 case LYX_ALIGN_SPECIAL:
2340 case LYX_ALIGN_DECIMAL:
2342 case LYX_ALIGN_LEFT:
2343 case LYX_ALIGN_RIGHT:
2344 case LYX_ALIGN_CENTER:
2345 if (runparams.moving_arg) {
2352 string const begin_tag = "\\begin";
2353 InsetCode code = ownerCode();
2354 bool const lastpar = runparams.isLastPar;
2355 // RTL in classic (PDF)LaTeX (without the Bidi package)
2356 // Luabibdi (used by LuaTeX) behaves like classic
2357 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2358 && !runparams.useBidiPackage();
2361 case LYX_ALIGN_NONE:
2362 case LYX_ALIGN_BLOCK:
2363 case LYX_ALIGN_LAYOUT:
2364 case LYX_ALIGN_SPECIAL:
2365 case LYX_ALIGN_DECIMAL:
2367 case LYX_ALIGN_LEFT: {
2369 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2370 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2372 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2374 } case LYX_ALIGN_RIGHT: {
2376 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2377 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2379 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2381 } case LYX_ALIGN_CENTER: {
2382 corrected_env(os, begin_tag, "center", code, lastpar, column);
2391 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2392 otexstream & os, OutputParams const & runparams) const
2394 LyXAlignment const curAlign = params_.align();
2396 if (curAlign == layout_->align)
2400 case LYX_ALIGN_NONE:
2401 case LYX_ALIGN_BLOCK:
2402 case LYX_ALIGN_LAYOUT:
2403 case LYX_ALIGN_SPECIAL:
2404 case LYX_ALIGN_DECIMAL:
2406 case LYX_ALIGN_LEFT:
2407 case LYX_ALIGN_RIGHT:
2408 case LYX_ALIGN_CENTER:
2409 if (runparams.moving_arg)
2414 bool output = false;
2416 string const end_tag = "\\par\\end";
2417 InsetCode code = ownerCode();
2418 bool const lastpar = runparams.isLastPar;
2419 // RTL in classic (PDF)LaTeX (without the Bidi package)
2420 // Luabibdi (used by LuaTeX) behaves like classic
2421 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2422 && !runparams.useBidiPackage();
2425 case LYX_ALIGN_NONE:
2426 case LYX_ALIGN_BLOCK:
2427 case LYX_ALIGN_LAYOUT:
2428 case LYX_ALIGN_SPECIAL:
2429 case LYX_ALIGN_DECIMAL:
2431 case LYX_ALIGN_LEFT: {
2433 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2434 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2436 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2438 } case LYX_ALIGN_RIGHT: {
2440 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2441 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2443 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2445 } case LYX_ALIGN_CENTER: {
2446 corrected_env(os, end_tag, "center", code, lastpar, col);
2451 return output || lastpar;
2455 // This one spits out the text of the paragraph
2456 void Paragraph::latex(BufferParams const & bparams,
2457 Font const & outerfont,
2459 OutputParams const & runparams,
2460 int start_pos, int end_pos, bool force) const
2462 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2464 // FIXME This check should not be needed. Perhaps issue an
2465 // error if it triggers.
2466 Layout const & style = inInset().forcePlainLayout() ?
2467 bparams.documentClass().plainLayout() : *d->layout_;
2469 if (!force && style.inpreamble)
2472 bool const allowcust = allowParagraphCustomization();
2474 // Current base font for all inherited font changes, without any
2475 // change caused by an individual character, except for the language:
2476 // It is set to the language of the first character.
2477 // As long as we are in the label, this font is the base font of the
2478 // label. Before the first body character it is set to the base font
2482 // If there is an open font-encoding changing command (script wrapper),
2483 // alien_script is set to its name
2484 string alien_script;
2487 // Maybe we have to create a optional argument.
2488 pos_type body_pos = beginOfBody();
2489 unsigned int column = 0;
2491 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2492 Font const real_outerfont = (!inInset().inheritFont()
2493 && runparams.local_font != nullptr)
2494 ? Font(runparams.local_font->fontInfo()) : outerfont;
2497 // the optional argument is kept in curly brackets in
2498 // case it contains a ']'
2499 // This is not strictly needed, but if this is changed it
2500 // would be a file format change, and tex2lyx would need
2501 // to be adjusted, since it unconditionally removes the
2502 // braces when it parses \item.
2505 basefont = getLabelFont(bparams, real_outerfont);
2507 basefont = getLayoutFont(bparams, real_outerfont);
2510 // Which font is currently active?
2511 Font running_font(basefont);
2512 // Do we have an open font change?
2513 bool open_font = false;
2515 Change runningChange = Change(Change::UNCHANGED);
2517 Encoding const * const prev_encoding = runparams.encoding;
2519 os.texrow().start(id(), 0);
2521 // if the paragraph is empty, the loop will not be entered at all
2523 // For InTitle commands, we have already opened a group
2524 // in output_latex::TeXOnePar.
2525 if (style.isCommand() && !style.intitle) {
2529 if (!style.leftdelim().empty()) {
2530 os << style.leftdelim();
2531 column += style.leftdelim().size();
2534 column += d->startTeXParParams(bparams, os, runparams);
2537 // Whether a \par can be issued for insets typeset inline with text.
2538 // Yes if greater than 0. This has to be static.
2539 THREAD_LOCAL_STATIC int parInline = 0;
2541 for (pos_type i = 0; i < size(); ++i) {
2542 // First char in paragraph or after label?
2543 if (i == body_pos) {
2546 bool needPar = false;
2547 column += running_font.latexWriteEndChanges(
2548 os, bparams, runparams,
2549 basefont, basefont, needPar);
2552 basefont = getLayoutFont(bparams, real_outerfont);
2553 running_font = basefont;
2555 column += Changes::latexMarkChange(os, bparams,
2556 runningChange, Change(Change::UNCHANGED),
2558 runningChange = Change(Change::UNCHANGED);
2563 // For InTitle commands, we have already opened a group
2564 // in output_latex::TeXOnePar.
2565 if (style.isCommand() && !style.intitle) {
2570 if (!style.leftdelim().empty()) {
2571 os << style.leftdelim();
2572 column += style.leftdelim().size();
2576 column += d->startTeXParParams(bparams, os,
2580 runparams.wasDisplayMath = runparams.inDisplayMath;
2581 runparams.inDisplayMath = false;
2582 bool deleted_display_math = false;
2583 Change const & change = runparams.inDeletedInset
2584 ? runparams.changeOfDeletedInset : lookupChange(i);
2586 char_type const c = d->text_[i];
2588 // Check whether a display math inset follows
2589 bool output_changes;
2590 if (runparams.for_searchAdv == OutputParams::NoSearch)
2591 output_changes = bparams.output_changes;
2593 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2595 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2597 runparams.ctObject = getInset(i)->getCtObject(runparams);
2599 InsetMath const * im = getInset(i)->asInsetMath();
2600 if (im && im->asHullInset()
2601 && im->asHullInset()->outerDisplay()) {
2602 runparams.inDisplayMath = true;
2603 // runparams.inDeletedInset will be set by
2604 // latexInset later, but we need this info
2605 // before it is called. On the other hand, we
2606 // cannot set it here because it is a counter.
2607 deleted_display_math = isDeleted(i);
2609 if (output_changes && deleted_display_math
2610 && runningChange == change
2611 && change.type == Change::DELETED
2612 && !os.afterParbreak()) {
2613 // A display math in the same paragraph follows.
2614 // We have to close and then reopen \lyxdeleted,
2615 // otherwise the math will be shifted up.
2616 OutputParams rp = runparams;
2618 bool needPar = false;
2619 column += running_font.latexWriteEndChanges(
2620 os, bparams, rp, basefont,
2624 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2625 : getLayoutFont(bparams, real_outerfont);
2626 running_font = basefont;
2627 column += Changes::latexMarkChange(os, bparams,
2628 Change(Change::INSERTED), change, rp);
2632 if (output_changes && runningChange != change) {
2633 if (!alien_script.empty()) {
2636 alien_script.clear();
2639 bool needPar = false;
2640 column += running_font.latexWriteEndChanges(
2641 os, bparams, runparams,
2642 basefont, basefont, needPar);
2645 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2646 : getLayoutFont(bparams, real_outerfont);
2647 running_font = basefont;
2648 column += Changes::latexMarkChange(os, bparams, runningChange,
2650 runningChange = change;
2653 // do not output text which is marked deleted
2654 // if change tracking output is disabled
2655 if (!output_changes && change.deleted()) {
2661 // Fully instantiated font
2662 Font current_font = getFont(bparams, i, outerfont);
2664 Font const prev_font = (i > 0) ?
2665 getFont(bparams, i - 1, outerfont)
2668 Font const last_font = running_font;
2669 bool const in_ct_deletion = (output_changes
2670 && runningChange == change
2671 && change.type == Change::DELETED
2672 && !os.afterParbreak());
2673 // Insets where font switches are used (rather than font commands)
2674 bool const fontswitch_inset =
2677 && getInset(i)->allowMultiPar()
2678 && getInset(i)->lyxCode() != ERT_CODE
2679 && getInset(i)->producesOutput();
2681 bool closeLanguage = false;
2682 bool lang_switched_at_inset = false;
2683 if (fontswitch_inset) {
2684 // Some insets cannot be inside a font change command.
2685 // However, even such insets *can* be placed in \L or \R
2686 // or their equivalents (for RTL language switches),
2687 // so we don't close the language in those cases
2688 // (= differing isRightToLeft()).
2689 // ArabTeX, though, doesn't seem to handle this special behavior.
2690 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2691 || basefont.language()->lang() == "arabic_arabtex"
2692 || current_font.language()->lang() == "arabic_arabtex";
2693 // We need to check prev_font as language changes directly at inset
2694 // will only be started inside the inset.
2695 lang_switched_at_inset = prev_font.language() != current_font.language();
2698 // Do we need to close the previous font?
2699 bool langClosed = false;
2701 ((current_font != running_font
2702 || current_font.language() != running_font.language())
2703 || (fontswitch_inset
2704 && (current_font == prev_font))))
2706 // ensure there is no open script-wrapper
2707 if (!alien_script.empty()) {
2710 alien_script.clear();
2712 if (in_ct_deletion) {
2713 // We have to close and then reopen \lyxdeleted,
2714 // as strikeout needs to be on lowest level.
2719 // Force language closing
2720 current_font.setLanguage(basefont.language());
2721 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2722 bool needPar = false;
2723 column += running_font.latexWriteEndChanges(
2724 os, bparams, runparams, basefont,
2726 if (in_ct_deletion) {
2727 // We have to close and then reopen \lyxdeleted,
2728 // as strikeout needs to be on lowest level.
2729 OutputParams rp = runparams;
2730 column += Changes::latexMarkChange(os, bparams,
2731 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2734 // Has the language been closed in the latexWriteEndChanges() call above?
2735 langClosed = running_font.language() != basefont.language()
2736 && running_font.language() != nextfont.language()
2737 && (running_font.language()->encoding()->package() != Encoding::CJK);
2738 running_font = basefont;
2741 // if necessary, close language environment before opening CJK
2742 string const running_lang = running_font.language()->babel();
2743 string const lang_end_command = lyxrc.language_command_end;
2744 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2745 && !running_lang.empty()
2746 && running_lang == openLanguageName()
2747 && current_font.language()->encoding()->package() == Encoding::CJK) {
2748 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2749 os << from_ascii(end_tag);
2750 column += end_tag.length();
2754 // Switch file encoding if necessary (and allowed)
2755 if ((!fontswitch_inset || closeLanguage)
2756 && !runparams.pass_thru && !style.pass_thru &&
2757 runparams.encoding->package() != Encoding::none &&
2758 current_font.language()->encoding()->package() != Encoding::none) {
2759 pair<bool, int> const enc_switch =
2760 switchEncoding(os.os(), bparams, runparams,
2761 *(current_font.language()->encoding()));
2762 if (enc_switch.first) {
2763 column += enc_switch.second;
2764 runparams.encoding = current_font.language()->encoding();
2768 // A display math inset inside an ulem command will be output
2769 // as a box of width \linewidth, so we have to either disable
2770 // indentation if the inset starts a paragraph, or start a new
2771 // line to accommodate such box. This has to be done before
2772 // writing any font changing commands.
2773 if (runparams.inDisplayMath && !deleted_display_math
2774 && runparams.inulemcmd) {
2775 if (os.afterParbreak())
2781 // Do we need to change font?
2782 if ((current_font != running_font ||
2783 current_font.language() != running_font.language())
2784 && i != body_pos - 1)
2786 if (!fontswitch_inset) {
2787 if (in_ct_deletion) {
2788 // We have to close and then reopen \lyxdeleted,
2789 // as strikeout needs to be on lowest level.
2790 OutputParams rp = runparams;
2791 bool needPar = false;
2792 column += running_font.latexWriteEndChanges(
2793 os, bparams, rp, basefont,
2798 otexstringstream ots;
2799 InsetText const * textinset = inInset().asInsetText();
2800 bool const cprotect = textinset
2801 ? textinset->hasCProtectContent(runparams.moving_arg)
2802 && !textinset->text().isMainText()
2804 column += current_font.latexWriteStartChanges(ots, bparams,
2805 runparams, basefont, last_font, false,
2807 // Check again for display math in ulem commands as a
2808 // font change may also occur just before a math inset.
2809 if (runparams.inDisplayMath && !deleted_display_math
2810 && runparams.inulemcmd) {
2811 if (os.afterParbreak())
2816 running_font = current_font;
2818 docstring fontchange = ots.str();
2820 // check whether the fontchange ends with a \\textcolor
2821 // modifier and the text starts with a space. If so we
2822 // need to add } in order to prevent \\textcolor from gobbling
2823 // the space (bug 4473).
2824 docstring const last_modifier = rsplit(fontchange, '\\');
2825 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2826 os << from_ascii("{}");
2827 else if (ots.terminateCommand())
2829 if (in_ct_deletion) {
2830 // We have to close and then reopen \lyxdeleted,
2831 // as strikeout needs to be on lowest level.
2832 OutputParams rp = runparams;
2833 column += Changes::latexMarkChange(os, bparams,
2834 Change(Change::UNCHANGED), change, rp);
2837 running_font = current_font;
2838 open_font = !langClosed;
2842 // FIXME: think about end_pos implementation...
2843 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2844 // FIXME: integrate this case in latexSpecialChar
2845 // Do not print the separation of the optional argument
2846 // if style.pass_thru is false. This works because
2847 // latexSpecialChar ignores spaces if
2848 // style.pass_thru is false.
2849 if (i != body_pos - 1) {
2850 if (d->simpleTeXBlanks(bparams, runparams, os,
2851 i, column, current_font, style)) {
2852 // A surrogate pair was output. We
2853 // must not call latexSpecialChar
2854 // in this iteration, since it would output
2855 // the combining character again.
2862 OutputParams rp = runparams;
2863 rp.free_spacing = style.free_spacing;
2864 rp.local_font = ¤t_font;
2865 rp.intitle = style.intitle;
2867 // Two major modes: LaTeX or plain
2868 // Handle here those cases common to both modes
2869 // and then split to handle the two modes separately.
2870 if (c == META_INSET) {
2871 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2872 // Greyedout notes and, in general, all insets
2873 // with InsetLayout::isDisplay() == false,
2874 // are typeset inline with the text. So, we
2875 // can add a \par to the last paragraph of
2876 // such insets only if nothing else follows.
2877 bool incremented = false;
2878 Inset const * inset = getInset(i);
2879 InsetText const * textinset = inset
2880 ? inset->asInsetText()
2882 if (i + 1 == size() && textinset
2883 && !inset->getLayout().isDisplay()) {
2884 ParagraphList const & pars =
2885 textinset->text().paragraphs();
2886 pit_type const pit = pars.size() - 1;
2887 Font const lastfont =
2888 pit < 0 || pars[pit].empty()
2889 ? pars[pit].getLayoutFont(
2892 : pars[pit].getFont(bparams,
2893 pars[pit].size() - 1,
2895 if (lastfont.fontInfo().size() !=
2896 basefont.fontInfo().size()) {
2901 // We need to restore parts of this after insets with
2902 // allowMultiPar() true
2903 Font const save_basefont = basefont;
2904 d->latexInset(bparams, os, rp, running_font,
2905 basefont, real_outerfont, open_font,
2906 runningChange, style, i, column, fontswitch_inset,
2907 closeLanguage, lang_switched_at_inset);
2908 if (fontswitch_inset) {
2910 bool needPar = false;
2911 column += running_font.latexWriteEndChanges(
2912 os, bparams, runparams,
2913 basefont, basefont, needPar);
2916 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2917 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2918 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2923 if (runparams.ctObject == CtObject::DisplayObject
2924 || runparams.ctObject == CtObject::UDisplayObject) {
2925 // Close \lyx*deleted and force its
2926 // reopening (if needed)
2929 runningChange = Change(Change::UNCHANGED);
2930 runparams.ctObject = CtObject::Normal;
2933 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2934 if (!bparams.useNonTeXFonts)
2935 script = Encodings::isKnownScriptChar(c);
2936 if (script != alien_script) {
2937 if (!alien_script.empty()) {
2939 alien_script.clear();
2941 string fontenc = running_font.language()->fontenc(bparams);
2943 && !Encodings::fontencSupportsScript(fontenc, script)) {
2944 column += script.length() + 2;
2945 os << "\\" << script << "{";
2946 alien_script = script;
2950 d->latexSpecialChar(os, bparams, rp, running_font,
2951 alien_script, style, i, end_pos, column);
2952 } catch (EncodingException & e) {
2953 if (runparams.dryrun) {
2954 os << "<" << _("LyX Warning: ")
2955 << _("uncodable character") << " '";
2959 // add location information and throw again.
2967 // Set the encoding to that returned from latexSpecialChar (see
2968 // comment for encoding member in OutputParams.h)
2969 runparams.encoding = rp.encoding;
2971 // Also carry on the info on a closed ulem command for insets
2972 // such as Note that do not produce any output, so that no
2973 // command is ever executed but its opening was recorded.
2974 runparams.inulemcmd = rp.inulemcmd;
2976 // These need to be passed upstream as well
2977 runparams.need_maketitle = rp.need_maketitle;
2978 runparams.have_maketitle = rp.have_maketitle;
2980 // And finally, pass the post_macros upstream
2981 runparams.post_macro = rp.post_macro;
2984 // Close wrapper for alien script
2985 if (!alien_script.empty()) {
2987 alien_script.clear();
2990 Font const font = empty()
2991 ? getLayoutFont(bparams, real_outerfont)
2992 : getFont(bparams, size() - 1, real_outerfont);
2994 InsetText const * textinset = inInset().asInsetText();
2996 bool const maintext = textinset
2997 ? textinset->text().isMainText()
3000 size_t const numpars = textinset
3001 ? textinset->text().paragraphs().size()
3004 bool needPar = false;
3006 if (style.resfont.size() != font.fontInfo().size()
3007 && (!runparams.isLastPar || maintext
3008 || (numpars > 1 && d->ownerCode() != CELL_CODE
3009 && (inInset().getLayout().isDisplay()
3011 && !style.isCommand()) {
3015 // If we have an open font definition, we have to close it
3017 // Make sure that \\par is done with the font of the last
3018 // character if this has another size as the default.
3019 // This is necessary because LaTeX (and LyX on the screen)
3020 // calculates the space between the baselines according
3021 // to this font. (Matthias)
3023 // We must not change the font for the last paragraph
3024 // of non-multipar insets, tabular cells or commands,
3025 // since this produces unwanted whitespace.
3026 #ifdef FIXED_LANGUAGE_END_DETECTION
3028 running_font.latexWriteEndChanges(os, bparams,
3029 runparams, basefont,
3030 next_->getFont(bparams, 0, outerfont),
3033 running_font.latexWriteEndChanges(os, bparams,
3034 runparams, basefont, basefont, needPar);
3037 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3038 //FIXME: there as we start another \selectlanguage with the next paragraph if
3039 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3040 running_font.latexWriteEndChanges(os, bparams, runparams,
3041 basefont, basefont, needPar);
3045 // The \par could not be inserted at the same nesting
3046 // level of the font size change, so do it now.
3047 os << "{\\" << font.latexSize() << "\\par}";
3050 column += Changes::latexMarkChange(os, bparams, runningChange,
3051 Change(Change::UNCHANGED), runparams);
3053 // Needed if there is an optional argument but no contents.
3054 if (body_pos > 0 && body_pos == size()) {
3058 if (!style.rightdelim().empty()) {
3059 os << style.rightdelim();
3060 column += style.rightdelim().size();
3063 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3064 && runparams.encoding != prev_encoding) {
3065 runparams.encoding = prev_encoding;
3066 os << setEncoding(prev_encoding->iconvName());
3069 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3073 bool Paragraph::emptyTag() const
3075 for (pos_type i = 0; i < size(); ++i) {
3076 if (Inset const * inset = getInset(i)) {
3077 InsetCode lyx_code = inset->lyxCode();
3078 // FIXME testing like that is wrong. What is
3080 if (lyx_code != TOC_CODE &&
3081 lyx_code != INCLUDE_CODE &&
3082 lyx_code != GRAPHICS_CODE &&
3083 lyx_code != ERT_CODE &&
3084 lyx_code != LISTINGS_CODE &&
3085 lyx_code != FLOAT_CODE &&
3086 lyx_code != TABULAR_CODE) {
3090 char_type c = d->text_[i];
3091 if (c != ' ' && c != '\t')
3099 string Paragraph::getID(Buffer const &, OutputParams const &)
3102 for (pos_type i = 0; i < size(); ++i) {
3103 if (Inset const * inset = getInset(i)) {
3104 InsetCode lyx_code = inset->lyxCode();
3105 if (lyx_code == LABEL_CODE) {
3106 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3107 docstring const & id = il->getParam("name");
3108 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3116 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3119 for (i = 0; i < size(); ++i) {
3120 if (Inset const * inset = getInset(i)) {
3121 inset->docbook(xs, runparams);
3123 char_type c = d->text_[i];
3133 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3137 for (i = 0; i < size(); ++i) {
3138 if (Inset const * inset = getInset(i)) {
3139 inset->xhtml(xs, runparams);
3141 char_type c = d->text_[i];
3151 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3154 pos_type size = text_.size();
3155 for (pos_type i = initial; i < size; ++i) {
3156 Font font = owner_->getFont(buf.params(), i, outerfont);
3157 if (text_[i] == META_INSET)
3159 if (i != initial && font != font_old)
3170 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3171 vector<xml::EndFontTag> & tagsToClose,
3172 bool & flag, FontState curstate, xml::FontTypes type)
3174 if (curstate == FONT_ON) {
3175 tagsToOpen.push_back(docbookStartFontTag(type));
3178 tagsToClose.push_back(docbookEndFontTag(type));
3183 class OptionalFontType {
3188 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3189 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3192 OptionalFontType fontShapeToXml(FontShape fs)
3196 return {xml::FT_ITALIC};
3198 return {xml::FT_SLANTED};
3199 case SMALLCAPS_SHAPE:
3200 return {xml::FT_SMALLCAPS};
3205 // the other tags are for internal use
3211 OptionalFontType fontFamilyToXml(FontFamily fm)
3215 return {xml::FT_ROMAN};
3217 return {xml::FT_SANS};
3218 case TYPEWRITER_FAMILY:
3219 return {xml::FT_TYPE};
3220 case INHERIT_FAMILY:
3223 // the other tags are for internal use
3229 OptionalFontType fontSizeToXml(FontSize fs)
3233 return {xml::FT_SIZE_TINY};
3235 return {xml::FT_SIZE_SCRIPT};
3237 return {xml::FT_SIZE_FOOTNOTE};
3239 return {xml::FT_SIZE_SMALL};
3241 return {xml::FT_SIZE_LARGE};
3243 return {xml::FT_SIZE_LARGER};
3245 return {xml::FT_SIZE_LARGEST};
3247 return {xml::FT_SIZE_HUGE};
3249 return {xml::FT_SIZE_HUGER};
3251 return {xml::FT_SIZE_INCREASE};
3253 return {xml::FT_SIZE_DECREASE};
3258 // the other tags are for internal use
3264 struct DocBookFontState
3266 FontShape curr_fs = INHERIT_SHAPE;
3267 FontFamily curr_fam = INHERIT_FAMILY;
3268 FontSize curr_size = INHERIT_SIZE;
3270 // track whether we have opened these tags
3271 bool emph_flag = false;
3272 bool bold_flag = false;
3273 bool noun_flag = false;
3274 bool ubar_flag = false;
3275 bool dbar_flag = false;
3276 bool sout_flag = false;
3277 bool xout_flag = false;
3278 bool wave_flag = false;
3280 bool shap_flag = false;
3282 bool faml_flag = false;
3284 bool size_flag = false;
3287 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3289 std::string const & default_family,
3290 DocBookFontState & fs)
3292 vector<xml::FontTag> tagsToOpen;
3293 vector<xml::EndFontTag> tagsToClose;
3296 FontState curstate = font.fontInfo().emph();
3297 if (font_old.emph() != curstate)
3298 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3301 curstate = font.fontInfo().noun();
3302 if (font_old.noun() != curstate)
3303 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3306 curstate = font.fontInfo().underbar();
3307 if (font_old.underbar() != curstate)
3308 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3311 curstate = font.fontInfo().strikeout();
3312 if (font_old.strikeout() != curstate)
3313 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3316 curstate = font.fontInfo().xout();
3317 if (font_old.xout() != curstate)
3318 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3321 curstate = font.fontInfo().uuline();
3322 if (font_old.uuline() != curstate)
3323 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3326 curstate = font.fontInfo().uwave();
3327 if (font_old.uwave() != curstate)
3328 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3331 // a little hackish, but allows us to reuse what we have.
3332 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3333 if (font_old.series() != font.fontInfo().series())
3334 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3337 fs.curr_fs = font.fontInfo().shape();
3338 FontShape old_fs = font_old.shape();
3339 if (old_fs != fs.curr_fs) {
3341 OptionalFontType tag = fontShapeToXml(old_fs);
3343 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3344 fs.shap_flag = false;
3347 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3349 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3353 fs.curr_fam = font.fontInfo().family();
3354 FontFamily old_fam = font_old.family();
3355 if (old_fam != fs.curr_fam) {
3357 OptionalFontType tag = fontFamilyToXml(old_fam);
3359 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3360 fs.faml_flag = false;
3362 switch (fs.curr_fam) {
3364 // we will treat a "default" font family as roman, since we have
3365 // no other idea what to do.
3366 if (default_family != "rmdefault" && default_family != "default") {
3367 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3368 fs.faml_flag = true;
3372 if (default_family != "sfdefault") {
3373 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3374 fs.faml_flag = true;
3377 case TYPEWRITER_FAMILY:
3378 if (default_family != "ttdefault") {
3379 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3380 fs.faml_flag = true;
3383 case INHERIT_FAMILY:
3386 // the other tags are for internal use
3393 fs.curr_size = font.fontInfo().size();
3394 FontSize old_size = font_old.size();
3395 if (old_size != fs.curr_size) {
3397 OptionalFontType tag = fontSizeToXml(old_size);
3399 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3400 fs.size_flag = false;
3403 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3404 if (tag.has_value) {
3405 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3406 fs.size_flag = true;
3410 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3413 } // anonymous namespace
3416 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3417 OutputParams const & runparams,
3418 Font const & outerfont,
3421 bool ignore_fonts) const
3423 // Track whether we have opened these tags
3424 DocBookFontState fs;
3426 Layout const & style = *d->layout_;
3428 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3430 string const default_family =
3431 buf.masterBuffer()->params().fonts_default_family;
3433 vector<xml::FontTag> tagsToOpen;
3434 vector<xml::EndFontTag> tagsToClose;
3436 std::vector<docstring> generatedParagraphs;
3437 DocBookFontState old_fs = fs;
3438 odocstringstream os;
3439 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3440 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3442 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3443 // characters at some point.
3444 std::vector<char_type> delayedChars;
3446 // Parsing main loop.
3447 for (pos_type i = initial; i < size(); ++i) {
3448 // Don't show deleted material in the output.
3452 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3454 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3456 xs->closeFontTags();
3458 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3459 generatedParagraphs.push_back(os.str());
3461 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3462 // that the string stream must be reset.
3463 os.str(from_ascii(""));
3465 xs = new XMLStream(os);
3467 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3468 if (!ignore_fonts) {
3469 font_old = outerfont.fontInfo();
3474 // Determine which tags should be opened or closed regarding fonts.
3475 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3476 if (!ignore_fonts) {
3477 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3480 // Other such tags? What about the other text ranges?
3482 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3483 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3484 for (; cit != cen; ++cit)
3487 // Deal with the delayed characters *after* closing font tags.
3488 if (!delayedChars.empty()) {
3489 for (char_type c: delayedChars)
3491 delayedChars.clear();
3494 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3495 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3496 for (; sit != sen; ++sit)
3499 tagsToClose.clear();
3503 if (Inset const * inset = getInset(i)) {
3504 if (!runparams.for_toc || inset->isInToc()) {
3505 OutputParams np = runparams;
3506 np.local_font = &font;
3508 // TODO: special case will bite here.
3509 np.docbook_in_par = true;
3510 inset->docbook(*xs, np);
3513 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3514 if (lyx::isSpace(c) && !ignore_fonts)
3515 delayedChars.push_back(c);
3519 font_old = font.fontInfo();
3522 // FIXME, this code is just imported from XHTML
3523 // I'm worried about what happens if a branch, say, is itself
3524 // wrapped in some font stuff. I think that will not work.
3526 xs->closeFontTags();
3528 // Deal with the delayed characters *after* closing font tags.
3529 if (!delayedChars.empty())
3530 for (char_type c: delayedChars)
3533 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3534 // last line to get a clean output.
3535 if (runparams.docbook_in_listing && !is_last_par)
3538 // Finalise the last (and most likely only) paragraph.
3539 generatedParagraphs.push_back(os.str());
3542 return generatedParagraphs;
3548 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3549 vector<xml::EndFontTag> & tagsToClose,
3550 bool & flag, FontState curstate, xml::FontTypes type)
3552 if (curstate == FONT_ON) {
3553 tagsToOpen.push_back(xhtmlStartFontTag(type));
3556 tagsToClose.push_back(xhtmlEndFontTag(type));
3561 } // anonymous namespace
3564 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3566 OutputParams const & runparams,
3567 Font const & outerfont,
3568 bool start_paragraph, bool close_paragraph,
3569 pos_type initial) const
3573 // track whether we have opened these tags
3574 bool emph_flag = false;
3575 bool bold_flag = false;
3576 bool noun_flag = false;
3577 bool ubar_flag = false;
3578 bool dbar_flag = false;
3579 bool sout_flag = false;
3580 bool xout_flag = false;
3581 bool wave_flag = false;
3583 bool shap_flag = false;
3585 bool faml_flag = false;
3587 bool size_flag = false;
3589 Layout const & style = *d->layout_;
3591 if (start_paragraph)
3592 xs.startDivision(allowEmpty());
3595 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3597 FontShape curr_fs = INHERIT_SHAPE;
3598 FontFamily curr_fam = INHERIT_FAMILY;
3599 FontSize curr_size = INHERIT_SIZE;
3601 string const default_family =
3602 buf.masterBuffer()->params().fonts_default_family;
3604 vector<xml::FontTag> tagsToOpen;
3605 vector<xml::EndFontTag> tagsToClose;
3607 // parsing main loop
3608 for (pos_type i = initial; i < size(); ++i) {
3609 // let's not show deleted material in the output
3613 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3616 FontState curstate = font.fontInfo().emph();
3617 if (font_old.emph() != curstate)
3618 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3621 curstate = font.fontInfo().noun();
3622 if (font_old.noun() != curstate)
3623 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3626 curstate = font.fontInfo().underbar();
3627 if (font_old.underbar() != curstate)
3628 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3631 curstate = font.fontInfo().strikeout();
3632 if (font_old.strikeout() != curstate)
3633 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3636 curstate = font.fontInfo().xout();
3637 if (font_old.xout() != curstate)
3638 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3641 curstate = font.fontInfo().uuline();
3642 if (font_old.uuline() != curstate)
3643 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3646 curstate = font.fontInfo().uwave();
3647 if (font_old.uwave() != curstate)
3648 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3651 // a little hackish, but allows us to reuse what we have.
3652 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3653 if (font_old.series() != font.fontInfo().series())
3654 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3657 curr_fs = font.fontInfo().shape();
3658 FontShape old_fs = font_old.shape();
3659 if (old_fs != curr_fs) {
3663 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3666 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3668 case SMALLCAPS_SHAPE:
3669 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3675 // the other tags are for internal use
3683 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3687 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3690 case SMALLCAPS_SHAPE:
3691 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3698 // the other tags are for internal use
3705 curr_fam = font.fontInfo().family();
3706 FontFamily old_fam = font_old.family();
3707 if (old_fam != curr_fam) {
3711 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3714 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3716 case TYPEWRITER_FAMILY:
3717 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3719 case INHERIT_FAMILY:
3722 // the other tags are for internal use
3730 // we will treat a "default" font family as roman, since we have
3731 // no other idea what to do.
3732 if (default_family != "rmdefault" && default_family != "default") {
3733 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3738 if (default_family != "sfdefault") {
3739 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3743 case TYPEWRITER_FAMILY:
3744 if (default_family != "ttdefault") {
3745 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3749 case INHERIT_FAMILY:
3752 // the other tags are for internal use
3759 curr_size = font.fontInfo().size();
3760 FontSize old_size = font_old.size();
3761 if (old_size != curr_size) {
3765 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3768 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3771 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3774 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3777 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3780 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3783 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3786 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3789 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3792 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3795 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3801 // the other tags are for internal use
3807 switch (curr_size) {
3809 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3813 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3817 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3821 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3825 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3829 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3833 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3837 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3841 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3845 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3849 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3856 // the other tags are for internal use
3863 // Other such tags? What about the other text ranges?
3865 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3866 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3867 for (; cit != cen; ++cit)
3870 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3871 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3872 for (; sit != sen; ++sit)
3875 tagsToClose.clear();
3878 Inset const * inset = getInset(i);
3880 if (!runparams.for_toc || inset->isInToc()) {
3881 OutputParams np = runparams;
3882 np.local_font = &font;
3883 // If the paragraph has size 1, then we are in the "special
3884 // case" where we do not output the containing paragraph info
3885 if (!inset->getLayout().htmlisblock() && size() != 1)
3886 np.html_in_par = true;
3887 retval += inset->xhtml(xs, np);
3890 char_type c = getUChar(buf.masterBuffer()->params(),
3892 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3893 xs << XMLStream::ESCAPE_NONE << " ";
3897 font_old = font.fontInfo();
3901 // I'm worried about what happens if a branch, say, is itself
3902 // wrapped in some font stuff. I think that will not work.
3904 if (close_paragraph)
3911 bool Paragraph::isHfill(pos_type pos) const
3913 Inset const * inset = getInset(pos);
3914 return inset && inset->isHfill();
3918 bool Paragraph::isNewline(pos_type pos) const
3920 // U+2028 LINE SEPARATOR
3921 // U+2029 PARAGRAPH SEPARATOR
3922 char_type const c = d->text_[pos];
3923 if (c == 0x2028 || c == 0x2029)
3925 Inset const * inset = getInset(pos);
3926 return inset && inset->lyxCode() == NEWLINE_CODE;
3930 bool Paragraph::isEnvSeparator(pos_type pos) const
3932 Inset const * inset = getInset(pos);
3933 return inset && inset->lyxCode() == SEPARATOR_CODE;
3937 bool Paragraph::isLineSeparator(pos_type pos) const
3939 char_type const c = d->text_[pos];
3940 if (isLineSeparatorChar(c))
3942 Inset const * inset = getInset(pos);
3943 return inset && inset->isLineSeparator();
3947 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3951 if (ignore_deleted && isDeleted(pos))
3953 if (Inset const * inset = getInset(pos))
3954 return !inset->isLetter();
3955 // if we have a hard hyphen (no en- or emdash) or apostrophe
3956 // we pass this to the spell checker
3957 // FIXME: this method is subject to change, visit
3958 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3959 // to get an impression how complex this is.
3960 if (isHardHyphenOrApostrophe(pos))
3962 char_type const c = d->text_[pos];
3963 // We want to pass the escape chars to the spellchecker
3964 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3965 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3969 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3971 pos_type const psize = size();
3974 char_type const c = d->text_[pos];
3975 if (c != '-' && c != '\'')
3977 pos_type nextpos = pos + 1;
3978 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3979 if ((nextpos == psize || isSpace(nextpos))
3980 && (pos == 0 || isSpace(prevpos)))
3986 bool Paragraph::needsCProtection(bool const fragile) const
3988 // first check the layout of the paragraph, but only in insets
3989 InsetText const * textinset = inInset().asInsetText();
3990 bool const maintext = textinset
3991 ? textinset->text().isMainText()
3994 if (!maintext && layout().needcprotect) {
3995 // Environments need cprotection regardless the content
3996 if (layout().latextype == LATEX_ENVIRONMENT)
3999 // Commands need cprotection if they contain specific chars
4000 int const nchars_escape = 9;
4001 static char_type const chars_escape[nchars_escape] = {
4002 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4004 docstring const pars = asString();
4005 for (int k = 0; k < nchars_escape; k++) {
4006 if (contains(pars, chars_escape[k]))
4011 // now check whether we have insets that need cprotection
4012 pos_type size = pos_type(d->text_.size());
4013 for (pos_type i = 0; i < size; ++i) {
4016 Inset const * ins = getInset(i);
4017 if (ins->needsCProtection(maintext, fragile))
4019 // Now check math environments
4020 InsetMath const * im = getInset(i)->asInsetMath();
4021 if (!im || im->cell(0).empty())
4023 switch(im->cell(0)[0]->lyxCode()) {
4024 case MATH_AMSARRAY_CODE:
4025 case MATH_SUBSTACK_CODE:
4027 case MATH_XYMATRIX_CODE:
4028 // these need cprotection
4039 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4041 return d->speller_state_.getRange(pos);
4045 bool Paragraph::isChar(pos_type pos) const
4047 if (Inset const * inset = getInset(pos))
4048 return inset->isChar();
4049 char_type const c = d->text_[pos];
4050 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4054 bool Paragraph::isSpace(pos_type pos) const
4056 if (Inset const * inset = getInset(pos))
4057 return inset->isSpace();
4058 char_type const c = d->text_[pos];
4059 return lyx::isSpace(c);
4064 Paragraph::getParLanguage(BufferParams const & bparams) const
4067 return getFirstFontSettings(bparams).language();
4068 // FIXME: we should check the prev par as well (Lgb)
4069 return bparams.language;
4073 bool Paragraph::isRTL(BufferParams const & bparams) const
4075 return getParLanguage(bparams)->rightToLeft()
4076 && !inInset().getLayout().forceLTR();
4080 void Paragraph::changeLanguage(BufferParams const & bparams,
4081 Language const * from, Language const * to)
4083 // change language including dummy font change at the end
4084 for (pos_type i = 0; i <= size(); ++i) {
4085 Font font = getFontSettings(bparams, i);
4086 if (font.language() == from) {
4087 font.setLanguage(to);
4089 d->requestSpellCheck(i);
4095 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4097 Language const * doc_language = bparams.language;
4098 for (auto const & f : d->fontlist_)
4099 if (f.font().language() != ignore_language &&
4100 f.font().language() != latex_language &&
4101 f.font().language() != doc_language)
4107 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4109 for (auto const & f : d->fontlist_) {
4110 Language const * lang = f.font().language();
4111 if (lang != ignore_language &&
4112 lang != latex_language)
4118 docstring Paragraph::asString(int options) const
4120 return asString(0, size(), options);
4124 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4126 odocstringstream os;
4129 && options & AS_STR_LABEL
4130 && !d->params_.labelString().empty())
4131 os << d->params_.labelString() << ' ';
4133 for (pos_type i = beg; i < end; ++i) {
4134 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4136 char_type const c = d->text_[i];
4137 if (isPrintable(c) || c == '\t'
4138 || (c == '\n' && (options & AS_STR_NEWLINES)))
4140 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4141 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4142 LASSERT(runparams != nullptr, return docstring());
4143 getInset(i)->plaintext(os, *runparams);
4145 getInset(i)->toString(os);
4154 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4155 bool const shorten, bool const label) const
4157 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4158 if (label && !labelString().empty())
4159 os += labelString() + ' ';
4160 if (!layout().isTocCaption())
4162 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4165 char_type const c = d->text_[i];
4168 else if (c == META_INSET)
4169 getInset(i)->forOutliner(os, tmplen, false);
4172 Text::shortenForOutliner(os, maxlen);
4176 void Paragraph::setInsetOwner(Inset const * inset)
4178 d->inset_owner_ = inset;
4182 int Paragraph::id() const
4188 void Paragraph::setId(int id)
4194 Layout const & Paragraph::layout() const
4200 void Paragraph::setLayout(Layout const & layout)
4202 d->layout_ = &layout;
4206 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4208 setLayout(tc.defaultLayout());
4212 void Paragraph::setPlainLayout(DocumentClass const & tc)
4214 setLayout(tc.plainLayout());
4218 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4220 if (usePlainLayout())
4223 setDefaultLayout(tc);
4227 Inset const & Paragraph::inInset() const
4229 LBUFERR(d->inset_owner_);
4230 return *d->inset_owner_;
4234 ParagraphParameters & Paragraph::params()
4240 ParagraphParameters const & Paragraph::params() const
4246 bool Paragraph::isFreeSpacing() const
4248 if (d->layout_->free_spacing)
4250 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4254 bool Paragraph::allowEmpty() const
4256 if (d->layout_->keepempty)
4258 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4262 bool Paragraph::brokenBiblio() const
4264 // There is a problem if there is no bibitem at position 0 in
4265 // paragraphs that need one, if there is another bibitem in the
4266 // paragraph or if this paragraph is not supposed to have
4267 // a bibitem inset at all.
4268 return ((d->layout_->labeltype == LABEL_BIBLIO
4269 && (d->insetlist_.find(BIBITEM_CODE) != 0
4270 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4271 || (d->layout_->labeltype != LABEL_BIBLIO
4272 && d->insetlist_.find(BIBITEM_CODE) != -1));
4276 int Paragraph::fixBiblio(Buffer const & buffer)
4278 // FIXME: when there was already an inset at 0, the return value is 1,
4279 // which does not tell whether another inset has been removed; the
4280 // cursor cannot be correctly updated.
4282 bool const track_changes = buffer.params().track_changes;
4283 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4285 // The case where paragraph is not BIBLIO
4286 if (d->layout_->labeltype != LABEL_BIBLIO) {
4287 if (bibitem_pos == -1)
4288 // No InsetBibitem => OK
4290 // There is an InsetBibitem: remove it!
4291 d->insetlist_.release(bibitem_pos);
4292 eraseChar(bibitem_pos, track_changes);
4293 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4296 bool const hasbibitem0 = bibitem_pos == 0;
4298 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4299 // There was an InsetBibitem at pos 0,
4300 // and no other one => OK
4301 if (bibitem_pos == -1)
4303 // there is a bibitem at the 0 position, but since
4304 // there is a second one, we copy the second on the
4305 // first. We're assuming there are at most two of
4306 // these, which there should be.
4307 // FIXME: why does it make sense to do that rather
4308 // than keep the first? (JMarc)
4309 Inset * inset = releaseInset(bibitem_pos);
4310 d->insetlist_.begin()->inset = inset;
4311 // This needs to be done to update the counter (#8499)
4312 buffer.updateBuffer();
4313 return -bibitem_pos;
4316 // We need to create an inset at the beginning
4317 Inset * inset = nullptr;
4318 if (bibitem_pos > 0) {
4319 // there was one somewhere in the paragraph, let's move it
4320 inset = d->insetlist_.release(bibitem_pos);
4321 eraseChar(bibitem_pos, track_changes);
4324 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4325 InsetCommandParams(BIBITEM_CODE));
4327 Font font(inherit_font, buffer.params().language);
4328 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4329 : Change::UNCHANGED));
4331 // This is needed to get the counters right
4332 buffer.updateBuffer();
4337 void Paragraph::checkAuthors(AuthorList const & authorList)
4339 d->changes_.checkAuthors(authorList);
4343 bool Paragraph::isChanged(pos_type pos) const
4345 return lookupChange(pos).changed();
4349 bool Paragraph::isInserted(pos_type pos) const
4351 return lookupChange(pos).inserted();
4355 bool Paragraph::isDeleted(pos_type pos) const
4357 return lookupChange(pos).deleted();
4361 InsetList const & Paragraph::insetList() const
4363 return d->insetlist_;
4367 void Paragraph::setInsetBuffers(Buffer & b)
4369 d->insetlist_.setBuffer(b);
4373 void Paragraph::resetBuffer()
4375 d->insetlist_.resetBuffer();
4379 Inset * Paragraph::releaseInset(pos_type pos)
4381 Inset * inset = d->insetlist_.release(pos);
4382 /// does not honour change tracking!
4383 eraseChar(pos, false);
4388 Inset * Paragraph::getInset(pos_type pos)
4390 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4391 ? d->insetlist_.get(pos) : nullptr;
4395 Inset const * Paragraph::getInset(pos_type pos) const
4397 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4398 ? d->insetlist_.get(pos) : nullptr;
4402 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4403 pos_type & right, TextCase action)
4405 // process sequences of modified characters; in change
4406 // tracking mode, this approach results in much better
4407 // usability than changing case on a char-by-char basis
4408 // We also need to track the current font, since font
4409 // changes within sequences can occur.
4410 vector<pair<char_type, Font> > changes;
4412 bool const trackChanges = bparams.track_changes;
4414 bool capitalize = true;
4416 for (; pos < right; ++pos) {
4417 char_type oldChar = d->text_[pos];
4418 char_type newChar = oldChar;
4420 // ignore insets and don't play with deleted text!
4421 if (oldChar != META_INSET && !isDeleted(pos)) {
4423 case text_lowercase:
4424 newChar = lowercase(oldChar);
4426 case text_capitalization:
4428 newChar = uppercase(oldChar);
4432 case text_uppercase:
4433 newChar = uppercase(oldChar);
4438 if (isWordSeparator(pos) || isDeleted(pos)) {
4439 // permit capitalization again
4443 if (oldChar != newChar) {
4444 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4445 if (pos != right - 1)
4447 // step behind the changing area
4451 int erasePos = pos - changes.size();
4452 for (auto const & change : changes) {
4453 insertChar(pos, change.first, change.second, trackChanges);
4454 if (!eraseChar(erasePos, trackChanges)) {
4457 ++right; // expand selection
4465 int Paragraph::find(docstring const & str, bool cs, bool mw,
4466 pos_type start_pos, bool del) const
4468 pos_type pos = start_pos;
4469 int const strsize = str.length();
4471 pos_type const parsize = d->text_.size();
4472 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4473 // ignore deleted matter
4474 if (!del && isDeleted(pos)) {
4475 if (pos == parsize - 1)
4481 // Ignore "invisible" letters such as ligature breaks
4482 // and hyphenation chars while searching
4483 bool nonmatch = false;
4484 while (pos < parsize && isInset(pos)) {
4485 Inset const * inset = getInset(pos);
4486 if (!inset->isLetter() && !inset->isChar())
4488 odocstringstream os;
4489 inset->toString(os);
4490 if (!os.str().empty()) {
4491 int const insetstringsize = os.str().length();
4492 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4493 if (str[i] != os.str()[j]) {
4501 if (nonmatch || i == strsize)
4503 if (cs && str[i] != d->text_[pos])
4505 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4512 // if necessary, check whether string matches word
4514 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4517 && !isWordSeparator(pos))
4521 return pos - start_pos;
4525 char_type Paragraph::getChar(pos_type pos) const
4527 return d->text_[pos];
4531 pos_type Paragraph::size() const
4533 return d->text_.size();
4537 bool Paragraph::empty() const
4539 return d->text_.empty();
4543 bool Paragraph::isInset(pos_type pos) const
4545 return d->text_[pos] == META_INSET;
4549 bool Paragraph::isSeparator(pos_type pos) const
4551 //FIXME: Are we sure this can be the only separator?
4552 return d->text_[pos] == ' ';
4556 void Paragraph::deregisterWords()
4558 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4559 Private::LangWordsMap::const_iterator ite = d->words_.end();
4560 for (; itl != ite; ++itl) {
4561 WordList & wl = theWordList(itl->first);
4562 Private::Words::const_iterator it = (itl->second).begin();
4563 Private::Words::const_iterator et = (itl->second).end();
4564 for (; it != et; ++it)
4571 void Paragraph::locateWord(pos_type & from, pos_type & to,
4572 word_location const loc, bool const ignore_deleted) const
4575 case WHOLE_WORD_STRICT:
4576 if (from == 0 || from == size()
4577 || isWordSeparator(from, ignore_deleted)
4578 || isWordSeparator(from - 1, ignore_deleted)) {
4585 // If we are already at the beginning of a word, do nothing
4586 if (!from || isWordSeparator(from - 1, ignore_deleted))
4591 // always move the cursor to the beginning of previous word
4592 while (from && !isWordSeparator(from - 1, ignore_deleted))
4596 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4599 // no need to move the 'from' cursor
4603 while (to < size() && !isWordSeparator(to, ignore_deleted))
4608 void Paragraph::collectWords()
4610 for (pos_type pos = 0; pos < size(); ++pos) {
4611 if (isWordSeparator(pos))
4613 pos_type from = pos;
4614 locateWord(from, pos, WHOLE_WORD);
4615 // Work around MSVC warning: The statement
4616 // if (pos < from + lyxrc.completion_minlength)
4617 // triggers a signed vs. unsigned warning.
4618 // I don't know why this happens, it could be a MSVC bug, or
4619 // related to LLP64 (windows) vs. LP64 (unix) programming
4620 // model, or the C++ standard might be ambigous in the section
4621 // defining the "usual arithmetic conversions". However, using
4622 // a temporary variable is safe and works on all compilers.
4623 pos_type const endpos = from + lyxrc.completion_minlength;
4626 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4627 if (cit == d->fontlist_.end())
4629 Language const * lang = cit->font().language();
4630 docstring const word = asString(from, pos, AS_STR_NONE);
4631 d->words_[lang->lang()].insert(word);
4636 void Paragraph::registerWords()
4638 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4639 Private::LangWordsMap::const_iterator ite = d->words_.end();
4640 for (; itl != ite; ++itl) {
4641 WordList & wl = theWordList(itl->first);
4642 Private::Words::const_iterator it = (itl->second).begin();
4643 Private::Words::const_iterator et = (itl->second).end();
4644 for (; it != et; ++it)
4650 void Paragraph::updateWords()
4658 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4660 SkipPositionsIterator begin = skips.begin();
4661 SkipPositions::iterator end = skips.end();
4662 if (pos > 0 && begin < end) {
4664 if (end->last == pos - 1) {
4669 skips.insert(end, FontSpan(pos, pos));
4673 Language * Paragraph::Private::locateSpellRange(
4674 pos_type & from, pos_type & to,
4675 SkipPositions & skips) const
4677 // skip leading white space
4678 while (from < to && owner_->isWordSeparator(from))
4680 // don't check empty range
4683 // get current language
4684 Language * lang = getSpellLanguage(from);
4685 pos_type last = from;
4686 bool samelang = true;
4687 bool sameinset = true;
4688 while (last < to && samelang && sameinset) {
4689 // hop to end of word
4690 while (last < to && !owner_->isWordSeparator(last)) {
4691 Inset const * inset = owner_->getInset(last);
4692 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4693 // check for "invisible" letters such as ligature breaks
4694 odocstringstream os;
4695 inset->toString(os);
4696 if (os.str().length() != 0) {
4697 // avoid spell check of visible special char insets
4698 // stop the loop in front of the special char inset
4703 appendSkipPosition(skips, last);
4704 } else if (owner_->isDeleted(last)) {
4705 appendSkipPosition(skips, last);
4709 // hop to next word while checking for insets
4710 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4711 if (Inset const * inset = owner_->getInset(last))
4712 sameinset = inset->isChar() && inset->isLetter();
4713 if (sameinset && owner_->isDeleted(last)) {
4714 appendSkipPosition(skips, last);
4719 if (sameinset && last < to) {
4720 // now check for language change
4721 samelang = lang == getSpellLanguage(last);
4724 // if language change detected backstep is needed
4732 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4735 const_cast<Language *>(owner_->getFontSettings(
4736 inset_owner_->buffer().params(), from).language());
4737 if (lang == inset_owner_->buffer().params().language
4738 && !lyxrc.spellchecker_alt_lang.empty()) {
4740 string const lang_variety =
4741 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4742 lang->setCode(lang_code);
4743 lang->setVariety(lang_variety);
4749 void Paragraph::requestSpellCheck(pos_type pos)
4751 d->requestSpellCheck(pos);
4755 bool Paragraph::needsSpellCheck() const
4757 SpellChecker::ChangeNumber speller_change_number = 0;
4758 if (theSpellChecker())
4759 speller_change_number = theSpellChecker()->changeNumber();
4760 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4761 d->speller_state_.needsCompleteRefresh(speller_change_number);
4763 return d->needsSpellCheck();
4767 bool Paragraph::Private::ignoreWord(docstring const & word) const
4769 // Ignore words with digits
4770 // FIXME: make this customizable
4771 // (note that some checkers ignore words with digits by default)
4772 docstring::const_iterator cit = word.begin();
4773 docstring::const_iterator const end = word.end();
4774 for (; cit != end; ++cit) {
4775 if (isNumber((*cit)))
4782 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4783 WordLangTuple & wl, docstring_list & suggestions,
4784 bool do_suggestion, bool check_learned) const
4786 SpellChecker::Result result = SpellChecker::WORD_OK;
4787 SpellChecker * speller = theSpellChecker();
4791 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4794 locateWord(from, to, WHOLE_WORD, true);
4795 if (from == to || from >= size())
4798 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4799 Language * lang = d->getSpellLanguage(from);
4801 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4804 wl = WordLangTuple(word, lang);
4809 if (needsSpellCheck() || check_learned) {
4811 if (!d->ignoreWord(word)) {
4812 bool const trailing_dot = to < size() && d->text_[to] == '.';
4813 result = speller->check(wl);
4814 if (SpellChecker::misspelled(result) && trailing_dot) {
4815 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4816 result = speller->check(wl);
4817 if (!SpellChecker::misspelled(result)) {
4818 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4820 from << ".." << to << "]");
4822 // spell check with dot appended failed too
4823 // restore original word/lang value
4824 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4825 wl = WordLangTuple(word, lang);
4829 if (!SpellChecker::misspelled(result)) {
4830 // area up to the begin of the next word is not misspelled
4831 while (end < size() && isWordSeparator(end))
4834 d->setMisspelled(from, end, result);
4836 result = d->speller_state_.getState(from);
4840 suggestions.clear();
4842 if (SpellChecker::misspelled(result)) {
4843 LYXERR(Debug::GUI, "misspelled word: \"" <<
4845 from << ".." << to << "]");
4847 speller->suggest(wl, suggestions);
4853 void Paragraph::anonymize()
4855 // This is a very crude anonymization for now
4856 for (char_type & c : d->text_)
4857 if (isLetterChar(c) || isNumber(c))
4862 void Paragraph::Private::markMisspelledWords(
4863 pos_type const & first, pos_type const & last,
4864 SpellChecker::Result result,
4865 docstring const & word,
4866 SkipPositions const & skips)
4868 if (!SpellChecker::misspelled(result)) {
4869 setMisspelled(first, last, SpellChecker::WORD_OK);
4873 SpellChecker * speller = theSpellChecker();
4874 // locate and enumerate the error positions
4875 int nerrors = speller->numMisspelledWords();
4877 SkipPositionsIterator it = skips.begin();
4878 SkipPositionsIterator et = skips.end();
4879 for (int index = 0; index < nerrors; ++index) {
4882 speller->misspelledWord(index, wstart, wlen);
4883 /// should not happen if speller supports range checks
4884 if (!wlen) continue;
4885 docstring const misspelled = word.substr(wstart, wlen);
4886 wstart += first + numskipped;
4887 if (snext < wstart) {
4888 /// mark the range of correct spelling
4889 numskipped += countSkips(it, et, wstart);
4890 setMisspelled(snext,
4891 wstart - 1, SpellChecker::WORD_OK);
4893 snext = wstart + wlen;
4894 numskipped += countSkips(it, et, snext);
4895 /// mark the range of misspelling
4896 setMisspelled(wstart, snext, result);
4897 LYXERR(Debug::GUI, "misspelled word: \"" <<
4898 misspelled << "\" [" <<
4899 wstart << ".." << (snext-1) << "]");
4902 if (snext <= last) {
4903 /// mark the range of correct spelling at end
4904 setMisspelled(snext, last, SpellChecker::WORD_OK);
4909 void Paragraph::spellCheck() const
4911 SpellChecker * speller = theSpellChecker();
4912 if (!speller || empty() ||!needsSpellCheck())
4916 d->rangeOfSpellCheck(start, endpos);
4917 if (speller->canCheckParagraph()) {
4918 // loop until we leave the range
4919 for (pos_type first = start; first < endpos; ) {
4920 pos_type last = endpos;
4921 Private::SkipPositions skips;
4922 Language * lang = d->locateSpellRange(first, last, skips);
4923 if (first >= endpos)
4925 // start the spell checker on the unit of meaning
4926 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4927 WordLangTuple wl = WordLangTuple(word, lang);
4928 SpellChecker::Result result = !word.empty() ?
4929 speller->check(wl) : SpellChecker::WORD_OK;
4930 d->markMisspelledWords(first, last, result, word, skips);
4934 static docstring_list suggestions;
4935 pos_type to = endpos;
4936 while (start < endpos) {
4938 spellCheck(start, to, wl, suggestions, false);
4942 d->readySpellCheck();
4946 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4948 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4949 if (result || pos <= 0 || pos > size())
4951 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4952 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4957 string Paragraph::magicLabel() const
4960 ss << "magicparlabel-" << id();