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 // For these, we use switches, so they should be taken as
1075 // base inside the inset.
1076 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1077 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1078 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1079 // Now re-do font changes in a way needed here
1080 // (using switches with multi-par insets)
1081 InsetText const * textinset = inset->asInsetText();
1082 bool const cprotect = textinset
1083 ? textinset->hasCProtectContent(runparams.moving_arg)
1084 && !textinset->text().isMainText()
1086 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1087 runparams, running_font,
1091 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1095 runparams.local_font = &basefont;
1098 size_t const previous_row_count = os.texrow().rows();
1101 runparams.lastid = id_;
1102 runparams.lastpos = i;
1103 inset->latex(os, runparams);
1104 } catch (EncodingException & e) {
1105 // add location information and throw again.
1114 if (os.texrow().rows() > previous_row_count) {
1115 os.texrow().start(owner_->id(), i + 1);
1118 column += (unsigned int)(os.os().tellp() - len);
1121 if (owner_->isDeleted(i))
1122 --runparams.inDeletedInset;
1126 void Paragraph::Private::latexSpecialChar(otexstream & os,
1127 BufferParams const & bparams,
1128 OutputParams const & runparams,
1129 Font const & running_font,
1130 string & alien_script,
1131 Layout const & style,
1134 unsigned int & column)
1136 char_type const c = owner_->getUChar(bparams, runparams, i);
1138 if (style.pass_thru || runparams.pass_thru
1139 || contains(style.pass_thru_chars, c)
1140 || contains(runparams.pass_thru_chars, c)) {
1142 Encoding const * const enc = runparams.encoding;
1143 if (enc && !enc->encodable(c))
1144 throw EncodingException(c);
1150 // TIPA uses its own T3 encoding
1151 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1153 // If T1 font encoding is used, use the special
1154 // characters it provides.
1155 // NOTE: Some languages reset the font encoding internally to a
1156 // non-standard font encoding. If we are using such a language,
1157 // we do not output special T1 chars.
1158 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1159 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1160 && latexSpecialT1(c, os, i, column))
1162 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1163 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1164 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1167 // Otherwise, we use what LaTeX provides us.
1170 os << "\\textbackslash" << termcmd;
1174 os << "\\textless" << termcmd;
1178 os << "\\textgreater" << termcmd;
1182 os << "\\textbar" << termcmd;
1187 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1188 (end_pos == -1 || i + 1 < end_pos) &&
1189 text_[i+1] == '-') {
1190 // Prevent "--" becoming an en dash and "---" an em dash.
1191 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1197 os << "\\textquotedbl" << termcmd;
1202 case '%': case '#': case '{':
1210 os << "\\textasciitilde" << termcmd;
1215 os << "\\textasciicircum" << termcmd;
1222 // avoid being mistaken for optional arguments
1230 // Blanks are printed before font switching.
1231 // Sure? I am not! (try nice-latex)
1232 // I am sure it's correct. LyX might be smarter
1233 // in the future, but for now, nothing wrong is
1239 // XeTeX's dash behaviour is determined via a global setting
1240 if (bparams.use_dash_ligatures
1241 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1243 // TODO #10961: && not in inset Flex Code
1244 // TODO #10961: && not in layout LyXCode
1245 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1262 Encoding const & encoding = *(runparams.encoding);
1263 char_type next = '\0';
1264 if (i + 1 < int(text_.size())) {
1265 next = text_[i + 1];
1266 if (Encodings::isCombiningChar(next)) {
1267 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1272 pair<docstring, bool> latex = encoding.latexChar(c);
1273 docstring nextlatex;
1274 bool nexttipas = false;
1275 string nexttipashortcut;
1276 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1277 nextlatex = encoding.latexChar(next).first;
1278 if (runparams.inIPA) {
1279 nexttipashortcut = Encodings::TIPAShortcut(next);
1280 nexttipas = !nexttipashortcut.empty();
1284 if (runparams.inIPA) {
1285 string const tipashortcut = Encodings::TIPAShortcut(c);
1286 if (!tipashortcut.empty()) {
1287 latex.first = from_ascii(tipashortcut);
1288 latex.second = false;
1292 // eventually close "script wrapper" command (see `Paragraph::latex`)
1293 if (!alien_script.empty()
1294 && alien_script != Encodings::isKnownScriptChar(next)) {
1295 column += latex.first.length();
1296 alien_script.clear();
1297 os << latex.first << "}";
1301 && ((!prefixIs(nextlatex, '\\')
1302 && !prefixIs(nextlatex, '{')
1303 && !prefixIs(nextlatex, '}'))
1305 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1307 // Prevent eating of a following space or command corruption by
1308 // following characters
1309 if (next == ' ' || next == '\0') {
1310 column += latex.first.length() + 1;
1311 os << latex.first << "{}";
1313 column += latex.first.length();
1314 os << latex.first << " ";
1317 column += latex.first.length() - 1;
1325 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1326 pos_type i, unsigned int & column)
1332 // In T1 encoding, these characters exist
1333 // but we should avoid ligatures
1334 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1336 os << "\\textcompwordmark" << termcmd;
1343 // soul.sty breaks with \char`\"
1344 os << "\\textquotedbl" << termcmd;
1353 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1354 pos_type i, unsigned int & column)
1356 // TU encoding is currently on par with T1.
1357 return latexSpecialT1(c, os, i, column);
1361 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1362 pos_type /*i*/, unsigned int & column)
1372 os << "\\textvertline" << termcmd;
1381 void Paragraph::Private::validate(LaTeXFeatures & features) const
1383 if (layout_->inpreamble && inset_owner_) {
1384 // FIXME: Using a string stream here circumvents the encoding
1385 // switching machinery of odocstream. Therefore the
1386 // output is wrong if this paragraph contains content
1387 // that needs to switch encoding.
1388 Buffer const & buf = inset_owner_->buffer();
1389 otexstringstream os;
1390 os << layout_->preamble();
1391 size_t const length = os.length();
1392 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1393 buf.getParFromID(owner_->id()).pit(), os,
1394 features.runparams(), string(), 0, -1, true);
1395 if (os.length() > length)
1396 features.addPreambleSnippet(os.release(), true);
1399 if (features.runparams().flavor == OutputParams::HTML
1400 && layout_->htmltitle()) {
1401 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1404 // check the params.
1405 if (!params_.spacing().isDefault())
1406 features.require("setspace");
1409 features.useLayout(layout_->name());
1412 fontlist_.validate(features);
1414 // then the indentation
1415 if (!params_.leftIndent().zero())
1416 features.require("ParagraphLeftIndent");
1419 InsetList::const_iterator icit = insetlist_.begin();
1420 InsetList::const_iterator iend = insetlist_.end();
1421 for (; icit != iend; ++icit) {
1423 features.inDeletedInset(owner_->isDeleted(icit->pos));
1424 if (icit->inset->lyxCode() == FOOT_CODE) {
1425 // FIXME: an item inset would make things much easier.
1426 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1427 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1428 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1429 && (icit->pos < begin_of_body_
1430 || (icit->pos == begin_of_body_
1431 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1432 features.saveNoteEnv("description");
1434 icit->inset->validate(features);
1435 features.inDeletedInset(false);
1436 if (layout_->needprotect &&
1437 icit->inset->lyxCode() == FOOT_CODE)
1438 features.require("NeedLyXFootnoteCode");
1442 // then the contents
1443 BufferParams const bp = features.runparams().is_child
1444 ? features.buffer().masterParams() : features.buffer().params();
1445 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1446 char_type c = text_[i];
1447 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1449 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1450 features.require("textquotedblp");
1451 else if (bp.main_font_encoding() != "T1"
1452 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1453 features.require("textquotedbl");
1454 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1455 // features that depend on the font or input encoding
1456 string feats = ci.textpreamble();
1457 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1458 if (fontenc.empty())
1459 fontenc = features.runparams().main_fontenc;
1460 while (!feats.empty()) {
1462 feats = split(feats, feat, ',');
1463 if (contains(feat, "!=")) {
1464 // a feature that is required except for the spcified
1465 // font or input encodings
1467 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1468 // multiple encodings are separated by semicolon
1469 vector<string> context = getVectorFromString(contexts, ";");
1470 // require feature if the context matches neither current font
1471 // nor input encoding
1472 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1473 && std::find(context.begin(), context.end(),
1474 features.runparams().encoding->name()) == context.end())
1475 features.require(realfeature);
1476 } else if (contains(feat, '=')) {
1477 // a feature that is required only for the spcified
1478 // font or input encodings
1480 string const contexts = split(feat, realfeature, '=');
1481 // multiple encodings are separated by semicolon
1482 vector<string> context = getVectorFromString(contexts, ";");
1483 // require feature if the context matches either current font
1484 // or input encoding
1485 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1486 || std::find(context.begin(), context.end(),
1487 features.runparams().encoding->name()) != context.end())
1488 features.require(realfeature);
1491 } else if (!bp.use_dash_ligatures
1492 && (c == 0x2013 || c == 0x2014)
1493 && bp.useNonTeXFonts
1494 && features.runparams().flavor == OutputParams::XETEX)
1495 // XeTeX's dash behaviour is determined via a global setting
1496 features.require("xetexdashbreakstate");
1497 BufferEncodings::validate(c, features);
1501 /////////////////////////////////////////////////////////////////////
1505 /////////////////////////////////////////////////////////////////////
1508 Layout const emptyParagraphLayout;
1511 Paragraph::Paragraph()
1512 : d(new Paragraph::Private(this, emptyParagraphLayout))
1519 Paragraph::Paragraph(Paragraph const & par)
1520 : itemdepth(par.itemdepth),
1521 d(new Paragraph::Private(*par.d, this))
1527 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1528 : itemdepth(par.itemdepth),
1529 d(new Paragraph::Private(*par.d, this, beg, end))
1535 Paragraph & Paragraph::operator=(Paragraph const & par)
1537 // needed as we will destroy the private part before copying it
1539 itemdepth = par.itemdepth;
1543 d = new Private(*par.d, this);
1550 Paragraph::~Paragraph()
1559 // this shall be called just before every "os << ..." action.
1560 void flushString(ostream & os, docstring & s)
1569 void Paragraph::write(ostream & os, BufferParams const & bparams,
1570 depth_type & dth) const
1572 // The beginning or end of a deeper (i.e. nested) area?
1573 if (dth != d->params_.depth()) {
1574 if (d->params_.depth() > dth) {
1575 while (d->params_.depth() > dth) {
1576 os << "\n\\begin_deeper";
1580 while (d->params_.depth() < dth) {
1581 os << "\n\\end_deeper";
1587 // First write the layout
1588 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1590 d->params_.write(os);
1592 Font font1(inherit_font, bparams.language);
1594 Change running_change = Change(Change::UNCHANGED);
1596 // this string is used as a buffer to avoid repetitive calls
1597 // to to_utf8(), which turn out to be expensive (JMarc)
1598 docstring write_buffer;
1601 for (pos_type i = 0; i <= size(); ++i) {
1603 Change const & change = lookupChange(i);
1604 if (change != running_change)
1605 flushString(os, write_buffer);
1606 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1607 running_change = change;
1612 // Write font changes
1613 Font font2 = getFontSettings(bparams, i);
1614 if (font2 != font1) {
1615 flushString(os, write_buffer);
1616 font2.lyxWriteChanges(font1, os);
1621 char_type const c = d->text_[i];
1624 if (Inset const * inset = getInset(i)) {
1625 flushString(os, write_buffer);
1626 if (inset->directWrite()) {
1627 // international char, let it write
1628 // code directly so it's shorter in
1634 os << "\\begin_inset ";
1636 os << "\n\\end_inset\n\n";
1639 // FIXME This can be removed again once the mystery
1640 // crash has been resolved.
1645 flushString(os, write_buffer);
1646 os << "\n\\backslash\n";
1650 flushString(os, write_buffer);
1651 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1658 if ((column > 70 && c == ' ')
1660 flushString(os, write_buffer);
1664 // this check is to amend a bug. LyX sometimes
1665 // inserts '\0' this could cause problems.
1667 write_buffer.push_back(c);
1669 LYXERR0("NUL char in structure.");
1675 flushString(os, write_buffer);
1676 os << "\n\\end_layout\n";
1677 // FIXME This can be removed again once the mystery
1678 // crash has been resolved.
1683 void Paragraph::validate(LaTeXFeatures & features) const
1685 d->validate(features);
1686 bool fragile = features.runparams().moving_arg;
1687 fragile |= layout().needprotect;
1688 if (inInset().getLayout().isNeedProtect())
1690 if (needsCProtection(fragile))
1691 features.require("cprotect");
1695 void Paragraph::insert(pos_type start, docstring const & str,
1696 Font const & font, Change const & change)
1698 for (size_t i = 0, n = str.size(); i != n ; ++i)
1699 insertChar(start + i, str[i], font, change);
1703 void Paragraph::appendChar(char_type c, Font const & font,
1704 Change const & change)
1707 d->changes_.insert(change, d->text_.size());
1708 // when appending characters, no need to update tables
1709 d->text_.push_back(c);
1710 setFont(d->text_.size() - 1, font);
1711 d->requestSpellCheck(d->text_.size() - 1);
1715 void Paragraph::appendString(docstring const & s, Font const & font,
1716 Change const & change)
1718 pos_type end = s.size();
1719 size_t oldsize = d->text_.size();
1720 size_t newsize = oldsize + end;
1721 size_t capacity = d->text_.capacity();
1722 if (newsize >= capacity)
1723 d->text_.reserve(max(capacity + 100, newsize));
1725 // when appending characters, no need to update tables
1728 // FIXME: Optimize this!
1729 for (size_t i = oldsize; i != newsize; ++i) {
1731 d->changes_.insert(change, i);
1732 d->requestSpellCheck(i);
1734 d->fontlist_.set(oldsize, font);
1735 d->fontlist_.set(newsize - 1, font);
1739 void Paragraph::insertChar(pos_type pos, char_type c,
1742 d->insertChar(pos, c, Change(trackChanges ?
1743 Change::INSERTED : Change::UNCHANGED));
1747 void Paragraph::insertChar(pos_type pos, char_type c,
1748 Font const & font, bool trackChanges)
1750 d->insertChar(pos, c, Change(trackChanges ?
1751 Change::INSERTED : Change::UNCHANGED));
1756 void Paragraph::insertChar(pos_type pos, char_type c,
1757 Font const & font, Change const & change)
1759 d->insertChar(pos, c, change);
1764 void Paragraph::resetFonts(Font const & font)
1766 d->fontlist_.clear();
1767 d->fontlist_.set(0, font);
1768 d->fontlist_.set(d->text_.size() - 1, font);
1771 // Gets uninstantiated font setting at position.
1772 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1776 LYXERR0("pos: " << pos << " size: " << size());
1780 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1781 if (cit != d->fontlist_.end())
1784 if (pos == size() && !empty())
1785 return getFontSettings(bparams, pos - 1);
1787 // Optimisation: avoid a full font instantiation if there is no
1788 // language change from previous call.
1789 static Font previous_font;
1790 static Language const * previous_lang = nullptr;
1791 Language const * lang = getParLanguage(bparams);
1792 if (lang != previous_lang) {
1793 previous_lang = lang;
1794 previous_font = Font(inherit_font, lang);
1796 return previous_font;
1800 FontSpan Paragraph::fontSpan(pos_type pos) const
1802 LBUFERR(pos <= size());
1805 return FontSpan(pos, pos);
1808 FontList::const_iterator cit = d->fontlist_.begin();
1809 FontList::const_iterator end = d->fontlist_.end();
1810 for (; cit != end; ++cit) {
1811 if (cit->pos() >= pos) {
1812 if (pos >= beginOfBody())
1813 return FontSpan(max(start, beginOfBody()),
1816 return FontSpan(start,
1817 min(beginOfBody() - 1,
1820 start = cit->pos() + 1;
1823 // This should not happen, but if so, we take no chances.
1824 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1825 LASSERT(false, return FontSpan(pos, pos));
1829 // Gets uninstantiated font setting at position 0
1830 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1832 if (!empty() && !d->fontlist_.empty())
1833 return d->fontlist_.begin()->font();
1835 // Optimisation: avoid a full font instantiation if there is no
1836 // language change from previous call.
1837 static Font previous_font;
1838 static Language const * previous_lang = nullptr;
1839 if (bparams.language != previous_lang) {
1840 previous_lang = bparams.language;
1841 previous_font = Font(inherit_font, bparams.language);
1844 return previous_font;
1848 // Gets the fully instantiated font at a given position in a paragraph
1849 // This is basically the same function as Text::GetFont() in text2.cpp.
1850 // The difference is that this one is used for generating the LaTeX file,
1851 // and thus cosmetic "improvements" are disallowed: This has to deliver
1852 // the true picture of the buffer. (Asger)
1853 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1854 Font const & outerfont) const
1858 Font font = getFontSettings(bparams, pos);
1860 pos_type const body_pos = beginOfBody();
1861 FontInfo & fi = font.fontInfo();
1863 fi.realize(d->layout_->labelfont);
1865 fi.realize(d->layout_->font);
1867 fi.realize(outerfont.fontInfo());
1868 fi.realize(bparams.getFont().fontInfo());
1874 Font const Paragraph::getLabelFont
1875 (BufferParams const & bparams, Font const & outerfont) const
1877 FontInfo tmpfont = d->layout_->labelfont;
1878 tmpfont.realize(outerfont.fontInfo());
1879 tmpfont.realize(bparams.getFont().fontInfo());
1880 return Font(tmpfont, getParLanguage(bparams));
1884 Font const Paragraph::getLayoutFont
1885 (BufferParams const & bparams, Font const & outerfont) const
1887 FontInfo tmpfont = d->layout_->font;
1888 tmpfont.realize(outerfont.fontInfo());
1889 tmpfont.realize(bparams.getFont().fontInfo());
1890 return Font(tmpfont, getParLanguage(bparams));
1894 char_type Paragraph::getUChar(BufferParams const & bparams,
1895 OutputParams const & rp,
1898 char_type c = d->text_[pos];
1900 // Return unchanged character in LTR languages
1901 // or if we use poylglossia/bidi (XeTeX).
1902 if (rp.useBidiPackage()
1903 || !getFontSettings(bparams, pos).isRightToLeft())
1906 // Without polyglossia/bidi, we need to account for some special cases.
1907 // FIXME This needs to be audited!
1909 // * The input is as expected for all delimiters
1910 // => checked for Hebrew!
1911 // * The output matches the display in the LyX workarea
1912 // => checked for Hebrew!
1913 // * The special cases below are really necessary
1914 // => checked for Hebrew!
1915 // * In arabic_arabi, brackets are transformed to Arabic
1916 // Ornate Parentheses. Is this is really wanted?
1918 string const & lang = getFontSettings(bparams, pos).language()->lang();
1921 // 1. In the following languages, parentheses need to be reversed.
1922 // Also with polyglodia/luabidi
1923 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1925 // 2. In the following languages, brackets don't need to be reversed.
1926 bool const reversebrackets = lang != "arabic_arabtex"
1927 && lang != "arabic_arabi"
1930 // Now swap delimiters if needed.
1941 if (reversebrackets)
1945 if (reversebrackets)
1966 void Paragraph::setFont(pos_type pos, Font const & font)
1968 LASSERT(pos <= size(), return);
1970 // First, reduce font against layout/label font
1971 // Update: The setCharFont() routine in text2.cpp already
1972 // reduces font, so we don't need to do that here. (Asger)
1974 d->fontlist_.set(pos, font);
1978 void Paragraph::makeSameLayout(Paragraph const & par)
1980 d->layout_ = par.d->layout_;
1981 d->params_ = par.d->params_;
1985 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1987 if (isFreeSpacing())
1993 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1994 if (eraseChar(pos, trackChanges))
2000 return count > 0 || pos > 0;
2004 bool Paragraph::hasSameLayout(Paragraph const & par) const
2006 return par.d->layout_ == d->layout_
2007 && d->params_.sameLayout(par.d->params_);
2011 depth_type Paragraph::getDepth() const
2013 return d->params_.depth();
2017 depth_type Paragraph::getMaxDepthAfter() const
2019 if (d->layout_->isEnvironment())
2020 return d->params_.depth() + 1;
2022 return d->params_.depth();
2026 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2028 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2029 return getDefaultAlign(bparams);
2031 return d->params_.align();
2035 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2037 LyXAlignment res = layout().align;
2038 if (isRTL(bparams)) {
2040 if (res == LYX_ALIGN_LEFT)
2041 res = LYX_ALIGN_RIGHT;
2042 else if (res == LYX_ALIGN_RIGHT)
2043 res = LYX_ALIGN_LEFT;
2049 docstring const & Paragraph::labelString() const
2051 return d->params_.labelString();
2055 // the next two functions are for the manual labels
2056 docstring const Paragraph::getLabelWidthString() const
2058 if (d->layout_->margintype == MARGIN_MANUAL
2059 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2060 return d->params_.labelWidthString();
2062 return _("Senseless with this layout!");
2066 void Paragraph::setLabelWidthString(docstring const & s)
2068 d->params_.labelWidthString(s);
2072 docstring Paragraph::expandLabel(Layout const & layout,
2073 BufferParams const & bparams) const
2075 return expandParagraphLabel(layout, bparams, true);
2079 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2080 BufferParams const & bparams, bool process_appendix) const
2082 DocumentClass const & tclass = bparams.documentClass();
2083 string const & lang = getParLanguage(bparams)->code();
2084 bool const in_appendix = process_appendix && d->params_.appendix();
2085 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2087 if (fmt.empty() && !layout.counter.empty())
2088 return tclass.counters().theCounter(layout.counter, lang);
2090 // handle 'inherited level parts' in 'fmt',
2091 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2092 size_t const i = fmt.find('@', 0);
2093 if (i != docstring::npos) {
2094 size_t const j = fmt.find('@', i + 1);
2095 if (j != docstring::npos) {
2096 docstring parent(fmt, i + 1, j - i - 1);
2097 docstring label = from_ascii("??");
2098 if (tclass.hasLayout(parent))
2099 label = expandParagraphLabel(tclass[parent], bparams,
2101 fmt = docstring(fmt, 0, i) + label
2102 + docstring(fmt, j + 1, docstring::npos);
2106 return tclass.counters().counterLabel(fmt, lang);
2110 void Paragraph::applyLayout(Layout const & new_layout)
2112 d->layout_ = &new_layout;
2113 LyXAlignment const oldAlign = d->params_.align();
2115 if (!(oldAlign & d->layout_->alignpossible)) {
2116 frontend::Alert::warning(_("Alignment not permitted"),
2117 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2118 d->params_.align(LYX_ALIGN_LAYOUT);
2123 pos_type Paragraph::beginOfBody() const
2125 return d->begin_of_body_;
2129 void Paragraph::setBeginOfBody()
2131 if (d->layout_->labeltype != LABEL_MANUAL) {
2132 d->begin_of_body_ = 0;
2136 // Unroll the first two cycles of the loop
2137 // and remember the previous character to
2138 // remove unnecessary getChar() calls
2140 pos_type end = size();
2141 bool prev_char_deleted = false;
2142 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2145 char_type previous_char = d->text_[i];
2146 if (!(isNewline(i) || isEnvSeparator(i))) {
2148 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2149 char_type temp = d->text_[i];
2150 prev_char_deleted = isDeleted(i);
2151 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2154 previous_char = temp;
2160 d->begin_of_body_ = i;
2164 bool Paragraph::allowParagraphCustomization() const
2166 return inInset().allowParagraphCustomization();
2170 bool Paragraph::usePlainLayout() const
2172 return inInset().usePlainLayout();
2176 bool Paragraph::isPassThru() const
2178 return inInset().isPassThru() || d->layout_->pass_thru;
2183 // paragraphs inside floats need different alignment tags to avoid
2186 bool noTrivlistCentering(InsetCode code)
2188 return code == FLOAT_CODE
2189 || code == WRAP_CODE
2190 || code == CELL_CODE;
2194 string correction(string const & orig)
2196 if (orig == "flushleft")
2197 return "raggedright";
2198 if (orig == "flushright")
2199 return "raggedleft";
2200 if (orig == "center")
2206 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2207 InsetCode code, bool const lastpar, int & col)
2209 string macro = suffix + "{";
2210 if (noTrivlistCentering(code)) {
2212 // the last paragraph in non-trivlist-aligned
2213 // context is special (to avoid unwanted whitespace)
2214 if (suffix == "\\begin") {
2215 macro = "\\" + correction(env) + "{}";
2216 os << from_ascii(macro);
2217 col += macro.size();
2222 macro += correction(env);
2226 if (suffix == "\\par\\end") {
2230 os << from_ascii(macro);
2231 col += macro.size();
2232 if (suffix == "\\begin") {
2242 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2243 otexstream & os, OutputParams const & runparams) const
2248 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2249 (layout_->toggle_indent != ITOGGLE_NEVER) :
2250 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2252 if (canindent && params_.noindent() && !layout_->pass_thru) {
2253 os << "\\noindent ";
2257 LyXAlignment const curAlign = params_.align();
2259 if (curAlign == layout_->align)
2263 case LYX_ALIGN_NONE:
2264 case LYX_ALIGN_BLOCK:
2265 case LYX_ALIGN_LAYOUT:
2266 case LYX_ALIGN_SPECIAL:
2267 case LYX_ALIGN_DECIMAL:
2269 case LYX_ALIGN_LEFT:
2270 case LYX_ALIGN_RIGHT:
2271 case LYX_ALIGN_CENTER:
2272 if (runparams.moving_arg) {
2279 string const begin_tag = "\\begin";
2280 InsetCode code = ownerCode();
2281 bool const lastpar = runparams.isLastPar;
2282 // RTL in classic (PDF)LaTeX (without the Bidi package)
2283 // Luabibdi (used by LuaTeX) behaves like classic
2284 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2285 && !runparams.useBidiPackage();
2288 case LYX_ALIGN_NONE:
2289 case LYX_ALIGN_BLOCK:
2290 case LYX_ALIGN_LAYOUT:
2291 case LYX_ALIGN_SPECIAL:
2292 case LYX_ALIGN_DECIMAL:
2294 case LYX_ALIGN_LEFT: {
2296 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2297 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2299 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2301 } case LYX_ALIGN_RIGHT: {
2303 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2304 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2306 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2308 } case LYX_ALIGN_CENTER: {
2309 corrected_env(os, begin_tag, "center", code, lastpar, column);
2318 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2319 otexstream & os, OutputParams const & runparams) const
2321 LyXAlignment const curAlign = params_.align();
2323 if (curAlign == layout_->align)
2327 case LYX_ALIGN_NONE:
2328 case LYX_ALIGN_BLOCK:
2329 case LYX_ALIGN_LAYOUT:
2330 case LYX_ALIGN_SPECIAL:
2331 case LYX_ALIGN_DECIMAL:
2333 case LYX_ALIGN_LEFT:
2334 case LYX_ALIGN_RIGHT:
2335 case LYX_ALIGN_CENTER:
2336 if (runparams.moving_arg)
2341 bool output = false;
2343 string const end_tag = "\\par\\end";
2344 InsetCode code = ownerCode();
2345 bool const lastpar = runparams.isLastPar;
2346 // RTL in classic (PDF)LaTeX (without the Bidi package)
2347 // Luabibdi (used by LuaTeX) behaves like classic
2348 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2349 && !runparams.useBidiPackage();
2352 case LYX_ALIGN_NONE:
2353 case LYX_ALIGN_BLOCK:
2354 case LYX_ALIGN_LAYOUT:
2355 case LYX_ALIGN_SPECIAL:
2356 case LYX_ALIGN_DECIMAL:
2358 case LYX_ALIGN_LEFT: {
2360 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2361 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2363 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2365 } case LYX_ALIGN_RIGHT: {
2367 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2368 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2370 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2372 } case LYX_ALIGN_CENTER: {
2373 corrected_env(os, end_tag, "center", code, lastpar, col);
2378 return output || lastpar;
2382 // This one spits out the text of the paragraph
2383 void Paragraph::latex(BufferParams const & bparams,
2384 Font const & outerfont,
2386 OutputParams const & runparams,
2387 int start_pos, int end_pos, bool force) const
2389 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2391 // FIXME This check should not be needed. Perhaps issue an
2392 // error if it triggers.
2393 Layout const & style = inInset().forcePlainLayout() ?
2394 bparams.documentClass().plainLayout() : *d->layout_;
2396 if (!force && style.inpreamble)
2399 bool const allowcust = allowParagraphCustomization();
2401 // Current base font for all inherited font changes, without any
2402 // change caused by an individual character, except for the language:
2403 // It is set to the language of the first character.
2404 // As long as we are in the label, this font is the base font of the
2405 // label. Before the first body character it is set to the base font
2409 // If there is an open font-encoding changing command (script wrapper),
2410 // alien_script is set to its name
2411 string alien_script;
2414 // Maybe we have to create a optional argument.
2415 pos_type body_pos = beginOfBody();
2416 unsigned int column = 0;
2418 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2419 Font const real_outerfont = (!inInset().inheritFont()
2420 && runparams.local_font != nullptr)
2421 ? Font(runparams.local_font->fontInfo()) : outerfont;
2424 // the optional argument is kept in curly brackets in
2425 // case it contains a ']'
2426 // This is not strictly needed, but if this is changed it
2427 // would be a file format change, and tex2lyx would need
2428 // to be adjusted, since it unconditionally removes the
2429 // braces when it parses \item.
2432 basefont = getLabelFont(bparams, real_outerfont);
2434 basefont = getLayoutFont(bparams, real_outerfont);
2437 // Which font is currently active?
2438 Font running_font(basefont);
2439 // Do we have an open font change?
2440 bool open_font = false;
2442 Change runningChange = Change(Change::UNCHANGED);
2444 Encoding const * const prev_encoding = runparams.encoding;
2446 os.texrow().start(id(), 0);
2448 // if the paragraph is empty, the loop will not be entered at all
2450 // For InTitle commands, we have already opened a group
2451 // in output_latex::TeXOnePar.
2452 if (style.isCommand() && !style.intitle) {
2456 if (!style.leftdelim().empty()) {
2457 os << style.leftdelim();
2458 column += style.leftdelim().size();
2461 column += d->startTeXParParams(bparams, os, runparams);
2464 // Whether a \par can be issued for insets typeset inline with text.
2465 // Yes if greater than 0. This has to be static.
2466 THREAD_LOCAL_STATIC int parInline = 0;
2468 for (pos_type i = 0; i < size(); ++i) {
2469 // First char in paragraph or after label?
2470 if (i == body_pos) {
2473 bool needPar = false;
2474 column += running_font.latexWriteEndChanges(
2475 os, bparams, runparams,
2476 basefont, basefont, needPar);
2479 basefont = getLayoutFont(bparams, real_outerfont);
2480 running_font = basefont;
2482 column += Changes::latexMarkChange(os, bparams,
2483 runningChange, Change(Change::UNCHANGED),
2485 runningChange = Change(Change::UNCHANGED);
2490 // For InTitle commands, we have already opened a group
2491 // in output_latex::TeXOnePar.
2492 if (style.isCommand() && !style.intitle) {
2497 if (!style.leftdelim().empty()) {
2498 os << style.leftdelim();
2499 column += style.leftdelim().size();
2503 column += d->startTeXParParams(bparams, os,
2507 runparams.wasDisplayMath = runparams.inDisplayMath;
2508 runparams.inDisplayMath = false;
2509 bool deleted_display_math = false;
2510 Change const & change = runparams.inDeletedInset
2511 ? runparams.changeOfDeletedInset : lookupChange(i);
2513 char_type const c = d->text_[i];
2515 // Check whether a display math inset follows
2517 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2519 runparams.ctObject = getInset(i)->CtObject(runparams);
2521 InsetMath const * im = getInset(i)->asInsetMath();
2522 if (im && im->asHullInset()
2523 && im->asHullInset()->outerDisplay()) {
2524 runparams.inDisplayMath = true;
2525 // runparams.inDeletedInset will be set by
2526 // latexInset later, but we need this info
2527 // before it is called. On the other hand, we
2528 // cannot set it here because it is a counter.
2529 deleted_display_math = isDeleted(i);
2531 if (bparams.output_changes && deleted_display_math
2532 && runningChange == change
2533 && change.type == Change::DELETED
2534 && !os.afterParbreak()) {
2535 // A display math in the same paragraph follows.
2536 // We have to close and then reopen \lyxdeleted,
2537 // otherwise the math will be shifted up.
2538 OutputParams rp = runparams;
2540 bool needPar = false;
2541 column += running_font.latexWriteEndChanges(
2542 os, bparams, rp, basefont,
2546 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2547 : getLayoutFont(bparams, real_outerfont);
2548 running_font = basefont;
2549 column += Changes::latexMarkChange(os, bparams,
2550 Change(Change::INSERTED), change, rp);
2554 if (bparams.output_changes && runningChange != change) {
2555 if (!alien_script.empty()) {
2558 alien_script.clear();
2561 bool needPar = false;
2562 column += running_font.latexWriteEndChanges(
2563 os, bparams, runparams,
2564 basefont, basefont, needPar);
2567 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2568 : getLayoutFont(bparams, real_outerfont);
2569 running_font = basefont;
2570 column += Changes::latexMarkChange(os, bparams, runningChange,
2572 runningChange = change;
2575 // do not output text which is marked deleted
2576 // if change tracking output is disabled
2577 if (!bparams.output_changes && change.deleted()) {
2583 // Fully instantiated font
2584 Font const current_font = getFont(bparams, i, outerfont);
2586 Font const prev_font = (i > 0) ?
2587 getFont(bparams, i - 1, outerfont)
2590 Font const last_font = running_font;
2591 bool const in_ct_deletion = (bparams.output_changes
2592 && runningChange == change
2593 && change.type == Change::DELETED
2594 && !os.afterParbreak());
2595 // Insets where font switches are used (rather than font commands)
2596 bool const fontswitch_inset =
2599 && getInset(i)->allowMultiPar()
2600 && !getInset(i)->isPassThru();
2602 // Do we need to close the previous font?
2604 ((current_font != running_font
2605 || current_font.language() != running_font.language())
2606 || (fontswitch_inset
2607 && (current_font == prev_font
2608 || current_font.language() == prev_font.language()))))
2610 // ensure there is no open script-wrapper
2611 if (!alien_script.empty()) {
2614 alien_script.clear();
2616 bool needPar = false;
2617 if (in_ct_deletion) {
2618 // We have to close and then reopen \lyxdeleted,
2619 // as strikeout needs to be on lowest level.
2623 column += running_font.latexWriteEndChanges(
2624 os, bparams, runparams, basefont,
2625 (i == body_pos-1) ? basefont : current_font,
2627 if (in_ct_deletion) {
2628 // We have to close and then reopen \lyxdeleted,
2629 // as strikeout needs to be on lowest level.
2630 OutputParams rp = runparams;
2631 column += Changes::latexMarkChange(os, bparams,
2632 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2634 running_font = basefont;
2638 // if necessary, close language environment before opening CJK
2639 string const running_lang = running_font.language()->babel();
2640 string const lang_end_command = lyxrc.language_command_end;
2641 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2642 && !running_lang.empty()
2643 && running_lang == openLanguageName()
2644 && current_font.language()->encoding()->package() == Encoding::CJK) {
2645 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2646 os << from_ascii(end_tag);
2647 column += end_tag.length();
2651 // Switch file encoding if necessary (and allowed)
2652 if (!runparams.pass_thru && !style.pass_thru &&
2653 runparams.encoding->package() != Encoding::none &&
2654 current_font.language()->encoding()->package() != Encoding::none) {
2655 pair<bool, int> const enc_switch =
2656 switchEncoding(os.os(), bparams, runparams,
2657 *(current_font.language()->encoding()));
2658 if (enc_switch.first) {
2659 column += enc_switch.second;
2660 runparams.encoding = current_font.language()->encoding();
2664 // A display math inset inside an ulem command will be output
2665 // as a box of width \linewidth, so we have to either disable
2666 // indentation if the inset starts a paragraph, or start a new
2667 // line to accommodate such box. This has to be done before
2668 // writing any font changing commands.
2669 if (runparams.inDisplayMath && !deleted_display_math
2670 && runparams.inulemcmd) {
2671 if (os.afterParbreak())
2677 // Do we need to change font?
2678 if ((current_font != running_font ||
2679 current_font.language() != running_font.language())
2680 && i != body_pos - 1)
2682 if (in_ct_deletion) {
2683 // We have to close and then reopen \lyxdeleted,
2684 // as strikeout needs to be on lowest level.
2685 bool needPar = false;
2686 OutputParams rp = runparams;
2687 column += running_font.latexWriteEndChanges(
2688 os, bparams, rp, basefont,
2693 otexstringstream ots;
2694 if (!fontswitch_inset) {
2695 InsetText const * textinset = inInset().asInsetText();
2696 bool const cprotect = textinset
2697 ? textinset->hasCProtectContent(runparams.moving_arg)
2698 && !textinset->text().isMainText()
2700 column += current_font.latexWriteStartChanges(ots, bparams,
2701 runparams, basefont, last_font, false,
2704 // Check again for display math in ulem commands as a
2705 // font change may also occur just before a math inset.
2706 if (runparams.inDisplayMath && !deleted_display_math
2707 && runparams.inulemcmd) {
2708 if (os.afterParbreak())
2713 running_font = current_font;
2715 docstring fontchange = ots.str();
2717 // check whether the fontchange ends with a \\textcolor
2718 // modifier and the text starts with a space. If so we
2719 // need to add } in order to prevent \\textcolor from gobbling
2720 // the space (bug 4473).
2721 docstring const last_modifier = rsplit(fontchange, '\\');
2722 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2723 os << from_ascii("{}");
2724 else if (ots.terminateCommand())
2726 if (in_ct_deletion) {
2727 // We have to close and then reopen \lyxdeleted,
2728 // as strikeout needs to be on lowest level.
2729 OutputParams rp = runparams;
2730 column += Changes::latexMarkChange(os, bparams,
2731 Change(Change::UNCHANGED), change, rp);
2735 // FIXME: think about end_pos implementation...
2736 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2737 // FIXME: integrate this case in latexSpecialChar
2738 // Do not print the separation of the optional argument
2739 // if style.pass_thru is false. This works because
2740 // latexSpecialChar ignores spaces if
2741 // style.pass_thru is false.
2742 if (i != body_pos - 1) {
2743 if (d->simpleTeXBlanks(bparams, runparams, os,
2744 i, column, current_font, style)) {
2745 // A surrogate pair was output. We
2746 // must not call latexSpecialChar
2747 // in this iteration, since it would output
2748 // the combining character again.
2755 OutputParams rp = runparams;
2756 rp.free_spacing = style.free_spacing;
2757 rp.local_font = ¤t_font;
2758 rp.intitle = style.intitle;
2760 // Two major modes: LaTeX or plain
2761 // Handle here those cases common to both modes
2762 // and then split to handle the two modes separately.
2763 if (c == META_INSET) {
2764 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2765 // Greyedout notes and, in general, all insets
2766 // with InsetLayout::isDisplay() == false,
2767 // are typeset inline with the text. So, we
2768 // can add a \par to the last paragraph of
2769 // such insets only if nothing else follows.
2770 bool incremented = false;
2771 Inset const * inset = getInset(i);
2772 InsetText const * textinset = inset
2773 ? inset->asInsetText()
2775 if (i + 1 == size() && textinset
2776 && !inset->getLayout().isDisplay()) {
2777 ParagraphList const & pars =
2778 textinset->text().paragraphs();
2779 pit_type const pit = pars.size() - 1;
2780 Font const lastfont =
2781 pit < 0 || pars[pit].empty()
2782 ? pars[pit].getLayoutFont(
2785 : pars[pit].getFont(bparams,
2786 pars[pit].size() - 1,
2788 if (lastfont.fontInfo().size() !=
2789 basefont.fontInfo().size()) {
2794 // We need to restore parts of this after insets with
2795 // allowMultiPar() true
2796 Font const save_basefont = basefont;
2797 d->latexInset(bparams, os, rp, running_font,
2798 basefont, real_outerfont, open_font,
2799 runningChange, style, i, column, fontswitch_inset);
2800 if (fontswitch_inset) {
2802 bool needPar = false;
2803 column += running_font.latexWriteEndChanges(
2804 os, bparams, runparams,
2805 basefont, basefont, needPar);
2808 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2809 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2810 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2815 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2816 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2817 // Close \lyx*deleted and force its
2818 // reopening (if needed)
2821 runningChange = Change(Change::UNCHANGED);
2822 runparams.ctObject = OutputParams::CT_NORMAL;
2825 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2826 if (!bparams.useNonTeXFonts)
2827 script = Encodings::isKnownScriptChar(c);
2828 if (script != alien_script) {
2829 if (!alien_script.empty()) {
2831 alien_script.clear();
2833 string fontenc = running_font.language()->fontenc(bparams);
2835 && !Encodings::fontencSupportsScript(fontenc, script)) {
2836 column += script.length() + 2;
2837 os << "\\" << script << "{";
2838 alien_script = script;
2842 d->latexSpecialChar(os, bparams, rp, running_font,
2843 alien_script, style, i, end_pos, column);
2844 } catch (EncodingException & e) {
2845 if (runparams.dryrun) {
2846 os << "<" << _("LyX Warning: ")
2847 << _("uncodable character") << " '";
2851 // add location information and throw again.
2859 // Set the encoding to that returned from latexSpecialChar (see
2860 // comment for encoding member in OutputParams.h)
2861 runparams.encoding = rp.encoding;
2863 // Also carry on the info on a closed ulem command for insets
2864 // such as Note that do not produce any output, so that no
2865 // command is ever executed but its opening was recorded.
2866 runparams.inulemcmd = rp.inulemcmd;
2868 // These need to be passed upstream as well
2869 runparams.need_maketitle = rp.need_maketitle;
2870 runparams.have_maketitle = rp.have_maketitle;
2872 // And finally, pass the post_macros upstream
2873 runparams.post_macro = rp.post_macro;
2876 // Close wrapper for alien script
2877 if (!alien_script.empty()) {
2879 alien_script.clear();
2882 // If we have an open font definition, we have to close it
2884 // Make sure that \\par is done with the font of the last
2885 // character if this has another size as the default.
2886 // This is necessary because LaTeX (and LyX on the screen)
2887 // calculates the space between the baselines according
2888 // to this font. (Matthias)
2890 // We must not change the font for the last paragraph
2891 // of non-multipar insets, tabular cells or commands,
2892 // since this produces unwanted whitespace.
2894 Font const font = empty()
2895 ? getLayoutFont(bparams, real_outerfont)
2896 : getFont(bparams, size() - 1, real_outerfont);
2898 InsetText const * textinset = inInset().asInsetText();
2900 bool const maintext = textinset
2901 ? textinset->text().isMainText()
2904 size_t const numpars = textinset
2905 ? textinset->text().paragraphs().size()
2908 bool needPar = false;
2910 if (style.resfont.size() != font.fontInfo().size()
2911 && (!runparams.isLastPar || maintext
2912 || (numpars > 1 && d->ownerCode() != CELL_CODE
2913 && (inInset().getLayout().isDisplay()
2915 && !style.isCommand()) {
2918 #ifdef FIXED_LANGUAGE_END_DETECTION
2920 running_font.latexWriteEndChanges(os, bparams,
2921 runparams, basefont,
2922 next_->getFont(bparams, 0, outerfont),
2925 running_font.latexWriteEndChanges(os, bparams,
2926 runparams, basefont, basefont, needPar);
2929 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2930 //FIXME: there as we start another \selectlanguage with the next paragraph if
2931 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2932 running_font.latexWriteEndChanges(os, bparams, runparams,
2933 basefont, basefont, needPar);
2936 // The \par could not be inserted at the same nesting
2937 // level of the font size change, so do it now.
2938 os << "{\\" << font.latexSize() << "\\par}";
2942 column += Changes::latexMarkChange(os, bparams, runningChange,
2943 Change(Change::UNCHANGED), runparams);
2945 // Needed if there is an optional argument but no contents.
2946 if (body_pos > 0 && body_pos == size()) {
2950 if (!style.rightdelim().empty()) {
2951 os << style.rightdelim();
2952 column += style.rightdelim().size();
2955 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2956 && runparams.encoding != prev_encoding) {
2957 runparams.encoding = prev_encoding;
2958 os << setEncoding(prev_encoding->iconvName());
2961 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2965 bool Paragraph::emptyTag() const
2967 for (pos_type i = 0; i < size(); ++i) {
2968 if (Inset const * inset = getInset(i)) {
2969 InsetCode lyx_code = inset->lyxCode();
2970 // FIXME testing like that is wrong. What is
2972 if (lyx_code != TOC_CODE &&
2973 lyx_code != INCLUDE_CODE &&
2974 lyx_code != GRAPHICS_CODE &&
2975 lyx_code != ERT_CODE &&
2976 lyx_code != LISTINGS_CODE &&
2977 lyx_code != FLOAT_CODE &&
2978 lyx_code != TABULAR_CODE) {
2982 char_type c = d->text_[i];
2983 if (c != ' ' && c != '\t')
2991 string Paragraph::getID(Buffer const &, OutputParams const &)
2994 for (pos_type i = 0; i < size(); ++i) {
2995 if (Inset const * inset = getInset(i)) {
2996 InsetCode lyx_code = inset->lyxCode();
2997 if (lyx_code == LABEL_CODE) {
2998 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2999 docstring const & id = il->getParam("name");
3000 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3008 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3011 for (i = 0; i < size(); ++i) {
3012 if (Inset const * inset = getInset(i)) {
3013 inset->docbook(xs, runparams);
3015 char_type c = d->text_[i];
3025 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3029 for (i = 0; i < size(); ++i) {
3030 if (Inset const * inset = getInset(i)) {
3031 inset->xhtml(xs, runparams);
3033 char_type c = d->text_[i];
3043 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3046 pos_type size = text_.size();
3047 for (pos_type i = initial; i < size; ++i) {
3048 Font font = owner_->getFont(buf.params(), i, outerfont);
3049 if (text_[i] == META_INSET)
3051 if (i != initial && font != font_old)
3062 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3063 vector<xml::EndFontTag> & tagsToClose,
3064 bool & flag, FontState curstate, xml::FontTypes type)
3066 if (curstate == FONT_ON) {
3067 tagsToOpen.push_back(docbookStartFontTag(type));
3070 tagsToClose.push_back(docbookEndFontTag(type));
3075 class OptionalFontType {
3080 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3081 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3084 OptionalFontType fontShapeToXml(FontShape fs)
3088 return {xml::FT_ITALIC};
3090 return {xml::FT_SLANTED};
3091 case SMALLCAPS_SHAPE:
3092 return {xml::FT_SMALLCAPS};
3097 // the other tags are for internal use
3103 OptionalFontType fontFamilyToXml(FontFamily fm)
3107 return {xml::FT_ROMAN};
3109 return {xml::FT_SANS};
3110 case TYPEWRITER_FAMILY:
3111 return {xml::FT_TYPE};
3112 case INHERIT_FAMILY:
3115 // the other tags are for internal use
3121 OptionalFontType fontSizeToXml(FontSize fs)
3125 return {xml::FT_SIZE_TINY};
3127 return {xml::FT_SIZE_SCRIPT};
3129 return {xml::FT_SIZE_FOOTNOTE};
3131 return {xml::FT_SIZE_SMALL};
3133 return {xml::FT_SIZE_LARGE};
3135 return {xml::FT_SIZE_LARGER};
3137 return {xml::FT_SIZE_LARGEST};
3139 return {xml::FT_SIZE_HUGE};
3141 return {xml::FT_SIZE_HUGER};
3143 return {xml::FT_SIZE_INCREASE};
3145 return {xml::FT_SIZE_DECREASE};
3150 // the other tags are for internal use
3156 struct DocBookFontState
3158 FontShape curr_fs = INHERIT_SHAPE;
3159 FontFamily curr_fam = INHERIT_FAMILY;
3160 FontSize curr_size = INHERIT_SIZE;
3162 // track whether we have opened these tags
3163 bool emph_flag = false;
3164 bool bold_flag = false;
3165 bool noun_flag = false;
3166 bool ubar_flag = false;
3167 bool dbar_flag = false;
3168 bool sout_flag = false;
3169 bool xout_flag = false;
3170 bool wave_flag = false;
3172 bool shap_flag = false;
3174 bool faml_flag = false;
3176 bool size_flag = false;
3179 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3181 std::string const & default_family,
3182 DocBookFontState & fs)
3184 vector<xml::FontTag> tagsToOpen;
3185 vector<xml::EndFontTag> tagsToClose;
3188 FontState curstate = font.fontInfo().emph();
3189 if (font_old.emph() != curstate)
3190 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3193 curstate = font.fontInfo().noun();
3194 if (font_old.noun() != curstate)
3195 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3198 curstate = font.fontInfo().underbar();
3199 if (font_old.underbar() != curstate)
3200 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3203 curstate = font.fontInfo().strikeout();
3204 if (font_old.strikeout() != curstate)
3205 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3208 curstate = font.fontInfo().xout();
3209 if (font_old.xout() != curstate)
3210 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3213 curstate = font.fontInfo().uuline();
3214 if (font_old.uuline() != curstate)
3215 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3218 curstate = font.fontInfo().uwave();
3219 if (font_old.uwave() != curstate)
3220 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3223 // a little hackish, but allows us to reuse what we have.
3224 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3225 if (font_old.series() != font.fontInfo().series())
3226 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3229 fs.curr_fs = font.fontInfo().shape();
3230 FontShape old_fs = font_old.shape();
3231 if (old_fs != fs.curr_fs) {
3233 OptionalFontType tag = fontShapeToXml(old_fs);
3235 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3236 fs.shap_flag = false;
3239 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3241 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3245 fs.curr_fam = font.fontInfo().family();
3246 FontFamily old_fam = font_old.family();
3247 if (old_fam != fs.curr_fam) {
3249 OptionalFontType tag = fontFamilyToXml(old_fam);
3251 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3252 fs.faml_flag = false;
3254 switch (fs.curr_fam) {
3256 // we will treat a "default" font family as roman, since we have
3257 // no other idea what to do.
3258 if (default_family != "rmdefault" && default_family != "default") {
3259 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3260 fs.faml_flag = true;
3264 if (default_family != "sfdefault") {
3265 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3266 fs.faml_flag = true;
3269 case TYPEWRITER_FAMILY:
3270 if (default_family != "ttdefault") {
3271 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3272 fs.faml_flag = true;
3275 case INHERIT_FAMILY:
3278 // the other tags are for internal use
3285 fs.curr_size = font.fontInfo().size();
3286 FontSize old_size = font_old.size();
3287 if (old_size != fs.curr_size) {
3289 OptionalFontType tag = fontSizeToXml(old_size);
3291 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3292 fs.size_flag = false;
3295 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3296 if (tag.has_value) {
3297 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3298 fs.size_flag = true;
3302 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3305 } // anonymous namespace
3308 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3310 OutputParams const & runparams,
3311 Font const & outerfont,
3312 bool start_paragraph, bool close_paragraph,
3313 pos_type initial) const
3315 // track whether we have opened these tags
3316 DocBookFontState fs;
3318 if (start_paragraph)
3319 xs.startDivision(allowEmpty());
3321 Layout const & style = *d->layout_;
3323 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3325 string const default_family =
3326 buf.masterBuffer()->params().fonts_default_family;
3328 vector<xml::FontTag> tagsToOpen;
3329 vector<xml::EndFontTag> tagsToClose;
3331 // parsing main loop
3332 for (pos_type i = initial; i < size(); ++i) {
3333 // let's not show deleted material in the output
3337 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3339 // Determine which tags should be opened or closed.
3340 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3343 // Other such tags? What about the other text ranges?
3345 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3346 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3347 for (; cit != cen; ++cit)
3350 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3351 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3352 for (; sit != sen; ++sit)
3355 tagsToClose.clear();
3358 if (Inset const * inset = getInset(i)) {
3359 if (!runparams.for_toc || inset->isInToc()) {
3360 OutputParams np = runparams;
3361 np.local_font = &font;
3362 // If the paragraph has size 1, then we are in the "special
3363 // case" where we do not output the containing paragraph info.
3364 // This "special case" is defined in more details in output_docbook.cpp, makeParagraphs. The results
3365 // of that brittle logic is passed to this function through open_par.
3366 if (!inset->getLayout().htmlisblock() && size() != 1) // TODO: htmlisblock here too!
3367 np.docbook_in_par = true;
3368 inset->docbook(xs, np);
3371 char_type c = getUChar(buf.masterBuffer()->params(), runparams, i);
3374 font_old = font.fontInfo();
3377 // FIXME, this code is just imported from XHTML
3378 // I'm worried about what happens if a branch, say, is itself
3379 // wrapped in some font stuff. I think that will not work.
3381 if (runparams.docbook_in_listing)
3383 if (close_paragraph)
3390 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3391 vector<xml::EndFontTag> & tagsToClose,
3392 bool & flag, FontState curstate, xml::FontTypes type)
3394 if (curstate == FONT_ON) {
3395 tagsToOpen.push_back(xhtmlStartFontTag(type));
3398 tagsToClose.push_back(xhtmlEndFontTag(type));
3403 } // anonymous namespace
3406 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3408 OutputParams const & runparams,
3409 Font const & outerfont,
3410 bool start_paragraph, bool close_paragraph,
3411 pos_type initial) const
3415 // track whether we have opened these tags
3416 bool emph_flag = false;
3417 bool bold_flag = false;
3418 bool noun_flag = false;
3419 bool ubar_flag = false;
3420 bool dbar_flag = false;
3421 bool sout_flag = false;
3422 bool xout_flag = false;
3423 bool wave_flag = false;
3425 bool shap_flag = false;
3427 bool faml_flag = false;
3429 bool size_flag = false;
3431 Layout const & style = *d->layout_;
3433 if (start_paragraph)
3434 xs.startDivision(allowEmpty());
3437 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3439 FontShape curr_fs = INHERIT_SHAPE;
3440 FontFamily curr_fam = INHERIT_FAMILY;
3441 FontSize curr_size = INHERIT_SIZE;
3443 string const default_family =
3444 buf.masterBuffer()->params().fonts_default_family;
3446 vector<xml::FontTag> tagsToOpen;
3447 vector<xml::EndFontTag> tagsToClose;
3449 // parsing main loop
3450 for (pos_type i = initial; i < size(); ++i) {
3451 // let's not show deleted material in the output
3455 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3458 FontState curstate = font.fontInfo().emph();
3459 if (font_old.emph() != curstate)
3460 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3463 curstate = font.fontInfo().noun();
3464 if (font_old.noun() != curstate)
3465 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3468 curstate = font.fontInfo().underbar();
3469 if (font_old.underbar() != curstate)
3470 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3473 curstate = font.fontInfo().strikeout();
3474 if (font_old.strikeout() != curstate)
3475 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3478 curstate = font.fontInfo().xout();
3479 if (font_old.xout() != curstate)
3480 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3483 curstate = font.fontInfo().uuline();
3484 if (font_old.uuline() != curstate)
3485 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3488 curstate = font.fontInfo().uwave();
3489 if (font_old.uwave() != curstate)
3490 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3493 // a little hackish, but allows us to reuse what we have.
3494 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3495 if (font_old.series() != font.fontInfo().series())
3496 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3499 curr_fs = font.fontInfo().shape();
3500 FontShape old_fs = font_old.shape();
3501 if (old_fs != curr_fs) {
3505 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3508 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3510 case SMALLCAPS_SHAPE:
3511 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3517 // the other tags are for internal use
3525 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3529 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3532 case SMALLCAPS_SHAPE:
3533 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3540 // the other tags are for internal use
3547 curr_fam = font.fontInfo().family();
3548 FontFamily old_fam = font_old.family();
3549 if (old_fam != curr_fam) {
3553 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3556 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3558 case TYPEWRITER_FAMILY:
3559 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3561 case INHERIT_FAMILY:
3564 // the other tags are for internal use
3572 // we will treat a "default" font family as roman, since we have
3573 // no other idea what to do.
3574 if (default_family != "rmdefault" && default_family != "default") {
3575 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3580 if (default_family != "sfdefault") {
3581 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3585 case TYPEWRITER_FAMILY:
3586 if (default_family != "ttdefault") {
3587 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3591 case INHERIT_FAMILY:
3594 // the other tags are for internal use
3601 curr_size = font.fontInfo().size();
3602 FontSize old_size = font_old.size();
3603 if (old_size != curr_size) {
3607 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3610 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3613 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3616 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3619 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3622 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3625 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3628 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3631 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3634 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3637 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3643 // the other tags are for internal use
3649 switch (curr_size) {
3651 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3655 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3659 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3663 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3667 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3671 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3675 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3679 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3683 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3687 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3691 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3698 // the other tags are for internal use
3705 // Other such tags? What about the other text ranges?
3707 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3708 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3709 for (; cit != cen; ++cit)
3712 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3713 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3714 for (; sit != sen; ++sit)
3717 tagsToClose.clear();
3720 Inset const * inset = getInset(i);
3722 if (!runparams.for_toc || inset->isInToc()) {
3723 OutputParams np = runparams;
3724 np.local_font = &font;
3725 // If the paragraph has size 1, then we are in the "special
3726 // case" where we do not output the containing paragraph info
3727 if (!inset->getLayout().htmlisblock() && size() != 1)
3728 np.html_in_par = true;
3729 retval += inset->xhtml(xs, np);
3732 char_type c = getUChar(buf.masterBuffer()->params(),
3734 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3735 xs << XMLStream::ESCAPE_NONE << " ";
3739 font_old = font.fontInfo();
3743 // I'm worried about what happens if a branch, say, is itself
3744 // wrapped in some font stuff. I think that will not work.
3746 if (close_paragraph)
3753 bool Paragraph::isHfill(pos_type pos) const
3755 Inset const * inset = getInset(pos);
3756 return inset && inset->isHfill();
3760 bool Paragraph::isNewline(pos_type pos) const
3762 // U+2028 LINE SEPARATOR
3763 // U+2029 PARAGRAPH SEPARATOR
3764 char_type const c = d->text_[pos];
3765 if (c == 0x2028 || c == 0x2029)
3767 Inset const * inset = getInset(pos);
3768 return inset && inset->lyxCode() == NEWLINE_CODE;
3772 bool Paragraph::isEnvSeparator(pos_type pos) const
3774 Inset const * inset = getInset(pos);
3775 return inset && inset->lyxCode() == SEPARATOR_CODE;
3779 bool Paragraph::isLineSeparator(pos_type pos) const
3781 char_type const c = d->text_[pos];
3782 if (isLineSeparatorChar(c))
3784 Inset const * inset = getInset(pos);
3785 return inset && inset->isLineSeparator();
3789 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3793 if (ignore_deleted && isDeleted(pos))
3795 if (Inset const * inset = getInset(pos))
3796 return !inset->isLetter();
3797 // if we have a hard hyphen (no en- or emdash) or apostrophe
3798 // we pass this to the spell checker
3799 // FIXME: this method is subject to change, visit
3800 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3801 // to get an impression how complex this is.
3802 if (isHardHyphenOrApostrophe(pos))
3804 char_type const c = d->text_[pos];
3805 // We want to pass the escape chars to the spellchecker
3806 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3807 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3811 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3813 pos_type const psize = size();
3816 char_type const c = d->text_[pos];
3817 if (c != '-' && c != '\'')
3819 int nextpos = pos + 1;
3820 int prevpos = pos > 0 ? pos - 1 : 0;
3821 if ((nextpos == psize || isSpace(nextpos))
3822 && (pos == 0 || isSpace(prevpos)))
3828 bool Paragraph::needsCProtection(bool const fragile) const
3830 // first check the layout of the paragraph, but only in insets
3831 InsetText const * textinset = inInset().asInsetText();
3832 bool const maintext = textinset
3833 ? textinset->text().isMainText()
3836 if (!maintext && layout().needcprotect) {
3837 // Environments need cprotection regardless the content
3838 if (layout().latextype == LATEX_ENVIRONMENT)
3841 // Commands need cprotection if they contain specific chars
3842 int const nchars_escape = 9;
3843 static char_type const chars_escape[nchars_escape] = {
3844 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3846 docstring const pars = asString();
3847 for (int k = 0; k < nchars_escape; k++) {
3848 if (contains(pars, chars_escape[k]))
3853 // now check whether we have insets that need cprotection
3854 pos_type size = pos_type(d->text_.size());
3855 for (pos_type i = 0; i < size; ++i) {
3858 Inset const * ins = getInset(i);
3859 if (ins->needsCProtection(maintext, fragile))
3861 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3862 // Environments need cprotection regardless the content
3864 // Now check math environments
3865 InsetMath const * im = getInset(i)->asInsetMath();
3866 if (!im || im->cell(0).empty())
3868 switch(im->cell(0)[0]->lyxCode()) {
3869 case MATH_AMSARRAY_CODE:
3870 case MATH_SUBSTACK_CODE:
3872 case MATH_XYMATRIX_CODE:
3873 // these need cprotection
3884 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3886 return d->speller_state_.getRange(pos);
3890 bool Paragraph::isChar(pos_type pos) const
3892 if (Inset const * inset = getInset(pos))
3893 return inset->isChar();
3894 char_type const c = d->text_[pos];
3895 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3899 bool Paragraph::isSpace(pos_type pos) const
3901 if (Inset const * inset = getInset(pos))
3902 return inset->isSpace();
3903 char_type const c = d->text_[pos];
3904 return lyx::isSpace(c);
3909 Paragraph::getParLanguage(BufferParams const & bparams) const
3912 return getFirstFontSettings(bparams).language();
3913 // FIXME: we should check the prev par as well (Lgb)
3914 return bparams.language;
3918 bool Paragraph::isRTL(BufferParams const & bparams) const
3920 return getParLanguage(bparams)->rightToLeft()
3921 && !inInset().getLayout().forceLTR();
3925 void Paragraph::changeLanguage(BufferParams const & bparams,
3926 Language const * from, Language const * to)
3928 // change language including dummy font change at the end
3929 for (pos_type i = 0; i <= size(); ++i) {
3930 Font font = getFontSettings(bparams, i);
3931 if (font.language() == from) {
3932 font.setLanguage(to);
3934 d->requestSpellCheck(i);
3940 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3942 Language const * doc_language = bparams.language;
3943 for (auto const & f : d->fontlist_)
3944 if (f.font().language() != ignore_language &&
3945 f.font().language() != latex_language &&
3946 f.font().language() != doc_language)
3952 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3954 for (auto const & f : d->fontlist_) {
3955 Language const * lang = f.font().language();
3956 if (lang != ignore_language &&
3957 lang != latex_language)
3963 docstring Paragraph::asString(int options) const
3965 return asString(0, size(), options);
3969 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3971 odocstringstream os;
3974 && options & AS_STR_LABEL
3975 && !d->params_.labelString().empty())
3976 os << d->params_.labelString() << ' ';
3978 for (pos_type i = beg; i < end; ++i) {
3979 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3981 char_type const c = d->text_[i];
3982 if (isPrintable(c) || c == '\t'
3983 || (c == '\n' && (options & AS_STR_NEWLINES)))
3985 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3986 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3987 LASSERT(runparams != nullptr, return docstring());
3988 getInset(i)->plaintext(os, *runparams);
3990 getInset(i)->toString(os);
3999 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4000 bool const shorten, bool const label) const
4002 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4003 if (label && !labelString().empty())
4004 os += labelString() + ' ';
4005 if (!layout().isTocCaption())
4007 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4010 char_type const c = d->text_[i];
4013 else if (c == META_INSET)
4014 getInset(i)->forOutliner(os, tmplen, false);
4017 Text::shortenForOutliner(os, maxlen);
4021 void Paragraph::setInsetOwner(Inset const * inset)
4023 d->inset_owner_ = inset;
4027 int Paragraph::id() const
4033 void Paragraph::setId(int id)
4039 Layout const & Paragraph::layout() const
4045 void Paragraph::setLayout(Layout const & layout)
4047 d->layout_ = &layout;
4051 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4053 setLayout(tc.defaultLayout());
4057 void Paragraph::setPlainLayout(DocumentClass const & tc)
4059 setLayout(tc.plainLayout());
4063 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
4065 if (usePlainLayout())
4066 setPlainLayout(tclass);
4068 setDefaultLayout(tclass);
4072 Inset const & Paragraph::inInset() const
4074 LBUFERR(d->inset_owner_);
4075 return *d->inset_owner_;
4079 ParagraphParameters & Paragraph::params()
4085 ParagraphParameters const & Paragraph::params() const
4091 bool Paragraph::isFreeSpacing() const
4093 if (d->layout_->free_spacing)
4095 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4099 bool Paragraph::allowEmpty() const
4101 if (d->layout_->keepempty)
4103 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4107 bool Paragraph::brokenBiblio() const
4109 // There is a problem if there is no bibitem at position 0 in
4110 // paragraphs that need one, if there is another bibitem in the
4111 // paragraph or if this paragraph is not supposed to have
4112 // a bibitem inset at all.
4113 return ((d->layout_->labeltype == LABEL_BIBLIO
4114 && (d->insetlist_.find(BIBITEM_CODE) != 0
4115 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4116 || (d->layout_->labeltype != LABEL_BIBLIO
4117 && d->insetlist_.find(BIBITEM_CODE) != -1));
4121 int Paragraph::fixBiblio(Buffer const & buffer)
4123 // FIXME: when there was already an inset at 0, the return value is 1,
4124 // which does not tell whether another inset has been removed; the
4125 // cursor cannot be correctly updated.
4127 bool const track_changes = buffer.params().track_changes;
4128 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4130 // The case where paragraph is not BIBLIO
4131 if (d->layout_->labeltype != LABEL_BIBLIO) {
4132 if (bibitem_pos == -1)
4133 // No InsetBibitem => OK
4135 // There is an InsetBibitem: remove it!
4136 d->insetlist_.release(bibitem_pos);
4137 eraseChar(bibitem_pos, track_changes);
4138 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4141 bool const hasbibitem0 = bibitem_pos == 0;
4143 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4144 // There was an InsetBibitem at pos 0,
4145 // and no other one => OK
4146 if (bibitem_pos == -1)
4148 // there is a bibitem at the 0 position, but since
4149 // there is a second one, we copy the second on the
4150 // first. We're assuming there are at most two of
4151 // these, which there should be.
4152 // FIXME: why does it make sense to do that rather
4153 // than keep the first? (JMarc)
4154 Inset * inset = releaseInset(bibitem_pos);
4155 d->insetlist_.begin()->inset = inset;
4156 // This needs to be done to update the counter (#8499)
4157 buffer.updateBuffer();
4158 return -bibitem_pos;
4161 // We need to create an inset at the beginning
4162 Inset * inset = nullptr;
4163 if (bibitem_pos > 0) {
4164 // there was one somewhere in the paragraph, let's move it
4165 inset = d->insetlist_.release(bibitem_pos);
4166 eraseChar(bibitem_pos, track_changes);
4169 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4170 InsetCommandParams(BIBITEM_CODE));
4172 Font font(inherit_font, buffer.params().language);
4173 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4174 : Change::UNCHANGED));
4176 // This is needed to get the counters right
4177 buffer.updateBuffer();
4182 void Paragraph::checkAuthors(AuthorList const & authorList)
4184 d->changes_.checkAuthors(authorList);
4188 bool Paragraph::isChanged(pos_type pos) const
4190 return lookupChange(pos).changed();
4194 bool Paragraph::isInserted(pos_type pos) const
4196 return lookupChange(pos).inserted();
4200 bool Paragraph::isDeleted(pos_type pos) const
4202 return lookupChange(pos).deleted();
4206 InsetList const & Paragraph::insetList() const
4208 return d->insetlist_;
4212 void Paragraph::setInsetBuffers(Buffer & b)
4214 d->insetlist_.setBuffer(b);
4218 void Paragraph::resetBuffer()
4220 d->insetlist_.resetBuffer();
4224 Inset * Paragraph::releaseInset(pos_type pos)
4226 Inset * inset = d->insetlist_.release(pos);
4227 /// does not honour change tracking!
4228 eraseChar(pos, false);
4233 Inset * Paragraph::getInset(pos_type pos)
4235 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4236 ? d->insetlist_.get(pos) : nullptr;
4240 Inset const * Paragraph::getInset(pos_type pos) const
4242 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4243 ? d->insetlist_.get(pos) : nullptr;
4247 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4248 pos_type & right, TextCase action)
4250 // process sequences of modified characters; in change
4251 // tracking mode, this approach results in much better
4252 // usability than changing case on a char-by-char basis
4253 // We also need to track the current font, since font
4254 // changes within sequences can occur.
4255 vector<pair<char_type, Font> > changes;
4257 bool const trackChanges = bparams.track_changes;
4259 bool capitalize = true;
4261 for (; pos < right; ++pos) {
4262 char_type oldChar = d->text_[pos];
4263 char_type newChar = oldChar;
4265 // ignore insets and don't play with deleted text!
4266 if (oldChar != META_INSET && !isDeleted(pos)) {
4268 case text_lowercase:
4269 newChar = lowercase(oldChar);
4271 case text_capitalization:
4273 newChar = uppercase(oldChar);
4277 case text_uppercase:
4278 newChar = uppercase(oldChar);
4283 if (isWordSeparator(pos) || isDeleted(pos)) {
4284 // permit capitalization again
4288 if (oldChar != newChar) {
4289 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4290 if (pos != right - 1)
4292 // step behind the changing area
4296 int erasePos = pos - changes.size();
4297 for (size_t i = 0; i < changes.size(); i++) {
4298 insertChar(pos, changes[i].first,
4301 if (!eraseChar(erasePos, trackChanges)) {
4304 ++right; // expand selection
4312 int Paragraph::find(docstring const & str, bool cs, bool mw,
4313 pos_type start_pos, bool del) const
4315 pos_type pos = start_pos;
4316 int const strsize = str.length();
4318 pos_type const parsize = d->text_.size();
4319 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4320 // Ignore "invisible" letters such as ligature breaks
4321 // and hyphenation chars while searching
4322 while (pos < parsize - 1 && isInset(pos)) {
4323 Inset const * inset = getInset(pos);
4324 if (!inset->isLetter())
4326 odocstringstream os;
4327 inset->toString(os);
4328 if (!os.str().empty())
4332 if (cs && str[i] != d->text_[pos])
4334 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4336 if (!del && isDeleted(pos))
4343 // if necessary, check whether string matches word
4345 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4348 && !isWordSeparator(pos))
4352 return pos - start_pos;
4356 char_type Paragraph::getChar(pos_type pos) const
4358 return d->text_[pos];
4362 pos_type Paragraph::size() const
4364 return d->text_.size();
4368 bool Paragraph::empty() const
4370 return d->text_.empty();
4374 bool Paragraph::isInset(pos_type pos) const
4376 return d->text_[pos] == META_INSET;
4380 bool Paragraph::isSeparator(pos_type pos) const
4382 //FIXME: Are we sure this can be the only separator?
4383 return d->text_[pos] == ' ';
4387 void Paragraph::deregisterWords()
4389 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4390 Private::LangWordsMap::const_iterator ite = d->words_.end();
4391 for (; itl != ite; ++itl) {
4392 WordList & wl = theWordList(itl->first);
4393 Private::Words::const_iterator it = (itl->second).begin();
4394 Private::Words::const_iterator et = (itl->second).end();
4395 for (; it != et; ++it)
4402 void Paragraph::locateWord(pos_type & from, pos_type & to,
4403 word_location const loc, bool const ignore_deleted) const
4406 case WHOLE_WORD_STRICT:
4407 if (from == 0 || from == size()
4408 || isWordSeparator(from, ignore_deleted)
4409 || isWordSeparator(from - 1, ignore_deleted)) {
4416 // If we are already at the beginning of a word, do nothing
4417 if (!from || isWordSeparator(from - 1, ignore_deleted))
4422 // always move the cursor to the beginning of previous word
4423 while (from && !isWordSeparator(from - 1, ignore_deleted))
4427 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4430 // no need to move the 'from' cursor
4434 while (to < size() && !isWordSeparator(to, ignore_deleted))
4439 void Paragraph::collectWords()
4441 for (pos_type pos = 0; pos < size(); ++pos) {
4442 if (isWordSeparator(pos))
4444 pos_type from = pos;
4445 locateWord(from, pos, WHOLE_WORD);
4446 // Work around MSVC warning: The statement
4447 // if (pos < from + lyxrc.completion_minlength)
4448 // triggers a signed vs. unsigned warning.
4449 // I don't know why this happens, it could be a MSVC bug, or
4450 // related to LLP64 (windows) vs. LP64 (unix) programming
4451 // model, or the C++ standard might be ambigous in the section
4452 // defining the "usual arithmetic conversions". However, using
4453 // a temporary variable is safe and works on all compilers.
4454 pos_type const endpos = from + lyxrc.completion_minlength;
4457 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4458 if (cit == d->fontlist_.end())
4460 Language const * lang = cit->font().language();
4461 docstring const word = asString(from, pos, AS_STR_NONE);
4462 d->words_[lang->lang()].insert(word);
4467 void Paragraph::registerWords()
4469 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4470 Private::LangWordsMap::const_iterator ite = d->words_.end();
4471 for (; itl != ite; ++itl) {
4472 WordList & wl = theWordList(itl->first);
4473 Private::Words::const_iterator it = (itl->second).begin();
4474 Private::Words::const_iterator et = (itl->second).end();
4475 for (; it != et; ++it)
4481 void Paragraph::updateWords()
4489 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4491 SkipPositionsIterator begin = skips.begin();
4492 SkipPositions::iterator end = skips.end();
4493 if (pos > 0 && begin < end) {
4495 if (end->last == pos - 1) {
4500 skips.insert(end, FontSpan(pos, pos));
4504 Language * Paragraph::Private::locateSpellRange(
4505 pos_type & from, pos_type & to,
4506 SkipPositions & skips) const
4508 // skip leading white space
4509 while (from < to && owner_->isWordSeparator(from))
4511 // don't check empty range
4514 // get current language
4515 Language * lang = getSpellLanguage(from);
4516 pos_type last = from;
4517 bool samelang = true;
4518 bool sameinset = true;
4519 while (last < to && samelang && sameinset) {
4520 // hop to end of word
4521 while (last < to && !owner_->isWordSeparator(last)) {
4522 Inset const * inset = owner_->getInset(last);
4523 if (inset && inset->lyxCode() == SPECIALCHAR_CODE) {
4524 // check for "invisible" letters such as ligature breaks
4525 odocstringstream os;
4526 inset->toString(os);
4527 if (os.str().length() != 0) {
4528 // avoid spell check of visible special char insets
4529 // stop the loop in front of the special char inset
4534 appendSkipPosition(skips, last);
4535 } else if (owner_->isDeleted(last)) {
4536 appendSkipPosition(skips, last);
4540 // hop to next word while checking for insets
4541 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4542 if (Inset const * inset = owner_->getInset(last))
4543 sameinset = inset->isChar() && inset->isLetter();
4544 if (sameinset && owner_->isDeleted(last)) {
4545 appendSkipPosition(skips, last);
4550 if (sameinset && last < to) {
4551 // now check for language change
4552 samelang = lang == getSpellLanguage(last);
4555 // if language change detected backstep is needed
4563 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4566 const_cast<Language *>(owner_->getFontSettings(
4567 inset_owner_->buffer().params(), from).language());
4568 if (lang == inset_owner_->buffer().params().language
4569 && !lyxrc.spellchecker_alt_lang.empty()) {
4571 string const lang_variety =
4572 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4573 lang->setCode(lang_code);
4574 lang->setVariety(lang_variety);
4580 void Paragraph::requestSpellCheck(pos_type pos)
4582 d->requestSpellCheck(pos);
4586 bool Paragraph::needsSpellCheck() const
4588 SpellChecker::ChangeNumber speller_change_number = 0;
4589 if (theSpellChecker())
4590 speller_change_number = theSpellChecker()->changeNumber();
4591 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4592 d->speller_state_.needsCompleteRefresh(speller_change_number);
4594 return d->needsSpellCheck();
4598 bool Paragraph::Private::ignoreWord(docstring const & word) const
4600 // Ignore words with digits
4601 // FIXME: make this customizable
4602 // (note that some checkers ignore words with digits by default)
4603 docstring::const_iterator cit = word.begin();
4604 docstring::const_iterator const end = word.end();
4605 for (; cit != end; ++cit) {
4606 if (isNumber((*cit)))
4613 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4614 WordLangTuple & wl, docstring_list & suggestions,
4615 bool do_suggestion, bool check_learned) const
4617 SpellChecker::Result result = SpellChecker::WORD_OK;
4618 SpellChecker * speller = theSpellChecker();
4622 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4625 locateWord(from, to, WHOLE_WORD, true);
4626 if (from == to || from >= size())
4629 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4630 Language * lang = d->getSpellLanguage(from);
4632 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4635 wl = WordLangTuple(word, lang);
4640 if (needsSpellCheck() || check_learned) {
4642 if (!d->ignoreWord(word)) {
4643 bool const trailing_dot = to < size() && d->text_[to] == '.';
4644 result = speller->check(wl);
4645 if (SpellChecker::misspelled(result) && trailing_dot) {
4646 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4647 result = speller->check(wl);
4648 if (!SpellChecker::misspelled(result)) {
4649 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4651 from << ".." << to << "]");
4653 // spell check with dot appended failed too
4654 // restore original word/lang value
4655 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4656 wl = WordLangTuple(word, lang);
4660 if (!SpellChecker::misspelled(result)) {
4661 // area up to the begin of the next word is not misspelled
4662 while (end < size() && isWordSeparator(end))
4665 d->setMisspelled(from, end, result);
4667 result = d->speller_state_.getState(from);
4671 suggestions.clear();
4673 if (SpellChecker::misspelled(result)) {
4674 LYXERR(Debug::GUI, "misspelled word: \"" <<
4676 from << ".." << to << "]");
4678 speller->suggest(wl, suggestions);
4684 void Paragraph::anonymize()
4686 // This is a very crude anonymization for now
4687 for (char_type & c : d->text_)
4688 if (isLetterChar(c) || isNumber(c))
4693 void Paragraph::Private::markMisspelledWords(
4694 pos_type const & first, pos_type const & last,
4695 SpellChecker::Result result,
4696 docstring const & word,
4697 SkipPositions const & skips)
4699 if (!SpellChecker::misspelled(result)) {
4700 setMisspelled(first, last, SpellChecker::WORD_OK);
4704 SpellChecker * speller = theSpellChecker();
4705 // locate and enumerate the error positions
4706 int nerrors = speller->numMisspelledWords();
4708 SkipPositionsIterator it = skips.begin();
4709 SkipPositionsIterator et = skips.end();
4710 for (int index = 0; index < nerrors; ++index) {
4713 speller->misspelledWord(index, wstart, wlen);
4714 /// should not happen if speller supports range checks
4715 if (!wlen) continue;
4716 docstring const misspelled = word.substr(wstart, wlen);
4717 wstart += first + numskipped;
4718 if (snext < wstart) {
4719 /// mark the range of correct spelling
4720 numskipped += countSkips(it, et, wstart);
4721 setMisspelled(snext,
4722 wstart - 1, SpellChecker::WORD_OK);
4724 snext = wstart + wlen;
4725 numskipped += countSkips(it, et, snext);
4726 /// mark the range of misspelling
4727 setMisspelled(wstart, snext, result);
4728 LYXERR(Debug::GUI, "misspelled word: \"" <<
4729 misspelled << "\" [" <<
4730 wstart << ".." << (snext-1) << "]");
4733 if (snext <= last) {
4734 /// mark the range of correct spelling at end
4735 setMisspelled(snext, last, SpellChecker::WORD_OK);
4740 void Paragraph::spellCheck() const
4742 SpellChecker * speller = theSpellChecker();
4743 if (!speller || empty() ||!needsSpellCheck())
4747 d->rangeOfSpellCheck(start, endpos);
4748 if (speller->canCheckParagraph()) {
4749 // loop until we leave the range
4750 for (pos_type first = start; first < endpos; ) {
4751 pos_type last = endpos;
4752 Private::SkipPositions skips;
4753 Language * lang = d->locateSpellRange(first, last, skips);
4754 if (first >= endpos)
4756 // start the spell checker on the unit of meaning
4757 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4758 WordLangTuple wl = WordLangTuple(word, lang);
4759 SpellChecker::Result result = word.size() ?
4760 speller->check(wl) : SpellChecker::WORD_OK;
4761 d->markMisspelledWords(first, last, result, word, skips);
4765 static docstring_list suggestions;
4766 pos_type to = endpos;
4767 while (start < endpos) {
4769 spellCheck(start, to, wl, suggestions, false);
4773 d->readySpellCheck();
4777 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4779 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4780 if (result || pos <= 0 || pos > size())
4782 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4783 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4788 string Paragraph::magicLabel() const
4791 ss << "magicparlabel-" << id();