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/ExceptionMessage.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/textutils.h"
70 using namespace lyx::support;
72 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
73 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
74 #define THREAD_LOCAL_STATIC static __thread
75 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
76 #define THREAD_LOCAL_STATIC static __declspec(thread)
78 #define THREAD_LOCAL_STATIC thread_local static
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 class SpellResultRange {
91 SpellResultRange(FontSpan range, SpellChecker::Result result)
92 : range_(range), result_(result)
95 FontSpan const & range() const { return range_; }
97 void range(FontSpan const & r) { range_ = r; }
99 SpellChecker::Result result() const { return result_; }
101 void result(SpellChecker::Result r) { result_ = r; }
103 bool contains(pos_type pos) const { return range_.contains(pos); }
105 bool covered(FontSpan const & r) const
107 // 1. first of new range inside current range or
108 // 2. last of new range inside current range or
109 // 3. first of current range inside new range or
110 // 4. last of current range inside new range
111 //FIXME: is this the same as !range_.intersect(r).empty() ?
112 return range_.contains(r.first) || range_.contains(r.last) ||
113 r.contains(range_.first) || r.contains(range_.last);
116 void shift(pos_type pos, int offset)
118 if (range_.first > pos) {
119 range_.first += offset;
120 range_.last += offset;
121 } else if (range_.last >= pos) {
122 range_.last += offset;
127 SpellChecker::Result result_ ;
131 /////////////////////////////////////////////////////////////////////
135 /////////////////////////////////////////////////////////////////////
137 class SpellCheckerState {
141 needs_refresh_ = true;
142 current_change_number_ = 0;
145 void setRange(FontSpan const & fp, SpellChecker::Result state)
148 RangesIterator et = ranges_.end();
149 RangesIterator it = ranges_.begin();
150 for (; it != et; ++it) {
151 if (!it->covered(fp))
152 result.push_back(SpellResultRange(it->range(), it->result()));
153 else if (state == SpellChecker::WORD_OK) {
154 // trim or split the current misspelled range
155 // store misspelled ranges only
156 FontSpan range = it->range();
157 if (fp.first > range.first) {
158 // misspelled area in front of WORD_OK
159 range.last = fp.first - 1;
160 result.push_back(SpellResultRange(range, it->result()));
163 if (fp.last < range.last) {
164 // misspelled area after WORD_OK range
165 range.first = fp.last + 1;
166 result.push_back(SpellResultRange(range, it->result()));
171 if (state != SpellChecker::WORD_OK)
172 ranges_.push_back(SpellResultRange(fp, state));
175 void increasePosAfterPos(pos_type pos)
177 correctRangesAfterPos(pos, 1);
181 void decreasePosAfterPos(pos_type pos)
183 correctRangesAfterPos(pos, -1);
187 void refreshLast(pos_type pos)
189 if (pos < refresh_.last)
193 SpellChecker::Result getState(pos_type pos) const
195 SpellChecker::Result result = SpellChecker::WORD_OK;
196 RangesIterator et = ranges_.end();
197 RangesIterator it = ranges_.begin();
198 for (; it != et; ++it) {
199 if(it->contains(pos)) {
206 FontSpan const & getRange(pos_type pos) const
208 /// empty span to indicate mismatch
209 static FontSpan empty_;
210 RangesIterator et = ranges_.end();
211 RangesIterator it = ranges_.begin();
212 for (; it != et; ++it) {
213 if(it->contains(pos)) {
220 bool needsRefresh() const
222 return needs_refresh_;
225 SpellChecker::ChangeNumber currentChangeNumber() const
227 return current_change_number_;
230 void refreshRange(pos_type & first, pos_type & last) const
232 first = refresh_.first;
233 last = refresh_.last;
236 void needsRefresh(pos_type pos)
238 if (needs_refresh_ && pos != -1) {
239 if (pos < refresh_.first)
240 refresh_.first = pos;
241 if (pos > refresh_.last)
243 } else if (pos != -1) {
244 // init request check for neighbour positions too
245 refresh_.first = pos > 0 ? pos - 1 : 0;
246 // no need for special end of paragraph check
247 refresh_.last = pos + 1;
249 needs_refresh_ = pos != -1;
252 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
254 needs_refresh_ = true;
257 current_change_number_ = change_number;
260 typedef vector<SpellResultRange> Ranges;
261 typedef Ranges::const_iterator RangesIterator;
263 /// the area of the paragraph with pending spell check
265 /// spell state cache version number
266 SpellChecker::ChangeNumber current_change_number_;
270 void correctRangesAfterPos(pos_type pos, int offset)
272 RangesIterator et = ranges_.end();
273 Ranges::iterator it = ranges_.begin();
274 for (; it != et; ++it) {
275 it->shift(pos, offset);
281 /////////////////////////////////////////////////////////////////////
283 // Paragraph::Private
285 /////////////////////////////////////////////////////////////////////
287 class Paragraph::Private
289 // Enforce our own "copy" constructor
290 Private(Private const &) = delete;
291 Private & operator=(Private const &) = delete;
292 // Unique ID generator
293 static int make_id();
296 Private(Paragraph * owner, Layout const & layout);
297 /// "Copy constructor"
298 Private(Private const &, Paragraph * owner);
299 /// Copy constructor from \p beg to \p end
300 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
303 void insertChar(pos_type pos, char_type c, Change const & change);
305 /// Output the surrogate pair formed by \p c and \p next to \p os.
306 /// \return the number of characters written.
307 int latexSurrogatePair(BufferParams const &, otexstream & os,
308 char_type c, char_type next,
309 OutputParams const &);
311 /// Output a space in appropriate formatting (or a surrogate pair
312 /// if the next character is a combining character).
313 /// \return whether a surrogate pair was output.
314 bool simpleTeXBlanks(BufferParams const &,
315 OutputParams const &,
318 unsigned int & column,
320 Layout const & style);
322 /// This could go to ParagraphParameters if we want to.
323 int startTeXParParams(BufferParams const &, otexstream &,
324 OutputParams const &) const;
326 /// This could go to ParagraphParameters if we want to.
327 bool endTeXParParams(BufferParams const &, otexstream &,
328 OutputParams const &) const;
331 void latexInset(BufferParams const &,
336 Font const & outerfont,
338 Change & running_change,
339 Layout const & style,
341 unsigned int & column,
342 bool const fontswitch_inset,
343 bool const closeLanguage,
344 bool const lang_switched_at_inset);
347 void latexSpecialChar(
349 BufferParams const & bparams,
350 OutputParams const & runparams,
351 Font const & running_font,
352 string & alien_script,
353 Layout const & style,
356 unsigned int & column);
363 unsigned int & column) const;
369 unsigned int & column) const;
375 unsigned int & column) const;
378 void validate(LaTeXFeatures & features) const;
380 /// Checks if the paragraph contains only text and no inset or font change.
381 bool onlyText(Buffer const & buf, Font const & outerfont,
382 pos_type initial) const;
384 /// a vector of speller skip positions
385 typedef vector<FontSpan> SkipPositions;
386 typedef SkipPositions::const_iterator SkipPositionsIterator;
388 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
390 Language * getSpellLanguage(pos_type const from) const;
392 Language * locateSpellRange(pos_type & from, pos_type & to,
393 SkipPositions & skips) const;
395 bool hasSpellerChange() const
397 SpellChecker::ChangeNumber speller_change_number = 0;
398 if (theSpellChecker())
399 speller_change_number = theSpellChecker()->changeNumber();
400 return speller_change_number > speller_state_.currentChangeNumber();
403 bool ignoreWord(docstring const & word) const ;
405 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
407 pos_type textsize = owner_->size();
408 // check for sane arguments
409 if (to <= from || from >= textsize)
411 FontSpan fp = FontSpan(from, to - 1);
412 speller_state_.setRange(fp, state);
415 void requestSpellCheck(pos_type pos)
418 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
420 speller_state_.needsRefresh(pos);
423 void readySpellCheck()
425 speller_state_.needsRefresh(-1);
428 bool needsSpellCheck() const
430 return speller_state_.needsRefresh();
433 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
435 speller_state_.refreshRange(first, last);
437 last = owner_->size();
440 pos_type endpos = last;
441 owner_->locateWord(first, endpos, WHOLE_WORD, true);
444 owner_->locateWord(last, endpos, WHOLE_WORD, true);
449 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
453 while (it != et && it->first < start) {
454 long skip = it->last - it->first + 1;
462 void markMisspelledWords(pos_type const & first, pos_type const & last,
463 SpellChecker::Result result,
464 docstring const & word,
465 SkipPositions const & skips);
467 InsetCode ownerCode() const
469 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
472 /// Which Paragraph owns us?
476 Inset const * inset_owner_;
482 ParagraphParameters params_;
484 /// for recording and looking up changes
488 InsetList insetlist_;
491 pos_type begin_of_body_;
493 typedef docstring TextContainer;
497 typedef set<docstring> Words;
498 typedef map<string, Words> LangWordsMap;
502 Layout const * layout_;
504 SpellCheckerState speller_state_;
510 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
511 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
518 int Paragraph::Private::make_id()
520 // The id is unique per session across buffers because it is used in
521 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
524 static int next_id(0);
529 Paragraph::Private::Private(Private const & p, Paragraph * owner)
530 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
531 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
532 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
533 layout_(p.layout_), id_(make_id())
535 requestSpellCheck(p.text_.size());
539 Paragraph::Private::Private(Private const & p, Paragraph * owner,
540 pos_type beg, pos_type end)
541 : owner_(owner), inset_owner_(p.inset_owner_),
542 params_(p.params_), changes_(p.changes_),
543 insetlist_(p.insetlist_, beg, end),
544 begin_of_body_(p.begin_of_body_), words_(p.words_),
545 layout_(p.layout_), id_(make_id())
547 if (beg >= pos_type(p.text_.size()))
549 text_ = p.text_.substr(beg, end - beg);
551 FontList::const_iterator fcit = fontlist_.begin();
552 FontList::const_iterator fend = fontlist_.end();
553 for (; fcit != fend; ++fcit) {
554 if (fcit->pos() < beg)
556 if (fcit->pos() >= end) {
557 // Add last entry in the fontlist_.
558 fontlist_.set(text_.size() - 1, fcit->font());
561 // Add a new entry in the fontlist_.
562 fontlist_.set(fcit->pos() - beg, fcit->font());
564 requestSpellCheck(p.text_.size());
568 /////////////////////////////////////////////////////////////////////
572 /////////////////////////////////////////////////////////////////////
576 /** This helper class should be instantiated at the start of methods
577 * that can create or merge changes. If as a result the value of
578 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
581 struct ChangesMonitor {
583 ChangesMonitor(Paragraph & par)
584 : par_(par), was_changed_(par.isChanged()) {}
588 /* We may need to run updateBuffer to check whether the buffer
589 * contains changes (and toggle the changes toolbar). We do it
591 * 1. the `changedness' of the paragraph has changed,
592 * 2. and we are not in the situation where the buffer has changes
593 * and new changes are added to the paragraph.
596 if (par_.isChanged() != was_changed_
597 && par_.inInset().isBufferValid()
598 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
599 par_.inInset().buffer().forceUpdate();
600 } catch(support::ExceptionMessage const &) {}
605 Paragraph const & par_;
612 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
613 bool output_active, TocBackend & backend) const
615 d->changes_.addToToc(cdit, buf, output_active, backend);
619 bool Paragraph::isDeleted(pos_type start, pos_type end) const
621 LASSERT(start >= 0 && start <= size(), return false);
622 LASSERT(end > start && end <= size() + 1, return false);
624 return d->changes_.isDeleted(start, end);
628 bool Paragraph::isChanged(pos_type start, pos_type end) const
630 LASSERT(start >= 0 && start <= size(), return false);
631 LASSERT(end > start && end <= size() + 1, return false);
633 return d->changes_.isChanged(start, end);
636 // FIXME: Ideally the diverse isChanged() methods should account for that!
637 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
639 LASSERT(start >= 0 && start <= size(), return false);
640 LASSERT(end > start && end <= size() + 1, return false);
642 for (auto const & icit : d->insetlist_) {
643 if (icit.pos < start)
647 if (icit.inset && icit.inset->isChanged())
653 bool Paragraph::isChanged() const
655 return d->changes_.isChanged();
659 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
661 // keep the logic here in sync with the logic of eraseChars()
665 Change const & change = d->changes_.lookup(size());
666 return change.inserted() && change.currentAuthor();
669 Change Paragraph::parEndChange() const
671 return d->changes_.lookup(size());
675 void Paragraph::setChange(Change const & change)
677 // Make sure that Buffer::hasChangesPresent is updated
678 ChangesMonitor cm(*this);
680 // beware of the imaginary end-of-par character!
681 d->changes_.set(change, 0, size() + 1);
684 * Propagate the change recursively - but not in case of DELETED!
686 * Imagine that your co-author makes changes in an existing inset. He
687 * sends your document to you and you come to the conclusion that the
688 * inset should go completely. If you erase it, LyX must not delete all
689 * text within the inset. Otherwise, the change tracked insertions of
690 * your co-author get lost and there is no way to restore them later.
692 * Conclusion: An inset's content should remain untouched if you delete it
695 if (!change.deleted()) {
696 for (pos_type pos = 0; pos < size(); ++pos) {
697 if (Inset * inset = getInset(pos))
698 inset->setChange(change);
704 void Paragraph::setChange(pos_type pos, Change const & change)
706 // Make sure that Buffer::hasChangesPresent is updated
707 ChangesMonitor cm(*this);
709 LASSERT(pos >= 0 && pos <= size(), return);
710 d->changes_.set(change, pos);
712 // see comment in setChange(Change const &) above
713 if (!change.deleted() && pos < size())
714 if (Inset * inset = getInset(pos))
715 inset->setChange(change);
719 Change const & Paragraph::lookupChange(pos_type pos) const
721 LBUFERR(pos >= 0 && pos <= size());
722 return d->changes_.lookup(pos);
726 void Paragraph::acceptChanges(pos_type start, pos_type end)
728 // Make sure that Buffer::hasChangesPresent is updated
729 ChangesMonitor cm(*this);
731 LASSERT(start >= 0 && start <= size(), return);
732 LASSERT(end > start && end <= size() + 1, return);
734 for (pos_type pos = start; pos < end; ++pos) {
735 switch (lookupChange(pos).type) {
736 case Change::UNCHANGED:
737 // accept changes in nested inset
738 if (Inset * inset = getInset(pos))
739 inset->acceptChanges();
742 case Change::INSERTED:
743 d->changes_.set(Change(Change::UNCHANGED), pos);
744 // also accept changes in nested inset
745 if (Inset * inset = getInset(pos))
746 inset->acceptChanges();
749 case Change::DELETED:
750 // Suppress access to non-existent
751 // "end-of-paragraph char"
753 eraseChar(pos, false);
764 void Paragraph::rejectChanges(pos_type start, pos_type end)
766 LASSERT(start >= 0 && start <= size(), return);
767 LASSERT(end > start && end <= size() + 1, return);
769 // Make sure that Buffer::hasChangesPresent is updated
770 ChangesMonitor cm(*this);
772 for (pos_type pos = start; pos < end; ++pos) {
773 switch (lookupChange(pos).type) {
774 case Change::UNCHANGED:
775 // reject changes in nested inset
776 if (Inset * inset = getInset(pos))
777 inset->rejectChanges();
780 case Change::INSERTED:
781 // Suppress access to non-existent
782 // "end-of-paragraph char"
784 eraseChar(pos, false);
790 case Change::DELETED:
791 d->changes_.set(Change(Change::UNCHANGED), pos);
793 // Do NOT reject changes within a deleted inset!
794 // There may be insertions of a co-author inside of it!
802 void Paragraph::Private::insertChar(pos_type pos, char_type c,
803 Change const & change)
805 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
807 // Make sure that Buffer::hasChangesPresent is updated
808 ChangesMonitor cm(*owner_);
811 changes_.insert(change, pos);
813 // This is actually very common when parsing buffers (and
814 // maybe inserting ascii text)
815 if (pos == pos_type(text_.size())) {
816 // when appending characters, no need to update tables
818 // but we want spell checking
819 requestSpellCheck(pos);
823 text_.insert(text_.begin() + pos, c);
825 // Update the font table.
826 fontlist_.increasePosAfterPos(pos);
829 insetlist_.increasePosAfterPos(pos);
831 // Update list of misspelled positions
832 speller_state_.increasePosAfterPos(pos);
836 bool Paragraph::insertInset(pos_type pos, Inset * inset,
837 Font const & font, Change const & change)
839 LASSERT(inset, return false);
840 LASSERT(pos >= 0 && pos <= size(), return false);
842 // Make sure that Buffer::hasChangesPresent is updated
843 ChangesMonitor cm(*this);
845 // Paragraph::insertInset() can be used in cut/copy/paste operation where
846 // d->inset_owner_ is not set yet.
847 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
850 d->insertChar(pos, META_INSET, change);
851 LASSERT(d->text_[pos] == META_INSET, return false);
853 // Add a new entry in the insetlist_.
854 d->insetlist_.insert(inset, pos);
856 // Some insets require run of spell checker
857 requestSpellCheck(pos);
863 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
865 LASSERT(pos >= 0 && pos <= size(), return false);
867 // Make sure that Buffer::hasChangesPresent is updated
868 ChangesMonitor cm(*this);
870 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
873 Change change = d->changes_.lookup(pos);
875 // set the character to DELETED if
876 // a) it was previously unchanged or
877 // b) it was inserted by a co-author
879 if (!change.changed() ||
880 (change.inserted() && !change.currentAuthor())) {
881 setChange(pos, Change(Change::DELETED));
882 // request run of spell checker
883 requestSpellCheck(pos);
887 if (change.deleted())
891 // Don't physically access the imaginary end-of-paragraph character.
892 // eraseChar() can only mark it as DELETED. A physical deletion of
893 // end-of-par must be handled externally.
899 d->changes_.erase(pos);
901 // if it is an inset, delete the inset entry
902 if (d->text_[pos] == META_INSET)
903 d->insetlist_.erase(pos);
905 d->text_.erase(d->text_.begin() + pos);
907 // Update the fontlist_
908 d->fontlist_.erase(pos);
910 // Update the insetlist_
911 d->insetlist_.decreasePosAfterPos(pos);
913 // Update list of misspelled positions
914 d->speller_state_.decreasePosAfterPos(pos);
915 d->speller_state_.refreshLast(size());
921 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
923 LASSERT(start >= 0 && start <= size(), return 0);
924 LASSERT(end >= start && end <= size() + 1, return 0);
927 for (pos_type count = end - start; count; --count) {
928 if (!eraseChar(i, trackChanges))
935 // Handle combining characters
936 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
937 otexstream & os, char_type c, char_type next,
938 OutputParams const & runparams)
940 // Writing next here may circumvent a possible font change between
941 // c and next. Since next is only output if it forms a surrogate pair
942 // with c we can ignore this:
943 // A font change inside a surrogate pair does not make sense and is
944 // hopefully impossible to input.
945 // FIXME: change tracking
946 // Is this correct WRT change tracking?
947 Encoding const & encoding = *(runparams.encoding);
948 docstring latex1 = encoding.latexChar(next).first;
949 if (runparams.inIPA) {
950 string const tipashortcut = Encodings::TIPAShortcut(next);
951 if (!tipashortcut.empty()) {
952 latex1 = from_ascii(tipashortcut);
955 docstring latex2 = encoding.latexChar(c).first;
957 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
958 // Encoding supports the combination:
959 // output as is (combining char after base char).
960 os << latex2 << latex1;
961 return latex1.length() + latex2.length();
964 os << latex1 << "{" << latex2 << "}";
965 return latex1.length() + latex2.length() + 2;
969 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
970 OutputParams const & runparams,
973 unsigned int & column,
975 Layout const & style)
977 if (style.pass_thru || runparams.pass_thru)
980 if (i + 1 < int(text_.size())) {
981 char_type next = text_[i + 1];
982 if (Encodings::isCombiningChar(next)) {
983 // This space has an accent, so we must always output it.
984 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
989 if (runparams.linelen > 0
990 && column > runparams.linelen
992 && text_[i - 1] != ' '
993 && (i + 1 < int(text_.size()))
994 // same in FreeSpacing mode
995 && !owner_->isFreeSpacing()
996 // In typewriter mode, we want to avoid
997 // ! . ? : at the end of a line
998 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
999 && (text_[i - 1] == '.'
1000 || text_[i - 1] == '?'
1001 || text_[i - 1] == ':'
1002 || text_[i - 1] == '!'))) {
1004 os.texrow().start(owner_->id(), i + 1);
1006 } else if (style.free_spacing) {
1015 void Paragraph::Private::latexInset(BufferParams const & bparams,
1017 OutputParams & runparams,
1018 Font & running_font,
1020 Font const & outerfont,
1022 Change & running_change,
1023 Layout const & style,
1025 unsigned int & column,
1026 bool const fontswitch_inset,
1027 bool const closeLanguage,
1028 bool const lang_switched_at_inset)
1030 Inset * inset = owner_->getInset(i);
1033 if (style.pass_thru) {
1034 odocstringstream ods;
1035 inset->plaintext(ods, runparams);
1040 // FIXME: move this to InsetNewline::latex
1041 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1042 // newlines are handled differently here than
1043 // the default in simpleTeXSpecialChars().
1044 if (!style.newline_allowed) {
1048 bool needPar = false;
1049 column += running_font.latexWriteEndChanges(
1050 os, bparams, runparams,
1051 basefont, basefont, needPar);
1055 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1058 basefont = owner_->getLayoutFont(bparams, outerfont);
1059 running_font = basefont;
1061 if (runparams.moving_arg)
1065 os.texrow().start(owner_->id(), i + 1);
1069 if (owner_->isDeleted(i)) {
1070 if( ++runparams.inDeletedInset == 1)
1071 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1074 if (inset->canTrackChanges()) {
1075 column += Changes::latexMarkChange(os, bparams, running_change,
1076 Change(Change::UNCHANGED), runparams);
1077 running_change = Change(Change::UNCHANGED);
1081 odocstream::pos_type const len = os.os().tellp();
1083 if (inset->forceLTR(runparams)
1084 && running_font.isRightToLeft()
1085 // ERT is an exception, it should be output with no
1086 // decorations at all
1087 && inset->lyxCode() != ERT_CODE) {
1088 if (runparams.use_polyglossia) {
1090 } else if (running_font.language()->lang() == "farsi"
1091 || running_font.language()->lang() == "arabic_arabi")
1092 os << "\\textLR{" << termcmd;
1098 if (open_font && fontswitch_inset) {
1099 bool lang_closed = false;
1100 // Close language if needed
1101 if (closeLanguage && !lang_switched_at_inset) {
1102 // We need prev_font here as language changes directly at inset
1103 // will only be started inside the inset.
1104 Font const prev_font = (i > 0) ?
1105 owner_->getFont(bparams, i - 1, outerfont)
1107 Font tmpfont(basefont);
1108 tmpfont.setLanguage(prev_font.language());
1109 bool needPar = false;
1110 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1112 needPar, closeLanguage);
1114 lang_closed = count > 0;
1116 // Update the running_font, making sure, however,
1117 // to leave the language as it was.
1118 // FIXME: probably a better way to keep track of the old
1119 // language, than copying the entire font?
1120 Font const copy_font(running_font);
1121 basefont = owner_->getLayoutFont(bparams, outerfont);
1122 running_font = basefont;
1124 running_font.setLanguage(copy_font.language());
1125 OutputParams rp = runparams;
1126 rp.encoding = basefont.language()->encoding();
1127 // For these, we use switches, so they should be taken as
1128 // base inside the inset.
1129 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1130 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1131 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1132 // Now re-do font changes in a way needed here
1133 // (using switches with multi-par insets)
1134 InsetText const * textinset = inset->asInsetText();
1135 bool const cprotect = textinset
1136 ? textinset->hasCProtectContent(runparams.moving_arg)
1137 && !textinset->text().isMainText()
1139 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1145 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1149 runparams.local_font = &basefont;
1152 if (fontswitch_inset && !closeLanguage) {
1153 // The directionality has been switched at inset.
1154 // Force markup inside.
1155 runparams.local_font = &basefont;
1158 size_t const previous_row_count = os.texrow().rows();
1161 runparams.lastid = id_;
1162 runparams.lastpos = i;
1163 inset->latex(os, runparams);
1164 } catch (EncodingException & e) {
1165 // add location information and throw again.
1174 if (os.texrow().rows() > previous_row_count) {
1175 os.texrow().start(owner_->id(), i + 1);
1178 column += (unsigned int)(os.os().tellp() - len);
1181 if (owner_->isDeleted(i))
1182 --runparams.inDeletedInset;
1186 void Paragraph::Private::latexSpecialChar(otexstream & os,
1187 BufferParams const & bparams,
1188 OutputParams const & runparams,
1189 Font const & running_font,
1190 string & alien_script,
1191 Layout const & style,
1194 unsigned int & column)
1196 char_type const c = owner_->getUChar(bparams, runparams, i);
1198 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1199 || contains(style.pass_thru_chars, c)
1200 || contains(runparams.pass_thru_chars, c)) {
1201 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1205 os << "\\braceleft ";
1207 os << "\\braceright ";
1211 else if (c != '\0') {
1212 Encoding const * const enc = runparams.encoding;
1213 if (enc && !enc->encodable(c))
1214 throw EncodingException(c);
1220 // TIPA uses its own T3 encoding
1221 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1223 // If T1 font encoding is used, use the special
1224 // characters it provides.
1225 // NOTE: Some languages reset the font encoding internally to a
1226 // non-standard font encoding. If we are using such a language,
1227 // we do not output special T1 chars.
1228 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1229 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1230 && latexSpecialT1(c, os, i, column))
1232 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1233 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1234 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1237 // Otherwise, we use what LaTeX provides us.
1240 os << "\\textbackslash" << termcmd;
1244 os << "\\textless" << termcmd;
1248 os << "\\textgreater" << termcmd;
1252 os << "\\textbar" << termcmd;
1257 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1258 (end_pos == -1 || i + 1 < end_pos) &&
1259 text_[i+1] == '-') {
1260 // Prevent "--" becoming an en dash and "---" an em dash.
1261 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1267 os << "\\textquotedbl" << termcmd;
1272 case '%': case '#': case '{':
1280 os << "\\textasciitilde" << termcmd;
1285 os << "\\textasciicircum" << termcmd;
1292 // avoid being mistaken for optional arguments
1300 // Blanks are printed before font switching.
1301 // Sure? I am not! (try nice-latex)
1302 // I am sure it's correct. LyX might be smarter
1303 // in the future, but for now, nothing wrong is
1309 // XeTeX's dash behaviour is determined via a global setting
1310 if (bparams.use_dash_ligatures
1311 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1313 // TODO #10961: && not in inset Flex Code
1314 // TODO #10961: && not in layout LyXCode
1315 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1332 Encoding const & encoding = *(runparams.encoding);
1333 char_type next = '\0';
1334 if (i + 1 < int(text_.size())) {
1335 next = text_[i + 1];
1336 if (Encodings::isCombiningChar(next)) {
1337 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1342 pair<docstring, bool> latex = encoding.latexChar(c);
1343 docstring nextlatex;
1344 bool nexttipas = false;
1345 string nexttipashortcut;
1346 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1347 nextlatex = encoding.latexChar(next).first;
1348 if (runparams.inIPA) {
1349 nexttipashortcut = Encodings::TIPAShortcut(next);
1350 nexttipas = !nexttipashortcut.empty();
1354 if (runparams.inIPA) {
1355 string const tipashortcut = Encodings::TIPAShortcut(c);
1356 if (!tipashortcut.empty()) {
1357 latex.first = from_ascii(tipashortcut);
1358 latex.second = false;
1362 // eventually close "script wrapper" command (see `Paragraph::latex`)
1363 if (!alien_script.empty()
1364 && alien_script != Encodings::isKnownScriptChar(next)) {
1365 column += latex.first.length();
1366 alien_script.clear();
1367 os << latex.first << "}";
1371 && ((!prefixIs(nextlatex, '\\')
1372 && !prefixIs(nextlatex, '{')
1373 && !prefixIs(nextlatex, '}'))
1375 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1377 // Prevent eating of a following space or command corruption by
1378 // following characters
1379 if (next == ' ' || next == '\0') {
1380 column += latex.first.length() + 1;
1381 os << latex.first << "{}";
1383 column += latex.first.length();
1384 os << latex.first << " ";
1387 column += latex.first.length() - 1;
1395 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1396 pos_type i, unsigned int & column) const
1402 // In T1 encoding, these characters exist
1403 // but we should avoid ligatures
1404 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1406 os << "\\textcompwordmark" << termcmd;
1413 // soul.sty breaks with \char`\"
1414 os << "\\textquotedbl" << termcmd;
1423 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1424 pos_type i, unsigned int & column) const
1426 // TU encoding is currently on par with T1.
1427 return latexSpecialT1(c, os, i, column);
1431 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1432 pos_type /*i*/, unsigned int & column) const
1442 os << "\\textvertline" << termcmd;
1451 void Paragraph::Private::validate(LaTeXFeatures & features) const
1453 if (layout_->inpreamble && inset_owner_) {
1454 // FIXME: Using a string stream here circumvents the encoding
1455 // switching machinery of odocstream. Therefore the
1456 // output is wrong if this paragraph contains content
1457 // that needs to switch encoding.
1458 Buffer const & buf = inset_owner_->buffer();
1459 otexstringstream os;
1460 os << layout_->preamble();
1461 size_t const length = os.length();
1462 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1463 buf.getParFromID(owner_->id()).pit(), os,
1464 features.runparams(), string(), 0, -1, true);
1465 if (os.length() > length)
1466 features.addPreambleSnippet(os.release(), true);
1469 if (features.runparams().flavor == Flavor::Html
1470 && layout_->htmltitle()) {
1471 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1474 // check the params.
1475 if (!params_.spacing().isDefault())
1476 features.require("setspace");
1479 features.useLayout(layout_->name());
1482 fontlist_.validate(features);
1484 // then the indentation
1485 if (!params_.leftIndent().zero())
1486 features.require("ParagraphLeftIndent");
1489 InsetList::const_iterator icit = insetlist_.begin();
1490 InsetList::const_iterator iend = insetlist_.end();
1491 for (; icit != iend; ++icit) {
1493 features.inDeletedInset(owner_->isDeleted(icit->pos));
1494 if (icit->inset->lyxCode() == FOOT_CODE) {
1495 // FIXME: an item inset would make things much easier.
1496 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1497 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1498 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1499 && (icit->pos < begin_of_body_
1500 || (icit->pos == begin_of_body_
1501 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1502 features.saveNoteEnv("description");
1504 icit->inset->validate(features);
1505 features.inDeletedInset(false);
1506 if (layout_->needprotect &&
1507 icit->inset->lyxCode() == FOOT_CODE)
1508 features.require("NeedLyXFootnoteCode");
1512 // then the contents
1513 BufferParams const bp = features.runparams().is_child
1514 ? features.buffer().masterParams() : features.buffer().params();
1515 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1516 char_type c = text_[i];
1517 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1519 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1520 features.require("textquotedblp");
1521 else if (bp.main_font_encoding() != "T1"
1522 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1523 features.require("textquotedbl");
1524 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1525 // features that depend on the font or input encoding
1526 string feats = ci.textpreamble();
1527 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1528 if (fontenc.empty())
1529 fontenc = features.runparams().main_fontenc;
1530 while (!feats.empty()) {
1532 feats = split(feats, feat, ',');
1533 if (contains(feat, "!=")) {
1534 // a feature that is required except for the spcified
1535 // font or input encodings
1537 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1538 // multiple encodings are separated by semicolon
1539 vector<string> context = getVectorFromString(contexts, ";");
1540 // require feature if the context matches neither current font
1541 // nor input encoding
1542 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1543 && std::find(context.begin(), context.end(),
1544 features.runparams().encoding->name()) == context.end())
1545 features.require(realfeature);
1546 } else if (contains(feat, '=')) {
1547 // a feature that is required only for the spcified
1548 // font or input encodings
1550 string const contexts = split(feat, realfeature, '=');
1551 // multiple encodings are separated by semicolon
1552 vector<string> context = getVectorFromString(contexts, ";");
1553 // require feature if the context matches either current font
1554 // or input encoding
1555 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1556 || std::find(context.begin(), context.end(),
1557 features.runparams().encoding->name()) != context.end())
1558 features.require(realfeature);
1561 } else if (!bp.use_dash_ligatures
1562 && (c == 0x2013 || c == 0x2014)
1563 && bp.useNonTeXFonts
1564 && features.runparams().flavor == Flavor::XeTeX)
1565 // XeTeX's dash behaviour is determined via a global setting
1566 features.require("xetexdashbreakstate");
1567 BufferEncodings::validate(c, features);
1571 /////////////////////////////////////////////////////////////////////
1575 /////////////////////////////////////////////////////////////////////
1578 Layout const emptyParagraphLayout;
1581 Paragraph::Paragraph()
1582 : d(new Paragraph::Private(this, emptyParagraphLayout))
1589 Paragraph::Paragraph(Paragraph const & par)
1590 : itemdepth(par.itemdepth),
1591 d(new Paragraph::Private(*par.d, this))
1597 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1598 : itemdepth(par.itemdepth),
1599 d(new Paragraph::Private(*par.d, this, beg, end))
1605 Paragraph & Paragraph::operator=(Paragraph const & par)
1607 // needed as we will destroy the private part before copying it
1609 itemdepth = par.itemdepth;
1613 d = new Private(*par.d, this);
1620 Paragraph::~Paragraph()
1629 // this shall be called just before every "os << ..." action.
1630 void flushString(ostream & os, docstring & s)
1639 void Paragraph::write(ostream & os, BufferParams const & bparams,
1640 depth_type & depth) const
1642 // The beginning or end of a deeper (i.e. nested) area?
1643 if (depth != d->params_.depth()) {
1644 if (d->params_.depth() > depth) {
1645 while (d->params_.depth() > depth) {
1646 os << "\n\\begin_deeper";
1650 while (d->params_.depth() < depth) {
1651 os << "\n\\end_deeper";
1657 // First write the layout
1658 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1660 d->params_.write(os);
1662 Font font1(inherit_font, bparams.language);
1664 Change running_change = Change(Change::UNCHANGED);
1666 // this string is used as a buffer to avoid repetitive calls
1667 // to to_utf8(), which turn out to be expensive (JMarc)
1668 docstring write_buffer;
1671 for (pos_type i = 0; i <= size(); ++i) {
1673 Change const & change = lookupChange(i);
1674 if (change != running_change)
1675 flushString(os, write_buffer);
1676 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1677 running_change = change;
1682 // Write font changes
1683 Font font2 = getFontSettings(bparams, i);
1684 if (font2 != font1) {
1685 flushString(os, write_buffer);
1686 font2.lyxWriteChanges(font1, os);
1691 char_type const c = d->text_[i];
1694 if (Inset const * inset = getInset(i)) {
1695 flushString(os, write_buffer);
1696 if (inset->directWrite()) {
1697 // international char, let it write
1698 // code directly so it's shorter in
1704 os << "\\begin_inset ";
1706 os << "\n\\end_inset\n\n";
1709 // FIXME This can be removed again once the mystery
1710 // crash has been resolved.
1715 flushString(os, write_buffer);
1716 os << "\n\\backslash\n";
1720 flushString(os, write_buffer);
1721 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1728 if ((column > 70 && c == ' ')
1730 flushString(os, write_buffer);
1734 // this check is to amend a bug. LyX sometimes
1735 // inserts '\0' this could cause problems.
1737 write_buffer.push_back(c);
1739 LYXERR0("NUL char in structure.");
1745 flushString(os, write_buffer);
1746 os << "\n\\end_layout\n";
1747 // FIXME This can be removed again once the mystery
1748 // crash has been resolved.
1753 void Paragraph::validate(LaTeXFeatures & features) const
1755 d->validate(features);
1756 bool fragile = features.runparams().moving_arg;
1757 fragile |= layout().needprotect;
1758 if (inInset().getLayout().isNeedProtect())
1760 if (needsCProtection(fragile))
1761 features.require("cprotect");
1765 void Paragraph::insert(pos_type pos, docstring const & str,
1766 Font const & font, Change const & change)
1768 for (size_t i = 0, n = str.size(); i != n ; ++i)
1769 insertChar(pos + i, str[i], font, change);
1773 void Paragraph::appendChar(char_type c, Font const & font,
1774 Change const & change)
1776 // Make sure that Buffer::hasChangesPresent is updated
1777 ChangesMonitor cm(*this);
1780 d->changes_.insert(change, d->text_.size());
1781 // when appending characters, no need to update tables
1782 d->text_.push_back(c);
1783 setFont(d->text_.size() - 1, font);
1784 d->requestSpellCheck(d->text_.size() - 1);
1788 void Paragraph::appendString(docstring const & s, Font const & font,
1789 Change const & change)
1791 // Make sure that Buffer::hasChangesPresent is updated
1792 ChangesMonitor cm(*this);
1794 pos_type end = s.size();
1795 size_t oldsize = d->text_.size();
1796 size_t newsize = oldsize + end;
1797 size_t capacity = d->text_.capacity();
1798 if (newsize >= capacity)
1799 d->text_.reserve(max(capacity + 100, newsize));
1801 // when appending characters, no need to update tables
1804 // FIXME: Optimize this!
1805 for (size_t i = oldsize; i != newsize; ++i) {
1807 d->changes_.insert(change, i);
1808 d->requestSpellCheck(i);
1810 d->fontlist_.set(oldsize, font);
1811 d->fontlist_.set(newsize - 1, font);
1815 void Paragraph::insertChar(pos_type pos, char_type c,
1818 d->insertChar(pos, c, Change(trackChanges ?
1819 Change::INSERTED : Change::UNCHANGED));
1823 void Paragraph::insertChar(pos_type pos, char_type c,
1824 Font const & font, bool trackChanges)
1826 d->insertChar(pos, c, Change(trackChanges ?
1827 Change::INSERTED : Change::UNCHANGED));
1832 void Paragraph::insertChar(pos_type pos, char_type c,
1833 Font const & font, Change const & change)
1835 d->insertChar(pos, c, change);
1840 void Paragraph::resetFonts(Font const & font)
1842 d->fontlist_.clear();
1843 d->fontlist_.set(0, font);
1844 d->fontlist_.set(d->text_.size() - 1, font);
1847 // Gets uninstantiated font setting at position.
1848 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1852 LYXERR0("pos: " << pos << " size: " << size());
1856 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1857 if (cit != d->fontlist_.end())
1860 if (pos == size() && !empty())
1861 return getFontSettings(bparams, pos - 1);
1863 // Optimisation: avoid a full font instantiation if there is no
1864 // language change from previous call.
1865 static Font previous_font;
1866 static Language const * previous_lang = nullptr;
1867 Language const * lang = getParLanguage(bparams);
1868 if (lang != previous_lang) {
1869 previous_lang = lang;
1870 previous_font = Font(inherit_font, lang);
1872 return previous_font;
1876 FontSpan Paragraph::fontSpan(pos_type pos) const
1878 LBUFERR(pos <= size());
1881 return FontSpan(pos, pos);
1884 FontList::const_iterator cit = d->fontlist_.begin();
1885 FontList::const_iterator end = d->fontlist_.end();
1886 for (; cit != end; ++cit) {
1887 if (cit->pos() >= pos) {
1888 if (pos >= beginOfBody())
1889 return FontSpan(max(start, beginOfBody()),
1892 return FontSpan(start,
1893 min(beginOfBody() - 1,
1896 start = cit->pos() + 1;
1899 // This should not happen, but if so, we take no chances.
1900 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1901 LASSERT(false, return FontSpan(pos, pos));
1905 // Gets uninstantiated font setting at position 0
1906 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1908 if (!empty() && !d->fontlist_.empty())
1909 return d->fontlist_.begin()->font();
1911 // Optimisation: avoid a full font instantiation if there is no
1912 // language change from previous call.
1913 static Font previous_font;
1914 static Language const * previous_lang = nullptr;
1915 if (bparams.language != previous_lang) {
1916 previous_lang = bparams.language;
1917 previous_font = Font(inherit_font, bparams.language);
1920 return previous_font;
1924 // Gets the fully instantiated font at a given position in a paragraph
1925 // This is basically the same function as Text::GetFont() in text2.cpp.
1926 // The difference is that this one is used for generating the LaTeX file,
1927 // and thus cosmetic "improvements" are disallowed: This has to deliver
1928 // the true picture of the buffer. (Asger)
1929 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1930 Font const & outerfont) const
1934 Font font = getFontSettings(bparams, pos);
1936 pos_type const body_pos = beginOfBody();
1937 FontInfo & fi = font.fontInfo();
1939 fi.realize(d->layout_->labelfont);
1941 fi.realize(d->layout_->font);
1943 fi.realize(outerfont.fontInfo());
1944 fi.realize(bparams.getFont().fontInfo());
1950 Font const Paragraph::getLabelFont
1951 (BufferParams const & bparams, Font const & outerfont) const
1953 FontInfo tmpfont = d->layout_->labelfont;
1954 tmpfont.realize(outerfont.fontInfo());
1955 tmpfont.realize(bparams.getFont().fontInfo());
1956 return Font(tmpfont, getParLanguage(bparams));
1960 Font const Paragraph::getLayoutFont
1961 (BufferParams const & bparams, Font const & outerfont) const
1963 FontInfo tmpfont = d->layout_->font;
1964 tmpfont.realize(outerfont.fontInfo());
1965 tmpfont.realize(bparams.getFont().fontInfo());
1966 return Font(tmpfont, getParLanguage(bparams));
1970 char_type Paragraph::getUChar(BufferParams const & bparams,
1971 OutputParams const & rp,
1974 char_type c = d->text_[pos];
1976 // Return unchanged character in LTR languages
1977 // or if we use poylglossia/bidi (XeTeX).
1978 if (rp.useBidiPackage()
1979 || !getFontSettings(bparams, pos).isRightToLeft())
1982 // Without polyglossia/bidi, we need to account for some special cases.
1983 // FIXME This needs to be audited!
1985 // * The input is as expected for all delimiters
1986 // => checked for Hebrew!
1987 // * The output matches the display in the LyX workarea
1988 // => checked for Hebrew!
1989 // * The special cases below are really necessary
1990 // => checked for Hebrew!
1991 // * In arabic_arabi, brackets are transformed to Arabic
1992 // Ornate Parentheses. Is this is really wanted?
1994 string const & lang = getFontSettings(bparams, pos).language()->lang();
1997 // 1. In the following languages, parentheses need to be reversed.
1998 // Also with polyglodia/luabidi
1999 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2001 // 2. In the following languages, brackets don't need to be reversed.
2002 bool const reversebrackets = lang != "arabic_arabtex"
2003 && lang != "arabic_arabi"
2006 // Now swap delimiters if needed.
2017 if (reversebrackets)
2021 if (reversebrackets)
2042 void Paragraph::setFont(pos_type pos, Font const & font)
2044 LASSERT(pos <= size(), return);
2046 // First, reduce font against layout/label font
2047 // Update: The setCharFont() routine in text2.cpp already
2048 // reduces font, so we don't need to do that here. (Asger)
2050 d->fontlist_.set(pos, font);
2054 void Paragraph::makeSameLayout(Paragraph const & par)
2056 d->layout_ = par.d->layout_;
2057 d->params_ = par.d->params_;
2061 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2063 if (isFreeSpacing())
2069 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2070 if (eraseChar(pos, trackChanges))
2076 return count > 0 || pos > 0;
2080 bool Paragraph::hasSameLayout(Paragraph const & par) const
2082 return par.d->layout_ == d->layout_
2083 && d->params_.sameLayout(par.d->params_);
2087 depth_type Paragraph::getDepth() const
2089 return d->params_.depth();
2093 depth_type Paragraph::getMaxDepthAfter() const
2095 if (d->layout_->isEnvironment())
2096 return d->params_.depth() + 1;
2098 return d->params_.depth();
2102 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2104 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2105 return getDefaultAlign(bparams);
2107 return d->params_.align();
2111 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2113 LyXAlignment res = layout().align;
2114 if (isRTL(bparams)) {
2116 if (res == LYX_ALIGN_LEFT)
2117 res = LYX_ALIGN_RIGHT;
2118 else if (res == LYX_ALIGN_RIGHT)
2119 res = LYX_ALIGN_LEFT;
2125 docstring const & Paragraph::labelString() const
2127 return d->params_.labelString();
2131 // the next two functions are for the manual labels
2132 docstring const Paragraph::getLabelWidthString() const
2134 if (d->layout_->margintype == MARGIN_MANUAL
2135 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2136 return d->params_.labelWidthString();
2138 return _("Senseless with this layout!");
2142 void Paragraph::setLabelWidthString(docstring const & s)
2144 d->params_.labelWidthString(s);
2148 docstring Paragraph::expandLabel(Layout const & layout,
2149 BufferParams const & bparams) const
2151 return expandParagraphLabel(layout, bparams, true);
2155 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2156 BufferParams const & bparams, bool process_appendix) const
2158 DocumentClass const & tclass = bparams.documentClass();
2159 string const & lang = getParLanguage(bparams)->code();
2160 bool const in_appendix = process_appendix && d->params_.appendix();
2161 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2163 if (fmt.empty() && !layout.counter.empty())
2164 return tclass.counters().theCounter(layout.counter, lang);
2166 // handle 'inherited level parts' in 'fmt',
2167 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2168 size_t const i = fmt.find('@', 0);
2169 if (i != docstring::npos) {
2170 size_t const j = fmt.find('@', i + 1);
2171 if (j != docstring::npos) {
2172 docstring parent(fmt, i + 1, j - i - 1);
2173 docstring label = from_ascii("??");
2174 if (tclass.hasLayout(parent))
2175 label = expandParagraphLabel(tclass[parent], bparams,
2177 fmt = docstring(fmt, 0, i) + label
2178 + docstring(fmt, j + 1, docstring::npos);
2182 return tclass.counters().counterLabel(fmt, lang);
2186 void Paragraph::applyLayout(Layout const & new_layout)
2188 d->layout_ = &new_layout;
2189 LyXAlignment const oldAlign = d->params_.align();
2191 if (!(oldAlign & d->layout_->alignpossible)) {
2192 frontend::Alert::warning(_("Alignment not permitted"),
2193 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2194 d->params_.align(LYX_ALIGN_LAYOUT);
2199 pos_type Paragraph::beginOfBody() const
2201 return d->begin_of_body_;
2205 void Paragraph::setBeginOfBody()
2207 if (d->layout_->labeltype != LABEL_MANUAL) {
2208 d->begin_of_body_ = 0;
2212 // Unroll the first two cycles of the loop
2213 // and remember the previous character to
2214 // remove unnecessary getChar() calls
2216 pos_type end = size();
2217 bool prev_char_deleted = false;
2218 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2221 char_type previous_char = d->text_[i];
2222 if (!(isNewline(i) || isEnvSeparator(i))) {
2224 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2225 char_type temp = d->text_[i];
2226 prev_char_deleted = isDeleted(i);
2227 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2230 previous_char = temp;
2236 d->begin_of_body_ = i;
2240 bool Paragraph::allowParagraphCustomization() const
2242 return inInset().allowParagraphCustomization();
2246 bool Paragraph::usePlainLayout() const
2248 return inInset().usePlainLayout();
2252 bool Paragraph::isPassThru() const
2254 return inInset().isPassThru() || d->layout_->pass_thru;
2259 // paragraphs inside floats need different alignment tags to avoid
2262 bool noTrivlistCentering(InsetCode code)
2264 return code == FLOAT_CODE
2265 || code == WRAP_CODE
2266 || code == CELL_CODE;
2270 string correction(string const & orig)
2272 if (orig == "flushleft")
2273 return "raggedright";
2274 if (orig == "flushright")
2275 return "raggedleft";
2276 if (orig == "center")
2282 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2283 InsetCode code, bool const lastpar, int & col)
2285 string macro = suffix + "{";
2286 if (noTrivlistCentering(code)) {
2288 // the last paragraph in non-trivlist-aligned
2289 // context is special (to avoid unwanted whitespace)
2290 if (suffix == "\\begin") {
2291 macro = "\\" + correction(env) + "{}";
2292 os << from_ascii(macro);
2293 col += macro.size();
2298 macro += correction(env);
2302 if (suffix == "\\par\\end") {
2306 os << from_ascii(macro);
2307 col += macro.size();
2308 if (suffix == "\\begin") {
2318 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2319 otexstream & os, OutputParams const & runparams) const
2324 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2325 (layout_->toggle_indent != ITOGGLE_NEVER) :
2326 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2328 if (canindent && params_.noindent() && !layout_->pass_thru) {
2329 os << "\\noindent ";
2333 LyXAlignment const curAlign = params_.align();
2335 if (curAlign == layout_->align)
2339 case LYX_ALIGN_NONE:
2340 case LYX_ALIGN_BLOCK:
2341 case LYX_ALIGN_LAYOUT:
2342 case LYX_ALIGN_SPECIAL:
2343 case LYX_ALIGN_DECIMAL:
2345 case LYX_ALIGN_LEFT:
2346 case LYX_ALIGN_RIGHT:
2347 case LYX_ALIGN_CENTER:
2348 if (runparams.moving_arg) {
2355 string const begin_tag = "\\begin";
2356 InsetCode code = ownerCode();
2357 bool const lastpar = runparams.isLastPar;
2358 // RTL in classic (PDF)LaTeX (without the Bidi package)
2359 // Luabibdi (used by LuaTeX) behaves like classic
2360 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2361 && !runparams.useBidiPackage();
2364 case LYX_ALIGN_NONE:
2365 case LYX_ALIGN_BLOCK:
2366 case LYX_ALIGN_LAYOUT:
2367 case LYX_ALIGN_SPECIAL:
2368 case LYX_ALIGN_DECIMAL:
2370 case LYX_ALIGN_LEFT: {
2372 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2373 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2375 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2377 } case LYX_ALIGN_RIGHT: {
2379 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2380 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2382 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2384 } case LYX_ALIGN_CENTER: {
2385 corrected_env(os, begin_tag, "center", code, lastpar, column);
2394 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2395 otexstream & os, OutputParams const & runparams) const
2397 LyXAlignment const curAlign = params_.align();
2399 if (curAlign == layout_->align)
2403 case LYX_ALIGN_NONE:
2404 case LYX_ALIGN_BLOCK:
2405 case LYX_ALIGN_LAYOUT:
2406 case LYX_ALIGN_SPECIAL:
2407 case LYX_ALIGN_DECIMAL:
2409 case LYX_ALIGN_LEFT:
2410 case LYX_ALIGN_RIGHT:
2411 case LYX_ALIGN_CENTER:
2412 if (runparams.moving_arg)
2417 bool output = false;
2419 string const end_tag = "\\par\\end";
2420 InsetCode code = ownerCode();
2421 bool const lastpar = runparams.isLastPar;
2422 // RTL in classic (PDF)LaTeX (without the Bidi package)
2423 // Luabibdi (used by LuaTeX) behaves like classic
2424 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2425 && !runparams.useBidiPackage();
2428 case LYX_ALIGN_NONE:
2429 case LYX_ALIGN_BLOCK:
2430 case LYX_ALIGN_LAYOUT:
2431 case LYX_ALIGN_SPECIAL:
2432 case LYX_ALIGN_DECIMAL:
2434 case LYX_ALIGN_LEFT: {
2436 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2437 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2439 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2441 } case LYX_ALIGN_RIGHT: {
2443 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2444 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2446 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2448 } case LYX_ALIGN_CENTER: {
2449 corrected_env(os, end_tag, "center", code, lastpar, col);
2454 return output || lastpar;
2458 // This one spits out the text of the paragraph
2459 void Paragraph::latex(BufferParams const & bparams,
2460 Font const & outerfont,
2462 OutputParams const & runparams,
2463 int start_pos, int end_pos, bool force) const
2465 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2467 // FIXME This check should not be needed. Perhaps issue an
2468 // error if it triggers.
2469 Layout const & style = inInset().forcePlainLayout() ?
2470 bparams.documentClass().plainLayout() : *d->layout_;
2472 if (!force && style.inpreamble)
2475 bool const allowcust = allowParagraphCustomization();
2477 // Current base font for all inherited font changes, without any
2478 // change caused by an individual character, except for the language:
2479 // It is set to the language of the first character.
2480 // As long as we are in the label, this font is the base font of the
2481 // label. Before the first body character it is set to the base font
2485 // If there is an open font-encoding changing command (script wrapper),
2486 // alien_script is set to its name
2487 string alien_script;
2490 // Maybe we have to create a optional argument.
2491 pos_type body_pos = beginOfBody();
2492 unsigned int column = 0;
2494 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2495 Font const real_outerfont = (!inInset().inheritFont()
2496 && runparams.local_font != nullptr)
2497 ? Font(runparams.local_font->fontInfo()) : outerfont;
2500 // the optional argument is kept in curly brackets in
2501 // case it contains a ']'
2502 // This is not strictly needed, but if this is changed it
2503 // would be a file format change, and tex2lyx would need
2504 // to be adjusted, since it unconditionally removes the
2505 // braces when it parses \item.
2508 basefont = getLabelFont(bparams, real_outerfont);
2510 basefont = getLayoutFont(bparams, real_outerfont);
2513 // Which font is currently active?
2514 Font running_font(basefont);
2515 // Do we have an open font change?
2516 bool open_font = false;
2518 Change runningChange =
2519 runparams.inDeletedInset && !inInset().canTrackChanges()
2520 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2522 Encoding const * const prev_encoding = runparams.encoding;
2524 os.texrow().start(id(), 0);
2526 // if the paragraph is empty, the loop will not be entered at all
2528 // For InTitle commands, we have already opened a group
2529 // in output_latex::TeXOnePar.
2530 if (style.isCommand() && !style.intitle) {
2534 if (!style.leftdelim().empty()) {
2535 os << style.leftdelim();
2536 column += style.leftdelim().size();
2539 column += d->startTeXParParams(bparams, os, runparams);
2542 // Whether a \par can be issued for insets typeset inline with text.
2543 // Yes if greater than 0. This has to be static.
2544 THREAD_LOCAL_STATIC int parInline = 0;
2546 for (pos_type i = 0; i < size(); ++i) {
2547 // First char in paragraph or after label?
2548 if (i == body_pos) {
2551 bool needPar = false;
2552 column += running_font.latexWriteEndChanges(
2553 os, bparams, runparams,
2554 basefont, basefont, needPar);
2557 basefont = getLayoutFont(bparams, real_outerfont);
2558 running_font = basefont;
2560 column += Changes::latexMarkChange(os, bparams,
2561 runningChange, Change(Change::UNCHANGED),
2563 runningChange = Change(Change::UNCHANGED);
2565 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2568 // For InTitle commands, we have already opened a group
2569 // in output_latex::TeXOnePar.
2570 if (style.isCommand() && !style.intitle) {
2575 if (!style.leftdelim().empty()) {
2576 os << style.leftdelim();
2577 column += style.leftdelim().size();
2581 column += d->startTeXParParams(bparams, os,
2585 runparams.wasDisplayMath = runparams.inDisplayMath;
2586 runparams.inDisplayMath = false;
2587 bool deleted_display_math = false;
2588 Change const & change = runparams.inDeletedInset
2589 ? runparams.changeOfDeletedInset : lookupChange(i);
2591 char_type const c = d->text_[i];
2593 // Check whether a display math inset follows
2594 bool output_changes;
2595 if (runparams.for_searchAdv == OutputParams::NoSearch)
2596 output_changes = bparams.output_changes;
2598 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2600 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2602 runparams.ctObject = getInset(i)->getCtObject(runparams);
2604 InsetMath const * im = getInset(i)->asInsetMath();
2605 if (im && im->asHullInset()
2606 && im->asHullInset()->outerDisplay()) {
2607 runparams.inDisplayMath = true;
2608 // runparams.inDeletedInset will be set by
2609 // latexInset later, but we need this info
2610 // before it is called. On the other hand, we
2611 // cannot set it here because it is a counter.
2612 deleted_display_math = isDeleted(i);
2614 if (output_changes && deleted_display_math
2615 && runningChange == change
2616 && change.type == Change::DELETED
2617 && !os.afterParbreak()) {
2618 // A display math in the same paragraph follows.
2619 // We have to close and then reopen \lyxdeleted,
2620 // otherwise the math will be shifted up.
2621 OutputParams rp = runparams;
2623 bool needPar = false;
2624 column += running_font.latexWriteEndChanges(
2625 os, bparams, rp, basefont,
2629 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2630 : getLayoutFont(bparams, real_outerfont);
2631 running_font = basefont;
2632 column += Changes::latexMarkChange(os, bparams,
2633 Change(Change::INSERTED), change, rp);
2637 if (output_changes && runningChange != change) {
2638 if (!alien_script.empty()) {
2641 alien_script.clear();
2644 bool needPar = false;
2645 column += running_font.latexWriteEndChanges(
2646 os, bparams, runparams,
2647 basefont, basefont, needPar);
2650 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2651 : getLayoutFont(bparams, real_outerfont);
2652 running_font = basefont;
2653 column += Changes::latexMarkChange(os, bparams, runningChange,
2655 runningChange = change;
2658 // do not output text which is marked deleted
2659 // if change tracking output is disabled
2660 if (!output_changes && change.deleted()) {
2666 // Fully instantiated font
2667 Font current_font = getFont(bparams, i, outerfont);
2669 Font const prev_font = (i > 0) ?
2670 getFont(bparams, i - 1, outerfont)
2673 Font const last_font = running_font;
2674 bool const in_ct_deletion = (output_changes
2675 && runningChange == change
2676 && change.type == Change::DELETED
2677 && !os.afterParbreak());
2678 // Insets where font switches are used (rather than font commands)
2679 bool const fontswitch_inset =
2682 && getInset(i)->allowMultiPar()
2683 && getInset(i)->lyxCode() != ERT_CODE
2684 && getInset(i)->producesOutput();
2686 bool closeLanguage = false;
2687 bool lang_switched_at_inset = false;
2688 if (fontswitch_inset) {
2689 // Some insets cannot be inside a font change command.
2690 // However, even such insets *can* be placed in \L or \R
2691 // or their equivalents (for RTL language switches),
2692 // so we don't close the language in those cases
2693 // (= differing isRightToLeft()).
2694 // ArabTeX, though, doesn't seem to handle this special behavior.
2695 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2696 || basefont.language()->lang() == "arabic_arabtex"
2697 || current_font.language()->lang() == "arabic_arabtex";
2698 // We need to check prev_font as language changes directly at inset
2699 // will only be started inside the inset.
2700 lang_switched_at_inset = prev_font.language() != current_font.language();
2703 // Do we need to close the previous font?
2704 bool langClosed = false;
2706 ((current_font != running_font
2707 || current_font.language() != running_font.language())
2708 || (fontswitch_inset
2709 && (current_font == prev_font))))
2711 // ensure there is no open script-wrapper
2712 if (!alien_script.empty()) {
2715 alien_script.clear();
2717 if (in_ct_deletion) {
2718 // We have to close and then reopen \lyxdeleted,
2719 // as strikeout needs to be on lowest level.
2724 // Force language closing
2725 current_font.setLanguage(basefont.language());
2726 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2727 bool needPar = false;
2728 column += running_font.latexWriteEndChanges(
2729 os, bparams, runparams, basefont,
2731 if (in_ct_deletion) {
2732 // We have to close and then reopen \lyxdeleted,
2733 // as strikeout needs to be on lowest level.
2734 OutputParams rp = runparams;
2735 column += Changes::latexMarkChange(os, bparams,
2736 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2739 // Has the language been closed in the latexWriteEndChanges() call above?
2740 langClosed = running_font.language() != basefont.language()
2741 && running_font.language() != nextfont.language()
2742 && (running_font.language()->encoding()->package() != Encoding::CJK);
2743 running_font = basefont;
2746 // if necessary, close language environment before opening CJK
2747 string const running_lang = running_font.language()->babel();
2748 string const lang_end_command = lyxrc.language_command_end;
2749 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2750 && !running_lang.empty()
2751 && running_lang == openLanguageName()
2752 && current_font.language()->encoding()->package() == Encoding::CJK) {
2753 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2754 os << from_ascii(end_tag);
2755 column += end_tag.length();
2759 // Switch file encoding if necessary (and allowed)
2760 if ((!fontswitch_inset || closeLanguage)
2761 && !runparams.pass_thru && !style.pass_thru &&
2762 runparams.encoding->package() != Encoding::none &&
2763 current_font.language()->encoding()->package() != Encoding::none) {
2764 pair<bool, int> const enc_switch =
2765 switchEncoding(os.os(), bparams, runparams,
2766 *(current_font.language()->encoding()));
2767 if (enc_switch.first) {
2768 column += enc_switch.second;
2769 runparams.encoding = current_font.language()->encoding();
2773 // A display math inset inside an ulem command will be output
2774 // as a box of width \linewidth, so we have to either disable
2775 // indentation if the inset starts a paragraph, or start a new
2776 // line to accommodate such box. This has to be done before
2777 // writing any font changing commands.
2778 if (runparams.inDisplayMath && !deleted_display_math
2779 && runparams.inulemcmd) {
2780 if (os.afterParbreak())
2786 // Do we need to change font?
2787 if ((current_font != running_font ||
2788 current_font.language() != running_font.language())
2789 && i != body_pos - 1)
2791 if (!fontswitch_inset) {
2792 if (in_ct_deletion) {
2793 // We have to close and then reopen \lyxdeleted,
2794 // as strikeout needs to be on lowest level.
2795 OutputParams rp = runparams;
2796 bool needPar = false;
2797 column += running_font.latexWriteEndChanges(
2798 os, bparams, rp, basefont,
2803 otexstringstream ots;
2804 InsetText const * textinset = inInset().asInsetText();
2805 bool const cprotect = textinset
2806 ? textinset->hasCProtectContent(runparams.moving_arg)
2807 && !textinset->text().isMainText()
2809 column += current_font.latexWriteStartChanges(ots, bparams,
2810 runparams, basefont, last_font, false,
2812 // Check again for display math in ulem commands as a
2813 // font change may also occur just before a math inset.
2814 if (runparams.inDisplayMath && !deleted_display_math
2815 && runparams.inulemcmd) {
2816 if (os.afterParbreak())
2821 running_font = current_font;
2823 docstring fontchange = ots.str();
2825 // check whether the fontchange ends with a \\textcolor
2826 // modifier and the text starts with a space. If so we
2827 // need to add } in order to prevent \\textcolor from gobbling
2828 // the space (bug 4473).
2829 docstring const last_modifier = rsplit(fontchange, '\\');
2830 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2831 os << from_ascii("{}");
2832 else if (ots.terminateCommand())
2834 if (in_ct_deletion) {
2835 // We have to close and then reopen \lyxdeleted,
2836 // as strikeout needs to be on lowest level.
2837 OutputParams rp = runparams;
2838 column += Changes::latexMarkChange(os, bparams,
2839 Change(Change::UNCHANGED), change, rp);
2842 running_font = current_font;
2843 open_font = !langClosed;
2847 // FIXME: think about end_pos implementation...
2848 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2849 // FIXME: integrate this case in latexSpecialChar
2850 // Do not print the separation of the optional argument
2851 // if style.pass_thru is false. This works because
2852 // latexSpecialChar ignores spaces if
2853 // style.pass_thru is false.
2854 if (i != body_pos - 1) {
2855 if (d->simpleTeXBlanks(bparams, runparams, os,
2856 i, column, current_font, style)) {
2857 // A surrogate pair was output. We
2858 // must not call latexSpecialChar
2859 // in this iteration, since it would output
2860 // the combining character again.
2867 OutputParams rp = runparams;
2868 rp.free_spacing = style.free_spacing;
2869 rp.local_font = ¤t_font;
2870 rp.intitle = style.intitle;
2872 // Two major modes: LaTeX or plain
2873 // Handle here those cases common to both modes
2874 // and then split to handle the two modes separately.
2875 if (c == META_INSET) {
2876 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2877 // Greyedout notes and, in general, all insets
2878 // with InsetLayout::isDisplay() == false,
2879 // are typeset inline with the text. So, we
2880 // can add a \par to the last paragraph of
2881 // such insets only if nothing else follows.
2882 bool incremented = false;
2883 Inset const * inset = getInset(i);
2884 InsetText const * textinset = inset
2885 ? inset->asInsetText()
2887 if (i + 1 == size() && textinset
2888 && !inset->getLayout().isDisplay()) {
2889 ParagraphList const & pars =
2890 textinset->text().paragraphs();
2891 pit_type const pit = pars.size() - 1;
2892 Font const lastfont =
2893 pit < 0 || pars[pit].empty()
2894 ? pars[pit].getLayoutFont(
2897 : pars[pit].getFont(bparams,
2898 pars[pit].size() - 1,
2900 if (lastfont.fontInfo().size() !=
2901 basefont.fontInfo().size()) {
2906 // We need to restore parts of this after insets with
2907 // allowMultiPar() true
2908 Font const save_basefont = basefont;
2909 d->latexInset(bparams, os, rp, running_font,
2910 basefont, real_outerfont, open_font,
2911 runningChange, style, i, column, fontswitch_inset,
2912 closeLanguage, lang_switched_at_inset);
2913 if (fontswitch_inset) {
2915 bool needPar = false;
2916 column += running_font.latexWriteEndChanges(
2917 os, bparams, runparams,
2918 basefont, basefont, needPar);
2921 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2922 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2923 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2928 if (runparams.ctObject == CtObject::DisplayObject
2929 || runparams.ctObject == CtObject::UDisplayObject) {
2930 // Close \lyx*deleted and force its
2931 // reopening (if needed)
2934 runningChange = Change(Change::UNCHANGED);
2935 runparams.ctObject = CtObject::Normal;
2938 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2939 if (!bparams.useNonTeXFonts)
2940 script = Encodings::isKnownScriptChar(c);
2941 if (script != alien_script) {
2942 if (!alien_script.empty()) {
2944 alien_script.clear();
2946 string fontenc = running_font.language()->fontenc(bparams);
2948 && !Encodings::fontencSupportsScript(fontenc, script)) {
2949 column += script.length() + 2;
2950 os << "\\" << script << "{";
2951 alien_script = script;
2955 d->latexSpecialChar(os, bparams, rp, running_font,
2956 alien_script, style, i, end_pos, column);
2957 } catch (EncodingException & e) {
2958 if (runparams.dryrun) {
2959 os << "<" << _("LyX Warning: ")
2960 << _("uncodable character") << " '";
2964 // add location information and throw again.
2972 // Set the encoding to that returned from latexSpecialChar (see
2973 // comment for encoding member in OutputParams.h)
2974 runparams.encoding = rp.encoding;
2976 // Also carry on the info on a closed ulem command for insets
2977 // such as Note that do not produce any output, so that no
2978 // command is ever executed but its opening was recorded.
2979 runparams.inulemcmd = rp.inulemcmd;
2981 // These need to be passed upstream as well
2982 runparams.need_maketitle = rp.need_maketitle;
2983 runparams.have_maketitle = rp.have_maketitle;
2985 // And finally, pass the post_macros upstream
2986 runparams.post_macro = rp.post_macro;
2989 // Close wrapper for alien script
2990 if (!alien_script.empty()) {
2992 alien_script.clear();
2995 Font const font = empty()
2996 ? getLayoutFont(bparams, real_outerfont)
2997 : getFont(bparams, size() - 1, real_outerfont);
2999 InsetText const * textinset = inInset().asInsetText();
3001 bool const maintext = textinset
3002 ? textinset->text().isMainText()
3005 size_t const numpars = textinset
3006 ? textinset->text().paragraphs().size()
3009 bool needPar = false;
3011 if (style.resfont.size() != font.fontInfo().size()
3012 && (!runparams.isLastPar || maintext
3013 || (numpars > 1 && d->ownerCode() != CELL_CODE
3014 && (inInset().getLayout().isDisplay()
3016 && !style.isCommand()) {
3020 // If we have an open font definition, we have to close it
3022 // Make sure that \\par is done with the font of the last
3023 // character if this has another size as the default.
3024 // This is necessary because LaTeX (and LyX on the screen)
3025 // calculates the space between the baselines according
3026 // to this font. (Matthias)
3028 // We must not change the font for the last paragraph
3029 // of non-multipar insets, tabular cells or commands,
3030 // since this produces unwanted whitespace.
3031 #ifdef FIXED_LANGUAGE_END_DETECTION
3033 running_font.latexWriteEndChanges(os, bparams,
3034 runparams, basefont,
3035 next_->getFont(bparams, 0, outerfont),
3038 running_font.latexWriteEndChanges(os, bparams,
3039 runparams, basefont, basefont, needPar);
3042 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3043 //FIXME: there as we start another \selectlanguage with the next paragraph if
3044 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3045 running_font.latexWriteEndChanges(os, bparams, runparams,
3046 basefont, basefont, needPar);
3050 // The \par could not be inserted at the same nesting
3051 // level of the font size change, so do it now.
3052 os << "{\\" << font.latexSize() << "\\par}";
3055 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3056 column += Changes::latexMarkChange(os, bparams, runningChange,
3057 Change(Change::UNCHANGED), runparams);
3059 // Needed if there is an optional argument but no contents.
3060 if (body_pos > 0 && body_pos == size()) {
3064 if (!style.rightdelim().empty()) {
3065 os << style.rightdelim();
3066 column += style.rightdelim().size();
3069 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3070 && runparams.encoding != prev_encoding) {
3071 runparams.encoding = prev_encoding;
3072 os << setEncoding(prev_encoding->iconvName());
3075 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3079 bool Paragraph::emptyTag() const
3081 for (pos_type i = 0; i < size(); ++i) {
3082 if (Inset const * inset = getInset(i)) {
3083 InsetCode lyx_code = inset->lyxCode();
3084 // FIXME testing like that is wrong. What is
3086 if (lyx_code != TOC_CODE &&
3087 lyx_code != INCLUDE_CODE &&
3088 lyx_code != GRAPHICS_CODE &&
3089 lyx_code != ERT_CODE &&
3090 lyx_code != LISTINGS_CODE &&
3091 lyx_code != FLOAT_CODE &&
3092 lyx_code != TABULAR_CODE) {
3096 char_type c = d->text_[i];
3097 if (c != ' ' && c != '\t')
3105 string Paragraph::getID(Buffer const &, OutputParams const &)
3108 for (pos_type i = 0; i < size(); ++i) {
3109 if (Inset const * inset = getInset(i)) {
3110 InsetCode lyx_code = inset->lyxCode();
3111 if (lyx_code == LABEL_CODE) {
3112 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3113 docstring const & id = il->getParam("name");
3114 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3122 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3125 for (i = 0; i < size(); ++i) {
3126 if (Inset const * inset = getInset(i)) {
3127 inset->docbook(xs, runparams);
3129 char_type c = d->text_[i];
3139 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3143 for (i = 0; i < size(); ++i) {
3144 if (Inset const * inset = getInset(i)) {
3145 inset->xhtml(xs, runparams);
3147 char_type c = d->text_[i];
3157 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3160 pos_type size = text_.size();
3161 for (pos_type i = initial; i < size; ++i) {
3162 Font font = owner_->getFont(buf.params(), i, outerfont);
3163 if (text_[i] == META_INSET)
3165 if (i != initial && font != font_old)
3176 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3177 vector<xml::EndFontTag> & tagsToClose,
3178 bool & flag, FontState curstate, xml::FontTypes type)
3180 if (curstate == FONT_ON) {
3181 tagsToOpen.push_back(docbookStartFontTag(type));
3184 tagsToClose.push_back(docbookEndFontTag(type));
3189 class OptionalFontType {
3194 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3195 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3198 OptionalFontType fontShapeToXml(FontShape fs)
3202 return {xml::FT_ITALIC};
3204 return {xml::FT_SLANTED};
3205 case SMALLCAPS_SHAPE:
3206 return {xml::FT_SMALLCAPS};
3211 // the other tags are for internal use
3217 OptionalFontType fontFamilyToXml(FontFamily fm)
3221 return {xml::FT_ROMAN};
3223 return {xml::FT_SANS};
3224 case TYPEWRITER_FAMILY:
3225 return {xml::FT_TYPE};
3226 case INHERIT_FAMILY:
3229 // the other tags are for internal use
3235 OptionalFontType fontSizeToXml(FontSize fs)
3239 return {xml::FT_SIZE_TINY};
3241 return {xml::FT_SIZE_SCRIPT};
3243 return {xml::FT_SIZE_FOOTNOTE};
3245 return {xml::FT_SIZE_SMALL};
3247 return {xml::FT_SIZE_LARGE};
3249 return {xml::FT_SIZE_LARGER};
3251 return {xml::FT_SIZE_LARGEST};
3253 return {xml::FT_SIZE_HUGE};
3255 return {xml::FT_SIZE_HUGER};
3257 return {xml::FT_SIZE_INCREASE};
3259 return {xml::FT_SIZE_DECREASE};
3264 // the other tags are for internal use
3270 struct DocBookFontState
3272 FontShape curr_fs = INHERIT_SHAPE;
3273 FontFamily curr_fam = INHERIT_FAMILY;
3274 FontSize curr_size = INHERIT_SIZE;
3276 // track whether we have opened these tags
3277 bool emph_flag = false;
3278 bool bold_flag = false;
3279 bool noun_flag = false;
3280 bool ubar_flag = false;
3281 bool dbar_flag = false;
3282 bool sout_flag = false;
3283 bool xout_flag = false;
3284 bool wave_flag = false;
3286 bool shap_flag = false;
3288 bool faml_flag = false;
3290 bool size_flag = false;
3293 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3295 std::string const & default_family,
3296 DocBookFontState & fs)
3298 vector<xml::FontTag> tagsToOpen;
3299 vector<xml::EndFontTag> tagsToClose;
3302 FontState curstate = font.fontInfo().emph();
3303 if (font_old.emph() != curstate)
3304 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3307 curstate = font.fontInfo().noun();
3308 if (font_old.noun() != curstate)
3309 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3312 curstate = font.fontInfo().underbar();
3313 if (font_old.underbar() != curstate)
3314 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3317 curstate = font.fontInfo().strikeout();
3318 if (font_old.strikeout() != curstate)
3319 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3322 curstate = font.fontInfo().xout();
3323 if (font_old.xout() != curstate)
3324 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3327 curstate = font.fontInfo().uuline();
3328 if (font_old.uuline() != curstate)
3329 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3332 curstate = font.fontInfo().uwave();
3333 if (font_old.uwave() != curstate)
3334 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3337 // a little hackish, but allows us to reuse what we have.
3338 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3339 if (font_old.series() != font.fontInfo().series())
3340 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3343 fs.curr_fs = font.fontInfo().shape();
3344 FontShape old_fs = font_old.shape();
3345 if (old_fs != fs.curr_fs) {
3347 OptionalFontType tag = fontShapeToXml(old_fs);
3349 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3350 fs.shap_flag = false;
3353 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3355 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3359 fs.curr_fam = font.fontInfo().family();
3360 FontFamily old_fam = font_old.family();
3361 if (old_fam != fs.curr_fam) {
3363 OptionalFontType tag = fontFamilyToXml(old_fam);
3365 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3366 fs.faml_flag = false;
3368 switch (fs.curr_fam) {
3370 // we will treat a "default" font family as roman, since we have
3371 // no other idea what to do.
3372 if (default_family != "rmdefault" && default_family != "default") {
3373 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3374 fs.faml_flag = true;
3378 if (default_family != "sfdefault") {
3379 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3380 fs.faml_flag = true;
3383 case TYPEWRITER_FAMILY:
3384 if (default_family != "ttdefault") {
3385 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3386 fs.faml_flag = true;
3389 case INHERIT_FAMILY:
3392 // the other tags are for internal use
3399 fs.curr_size = font.fontInfo().size();
3400 FontSize old_size = font_old.size();
3401 if (old_size != fs.curr_size) {
3403 OptionalFontType tag = fontSizeToXml(old_size);
3405 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3406 fs.size_flag = false;
3409 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3410 if (tag.has_value) {
3411 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3412 fs.size_flag = true;
3416 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3419 } // anonymous namespace
3422 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3423 OutputParams const & runparams,
3424 Font const & outerfont,
3427 bool ignore_fonts) const
3429 // Track whether we have opened these tags
3430 DocBookFontState fs;
3432 Layout const & style = *d->layout_;
3434 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3436 string const default_family =
3437 buf.masterBuffer()->params().fonts_default_family;
3439 vector<xml::FontTag> tagsToOpen;
3440 vector<xml::EndFontTag> tagsToClose;
3442 std::vector<docstring> generatedParagraphs;
3443 DocBookFontState old_fs = fs;
3444 odocstringstream os;
3445 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3446 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3448 // When a font tag ends with a space, output it after the closing font tag. This requires to store delayed
3449 // characters at some point.
3450 std::vector<char_type> delayedChars;
3452 // Parsing main loop.
3453 for (pos_type i = initial; i < size(); ++i) {
3454 bool ignore_fonts_i = ignore_fonts
3455 || style.docbooknofontinside()
3456 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3458 // Don't show deleted material in the output.
3462 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3464 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3465 if (!ignore_fonts_i)
3466 xs->closeFontTags();
3468 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3469 generatedParagraphs.push_back(os.str());
3471 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3472 // that the string stream must be reset.
3473 os.str(from_ascii(""));
3475 xs = new XMLStream(os);
3477 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3478 if (!ignore_fonts_i) {
3479 font_old = outerfont.fontInfo();
3484 // Determine which tags should be opened or closed regarding fonts.
3485 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3486 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3488 if (!ignore_fonts_i) {
3489 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3490 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3491 for (; cit != cen; ++cit)
3495 // Deal with the delayed characters *after* closing font tags.
3496 if (!delayedChars.empty()) {
3497 for (char_type c: delayedChars)
3499 delayedChars.clear();
3502 if (!ignore_fonts_i) {
3503 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3504 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3505 for (; sit != sen; ++sit)
3508 tagsToClose.clear();
3512 // Finally, write the next character or inset.
3513 if (Inset const * inset = getInset(i)) {
3514 if (!runparams.for_toc || inset->isInToc()) {
3515 OutputParams np = runparams;
3516 np.local_font = &font;
3518 // TODO: special case will bite here.
3519 np.docbook_in_par = true;
3520 inset->docbook(*xs, np);
3523 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3524 if (lyx::isSpace(c) && !ignore_fonts)
3525 delayedChars.push_back(c);
3529 font_old = font.fontInfo();
3532 // FIXME, this code is just imported from XHTML
3533 // I'm worried about what happens if a branch, say, is itself
3534 // wrapped in some font stuff. I think that will not work.
3536 xs->closeFontTags();
3538 // Deal with the delayed characters *after* closing font tags.
3539 if (!delayedChars.empty())
3540 for (char_type c: delayedChars)
3543 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3544 // last line to get a clean output.
3545 if (runparams.docbook_in_listing && !is_last_par)
3548 // Finalise the last (and most likely only) paragraph.
3549 generatedParagraphs.push_back(os.str());
3552 return generatedParagraphs;
3558 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3559 vector<xml::EndFontTag> & tagsToClose,
3560 bool & flag, FontState curstate, xml::FontTypes type)
3562 if (curstate == FONT_ON) {
3563 tagsToOpen.push_back(xhtmlStartFontTag(type));
3566 tagsToClose.push_back(xhtmlEndFontTag(type));
3571 } // anonymous namespace
3574 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3576 OutputParams const & runparams,
3577 Font const & outerfont,
3578 bool start_paragraph, bool close_paragraph,
3579 pos_type initial) const
3583 // track whether we have opened these tags
3584 bool emph_flag = false;
3585 bool bold_flag = false;
3586 bool noun_flag = false;
3587 bool ubar_flag = false;
3588 bool dbar_flag = false;
3589 bool sout_flag = false;
3590 bool xout_flag = false;
3591 bool wave_flag = false;
3593 bool shap_flag = false;
3595 bool faml_flag = false;
3597 bool size_flag = false;
3599 Layout const & style = *d->layout_;
3601 if (start_paragraph)
3602 xs.startDivision(allowEmpty());
3605 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3607 FontShape curr_fs = INHERIT_SHAPE;
3608 FontFamily curr_fam = INHERIT_FAMILY;
3609 FontSize curr_size = INHERIT_SIZE;
3611 string const default_family =
3612 buf.masterBuffer()->params().fonts_default_family;
3614 vector<xml::FontTag> tagsToOpen;
3615 vector<xml::EndFontTag> tagsToClose;
3617 // parsing main loop
3618 for (pos_type i = initial; i < size(); ++i) {
3619 // let's not show deleted material in the output
3623 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3626 FontState curstate = font.fontInfo().emph();
3627 if (font_old.emph() != curstate)
3628 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3631 curstate = font.fontInfo().noun();
3632 if (font_old.noun() != curstate)
3633 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3636 curstate = font.fontInfo().underbar();
3637 if (font_old.underbar() != curstate)
3638 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3641 curstate = font.fontInfo().strikeout();
3642 if (font_old.strikeout() != curstate)
3643 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3646 curstate = font.fontInfo().xout();
3647 if (font_old.xout() != curstate)
3648 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3651 curstate = font.fontInfo().uuline();
3652 if (font_old.uuline() != curstate)
3653 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3656 curstate = font.fontInfo().uwave();
3657 if (font_old.uwave() != curstate)
3658 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3661 // a little hackish, but allows us to reuse what we have.
3662 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3663 if (font_old.series() != font.fontInfo().series())
3664 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3667 curr_fs = font.fontInfo().shape();
3668 FontShape old_fs = font_old.shape();
3669 if (old_fs != curr_fs) {
3673 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3676 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3678 case SMALLCAPS_SHAPE:
3679 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3685 // the other tags are for internal use
3693 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3697 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3700 case SMALLCAPS_SHAPE:
3701 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3708 // the other tags are for internal use
3715 curr_fam = font.fontInfo().family();
3716 FontFamily old_fam = font_old.family();
3717 if (old_fam != curr_fam) {
3721 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3724 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3726 case TYPEWRITER_FAMILY:
3727 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3729 case INHERIT_FAMILY:
3732 // the other tags are for internal use
3740 // we will treat a "default" font family as roman, since we have
3741 // no other idea what to do.
3742 if (default_family != "rmdefault" && default_family != "default") {
3743 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3748 if (default_family != "sfdefault") {
3749 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3753 case TYPEWRITER_FAMILY:
3754 if (default_family != "ttdefault") {
3755 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3759 case INHERIT_FAMILY:
3762 // the other tags are for internal use
3769 curr_size = font.fontInfo().size();
3770 FontSize old_size = font_old.size();
3771 if (old_size != curr_size) {
3775 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3778 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3781 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3784 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3787 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3790 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3793 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3796 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3799 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3802 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3805 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3811 // the other tags are for internal use
3817 switch (curr_size) {
3819 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3823 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3827 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3831 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3835 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3839 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3843 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3847 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3851 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3855 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3859 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3866 // the other tags are for internal use
3873 // Other such tags? What about the other text ranges?
3875 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3876 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3877 for (; cit != cen; ++cit)
3880 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3881 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3882 for (; sit != sen; ++sit)
3885 tagsToClose.clear();
3888 Inset const * inset = getInset(i);
3890 if (!runparams.for_toc || inset->isInToc()) {
3891 OutputParams np = runparams;
3892 np.local_font = &font;
3893 // If the paragraph has size 1, then we are in the "special
3894 // case" where we do not output the containing paragraph info
3895 if (!inset->getLayout().htmlisblock() && size() != 1)
3896 np.html_in_par = true;
3897 retval += inset->xhtml(xs, np);
3900 char_type c = getUChar(buf.masterBuffer()->params(),
3902 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3903 xs << XMLStream::ESCAPE_NONE << " ";
3907 font_old = font.fontInfo();
3911 // I'm worried about what happens if a branch, say, is itself
3912 // wrapped in some font stuff. I think that will not work.
3914 if (close_paragraph)
3921 bool Paragraph::isHfill(pos_type pos) const
3923 Inset const * inset = getInset(pos);
3924 return inset && inset->isHfill();
3928 bool Paragraph::isNewline(pos_type pos) const
3930 // U+2028 LINE SEPARATOR
3931 // U+2029 PARAGRAPH SEPARATOR
3932 char_type const c = d->text_[pos];
3933 if (c == 0x2028 || c == 0x2029)
3935 Inset const * inset = getInset(pos);
3936 return inset && inset->lyxCode() == NEWLINE_CODE;
3940 bool Paragraph::isEnvSeparator(pos_type pos) const
3942 Inset const * inset = getInset(pos);
3943 return inset && inset->lyxCode() == SEPARATOR_CODE;
3947 bool Paragraph::isLineSeparator(pos_type pos) const
3949 char_type const c = d->text_[pos];
3950 if (isLineSeparatorChar(c))
3952 Inset const * inset = getInset(pos);
3953 return inset && inset->isLineSeparator();
3957 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3961 if (ignore_deleted && isDeleted(pos))
3963 if (Inset const * inset = getInset(pos))
3964 return !inset->isLetter();
3965 // if we have a hard hyphen (no en- or emdash) or apostrophe
3966 // we pass this to the spell checker
3967 // FIXME: this method is subject to change, visit
3968 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3969 // to get an impression how complex this is.
3970 if (isHardHyphenOrApostrophe(pos))
3972 char_type const c = d->text_[pos];
3973 // We want to pass the escape chars to the spellchecker
3974 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3975 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3979 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3981 pos_type const psize = size();
3984 char_type const c = d->text_[pos];
3985 if (c != '-' && c != '\'')
3987 pos_type nextpos = pos + 1;
3988 pos_type prevpos = pos > 0 ? pos - 1 : 0;
3989 if ((nextpos == psize || isSpace(nextpos))
3990 && (pos == 0 || isSpace(prevpos)))
3996 bool Paragraph::needsCProtection(bool const fragile) const
3998 // first check the layout of the paragraph, but only in insets
3999 InsetText const * textinset = inInset().asInsetText();
4000 bool const maintext = textinset
4001 ? textinset->text().isMainText()
4004 if (!maintext && layout().needcprotect) {
4005 // Environments need cprotection regardless the content
4006 if (layout().latextype == LATEX_ENVIRONMENT)
4009 // Commands need cprotection if they contain specific chars
4010 int const nchars_escape = 9;
4011 static char_type const chars_escape[nchars_escape] = {
4012 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4014 docstring const pars = asString();
4015 for (int k = 0; k < nchars_escape; k++) {
4016 if (contains(pars, chars_escape[k]))
4021 // now check whether we have insets that need cprotection
4022 pos_type size = pos_type(d->text_.size());
4023 for (pos_type i = 0; i < size; ++i) {
4026 Inset const * ins = getInset(i);
4027 if (ins->needsCProtection(maintext, fragile))
4029 // Now check math environments
4030 InsetMath const * im = getInset(i)->asInsetMath();
4031 if (!im || im->cell(0).empty())
4033 switch(im->cell(0)[0]->lyxCode()) {
4034 case MATH_AMSARRAY_CODE:
4035 case MATH_SUBSTACK_CODE:
4037 case MATH_XYMATRIX_CODE:
4038 // these need cprotection
4049 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4051 return d->speller_state_.getRange(pos);
4055 bool Paragraph::isChar(pos_type pos) const
4057 if (Inset const * inset = getInset(pos))
4058 return inset->isChar();
4059 char_type const c = d->text_[pos];
4060 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4064 bool Paragraph::isSpace(pos_type pos) const
4066 if (Inset const * inset = getInset(pos))
4067 return inset->isSpace();
4068 char_type const c = d->text_[pos];
4069 return lyx::isSpace(c);
4074 Paragraph::getParLanguage(BufferParams const & bparams) const
4077 return getFirstFontSettings(bparams).language();
4078 // FIXME: we should check the prev par as well (Lgb)
4079 return bparams.language;
4083 bool Paragraph::isRTL(BufferParams const & bparams) const
4085 return getParLanguage(bparams)->rightToLeft()
4086 && !inInset().getLayout().forceLTR();
4090 void Paragraph::changeLanguage(BufferParams const & bparams,
4091 Language const * from, Language const * to)
4093 // change language including dummy font change at the end
4094 for (pos_type i = 0; i <= size(); ++i) {
4095 Font font = getFontSettings(bparams, i);
4096 if (font.language() == from) {
4097 font.setLanguage(to);
4099 d->requestSpellCheck(i);
4105 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4107 Language const * doc_language = bparams.language;
4108 for (auto const & f : d->fontlist_)
4109 if (f.font().language() != ignore_language &&
4110 f.font().language() != latex_language &&
4111 f.font().language() != doc_language)
4117 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4119 for (auto const & f : d->fontlist_) {
4120 Language const * lang = f.font().language();
4121 if (lang != ignore_language &&
4122 lang != latex_language)
4128 docstring Paragraph::asString(int options) const
4130 return asString(0, size(), options);
4134 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4136 odocstringstream os;
4139 && options & AS_STR_LABEL
4140 && !d->params_.labelString().empty())
4141 os << d->params_.labelString() << ' ';
4143 for (pos_type i = beg; i < end; ++i) {
4144 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4146 char_type const c = d->text_[i];
4147 if (isPrintable(c) || c == '\t'
4148 || (c == '\n' && (options & AS_STR_NEWLINES)))
4150 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4151 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4152 LASSERT(runparams != nullptr, return docstring());
4153 getInset(i)->plaintext(os, *runparams);
4154 } else if (c == META_INSET && (options & AS_STR_MATHED)
4155 && getInset(i)->lyxCode() == REF_CODE) {
4156 Buffer const & buf = getInset(i)->buffer();
4157 OutputParams rp(&buf.params().encoding());
4158 Font const font(inherit_font, buf.params().language);
4159 rp.local_font = &font;
4161 getInset(i)->latex(ots, rp);
4163 getInset(i)->toString(os);
4172 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4173 bool const shorten, bool const label) const
4175 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4176 if (label && !labelString().empty())
4177 os += labelString() + ' ';
4178 if (!layout().isTocCaption())
4180 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4183 char_type const c = d->text_[i];
4186 else if (c == META_INSET)
4187 getInset(i)->forOutliner(os, tmplen, false);
4190 Text::shortenForOutliner(os, maxlen);
4194 void Paragraph::setInsetOwner(Inset const * inset)
4196 d->inset_owner_ = inset;
4200 int Paragraph::id() const
4206 void Paragraph::setId(int id)
4212 Layout const & Paragraph::layout() const
4218 void Paragraph::setLayout(Layout const & layout)
4220 d->layout_ = &layout;
4224 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4226 setLayout(tc.defaultLayout());
4230 void Paragraph::setPlainLayout(DocumentClass const & tc)
4232 setLayout(tc.plainLayout());
4236 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4238 if (usePlainLayout())
4241 setDefaultLayout(tc);
4245 Inset const & Paragraph::inInset() const
4247 LBUFERR(d->inset_owner_);
4248 return *d->inset_owner_;
4252 ParagraphParameters & Paragraph::params()
4258 ParagraphParameters const & Paragraph::params() const
4264 bool Paragraph::isFreeSpacing() const
4266 if (d->layout_->free_spacing)
4268 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4272 bool Paragraph::allowEmpty() const
4274 if (d->layout_->keepempty)
4276 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4280 bool Paragraph::brokenBiblio() const
4282 // There is a problem if there is no bibitem at position 0 in
4283 // paragraphs that need one, if there is another bibitem in the
4284 // paragraph or if this paragraph is not supposed to have
4285 // a bibitem inset at all.
4286 return ((d->layout_->labeltype == LABEL_BIBLIO
4287 && (d->insetlist_.find(BIBITEM_CODE) != 0
4288 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4289 || (d->layout_->labeltype != LABEL_BIBLIO
4290 && d->insetlist_.find(BIBITEM_CODE) != -1));
4294 int Paragraph::fixBiblio(Buffer const & buffer)
4296 // FIXME: when there was already an inset at 0, the return value is 1,
4297 // which does not tell whether another inset has been removed; the
4298 // cursor cannot be correctly updated.
4300 bool const track_changes = buffer.params().track_changes;
4301 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4303 // The case where paragraph is not BIBLIO
4304 if (d->layout_->labeltype != LABEL_BIBLIO) {
4305 if (bibitem_pos == -1)
4306 // No InsetBibitem => OK
4308 // There is an InsetBibitem: remove it!
4309 d->insetlist_.release(bibitem_pos);
4310 eraseChar(bibitem_pos, track_changes);
4311 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4314 bool const hasbibitem0 = bibitem_pos == 0;
4316 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4317 // There was an InsetBibitem at pos 0,
4318 // and no other one => OK
4319 if (bibitem_pos == -1)
4321 // there is a bibitem at the 0 position, but since
4322 // there is a second one, we copy the second on the
4323 // first. We're assuming there are at most two of
4324 // these, which there should be.
4325 // FIXME: why does it make sense to do that rather
4326 // than keep the first? (JMarc)
4327 Inset * inset = releaseInset(bibitem_pos);
4328 d->insetlist_.begin()->inset = inset;
4329 // This needs to be done to update the counter (#8499)
4330 buffer.updateBuffer();
4331 return -bibitem_pos;
4334 // We need to create an inset at the beginning
4335 Inset * inset = nullptr;
4336 if (bibitem_pos > 0) {
4337 // there was one somewhere in the paragraph, let's move it
4338 inset = d->insetlist_.release(bibitem_pos);
4339 eraseChar(bibitem_pos, track_changes);
4342 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4343 InsetCommandParams(BIBITEM_CODE));
4345 Font font(inherit_font, buffer.params().language);
4346 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4347 : Change::UNCHANGED));
4349 // This is needed to get the counters right
4350 buffer.updateBuffer();
4355 void Paragraph::checkAuthors(AuthorList const & authorList)
4357 d->changes_.checkAuthors(authorList);
4361 bool Paragraph::isChanged(pos_type pos) const
4363 return lookupChange(pos).changed();
4367 bool Paragraph::isInserted(pos_type pos) const
4369 return lookupChange(pos).inserted();
4373 bool Paragraph::isDeleted(pos_type pos) const
4375 return lookupChange(pos).deleted();
4379 InsetList const & Paragraph::insetList() const
4381 return d->insetlist_;
4385 void Paragraph::setInsetBuffers(Buffer & b)
4387 d->insetlist_.setBuffer(b);
4391 void Paragraph::resetBuffer()
4393 d->insetlist_.resetBuffer();
4397 Inset * Paragraph::releaseInset(pos_type pos)
4399 Inset * inset = d->insetlist_.release(pos);
4400 /// does not honour change tracking!
4401 eraseChar(pos, false);
4406 Inset * Paragraph::getInset(pos_type pos)
4408 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4409 ? d->insetlist_.get(pos) : nullptr;
4413 Inset const * Paragraph::getInset(pos_type pos) const
4415 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4416 ? d->insetlist_.get(pos) : nullptr;
4420 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4421 pos_type & right, TextCase action)
4423 // process sequences of modified characters; in change
4424 // tracking mode, this approach results in much better
4425 // usability than changing case on a char-by-char basis
4426 // We also need to track the current font, since font
4427 // changes within sequences can occur.
4428 vector<pair<char_type, Font> > changes;
4430 bool const trackChanges = bparams.track_changes;
4432 bool capitalize = true;
4434 for (; pos < right; ++pos) {
4435 char_type oldChar = d->text_[pos];
4436 char_type newChar = oldChar;
4438 // ignore insets and don't play with deleted text!
4439 if (oldChar != META_INSET && !isDeleted(pos)) {
4441 case text_lowercase:
4442 newChar = lowercase(oldChar);
4444 case text_capitalization:
4446 newChar = uppercase(oldChar);
4450 case text_uppercase:
4451 newChar = uppercase(oldChar);
4456 if (isWordSeparator(pos) || isDeleted(pos)) {
4457 // permit capitalization again
4461 if (oldChar != newChar) {
4462 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4463 if (pos != right - 1)
4465 // step behind the changing area
4469 int erasePos = pos - changes.size();
4470 for (auto const & change : changes) {
4471 insertChar(pos, change.first, change.second, trackChanges);
4472 if (!eraseChar(erasePos, trackChanges)) {
4475 ++right; // expand selection
4483 int Paragraph::find(docstring const & str, bool cs, bool mw,
4484 pos_type start_pos, bool del) const
4486 pos_type pos = start_pos;
4487 int const strsize = str.length();
4489 pos_type const parsize = d->text_.size();
4490 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4491 // ignore deleted matter
4492 if (!del && isDeleted(pos)) {
4493 if (pos == parsize - 1)
4499 // Ignore "invisible" letters such as ligature breaks
4500 // and hyphenation chars while searching
4501 bool nonmatch = false;
4502 while (pos < parsize && isInset(pos)) {
4503 Inset const * inset = getInset(pos);
4504 if (!inset->isLetter() && !inset->isChar())
4506 odocstringstream os;
4507 inset->toString(os);
4508 docstring const insetstring = os.str();
4509 if (!insetstring.empty()) {
4510 int const insetstringsize = insetstring.length();
4511 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4512 if ((cs && str[i] != insetstring[j])
4513 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4521 if (nonmatch || i == strsize)
4523 if (cs && str[i] != d->text_[pos])
4525 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4532 // if necessary, check whether string matches word
4534 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4537 && !isWordSeparator(pos))
4541 return pos - start_pos;
4545 char_type Paragraph::getChar(pos_type pos) const
4547 return d->text_[pos];
4551 pos_type Paragraph::size() const
4553 return d->text_.size();
4557 bool Paragraph::empty() const
4559 return d->text_.empty();
4563 bool Paragraph::isInset(pos_type pos) const
4565 return d->text_[pos] == META_INSET;
4569 bool Paragraph::isSeparator(pos_type pos) const
4571 //FIXME: Are we sure this can be the only separator?
4572 return d->text_[pos] == ' ';
4576 void Paragraph::deregisterWords()
4578 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4579 Private::LangWordsMap::const_iterator ite = d->words_.end();
4580 for (; itl != ite; ++itl) {
4581 WordList & wl = theWordList(itl->first);
4582 Private::Words::const_iterator it = (itl->second).begin();
4583 Private::Words::const_iterator et = (itl->second).end();
4584 for (; it != et; ++it)
4591 void Paragraph::locateWord(pos_type & from, pos_type & to,
4592 word_location const loc, bool const ignore_deleted) const
4595 case WHOLE_WORD_STRICT:
4596 if (from == 0 || from == size()
4597 || isWordSeparator(from, ignore_deleted)
4598 || isWordSeparator(from - 1, ignore_deleted)) {
4605 // If we are already at the beginning of a word, do nothing
4606 if (!from || isWordSeparator(from - 1, ignore_deleted))
4611 // always move the cursor to the beginning of previous word
4612 while (from && !isWordSeparator(from - 1, ignore_deleted))
4616 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4619 // no need to move the 'from' cursor
4623 while (to < size() && !isWordSeparator(to, ignore_deleted))
4628 void Paragraph::collectWords()
4630 for (pos_type pos = 0; pos < size(); ++pos) {
4631 if (isWordSeparator(pos))
4633 pos_type from = pos;
4634 locateWord(from, pos, WHOLE_WORD);
4635 // Work around MSVC warning: The statement
4636 // if (pos < from + lyxrc.completion_minlength)
4637 // triggers a signed vs. unsigned warning.
4638 // I don't know why this happens, it could be a MSVC bug, or
4639 // related to LLP64 (windows) vs. LP64 (unix) programming
4640 // model, or the C++ standard might be ambigous in the section
4641 // defining the "usual arithmetic conversions". However, using
4642 // a temporary variable is safe and works on all compilers.
4643 pos_type const endpos = from + lyxrc.completion_minlength;
4646 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4647 if (cit == d->fontlist_.end())
4649 Language const * lang = cit->font().language();
4650 docstring const word = asString(from, pos, AS_STR_NONE);
4651 d->words_[lang->lang()].insert(word);
4656 void Paragraph::registerWords()
4658 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4659 Private::LangWordsMap::const_iterator ite = d->words_.end();
4660 for (; itl != ite; ++itl) {
4661 WordList & wl = theWordList(itl->first);
4662 Private::Words::const_iterator it = (itl->second).begin();
4663 Private::Words::const_iterator et = (itl->second).end();
4664 for (; it != et; ++it)
4670 void Paragraph::updateWords()
4678 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4680 SkipPositionsIterator begin = skips.begin();
4681 SkipPositions::iterator end = skips.end();
4682 if (pos > 0 && begin < end) {
4684 if (end->last == pos - 1) {
4689 skips.insert(end, FontSpan(pos, pos));
4693 Language * Paragraph::Private::locateSpellRange(
4694 pos_type & from, pos_type & to,
4695 SkipPositions & skips) const
4697 // skip leading white space
4698 while (from < to && owner_->isWordSeparator(from))
4700 // don't check empty range
4703 // get current language
4704 Language * lang = getSpellLanguage(from);
4705 pos_type last = from;
4706 bool samelang = true;
4707 bool sameinset = true;
4708 while (last < to && samelang && sameinset) {
4709 // hop to end of word
4710 while (last < to && !owner_->isWordSeparator(last)) {
4711 Inset const * inset = owner_->getInset(last);
4712 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4713 // check for "invisible" letters such as ligature breaks
4714 odocstringstream os;
4715 inset->toString(os);
4716 if (os.str().length() != 0) {
4717 // avoid spell check of visible special char insets
4718 // stop the loop in front of the special char inset
4723 appendSkipPosition(skips, last);
4724 } else if (owner_->isDeleted(last)) {
4725 appendSkipPosition(skips, last);
4729 // hop to next word while checking for insets
4730 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4731 if (Inset const * inset = owner_->getInset(last))
4732 sameinset = inset->isChar() && inset->isLetter();
4733 if (sameinset && owner_->isDeleted(last)) {
4734 appendSkipPosition(skips, last);
4739 if (sameinset && last < to) {
4740 // now check for language change
4741 samelang = lang == getSpellLanguage(last);
4744 // if language change detected backstep is needed
4752 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4755 const_cast<Language *>(owner_->getFontSettings(
4756 inset_owner_->buffer().params(), from).language());
4757 if (lang == inset_owner_->buffer().params().language
4758 && !lyxrc.spellchecker_alt_lang.empty()) {
4760 string const lang_variety =
4761 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4762 lang->setCode(lang_code);
4763 lang->setVariety(lang_variety);
4769 void Paragraph::requestSpellCheck(pos_type pos)
4771 d->requestSpellCheck(pos);
4775 bool Paragraph::needsSpellCheck() const
4777 SpellChecker::ChangeNumber speller_change_number = 0;
4778 if (theSpellChecker())
4779 speller_change_number = theSpellChecker()->changeNumber();
4780 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4781 d->speller_state_.needsCompleteRefresh(speller_change_number);
4783 return d->needsSpellCheck();
4787 bool Paragraph::Private::ignoreWord(docstring const & word) const
4789 // Ignore words with digits
4790 // FIXME: make this customizable
4791 // (note that some checkers ignore words with digits by default)
4792 docstring::const_iterator cit = word.begin();
4793 docstring::const_iterator const end = word.end();
4794 for (; cit != end; ++cit) {
4795 if (isNumber((*cit)))
4802 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4803 WordLangTuple & wl, docstring_list & suggestions,
4804 bool do_suggestion, bool check_learned) const
4806 SpellChecker::Result result = SpellChecker::WORD_OK;
4807 SpellChecker * speller = theSpellChecker();
4811 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4814 locateWord(from, to, WHOLE_WORD, true);
4815 if (from == to || from >= size())
4818 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4819 Language * lang = d->getSpellLanguage(from);
4821 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4824 wl = WordLangTuple(word, lang);
4829 if (needsSpellCheck() || check_learned) {
4831 if (!d->ignoreWord(word)) {
4832 bool const trailing_dot = to < size() && d->text_[to] == '.';
4833 result = speller->check(wl);
4834 if (SpellChecker::misspelled(result) && trailing_dot) {
4835 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4836 result = speller->check(wl);
4837 if (!SpellChecker::misspelled(result)) {
4838 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4840 from << ".." << to << "]");
4842 // spell check with dot appended failed too
4843 // restore original word/lang value
4844 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4845 wl = WordLangTuple(word, lang);
4849 if (!SpellChecker::misspelled(result)) {
4850 // area up to the begin of the next word is not misspelled
4851 while (end < size() && isWordSeparator(end))
4854 d->setMisspelled(from, end, result);
4856 result = d->speller_state_.getState(from);
4860 suggestions.clear();
4862 if (SpellChecker::misspelled(result)) {
4863 LYXERR(Debug::GUI, "misspelled word: \"" <<
4865 from << ".." << to << "]");
4867 speller->suggest(wl, suggestions);
4873 void Paragraph::anonymize()
4875 // This is a very crude anonymization for now
4876 for (char_type & c : d->text_)
4877 if (isLetterChar(c) || isNumber(c))
4882 void Paragraph::Private::markMisspelledWords(
4883 pos_type const & first, pos_type const & last,
4884 SpellChecker::Result result,
4885 docstring const & word,
4886 SkipPositions const & skips)
4888 if (!SpellChecker::misspelled(result)) {
4889 setMisspelled(first, last, SpellChecker::WORD_OK);
4893 SpellChecker * speller = theSpellChecker();
4894 // locate and enumerate the error positions
4895 int nerrors = speller->numMisspelledWords();
4897 SkipPositionsIterator it = skips.begin();
4898 SkipPositionsIterator et = skips.end();
4899 for (int index = 0; index < nerrors; ++index) {
4902 speller->misspelledWord(index, wstart, wlen);
4903 /// should not happen if speller supports range checks
4904 if (!wlen) continue;
4905 docstring const misspelled = word.substr(wstart, wlen);
4906 wstart += first + numskipped;
4907 if (snext < wstart) {
4908 /// mark the range of correct spelling
4909 numskipped += countSkips(it, et, wstart);
4910 setMisspelled(snext,
4911 wstart - 1, SpellChecker::WORD_OK);
4913 snext = wstart + wlen;
4914 numskipped += countSkips(it, et, snext);
4915 /// mark the range of misspelling
4916 setMisspelled(wstart, snext, result);
4917 LYXERR(Debug::GUI, "misspelled word: \"" <<
4918 misspelled << "\" [" <<
4919 wstart << ".." << (snext-1) << "]");
4922 if (snext <= last) {
4923 /// mark the range of correct spelling at end
4924 setMisspelled(snext, last, SpellChecker::WORD_OK);
4929 void Paragraph::spellCheck() const
4931 SpellChecker * speller = theSpellChecker();
4932 if (!speller || empty() ||!needsSpellCheck())
4936 d->rangeOfSpellCheck(start, endpos);
4937 if (speller->canCheckParagraph()) {
4938 // loop until we leave the range
4939 for (pos_type first = start; first < endpos; ) {
4940 pos_type last = endpos;
4941 Private::SkipPositions skips;
4942 Language * lang = d->locateSpellRange(first, last, skips);
4943 if (first >= endpos)
4945 // start the spell checker on the unit of meaning
4946 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4947 WordLangTuple wl = WordLangTuple(word, lang);
4948 SpellChecker::Result result = !word.empty() ?
4949 speller->check(wl) : SpellChecker::WORD_OK;
4950 d->markMisspelledWords(first, last, result, word, skips);
4954 static docstring_list suggestions;
4955 pos_type to = endpos;
4956 while (start < endpos) {
4958 spellCheck(start, to, wl, suggestions, false);
4962 d->readySpellCheck();
4966 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4968 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4969 if (result || pos <= 0 || pos > size())
4971 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4972 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4977 string Paragraph::magicLabel() const
4980 ss << "magicparlabel-" << id();