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);
349 void latexSpecialChar(
351 BufferParams const & bparams,
352 OutputParams const & runparams,
353 Font const & running_font,
354 string & alien_script,
355 Layout const & style,
358 unsigned int & column);
365 unsigned int & column);
371 unsigned int & column);
377 unsigned int & column);
380 void validate(LaTeXFeatures & features) const;
382 /// Checks if the paragraph contains only text and no inset or font change.
383 bool onlyText(Buffer const & buf, Font const & outerfont,
384 pos_type initial) const;
386 /// a vector of speller skip positions
387 typedef vector<FontSpan> SkipPositions;
388 typedef SkipPositions::const_iterator SkipPositionsIterator;
390 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
392 Language * getSpellLanguage(pos_type const from) const;
394 Language * locateSpellRange(pos_type & from, pos_type & to,
395 SkipPositions & skips) const;
397 bool hasSpellerChange() const
399 SpellChecker::ChangeNumber speller_change_number = 0;
400 if (theSpellChecker())
401 speller_change_number = theSpellChecker()->changeNumber();
402 return speller_change_number > speller_state_.currentChangeNumber();
405 bool ignoreWord(docstring const & word) const ;
407 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
409 pos_type textsize = owner_->size();
410 // check for sane arguments
411 if (to <= from || from >= textsize)
413 FontSpan fp = FontSpan(from, to - 1);
414 speller_state_.setRange(fp, state);
417 void requestSpellCheck(pos_type pos)
420 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
422 speller_state_.needsRefresh(pos);
425 void readySpellCheck()
427 speller_state_.needsRefresh(-1);
430 bool needsSpellCheck() const
432 return speller_state_.needsRefresh();
435 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
437 speller_state_.refreshRange(first, last);
439 last = owner_->size();
442 pos_type endpos = last;
443 owner_->locateWord(first, endpos, WHOLE_WORD, true);
446 owner_->locateWord(last, endpos, WHOLE_WORD, true);
451 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
455 while (it != et && it->first < start) {
456 long skip = it->last - it->first + 1;
464 void markMisspelledWords(pos_type const & first, pos_type const & last,
465 SpellChecker::Result result,
466 docstring const & word,
467 SkipPositions const & skips);
469 InsetCode ownerCode() const
471 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
474 /// Which Paragraph owns us?
478 Inset const * inset_owner_;
484 ParagraphParameters params_;
486 /// for recording and looking up changes
490 InsetList insetlist_;
493 pos_type begin_of_body_;
495 typedef docstring TextContainer;
499 typedef set<docstring> Words;
500 typedef map<string, Words> LangWordsMap;
504 Layout const * layout_;
506 SpellCheckerState speller_state_;
512 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
513 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
520 int Paragraph::Private::make_id()
522 // The id is unique per session across buffers because it is used in
523 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
526 static int next_id(0);
531 Paragraph::Private::Private(Private const & p, Paragraph * owner)
532 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
533 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
534 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
535 layout_(p.layout_), id_(make_id())
537 requestSpellCheck(p.text_.size());
541 Paragraph::Private::Private(Private const & p, Paragraph * owner,
542 pos_type beg, pos_type end)
543 : owner_(owner), inset_owner_(p.inset_owner_),
544 params_(p.params_), changes_(p.changes_),
545 insetlist_(p.insetlist_, beg, end),
546 begin_of_body_(p.begin_of_body_), words_(p.words_),
547 layout_(p.layout_), id_(make_id())
549 if (beg >= pos_type(p.text_.size()))
551 text_ = p.text_.substr(beg, end - beg);
553 FontList::const_iterator fcit = fontlist_.begin();
554 FontList::const_iterator fend = fontlist_.end();
555 for (; fcit != fend; ++fcit) {
556 if (fcit->pos() < beg)
558 if (fcit->pos() >= end) {
559 // Add last entry in the fontlist_.
560 fontlist_.set(text_.size() - 1, fcit->font());
563 // Add a new entry in the fontlist_.
564 fontlist_.set(fcit->pos() - beg, fcit->font());
566 requestSpellCheck(p.text_.size());
570 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
571 bool output_active, TocBackend & backend) const
573 d->changes_.addToToc(cdit, buf, output_active, backend);
577 bool Paragraph::isDeleted(pos_type start, pos_type end) const
579 LASSERT(start >= 0 && start <= size(), return false);
580 LASSERT(end > start && end <= size() + 1, return false);
582 return d->changes_.isDeleted(start, end);
586 bool Paragraph::isChanged(pos_type start, pos_type end) const
588 LASSERT(start >= 0 && start <= size(), return false);
589 LASSERT(end > start && end <= size() + 1, return false);
591 return d->changes_.isChanged(start, end);
594 // FIXME: Ideally the diverse isChanged() methods should account for that!
595 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
597 LASSERT(start >= 0 && start <= size(), return false);
598 LASSERT(end > start && end <= size() + 1, return false);
600 for (auto const & icit : d->insetlist_) {
601 if (icit.pos < start)
605 if (icit.inset && icit.inset->isChanged())
611 bool Paragraph::isChanged() const
613 return d->changes_.isChanged();
617 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
619 // keep the logic here in sync with the logic of eraseChars()
623 Change const & change = d->changes_.lookup(size());
624 return change.inserted() && change.currentAuthor();
627 Change Paragraph::parEndChange() const
629 return d->changes_.lookup(size());
633 void Paragraph::setChange(Change const & change)
635 // beware of the imaginary end-of-par character!
636 d->changes_.set(change, 0, size() + 1);
639 * Propagate the change recursively - but not in case of DELETED!
641 * Imagine that your co-author makes changes in an existing inset. He
642 * sends your document to you and you come to the conclusion that the
643 * inset should go completely. If you erase it, LyX must not delete all
644 * text within the inset. Otherwise, the change tracked insertions of
645 * your co-author get lost and there is no way to restore them later.
647 * Conclusion: An inset's content should remain untouched if you delete it
650 if (!change.deleted()) {
651 for (pos_type pos = 0; pos < size(); ++pos) {
652 if (Inset * inset = getInset(pos))
653 inset->setChange(change);
659 void Paragraph::setChange(pos_type pos, Change const & change)
661 LASSERT(pos >= 0 && pos <= size(), return);
662 d->changes_.set(change, pos);
664 // see comment in setChange(Change const &) above
665 if (!change.deleted() && pos < size())
666 if (Inset * inset = getInset(pos))
667 inset->setChange(change);
671 Change const & Paragraph::lookupChange(pos_type pos) const
673 LBUFERR(pos >= 0 && pos <= size());
674 return d->changes_.lookup(pos);
678 void Paragraph::acceptChanges(pos_type start, pos_type end)
680 LASSERT(start >= 0 && start <= size(), return);
681 LASSERT(end > start && end <= size() + 1, return);
683 for (pos_type pos = start; pos < end; ++pos) {
684 switch (lookupChange(pos).type) {
685 case Change::UNCHANGED:
686 // accept changes in nested inset
687 if (Inset * inset = getInset(pos))
688 inset->acceptChanges();
691 case Change::INSERTED:
692 d->changes_.set(Change(Change::UNCHANGED), pos);
693 // also accept changes in nested inset
694 if (Inset * inset = getInset(pos))
695 inset->acceptChanges();
698 case Change::DELETED:
699 // Suppress access to non-existent
700 // "end-of-paragraph char"
702 eraseChar(pos, false);
713 void Paragraph::rejectChanges(pos_type start, pos_type end)
715 LASSERT(start >= 0 && start <= size(), return);
716 LASSERT(end > start && end <= size() + 1, return);
718 for (pos_type pos = start; pos < end; ++pos) {
719 switch (lookupChange(pos).type) {
720 case Change::UNCHANGED:
721 // reject changes in nested inset
722 if (Inset * inset = getInset(pos))
723 inset->rejectChanges();
726 case Change::INSERTED:
727 // Suppress access to non-existent
728 // "end-of-paragraph char"
730 eraseChar(pos, false);
736 case Change::DELETED:
737 d->changes_.set(Change(Change::UNCHANGED), pos);
739 // Do NOT reject changes within a deleted inset!
740 // There may be insertions of a co-author inside of it!
748 void Paragraph::Private::insertChar(pos_type pos, char_type c,
749 Change const & change)
751 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
754 changes_.insert(change, pos);
756 // This is actually very common when parsing buffers (and
757 // maybe inserting ascii text)
758 if (pos == pos_type(text_.size())) {
759 // when appending characters, no need to update tables
761 // but we want spell checking
762 requestSpellCheck(pos);
766 text_.insert(text_.begin() + pos, c);
768 // Update the font table.
769 fontlist_.increasePosAfterPos(pos);
772 insetlist_.increasePosAfterPos(pos);
774 // Update list of misspelled positions
775 speller_state_.increasePosAfterPos(pos);
779 bool Paragraph::insertInset(pos_type pos, Inset * inset,
780 Font const & font, Change const & change)
782 LASSERT(inset, return false);
783 LASSERT(pos >= 0 && pos <= size(), return false);
785 // Paragraph::insertInset() can be used in cut/copy/paste operation where
786 // d->inset_owner_ is not set yet.
787 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
790 d->insertChar(pos, META_INSET, change);
791 LASSERT(d->text_[pos] == META_INSET, return false);
793 // Add a new entry in the insetlist_.
794 d->insetlist_.insert(inset, pos);
796 // Some insets require run of spell checker
797 requestSpellCheck(pos);
803 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
805 LASSERT(pos >= 0 && pos <= size(), return false);
807 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
810 Change change = d->changes_.lookup(pos);
812 // set the character to DELETED if
813 // a) it was previously unchanged or
814 // b) it was inserted by a co-author
816 if (!change.changed() ||
817 (change.inserted() && !change.currentAuthor())) {
818 setChange(pos, Change(Change::DELETED));
819 // request run of spell checker
820 requestSpellCheck(pos);
824 if (change.deleted())
828 // Don't physically access the imaginary end-of-paragraph character.
829 // eraseChar() can only mark it as DELETED. A physical deletion of
830 // end-of-par must be handled externally.
836 d->changes_.erase(pos);
838 // if it is an inset, delete the inset entry
839 if (d->text_[pos] == META_INSET)
840 d->insetlist_.erase(pos);
842 d->text_.erase(d->text_.begin() + pos);
844 // Update the fontlist_
845 d->fontlist_.erase(pos);
847 // Update the insetlist_
848 d->insetlist_.decreasePosAfterPos(pos);
850 // Update list of misspelled positions
851 d->speller_state_.decreasePosAfterPos(pos);
852 d->speller_state_.refreshLast(size());
858 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
860 LASSERT(start >= 0 && start <= size(), return 0);
861 LASSERT(end >= start && end <= size() + 1, return 0);
864 for (pos_type count = end - start; count; --count) {
865 if (!eraseChar(i, trackChanges))
871 // Handle combining characters
872 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
873 otexstream & os, char_type c, char_type next,
874 OutputParams const & runparams)
876 // Writing next here may circumvent a possible font change between
877 // c and next. Since next is only output if it forms a surrogate pair
878 // with c we can ignore this:
879 // A font change inside a surrogate pair does not make sense and is
880 // hopefully impossible to input.
881 // FIXME: change tracking
882 // Is this correct WRT change tracking?
883 Encoding const & encoding = *(runparams.encoding);
884 docstring latex1 = encoding.latexChar(next).first;
885 if (runparams.inIPA) {
886 string const tipashortcut = Encodings::TIPAShortcut(next);
887 if (!tipashortcut.empty()) {
888 latex1 = from_ascii(tipashortcut);
891 docstring latex2 = encoding.latexChar(c).first;
893 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
894 // Encoding supports the combination:
895 // output as is (combining char after base char).
896 os << latex2 << latex1;
897 return latex1.length() + latex2.length();
900 os << latex1 << "{" << latex2 << "}";
901 return latex1.length() + latex2.length() + 2;
905 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
906 OutputParams const & runparams,
909 unsigned int & column,
911 Layout const & style)
913 if (style.pass_thru || runparams.pass_thru)
916 if (i + 1 < int(text_.size())) {
917 char_type next = text_[i + 1];
918 if (Encodings::isCombiningChar(next)) {
919 // This space has an accent, so we must always output it.
920 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
925 if (runparams.linelen > 0
926 && column > runparams.linelen
928 && text_[i - 1] != ' '
929 && (i + 1 < int(text_.size()))
930 // same in FreeSpacing mode
931 && !owner_->isFreeSpacing()
932 // In typewriter mode, we want to avoid
933 // ! . ? : at the end of a line
934 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
935 && (text_[i - 1] == '.'
936 || text_[i - 1] == '?'
937 || text_[i - 1] == ':'
938 || text_[i - 1] == '!'))) {
940 os.texrow().start(owner_->id(), i + 1);
942 } else if (style.free_spacing) {
951 void Paragraph::Private::latexInset(BufferParams const & bparams,
953 OutputParams & runparams,
956 Font const & outerfont,
958 Change & running_change,
959 Layout const & style,
961 unsigned int & column,
962 bool const fontswitch_inset)
964 Inset * inset = owner_->getInset(i);
967 if (style.pass_thru) {
968 odocstringstream ods;
969 inset->plaintext(ods, runparams);
974 // FIXME: move this to InsetNewline::latex
975 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
976 // newlines are handled differently here than
977 // the default in simpleTeXSpecialChars().
978 if (!style.newline_allowed) {
982 bool needPar = false;
983 column += running_font.latexWriteEndChanges(
984 os, bparams, runparams,
985 basefont, basefont, needPar);
989 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
992 basefont = owner_->getLayoutFont(bparams, outerfont);
993 running_font = basefont;
995 if (runparams.moving_arg)
999 os.texrow().start(owner_->id(), i + 1);
1003 if (owner_->isDeleted(i)) {
1004 if( ++runparams.inDeletedInset == 1)
1005 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1008 if (inset->canTrackChanges()) {
1009 column += Changes::latexMarkChange(os, bparams, running_change,
1010 Change(Change::UNCHANGED), runparams);
1011 running_change = Change(Change::UNCHANGED);
1015 odocstream::pos_type const len = os.os().tellp();
1017 if (inset->forceLTR(runparams)
1018 && running_font.isRightToLeft()
1019 // ERT is an exception, it should be output with no
1020 // decorations at all
1021 && inset->lyxCode() != ERT_CODE) {
1022 if (runparams.use_polyglossia) {
1024 } else if (running_font.language()->lang() == "farsi"
1025 || running_font.language()->lang() == "arabic_arabi")
1026 os << "\\textLR{" << termcmd;
1032 if (open_font && (!inset->inheritFont() || fontswitch_inset)) {
1033 // Some insets cannot be inside a font change command.
1034 // However, even such insets *can* be placed in \L or \R
1035 // or their equivalents (for RTL language switches),
1036 // so we don't close the language in those cases
1037 // (= differing isRightToLeft()).
1038 // ArabTeX, though, doesn't seem to handle this special behavior.
1039 bool const inRLSwitch =
1040 basefont.isRightToLeft() != running_font.isRightToLeft()
1041 && basefont.language()->lang() != "arabic_arabtex"
1042 && running_font.language()->lang() != "arabic_arabtex";
1043 // Having said that, PassThru insets must be inside a font change command,
1044 // as we do not re-open the font inside. So:
1045 bool const closeLanguage = !inset->isPassThru() && !inRLSwitch;
1046 bool lang_closed = false;
1047 bool lang_switched_at_inset = false;
1048 // Close language if needed
1049 if (closeLanguage) {
1050 // We need prev_font here as language changes directly at inset
1051 // will only be started inside the inset.
1052 Font const prev_font = (i > 0) ?
1053 owner_->getFont(bparams, i - 1, outerfont)
1055 Font tmpfont(basefont);
1056 tmpfont.setLanguage(prev_font.language());
1057 bool needPar = false;
1058 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1060 needPar, closeLanguage);
1062 lang_closed = count > 0;
1063 lang_switched_at_inset = prev_font.language() != running_font.language();
1065 // Update the running_font, making sure, however,
1066 // to leave the language as it was.
1067 // FIXME: probably a better way to keep track of the old
1068 // language, than copying the entire font?
1069 Font const copy_font(running_font);
1070 basefont = owner_->getLayoutFont(bparams, outerfont);
1071 running_font = basefont;
1073 running_font.setLanguage(copy_font.language());
1074 OutputParams rp = runparams;
1075 rp.encoding = basefont.language()->encoding();
1076 // For these, we use switches, so they should be taken as
1077 // base inside the inset.
1078 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1079 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1080 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1081 // Now re-do font changes in a way needed here
1082 // (using switches with multi-par insets)
1083 InsetText const * textinset = inset->asInsetText();
1084 bool const cprotect = textinset
1085 ? textinset->hasCProtectContent(runparams.moving_arg)
1086 && !textinset->text().isMainText()
1088 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1093 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1097 runparams.local_font = &basefont;
1100 size_t const previous_row_count = os.texrow().rows();
1103 runparams.lastid = id_;
1104 runparams.lastpos = i;
1105 inset->latex(os, runparams);
1106 } catch (EncodingException & e) {
1107 // add location information and throw again.
1116 if (os.texrow().rows() > previous_row_count) {
1117 os.texrow().start(owner_->id(), i + 1);
1120 column += (unsigned int)(os.os().tellp() - len);
1123 if (owner_->isDeleted(i))
1124 --runparams.inDeletedInset;
1128 void Paragraph::Private::latexSpecialChar(otexstream & os,
1129 BufferParams const & bparams,
1130 OutputParams const & runparams,
1131 Font const & running_font,
1132 string & alien_script,
1133 Layout const & style,
1136 unsigned int & column)
1138 char_type const c = owner_->getUChar(bparams, runparams, i);
1140 if (style.pass_thru || runparams.pass_thru
1141 || contains(style.pass_thru_chars, c)
1142 || contains(runparams.pass_thru_chars, c)) {
1144 Encoding const * const enc = runparams.encoding;
1145 if (enc && !enc->encodable(c))
1146 throw EncodingException(c);
1152 // TIPA uses its own T3 encoding
1153 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1155 // If T1 font encoding is used, use the special
1156 // characters it provides.
1157 // NOTE: Some languages reset the font encoding internally to a
1158 // non-standard font encoding. If we are using such a language,
1159 // we do not output special T1 chars.
1160 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1161 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1162 && latexSpecialT1(c, os, i, column))
1164 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1165 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1166 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1169 // Otherwise, we use what LaTeX provides us.
1172 os << "\\textbackslash" << termcmd;
1176 os << "\\textless" << termcmd;
1180 os << "\\textgreater" << termcmd;
1184 os << "\\textbar" << termcmd;
1189 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1190 (end_pos == -1 || i + 1 < end_pos) &&
1191 text_[i+1] == '-') {
1192 // Prevent "--" becoming an en dash and "---" an em dash.
1193 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1199 os << "\\textquotedbl" << termcmd;
1204 case '%': case '#': case '{':
1212 os << "\\textasciitilde" << termcmd;
1217 os << "\\textasciicircum" << termcmd;
1224 // avoid being mistaken for optional arguments
1232 // Blanks are printed before font switching.
1233 // Sure? I am not! (try nice-latex)
1234 // I am sure it's correct. LyX might be smarter
1235 // in the future, but for now, nothing wrong is
1241 // XeTeX's dash behaviour is determined via a global setting
1242 if (bparams.use_dash_ligatures
1243 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1245 // TODO #10961: && not in inset Flex Code
1246 // TODO #10961: && not in layout LyXCode
1247 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1264 Encoding const & encoding = *(runparams.encoding);
1265 char_type next = '\0';
1266 if (i + 1 < int(text_.size())) {
1267 next = text_[i + 1];
1268 if (Encodings::isCombiningChar(next)) {
1269 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1274 pair<docstring, bool> latex = encoding.latexChar(c);
1275 docstring nextlatex;
1276 bool nexttipas = false;
1277 string nexttipashortcut;
1278 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1279 nextlatex = encoding.latexChar(next).first;
1280 if (runparams.inIPA) {
1281 nexttipashortcut = Encodings::TIPAShortcut(next);
1282 nexttipas = !nexttipashortcut.empty();
1286 if (runparams.inIPA) {
1287 string const tipashortcut = Encodings::TIPAShortcut(c);
1288 if (!tipashortcut.empty()) {
1289 latex.first = from_ascii(tipashortcut);
1290 latex.second = false;
1294 // eventually close "script wrapper" command (see `Paragraph::latex`)
1295 if (!alien_script.empty()
1296 && alien_script != Encodings::isKnownScriptChar(next)) {
1297 column += latex.first.length();
1298 alien_script.clear();
1299 os << latex.first << "}";
1303 && ((!prefixIs(nextlatex, '\\')
1304 && !prefixIs(nextlatex, '{')
1305 && !prefixIs(nextlatex, '}'))
1307 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1309 // Prevent eating of a following space or command corruption by
1310 // following characters
1311 if (next == ' ' || next == '\0') {
1312 column += latex.first.length() + 1;
1313 os << latex.first << "{}";
1315 column += latex.first.length();
1316 os << latex.first << " ";
1319 column += latex.first.length() - 1;
1327 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1328 pos_type i, unsigned int & column)
1334 // In T1 encoding, these characters exist
1335 // but we should avoid ligatures
1336 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1338 os << "\\textcompwordmark" << termcmd;
1345 // soul.sty breaks with \char`\"
1346 os << "\\textquotedbl" << termcmd;
1355 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1356 pos_type i, unsigned int & column)
1358 // TU encoding is currently on par with T1.
1359 return latexSpecialT1(c, os, i, column);
1363 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1364 pos_type /*i*/, unsigned int & column)
1374 os << "\\textvertline" << termcmd;
1383 void Paragraph::Private::validate(LaTeXFeatures & features) const
1385 if (layout_->inpreamble && inset_owner_) {
1386 // FIXME: Using a string stream here circumvents the encoding
1387 // switching machinery of odocstream. Therefore the
1388 // output is wrong if this paragraph contains content
1389 // that needs to switch encoding.
1390 Buffer const & buf = inset_owner_->buffer();
1391 otexstringstream os;
1392 os << layout_->preamble();
1393 size_t const length = os.length();
1394 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1395 buf.getParFromID(owner_->id()).pit(), os,
1396 features.runparams(), string(), 0, -1, true);
1397 if (os.length() > length)
1398 features.addPreambleSnippet(os.release(), true);
1401 if (features.runparams().flavor == OutputParams::HTML
1402 && layout_->htmltitle()) {
1403 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1406 // check the params.
1407 if (!params_.spacing().isDefault())
1408 features.require("setspace");
1411 features.useLayout(layout_->name());
1414 fontlist_.validate(features);
1416 // then the indentation
1417 if (!params_.leftIndent().zero())
1418 features.require("ParagraphLeftIndent");
1421 InsetList::const_iterator icit = insetlist_.begin();
1422 InsetList::const_iterator iend = insetlist_.end();
1423 for (; icit != iend; ++icit) {
1425 features.inDeletedInset(owner_->isDeleted(icit->pos));
1426 if (icit->inset->lyxCode() == FOOT_CODE) {
1427 // FIXME: an item inset would make things much easier.
1428 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1429 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1430 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1431 && (icit->pos < begin_of_body_
1432 || (icit->pos == begin_of_body_
1433 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1434 features.saveNoteEnv("description");
1436 icit->inset->validate(features);
1437 features.inDeletedInset(false);
1438 if (layout_->needprotect &&
1439 icit->inset->lyxCode() == FOOT_CODE)
1440 features.require("NeedLyXFootnoteCode");
1444 // then the contents
1445 BufferParams const bp = features.runparams().is_child
1446 ? features.buffer().masterParams() : features.buffer().params();
1447 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1448 char_type c = text_[i];
1449 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1451 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1452 features.require("textquotedblp");
1453 else if (bp.main_font_encoding() != "T1"
1454 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1455 features.require("textquotedbl");
1456 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1457 // features that depend on the font or input encoding
1458 string feats = ci.textpreamble();
1459 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1460 if (fontenc.empty())
1461 fontenc = features.runparams().main_fontenc;
1462 while (!feats.empty()) {
1464 feats = split(feats, feat, ',');
1465 if (contains(feat, "!=")) {
1466 // a feature that is required except for the spcified
1467 // font or input encodings
1469 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1470 // multiple encodings are separated by semicolon
1471 vector<string> context = getVectorFromString(contexts, ";");
1472 // require feature if the context matches neither current font
1473 // nor input encoding
1474 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1475 && std::find(context.begin(), context.end(),
1476 features.runparams().encoding->name()) == context.end())
1477 features.require(realfeature);
1478 } else if (contains(feat, '=')) {
1479 // a feature that is required only for the spcified
1480 // font or input encodings
1482 string const contexts = split(feat, realfeature, '=');
1483 // multiple encodings are separated by semicolon
1484 vector<string> context = getVectorFromString(contexts, ";");
1485 // require feature if the context matches either current font
1486 // or input encoding
1487 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1488 || std::find(context.begin(), context.end(),
1489 features.runparams().encoding->name()) != context.end())
1490 features.require(realfeature);
1493 } else if (!bp.use_dash_ligatures
1494 && (c == 0x2013 || c == 0x2014)
1495 && bp.useNonTeXFonts
1496 && features.runparams().flavor == OutputParams::XETEX)
1497 // XeTeX's dash behaviour is determined via a global setting
1498 features.require("xetexdashbreakstate");
1499 BufferEncodings::validate(c, features);
1503 /////////////////////////////////////////////////////////////////////
1507 /////////////////////////////////////////////////////////////////////
1510 Layout const emptyParagraphLayout;
1513 Paragraph::Paragraph()
1514 : d(new Paragraph::Private(this, emptyParagraphLayout))
1521 Paragraph::Paragraph(Paragraph const & par)
1522 : itemdepth(par.itemdepth),
1523 d(new Paragraph::Private(*par.d, this))
1529 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1530 : itemdepth(par.itemdepth),
1531 d(new Paragraph::Private(*par.d, this, beg, end))
1537 Paragraph & Paragraph::operator=(Paragraph const & par)
1539 // needed as we will destroy the private part before copying it
1541 itemdepth = par.itemdepth;
1545 d = new Private(*par.d, this);
1552 Paragraph::~Paragraph()
1561 // this shall be called just before every "os << ..." action.
1562 void flushString(ostream & os, docstring & s)
1571 void Paragraph::write(ostream & os, BufferParams const & bparams,
1572 depth_type & dth) const
1574 // The beginning or end of a deeper (i.e. nested) area?
1575 if (dth != d->params_.depth()) {
1576 if (d->params_.depth() > dth) {
1577 while (d->params_.depth() > dth) {
1578 os << "\n\\begin_deeper";
1582 while (d->params_.depth() < dth) {
1583 os << "\n\\end_deeper";
1589 // First write the layout
1590 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1592 d->params_.write(os);
1594 Font font1(inherit_font, bparams.language);
1596 Change running_change = Change(Change::UNCHANGED);
1598 // this string is used as a buffer to avoid repetitive calls
1599 // to to_utf8(), which turn out to be expensive (JMarc)
1600 docstring write_buffer;
1603 for (pos_type i = 0; i <= size(); ++i) {
1605 Change const & change = lookupChange(i);
1606 if (change != running_change)
1607 flushString(os, write_buffer);
1608 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1609 running_change = change;
1614 // Write font changes
1615 Font font2 = getFontSettings(bparams, i);
1616 if (font2 != font1) {
1617 flushString(os, write_buffer);
1618 font2.lyxWriteChanges(font1, os);
1623 char_type const c = d->text_[i];
1626 if (Inset const * inset = getInset(i)) {
1627 flushString(os, write_buffer);
1628 if (inset->directWrite()) {
1629 // international char, let it write
1630 // code directly so it's shorter in
1636 os << "\\begin_inset ";
1638 os << "\n\\end_inset\n\n";
1641 // FIXME This can be removed again once the mystery
1642 // crash has been resolved.
1647 flushString(os, write_buffer);
1648 os << "\n\\backslash\n";
1652 flushString(os, write_buffer);
1653 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1660 if ((column > 70 && c == ' ')
1662 flushString(os, write_buffer);
1666 // this check is to amend a bug. LyX sometimes
1667 // inserts '\0' this could cause problems.
1669 write_buffer.push_back(c);
1671 LYXERR0("NUL char in structure.");
1677 flushString(os, write_buffer);
1678 os << "\n\\end_layout\n";
1679 // FIXME This can be removed again once the mystery
1680 // crash has been resolved.
1685 void Paragraph::validate(LaTeXFeatures & features) const
1687 d->validate(features);
1688 bool fragile = features.runparams().moving_arg;
1689 fragile |= layout().needprotect;
1690 if (inInset().getLayout().isNeedProtect())
1692 if (needsCProtection(fragile))
1693 features.require("cprotect");
1697 void Paragraph::insert(pos_type start, docstring const & str,
1698 Font const & font, Change const & change)
1700 for (size_t i = 0, n = str.size(); i != n ; ++i)
1701 insertChar(start + i, str[i], font, change);
1705 void Paragraph::appendChar(char_type c, Font const & font,
1706 Change const & change)
1709 d->changes_.insert(change, d->text_.size());
1710 // when appending characters, no need to update tables
1711 d->text_.push_back(c);
1712 setFont(d->text_.size() - 1, font);
1713 d->requestSpellCheck(d->text_.size() - 1);
1717 void Paragraph::appendString(docstring const & s, Font const & font,
1718 Change const & change)
1720 pos_type end = s.size();
1721 size_t oldsize = d->text_.size();
1722 size_t newsize = oldsize + end;
1723 size_t capacity = d->text_.capacity();
1724 if (newsize >= capacity)
1725 d->text_.reserve(max(capacity + 100, newsize));
1727 // when appending characters, no need to update tables
1730 // FIXME: Optimize this!
1731 for (size_t i = oldsize; i != newsize; ++i) {
1733 d->changes_.insert(change, i);
1734 d->requestSpellCheck(i);
1736 d->fontlist_.set(oldsize, font);
1737 d->fontlist_.set(newsize - 1, font);
1741 void Paragraph::insertChar(pos_type pos, char_type c,
1744 d->insertChar(pos, c, Change(trackChanges ?
1745 Change::INSERTED : Change::UNCHANGED));
1749 void Paragraph::insertChar(pos_type pos, char_type c,
1750 Font const & font, bool trackChanges)
1752 d->insertChar(pos, c, Change(trackChanges ?
1753 Change::INSERTED : Change::UNCHANGED));
1758 void Paragraph::insertChar(pos_type pos, char_type c,
1759 Font const & font, Change const & change)
1761 d->insertChar(pos, c, change);
1766 void Paragraph::resetFonts(Font const & font)
1768 d->fontlist_.clear();
1769 d->fontlist_.set(0, font);
1770 d->fontlist_.set(d->text_.size() - 1, font);
1773 // Gets uninstantiated font setting at position.
1774 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1778 LYXERR0("pos: " << pos << " size: " << size());
1782 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1783 if (cit != d->fontlist_.end())
1786 if (pos == size() && !empty())
1787 return getFontSettings(bparams, pos - 1);
1789 // Optimisation: avoid a full font instantiation if there is no
1790 // language change from previous call.
1791 static Font previous_font;
1792 static Language const * previous_lang = nullptr;
1793 Language const * lang = getParLanguage(bparams);
1794 if (lang != previous_lang) {
1795 previous_lang = lang;
1796 previous_font = Font(inherit_font, lang);
1798 return previous_font;
1802 FontSpan Paragraph::fontSpan(pos_type pos) const
1804 LBUFERR(pos <= size());
1807 return FontSpan(pos, pos);
1810 FontList::const_iterator cit = d->fontlist_.begin();
1811 FontList::const_iterator end = d->fontlist_.end();
1812 for (; cit != end; ++cit) {
1813 if (cit->pos() >= pos) {
1814 if (pos >= beginOfBody())
1815 return FontSpan(max(start, beginOfBody()),
1818 return FontSpan(start,
1819 min(beginOfBody() - 1,
1822 start = cit->pos() + 1;
1825 // This should not happen, but if so, we take no chances.
1826 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1827 LASSERT(false, return FontSpan(pos, pos));
1831 // Gets uninstantiated font setting at position 0
1832 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1834 if (!empty() && !d->fontlist_.empty())
1835 return d->fontlist_.begin()->font();
1837 // Optimisation: avoid a full font instantiation if there is no
1838 // language change from previous call.
1839 static Font previous_font;
1840 static Language const * previous_lang = nullptr;
1841 if (bparams.language != previous_lang) {
1842 previous_lang = bparams.language;
1843 previous_font = Font(inherit_font, bparams.language);
1846 return previous_font;
1850 // Gets the fully instantiated font at a given position in a paragraph
1851 // This is basically the same function as Text::GetFont() in text2.cpp.
1852 // The difference is that this one is used for generating the LaTeX file,
1853 // and thus cosmetic "improvements" are disallowed: This has to deliver
1854 // the true picture of the buffer. (Asger)
1855 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1856 Font const & outerfont) const
1860 Font font = getFontSettings(bparams, pos);
1862 pos_type const body_pos = beginOfBody();
1863 FontInfo & fi = font.fontInfo();
1865 fi.realize(d->layout_->labelfont);
1867 fi.realize(d->layout_->font);
1869 fi.realize(outerfont.fontInfo());
1870 fi.realize(bparams.getFont().fontInfo());
1876 Font const Paragraph::getLabelFont
1877 (BufferParams const & bparams, Font const & outerfont) const
1879 FontInfo tmpfont = d->layout_->labelfont;
1880 tmpfont.realize(outerfont.fontInfo());
1881 tmpfont.realize(bparams.getFont().fontInfo());
1882 return Font(tmpfont, getParLanguage(bparams));
1886 Font const Paragraph::getLayoutFont
1887 (BufferParams const & bparams, Font const & outerfont) const
1889 FontInfo tmpfont = d->layout_->font;
1890 tmpfont.realize(outerfont.fontInfo());
1891 tmpfont.realize(bparams.getFont().fontInfo());
1892 return Font(tmpfont, getParLanguage(bparams));
1896 char_type Paragraph::getUChar(BufferParams const & bparams,
1897 OutputParams const & rp,
1900 char_type c = d->text_[pos];
1902 // Return unchanged character in LTR languages
1903 // or if we use poylglossia/bidi (XeTeX).
1904 if (rp.useBidiPackage()
1905 || !getFontSettings(bparams, pos).isRightToLeft())
1908 // Without polyglossia/bidi, we need to account for some special cases.
1909 // FIXME This needs to be audited!
1911 // * The input is as expected for all delimiters
1912 // => checked for Hebrew!
1913 // * The output matches the display in the LyX workarea
1914 // => checked for Hebrew!
1915 // * The special cases below are really necessary
1916 // => checked for Hebrew!
1917 // * In arabic_arabi, brackets are transformed to Arabic
1918 // Ornate Parentheses. Is this is really wanted?
1920 string const & lang = getFontSettings(bparams, pos).language()->lang();
1923 // 1. In the following languages, parentheses need to be reversed.
1924 // Also with polyglodia/luabidi
1925 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1927 // 2. In the following languages, brackets don't need to be reversed.
1928 bool const reversebrackets = lang != "arabic_arabtex"
1929 && lang != "arabic_arabi"
1932 // Now swap delimiters if needed.
1943 if (reversebrackets)
1947 if (reversebrackets)
1968 void Paragraph::setFont(pos_type pos, Font const & font)
1970 LASSERT(pos <= size(), return);
1972 // First, reduce font against layout/label font
1973 // Update: The setCharFont() routine in text2.cpp already
1974 // reduces font, so we don't need to do that here. (Asger)
1976 d->fontlist_.set(pos, font);
1980 void Paragraph::makeSameLayout(Paragraph const & par)
1982 d->layout_ = par.d->layout_;
1983 d->params_ = par.d->params_;
1987 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1989 if (isFreeSpacing())
1995 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1996 if (eraseChar(pos, trackChanges))
2002 return count > 0 || pos > 0;
2006 bool Paragraph::hasSameLayout(Paragraph const & par) const
2008 return par.d->layout_ == d->layout_
2009 && d->params_.sameLayout(par.d->params_);
2013 depth_type Paragraph::getDepth() const
2015 return d->params_.depth();
2019 depth_type Paragraph::getMaxDepthAfter() const
2021 if (d->layout_->isEnvironment())
2022 return d->params_.depth() + 1;
2024 return d->params_.depth();
2028 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2030 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2031 return getDefaultAlign(bparams);
2033 return d->params_.align();
2037 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2039 LyXAlignment res = layout().align;
2040 if (isRTL(bparams)) {
2042 if (res == LYX_ALIGN_LEFT)
2043 res = LYX_ALIGN_RIGHT;
2044 else if (res == LYX_ALIGN_RIGHT)
2045 res = LYX_ALIGN_LEFT;
2051 docstring const & Paragraph::labelString() const
2053 return d->params_.labelString();
2057 // the next two functions are for the manual labels
2058 docstring const Paragraph::getLabelWidthString() const
2060 if (d->layout_->margintype == MARGIN_MANUAL
2061 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2062 return d->params_.labelWidthString();
2064 return _("Senseless with this layout!");
2068 void Paragraph::setLabelWidthString(docstring const & s)
2070 d->params_.labelWidthString(s);
2074 docstring Paragraph::expandLabel(Layout const & layout,
2075 BufferParams const & bparams) const
2077 return expandParagraphLabel(layout, bparams, true);
2081 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2082 BufferParams const & bparams, bool process_appendix) const
2084 DocumentClass const & tclass = bparams.documentClass();
2085 string const & lang = getParLanguage(bparams)->code();
2086 bool const in_appendix = process_appendix && d->params_.appendix();
2087 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2089 if (fmt.empty() && !layout.counter.empty())
2090 return tclass.counters().theCounter(layout.counter, lang);
2092 // handle 'inherited level parts' in 'fmt',
2093 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2094 size_t const i = fmt.find('@', 0);
2095 if (i != docstring::npos) {
2096 size_t const j = fmt.find('@', i + 1);
2097 if (j != docstring::npos) {
2098 docstring parent(fmt, i + 1, j - i - 1);
2099 docstring label = from_ascii("??");
2100 if (tclass.hasLayout(parent))
2101 label = expandParagraphLabel(tclass[parent], bparams,
2103 fmt = docstring(fmt, 0, i) + label
2104 + docstring(fmt, j + 1, docstring::npos);
2108 return tclass.counters().counterLabel(fmt, lang);
2112 void Paragraph::applyLayout(Layout const & new_layout)
2114 d->layout_ = &new_layout;
2115 LyXAlignment const oldAlign = d->params_.align();
2117 if (!(oldAlign & d->layout_->alignpossible)) {
2118 frontend::Alert::warning(_("Alignment not permitted"),
2119 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2120 d->params_.align(LYX_ALIGN_LAYOUT);
2125 pos_type Paragraph::beginOfBody() const
2127 return d->begin_of_body_;
2131 void Paragraph::setBeginOfBody()
2133 if (d->layout_->labeltype != LABEL_MANUAL) {
2134 d->begin_of_body_ = 0;
2138 // Unroll the first two cycles of the loop
2139 // and remember the previous character to
2140 // remove unnecessary getChar() calls
2142 pos_type end = size();
2143 bool prev_char_deleted = false;
2144 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2147 char_type previous_char = d->text_[i];
2148 if (!(isNewline(i) || isEnvSeparator(i))) {
2150 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2151 char_type temp = d->text_[i];
2152 prev_char_deleted = isDeleted(i);
2153 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2156 previous_char = temp;
2162 d->begin_of_body_ = i;
2166 bool Paragraph::allowParagraphCustomization() const
2168 return inInset().allowParagraphCustomization();
2172 bool Paragraph::usePlainLayout() const
2174 return inInset().usePlainLayout();
2178 bool Paragraph::isPassThru() const
2180 return inInset().isPassThru() || d->layout_->pass_thru;
2185 // paragraphs inside floats need different alignment tags to avoid
2188 bool noTrivlistCentering(InsetCode code)
2190 return code == FLOAT_CODE
2191 || code == WRAP_CODE
2192 || code == CELL_CODE;
2196 string correction(string const & orig)
2198 if (orig == "flushleft")
2199 return "raggedright";
2200 if (orig == "flushright")
2201 return "raggedleft";
2202 if (orig == "center")
2208 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2209 InsetCode code, bool const lastpar, int & col)
2211 string macro = suffix + "{";
2212 if (noTrivlistCentering(code)) {
2214 // the last paragraph in non-trivlist-aligned
2215 // context is special (to avoid unwanted whitespace)
2216 if (suffix == "\\begin") {
2217 macro = "\\" + correction(env) + "{}";
2218 os << from_ascii(macro);
2219 col += macro.size();
2224 macro += correction(env);
2228 if (suffix == "\\par\\end") {
2232 os << from_ascii(macro);
2233 col += macro.size();
2234 if (suffix == "\\begin") {
2244 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2245 otexstream & os, OutputParams const & runparams) const
2250 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2251 (layout_->toggle_indent != ITOGGLE_NEVER) :
2252 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2254 if (canindent && params_.noindent() && !layout_->pass_thru) {
2255 os << "\\noindent ";
2259 LyXAlignment const curAlign = params_.align();
2261 if (curAlign == layout_->align)
2265 case LYX_ALIGN_NONE:
2266 case LYX_ALIGN_BLOCK:
2267 case LYX_ALIGN_LAYOUT:
2268 case LYX_ALIGN_SPECIAL:
2269 case LYX_ALIGN_DECIMAL:
2271 case LYX_ALIGN_LEFT:
2272 case LYX_ALIGN_RIGHT:
2273 case LYX_ALIGN_CENTER:
2274 if (runparams.moving_arg) {
2281 string const begin_tag = "\\begin";
2282 InsetCode code = ownerCode();
2283 bool const lastpar = runparams.isLastPar;
2284 // RTL in classic (PDF)LaTeX (without the Bidi package)
2285 // Luabibdi (used by LuaTeX) behaves like classic
2286 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2287 && !runparams.useBidiPackage();
2290 case LYX_ALIGN_NONE:
2291 case LYX_ALIGN_BLOCK:
2292 case LYX_ALIGN_LAYOUT:
2293 case LYX_ALIGN_SPECIAL:
2294 case LYX_ALIGN_DECIMAL:
2296 case LYX_ALIGN_LEFT: {
2298 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2299 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2301 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2303 } case LYX_ALIGN_RIGHT: {
2305 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2306 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2308 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2310 } case LYX_ALIGN_CENTER: {
2311 corrected_env(os, begin_tag, "center", code, lastpar, column);
2320 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2321 otexstream & os, OutputParams const & runparams) const
2323 LyXAlignment const curAlign = params_.align();
2325 if (curAlign == layout_->align)
2329 case LYX_ALIGN_NONE:
2330 case LYX_ALIGN_BLOCK:
2331 case LYX_ALIGN_LAYOUT:
2332 case LYX_ALIGN_SPECIAL:
2333 case LYX_ALIGN_DECIMAL:
2335 case LYX_ALIGN_LEFT:
2336 case LYX_ALIGN_RIGHT:
2337 case LYX_ALIGN_CENTER:
2338 if (runparams.moving_arg)
2343 bool output = false;
2345 string const end_tag = "\\par\\end";
2346 InsetCode code = ownerCode();
2347 bool const lastpar = runparams.isLastPar;
2348 // RTL in classic (PDF)LaTeX (without the Bidi package)
2349 // Luabibdi (used by LuaTeX) behaves like classic
2350 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2351 && !runparams.useBidiPackage();
2354 case LYX_ALIGN_NONE:
2355 case LYX_ALIGN_BLOCK:
2356 case LYX_ALIGN_LAYOUT:
2357 case LYX_ALIGN_SPECIAL:
2358 case LYX_ALIGN_DECIMAL:
2360 case LYX_ALIGN_LEFT: {
2362 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2363 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2365 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2367 } case LYX_ALIGN_RIGHT: {
2369 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2370 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2372 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2374 } case LYX_ALIGN_CENTER: {
2375 corrected_env(os, end_tag, "center", code, lastpar, col);
2380 return output || lastpar;
2384 // This one spits out the text of the paragraph
2385 void Paragraph::latex(BufferParams const & bparams,
2386 Font const & outerfont,
2388 OutputParams const & runparams,
2389 int start_pos, int end_pos, bool force) const
2391 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2393 // FIXME This check should not be needed. Perhaps issue an
2394 // error if it triggers.
2395 Layout const & style = inInset().forcePlainLayout() ?
2396 bparams.documentClass().plainLayout() : *d->layout_;
2398 if (!force && style.inpreamble)
2401 bool const allowcust = allowParagraphCustomization();
2403 // Current base font for all inherited font changes, without any
2404 // change caused by an individual character, except for the language:
2405 // It is set to the language of the first character.
2406 // As long as we are in the label, this font is the base font of the
2407 // label. Before the first body character it is set to the base font
2411 // If there is an open font-encoding changing command (script wrapper),
2412 // alien_script is set to its name
2413 string alien_script;
2416 // Maybe we have to create a optional argument.
2417 pos_type body_pos = beginOfBody();
2418 unsigned int column = 0;
2420 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2421 Font const real_outerfont = (!inInset().inheritFont()
2422 && runparams.local_font != nullptr)
2423 ? Font(runparams.local_font->fontInfo()) : outerfont;
2426 // the optional argument is kept in curly brackets in
2427 // case it contains a ']'
2428 // This is not strictly needed, but if this is changed it
2429 // would be a file format change, and tex2lyx would need
2430 // to be adjusted, since it unconditionally removes the
2431 // braces when it parses \item.
2434 basefont = getLabelFont(bparams, real_outerfont);
2436 basefont = getLayoutFont(bparams, real_outerfont);
2439 // Which font is currently active?
2440 Font running_font(basefont);
2441 // Do we have an open font change?
2442 bool open_font = false;
2444 Change runningChange = Change(Change::UNCHANGED);
2446 Encoding const * const prev_encoding = runparams.encoding;
2448 os.texrow().start(id(), 0);
2450 // if the paragraph is empty, the loop will not be entered at all
2452 // For InTitle commands, we have already opened a group
2453 // in output_latex::TeXOnePar.
2454 if (style.isCommand() && !style.intitle) {
2458 if (!style.leftdelim().empty()) {
2459 os << style.leftdelim();
2460 column += style.leftdelim().size();
2463 column += d->startTeXParParams(bparams, os, runparams);
2466 // Whether a \par can be issued for insets typeset inline with text.
2467 // Yes if greater than 0. This has to be static.
2468 THREAD_LOCAL_STATIC int parInline = 0;
2470 for (pos_type i = 0; i < size(); ++i) {
2471 // First char in paragraph or after label?
2472 if (i == body_pos) {
2475 bool needPar = false;
2476 column += running_font.latexWriteEndChanges(
2477 os, bparams, runparams,
2478 basefont, basefont, needPar);
2481 basefont = getLayoutFont(bparams, real_outerfont);
2482 running_font = basefont;
2484 column += Changes::latexMarkChange(os, bparams,
2485 runningChange, Change(Change::UNCHANGED),
2487 runningChange = Change(Change::UNCHANGED);
2492 // For InTitle commands, we have already opened a group
2493 // in output_latex::TeXOnePar.
2494 if (style.isCommand() && !style.intitle) {
2499 if (!style.leftdelim().empty()) {
2500 os << style.leftdelim();
2501 column += style.leftdelim().size();
2505 column += d->startTeXParParams(bparams, os,
2509 runparams.wasDisplayMath = runparams.inDisplayMath;
2510 runparams.inDisplayMath = false;
2511 bool deleted_display_math = false;
2512 Change const & change = runparams.inDeletedInset
2513 ? runparams.changeOfDeletedInset : lookupChange(i);
2515 char_type const c = d->text_[i];
2517 // Check whether a display math inset follows
2519 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2521 runparams.ctObject = getInset(i)->CtObject(runparams);
2523 InsetMath const * im = getInset(i)->asInsetMath();
2524 if (im && im->asHullInset()
2525 && im->asHullInset()->outerDisplay()) {
2526 runparams.inDisplayMath = true;
2527 // runparams.inDeletedInset will be set by
2528 // latexInset later, but we need this info
2529 // before it is called. On the other hand, we
2530 // cannot set it here because it is a counter.
2531 deleted_display_math = isDeleted(i);
2533 if (bparams.output_changes && deleted_display_math
2534 && runningChange == change
2535 && change.type == Change::DELETED
2536 && !os.afterParbreak()) {
2537 // A display math in the same paragraph follows.
2538 // We have to close and then reopen \lyxdeleted,
2539 // otherwise the math will be shifted up.
2540 OutputParams rp = runparams;
2542 bool needPar = false;
2543 column += running_font.latexWriteEndChanges(
2544 os, bparams, rp, basefont,
2548 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2549 : getLayoutFont(bparams, real_outerfont);
2550 running_font = basefont;
2551 column += Changes::latexMarkChange(os, bparams,
2552 Change(Change::INSERTED), change, rp);
2556 if (bparams.output_changes && runningChange != change) {
2557 if (!alien_script.empty()) {
2560 alien_script.clear();
2563 bool needPar = false;
2564 column += running_font.latexWriteEndChanges(
2565 os, bparams, runparams,
2566 basefont, basefont, needPar);
2569 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2570 : getLayoutFont(bparams, real_outerfont);
2571 running_font = basefont;
2572 column += Changes::latexMarkChange(os, bparams, runningChange,
2574 runningChange = change;
2577 // do not output text which is marked deleted
2578 // if change tracking output is disabled
2579 if (!bparams.output_changes && change.deleted()) {
2585 // Fully instantiated font
2586 Font const current_font = getFont(bparams, i, outerfont);
2588 Font const prev_font = (i > 0) ?
2589 getFont(bparams, i - 1, outerfont)
2592 Font const last_font = running_font;
2593 bool const in_ct_deletion = (bparams.output_changes
2594 && runningChange == change
2595 && change.type == Change::DELETED
2596 && !os.afterParbreak());
2597 // Insets where font switches are used (rather than font commands)
2598 bool const fontswitch_inset =
2601 && getInset(i)->allowMultiPar()
2602 && getInset(i)->lyxCode() != ERT_CODE;
2604 // Do we need to close the previous font?
2606 ((current_font != running_font
2607 || current_font.language() != running_font.language())
2608 || (fontswitch_inset
2609 && (current_font == prev_font
2610 || current_font.language() == prev_font.language()))))
2612 // ensure there is no open script-wrapper
2613 if (!alien_script.empty()) {
2616 alien_script.clear();
2618 bool needPar = false;
2619 if (in_ct_deletion) {
2620 // We have to close and then reopen \lyxdeleted,
2621 // as strikeout needs to be on lowest level.
2625 column += running_font.latexWriteEndChanges(
2626 os, bparams, runparams, basefont,
2627 (i == body_pos-1) ? basefont : current_font,
2629 if (in_ct_deletion) {
2630 // We have to close and then reopen \lyxdeleted,
2631 // as strikeout needs to be on lowest level.
2632 OutputParams rp = runparams;
2633 column += Changes::latexMarkChange(os, bparams,
2634 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2636 running_font = basefont;
2640 // if necessary, close language environment before opening CJK
2641 string const running_lang = running_font.language()->babel();
2642 string const lang_end_command = lyxrc.language_command_end;
2643 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2644 && !running_lang.empty()
2645 && running_lang == openLanguageName()
2646 && current_font.language()->encoding()->package() == Encoding::CJK) {
2647 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2648 os << from_ascii(end_tag);
2649 column += end_tag.length();
2653 // Switch file encoding if necessary (and allowed)
2654 if (!runparams.pass_thru && !style.pass_thru &&
2655 runparams.encoding->package() != Encoding::none &&
2656 current_font.language()->encoding()->package() != Encoding::none) {
2657 pair<bool, int> const enc_switch =
2658 switchEncoding(os.os(), bparams, runparams,
2659 *(current_font.language()->encoding()));
2660 if (enc_switch.first) {
2661 column += enc_switch.second;
2662 runparams.encoding = current_font.language()->encoding();
2666 // A display math inset inside an ulem command will be output
2667 // as a box of width \linewidth, so we have to either disable
2668 // indentation if the inset starts a paragraph, or start a new
2669 // line to accommodate such box. This has to be done before
2670 // writing any font changing commands.
2671 if (runparams.inDisplayMath && !deleted_display_math
2672 && runparams.inulemcmd) {
2673 if (os.afterParbreak())
2679 // Do we need to change font?
2680 if ((current_font != running_font ||
2681 current_font.language() != running_font.language())
2682 && i != body_pos - 1)
2684 if (in_ct_deletion) {
2685 // We have to close and then reopen \lyxdeleted,
2686 // as strikeout needs to be on lowest level.
2687 bool needPar = false;
2688 OutputParams rp = runparams;
2689 column += running_font.latexWriteEndChanges(
2690 os, bparams, rp, basefont,
2695 otexstringstream ots;
2696 if (!fontswitch_inset) {
2697 InsetText const * textinset = inInset().asInsetText();
2698 bool const cprotect = textinset
2699 ? textinset->hasCProtectContent(runparams.moving_arg)
2700 && !textinset->text().isMainText()
2702 column += current_font.latexWriteStartChanges(ots, bparams,
2703 runparams, basefont, last_font, false,
2706 // Check again for display math in ulem commands as a
2707 // font change may also occur just before a math inset.
2708 if (runparams.inDisplayMath && !deleted_display_math
2709 && runparams.inulemcmd) {
2710 if (os.afterParbreak())
2715 running_font = current_font;
2717 docstring fontchange = ots.str();
2719 // check whether the fontchange ends with a \\textcolor
2720 // modifier and the text starts with a space. If so we
2721 // need to add } in order to prevent \\textcolor from gobbling
2722 // the space (bug 4473).
2723 docstring const last_modifier = rsplit(fontchange, '\\');
2724 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2725 os << from_ascii("{}");
2726 else if (ots.terminateCommand())
2728 if (in_ct_deletion) {
2729 // We have to close and then reopen \lyxdeleted,
2730 // as strikeout needs to be on lowest level.
2731 OutputParams rp = runparams;
2732 column += Changes::latexMarkChange(os, bparams,
2733 Change(Change::UNCHANGED), change, rp);
2737 // FIXME: think about end_pos implementation...
2738 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2739 // FIXME: integrate this case in latexSpecialChar
2740 // Do not print the separation of the optional argument
2741 // if style.pass_thru is false. This works because
2742 // latexSpecialChar ignores spaces if
2743 // style.pass_thru is false.
2744 if (i != body_pos - 1) {
2745 if (d->simpleTeXBlanks(bparams, runparams, os,
2746 i, column, current_font, style)) {
2747 // A surrogate pair was output. We
2748 // must not call latexSpecialChar
2749 // in this iteration, since it would output
2750 // the combining character again.
2757 OutputParams rp = runparams;
2758 rp.free_spacing = style.free_spacing;
2759 rp.local_font = ¤t_font;
2760 rp.intitle = style.intitle;
2762 // Two major modes: LaTeX or plain
2763 // Handle here those cases common to both modes
2764 // and then split to handle the two modes separately.
2765 if (c == META_INSET) {
2766 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2767 // Greyedout notes and, in general, all insets
2768 // with InsetLayout::isDisplay() == false,
2769 // are typeset inline with the text. So, we
2770 // can add a \par to the last paragraph of
2771 // such insets only if nothing else follows.
2772 bool incremented = false;
2773 Inset const * inset = getInset(i);
2774 InsetText const * textinset = inset
2775 ? inset->asInsetText()
2777 if (i + 1 == size() && textinset
2778 && !inset->getLayout().isDisplay()) {
2779 ParagraphList const & pars =
2780 textinset->text().paragraphs();
2781 pit_type const pit = pars.size() - 1;
2782 Font const lastfont =
2783 pit < 0 || pars[pit].empty()
2784 ? pars[pit].getLayoutFont(
2787 : pars[pit].getFont(bparams,
2788 pars[pit].size() - 1,
2790 if (lastfont.fontInfo().size() !=
2791 basefont.fontInfo().size()) {
2796 // We need to restore parts of this after insets with
2797 // allowMultiPar() true
2798 Font const save_basefont = basefont;
2799 d->latexInset(bparams, os, rp, running_font,
2800 basefont, real_outerfont, open_font,
2801 runningChange, style, i, column, fontswitch_inset);
2802 if (fontswitch_inset) {
2804 bool needPar = false;
2805 column += running_font.latexWriteEndChanges(
2806 os, bparams, runparams,
2807 basefont, basefont, needPar);
2810 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2811 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2812 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2817 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2818 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2819 // Close \lyx*deleted and force its
2820 // reopening (if needed)
2823 runningChange = Change(Change::UNCHANGED);
2824 runparams.ctObject = OutputParams::CT_NORMAL;
2827 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2828 if (!bparams.useNonTeXFonts)
2829 script = Encodings::isKnownScriptChar(c);
2830 if (script != alien_script) {
2831 if (!alien_script.empty()) {
2833 alien_script.clear();
2835 string fontenc = running_font.language()->fontenc(bparams);
2837 && !Encodings::fontencSupportsScript(fontenc, script)) {
2838 column += script.length() + 2;
2839 os << "\\" << script << "{";
2840 alien_script = script;
2844 d->latexSpecialChar(os, bparams, rp, running_font,
2845 alien_script, style, i, end_pos, column);
2846 } catch (EncodingException & e) {
2847 if (runparams.dryrun) {
2848 os << "<" << _("LyX Warning: ")
2849 << _("uncodable character") << " '";
2853 // add location information and throw again.
2861 // Set the encoding to that returned from latexSpecialChar (see
2862 // comment for encoding member in OutputParams.h)
2863 runparams.encoding = rp.encoding;
2865 // Also carry on the info on a closed ulem command for insets
2866 // such as Note that do not produce any output, so that no
2867 // command is ever executed but its opening was recorded.
2868 runparams.inulemcmd = rp.inulemcmd;
2870 // These need to be passed upstream as well
2871 runparams.need_maketitle = rp.need_maketitle;
2872 runparams.have_maketitle = rp.have_maketitle;
2874 // And finally, pass the post_macros upstream
2875 runparams.post_macro = rp.post_macro;
2878 // Close wrapper for alien script
2879 if (!alien_script.empty()) {
2881 alien_script.clear();
2884 // If we have an open font definition, we have to close it
2886 // Make sure that \\par is done with the font of the last
2887 // character if this has another size as the default.
2888 // This is necessary because LaTeX (and LyX on the screen)
2889 // calculates the space between the baselines according
2890 // to this font. (Matthias)
2892 // We must not change the font for the last paragraph
2893 // of non-multipar insets, tabular cells or commands,
2894 // since this produces unwanted whitespace.
2896 Font const font = empty()
2897 ? getLayoutFont(bparams, real_outerfont)
2898 : getFont(bparams, size() - 1, real_outerfont);
2900 InsetText const * textinset = inInset().asInsetText();
2902 bool const maintext = textinset
2903 ? textinset->text().isMainText()
2906 size_t const numpars = textinset
2907 ? textinset->text().paragraphs().size()
2910 bool needPar = false;
2912 if (style.resfont.size() != font.fontInfo().size()
2913 && (!runparams.isLastPar || maintext
2914 || (numpars > 1 && d->ownerCode() != CELL_CODE
2915 && (inInset().getLayout().isDisplay()
2917 && !style.isCommand()) {
2920 #ifdef FIXED_LANGUAGE_END_DETECTION
2922 running_font.latexWriteEndChanges(os, bparams,
2923 runparams, basefont,
2924 next_->getFont(bparams, 0, outerfont),
2927 running_font.latexWriteEndChanges(os, bparams,
2928 runparams, basefont, basefont, needPar);
2931 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2932 //FIXME: there as we start another \selectlanguage with the next paragraph if
2933 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2934 running_font.latexWriteEndChanges(os, bparams, runparams,
2935 basefont, basefont, needPar);
2938 // The \par could not be inserted at the same nesting
2939 // level of the font size change, so do it now.
2940 os << "{\\" << font.latexSize() << "\\par}";
2944 column += Changes::latexMarkChange(os, bparams, runningChange,
2945 Change(Change::UNCHANGED), runparams);
2947 // Needed if there is an optional argument but no contents.
2948 if (body_pos > 0 && body_pos == size()) {
2952 if (!style.rightdelim().empty()) {
2953 os << style.rightdelim();
2954 column += style.rightdelim().size();
2957 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2958 && runparams.encoding != prev_encoding) {
2959 runparams.encoding = prev_encoding;
2960 os << setEncoding(prev_encoding->iconvName());
2963 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2967 bool Paragraph::emptyTag() const
2969 for (pos_type i = 0; i < size(); ++i) {
2970 if (Inset const * inset = getInset(i)) {
2971 InsetCode lyx_code = inset->lyxCode();
2972 // FIXME testing like that is wrong. What is
2974 if (lyx_code != TOC_CODE &&
2975 lyx_code != INCLUDE_CODE &&
2976 lyx_code != GRAPHICS_CODE &&
2977 lyx_code != ERT_CODE &&
2978 lyx_code != LISTINGS_CODE &&
2979 lyx_code != FLOAT_CODE &&
2980 lyx_code != TABULAR_CODE) {
2984 char_type c = d->text_[i];
2985 if (c != ' ' && c != '\t')
2993 string Paragraph::getID(Buffer const &, OutputParams const &)
2996 for (pos_type i = 0; i < size(); ++i) {
2997 if (Inset const * inset = getInset(i)) {
2998 InsetCode lyx_code = inset->lyxCode();
2999 if (lyx_code == LABEL_CODE) {
3000 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3001 docstring const & id = il->getParam("name");
3002 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3010 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3013 for (i = 0; i < size(); ++i) {
3014 if (Inset const * inset = getInset(i)) {
3015 inset->docbook(xs, runparams);
3017 char_type c = d->text_[i];
3027 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3031 for (i = 0; i < size(); ++i) {
3032 if (Inset const * inset = getInset(i)) {
3033 inset->xhtml(xs, runparams);
3035 char_type c = d->text_[i];
3045 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3048 pos_type size = text_.size();
3049 for (pos_type i = initial; i < size; ++i) {
3050 Font font = owner_->getFont(buf.params(), i, outerfont);
3051 if (text_[i] == META_INSET)
3053 if (i != initial && font != font_old)
3064 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3065 vector<xml::EndFontTag> & tagsToClose,
3066 bool & flag, FontState curstate, xml::FontTypes type)
3068 if (curstate == FONT_ON) {
3069 tagsToOpen.push_back(docbookStartFontTag(type));
3072 tagsToClose.push_back(docbookEndFontTag(type));
3077 class OptionalFontType {
3082 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3083 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3086 OptionalFontType fontShapeToXml(FontShape fs)
3090 return {xml::FT_ITALIC};
3092 return {xml::FT_SLANTED};
3093 case SMALLCAPS_SHAPE:
3094 return {xml::FT_SMALLCAPS};
3099 // the other tags are for internal use
3105 OptionalFontType fontFamilyToXml(FontFamily fm)
3109 return {xml::FT_ROMAN};
3111 return {xml::FT_SANS};
3112 case TYPEWRITER_FAMILY:
3113 return {xml::FT_TYPE};
3114 case INHERIT_FAMILY:
3117 // the other tags are for internal use
3123 OptionalFontType fontSizeToXml(FontSize fs)
3127 return {xml::FT_SIZE_TINY};
3129 return {xml::FT_SIZE_SCRIPT};
3131 return {xml::FT_SIZE_FOOTNOTE};
3133 return {xml::FT_SIZE_SMALL};
3135 return {xml::FT_SIZE_LARGE};
3137 return {xml::FT_SIZE_LARGER};
3139 return {xml::FT_SIZE_LARGEST};
3141 return {xml::FT_SIZE_HUGE};
3143 return {xml::FT_SIZE_HUGER};
3145 return {xml::FT_SIZE_INCREASE};
3147 return {xml::FT_SIZE_DECREASE};
3152 // the other tags are for internal use
3158 struct DocBookFontState
3160 FontShape curr_fs = INHERIT_SHAPE;
3161 FontFamily curr_fam = INHERIT_FAMILY;
3162 FontSize curr_size = INHERIT_SIZE;
3164 // track whether we have opened these tags
3165 bool emph_flag = false;
3166 bool bold_flag = false;
3167 bool noun_flag = false;
3168 bool ubar_flag = false;
3169 bool dbar_flag = false;
3170 bool sout_flag = false;
3171 bool xout_flag = false;
3172 bool wave_flag = false;
3174 bool shap_flag = false;
3176 bool faml_flag = false;
3178 bool size_flag = false;
3181 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3183 std::string const & default_family,
3184 DocBookFontState & fs)
3186 vector<xml::FontTag> tagsToOpen;
3187 vector<xml::EndFontTag> tagsToClose;
3190 FontState curstate = font.fontInfo().emph();
3191 if (font_old.emph() != curstate)
3192 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3195 curstate = font.fontInfo().noun();
3196 if (font_old.noun() != curstate)
3197 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3200 curstate = font.fontInfo().underbar();
3201 if (font_old.underbar() != curstate)
3202 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3205 curstate = font.fontInfo().strikeout();
3206 if (font_old.strikeout() != curstate)
3207 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3210 curstate = font.fontInfo().xout();
3211 if (font_old.xout() != curstate)
3212 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3215 curstate = font.fontInfo().uuline();
3216 if (font_old.uuline() != curstate)
3217 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3220 curstate = font.fontInfo().uwave();
3221 if (font_old.uwave() != curstate)
3222 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3225 // a little hackish, but allows us to reuse what we have.
3226 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3227 if (font_old.series() != font.fontInfo().series())
3228 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3231 fs.curr_fs = font.fontInfo().shape();
3232 FontShape old_fs = font_old.shape();
3233 if (old_fs != fs.curr_fs) {
3235 OptionalFontType tag = fontShapeToXml(old_fs);
3237 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3238 fs.shap_flag = false;
3241 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3243 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3247 fs.curr_fam = font.fontInfo().family();
3248 FontFamily old_fam = font_old.family();
3249 if (old_fam != fs.curr_fam) {
3251 OptionalFontType tag = fontFamilyToXml(old_fam);
3253 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3254 fs.faml_flag = false;
3256 switch (fs.curr_fam) {
3258 // we will treat a "default" font family as roman, since we have
3259 // no other idea what to do.
3260 if (default_family != "rmdefault" && default_family != "default") {
3261 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3262 fs.faml_flag = true;
3266 if (default_family != "sfdefault") {
3267 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3268 fs.faml_flag = true;
3271 case TYPEWRITER_FAMILY:
3272 if (default_family != "ttdefault") {
3273 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3274 fs.faml_flag = true;
3277 case INHERIT_FAMILY:
3280 // the other tags are for internal use
3287 fs.curr_size = font.fontInfo().size();
3288 FontSize old_size = font_old.size();
3289 if (old_size != fs.curr_size) {
3291 OptionalFontType tag = fontSizeToXml(old_size);
3293 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3294 fs.size_flag = false;
3297 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3298 if (tag.has_value) {
3299 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3300 fs.size_flag = true;
3304 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3307 } // anonymous namespace
3310 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3312 OutputParams const & runparams,
3313 Font const & outerfont,
3314 bool start_paragraph, bool close_paragraph,
3315 pos_type initial) const
3317 // track whether we have opened these tags
3318 DocBookFontState fs;
3320 if (start_paragraph)
3321 xs.startDivision(allowEmpty());
3323 Layout const & style = *d->layout_;
3325 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3327 string const default_family =
3328 buf.masterBuffer()->params().fonts_default_family;
3330 vector<xml::FontTag> tagsToOpen;
3331 vector<xml::EndFontTag> tagsToClose;
3333 // parsing main loop
3334 for (pos_type i = initial; i < size(); ++i) {
3335 // let's not show deleted material in the output
3339 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3341 // Determine which tags should be opened or closed.
3342 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3345 // Other such tags? What about the other text ranges?
3347 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3348 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3349 for (; cit != cen; ++cit)
3352 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3353 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3354 for (; sit != sen; ++sit)
3357 tagsToClose.clear();
3360 if (Inset const * inset = getInset(i)) {
3361 if (!runparams.for_toc || inset->isInToc()) {
3362 OutputParams np = runparams;
3363 np.local_font = &font;
3364 // If the paragraph has size 1, then we are in the "special
3365 // case" where we do not output the containing paragraph info.
3366 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3367 // of that brittle logic is passed to this function through open_par.
3368 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3369 np.docbook_in_par = true;
3370 inset->docbook(xs, np);
3373 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3376 font_old = font.fontInfo();
3379 // FIXME, this code is just imported from XHTML
3380 // I'm worried about what happens if a branch, say, is itself
3381 // wrapped in some font stuff. I think that will not work.
3383 if (runparams.docbook_in_listing)
3385 if (close_paragraph)
3392 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3393 vector<xml::EndFontTag> & tagsToClose,
3394 bool & flag, FontState curstate, xml::FontTypes type)
3396 if (curstate == FONT_ON) {
3397 tagsToOpen.push_back(xhtmlStartFontTag(type));
3400 tagsToClose.push_back(xhtmlEndFontTag(type));
3405 } // anonymous namespace
3408 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3410 OutputParams const & runparams,
3411 Font const & outerfont,
3412 bool start_paragraph, bool close_paragraph,
3413 pos_type initial) const
3417 // track whether we have opened these tags
3418 bool emph_flag = false;
3419 bool bold_flag = false;
3420 bool noun_flag = false;
3421 bool ubar_flag = false;
3422 bool dbar_flag = false;
3423 bool sout_flag = false;
3424 bool xout_flag = false;
3425 bool wave_flag = false;
3427 bool shap_flag = false;
3429 bool faml_flag = false;
3431 bool size_flag = false;
3433 Layout const & style = *d->layout_;
3435 if (start_paragraph)
3436 xs.startDivision(allowEmpty());
3439 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3441 FontShape curr_fs = INHERIT_SHAPE;
3442 FontFamily curr_fam = INHERIT_FAMILY;
3443 FontSize curr_size = INHERIT_SIZE;
3445 string const default_family =
3446 buf.masterBuffer()->params().fonts_default_family;
3448 vector<xml::FontTag> tagsToOpen;
3449 vector<xml::EndFontTag> tagsToClose;
3451 // parsing main loop
3452 for (pos_type i = initial; i < size(); ++i) {
3453 // let's not show deleted material in the output
3457 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3460 FontState curstate = font.fontInfo().emph();
3461 if (font_old.emph() != curstate)
3462 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3465 curstate = font.fontInfo().noun();
3466 if (font_old.noun() != curstate)
3467 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3470 curstate = font.fontInfo().underbar();
3471 if (font_old.underbar() != curstate)
3472 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3475 curstate = font.fontInfo().strikeout();
3476 if (font_old.strikeout() != curstate)
3477 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3480 curstate = font.fontInfo().xout();
3481 if (font_old.xout() != curstate)
3482 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3485 curstate = font.fontInfo().uuline();
3486 if (font_old.uuline() != curstate)
3487 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3490 curstate = font.fontInfo().uwave();
3491 if (font_old.uwave() != curstate)
3492 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3495 // a little hackish, but allows us to reuse what we have.
3496 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3497 if (font_old.series() != font.fontInfo().series())
3498 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3501 curr_fs = font.fontInfo().shape();
3502 FontShape old_fs = font_old.shape();
3503 if (old_fs != curr_fs) {
3507 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3510 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3512 case SMALLCAPS_SHAPE:
3513 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3519 // the other tags are for internal use
3527 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3531 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3534 case SMALLCAPS_SHAPE:
3535 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3542 // the other tags are for internal use
3549 curr_fam = font.fontInfo().family();
3550 FontFamily old_fam = font_old.family();
3551 if (old_fam != curr_fam) {
3555 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3558 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3560 case TYPEWRITER_FAMILY:
3561 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3563 case INHERIT_FAMILY:
3566 // the other tags are for internal use
3574 // we will treat a "default" font family as roman, since we have
3575 // no other idea what to do.
3576 if (default_family != "rmdefault" && default_family != "default") {
3577 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3582 if (default_family != "sfdefault") {
3583 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3587 case TYPEWRITER_FAMILY:
3588 if (default_family != "ttdefault") {
3589 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3593 case INHERIT_FAMILY:
3596 // the other tags are for internal use
3603 curr_size = font.fontInfo().size();
3604 FontSize old_size = font_old.size();
3605 if (old_size != curr_size) {
3609 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3612 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3615 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3618 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3621 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3624 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3627 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3630 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3633 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3636 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3639 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3645 // the other tags are for internal use
3651 switch (curr_size) {
3653 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3657 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3661 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3665 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3669 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3673 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3677 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3681 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3685 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3689 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3693 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3700 // the other tags are for internal use
3707 // Other such tags? What about the other text ranges?
3709 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3710 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3711 for (; cit != cen; ++cit)
3714 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3715 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3716 for (; sit != sen; ++sit)
3719 tagsToClose.clear();
3722 Inset const * inset = getInset(i);
3724 if (!runparams.for_toc || inset->isInToc()) {
3725 OutputParams np = runparams;
3726 np.local_font = &font;
3727 // If the paragraph has size 1, then we are in the "special
3728 // case" where we do not output the containing paragraph info
3729 if (!inset->getLayout().htmlisblock() && size() != 1)
3730 np.html_in_par = true;
3731 retval += inset->xhtml(xs, np);
3734 char_type c = getUChar(buf.masterBuffer()->params(),
3736 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3737 xs << XMLStream::ESCAPE_NONE << " ";
3741 font_old = font.fontInfo();
3745 // I'm worried about what happens if a branch, say, is itself
3746 // wrapped in some font stuff. I think that will not work.
3748 if (close_paragraph)
3755 bool Paragraph::isHfill(pos_type pos) const
3757 Inset const * inset = getInset(pos);
3758 return inset && inset->isHfill();
3762 bool Paragraph::isNewline(pos_type pos) const
3764 // U+2028 LINE SEPARATOR
3765 // U+2029 PARAGRAPH SEPARATOR
3766 char_type const c = d->text_[pos];
3767 if (c == 0x2028 || c == 0x2029)
3769 Inset const * inset = getInset(pos);
3770 return inset && inset->lyxCode() == NEWLINE_CODE;
3774 bool Paragraph::isEnvSeparator(pos_type pos) const
3776 Inset const * inset = getInset(pos);
3777 return inset && inset->lyxCode() == SEPARATOR_CODE;
3781 bool Paragraph::isLineSeparator(pos_type pos) const
3783 char_type const c = d->text_[pos];
3784 if (isLineSeparatorChar(c))
3786 Inset const * inset = getInset(pos);
3787 return inset && inset->isLineSeparator();
3791 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3795 if (ignore_deleted && isDeleted(pos))
3797 if (Inset const * inset = getInset(pos))
3798 return !inset->isLetter();
3799 // if we have a hard hyphen (no en- or emdash) or apostrophe
3800 // we pass this to the spell checker
3801 // FIXME: this method is subject to change, visit
3802 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3803 // to get an impression how complex this is.
3804 if (isHardHyphenOrApostrophe(pos))
3806 char_type const c = d->text_[pos];
3807 // We want to pass the escape chars to the spellchecker
3808 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3809 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3813 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3815 pos_type const psize = size();
3818 char_type const c = d->text_[pos];
3819 if (c != '-' && c != '\'')
3821 int nextpos = pos + 1;
3822 int prevpos = pos > 0 ? pos - 1 : 0;
3823 if ((nextpos == psize || isSpace(nextpos))
3824 && (pos == 0 || isSpace(prevpos)))
3830 bool Paragraph::needsCProtection(bool const fragile) const
3832 // first check the layout of the paragraph, but only in insets
3833 InsetText const * textinset = inInset().asInsetText();
3834 bool const maintext = textinset
3835 ? textinset->text().isMainText()
3838 if (!maintext && layout().needcprotect) {
3839 // Environments need cprotection regardless the content
3840 if (layout().latextype == LATEX_ENVIRONMENT)
3843 // Commands need cprotection if they contain specific chars
3844 int const nchars_escape = 9;
3845 static char_type const chars_escape[nchars_escape] = {
3846 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3848 docstring const pars = asString();
3849 for (int k = 0; k < nchars_escape; k++) {
3850 if (contains(pars, chars_escape[k]))
3855 // now check whether we have insets that need cprotection
3856 pos_type size = pos_type(d->text_.size());
3857 for (pos_type i = 0; i < size; ++i) {
3860 Inset const * ins = getInset(i);
3861 if (ins->needsCProtection(maintext, fragile))
3863 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3864 // Environments need cprotection regardless the content
3866 // Now check math environments
3867 InsetMath const * im = getInset(i)->asInsetMath();
3868 if (!im || im->cell(0).empty())
3870 switch(im->cell(0)[0]->lyxCode()) {
3871 case MATH_AMSARRAY_CODE:
3872 case MATH_SUBSTACK_CODE:
3874 case MATH_XYMATRIX_CODE:
3875 // these need cprotection
3886 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3888 return d->speller_state_.getRange(pos);
3892 bool Paragraph::isChar(pos_type pos) const
3894 if (Inset const * inset = getInset(pos))
3895 return inset->isChar();
3896 char_type const c = d->text_[pos];
3897 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3901 bool Paragraph::isSpace(pos_type pos) const
3903 if (Inset const * inset = getInset(pos))
3904 return inset->isSpace();
3905 char_type const c = d->text_[pos];
3906 return lyx::isSpace(c);
3911 Paragraph::getParLanguage(BufferParams const & bparams) const
3914 return getFirstFontSettings(bparams).language();
3915 // FIXME: we should check the prev par as well (Lgb)
3916 return bparams.language;
3920 bool Paragraph::isRTL(BufferParams const & bparams) const
3922 return getParLanguage(bparams)->rightToLeft()
3923 && !inInset().getLayout().forceLTR();
3927 void Paragraph::changeLanguage(BufferParams const & bparams,
3928 Language const * from, Language const * to)
3930 // change language including dummy font change at the end
3931 for (pos_type i = 0; i <= size(); ++i) {
3932 Font font = getFontSettings(bparams, i);
3933 if (font.language() == from) {
3934 font.setLanguage(to);
3936 d->requestSpellCheck(i);
3942 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3944 Language const * doc_language = bparams.language;
3945 for (auto const & f : d->fontlist_)
3946 if (f.font().language() != ignore_language &&
3947 f.font().language() != latex_language &&
3948 f.font().language() != doc_language)
3954 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3956 for (auto const & f : d->fontlist_) {
3957 Language const * lang = f.font().language();
3958 if (lang != ignore_language &&
3959 lang != latex_language)
3965 docstring Paragraph::asString(int options) const
3967 return asString(0, size(), options);
3971 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3973 odocstringstream os;
3976 && options & AS_STR_LABEL
3977 && !d->params_.labelString().empty())
3978 os << d->params_.labelString() << ' ';
3980 for (pos_type i = beg; i < end; ++i) {
3981 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3983 char_type const c = d->text_[i];
3984 if (isPrintable(c) || c == '\t'
3985 || (c == '\n' && (options & AS_STR_NEWLINES)))
3987 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3988 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3989 LASSERT(runparams != nullptr, return docstring());
3990 getInset(i)->plaintext(os, *runparams);
3992 getInset(i)->toString(os);
4001 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4002 bool const shorten, bool const label) const
4004 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4005 if (label && !labelString().empty())
4006 os += labelString() + ' ';
4007 if (!layout().isTocCaption())
4009 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4012 char_type const c = d->text_[i];
4015 else if (c == META_INSET)
4016 getInset(i)->forOutliner(os, tmplen, false);
4019 Text::shortenForOutliner(os, maxlen);
4023 void Paragraph::setInsetOwner(Inset const * inset)
4025 d->inset_owner_ = inset;
4029 int Paragraph::id() const
4035 void Paragraph::setId(int id)
4041 Layout const & Paragraph::layout() const
4047 void Paragraph::setLayout(Layout const & layout)
4049 d->layout_ = &layout;
4053 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4055 setLayout(tc.defaultLayout());
4059 void Paragraph::setPlainLayout(DocumentClass const & tc)
4061 setLayout(tc.plainLayout());
4065 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4067 if (usePlainLayout())
4068 setPlainLayout(tclass);
4070 setDefaultLayout(tclass);
4074 Inset const & Paragraph::inInset() const
4076 LBUFERR(d->inset_owner_);
4077 return *d->inset_owner_;
4081 ParagraphParameters & Paragraph::params()
4087 ParagraphParameters const & Paragraph::params() const
4093 bool Paragraph::isFreeSpacing() const
4095 if (d->layout_->free_spacing)
4097 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4101 bool Paragraph::allowEmpty() const
4103 if (d->layout_->keepempty)
4105 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4109 bool Paragraph::brokenBiblio() const
4111 // There is a problem if there is no bibitem at position 0 in
4112 // paragraphs that need one, if there is another bibitem in the
4113 // paragraph or if this paragraph is not supposed to have
4114 // a bibitem inset at all.
4115 return ((d->layout_->labeltype == LABEL_BIBLIO
4116 && (d->insetlist_.find(BIBITEM_CODE) != 0
4117 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4118 || (d->layout_->labeltype != LABEL_BIBLIO
4119 && d->insetlist_.find(BIBITEM_CODE) != -1));
4123 int Paragraph::fixBiblio(Buffer const & buffer)
4125 // FIXME: when there was already an inset at 0, the return value is 1,
4126 // which does not tell whether another inset has been removed; the
4127 // cursor cannot be correctly updated.
4129 bool const track_changes = buffer.params().track_changes;
4130 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4132 // The case where paragraph is not BIBLIO
4133 if (d->layout_->labeltype != LABEL_BIBLIO) {
4134 if (bibitem_pos == -1)
4135 // No InsetBibitem => OK
4137 // There is an InsetBibitem: remove it!
4138 d->insetlist_.release(bibitem_pos);
4139 eraseChar(bibitem_pos, track_changes);
4140 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4143 bool const hasbibitem0 = bibitem_pos == 0;
4145 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4146 // There was an InsetBibitem at pos 0,
4147 // and no other one => OK
4148 if (bibitem_pos == -1)
4150 // there is a bibitem at the 0 position, but since
4151 // there is a second one, we copy the second on the
4152 // first. We're assuming there are at most two of
4153 // these, which there should be.
4154 // FIXME: why does it make sense to do that rather
4155 // than keep the first? (JMarc)
4156 Inset * inset = releaseInset(bibitem_pos);
4157 d->insetlist_.begin()->inset = inset;
4158 // This needs to be done to update the counter (#8499)
4159 buffer.updateBuffer();
4160 return -bibitem_pos;
4163 // We need to create an inset at the beginning
4164 Inset * inset = nullptr;
4165 if (bibitem_pos > 0) {
4166 // there was one somewhere in the paragraph, let's move it
4167 inset = d->insetlist_.release(bibitem_pos);
4168 eraseChar(bibitem_pos, track_changes);
4171 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4172 InsetCommandParams(BIBITEM_CODE));
4174 Font font(inherit_font, buffer.params().language);
4175 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4176 : Change::UNCHANGED));
4178 // This is needed to get the counters right
4179 buffer.updateBuffer();
4184 void Paragraph::checkAuthors(AuthorList const & authorList)
4186 d->changes_.checkAuthors(authorList);
4190 bool Paragraph::isChanged(pos_type pos) const
4192 return lookupChange(pos).changed();
4196 bool Paragraph::isInserted(pos_type pos) const
4198 return lookupChange(pos).inserted();
4202 bool Paragraph::isDeleted(pos_type pos) const
4204 return lookupChange(pos).deleted();
4208 InsetList const & Paragraph::insetList() const
4210 return d->insetlist_;
4214 void Paragraph::setInsetBuffers(Buffer & b)
4216 d->insetlist_.setBuffer(b);
4220 void Paragraph::resetBuffer()
4222 d->insetlist_.resetBuffer();
4226 Inset * Paragraph::releaseInset(pos_type pos)
4228 Inset * inset = d->insetlist_.release(pos);
4229 /// does not honour change tracking!
4230 eraseChar(pos, false);
4235 Inset * Paragraph::getInset(pos_type pos)
4237 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4238 ? d->insetlist_.get(pos) : nullptr;
4242 Inset const * Paragraph::getInset(pos_type pos) const
4244 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4245 ? d->insetlist_.get(pos) : nullptr;
4249 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4250 pos_type & right, TextCase action)
4252 // process sequences of modified characters; in change
4253 // tracking mode, this approach results in much better
4254 // usability than changing case on a char-by-char basis
4255 // We also need to track the current font, since font
4256 // changes within sequences can occur.
4257 vector<pair<char_type, Font> > changes;
4259 bool const trackChanges = bparams.track_changes;
4261 bool capitalize = true;
4263 for (; pos < right; ++pos) {
4264 char_type oldChar = d->text_[pos];
4265 char_type newChar = oldChar;
4267 // ignore insets and don't play with deleted text!
4268 if (oldChar != META_INSET && !isDeleted(pos)) {
4270 case text_lowercase:
4271 newChar = lowercase(oldChar);
4273 case text_capitalization:
4275 newChar = uppercase(oldChar);
4279 case text_uppercase:
4280 newChar = uppercase(oldChar);
4285 if (isWordSeparator(pos) || isDeleted(pos)) {
4286 // permit capitalization again
4290 if (oldChar != newChar) {
4291 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4292 if (pos != right - 1)
4294 // step behind the changing area
4298 int erasePos = pos - changes.size();
4299 for (size_t i = 0; i < changes.size(); i++) {
4300 insertChar(pos, changes[i].first,
4303 if (!eraseChar(erasePos, trackChanges)) {
4306 ++right; // expand selection
4314 int Paragraph::find(docstring const & str, bool cs, bool mw,
4315 pos_type start_pos, bool del) const
4317 pos_type pos = start_pos;
4318 int const strsize = str.length();
4320 pos_type const parsize = d->text_.size();
4321 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4322 // Ignore "invisible" letters such as ligature breaks
4323 // and hyphenation chars while searching
4324 while (pos < parsize - 1 && isInset(pos)) {
4325 Inset const * inset = getInset(pos);
4326 if (!inset->isLetter())
4328 odocstringstream os;
4329 inset->toString(os);
4330 if (!os.str().empty())
4334 if (cs && str[i] != d->text_[pos])
4336 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4338 if (!del && isDeleted(pos))
4345 // if necessary, check whether string matches word
4347 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4350 && !isWordSeparator(pos))
4354 return pos - start_pos;
4358 char_type Paragraph::getChar(pos_type pos) const
4360 return d->text_[pos];
4364 pos_type Paragraph::size() const
4366 return d->text_.size();
4370 bool Paragraph::empty() const
4372 return d->text_.empty();
4376 bool Paragraph::isInset(pos_type pos) const
4378 return d->text_[pos] == META_INSET;
4382 bool Paragraph::isSeparator(pos_type pos) const
4384 //FIXME: Are we sure this can be the only separator?
4385 return d->text_[pos] == ' ';
4389 void Paragraph::deregisterWords()
4391 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4392 Private::LangWordsMap::const_iterator ite = d->words_.end();
4393 for (; itl != ite; ++itl) {
4394 WordList & wl = theWordList(itl->first);
4395 Private::Words::const_iterator it = (itl->second).begin();
4396 Private::Words::const_iterator et = (itl->second).end();
4397 for (; it != et; ++it)
4404 void Paragraph::locateWord(pos_type & from, pos_type & to,
4405 word_location const loc, bool const ignore_deleted) const
4408 case WHOLE_WORD_STRICT:
4409 if (from == 0 || from == size()
4410 || isWordSeparator(from, ignore_deleted)
4411 || isWordSeparator(from - 1, ignore_deleted)) {
4418 // If we are already at the beginning of a word, do nothing
4419 if (!from || isWordSeparator(from - 1, ignore_deleted))
4424 // always move the cursor to the beginning of previous word
4425 while (from && !isWordSeparator(from - 1, ignore_deleted))
4429 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4432 // no need to move the 'from' cursor
4436 while (to < size() && !isWordSeparator(to, ignore_deleted))
4441 void Paragraph::collectWords()
4443 for (pos_type pos = 0; pos < size(); ++pos) {
4444 if (isWordSeparator(pos))
4446 pos_type from = pos;
4447 locateWord(from, pos, WHOLE_WORD);
4448 // Work around MSVC warning: The statement
4449 // if (pos < from + lyxrc.completion_minlength)
4450 // triggers a signed vs. unsigned warning.
4451 // I don't know why this happens, it could be a MSVC bug, or
4452 // related to LLP64 (windows) vs. LP64 (unix) programming
4453 // model, or the C++ standard might be ambigous in the section
4454 // defining the "usual arithmetic conversions". However, using
4455 // a temporary variable is safe and works on all compilers.
4456 pos_type const endpos = from + lyxrc.completion_minlength;
4459 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4460 if (cit == d->fontlist_.end())
4462 Language const * lang = cit->font().language();
4463 docstring const word = asString(from, pos, AS_STR_NONE);
4464 d->words_[lang->lang()].insert(word);
4469 void Paragraph::registerWords()
4471 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4472 Private::LangWordsMap::const_iterator ite = d->words_.end();
4473 for (; itl != ite; ++itl) {
4474 WordList & wl = theWordList(itl->first);
4475 Private::Words::const_iterator it = (itl->second).begin();
4476 Private::Words::const_iterator et = (itl->second).end();
4477 for (; it != et; ++it)
4483 void Paragraph::updateWords()
4491 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4493 SkipPositionsIterator begin = skips.begin();
4494 SkipPositions::iterator end = skips.end();
4495 if (pos > 0 && begin < end) {
4497 if (end->last == pos - 1) {
4502 skips.insert(end, FontSpan(pos, pos));
4506 Language * Paragraph::Private::locateSpellRange(
4507 pos_type & from, pos_type & to,
4508 SkipPositions & skips) const
4510 // skip leading white space
4511 while (from < to && owner_->isWordSeparator(from))
4513 // don't check empty range
4516 // get current language
4517 Language * lang = getSpellLanguage(from);
4518 pos_type last = from;
4519 bool samelang = true;
4520 bool sameinset = true;
4521 while (last < to && samelang && sameinset) {
4522 // hop to end of word
4523 while (last < to && !owner_->isWordSeparator(last)) {
4524 Inset const * inset = owner_->getInset(last);
4525 if (inset && inset->lyxCode() == SPECIALCHAR_CODE) {
4526 // check for "invisible" letters such as ligature breaks
4527 odocstringstream os;
4528 inset->toString(os);
4529 if (os.str().length() != 0) {
4530 // avoid spell check of visible special char insets
4531 // stop the loop in front of the special char inset
4536 appendSkipPosition(skips, last);
4537 } else if (owner_->isDeleted(last)) {
4538 appendSkipPosition(skips, last);
4542 // hop to next word while checking for insets
4543 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4544 if (Inset const * inset = owner_->getInset(last))
4545 sameinset = inset->isChar() && inset->isLetter();
4546 if (sameinset && owner_->isDeleted(last)) {
4547 appendSkipPosition(skips, last);
4552 if (sameinset && last < to) {
4553 // now check for language change
4554 samelang = lang == getSpellLanguage(last);
4557 // if language change detected backstep is needed
4565 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4568 const_cast<Language *>(owner_->getFontSettings(
4569 inset_owner_->buffer().params(), from).language());
4570 if (lang == inset_owner_->buffer().params().language
4571 && !lyxrc.spellchecker_alt_lang.empty()) {
4573 string const lang_variety =
4574 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4575 lang->setCode(lang_code);
4576 lang->setVariety(lang_variety);
4582 void Paragraph::requestSpellCheck(pos_type pos)
4584 d->requestSpellCheck(pos);
4588 bool Paragraph::needsSpellCheck() const
4590 SpellChecker::ChangeNumber speller_change_number = 0;
4591 if (theSpellChecker())
4592 speller_change_number = theSpellChecker()->changeNumber();
4593 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4594 d->speller_state_.needsCompleteRefresh(speller_change_number);
4596 return d->needsSpellCheck();
4600 bool Paragraph::Private::ignoreWord(docstring const & word) const
4602 // Ignore words with digits
4603 // FIXME: make this customizable
4604 // (note that some checkers ignore words with digits by default)
4605 docstring::const_iterator cit = word.begin();
4606 docstring::const_iterator const end = word.end();
4607 for (; cit != end; ++cit) {
4608 if (isNumber((*cit)))
4615 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4616 WordLangTuple & wl, docstring_list & suggestions,
4617 bool do_suggestion, bool check_learned) const
4619 SpellChecker::Result result = SpellChecker::WORD_OK;
4620 SpellChecker * speller = theSpellChecker();
4624 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4627 locateWord(from, to, WHOLE_WORD, true);
4628 if (from == to || from >= size())
4631 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4632 Language * lang = d->getSpellLanguage(from);
4634 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4637 wl = WordLangTuple(word, lang);
4642 if (needsSpellCheck() || check_learned) {
4644 if (!d->ignoreWord(word)) {
4645 bool const trailing_dot = to < size() && d->text_[to] == '.';
4646 result = speller->check(wl);
4647 if (SpellChecker::misspelled(result) && trailing_dot) {
4648 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4649 result = speller->check(wl);
4650 if (!SpellChecker::misspelled(result)) {
4651 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4653 from << ".." << to << "]");
4655 // spell check with dot appended failed too
4656 // restore original word/lang value
4657 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4658 wl = WordLangTuple(word, lang);
4662 if (!SpellChecker::misspelled(result)) {
4663 // area up to the begin of the next word is not misspelled
4664 while (end < size() && isWordSeparator(end))
4667 d->setMisspelled(from, end, result);
4669 result = d->speller_state_.getState(from);
4673 suggestions.clear();
4675 if (SpellChecker::misspelled(result)) {
4676 LYXERR(Debug::GUI, "misspelled word: \"" <<
4678 from << ".." << to << "]");
4680 speller->suggest(wl, suggestions);
4686 void Paragraph::anonymize()
4688 // This is a very crude anonymization for now
4689 for (char_type & c : d->text_)
4690 if (isLetterChar(c) || isNumber(c))
4695 void Paragraph::Private::markMisspelledWords(
4696 pos_type const & first, pos_type const & last,
4697 SpellChecker::Result result,
4698 docstring const & word,
4699 SkipPositions const & skips)
4701 if (!SpellChecker::misspelled(result)) {
4702 setMisspelled(first, last, SpellChecker::WORD_OK);
4706 SpellChecker * speller = theSpellChecker();
4707 // locate and enumerate the error positions
4708 int nerrors = speller->numMisspelledWords();
4710 SkipPositionsIterator it = skips.begin();
4711 SkipPositionsIterator et = skips.end();
4712 for (int index = 0; index < nerrors; ++index) {
4715 speller->misspelledWord(index, wstart, wlen);
4716 /// should not happen if speller supports range checks
4717 if (!wlen) continue;
4718 docstring const misspelled = word.substr(wstart, wlen);
4719 wstart += first + numskipped;
4720 if (snext < wstart) {
4721 /// mark the range of correct spelling
4722 numskipped += countSkips(it, et, wstart);
4723 setMisspelled(snext,
4724 wstart - 1, SpellChecker::WORD_OK);
4726 snext = wstart + wlen;
4727 numskipped += countSkips(it, et, snext);
4728 /// mark the range of misspelling
4729 setMisspelled(wstart, snext, result);
4730 LYXERR(Debug::GUI, "misspelled word: \"" <<
4731 misspelled << "\" [" <<
4732 wstart << ".." << (snext-1) << "]");
4735 if (snext <= last) {
4736 /// mark the range of correct spelling at end
4737 setMisspelled(snext, last, SpellChecker::WORD_OK);
4742 void Paragraph::spellCheck() const
4744 SpellChecker * speller = theSpellChecker();
4745 if (!speller || empty() ||!needsSpellCheck())
4749 d->rangeOfSpellCheck(start, endpos);
4750 if (speller->canCheckParagraph()) {
4751 // loop until we leave the range
4752 for (pos_type first = start; first < endpos; ) {
4753 pos_type last = endpos;
4754 Private::SkipPositions skips;
4755 Language * lang = d->locateSpellRange(first, last, skips);
4756 if (first >= endpos)
4758 // start the spell checker on the unit of meaning
4759 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4760 WordLangTuple wl = WordLangTuple(word, lang);
4761 SpellChecker::Result result = word.size() ?
4762 speller->check(wl) : SpellChecker::WORD_OK;
4763 d->markMisspelledWords(first, last, result, word, skips);
4767 static docstring_list suggestions;
4768 pos_type to = endpos;
4769 while (start < endpos) {
4771 spellCheck(start, to, wl, suggestions, false);
4775 d->readySpellCheck();
4779 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4781 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4782 if (result || pos <= 0 || pos > size())
4784 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4785 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4790 string Paragraph::magicLabel() const
4793 ss << "magicparlabel-" << id();