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 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"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
36 #include "OutputParams.h"
37 #include "output_latex.h"
38 #include "output_xhtml.h"
39 #include "output_docbook.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/Length.h"
65 #include "support/lstrings.h"
66 #include "support/textutils.h"
67 #include "output_docbook.h"
74 using namespace lyx::support;
76 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
77 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
78 #define THREAD_LOCAL_STATIC static __thread
79 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
80 #define THREAD_LOCAL_STATIC static __declspec(thread)
82 #define THREAD_LOCAL_STATIC thread_local static
87 /////////////////////////////////////////////////////////////////////
91 /////////////////////////////////////////////////////////////////////
93 class SpellResultRange {
95 SpellResultRange(FontSpan range, SpellChecker::Result result)
96 : range_(range), result_(result)
99 FontSpan const & range() const { return range_; }
101 void range(FontSpan const & r) { range_ = r; }
103 SpellChecker::Result result() const { return result_; }
105 void result(SpellChecker::Result r) { result_ = r; }
107 bool contains(pos_type pos) const { return range_.contains(pos); }
109 bool covered(FontSpan const & r) const
111 // 1. first of new range inside current range or
112 // 2. last of new range inside current range or
113 // 3. first of current range inside new range or
114 // 4. last of current range inside new range
115 //FIXME: is this the same as !range_.intersect(r).empty() ?
116 return range_.contains(r.first) || range_.contains(r.last) ||
117 r.contains(range_.first) || r.contains(range_.last);
120 void shift(pos_type pos, int offset)
122 if (range_.first > pos) {
123 range_.first += offset;
124 range_.last += offset;
125 } else if (range_.last >= pos) {
126 range_.last += offset;
131 SpellChecker::Result result_ ;
135 /////////////////////////////////////////////////////////////////////
139 /////////////////////////////////////////////////////////////////////
141 class SpellCheckerState {
145 needs_refresh_ = true;
146 current_change_number_ = 0;
149 void setRange(FontSpan const & fp, SpellChecker::Result state)
152 RangesIterator et = ranges_.end();
153 RangesIterator it = ranges_.begin();
154 for (; it != et; ++it) {
155 if (!it->covered(fp))
156 result.push_back(SpellResultRange(it->range(), it->result()));
157 else if (state == SpellChecker::WORD_OK) {
158 // trim or split the current misspelled range
159 // store misspelled ranges only
160 FontSpan range = it->range();
161 if (fp.first > range.first) {
162 // misspelled area in front of WORD_OK
163 range.last = fp.first - 1;
164 result.push_back(SpellResultRange(range, it->result()));
167 if (fp.last < range.last) {
168 // misspelled area after WORD_OK range
169 range.first = fp.last + 1;
170 result.push_back(SpellResultRange(range, it->result()));
175 if (state != SpellChecker::WORD_OK)
176 ranges_.push_back(SpellResultRange(fp, state));
179 void increasePosAfterPos(pos_type pos)
181 correctRangesAfterPos(pos, 1);
185 void decreasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, -1);
191 void refreshLast(pos_type pos)
193 if (pos < refresh_.last)
197 SpellChecker::Result getState(pos_type pos) const
199 SpellChecker::Result result = SpellChecker::WORD_OK;
200 RangesIterator et = ranges_.end();
201 RangesIterator it = ranges_.begin();
202 for (; it != et; ++it) {
203 if(it->contains(pos)) {
210 FontSpan const & getRange(pos_type pos) const
212 /// empty span to indicate mismatch
213 static FontSpan empty_;
214 RangesIterator et = ranges_.end();
215 RangesIterator it = ranges_.begin();
216 for (; it != et; ++it) {
217 if(it->contains(pos)) {
224 bool needsRefresh() const
226 return needs_refresh_;
229 SpellChecker::ChangeNumber currentChangeNumber() const
231 return current_change_number_;
234 void refreshRange(pos_type & first, pos_type & last) const
236 first = refresh_.first;
237 last = refresh_.last;
240 void needsRefresh(pos_type pos)
242 if (needs_refresh_ && pos != -1) {
243 if (pos < refresh_.first)
244 refresh_.first = pos;
245 if (pos > refresh_.last)
247 } else if (pos != -1) {
248 // init request check for neighbour positions too
249 refresh_.first = pos > 0 ? pos - 1 : 0;
250 // no need for special end of paragraph check
251 refresh_.last = pos + 1;
253 needs_refresh_ = pos != -1;
256 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
258 needs_refresh_ = true;
261 current_change_number_ = change_number;
264 typedef vector<SpellResultRange> Ranges;
265 typedef Ranges::const_iterator RangesIterator;
267 /// the area of the paragraph with pending spell check
269 /// spell state cache version number
270 SpellChecker::ChangeNumber current_change_number_;
274 void correctRangesAfterPos(pos_type pos, int offset)
276 RangesIterator et = ranges_.end();
277 Ranges::iterator it = ranges_.begin();
278 for (; it != et; ++it) {
279 it->shift(pos, offset);
285 /////////////////////////////////////////////////////////////////////
287 // Paragraph::Private
289 /////////////////////////////////////////////////////////////////////
291 class Paragraph::Private
293 // Enforce our own "copy" constructor
294 Private(Private const &) = delete;
295 Private & operator=(Private const &) = delete;
296 // Unique ID generator
297 static int make_id();
300 Private(Paragraph * owner, Layout const & layout);
301 /// "Copy constructor"
302 Private(Private const &, Paragraph * owner);
303 /// Copy constructor from \p beg to \p end
304 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
307 void insertChar(pos_type pos, char_type c, Change const & change);
309 /// Output the surrogate pair formed by \p c and \p next to \p os.
310 /// \return the number of characters written.
311 int latexSurrogatePair(BufferParams const &, otexstream & os,
312 char_type c, char_type next,
313 OutputParams const &);
315 /// Output a space in appropriate formatting (or a surrogate pair
316 /// if the next character is a combining character).
317 /// \return whether a surrogate pair was output.
318 bool simpleTeXBlanks(BufferParams const &,
319 OutputParams const &,
322 unsigned int & column,
324 Layout const & style);
326 /// This could go to ParagraphParameters if we want to.
327 int startTeXParParams(BufferParams const &, otexstream &,
328 OutputParams const &) const;
330 /// This could go to ParagraphParameters if we want to.
331 bool endTeXParParams(BufferParams const &, otexstream &,
332 OutputParams const &) const;
335 void latexInset(BufferParams const &,
340 Font const & outerfont,
342 Change & running_change,
343 Layout const & style,
345 unsigned int & column,
346 bool const fontswitch_inset,
347 bool const closeLanguage,
348 bool const lang_switched_at_inset);
351 void latexSpecialChar(
353 BufferParams const & bparams,
354 OutputParams const & runparams,
355 Font const & running_font,
356 string & alien_script,
357 Layout const & style,
360 unsigned int & column);
367 unsigned int & column);
373 unsigned int & column);
379 unsigned int & column);
382 void validate(LaTeXFeatures & features) const;
384 /// Checks if the paragraph contains only text and no inset or font change.
385 bool onlyText(Buffer const & buf, Font const & outerfont,
386 pos_type initial) const;
388 /// a vector of speller skip positions
389 typedef vector<FontSpan> SkipPositions;
390 typedef SkipPositions::const_iterator SkipPositionsIterator;
392 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
394 Language * getSpellLanguage(pos_type const from) const;
396 Language * locateSpellRange(pos_type & from, pos_type & to,
397 SkipPositions & skips) const;
399 bool hasSpellerChange() const
401 SpellChecker::ChangeNumber speller_change_number = 0;
402 if (theSpellChecker())
403 speller_change_number = theSpellChecker()->changeNumber();
404 return speller_change_number > speller_state_.currentChangeNumber();
407 bool ignoreWord(docstring const & word) const ;
409 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
411 pos_type textsize = owner_->size();
412 // check for sane arguments
413 if (to <= from || from >= textsize)
415 FontSpan fp = FontSpan(from, to - 1);
416 speller_state_.setRange(fp, state);
419 void requestSpellCheck(pos_type pos)
422 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
424 speller_state_.needsRefresh(pos);
427 void readySpellCheck()
429 speller_state_.needsRefresh(-1);
432 bool needsSpellCheck() const
434 return speller_state_.needsRefresh();
437 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
439 speller_state_.refreshRange(first, last);
441 last = owner_->size();
444 pos_type endpos = last;
445 owner_->locateWord(first, endpos, WHOLE_WORD, true);
448 owner_->locateWord(last, endpos, WHOLE_WORD, true);
453 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
457 while (it != et && it->first < start) {
458 long skip = it->last - it->first + 1;
466 void markMisspelledWords(pos_type const & first, pos_type const & last,
467 SpellChecker::Result result,
468 docstring const & word,
469 SkipPositions const & skips);
471 InsetCode ownerCode() const
473 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
476 /// Which Paragraph owns us?
480 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<string, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
514 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
515 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
522 int Paragraph::Private::make_id()
524 // The id is unique per session across buffers because it is used in
525 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
528 static int next_id(0);
533 Paragraph::Private::Private(Private const & p, Paragraph * owner)
534 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
535 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
536 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
537 layout_(p.layout_), id_(make_id())
539 requestSpellCheck(p.text_.size());
543 Paragraph::Private::Private(Private const & p, Paragraph * owner,
544 pos_type beg, pos_type end)
545 : owner_(owner), inset_owner_(p.inset_owner_),
546 params_(p.params_), changes_(p.changes_),
547 insetlist_(p.insetlist_, beg, end),
548 begin_of_body_(p.begin_of_body_), words_(p.words_),
549 layout_(p.layout_), id_(make_id())
551 if (beg >= pos_type(p.text_.size()))
553 text_ = p.text_.substr(beg, end - beg);
555 FontList::const_iterator fcit = fontlist_.begin();
556 FontList::const_iterator fend = fontlist_.end();
557 for (; fcit != fend; ++fcit) {
558 if (fcit->pos() < beg)
560 if (fcit->pos() >= end) {
561 // Add last entry in the fontlist_.
562 fontlist_.set(text_.size() - 1, fcit->font());
565 // Add a new entry in the fontlist_.
566 fontlist_.set(fcit->pos() - beg, fcit->font());
568 requestSpellCheck(p.text_.size());
572 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
573 bool output_active, TocBackend & backend) const
575 d->changes_.addToToc(cdit, buf, output_active, backend);
579 bool Paragraph::isDeleted(pos_type start, pos_type end) const
581 LASSERT(start >= 0 && start <= size(), return false);
582 LASSERT(end > start && end <= size() + 1, return false);
584 return d->changes_.isDeleted(start, end);
588 bool Paragraph::isChanged(pos_type start, pos_type end) const
590 LASSERT(start >= 0 && start <= size(), return false);
591 LASSERT(end > start && end <= size() + 1, return false);
593 return d->changes_.isChanged(start, end);
596 // FIXME: Ideally the diverse isChanged() methods should account for that!
597 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
599 LASSERT(start >= 0 && start <= size(), return false);
600 LASSERT(end > start && end <= size() + 1, return false);
602 for (auto const & icit : d->insetlist_) {
603 if (icit.pos < start)
607 if (icit.inset && icit.inset->isChanged())
613 bool Paragraph::isChanged() const
615 return d->changes_.isChanged();
619 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
621 // keep the logic here in sync with the logic of eraseChars()
625 Change const & change = d->changes_.lookup(size());
626 return change.inserted() && change.currentAuthor();
629 Change Paragraph::parEndChange() const
631 return d->changes_.lookup(size());
635 void Paragraph::setChange(Change const & change)
637 // beware of the imaginary end-of-par character!
638 d->changes_.set(change, 0, size() + 1);
641 * Propagate the change recursively - but not in case of DELETED!
643 * Imagine that your co-author makes changes in an existing inset. He
644 * sends your document to you and you come to the conclusion that the
645 * inset should go completely. If you erase it, LyX must not delete all
646 * text within the inset. Otherwise, the change tracked insertions of
647 * your co-author get lost and there is no way to restore them later.
649 * Conclusion: An inset's content should remain untouched if you delete it
652 if (!change.deleted()) {
653 for (pos_type pos = 0; pos < size(); ++pos) {
654 if (Inset * inset = getInset(pos))
655 inset->setChange(change);
661 void Paragraph::setChange(pos_type pos, Change const & change)
663 LASSERT(pos >= 0 && pos <= size(), return);
664 d->changes_.set(change, pos);
666 // see comment in setChange(Change const &) above
667 if (!change.deleted() && pos < size())
668 if (Inset * inset = getInset(pos))
669 inset->setChange(change);
673 Change const & Paragraph::lookupChange(pos_type pos) const
675 LBUFERR(pos >= 0 && pos <= size());
676 return d->changes_.lookup(pos);
680 void Paragraph::acceptChanges(pos_type start, pos_type end)
682 LASSERT(start >= 0 && start <= size(), return);
683 LASSERT(end > start && end <= size() + 1, return);
685 for (pos_type pos = start; pos < end; ++pos) {
686 switch (lookupChange(pos).type) {
687 case Change::UNCHANGED:
688 // accept changes in nested inset
689 if (Inset * inset = getInset(pos))
690 inset->acceptChanges();
693 case Change::INSERTED:
694 d->changes_.set(Change(Change::UNCHANGED), pos);
695 // also accept changes in nested inset
696 if (Inset * inset = getInset(pos))
697 inset->acceptChanges();
700 case Change::DELETED:
701 // Suppress access to non-existent
702 // "end-of-paragraph char"
704 eraseChar(pos, false);
715 void Paragraph::rejectChanges(pos_type start, pos_type end)
717 LASSERT(start >= 0 && start <= size(), return);
718 LASSERT(end > start && end <= size() + 1, return);
720 for (pos_type pos = start; pos < end; ++pos) {
721 switch (lookupChange(pos).type) {
722 case Change::UNCHANGED:
723 // reject changes in nested inset
724 if (Inset * inset = getInset(pos))
725 inset->rejectChanges();
728 case Change::INSERTED:
729 // Suppress access to non-existent
730 // "end-of-paragraph char"
732 eraseChar(pos, false);
738 case Change::DELETED:
739 d->changes_.set(Change(Change::UNCHANGED), pos);
741 // Do NOT reject changes within a deleted inset!
742 // There may be insertions of a co-author inside of it!
750 void Paragraph::Private::insertChar(pos_type pos, char_type c,
751 Change const & change)
753 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
756 changes_.insert(change, pos);
758 // This is actually very common when parsing buffers (and
759 // maybe inserting ascii text)
760 if (pos == pos_type(text_.size())) {
761 // when appending characters, no need to update tables
763 // but we want spell checking
764 requestSpellCheck(pos);
768 text_.insert(text_.begin() + pos, c);
770 // Update the font table.
771 fontlist_.increasePosAfterPos(pos);
774 insetlist_.increasePosAfterPos(pos);
776 // Update list of misspelled positions
777 speller_state_.increasePosAfterPos(pos);
781 bool Paragraph::insertInset(pos_type pos, Inset * inset,
782 Font const & font, Change const & change)
784 LASSERT(inset, return false);
785 LASSERT(pos >= 0 && pos <= size(), return false);
787 // Paragraph::insertInset() can be used in cut/copy/paste operation where
788 // d->inset_owner_ is not set yet.
789 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
792 d->insertChar(pos, META_INSET, change);
793 LASSERT(d->text_[pos] == META_INSET, return false);
795 // Add a new entry in the insetlist_.
796 d->insetlist_.insert(inset, pos);
798 // Some insets require run of spell checker
799 requestSpellCheck(pos);
805 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
807 LASSERT(pos >= 0 && pos <= size(), return false);
809 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
812 Change change = d->changes_.lookup(pos);
814 // set the character to DELETED if
815 // a) it was previously unchanged or
816 // b) it was inserted by a co-author
818 if (!change.changed() ||
819 (change.inserted() && !change.currentAuthor())) {
820 setChange(pos, Change(Change::DELETED));
821 // request run of spell checker
822 requestSpellCheck(pos);
826 if (change.deleted())
830 // Don't physically access the imaginary end-of-paragraph character.
831 // eraseChar() can only mark it as DELETED. A physical deletion of
832 // end-of-par must be handled externally.
838 d->changes_.erase(pos);
840 // if it is an inset, delete the inset entry
841 if (d->text_[pos] == META_INSET)
842 d->insetlist_.erase(pos);
844 d->text_.erase(d->text_.begin() + pos);
846 // Update the fontlist_
847 d->fontlist_.erase(pos);
849 // Update the insetlist_
850 d->insetlist_.decreasePosAfterPos(pos);
852 // Update list of misspelled positions
853 d->speller_state_.decreasePosAfterPos(pos);
854 d->speller_state_.refreshLast(size());
860 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
862 LASSERT(start >= 0 && start <= size(), return 0);
863 LASSERT(end >= start && end <= size() + 1, return 0);
866 for (pos_type count = end - start; count; --count) {
867 if (!eraseChar(i, trackChanges))
873 // Handle combining characters
874 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
875 otexstream & os, char_type c, char_type next,
876 OutputParams const & runparams)
878 // Writing next here may circumvent a possible font change between
879 // c and next. Since next is only output if it forms a surrogate pair
880 // with c we can ignore this:
881 // A font change inside a surrogate pair does not make sense and is
882 // hopefully impossible to input.
883 // FIXME: change tracking
884 // Is this correct WRT change tracking?
885 Encoding const & encoding = *(runparams.encoding);
886 docstring latex1 = encoding.latexChar(next).first;
887 if (runparams.inIPA) {
888 string const tipashortcut = Encodings::TIPAShortcut(next);
889 if (!tipashortcut.empty()) {
890 latex1 = from_ascii(tipashortcut);
893 docstring latex2 = encoding.latexChar(c).first;
895 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
896 // Encoding supports the combination:
897 // output as is (combining char after base char).
898 os << latex2 << latex1;
899 return latex1.length() + latex2.length();
902 os << latex1 << "{" << latex2 << "}";
903 return latex1.length() + latex2.length() + 2;
907 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
908 OutputParams const & runparams,
911 unsigned int & column,
913 Layout const & style)
915 if (style.pass_thru || runparams.pass_thru)
918 if (i + 1 < int(text_.size())) {
919 char_type next = text_[i + 1];
920 if (Encodings::isCombiningChar(next)) {
921 // This space has an accent, so we must always output it.
922 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
927 if (runparams.linelen > 0
928 && column > runparams.linelen
930 && text_[i - 1] != ' '
931 && (i + 1 < int(text_.size()))
932 // same in FreeSpacing mode
933 && !owner_->isFreeSpacing()
934 // In typewriter mode, we want to avoid
935 // ! . ? : at the end of a line
936 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
937 && (text_[i - 1] == '.'
938 || text_[i - 1] == '?'
939 || text_[i - 1] == ':'
940 || text_[i - 1] == '!'))) {
942 os.texrow().start(owner_->id(), i + 1);
944 } else if (style.free_spacing) {
953 void Paragraph::Private::latexInset(BufferParams const & bparams,
955 OutputParams & runparams,
958 Font const & outerfont,
960 Change & running_change,
961 Layout const & style,
963 unsigned int & column,
964 bool const fontswitch_inset,
965 bool const closeLanguage,
966 bool const lang_switched_at_inset)
968 Inset * inset = owner_->getInset(i);
971 if (style.pass_thru) {
972 odocstringstream ods;
973 inset->plaintext(ods, runparams);
978 // FIXME: move this to InsetNewline::latex
979 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
980 // newlines are handled differently here than
981 // the default in simpleTeXSpecialChars().
982 if (!style.newline_allowed) {
986 bool needPar = false;
987 column += running_font.latexWriteEndChanges(
988 os, bparams, runparams,
989 basefont, basefont, needPar);
993 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
996 basefont = owner_->getLayoutFont(bparams, outerfont);
997 running_font = basefont;
999 if (runparams.moving_arg)
1003 os.texrow().start(owner_->id(), i + 1);
1007 if (owner_->isDeleted(i)) {
1008 if( ++runparams.inDeletedInset == 1)
1009 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1012 if (inset->canTrackChanges()) {
1013 column += Changes::latexMarkChange(os, bparams, running_change,
1014 Change(Change::UNCHANGED), runparams);
1015 running_change = Change(Change::UNCHANGED);
1019 odocstream::pos_type const len = os.os().tellp();
1021 if (inset->forceLTR(runparams)
1022 && running_font.isRightToLeft()
1023 // ERT is an exception, it should be output with no
1024 // decorations at all
1025 && inset->lyxCode() != ERT_CODE) {
1026 if (runparams.use_polyglossia) {
1028 } else if (running_font.language()->lang() == "farsi"
1029 || running_font.language()->lang() == "arabic_arabi")
1030 os << "\\textLR{" << termcmd;
1036 if (open_font && fontswitch_inset) {
1037 bool lang_closed = false;
1038 // Close language if needed
1039 if (closeLanguage && !lang_switched_at_inset) {
1040 // We need prev_font here as language changes directly at inset
1041 // will only be started inside the inset.
1042 Font const prev_font = (i > 0) ?
1043 owner_->getFont(bparams, i - 1, outerfont)
1045 Font tmpfont(basefont);
1046 tmpfont.setLanguage(prev_font.language());
1047 bool needPar = false;
1048 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1050 needPar, closeLanguage);
1052 lang_closed = count > 0;
1054 // Update the running_font, making sure, however,
1055 // to leave the language as it was.
1056 // FIXME: probably a better way to keep track of the old
1057 // language, than copying the entire font?
1058 Font const copy_font(running_font);
1059 basefont = owner_->getLayoutFont(bparams, outerfont);
1060 running_font = basefont;
1062 running_font.setLanguage(copy_font.language());
1063 OutputParams rp = runparams;
1064 rp.encoding = basefont.language()->encoding();
1065 // For these, we use switches, so they should be taken as
1066 // base inside the inset.
1067 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1068 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1069 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1070 // Now re-do font changes in a way needed here
1071 // (using switches with multi-par insets)
1072 InsetText const * textinset = inset->asInsetText();
1073 bool const cprotect = textinset
1074 ? textinset->hasCProtectContent(runparams.moving_arg)
1075 && !textinset->text().isMainText()
1077 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1083 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1087 runparams.local_font = &basefont;
1090 if (fontswitch_inset && !closeLanguage && fontswitch_inset) {
1091 // The directionality has been switched at inset.
1092 // Force markup inside.
1093 runparams.local_font = &basefont;
1096 size_t const previous_row_count = os.texrow().rows();
1099 runparams.lastid = id_;
1100 runparams.lastpos = i;
1101 inset->latex(os, runparams);
1102 } catch (EncodingException & e) {
1103 // add location information and throw again.
1112 if (os.texrow().rows() > previous_row_count) {
1113 os.texrow().start(owner_->id(), i + 1);
1116 column += (unsigned int)(os.os().tellp() - len);
1119 if (owner_->isDeleted(i))
1120 --runparams.inDeletedInset;
1124 void Paragraph::Private::latexSpecialChar(otexstream & os,
1125 BufferParams const & bparams,
1126 OutputParams const & runparams,
1127 Font const & running_font,
1128 string & alien_script,
1129 Layout const & style,
1132 unsigned int & column)
1134 char_type const c = owner_->getUChar(bparams, runparams, i);
1136 if (style.pass_thru || runparams.pass_thru
1137 || contains(style.pass_thru_chars, c)
1138 || contains(runparams.pass_thru_chars, c)) {
1140 Encoding const * const enc = runparams.encoding;
1141 if (enc && !enc->encodable(c))
1142 throw EncodingException(c);
1148 // TIPA uses its own T3 encoding
1149 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1151 // If T1 font encoding is used, use the special
1152 // characters it provides.
1153 // NOTE: Some languages reset the font encoding internally to a
1154 // non-standard font encoding. If we are using such a language,
1155 // we do not output special T1 chars.
1156 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1157 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1158 && latexSpecialT1(c, os, i, column))
1160 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1161 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1162 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1165 // Otherwise, we use what LaTeX provides us.
1168 os << "\\textbackslash" << termcmd;
1172 os << "\\textless" << termcmd;
1176 os << "\\textgreater" << termcmd;
1180 os << "\\textbar" << termcmd;
1185 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1186 (end_pos == -1 || i + 1 < end_pos) &&
1187 text_[i+1] == '-') {
1188 // Prevent "--" becoming an en dash and "---" an em dash.
1189 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1195 os << "\\textquotedbl" << termcmd;
1200 case '%': case '#': case '{':
1208 os << "\\textasciitilde" << termcmd;
1213 os << "\\textasciicircum" << termcmd;
1220 // avoid being mistaken for optional arguments
1228 // Blanks are printed before font switching.
1229 // Sure? I am not! (try nice-latex)
1230 // I am sure it's correct. LyX might be smarter
1231 // in the future, but for now, nothing wrong is
1237 // XeTeX's dash behaviour is determined via a global setting
1238 if (bparams.use_dash_ligatures
1239 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1241 // TODO #10961: && not in inset Flex Code
1242 // TODO #10961: && not in layout LyXCode
1243 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1260 Encoding const & encoding = *(runparams.encoding);
1261 char_type next = '\0';
1262 if (i + 1 < int(text_.size())) {
1263 next = text_[i + 1];
1264 if (Encodings::isCombiningChar(next)) {
1265 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1270 pair<docstring, bool> latex = encoding.latexChar(c);
1271 docstring nextlatex;
1272 bool nexttipas = false;
1273 string nexttipashortcut;
1274 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1275 nextlatex = encoding.latexChar(next).first;
1276 if (runparams.inIPA) {
1277 nexttipashortcut = Encodings::TIPAShortcut(next);
1278 nexttipas = !nexttipashortcut.empty();
1282 if (runparams.inIPA) {
1283 string const tipashortcut = Encodings::TIPAShortcut(c);
1284 if (!tipashortcut.empty()) {
1285 latex.first = from_ascii(tipashortcut);
1286 latex.second = false;
1290 // eventually close "script wrapper" command (see `Paragraph::latex`)
1291 if (!alien_script.empty()
1292 && alien_script != Encodings::isKnownScriptChar(next)) {
1293 column += latex.first.length();
1294 alien_script.clear();
1295 os << latex.first << "}";
1299 && ((!prefixIs(nextlatex, '\\')
1300 && !prefixIs(nextlatex, '{')
1301 && !prefixIs(nextlatex, '}'))
1303 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1305 // Prevent eating of a following space or command corruption by
1306 // following characters
1307 if (next == ' ' || next == '\0') {
1308 column += latex.first.length() + 1;
1309 os << latex.first << "{}";
1311 column += latex.first.length();
1312 os << latex.first << " ";
1315 column += latex.first.length() - 1;
1323 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1324 pos_type i, unsigned int & column)
1330 // In T1 encoding, these characters exist
1331 // but we should avoid ligatures
1332 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1334 os << "\\textcompwordmark" << termcmd;
1341 // soul.sty breaks with \char`\"
1342 os << "\\textquotedbl" << termcmd;
1351 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1352 pos_type i, unsigned int & column)
1354 // TU encoding is currently on par with T1.
1355 return latexSpecialT1(c, os, i, column);
1359 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1360 pos_type /*i*/, unsigned int & column)
1370 os << "\\textvertline" << termcmd;
1379 void Paragraph::Private::validate(LaTeXFeatures & features) const
1381 if (layout_->inpreamble && inset_owner_) {
1382 // FIXME: Using a string stream here circumvents the encoding
1383 // switching machinery of odocstream. Therefore the
1384 // output is wrong if this paragraph contains content
1385 // that needs to switch encoding.
1386 Buffer const & buf = inset_owner_->buffer();
1387 otexstringstream os;
1388 os << layout_->preamble();
1389 size_t const length = os.length();
1390 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1391 buf.getParFromID(owner_->id()).pit(), os,
1392 features.runparams(), string(), 0, -1, true);
1393 if (os.length() > length)
1394 features.addPreambleSnippet(os.release(), true);
1397 if (features.runparams().flavor == OutputParams::HTML
1398 && layout_->htmltitle()) {
1399 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1402 // check the params.
1403 if (!params_.spacing().isDefault())
1404 features.require("setspace");
1407 features.useLayout(layout_->name());
1410 fontlist_.validate(features);
1412 // then the indentation
1413 if (!params_.leftIndent().zero())
1414 features.require("ParagraphLeftIndent");
1417 InsetList::const_iterator icit = insetlist_.begin();
1418 InsetList::const_iterator iend = insetlist_.end();
1419 for (; icit != iend; ++icit) {
1421 features.inDeletedInset(owner_->isDeleted(icit->pos));
1422 if (icit->inset->lyxCode() == FOOT_CODE) {
1423 // FIXME: an item inset would make things much easier.
1424 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1425 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1426 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1427 && (icit->pos < begin_of_body_
1428 || (icit->pos == begin_of_body_
1429 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1430 features.saveNoteEnv("description");
1432 icit->inset->validate(features);
1433 features.inDeletedInset(false);
1434 if (layout_->needprotect &&
1435 icit->inset->lyxCode() == FOOT_CODE)
1436 features.require("NeedLyXFootnoteCode");
1440 // then the contents
1441 BufferParams const bp = features.runparams().is_child
1442 ? features.buffer().masterParams() : features.buffer().params();
1443 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1444 char_type c = text_[i];
1445 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1447 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1448 features.require("textquotedblp");
1449 else if (bp.main_font_encoding() != "T1"
1450 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1451 features.require("textquotedbl");
1452 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1453 // features that depend on the font or input encoding
1454 string feats = ci.textpreamble();
1455 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1456 if (fontenc.empty())
1457 fontenc = features.runparams().main_fontenc;
1458 while (!feats.empty()) {
1460 feats = split(feats, feat, ',');
1461 if (contains(feat, "!=")) {
1462 // a feature that is required except for the spcified
1463 // font or input encodings
1465 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1466 // multiple encodings are separated by semicolon
1467 vector<string> context = getVectorFromString(contexts, ";");
1468 // require feature if the context matches neither current font
1469 // nor input encoding
1470 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1471 && std::find(context.begin(), context.end(),
1472 features.runparams().encoding->name()) == context.end())
1473 features.require(realfeature);
1474 } else if (contains(feat, '=')) {
1475 // a feature that is required only for the spcified
1476 // font or input encodings
1478 string const contexts = split(feat, realfeature, '=');
1479 // multiple encodings are separated by semicolon
1480 vector<string> context = getVectorFromString(contexts, ";");
1481 // require feature if the context matches either current font
1482 // or input encoding
1483 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1484 || std::find(context.begin(), context.end(),
1485 features.runparams().encoding->name()) != context.end())
1486 features.require(realfeature);
1489 } else if (!bp.use_dash_ligatures
1490 && (c == 0x2013 || c == 0x2014)
1491 && bp.useNonTeXFonts
1492 && features.runparams().flavor == OutputParams::XETEX)
1493 // XeTeX's dash behaviour is determined via a global setting
1494 features.require("xetexdashbreakstate");
1495 BufferEncodings::validate(c, features);
1499 /////////////////////////////////////////////////////////////////////
1503 /////////////////////////////////////////////////////////////////////
1506 Layout const emptyParagraphLayout;
1509 Paragraph::Paragraph()
1510 : d(new Paragraph::Private(this, emptyParagraphLayout))
1517 Paragraph::Paragraph(Paragraph const & par)
1518 : itemdepth(par.itemdepth),
1519 d(new Paragraph::Private(*par.d, this))
1525 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1526 : itemdepth(par.itemdepth),
1527 d(new Paragraph::Private(*par.d, this, beg, end))
1533 Paragraph & Paragraph::operator=(Paragraph const & par)
1535 // needed as we will destroy the private part before copying it
1537 itemdepth = par.itemdepth;
1541 d = new Private(*par.d, this);
1548 Paragraph::~Paragraph()
1557 // this shall be called just before every "os << ..." action.
1558 void flushString(ostream & os, docstring & s)
1567 void Paragraph::write(ostream & os, BufferParams const & bparams,
1568 depth_type & dth) const
1570 // The beginning or end of a deeper (i.e. nested) area?
1571 if (dth != d->params_.depth()) {
1572 if (d->params_.depth() > dth) {
1573 while (d->params_.depth() > dth) {
1574 os << "\n\\begin_deeper";
1578 while (d->params_.depth() < dth) {
1579 os << "\n\\end_deeper";
1585 // First write the layout
1586 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1588 d->params_.write(os);
1590 Font font1(inherit_font, bparams.language);
1592 Change running_change = Change(Change::UNCHANGED);
1594 // this string is used as a buffer to avoid repetitive calls
1595 // to to_utf8(), which turn out to be expensive (JMarc)
1596 docstring write_buffer;
1599 for (pos_type i = 0; i <= size(); ++i) {
1601 Change const & change = lookupChange(i);
1602 if (change != running_change)
1603 flushString(os, write_buffer);
1604 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1605 running_change = change;
1610 // Write font changes
1611 Font font2 = getFontSettings(bparams, i);
1612 if (font2 != font1) {
1613 flushString(os, write_buffer);
1614 font2.lyxWriteChanges(font1, os);
1619 char_type const c = d->text_[i];
1622 if (Inset const * inset = getInset(i)) {
1623 flushString(os, write_buffer);
1624 if (inset->directWrite()) {
1625 // international char, let it write
1626 // code directly so it's shorter in
1632 os << "\\begin_inset ";
1634 os << "\n\\end_inset\n\n";
1637 // FIXME This can be removed again once the mystery
1638 // crash has been resolved.
1643 flushString(os, write_buffer);
1644 os << "\n\\backslash\n";
1648 flushString(os, write_buffer);
1649 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1656 if ((column > 70 && c == ' ')
1658 flushString(os, write_buffer);
1662 // this check is to amend a bug. LyX sometimes
1663 // inserts '\0' this could cause problems.
1665 write_buffer.push_back(c);
1667 LYXERR0("NUL char in structure.");
1673 flushString(os, write_buffer);
1674 os << "\n\\end_layout\n";
1675 // FIXME This can be removed again once the mystery
1676 // crash has been resolved.
1681 void Paragraph::validate(LaTeXFeatures & features) const
1683 d->validate(features);
1684 bool fragile = features.runparams().moving_arg;
1685 fragile |= layout().needprotect;
1686 if (inInset().getLayout().isNeedProtect())
1688 if (needsCProtection(fragile))
1689 features.require("cprotect");
1693 void Paragraph::insert(pos_type start, docstring const & str,
1694 Font const & font, Change const & change)
1696 for (size_t i = 0, n = str.size(); i != n ; ++i)
1697 insertChar(start + i, str[i], font, change);
1701 void Paragraph::appendChar(char_type c, Font const & font,
1702 Change const & change)
1705 d->changes_.insert(change, d->text_.size());
1706 // when appending characters, no need to update tables
1707 d->text_.push_back(c);
1708 setFont(d->text_.size() - 1, font);
1709 d->requestSpellCheck(d->text_.size() - 1);
1713 void Paragraph::appendString(docstring const & s, Font const & font,
1714 Change const & change)
1716 pos_type end = s.size();
1717 size_t oldsize = d->text_.size();
1718 size_t newsize = oldsize + end;
1719 size_t capacity = d->text_.capacity();
1720 if (newsize >= capacity)
1721 d->text_.reserve(max(capacity + 100, newsize));
1723 // when appending characters, no need to update tables
1726 // FIXME: Optimize this!
1727 for (size_t i = oldsize; i != newsize; ++i) {
1729 d->changes_.insert(change, i);
1730 d->requestSpellCheck(i);
1732 d->fontlist_.set(oldsize, font);
1733 d->fontlist_.set(newsize - 1, font);
1737 void Paragraph::insertChar(pos_type pos, char_type c,
1740 d->insertChar(pos, c, Change(trackChanges ?
1741 Change::INSERTED : Change::UNCHANGED));
1745 void Paragraph::insertChar(pos_type pos, char_type c,
1746 Font const & font, bool trackChanges)
1748 d->insertChar(pos, c, Change(trackChanges ?
1749 Change::INSERTED : Change::UNCHANGED));
1754 void Paragraph::insertChar(pos_type pos, char_type c,
1755 Font const & font, Change const & change)
1757 d->insertChar(pos, c, change);
1762 void Paragraph::resetFonts(Font const & font)
1764 d->fontlist_.clear();
1765 d->fontlist_.set(0, font);
1766 d->fontlist_.set(d->text_.size() - 1, font);
1769 // Gets uninstantiated font setting at position.
1770 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1774 LYXERR0("pos: " << pos << " size: " << size());
1778 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1779 if (cit != d->fontlist_.end())
1782 if (pos == size() && !empty())
1783 return getFontSettings(bparams, pos - 1);
1785 // Optimisation: avoid a full font instantiation if there is no
1786 // language change from previous call.
1787 static Font previous_font;
1788 static Language const * previous_lang = nullptr;
1789 Language const * lang = getParLanguage(bparams);
1790 if (lang != previous_lang) {
1791 previous_lang = lang;
1792 previous_font = Font(inherit_font, lang);
1794 return previous_font;
1798 FontSpan Paragraph::fontSpan(pos_type pos) const
1800 LBUFERR(pos <= size());
1803 return FontSpan(pos, pos);
1806 FontList::const_iterator cit = d->fontlist_.begin();
1807 FontList::const_iterator end = d->fontlist_.end();
1808 for (; cit != end; ++cit) {
1809 if (cit->pos() >= pos) {
1810 if (pos >= beginOfBody())
1811 return FontSpan(max(start, beginOfBody()),
1814 return FontSpan(start,
1815 min(beginOfBody() - 1,
1818 start = cit->pos() + 1;
1821 // This should not happen, but if so, we take no chances.
1822 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1823 LASSERT(false, return FontSpan(pos, pos));
1827 // Gets uninstantiated font setting at position 0
1828 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1830 if (!empty() && !d->fontlist_.empty())
1831 return d->fontlist_.begin()->font();
1833 // Optimisation: avoid a full font instantiation if there is no
1834 // language change from previous call.
1835 static Font previous_font;
1836 static Language const * previous_lang = nullptr;
1837 if (bparams.language != previous_lang) {
1838 previous_lang = bparams.language;
1839 previous_font = Font(inherit_font, bparams.language);
1842 return previous_font;
1846 // Gets the fully instantiated font at a given position in a paragraph
1847 // This is basically the same function as Text::GetFont() in text2.cpp.
1848 // The difference is that this one is used for generating the LaTeX file,
1849 // and thus cosmetic "improvements" are disallowed: This has to deliver
1850 // the true picture of the buffer. (Asger)
1851 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1852 Font const & outerfont) const
1856 Font font = getFontSettings(bparams, pos);
1858 pos_type const body_pos = beginOfBody();
1859 FontInfo & fi = font.fontInfo();
1861 fi.realize(d->layout_->labelfont);
1863 fi.realize(d->layout_->font);
1865 fi.realize(outerfont.fontInfo());
1866 fi.realize(bparams.getFont().fontInfo());
1872 Font const Paragraph::getLabelFont
1873 (BufferParams const & bparams, Font const & outerfont) const
1875 FontInfo tmpfont = d->layout_->labelfont;
1876 tmpfont.realize(outerfont.fontInfo());
1877 tmpfont.realize(bparams.getFont().fontInfo());
1878 return Font(tmpfont, getParLanguage(bparams));
1882 Font const Paragraph::getLayoutFont
1883 (BufferParams const & bparams, Font const & outerfont) const
1885 FontInfo tmpfont = d->layout_->font;
1886 tmpfont.realize(outerfont.fontInfo());
1887 tmpfont.realize(bparams.getFont().fontInfo());
1888 return Font(tmpfont, getParLanguage(bparams));
1892 char_type Paragraph::getUChar(BufferParams const & bparams,
1893 OutputParams const & rp,
1896 char_type c = d->text_[pos];
1898 // Return unchanged character in LTR languages
1899 // or if we use poylglossia/bidi (XeTeX).
1900 if (rp.useBidiPackage()
1901 || !getFontSettings(bparams, pos).isRightToLeft())
1904 // Without polyglossia/bidi, we need to account for some special cases.
1905 // FIXME This needs to be audited!
1907 // * The input is as expected for all delimiters
1908 // => checked for Hebrew!
1909 // * The output matches the display in the LyX workarea
1910 // => checked for Hebrew!
1911 // * The special cases below are really necessary
1912 // => checked for Hebrew!
1913 // * In arabic_arabi, brackets are transformed to Arabic
1914 // Ornate Parentheses. Is this is really wanted?
1916 string const & lang = getFontSettings(bparams, pos).language()->lang();
1919 // 1. In the following languages, parentheses need to be reversed.
1920 // Also with polyglodia/luabidi
1921 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1923 // 2. In the following languages, brackets don't need to be reversed.
1924 bool const reversebrackets = lang != "arabic_arabtex"
1925 && lang != "arabic_arabi"
1928 // Now swap delimiters if needed.
1939 if (reversebrackets)
1943 if (reversebrackets)
1964 void Paragraph::setFont(pos_type pos, Font const & font)
1966 LASSERT(pos <= size(), return);
1968 // First, reduce font against layout/label font
1969 // Update: The setCharFont() routine in text2.cpp already
1970 // reduces font, so we don't need to do that here. (Asger)
1972 d->fontlist_.set(pos, font);
1976 void Paragraph::makeSameLayout(Paragraph const & par)
1978 d->layout_ = par.d->layout_;
1979 d->params_ = par.d->params_;
1983 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1985 if (isFreeSpacing())
1991 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1992 if (eraseChar(pos, trackChanges))
1998 return count > 0 || pos > 0;
2002 bool Paragraph::hasSameLayout(Paragraph const & par) const
2004 return par.d->layout_ == d->layout_
2005 && d->params_.sameLayout(par.d->params_);
2009 depth_type Paragraph::getDepth() const
2011 return d->params_.depth();
2015 depth_type Paragraph::getMaxDepthAfter() const
2017 if (d->layout_->isEnvironment())
2018 return d->params_.depth() + 1;
2020 return d->params_.depth();
2024 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2026 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2027 return getDefaultAlign(bparams);
2029 return d->params_.align();
2033 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2035 LyXAlignment res = layout().align;
2036 if (isRTL(bparams)) {
2038 if (res == LYX_ALIGN_LEFT)
2039 res = LYX_ALIGN_RIGHT;
2040 else if (res == LYX_ALIGN_RIGHT)
2041 res = LYX_ALIGN_LEFT;
2047 docstring const & Paragraph::labelString() const
2049 return d->params_.labelString();
2053 // the next two functions are for the manual labels
2054 docstring const Paragraph::getLabelWidthString() const
2056 if (d->layout_->margintype == MARGIN_MANUAL
2057 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2058 return d->params_.labelWidthString();
2060 return _("Senseless with this layout!");
2064 void Paragraph::setLabelWidthString(docstring const & s)
2066 d->params_.labelWidthString(s);
2070 docstring Paragraph::expandLabel(Layout const & layout,
2071 BufferParams const & bparams) const
2073 return expandParagraphLabel(layout, bparams, true);
2077 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2078 BufferParams const & bparams, bool process_appendix) const
2080 DocumentClass const & tclass = bparams.documentClass();
2081 string const & lang = getParLanguage(bparams)->code();
2082 bool const in_appendix = process_appendix && d->params_.appendix();
2083 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2085 if (fmt.empty() && !layout.counter.empty())
2086 return tclass.counters().theCounter(layout.counter, lang);
2088 // handle 'inherited level parts' in 'fmt',
2089 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2090 size_t const i = fmt.find('@', 0);
2091 if (i != docstring::npos) {
2092 size_t const j = fmt.find('@', i + 1);
2093 if (j != docstring::npos) {
2094 docstring parent(fmt, i + 1, j - i - 1);
2095 docstring label = from_ascii("??");
2096 if (tclass.hasLayout(parent))
2097 label = expandParagraphLabel(tclass[parent], bparams,
2099 fmt = docstring(fmt, 0, i) + label
2100 + docstring(fmt, j + 1, docstring::npos);
2104 return tclass.counters().counterLabel(fmt, lang);
2108 void Paragraph::applyLayout(Layout const & new_layout)
2110 d->layout_ = &new_layout;
2111 LyXAlignment const oldAlign = d->params_.align();
2113 if (!(oldAlign & d->layout_->alignpossible)) {
2114 frontend::Alert::warning(_("Alignment not permitted"),
2115 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2116 d->params_.align(LYX_ALIGN_LAYOUT);
2121 pos_type Paragraph::beginOfBody() const
2123 return d->begin_of_body_;
2127 void Paragraph::setBeginOfBody()
2129 if (d->layout_->labeltype != LABEL_MANUAL) {
2130 d->begin_of_body_ = 0;
2134 // Unroll the first two cycles of the loop
2135 // and remember the previous character to
2136 // remove unnecessary getChar() calls
2138 pos_type end = size();
2139 bool prev_char_deleted = false;
2140 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2143 char_type previous_char = d->text_[i];
2144 if (!(isNewline(i) || isEnvSeparator(i))) {
2146 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2147 char_type temp = d->text_[i];
2148 prev_char_deleted = isDeleted(i);
2149 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2152 previous_char = temp;
2158 d->begin_of_body_ = i;
2162 bool Paragraph::allowParagraphCustomization() const
2164 return inInset().allowParagraphCustomization();
2168 bool Paragraph::usePlainLayout() const
2170 return inInset().usePlainLayout();
2174 bool Paragraph::isPassThru() const
2176 return inInset().isPassThru() || d->layout_->pass_thru;
2181 // paragraphs inside floats need different alignment tags to avoid
2184 bool noTrivlistCentering(InsetCode code)
2186 return code == FLOAT_CODE
2187 || code == WRAP_CODE
2188 || code == CELL_CODE;
2192 string correction(string const & orig)
2194 if (orig == "flushleft")
2195 return "raggedright";
2196 if (orig == "flushright")
2197 return "raggedleft";
2198 if (orig == "center")
2204 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2205 InsetCode code, bool const lastpar, int & col)
2207 string macro = suffix + "{";
2208 if (noTrivlistCentering(code)) {
2210 // the last paragraph in non-trivlist-aligned
2211 // context is special (to avoid unwanted whitespace)
2212 if (suffix == "\\begin") {
2213 macro = "\\" + correction(env) + "{}";
2214 os << from_ascii(macro);
2215 col += macro.size();
2220 macro += correction(env);
2224 if (suffix == "\\par\\end") {
2228 os << from_ascii(macro);
2229 col += macro.size();
2230 if (suffix == "\\begin") {
2240 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2241 otexstream & os, OutputParams const & runparams) const
2246 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2247 (layout_->toggle_indent != ITOGGLE_NEVER) :
2248 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2250 if (canindent && params_.noindent() && !layout_->pass_thru) {
2251 os << "\\noindent ";
2255 LyXAlignment const curAlign = params_.align();
2257 if (curAlign == layout_->align)
2261 case LYX_ALIGN_NONE:
2262 case LYX_ALIGN_BLOCK:
2263 case LYX_ALIGN_LAYOUT:
2264 case LYX_ALIGN_SPECIAL:
2265 case LYX_ALIGN_DECIMAL:
2267 case LYX_ALIGN_LEFT:
2268 case LYX_ALIGN_RIGHT:
2269 case LYX_ALIGN_CENTER:
2270 if (runparams.moving_arg) {
2277 string const begin_tag = "\\begin";
2278 InsetCode code = ownerCode();
2279 bool const lastpar = runparams.isLastPar;
2280 // RTL in classic (PDF)LaTeX (without the Bidi package)
2281 // Luabibdi (used by LuaTeX) behaves like classic
2282 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2283 && !runparams.useBidiPackage();
2286 case LYX_ALIGN_NONE:
2287 case LYX_ALIGN_BLOCK:
2288 case LYX_ALIGN_LAYOUT:
2289 case LYX_ALIGN_SPECIAL:
2290 case LYX_ALIGN_DECIMAL:
2292 case LYX_ALIGN_LEFT: {
2294 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2295 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2297 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2299 } case LYX_ALIGN_RIGHT: {
2301 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2302 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2304 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2306 } case LYX_ALIGN_CENTER: {
2307 corrected_env(os, begin_tag, "center", code, lastpar, column);
2316 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2317 otexstream & os, OutputParams const & runparams) const
2319 LyXAlignment const curAlign = params_.align();
2321 if (curAlign == layout_->align)
2325 case LYX_ALIGN_NONE:
2326 case LYX_ALIGN_BLOCK:
2327 case LYX_ALIGN_LAYOUT:
2328 case LYX_ALIGN_SPECIAL:
2329 case LYX_ALIGN_DECIMAL:
2331 case LYX_ALIGN_LEFT:
2332 case LYX_ALIGN_RIGHT:
2333 case LYX_ALIGN_CENTER:
2334 if (runparams.moving_arg)
2339 bool output = false;
2341 string const end_tag = "\\par\\end";
2342 InsetCode code = ownerCode();
2343 bool const lastpar = runparams.isLastPar;
2344 // RTL in classic (PDF)LaTeX (without the Bidi package)
2345 // Luabibdi (used by LuaTeX) behaves like classic
2346 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2347 && !runparams.useBidiPackage();
2350 case LYX_ALIGN_NONE:
2351 case LYX_ALIGN_BLOCK:
2352 case LYX_ALIGN_LAYOUT:
2353 case LYX_ALIGN_SPECIAL:
2354 case LYX_ALIGN_DECIMAL:
2356 case LYX_ALIGN_LEFT: {
2358 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2359 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2361 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2363 } case LYX_ALIGN_RIGHT: {
2365 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2366 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2368 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2370 } case LYX_ALIGN_CENTER: {
2371 corrected_env(os, end_tag, "center", code, lastpar, col);
2376 return output || lastpar;
2380 // This one spits out the text of the paragraph
2381 void Paragraph::latex(BufferParams const & bparams,
2382 Font const & outerfont,
2384 OutputParams const & runparams,
2385 int start_pos, int end_pos, bool force) const
2387 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2389 // FIXME This check should not be needed. Perhaps issue an
2390 // error if it triggers.
2391 Layout const & style = inInset().forcePlainLayout() ?
2392 bparams.documentClass().plainLayout() : *d->layout_;
2394 if (!force && style.inpreamble)
2397 bool const allowcust = allowParagraphCustomization();
2399 // Current base font for all inherited font changes, without any
2400 // change caused by an individual character, except for the language:
2401 // It is set to the language of the first character.
2402 // As long as we are in the label, this font is the base font of the
2403 // label. Before the first body character it is set to the base font
2407 // If there is an open font-encoding changing command (script wrapper),
2408 // alien_script is set to its name
2409 string alien_script;
2412 // Maybe we have to create a optional argument.
2413 pos_type body_pos = beginOfBody();
2414 unsigned int column = 0;
2416 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2417 Font const real_outerfont = (!inInset().inheritFont()
2418 && runparams.local_font != nullptr)
2419 ? Font(runparams.local_font->fontInfo()) : outerfont;
2422 // the optional argument is kept in curly brackets in
2423 // case it contains a ']'
2424 // This is not strictly needed, but if this is changed it
2425 // would be a file format change, and tex2lyx would need
2426 // to be adjusted, since it unconditionally removes the
2427 // braces when it parses \item.
2430 basefont = getLabelFont(bparams, real_outerfont);
2432 basefont = getLayoutFont(bparams, real_outerfont);
2435 // Which font is currently active?
2436 Font running_font(basefont);
2437 // Do we have an open font change?
2438 bool open_font = false;
2440 Change runningChange = Change(Change::UNCHANGED);
2442 Encoding const * const prev_encoding = runparams.encoding;
2444 os.texrow().start(id(), 0);
2446 // if the paragraph is empty, the loop will not be entered at all
2448 // For InTitle commands, we have already opened a group
2449 // in output_latex::TeXOnePar.
2450 if (style.isCommand() && !style.intitle) {
2454 if (!style.leftdelim().empty()) {
2455 os << style.leftdelim();
2456 column += style.leftdelim().size();
2459 column += d->startTeXParParams(bparams, os, runparams);
2462 // Whether a \par can be issued for insets typeset inline with text.
2463 // Yes if greater than 0. This has to be static.
2464 THREAD_LOCAL_STATIC int parInline = 0;
2466 for (pos_type i = 0; i < size(); ++i) {
2467 // First char in paragraph or after label?
2468 if (i == body_pos) {
2471 bool needPar = false;
2472 column += running_font.latexWriteEndChanges(
2473 os, bparams, runparams,
2474 basefont, basefont, needPar);
2477 basefont = getLayoutFont(bparams, real_outerfont);
2478 running_font = basefont;
2480 column += Changes::latexMarkChange(os, bparams,
2481 runningChange, Change(Change::UNCHANGED),
2483 runningChange = Change(Change::UNCHANGED);
2488 // For InTitle commands, we have already opened a group
2489 // in output_latex::TeXOnePar.
2490 if (style.isCommand() && !style.intitle) {
2495 if (!style.leftdelim().empty()) {
2496 os << style.leftdelim();
2497 column += style.leftdelim().size();
2501 column += d->startTeXParParams(bparams, os,
2505 runparams.wasDisplayMath = runparams.inDisplayMath;
2506 runparams.inDisplayMath = false;
2507 bool deleted_display_math = false;
2508 Change const & change = runparams.inDeletedInset
2509 ? runparams.changeOfDeletedInset : lookupChange(i);
2511 char_type const c = d->text_[i];
2513 // Check whether a display math inset follows
2515 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2517 runparams.ctObject = getInset(i)->CtObject(runparams);
2519 InsetMath const * im = getInset(i)->asInsetMath();
2520 if (im && im->asHullInset()
2521 && im->asHullInset()->outerDisplay()) {
2522 runparams.inDisplayMath = true;
2523 // runparams.inDeletedInset will be set by
2524 // latexInset later, but we need this info
2525 // before it is called. On the other hand, we
2526 // cannot set it here because it is a counter.
2527 deleted_display_math = isDeleted(i);
2529 if (bparams.output_changes && deleted_display_math
2530 && runningChange == change
2531 && change.type == Change::DELETED
2532 && !os.afterParbreak()) {
2533 // A display math in the same paragraph follows.
2534 // We have to close and then reopen \lyxdeleted,
2535 // otherwise the math will be shifted up.
2536 OutputParams rp = runparams;
2538 bool needPar = false;
2539 column += running_font.latexWriteEndChanges(
2540 os, bparams, rp, basefont,
2544 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2545 : getLayoutFont(bparams, real_outerfont);
2546 running_font = basefont;
2547 column += Changes::latexMarkChange(os, bparams,
2548 Change(Change::INSERTED), change, rp);
2552 if (bparams.output_changes && runningChange != change) {
2553 if (!alien_script.empty()) {
2556 alien_script.clear();
2559 bool needPar = false;
2560 column += running_font.latexWriteEndChanges(
2561 os, bparams, runparams,
2562 basefont, basefont, needPar);
2565 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2566 : getLayoutFont(bparams, real_outerfont);
2567 running_font = basefont;
2568 column += Changes::latexMarkChange(os, bparams, runningChange,
2570 runningChange = change;
2573 // do not output text which is marked deleted
2574 // if change tracking output is disabled
2575 if (!bparams.output_changes && change.deleted()) {
2581 // Fully instantiated font
2582 Font current_font = getFont(bparams, i, outerfont);
2584 Font const prev_font = (i > 0) ?
2585 getFont(bparams, i - 1, outerfont)
2588 Font const last_font = running_font;
2589 bool const in_ct_deletion = (bparams.output_changes
2590 && runningChange == change
2591 && change.type == Change::DELETED
2592 && !os.afterParbreak());
2593 // Insets where font switches are used (rather than font commands)
2594 bool const fontswitch_inset =
2597 && getInset(i)->allowMultiPar()
2598 && getInset(i)->lyxCode() != ERT_CODE;
2600 bool closeLanguage = false;
2601 bool lang_switched_at_inset = false;
2602 if (fontswitch_inset) {
2603 // Some insets cannot be inside a font change command.
2604 // However, even such insets *can* be placed in \L or \R
2605 // or their equivalents (for RTL language switches),
2606 // so we don't close the language in those cases
2607 // (= differing isRightToLeft()).
2608 // ArabTeX, though, doesn't seem to handle this special behavior.
2609 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2610 || basefont.language()->lang() == "arabic_arabtex"
2611 || current_font.language()->lang() == "arabic_arabtex";
2612 // We need to check prev_font as language changes directly at inset
2613 // will only be started inside the inset.
2614 lang_switched_at_inset = prev_font.language() != current_font.language();
2617 // Do we need to close the previous font?
2618 bool langClosed = false;
2620 ((current_font != running_font
2621 || current_font.language() != running_font.language())
2622 || (fontswitch_inset
2623 && (current_font == prev_font))))
2625 // ensure there is no open script-wrapper
2626 if (!alien_script.empty()) {
2629 alien_script.clear();
2631 bool needPar = false;
2632 if (in_ct_deletion) {
2633 // We have to close and then reopen \lyxdeleted,
2634 // as strikeout needs to be on lowest level.
2639 // Force language closing
2640 current_font.setLanguage(basefont.language());
2641 column += running_font.latexWriteEndChanges(
2642 os, bparams, runparams, basefont,
2643 (i == body_pos-1) ? basefont : current_font,
2645 if (in_ct_deletion) {
2646 // We have to close and then reopen \lyxdeleted,
2647 // as strikeout needs to be on lowest level.
2648 OutputParams rp = runparams;
2649 column += Changes::latexMarkChange(os, bparams,
2650 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2652 running_font = basefont;
2657 // if necessary, close language environment before opening CJK
2658 string const running_lang = running_font.language()->babel();
2659 string const lang_end_command = lyxrc.language_command_end;
2660 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2661 && !running_lang.empty()
2662 && running_lang == openLanguageName()
2663 && current_font.language()->encoding()->package() == Encoding::CJK) {
2664 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2665 os << from_ascii(end_tag);
2666 column += end_tag.length();
2670 // Switch file encoding if necessary (and allowed)
2671 if ((!fontswitch_inset || closeLanguage)
2672 && !runparams.pass_thru && !style.pass_thru &&
2673 runparams.encoding->package() != Encoding::none &&
2674 current_font.language()->encoding()->package() != Encoding::none) {
2675 pair<bool, int> const enc_switch =
2676 switchEncoding(os.os(), bparams, runparams,
2677 *(current_font.language()->encoding()));
2678 if (enc_switch.first) {
2679 column += enc_switch.second;
2680 runparams.encoding = current_font.language()->encoding();
2684 // A display math inset inside an ulem command will be output
2685 // as a box of width \linewidth, so we have to either disable
2686 // indentation if the inset starts a paragraph, or start a new
2687 // line to accommodate such box. This has to be done before
2688 // writing any font changing commands.
2689 if (runparams.inDisplayMath && !deleted_display_math
2690 && runparams.inulemcmd) {
2691 if (os.afterParbreak())
2697 // Do we need to change font?
2698 if ((current_font != running_font ||
2699 current_font.language() != running_font.language())
2700 && i != body_pos - 1)
2702 if (!fontswitch_inset) {
2703 if (in_ct_deletion) {
2704 // We have to close and then reopen \lyxdeleted,
2705 // as strikeout needs to be on lowest level.
2706 bool needPar = false;
2707 OutputParams rp = runparams;
2708 column += running_font.latexWriteEndChanges(
2709 os, bparams, rp, basefont,
2714 otexstringstream ots;
2715 InsetText const * textinset = inInset().asInsetText();
2716 bool const cprotect = textinset
2717 ? textinset->hasCProtectContent(runparams.moving_arg)
2718 && !textinset->text().isMainText()
2720 column += current_font.latexWriteStartChanges(ots, bparams,
2721 runparams, basefont, last_font, false,
2723 // Check again for display math in ulem commands as a
2724 // font change may also occur just before a math inset.
2725 if (runparams.inDisplayMath && !deleted_display_math
2726 && runparams.inulemcmd) {
2727 if (os.afterParbreak())
2732 running_font = current_font;
2734 docstring fontchange = ots.str();
2736 // check whether the fontchange ends with a \\textcolor
2737 // modifier and the text starts with a space. If so we
2738 // need to add } in order to prevent \\textcolor from gobbling
2739 // the space (bug 4473).
2740 docstring const last_modifier = rsplit(fontchange, '\\');
2741 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2742 os << from_ascii("{}");
2743 else if (ots.terminateCommand())
2745 if (in_ct_deletion) {
2746 // We have to close and then reopen \lyxdeleted,
2747 // as strikeout needs to be on lowest level.
2748 OutputParams rp = runparams;
2749 column += Changes::latexMarkChange(os, bparams,
2750 Change(Change::UNCHANGED), change, rp);
2753 running_font = current_font;
2754 open_font = !langClosed;
2758 // FIXME: think about end_pos implementation...
2759 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2760 // FIXME: integrate this case in latexSpecialChar
2761 // Do not print the separation of the optional argument
2762 // if style.pass_thru is false. This works because
2763 // latexSpecialChar ignores spaces if
2764 // style.pass_thru is false.
2765 if (i != body_pos - 1) {
2766 if (d->simpleTeXBlanks(bparams, runparams, os,
2767 i, column, current_font, style)) {
2768 // A surrogate pair was output. We
2769 // must not call latexSpecialChar
2770 // in this iteration, since it would output
2771 // the combining character again.
2778 OutputParams rp = runparams;
2779 rp.free_spacing = style.free_spacing;
2780 rp.local_font = ¤t_font;
2781 rp.intitle = style.intitle;
2783 // Two major modes: LaTeX or plain
2784 // Handle here those cases common to both modes
2785 // and then split to handle the two modes separately.
2786 if (c == META_INSET) {
2787 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2788 // Greyedout notes and, in general, all insets
2789 // with InsetLayout::isDisplay() == false,
2790 // are typeset inline with the text. So, we
2791 // can add a \par to the last paragraph of
2792 // such insets only if nothing else follows.
2793 bool incremented = false;
2794 Inset const * inset = getInset(i);
2795 InsetText const * textinset = inset
2796 ? inset->asInsetText()
2798 if (i + 1 == size() && textinset
2799 && !inset->getLayout().isDisplay()) {
2800 ParagraphList const & pars =
2801 textinset->text().paragraphs();
2802 pit_type const pit = pars.size() - 1;
2803 Font const lastfont =
2804 pit < 0 || pars[pit].empty()
2805 ? pars[pit].getLayoutFont(
2808 : pars[pit].getFont(bparams,
2809 pars[pit].size() - 1,
2811 if (lastfont.fontInfo().size() !=
2812 basefont.fontInfo().size()) {
2817 // We need to restore parts of this after insets with
2818 // allowMultiPar() true
2819 Font const save_basefont = basefont;
2820 d->latexInset(bparams, os, rp, running_font,
2821 basefont, real_outerfont, open_font,
2822 runningChange, style, i, column, fontswitch_inset,
2823 closeLanguage, lang_switched_at_inset);
2824 if (fontswitch_inset) {
2826 bool needPar = false;
2827 column += running_font.latexWriteEndChanges(
2828 os, bparams, runparams,
2829 basefont, basefont, needPar);
2832 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2833 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2834 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2839 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2840 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2841 // Close \lyx*deleted and force its
2842 // reopening (if needed)
2845 runningChange = Change(Change::UNCHANGED);
2846 runparams.ctObject = OutputParams::CT_NORMAL;
2849 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2850 if (!bparams.useNonTeXFonts)
2851 script = Encodings::isKnownScriptChar(c);
2852 if (script != alien_script) {
2853 if (!alien_script.empty()) {
2855 alien_script.clear();
2857 string fontenc = running_font.language()->fontenc(bparams);
2859 && !Encodings::fontencSupportsScript(fontenc, script)) {
2860 column += script.length() + 2;
2861 os << "\\" << script << "{";
2862 alien_script = script;
2866 d->latexSpecialChar(os, bparams, rp, running_font,
2867 alien_script, style, i, end_pos, column);
2868 } catch (EncodingException & e) {
2869 if (runparams.dryrun) {
2870 os << "<" << _("LyX Warning: ")
2871 << _("uncodable character") << " '";
2875 // add location information and throw again.
2883 // Set the encoding to that returned from latexSpecialChar (see
2884 // comment for encoding member in OutputParams.h)
2885 runparams.encoding = rp.encoding;
2887 // Also carry on the info on a closed ulem command for insets
2888 // such as Note that do not produce any output, so that no
2889 // command is ever executed but its opening was recorded.
2890 runparams.inulemcmd = rp.inulemcmd;
2892 // These need to be passed upstream as well
2893 runparams.need_maketitle = rp.need_maketitle;
2894 runparams.have_maketitle = rp.have_maketitle;
2896 // And finally, pass the post_macros upstream
2897 runparams.post_macro = rp.post_macro;
2900 // Close wrapper for alien script
2901 if (!alien_script.empty()) {
2903 alien_script.clear();
2906 // If we have an open font definition, we have to close it
2908 // Make sure that \\par is done with the font of the last
2909 // character if this has another size as the default.
2910 // This is necessary because LaTeX (and LyX on the screen)
2911 // calculates the space between the baselines according
2912 // to this font. (Matthias)
2914 // We must not change the font for the last paragraph
2915 // of non-multipar insets, tabular cells or commands,
2916 // since this produces unwanted whitespace.
2918 Font const font = empty()
2919 ? getLayoutFont(bparams, real_outerfont)
2920 : getFont(bparams, size() - 1, real_outerfont);
2922 InsetText const * textinset = inInset().asInsetText();
2924 bool const maintext = textinset
2925 ? textinset->text().isMainText()
2928 size_t const numpars = textinset
2929 ? textinset->text().paragraphs().size()
2932 bool needPar = false;
2934 if (style.resfont.size() != font.fontInfo().size()
2935 && (!runparams.isLastPar || maintext
2936 || (numpars > 1 && d->ownerCode() != CELL_CODE
2937 && (inInset().getLayout().isDisplay()
2939 && !style.isCommand()) {
2942 #ifdef FIXED_LANGUAGE_END_DETECTION
2944 running_font.latexWriteEndChanges(os, bparams,
2945 runparams, basefont,
2946 next_->getFont(bparams, 0, outerfont),
2949 running_font.latexWriteEndChanges(os, bparams,
2950 runparams, basefont, basefont, needPar);
2953 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2954 //FIXME: there as we start another \selectlanguage with the next paragraph if
2955 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2956 running_font.latexWriteEndChanges(os, bparams, runparams,
2957 basefont, basefont, needPar);
2960 // The \par could not be inserted at the same nesting
2961 // level of the font size change, so do it now.
2962 os << "{\\" << font.latexSize() << "\\par}";
2966 column += Changes::latexMarkChange(os, bparams, runningChange,
2967 Change(Change::UNCHANGED), runparams);
2969 // Needed if there is an optional argument but no contents.
2970 if (body_pos > 0 && body_pos == size()) {
2974 if (!style.rightdelim().empty()) {
2975 os << style.rightdelim();
2976 column += style.rightdelim().size();
2979 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2980 && runparams.encoding != prev_encoding) {
2981 runparams.encoding = prev_encoding;
2982 os << setEncoding(prev_encoding->iconvName());
2985 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2989 bool Paragraph::emptyTag() const
2991 for (pos_type i = 0; i < size(); ++i) {
2992 if (Inset const * inset = getInset(i)) {
2993 InsetCode lyx_code = inset->lyxCode();
2994 // FIXME testing like that is wrong. What is
2996 if (lyx_code != TOC_CODE &&
2997 lyx_code != INCLUDE_CODE &&
2998 lyx_code != GRAPHICS_CODE &&
2999 lyx_code != ERT_CODE &&
3000 lyx_code != LISTINGS_CODE &&
3001 lyx_code != FLOAT_CODE &&
3002 lyx_code != TABULAR_CODE) {
3006 char_type c = d->text_[i];
3007 if (c != ' ' && c != '\t')
3015 string Paragraph::getID(Buffer const &, OutputParams const &)
3018 for (pos_type i = 0; i < size(); ++i) {
3019 if (Inset const * inset = getInset(i)) {
3020 InsetCode lyx_code = inset->lyxCode();
3021 if (lyx_code == LABEL_CODE) {
3022 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3023 docstring const & id = il->getParam("name");
3024 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3032 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3035 for (i = 0; i < size(); ++i) {
3036 if (Inset const * inset = getInset(i)) {
3037 inset->docbook(xs, runparams);
3039 char_type c = d->text_[i];
3049 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3053 for (i = 0; i < size(); ++i) {
3054 if (Inset const * inset = getInset(i)) {
3055 inset->xhtml(xs, runparams);
3057 char_type c = d->text_[i];
3067 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3070 pos_type size = text_.size();
3071 for (pos_type i = initial; i < size; ++i) {
3072 Font font = owner_->getFont(buf.params(), i, outerfont);
3073 if (text_[i] == META_INSET)
3075 if (i != initial && font != font_old)
3086 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3087 vector<xml::EndFontTag> & tagsToClose,
3088 bool & flag, FontState curstate, xml::FontTypes type)
3090 if (curstate == FONT_ON) {
3091 tagsToOpen.push_back(docbookStartFontTag(type));
3094 tagsToClose.push_back(docbookEndFontTag(type));
3099 class OptionalFontType {
3104 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3105 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3108 OptionalFontType fontShapeToXml(FontShape fs)
3112 return {xml::FT_ITALIC};
3114 return {xml::FT_SLANTED};
3115 case SMALLCAPS_SHAPE:
3116 return {xml::FT_SMALLCAPS};
3121 // the other tags are for internal use
3127 OptionalFontType fontFamilyToXml(FontFamily fm)
3131 return {xml::FT_ROMAN};
3133 return {xml::FT_SANS};
3134 case TYPEWRITER_FAMILY:
3135 return {xml::FT_TYPE};
3136 case INHERIT_FAMILY:
3139 // the other tags are for internal use
3145 OptionalFontType fontSizeToXml(FontSize fs)
3149 return {xml::FT_SIZE_TINY};
3151 return {xml::FT_SIZE_SCRIPT};
3153 return {xml::FT_SIZE_FOOTNOTE};
3155 return {xml::FT_SIZE_SMALL};
3157 return {xml::FT_SIZE_LARGE};
3159 return {xml::FT_SIZE_LARGER};
3161 return {xml::FT_SIZE_LARGEST};
3163 return {xml::FT_SIZE_HUGE};
3165 return {xml::FT_SIZE_HUGER};
3167 return {xml::FT_SIZE_INCREASE};
3169 return {xml::FT_SIZE_DECREASE};
3174 // the other tags are for internal use
3180 struct DocBookFontState
3182 FontShape curr_fs = INHERIT_SHAPE;
3183 FontFamily curr_fam = INHERIT_FAMILY;
3184 FontSize curr_size = INHERIT_SIZE;
3186 // track whether we have opened these tags
3187 bool emph_flag = false;
3188 bool bold_flag = false;
3189 bool noun_flag = false;
3190 bool ubar_flag = false;
3191 bool dbar_flag = false;
3192 bool sout_flag = false;
3193 bool xout_flag = false;
3194 bool wave_flag = false;
3196 bool shap_flag = false;
3198 bool faml_flag = false;
3200 bool size_flag = false;
3203 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3205 std::string const & default_family,
3206 DocBookFontState & fs)
3208 vector<xml::FontTag> tagsToOpen;
3209 vector<xml::EndFontTag> tagsToClose;
3212 FontState curstate = font.fontInfo().emph();
3213 if (font_old.emph() != curstate)
3214 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3217 curstate = font.fontInfo().noun();
3218 if (font_old.noun() != curstate)
3219 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3222 curstate = font.fontInfo().underbar();
3223 if (font_old.underbar() != curstate)
3224 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3227 curstate = font.fontInfo().strikeout();
3228 if (font_old.strikeout() != curstate)
3229 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3232 curstate = font.fontInfo().xout();
3233 if (font_old.xout() != curstate)
3234 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3237 curstate = font.fontInfo().uuline();
3238 if (font_old.uuline() != curstate)
3239 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3242 curstate = font.fontInfo().uwave();
3243 if (font_old.uwave() != curstate)
3244 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3247 // a little hackish, but allows us to reuse what we have.
3248 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3249 if (font_old.series() != font.fontInfo().series())
3250 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3253 fs.curr_fs = font.fontInfo().shape();
3254 FontShape old_fs = font_old.shape();
3255 if (old_fs != fs.curr_fs) {
3257 OptionalFontType tag = fontShapeToXml(old_fs);
3259 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3260 fs.shap_flag = false;
3263 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3265 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3269 fs.curr_fam = font.fontInfo().family();
3270 FontFamily old_fam = font_old.family();
3271 if (old_fam != fs.curr_fam) {
3273 OptionalFontType tag = fontFamilyToXml(old_fam);
3275 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3276 fs.faml_flag = false;
3278 switch (fs.curr_fam) {
3280 // we will treat a "default" font family as roman, since we have
3281 // no other idea what to do.
3282 if (default_family != "rmdefault" && default_family != "default") {
3283 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3284 fs.faml_flag = true;
3288 if (default_family != "sfdefault") {
3289 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3290 fs.faml_flag = true;
3293 case TYPEWRITER_FAMILY:
3294 if (default_family != "ttdefault") {
3295 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3296 fs.faml_flag = true;
3299 case INHERIT_FAMILY:
3302 // the other tags are for internal use
3309 fs.curr_size = font.fontInfo().size();
3310 FontSize old_size = font_old.size();
3311 if (old_size != fs.curr_size) {
3313 OptionalFontType tag = fontSizeToXml(old_size);
3315 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3316 fs.size_flag = false;
3319 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3320 if (tag.has_value) {
3321 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3322 fs.size_flag = true;
3326 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3329 } // anonymous namespace
3332 std::vector<docstring> Paragraph::simpleDocBookOnePar(Buffer const & buf,
3333 OutputParams const & runparams,
3334 Font const & outerfont,
3335 pos_type initial) const
3337 // Track whether we have opened these tags
3338 DocBookFontState fs;
3340 Layout const & style = *d->layout_;
3342 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3344 string const default_family =
3345 buf.masterBuffer()->params().fonts_default_family;
3347 vector<xml::FontTag> tagsToOpen;
3348 vector<xml::EndFontTag> tagsToClose;
3350 std::vector<docstring> generatedParagraphs;
3351 odocstringstream os;
3352 auto * xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3353 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3355 // Parsing main loop.
3356 for (pos_type i = initial; i < size(); ++i) {
3357 // Don't show deleted material in the output.
3361 // If this is an InsetNewline, generate a new paragraph.
3362 if (getInset(i) != nullptr && getInset(i)->lyxCode() == NEWLINE_CODE) {
3363 generatedParagraphs.push_back(os.str());
3364 os = odocstringstream();
3366 xs = new XMLStream(os);
3369 // Determine which tags should be opened or closed.
3370 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3371 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3374 // Other such tags? What about the other text ranges?
3376 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3377 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3378 for (; cit != cen; ++cit)
3381 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3382 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3383 for (; sit != sen; ++sit)
3386 tagsToClose.clear();
3389 if (Inset const * inset = getInset(i)) {
3390 if (!runparams.for_toc || inset->isInToc()) {
3391 OutputParams np = runparams;
3392 np.local_font = &font;
3394 // TODO: special case will bite here.
3395 np.docbook_in_par = true;
3396 inset->docbook(*xs, np);
3399 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3402 font_old = font.fontInfo();
3405 // FIXME, this code is just imported from XHTML
3406 // I'm worried about what happens if a branch, say, is itself
3407 // wrapped in some font stuff. I think that will not work.
3408 xs->closeFontTags();
3409 if (runparams.docbook_in_listing)
3412 // Finalise the last (and most likely only) paragraph.
3413 generatedParagraphs.push_back(os.str());
3416 return generatedParagraphs;
3422 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3423 vector<xml::EndFontTag> & tagsToClose,
3424 bool & flag, FontState curstate, xml::FontTypes type)
3426 if (curstate == FONT_ON) {
3427 tagsToOpen.push_back(xhtmlStartFontTag(type));
3430 tagsToClose.push_back(xhtmlEndFontTag(type));
3435 } // anonymous namespace
3438 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3440 OutputParams const & runparams,
3441 Font const & outerfont,
3442 bool start_paragraph, bool close_paragraph,
3443 pos_type initial) const
3447 // track whether we have opened these tags
3448 bool emph_flag = false;
3449 bool bold_flag = false;
3450 bool noun_flag = false;
3451 bool ubar_flag = false;
3452 bool dbar_flag = false;
3453 bool sout_flag = false;
3454 bool xout_flag = false;
3455 bool wave_flag = false;
3457 bool shap_flag = false;
3459 bool faml_flag = false;
3461 bool size_flag = false;
3463 Layout const & style = *d->layout_;
3465 if (start_paragraph)
3466 xs.startDivision(allowEmpty());
3469 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3471 FontShape curr_fs = INHERIT_SHAPE;
3472 FontFamily curr_fam = INHERIT_FAMILY;
3473 FontSize curr_size = INHERIT_SIZE;
3475 string const default_family =
3476 buf.masterBuffer()->params().fonts_default_family;
3478 vector<xml::FontTag> tagsToOpen;
3479 vector<xml::EndFontTag> tagsToClose;
3481 // parsing main loop
3482 for (pos_type i = initial; i < size(); ++i) {
3483 // let's not show deleted material in the output
3487 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3490 FontState curstate = font.fontInfo().emph();
3491 if (font_old.emph() != curstate)
3492 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3495 curstate = font.fontInfo().noun();
3496 if (font_old.noun() != curstate)
3497 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3500 curstate = font.fontInfo().underbar();
3501 if (font_old.underbar() != curstate)
3502 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3505 curstate = font.fontInfo().strikeout();
3506 if (font_old.strikeout() != curstate)
3507 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3510 curstate = font.fontInfo().xout();
3511 if (font_old.xout() != curstate)
3512 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3515 curstate = font.fontInfo().uuline();
3516 if (font_old.uuline() != curstate)
3517 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3520 curstate = font.fontInfo().uwave();
3521 if (font_old.uwave() != curstate)
3522 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3525 // a little hackish, but allows us to reuse what we have.
3526 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3527 if (font_old.series() != font.fontInfo().series())
3528 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3531 curr_fs = font.fontInfo().shape();
3532 FontShape old_fs = font_old.shape();
3533 if (old_fs != curr_fs) {
3537 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3540 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3542 case SMALLCAPS_SHAPE:
3543 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3549 // the other tags are for internal use
3557 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3561 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3564 case SMALLCAPS_SHAPE:
3565 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3572 // the other tags are for internal use
3579 curr_fam = font.fontInfo().family();
3580 FontFamily old_fam = font_old.family();
3581 if (old_fam != curr_fam) {
3585 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3588 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3590 case TYPEWRITER_FAMILY:
3591 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3593 case INHERIT_FAMILY:
3596 // the other tags are for internal use
3604 // we will treat a "default" font family as roman, since we have
3605 // no other idea what to do.
3606 if (default_family != "rmdefault" && default_family != "default") {
3607 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3612 if (default_family != "sfdefault") {
3613 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3617 case TYPEWRITER_FAMILY:
3618 if (default_family != "ttdefault") {
3619 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3623 case INHERIT_FAMILY:
3626 // the other tags are for internal use
3633 curr_size = font.fontInfo().size();
3634 FontSize old_size = font_old.size();
3635 if (old_size != curr_size) {
3639 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3642 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3645 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3648 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3651 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3654 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3657 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3660 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3663 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3666 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3669 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3675 // the other tags are for internal use
3681 switch (curr_size) {
3683 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3687 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3691 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3695 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3699 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3703 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3707 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3711 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3715 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3719 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3723 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3730 // the other tags are for internal use
3737 // Other such tags? What about the other text ranges?
3739 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3740 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3741 for (; cit != cen; ++cit)
3744 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3745 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3746 for (; sit != sen; ++sit)
3749 tagsToClose.clear();
3752 Inset const * inset = getInset(i);
3754 if (!runparams.for_toc || inset->isInToc()) {
3755 OutputParams np = runparams;
3756 np.local_font = &font;
3757 // If the paragraph has size 1, then we are in the "special
3758 // case" where we do not output the containing paragraph info
3759 if (!inset->getLayout().htmlisblock() && size() != 1)
3760 np.html_in_par = true;
3761 retval += inset->xhtml(xs, np);
3764 char_type c = getUChar(buf.masterBuffer()->params(),
3766 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3767 xs << XMLStream::ESCAPE_NONE << " ";
3771 font_old = font.fontInfo();
3775 // I'm worried about what happens if a branch, say, is itself
3776 // wrapped in some font stuff. I think that will not work.
3778 if (close_paragraph)
3785 bool Paragraph::isHfill(pos_type pos) const
3787 Inset const * inset = getInset(pos);
3788 return inset && inset->isHfill();
3792 bool Paragraph::isNewline(pos_type pos) const
3794 // U+2028 LINE SEPARATOR
3795 // U+2029 PARAGRAPH SEPARATOR
3796 char_type const c = d->text_[pos];
3797 if (c == 0x2028 || c == 0x2029)
3799 Inset const * inset = getInset(pos);
3800 return inset && inset->lyxCode() == NEWLINE_CODE;
3804 bool Paragraph::isEnvSeparator(pos_type pos) const
3806 Inset const * inset = getInset(pos);
3807 return inset && inset->lyxCode() == SEPARATOR_CODE;
3811 bool Paragraph::isLineSeparator(pos_type pos) const
3813 char_type const c = d->text_[pos];
3814 if (isLineSeparatorChar(c))
3816 Inset const * inset = getInset(pos);
3817 return inset && inset->isLineSeparator();
3821 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3825 if (ignore_deleted && isDeleted(pos))
3827 if (Inset const * inset = getInset(pos))
3828 return !inset->isLetter();
3829 // if we have a hard hyphen (no en- or emdash) or apostrophe
3830 // we pass this to the spell checker
3831 // FIXME: this method is subject to change, visit
3832 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3833 // to get an impression how complex this is.
3834 if (isHardHyphenOrApostrophe(pos))
3836 char_type const c = d->text_[pos];
3837 // We want to pass the escape chars to the spellchecker
3838 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3839 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3843 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3845 pos_type const psize = size();
3848 char_type const c = d->text_[pos];
3849 if (c != '-' && c != '\'')
3851 int nextpos = pos + 1;
3852 int prevpos = pos > 0 ? pos - 1 : 0;
3853 if ((nextpos == psize || isSpace(nextpos))
3854 && (pos == 0 || isSpace(prevpos)))
3860 bool Paragraph::needsCProtection(bool const fragile) const
3862 // first check the layout of the paragraph, but only in insets
3863 InsetText const * textinset = inInset().asInsetText();
3864 bool const maintext = textinset
3865 ? textinset->text().isMainText()
3868 if (!maintext && layout().needcprotect) {
3869 // Environments need cprotection regardless the content
3870 if (layout().latextype == LATEX_ENVIRONMENT)
3873 // Commands need cprotection if they contain specific chars
3874 int const nchars_escape = 9;
3875 static char_type const chars_escape[nchars_escape] = {
3876 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3878 docstring const pars = asString();
3879 for (int k = 0; k < nchars_escape; k++) {
3880 if (contains(pars, chars_escape[k]))
3885 // now check whether we have insets that need cprotection
3886 pos_type size = pos_type(d->text_.size());
3887 for (pos_type i = 0; i < size; ++i) {
3890 Inset const * ins = getInset(i);
3891 if (ins->needsCProtection(maintext, fragile))
3893 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3894 // Environments need cprotection regardless the content
3896 // Now check math environments
3897 InsetMath const * im = getInset(i)->asInsetMath();
3898 if (!im || im->cell(0).empty())
3900 switch(im->cell(0)[0]->lyxCode()) {
3901 case MATH_AMSARRAY_CODE:
3902 case MATH_SUBSTACK_CODE:
3904 case MATH_XYMATRIX_CODE:
3905 // these need cprotection
3916 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3918 return d->speller_state_.getRange(pos);
3922 bool Paragraph::isChar(pos_type pos) const
3924 if (Inset const * inset = getInset(pos))
3925 return inset->isChar();
3926 char_type const c = d->text_[pos];
3927 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3931 bool Paragraph::isSpace(pos_type pos) const
3933 if (Inset const * inset = getInset(pos))
3934 return inset->isSpace();
3935 char_type const c = d->text_[pos];
3936 return lyx::isSpace(c);
3941 Paragraph::getParLanguage(BufferParams const & bparams) const
3944 return getFirstFontSettings(bparams).language();
3945 // FIXME: we should check the prev par as well (Lgb)
3946 return bparams.language;
3950 bool Paragraph::isRTL(BufferParams const & bparams) const
3952 return getParLanguage(bparams)->rightToLeft()
3953 && !inInset().getLayout().forceLTR();
3957 void Paragraph::changeLanguage(BufferParams const & bparams,
3958 Language const * from, Language const * to)
3960 // change language including dummy font change at the end
3961 for (pos_type i = 0; i <= size(); ++i) {
3962 Font font = getFontSettings(bparams, i);
3963 if (font.language() == from) {
3964 font.setLanguage(to);
3966 d->requestSpellCheck(i);
3972 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3974 Language const * doc_language = bparams.language;
3975 for (auto const & f : d->fontlist_)
3976 if (f.font().language() != ignore_language &&
3977 f.font().language() != latex_language &&
3978 f.font().language() != doc_language)
3984 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3986 for (auto const & f : d->fontlist_) {
3987 Language const * lang = f.font().language();
3988 if (lang != ignore_language &&
3989 lang != latex_language)
3995 docstring Paragraph::asString(int options) const
3997 return asString(0, size(), options);
4001 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4003 odocstringstream os;
4006 && options & AS_STR_LABEL
4007 && !d->params_.labelString().empty())
4008 os << d->params_.labelString() << ' ';
4010 for (pos_type i = beg; i < end; ++i) {
4011 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4013 char_type const c = d->text_[i];
4014 if (isPrintable(c) || c == '\t'
4015 || (c == '\n' && (options & AS_STR_NEWLINES)))
4017 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4018 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4019 LASSERT(runparams != nullptr, return docstring());
4020 getInset(i)->plaintext(os, *runparams);
4022 getInset(i)->toString(os);
4031 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4032 bool const shorten, bool const label) const
4034 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4035 if (label && !labelString().empty())
4036 os += labelString() + ' ';
4037 if (!layout().isTocCaption())
4039 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4042 char_type const c = d->text_[i];
4045 else if (c == META_INSET)
4046 getInset(i)->forOutliner(os, tmplen, false);
4049 Text::shortenForOutliner(os, maxlen);
4053 void Paragraph::setInsetOwner(Inset const * inset)
4055 d->inset_owner_ = inset;
4059 int Paragraph::id() const
4065 void Paragraph::setId(int id)
4071 Layout const & Paragraph::layout() const
4077 void Paragraph::setLayout(Layout const & layout)
4079 d->layout_ = &layout;
4083 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4085 setLayout(tc.defaultLayout());
4089 void Paragraph::setPlainLayout(DocumentClass const & tc)
4091 setLayout(tc.plainLayout());
4095 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4097 if (usePlainLayout())
4098 setPlainLayout(tclass);
4100 setDefaultLayout(tclass);
4104 Inset const & Paragraph::inInset() const
4106 LBUFERR(d->inset_owner_);
4107 return *d->inset_owner_;
4111 ParagraphParameters & Paragraph::params()
4117 ParagraphParameters const & Paragraph::params() const
4123 bool Paragraph::isFreeSpacing() const
4125 if (d->layout_->free_spacing)
4127 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4131 bool Paragraph::allowEmpty() const
4133 if (d->layout_->keepempty)
4135 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4139 bool Paragraph::brokenBiblio() const
4141 // There is a problem if there is no bibitem at position 0 in
4142 // paragraphs that need one, if there is another bibitem in the
4143 // paragraph or if this paragraph is not supposed to have
4144 // a bibitem inset at all.
4145 return ((d->layout_->labeltype == LABEL_BIBLIO
4146 && (d->insetlist_.find(BIBITEM_CODE) != 0
4147 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4148 || (d->layout_->labeltype != LABEL_BIBLIO
4149 && d->insetlist_.find(BIBITEM_CODE) != -1));
4153 int Paragraph::fixBiblio(Buffer const & buffer)
4155 // FIXME: when there was already an inset at 0, the return value is 1,
4156 // which does not tell whether another inset has been removed; the
4157 // cursor cannot be correctly updated.
4159 bool const track_changes = buffer.params().track_changes;
4160 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4162 // The case where paragraph is not BIBLIO
4163 if (d->layout_->labeltype != LABEL_BIBLIO) {
4164 if (bibitem_pos == -1)
4165 // No InsetBibitem => OK
4167 // There is an InsetBibitem: remove it!
4168 d->insetlist_.release(bibitem_pos);
4169 eraseChar(bibitem_pos, track_changes);
4170 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4173 bool const hasbibitem0 = bibitem_pos == 0;
4175 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4176 // There was an InsetBibitem at pos 0,
4177 // and no other one => OK
4178 if (bibitem_pos == -1)
4180 // there is a bibitem at the 0 position, but since
4181 // there is a second one, we copy the second on the
4182 // first. We're assuming there are at most two of
4183 // these, which there should be.
4184 // FIXME: why does it make sense to do that rather
4185 // than keep the first? (JMarc)
4186 Inset * inset = releaseInset(bibitem_pos);
4187 d->insetlist_.begin()->inset = inset;
4188 // This needs to be done to update the counter (#8499)
4189 buffer.updateBuffer();
4190 return -bibitem_pos;
4193 // We need to create an inset at the beginning
4194 Inset * inset = nullptr;
4195 if (bibitem_pos > 0) {
4196 // there was one somewhere in the paragraph, let's move it
4197 inset = d->insetlist_.release(bibitem_pos);
4198 eraseChar(bibitem_pos, track_changes);
4201 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4202 InsetCommandParams(BIBITEM_CODE));
4204 Font font(inherit_font, buffer.params().language);
4205 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4206 : Change::UNCHANGED));
4208 // This is needed to get the counters right
4209 buffer.updateBuffer();
4214 void Paragraph::checkAuthors(AuthorList const & authorList)
4216 d->changes_.checkAuthors(authorList);
4220 bool Paragraph::isChanged(pos_type pos) const
4222 return lookupChange(pos).changed();
4226 bool Paragraph::isInserted(pos_type pos) const
4228 return lookupChange(pos).inserted();
4232 bool Paragraph::isDeleted(pos_type pos) const
4234 return lookupChange(pos).deleted();
4238 InsetList const & Paragraph::insetList() const
4240 return d->insetlist_;
4244 void Paragraph::setInsetBuffers(Buffer & b)
4246 d->insetlist_.setBuffer(b);
4250 void Paragraph::resetBuffer()
4252 d->insetlist_.resetBuffer();
4256 Inset * Paragraph::releaseInset(pos_type pos)
4258 Inset * inset = d->insetlist_.release(pos);
4259 /// does not honour change tracking!
4260 eraseChar(pos, false);
4265 Inset * Paragraph::getInset(pos_type pos)
4267 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4268 ? d->insetlist_.get(pos) : nullptr;
4272 Inset const * Paragraph::getInset(pos_type pos) const
4274 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4275 ? d->insetlist_.get(pos) : nullptr;
4279 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4280 pos_type & right, TextCase action)
4282 // process sequences of modified characters; in change
4283 // tracking mode, this approach results in much better
4284 // usability than changing case on a char-by-char basis
4285 // We also need to track the current font, since font
4286 // changes within sequences can occur.
4287 vector<pair<char_type, Font> > changes;
4289 bool const trackChanges = bparams.track_changes;
4291 bool capitalize = true;
4293 for (; pos < right; ++pos) {
4294 char_type oldChar = d->text_[pos];
4295 char_type newChar = oldChar;
4297 // ignore insets and don't play with deleted text!
4298 if (oldChar != META_INSET && !isDeleted(pos)) {
4300 case text_lowercase:
4301 newChar = lowercase(oldChar);
4303 case text_capitalization:
4305 newChar = uppercase(oldChar);
4309 case text_uppercase:
4310 newChar = uppercase(oldChar);
4315 if (isWordSeparator(pos) || isDeleted(pos)) {
4316 // permit capitalization again
4320 if (oldChar != newChar) {
4321 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4322 if (pos != right - 1)
4324 // step behind the changing area
4328 int erasePos = pos - changes.size();
4329 for (size_t i = 0; i < changes.size(); i++) {
4330 insertChar(pos, changes[i].first,
4333 if (!eraseChar(erasePos, trackChanges)) {
4336 ++right; // expand selection
4344 int Paragraph::find(docstring const & str, bool cs, bool mw,
4345 pos_type start_pos, bool del) const
4347 pos_type pos = start_pos;
4348 int const strsize = str.length();
4350 pos_type const parsize = d->text_.size();
4351 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4352 // Ignore "invisible" letters such as ligature breaks
4353 // and hyphenation chars while searching
4354 while (pos < parsize - 1 && isInset(pos)) {
4355 Inset const * inset = getInset(pos);
4356 if (!inset->isLetter())
4358 odocstringstream os;
4359 inset->toString(os);
4360 if (!os.str().empty())
4364 if (cs && str[i] != d->text_[pos])
4366 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4368 if (!del && isDeleted(pos))
4375 // if necessary, check whether string matches word
4377 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4380 && !isWordSeparator(pos))
4384 return pos - start_pos;
4388 char_type Paragraph::getChar(pos_type pos) const
4390 return d->text_[pos];
4394 pos_type Paragraph::size() const
4396 return d->text_.size();
4400 bool Paragraph::empty() const
4402 return d->text_.empty();
4406 bool Paragraph::isInset(pos_type pos) const
4408 return d->text_[pos] == META_INSET;
4412 bool Paragraph::isSeparator(pos_type pos) const
4414 //FIXME: Are we sure this can be the only separator?
4415 return d->text_[pos] == ' ';
4419 void Paragraph::deregisterWords()
4421 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4422 Private::LangWordsMap::const_iterator ite = d->words_.end();
4423 for (; itl != ite; ++itl) {
4424 WordList & wl = theWordList(itl->first);
4425 Private::Words::const_iterator it = (itl->second).begin();
4426 Private::Words::const_iterator et = (itl->second).end();
4427 for (; it != et; ++it)
4434 void Paragraph::locateWord(pos_type & from, pos_type & to,
4435 word_location const loc, bool const ignore_deleted) const
4438 case WHOLE_WORD_STRICT:
4439 if (from == 0 || from == size()
4440 || isWordSeparator(from, ignore_deleted)
4441 || isWordSeparator(from - 1, ignore_deleted)) {
4448 // If we are already at the beginning of a word, do nothing
4449 if (!from || isWordSeparator(from - 1, ignore_deleted))
4454 // always move the cursor to the beginning of previous word
4455 while (from && !isWordSeparator(from - 1, ignore_deleted))
4459 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4462 // no need to move the 'from' cursor
4466 while (to < size() && !isWordSeparator(to, ignore_deleted))
4471 void Paragraph::collectWords()
4473 for (pos_type pos = 0; pos < size(); ++pos) {
4474 if (isWordSeparator(pos))
4476 pos_type from = pos;
4477 locateWord(from, pos, WHOLE_WORD);
4478 // Work around MSVC warning: The statement
4479 // if (pos < from + lyxrc.completion_minlength)
4480 // triggers a signed vs. unsigned warning.
4481 // I don't know why this happens, it could be a MSVC bug, or
4482 // related to LLP64 (windows) vs. LP64 (unix) programming
4483 // model, or the C++ standard might be ambigous in the section
4484 // defining the "usual arithmetic conversions". However, using
4485 // a temporary variable is safe and works on all compilers.
4486 pos_type const endpos = from + lyxrc.completion_minlength;
4489 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4490 if (cit == d->fontlist_.end())
4492 Language const * lang = cit->font().language();
4493 docstring const word = asString(from, pos, AS_STR_NONE);
4494 d->words_[lang->lang()].insert(word);
4499 void Paragraph::registerWords()
4501 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4502 Private::LangWordsMap::const_iterator ite = d->words_.end();
4503 for (; itl != ite; ++itl) {
4504 WordList & wl = theWordList(itl->first);
4505 Private::Words::const_iterator it = (itl->second).begin();
4506 Private::Words::const_iterator et = (itl->second).end();
4507 for (; it != et; ++it)
4513 void Paragraph::updateWords()
4521 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4523 SkipPositionsIterator begin = skips.begin();
4524 SkipPositions::iterator end = skips.end();
4525 if (pos > 0 && begin < end) {
4527 if (end->last == pos - 1) {
4532 skips.insert(end, FontSpan(pos, pos));
4536 Language * Paragraph::Private::locateSpellRange(
4537 pos_type & from, pos_type & to,
4538 SkipPositions & skips) const
4540 // skip leading white space
4541 while (from < to && owner_->isWordSeparator(from))
4543 // don't check empty range
4546 // get current language
4547 Language * lang = getSpellLanguage(from);
4548 pos_type last = from;
4549 bool samelang = true;
4550 bool sameinset = true;
4551 while (last < to && samelang && sameinset) {
4552 // hop to end of word
4553 while (last < to && !owner_->isWordSeparator(last)) {
4554 Inset const * inset = owner_->getInset(last);
4555 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4556 // check for "invisible" letters such as ligature breaks
4557 odocstringstream os;
4558 inset->toString(os);
4559 if (os.str().length() != 0) {
4560 // avoid spell check of visible special char insets
4561 // stop the loop in front of the special char inset
4566 appendSkipPosition(skips, last);
4567 } else if (owner_->isDeleted(last)) {
4568 appendSkipPosition(skips, last);
4572 // hop to next word while checking for insets
4573 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4574 if (Inset const * inset = owner_->getInset(last))
4575 sameinset = inset->isChar() && inset->isLetter();
4576 if (sameinset && owner_->isDeleted(last)) {
4577 appendSkipPosition(skips, last);
4582 if (sameinset && last < to) {
4583 // now check for language change
4584 samelang = lang == getSpellLanguage(last);
4587 // if language change detected backstep is needed
4595 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4598 const_cast<Language *>(owner_->getFontSettings(
4599 inset_owner_->buffer().params(), from).language());
4600 if (lang == inset_owner_->buffer().params().language
4601 && !lyxrc.spellchecker_alt_lang.empty()) {
4603 string const lang_variety =
4604 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4605 lang->setCode(lang_code);
4606 lang->setVariety(lang_variety);
4612 void Paragraph::requestSpellCheck(pos_type pos)
4614 d->requestSpellCheck(pos);
4618 bool Paragraph::needsSpellCheck() const
4620 SpellChecker::ChangeNumber speller_change_number = 0;
4621 if (theSpellChecker())
4622 speller_change_number = theSpellChecker()->changeNumber();
4623 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4624 d->speller_state_.needsCompleteRefresh(speller_change_number);
4626 return d->needsSpellCheck();
4630 bool Paragraph::Private::ignoreWord(docstring const & word) const
4632 // Ignore words with digits
4633 // FIXME: make this customizable
4634 // (note that some checkers ignore words with digits by default)
4635 docstring::const_iterator cit = word.begin();
4636 docstring::const_iterator const end = word.end();
4637 for (; cit != end; ++cit) {
4638 if (isNumber((*cit)))
4645 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4646 WordLangTuple & wl, docstring_list & suggestions,
4647 bool do_suggestion, bool check_learned) const
4649 SpellChecker::Result result = SpellChecker::WORD_OK;
4650 SpellChecker * speller = theSpellChecker();
4654 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4657 locateWord(from, to, WHOLE_WORD, true);
4658 if (from == to || from >= size())
4661 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4662 Language * lang = d->getSpellLanguage(from);
4664 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4667 wl = WordLangTuple(word, lang);
4672 if (needsSpellCheck() || check_learned) {
4674 if (!d->ignoreWord(word)) {
4675 bool const trailing_dot = to < size() && d->text_[to] == '.';
4676 result = speller->check(wl);
4677 if (SpellChecker::misspelled(result) && trailing_dot) {
4678 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4679 result = speller->check(wl);
4680 if (!SpellChecker::misspelled(result)) {
4681 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4683 from << ".." << to << "]");
4685 // spell check with dot appended failed too
4686 // restore original word/lang value
4687 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4688 wl = WordLangTuple(word, lang);
4692 if (!SpellChecker::misspelled(result)) {
4693 // area up to the begin of the next word is not misspelled
4694 while (end < size() && isWordSeparator(end))
4697 d->setMisspelled(from, end, result);
4699 result = d->speller_state_.getState(from);
4703 suggestions.clear();
4705 if (SpellChecker::misspelled(result)) {
4706 LYXERR(Debug::GUI, "misspelled word: \"" <<
4708 from << ".." << to << "]");
4710 speller->suggest(wl, suggestions);
4716 void Paragraph::anonymize()
4718 // This is a very crude anonymization for now
4719 for (char_type & c : d->text_)
4720 if (isLetterChar(c) || isNumber(c))
4725 void Paragraph::Private::markMisspelledWords(
4726 pos_type const & first, pos_type const & last,
4727 SpellChecker::Result result,
4728 docstring const & word,
4729 SkipPositions const & skips)
4731 if (!SpellChecker::misspelled(result)) {
4732 setMisspelled(first, last, SpellChecker::WORD_OK);
4736 SpellChecker * speller = theSpellChecker();
4737 // locate and enumerate the error positions
4738 int nerrors = speller->numMisspelledWords();
4740 SkipPositionsIterator it = skips.begin();
4741 SkipPositionsIterator et = skips.end();
4742 for (int index = 0; index < nerrors; ++index) {
4745 speller->misspelledWord(index, wstart, wlen);
4746 /// should not happen if speller supports range checks
4747 if (!wlen) continue;
4748 docstring const misspelled = word.substr(wstart, wlen);
4749 wstart += first + numskipped;
4750 if (snext < wstart) {
4751 /// mark the range of correct spelling
4752 numskipped += countSkips(it, et, wstart);
4753 setMisspelled(snext,
4754 wstart - 1, SpellChecker::WORD_OK);
4756 snext = wstart + wlen;
4757 numskipped += countSkips(it, et, snext);
4758 /// mark the range of misspelling
4759 setMisspelled(wstart, snext, result);
4760 LYXERR(Debug::GUI, "misspelled word: \"" <<
4761 misspelled << "\" [" <<
4762 wstart << ".." << (snext-1) << "]");
4765 if (snext <= last) {
4766 /// mark the range of correct spelling at end
4767 setMisspelled(snext, last, SpellChecker::WORD_OK);
4772 void Paragraph::spellCheck() const
4774 SpellChecker * speller = theSpellChecker();
4775 if (!speller || empty() ||!needsSpellCheck())
4779 d->rangeOfSpellCheck(start, endpos);
4780 if (speller->canCheckParagraph()) {
4781 // loop until we leave the range
4782 for (pos_type first = start; first < endpos; ) {
4783 pos_type last = endpos;
4784 Private::SkipPositions skips;
4785 Language * lang = d->locateSpellRange(first, last, skips);
4786 if (first >= endpos)
4788 // start the spell checker on the unit of meaning
4789 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4790 WordLangTuple wl = WordLangTuple(word, lang);
4791 SpellChecker::Result result = word.size() ?
4792 speller->check(wl) : SpellChecker::WORD_OK;
4793 d->markMisspelledWords(first, last, result, word, skips);
4797 static docstring_list suggestions;
4798 pos_type to = endpos;
4799 while (start < endpos) {
4801 spellCheck(start, to, wl, suggestions, false);
4805 d->readySpellCheck();
4809 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4811 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4812 if (result || pos <= 0 || pos > size())
4814 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4815 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4820 string Paragraph::magicLabel() const
4823 ss << "magicparlabel-" << id();