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"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.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/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
93 /////////////////////////////////////////////////////////////////////
97 /////////////////////////////////////////////////////////////////////
99 class SpellResultRange {
101 SpellResultRange(FontSpan range, SpellChecker::Result result)
102 : range_(range), result_(result)
105 FontSpan const & range() const { return range_; }
107 void range(FontSpan const & r) { range_ = r; }
109 SpellChecker::Result result() const { return result_; }
111 void result(SpellChecker::Result r) { result_ = r; }
113 bool contains(pos_type pos) const { return range_.contains(pos); }
115 bool covered(FontSpan const & r) const
117 // 1. first of new range inside current range or
118 // 2. last of new range inside current range or
119 // 3. first of current range inside new range or
120 // 4. last of current range inside new range
121 //FIXME: is this the same as !range_.intersect(r).empty() ?
122 return range_.contains(r.first) || range_.contains(r.last) ||
123 r.contains(range_.first) || r.contains(range_.last);
126 void shift(pos_type pos, int offset)
128 if (range_.first > pos) {
129 range_.first += offset;
130 range_.last += offset;
131 } else if (range_.last >= pos) {
132 range_.last += offset;
137 SpellChecker::Result result_ ;
141 /////////////////////////////////////////////////////////////////////
145 /////////////////////////////////////////////////////////////////////
147 class SpellCheckerState {
151 needs_refresh_ = true;
152 current_change_number_ = 0;
155 void setRange(FontSpan const & fp, SpellChecker::Result state)
158 RangesIterator et = ranges_.end();
159 RangesIterator it = ranges_.begin();
160 for (; it != et; ++it) {
161 if (!it->covered(fp))
162 result.push_back(SpellResultRange(it->range(), it->result()));
163 else if (state == SpellChecker::WORD_OK) {
164 // trim or split the current misspelled range
165 // store misspelled ranges only
166 FontSpan range = it->range();
167 if (fp.first > range.first) {
168 // misspelled area in front of WORD_OK
169 range.last = fp.first - 1;
170 result.push_back(SpellResultRange(range, it->result()));
173 if (fp.last < range.last) {
174 // misspelled area after WORD_OK range
175 range.first = fp.last + 1;
176 result.push_back(SpellResultRange(range, it->result()));
181 if (state != SpellChecker::WORD_OK)
182 ranges_.push_back(SpellResultRange(fp, state));
185 void increasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, 1);
191 void decreasePosAfterPos(pos_type pos)
193 correctRangesAfterPos(pos, -1);
197 void refreshLast(pos_type pos)
199 if (pos < refresh_.last)
203 SpellChecker::Result getState(pos_type pos) const
205 SpellChecker::Result result = SpellChecker::WORD_OK;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 FontSpan const & getRange(pos_type pos) const
218 /// empty span to indicate mismatch
219 static FontSpan empty_;
220 RangesIterator et = ranges_.end();
221 RangesIterator it = ranges_.begin();
222 for (; it != et; ++it) {
223 if(it->contains(pos)) {
230 bool needsRefresh() const
232 return needs_refresh_;
235 SpellChecker::ChangeNumber currentChangeNumber() const
237 return current_change_number_;
240 void refreshRange(pos_type & first, pos_type & last) const
242 first = refresh_.first;
243 last = refresh_.last;
246 void needsRefresh(pos_type pos)
248 if (needs_refresh_ && pos != -1) {
249 if (pos < refresh_.first)
250 refresh_.first = pos;
251 if (pos > refresh_.last)
253 } else if (pos != -1) {
254 // init request check for neighbour positions too
255 refresh_.first = pos > 0 ? pos - 1 : 0;
256 // no need for special end of paragraph check
257 refresh_.last = pos + 1;
259 needs_refresh_ = pos != -1;
262 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
264 needs_refresh_ = true;
267 current_change_number_ = change_number;
270 typedef vector<SpellResultRange> Ranges;
271 typedef Ranges::const_iterator RangesIterator;
273 /// the area of the paragraph with pending spell check
276 /// spell state cache version number
277 SpellChecker::ChangeNumber current_change_number_;
280 void correctRangesAfterPos(pos_type pos, int offset)
282 RangesIterator et = ranges_.end();
283 Ranges::iterator it = ranges_.begin();
284 for (; it != et; ++it) {
285 it->shift(pos, offset);
291 /////////////////////////////////////////////////////////////////////
293 // Paragraph::Private
295 /////////////////////////////////////////////////////////////////////
297 class Paragraph::Private
299 // Enforce our own "copy" constructor
300 Private(Private const &) = delete;
301 Private & operator=(Private const &) = delete;
302 // Unique ID generator
303 static int make_id();
306 Private(Paragraph * owner, Layout const & layout);
307 /// "Copy constructor"
308 Private(Private const &, Paragraph * owner);
309 /// Copy constructor from \p beg to \p end
310 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
313 void insertChar(pos_type pos, char_type c, Change const & change);
315 /// Output the surrogate pair formed by \p c and \p next to \p os.
316 /// \return the number of characters written.
317 int latexSurrogatePair(BufferParams const &, otexstream & os,
318 char_type c, char_type next,
319 OutputParams const &);
321 /// Output a space in appropriate formatting (or a surrogate pair
322 /// if the next character is a combining character).
323 /// \return whether a surrogate pair was output.
324 bool simpleTeXBlanks(BufferParams const &,
325 OutputParams const &,
328 unsigned int & column,
330 Layout const & style);
332 /// This could go to ParagraphParameters if we want to.
333 int startTeXParParams(BufferParams const &, otexstream &,
334 OutputParams const &) const;
336 /// This could go to ParagraphParameters if we want to.
337 bool endTeXParParams(BufferParams const &, otexstream &,
338 OutputParams const &) const;
341 void latexInset(BufferParams const &,
346 Font const & outerfont,
348 Change & running_change,
349 Layout const & style,
351 unsigned int & column);
354 void latexSpecialChar(
356 BufferParams const & bparams,
357 OutputParams const & runparams,
358 Font const & running_font,
359 string & alien_script,
360 Layout const & style,
363 unsigned int & column);
370 unsigned int & column);
376 unsigned int & column);
382 unsigned int & column);
385 void validate(LaTeXFeatures & features) const;
387 /// Checks if the paragraph contains only text and no inset or font change.
388 bool onlyText(Buffer const & buf, Font const & outerfont,
389 pos_type initial) const;
391 /// a vector of speller skip positions
392 typedef vector<FontSpan> SkipPositions;
393 typedef SkipPositions::const_iterator SkipPositionsIterator;
395 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
397 Language * getSpellLanguage(pos_type const from) const;
399 Language * locateSpellRange(pos_type & from, pos_type & to,
400 SkipPositions & skips) const;
402 bool hasSpellerChange() const
404 SpellChecker::ChangeNumber speller_change_number = 0;
405 if (theSpellChecker())
406 speller_change_number = theSpellChecker()->changeNumber();
407 return speller_change_number > speller_state_.currentChangeNumber();
410 bool ignoreWord(docstring const & word) const ;
412 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
414 pos_type textsize = owner_->size();
415 // check for sane arguments
416 if (to <= from || from >= textsize)
418 FontSpan fp = FontSpan(from, to - 1);
419 speller_state_.setRange(fp, state);
422 void requestSpellCheck(pos_type pos)
425 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
427 speller_state_.needsRefresh(pos);
430 void readySpellCheck()
432 speller_state_.needsRefresh(-1);
435 bool needsSpellCheck() const
437 return speller_state_.needsRefresh();
440 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
442 speller_state_.refreshRange(first, last);
444 last = owner_->size();
447 pos_type endpos = last;
448 owner_->locateWord(first, endpos, WHOLE_WORD, true);
451 owner_->locateWord(last, endpos, WHOLE_WORD, true);
456 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
460 while (it != et && it->first < start) {
461 int skip = it->last - it->first + 1;
469 void markMisspelledWords(pos_type const & first, pos_type const & last,
470 SpellChecker::Result result,
471 docstring const & word,
472 SkipPositions const & skips);
474 InsetCode ownerCode() const
476 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
479 /// Which Paragraph owns us?
483 Inset const * inset_owner_;
492 ParagraphParameters params_;
494 /// for recording and looking up changes
498 InsetList insetlist_;
501 pos_type begin_of_body_;
503 typedef docstring TextContainer;
507 typedef set<docstring> Words;
508 typedef map<string, Words> LangWordsMap;
512 Layout const * layout_;
514 SpellCheckerState speller_state_;
518 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
519 : owner_(owner), inset_owner_(nullptr), id_(-1), begin_of_body_(0), layout_(&layout)
526 int Paragraph::Private::make_id()
528 // The id is unique per session across buffers because it is used in
529 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
532 static atomic_uint next_id(0);
537 Paragraph::Private::Private(Private const & p, Paragraph * owner)
538 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
540 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
541 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
544 requestSpellCheck(p.text_.size());
548 Paragraph::Private::Private(Private const & p, Paragraph * owner,
549 pos_type beg, pos_type end)
550 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
551 params_(p.params_), changes_(p.changes_),
552 insetlist_(p.insetlist_, beg, end),
553 begin_of_body_(p.begin_of_body_), words_(p.words_),
556 if (beg >= pos_type(p.text_.size()))
558 text_ = p.text_.substr(beg, end - beg);
560 FontList::const_iterator fcit = fontlist_.begin();
561 FontList::const_iterator fend = fontlist_.end();
562 for (; fcit != fend; ++fcit) {
563 if (fcit->pos() < beg)
565 if (fcit->pos() >= end) {
566 // Add last entry in the fontlist_.
567 fontlist_.set(text_.size() - 1, fcit->font());
570 // Add a new entry in the fontlist_.
571 fontlist_.set(fcit->pos() - beg, fcit->font());
573 requestSpellCheck(p.text_.size());
577 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
578 bool output_active, TocBackend & backend) const
580 d->changes_.addToToc(cdit, buf, output_active, backend);
584 bool Paragraph::isDeleted(pos_type start, pos_type end) const
586 LASSERT(start >= 0 && start <= size(), return false);
587 LASSERT(end > start && end <= size() + 1, return false);
589 return d->changes_.isDeleted(start, end);
593 bool Paragraph::isChanged(pos_type start, pos_type end) const
595 LASSERT(start >= 0 && start <= size(), return false);
596 LASSERT(end > start && end <= size() + 1, return false);
598 return d->changes_.isChanged(start, end);
601 // FIXME: Ideally the diverse isChanged() methods should account for that!
602 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
604 LASSERT(start >= 0 && start <= size(), return false);
605 LASSERT(end > start && end <= size() + 1, return false);
607 for (auto const & icit : d->insetlist_) {
608 if (icit.pos < start)
612 if (icit.inset && icit.inset->isChanged())
618 bool Paragraph::isChanged() const
620 return d->changes_.isChanged();
624 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
626 // keep the logic here in sync with the logic of eraseChars()
630 Change const & change = d->changes_.lookup(size());
631 return change.inserted() && change.currentAuthor();
634 Change Paragraph::parEndChange() const
636 return d->changes_.lookup(size());
640 void Paragraph::setChange(Change const & change)
642 // beware of the imaginary end-of-par character!
643 d->changes_.set(change, 0, size() + 1);
646 * Propagate the change recursively - but not in case of DELETED!
648 * Imagine that your co-author makes changes in an existing inset. He
649 * sends your document to you and you come to the conclusion that the
650 * inset should go completely. If you erase it, LyX must not delete all
651 * text within the inset. Otherwise, the change tracked insertions of
652 * your co-author get lost and there is no way to restore them later.
654 * Conclusion: An inset's content should remain untouched if you delete it
657 if (!change.deleted()) {
658 for (pos_type pos = 0; pos < size(); ++pos) {
659 if (Inset * inset = getInset(pos))
660 inset->setChange(change);
666 void Paragraph::setChange(pos_type pos, Change const & change)
668 LASSERT(pos >= 0 && pos <= size(), return);
669 d->changes_.set(change, pos);
671 // see comment in setChange(Change const &) above
672 if (!change.deleted() && pos < size())
673 if (Inset * inset = getInset(pos))
674 inset->setChange(change);
678 Change const & Paragraph::lookupChange(pos_type pos) const
680 LBUFERR(pos >= 0 && pos <= size());
681 return d->changes_.lookup(pos);
685 void Paragraph::acceptChanges(pos_type start, pos_type end)
687 LASSERT(start >= 0 && start <= size(), return);
688 LASSERT(end > start && end <= size() + 1, return);
690 for (pos_type pos = start; pos < end; ++pos) {
691 switch (lookupChange(pos).type) {
692 case Change::UNCHANGED:
693 // accept changes in nested inset
694 if (Inset * inset = getInset(pos))
695 inset->acceptChanges();
698 case Change::INSERTED:
699 d->changes_.set(Change(Change::UNCHANGED), pos);
700 // also accept changes in nested inset
701 if (Inset * inset = getInset(pos))
702 inset->acceptChanges();
705 case Change::DELETED:
706 // Suppress access to non-existent
707 // "end-of-paragraph char"
709 eraseChar(pos, false);
720 void Paragraph::rejectChanges(pos_type start, pos_type end)
722 LASSERT(start >= 0 && start <= size(), return);
723 LASSERT(end > start && end <= size() + 1, return);
725 for (pos_type pos = start; pos < end; ++pos) {
726 switch (lookupChange(pos).type) {
727 case Change::UNCHANGED:
728 // reject changes in nested inset
729 if (Inset * inset = getInset(pos))
730 inset->rejectChanges();
733 case Change::INSERTED:
734 // Suppress access to non-existent
735 // "end-of-paragraph char"
737 eraseChar(pos, false);
743 case Change::DELETED:
744 d->changes_.set(Change(Change::UNCHANGED), pos);
746 // Do NOT reject changes within a deleted inset!
747 // There may be insertions of a co-author inside of it!
755 void Paragraph::Private::insertChar(pos_type pos, char_type c,
756 Change const & change)
758 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
761 changes_.insert(change, pos);
763 // This is actually very common when parsing buffers (and
764 // maybe inserting ascii text)
765 if (pos == pos_type(text_.size())) {
766 // when appending characters, no need to update tables
768 // but we want spell checking
769 requestSpellCheck(pos);
773 text_.insert(text_.begin() + pos, c);
775 // Update the font table.
776 fontlist_.increasePosAfterPos(pos);
779 insetlist_.increasePosAfterPos(pos);
781 // Update list of misspelled positions
782 speller_state_.increasePosAfterPos(pos);
786 bool Paragraph::insertInset(pos_type pos, Inset * inset,
787 Font const & font, Change const & change)
789 LASSERT(inset, return false);
790 LASSERT(pos >= 0 && pos <= size(), return false);
792 // Paragraph::insertInset() can be used in cut/copy/paste operation where
793 // d->inset_owner_ is not set yet.
794 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
797 d->insertChar(pos, META_INSET, change);
798 LASSERT(d->text_[pos] == META_INSET, return false);
800 // Add a new entry in the insetlist_.
801 d->insetlist_.insert(inset, pos);
803 // Some insets require run of spell checker
804 requestSpellCheck(pos);
810 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
812 LASSERT(pos >= 0 && pos <= size(), return false);
814 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
817 Change change = d->changes_.lookup(pos);
819 // set the character to DELETED if
820 // a) it was previously unchanged or
821 // b) it was inserted by a co-author
823 if (!change.changed() ||
824 (change.inserted() && !change.currentAuthor())) {
825 setChange(pos, Change(Change::DELETED));
826 // request run of spell checker
827 requestSpellCheck(pos);
831 if (change.deleted())
835 // Don't physically access the imaginary end-of-paragraph character.
836 // eraseChar() can only mark it as DELETED. A physical deletion of
837 // end-of-par must be handled externally.
843 d->changes_.erase(pos);
845 // if it is an inset, delete the inset entry
846 if (d->text_[pos] == META_INSET)
847 d->insetlist_.erase(pos);
849 d->text_.erase(d->text_.begin() + pos);
851 // Update the fontlist_
852 d->fontlist_.erase(pos);
854 // Update the insetlist_
855 d->insetlist_.decreasePosAfterPos(pos);
857 // Update list of misspelled positions
858 d->speller_state_.decreasePosAfterPos(pos);
859 d->speller_state_.refreshLast(size());
865 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
867 LASSERT(start >= 0 && start <= size(), return 0);
868 LASSERT(end >= start && end <= size() + 1, return 0);
871 for (pos_type count = end - start; count; --count) {
872 if (!eraseChar(i, trackChanges))
878 // Handle combining characters
879 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
880 otexstream & os, char_type c, char_type next,
881 OutputParams const & runparams)
883 // Writing next here may circumvent a possible font change between
884 // c and next. Since next is only output if it forms a surrogate pair
885 // with c we can ignore this:
886 // A font change inside a surrogate pair does not make sense and is
887 // hopefully impossible to input.
888 // FIXME: change tracking
889 // Is this correct WRT change tracking?
890 Encoding const & encoding = *(runparams.encoding);
891 docstring latex1 = encoding.latexChar(next).first;
892 if (runparams.inIPA) {
893 string const tipashortcut = Encodings::TIPAShortcut(next);
894 if (!tipashortcut.empty()) {
895 latex1 = from_ascii(tipashortcut);
898 docstring latex2 = encoding.latexChar(c).first;
900 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
901 // Encoding supports the combination:
902 // output as is (combining char after base char).
903 os << latex2 << latex1;
904 return latex1.length() + latex2.length();
907 os << latex1 << "{" << latex2 << "}";
908 return latex1.length() + latex2.length() + 2;
912 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
913 OutputParams const & runparams,
916 unsigned int & column,
918 Layout const & style)
920 if (style.pass_thru || runparams.pass_thru)
923 if (i + 1 < int(text_.size())) {
924 char_type next = text_[i + 1];
925 if (Encodings::isCombiningChar(next)) {
926 // This space has an accent, so we must always output it.
927 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
932 if (runparams.linelen > 0
933 && column > runparams.linelen
935 && text_[i - 1] != ' '
936 && (i + 1 < int(text_.size()))
937 // same in FreeSpacing mode
938 && !owner_->isFreeSpacing()
939 // In typewriter mode, we want to avoid
940 // ! . ? : at the end of a line
941 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
942 && (text_[i - 1] == '.'
943 || text_[i - 1] == '?'
944 || text_[i - 1] == ':'
945 || text_[i - 1] == '!'))) {
947 os.texrow().start(owner_->id(), i + 1);
949 } else if (style.free_spacing) {
958 void Paragraph::Private::latexInset(BufferParams const & bparams,
960 OutputParams & runparams,
963 Font const & outerfont,
965 Change & running_change,
966 Layout const & style,
968 unsigned int & column)
970 Inset * inset = owner_->getInset(i);
973 if (style.pass_thru) {
974 odocstringstream ods;
975 inset->plaintext(ods, runparams);
980 // FIXME: move this to InsetNewline::latex
981 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
982 // newlines are handled differently here than
983 // the default in simpleTeXSpecialChars().
984 if (!style.newline_allowed) {
988 bool needPar = false;
989 column += running_font.latexWriteEndChanges(
990 os, bparams, runparams,
991 basefont, basefont, needPar);
995 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
998 basefont = owner_->getLayoutFont(bparams, outerfont);
999 running_font = basefont;
1001 if (runparams.moving_arg)
1005 os.texrow().start(owner_->id(), i + 1);
1009 if (owner_->isDeleted(i)) {
1010 if( ++runparams.inDeletedInset == 1)
1011 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1014 if (inset->canTrackChanges()) {
1015 column += Changes::latexMarkChange(os, bparams, running_change,
1016 Change(Change::UNCHANGED), runparams);
1017 running_change = Change(Change::UNCHANGED);
1021 odocstream::pos_type const len = os.os().tellp();
1023 if (inset->forceLTR(runparams)
1024 && running_font.isRightToLeft()
1025 // ERT is an exception, it should be output with no
1026 // decorations at all
1027 && inset->lyxCode() != ERT_CODE) {
1028 if (runparams.use_polyglossia) {
1030 } else if (running_font.language()->lang() == "farsi"
1031 || running_font.language()->lang() == "arabic_arabi")
1032 os << "\\textLR{" << termcmd;
1038 // FIXME: Bug: we can have an empty font change here!
1039 // if there has just been a font change, we are going to close it
1040 // right now, which means stupid latex code like \textsf{}. AFAIK,
1041 // this does not harm dvi output. A minor bug, thus (JMarc)
1043 // Some insets cannot be inside a font change command.
1044 // However, even such insets *can* be placed in \L or \R
1045 // or their equivalents (for RTL language switches), so we don't
1046 // close the language in those cases.
1047 // ArabTeX, though, cannot handle this special behavior, it seems.
1048 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1049 || running_font.language()->lang() == "arabic_arabtex";
1050 if (open_font && !inset->inheritFont()) {
1051 bool needPar = false;
1052 bool closeLanguage = arabtex
1053 || basefont.isRightToLeft() == running_font.isRightToLeft();
1054 unsigned int count = running_font.latexWriteEndChanges(os,
1055 bparams, runparams, basefont, basefont,
1056 needPar, closeLanguage);
1058 // if any font properties were closed, update the running_font,
1059 // making sure, however, to leave the language as it was
1061 // FIXME: probably a better way to keep track of the old
1062 // language, than copying the entire font?
1063 Font const copy_font(running_font);
1064 basefont = owner_->getLayoutFont(bparams, outerfont);
1065 running_font = basefont;
1067 running_font.setLanguage(copy_font.language());
1068 // leave font open if language is still open
1069 open_font = (running_font.language() == basefont.language());
1071 runparams.local_font = &basefont;
1075 size_t const previous_row_count = os.texrow().rows();
1078 runparams.lastid = id_;
1079 runparams.lastpos = i;
1080 inset->latex(os, runparams);
1081 } catch (EncodingException & e) {
1082 // add location information and throw again.
1091 if (os.texrow().rows() > previous_row_count) {
1092 os.texrow().start(owner_->id(), i + 1);
1095 column += (unsigned int)(os.os().tellp() - len);
1098 if (owner_->isDeleted(i))
1099 --runparams.inDeletedInset;
1103 void Paragraph::Private::latexSpecialChar(otexstream & os,
1104 BufferParams const & bparams,
1105 OutputParams const & runparams,
1106 Font const & running_font,
1107 string & alien_script,
1108 Layout const & style,
1111 unsigned int & column)
1113 char_type const c = owner_->getUChar(bparams, runparams, i);
1115 if (style.pass_thru || runparams.pass_thru
1116 || contains(style.pass_thru_chars, c)
1117 || contains(runparams.pass_thru_chars, c)) {
1119 Encoding const * const enc = runparams.encoding;
1120 if (enc && !enc->encodable(c))
1121 throw EncodingException(c);
1127 // TIPA uses its own T3 encoding
1128 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1130 // If T1 font encoding is used, use the special
1131 // characters it provides.
1132 // NOTE: Some languages reset the font encoding internally to a
1133 // non-standard font encoding. If we are using such a language,
1134 // we do not output special T1 chars.
1135 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1136 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1137 && latexSpecialT1(c, os, i, column))
1139 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1140 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1141 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1144 // Otherwise, we use what LaTeX provides us.
1147 os << "\\textbackslash" << termcmd;
1151 os << "\\textless" << termcmd;
1155 os << "\\textgreater" << termcmd;
1159 os << "\\textbar" << termcmd;
1164 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1165 (end_pos == -1 || i + 1 < end_pos) &&
1166 text_[i+1] == '-') {
1167 // Prevent "--" becoming an en dash and "---" an em dash.
1168 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1174 os << "\\textquotedbl" << termcmd;
1179 case '%': case '#': case '{':
1187 os << "\\textasciitilde" << termcmd;
1192 os << "\\textasciicircum" << termcmd;
1199 // avoid being mistaken for optional arguments
1207 // Blanks are printed before font switching.
1208 // Sure? I am not! (try nice-latex)
1209 // I am sure it's correct. LyX might be smarter
1210 // in the future, but for now, nothing wrong is
1216 // XeTeX's dash behaviour is determined via a global setting
1217 if (bparams.use_dash_ligatures
1218 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1220 // TODO #10961: && not in inset Flex Code
1221 // TODO #10961: && not in layout LyXCode
1222 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1239 Encoding const & encoding = *(runparams.encoding);
1240 char_type next = '\0';
1241 if (i + 1 < int(text_.size())) {
1242 next = text_[i + 1];
1243 if (Encodings::isCombiningChar(next)) {
1244 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1249 pair<docstring, bool> latex = encoding.latexChar(c);
1250 docstring nextlatex;
1251 bool nexttipas = false;
1252 string nexttipashortcut;
1253 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1254 nextlatex = encoding.latexChar(next).first;
1255 if (runparams.inIPA) {
1256 nexttipashortcut = Encodings::TIPAShortcut(next);
1257 nexttipas = !nexttipashortcut.empty();
1261 if (runparams.inIPA) {
1262 string const tipashortcut = Encodings::TIPAShortcut(c);
1263 if (!tipashortcut.empty()) {
1264 latex.first = from_ascii(tipashortcut);
1265 latex.second = false;
1269 // eventually close "script wrapper" command (see `Paragraph::latex`)
1270 if (!alien_script.empty()
1271 && alien_script != Encodings::isKnownScriptChar(next)) {
1272 column += latex.first.length();
1273 alien_script.clear();
1274 os << latex.first << "}";
1278 && ((!prefixIs(nextlatex, '\\')
1279 && !prefixIs(nextlatex, '{')
1280 && !prefixIs(nextlatex, '}'))
1282 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1284 // Prevent eating of a following space or command corruption by
1285 // following characters
1286 if (next == ' ' || next == '\0') {
1287 column += latex.first.length() + 1;
1288 os << latex.first << "{}";
1290 column += latex.first.length();
1291 os << latex.first << " ";
1294 column += latex.first.length() - 1;
1302 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1303 pos_type i, unsigned int & column)
1309 // In T1 encoding, these characters exist
1310 // but we should avoid ligatures
1311 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1313 os << "\\textcompwordmark" << termcmd;
1320 // soul.sty breaks with \char`\"
1321 os << "\\textquotedbl" << termcmd;
1330 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1331 pos_type i, unsigned int & column)
1333 // TU encoding is currently on par with T1.
1334 return latexSpecialT1(c, os, i, column);
1338 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1339 pos_type /*i*/, unsigned int & column)
1349 os << "\\textvertline" << termcmd;
1358 void Paragraph::Private::validate(LaTeXFeatures & features) const
1360 if (layout_->inpreamble && inset_owner_) {
1361 // FIXME: Using a string stream here circumvents the encoding
1362 // switching machinery of odocstream. Therefore the
1363 // output is wrong if this paragraph contains content
1364 // that needs to switch encoding.
1365 Buffer const & buf = inset_owner_->buffer();
1366 otexstringstream os;
1367 os << layout_->preamble();
1368 size_t const length = os.length();
1369 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1370 buf.getParFromID(owner_->id()).pit(), os,
1371 features.runparams(), string(), 0, -1, true);
1372 if (os.length() > length)
1373 features.addPreambleSnippet(os.release(), true);
1376 if (features.runparams().flavor == OutputParams::HTML
1377 && layout_->htmltitle()) {
1378 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1381 // check the params.
1382 if (!params_.spacing().isDefault())
1383 features.require("setspace");
1386 features.useLayout(layout_->name());
1389 fontlist_.validate(features);
1391 // then the indentation
1392 if (!params_.leftIndent().zero())
1393 features.require("ParagraphLeftIndent");
1396 InsetList::const_iterator icit = insetlist_.begin();
1397 InsetList::const_iterator iend = insetlist_.end();
1398 for (; icit != iend; ++icit) {
1400 features.inDeletedInset(owner_->isDeleted(icit->pos));
1401 if (icit->inset->lyxCode() == FOOT_CODE) {
1402 // FIXME: an item inset would make things much easier.
1403 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1404 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1405 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1406 && (icit->pos < begin_of_body_
1407 || (icit->pos == begin_of_body_
1408 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1409 features.saveNoteEnv("description");
1411 icit->inset->validate(features);
1412 features.inDeletedInset(false);
1413 if (layout_->needprotect &&
1414 icit->inset->lyxCode() == FOOT_CODE)
1415 features.require("NeedLyXFootnoteCode");
1419 // then the contents
1420 BufferParams const bp = features.runparams().is_child
1421 ? features.buffer().masterParams() : features.buffer().params();
1422 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1423 char_type c = text_[i];
1424 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1426 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1427 features.require("textquotedblp");
1428 else if (bp.main_font_encoding() != "T1"
1429 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1430 features.require("textquotedbl");
1431 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1432 // features that depend on the font or input encoding
1433 string feats = ci.textpreamble();
1434 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1435 if (fontenc.empty())
1436 fontenc = features.runparams().main_fontenc;
1437 while (!feats.empty()) {
1439 feats = split(feats, feat, ',');
1440 if (contains(feat, "!=")) {
1441 // a feature that is required except for the spcified
1442 // font or input encodings
1444 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1445 // multiple encodings are separated by semicolon
1446 vector<string> context = getVectorFromString(contexts, ";");
1447 // require feature if the context matches neither current font
1448 // nor input encoding
1449 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1450 && std::find(context.begin(), context.end(),
1451 features.runparams().encoding->name()) == context.end())
1452 features.require(realfeature);
1453 } else if (contains(feat, '=')) {
1454 // a feature that is required only for the spcified
1455 // font or input encodings
1457 string const contexts = split(feat, realfeature, '=');
1458 // multiple encodings are separated by semicolon
1459 vector<string> context = getVectorFromString(contexts, ";");
1460 // require feature if the context matches either current font
1461 // or input encoding
1462 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1463 || std::find(context.begin(), context.end(),
1464 features.runparams().encoding->name()) != context.end())
1465 features.require(realfeature);
1468 } else if (!bp.use_dash_ligatures
1469 && (c == 0x2013 || c == 0x2014)
1470 && bp.useNonTeXFonts
1471 && features.runparams().flavor == OutputParams::XETEX)
1472 // XeTeX's dash behaviour is determined via a global setting
1473 features.require("xetexdashbreakstate");
1474 BufferEncodings::validate(c, features);
1478 /////////////////////////////////////////////////////////////////////
1482 /////////////////////////////////////////////////////////////////////
1485 Layout const emptyParagraphLayout;
1488 Paragraph::Paragraph()
1489 : d(new Paragraph::Private(this, emptyParagraphLayout))
1496 Paragraph::Paragraph(Paragraph const & par)
1497 : itemdepth(par.itemdepth),
1498 d(new Paragraph::Private(*par.d, this))
1504 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1505 : itemdepth(par.itemdepth),
1506 d(new Paragraph::Private(*par.d, this, beg, end))
1512 Paragraph & Paragraph::operator=(Paragraph const & par)
1514 // needed as we will destroy the private part before copying it
1516 itemdepth = par.itemdepth;
1520 d = new Private(*par.d, this);
1527 Paragraph::~Paragraph()
1536 // this shall be called just before every "os << ..." action.
1537 void flushString(ostream & os, docstring & s)
1546 void Paragraph::write(ostream & os, BufferParams const & bparams,
1547 depth_type & dth) const
1549 // The beginning or end of a deeper (i.e. nested) area?
1550 if (dth != d->params_.depth()) {
1551 if (d->params_.depth() > dth) {
1552 while (d->params_.depth() > dth) {
1553 os << "\n\\begin_deeper";
1557 while (d->params_.depth() < dth) {
1558 os << "\n\\end_deeper";
1564 // First write the layout
1565 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1567 d->params_.write(os);
1569 Font font1(inherit_font, bparams.language);
1571 Change running_change = Change(Change::UNCHANGED);
1573 // this string is used as a buffer to avoid repetitive calls
1574 // to to_utf8(), which turn out to be expensive (JMarc)
1575 docstring write_buffer;
1578 for (pos_type i = 0; i <= size(); ++i) {
1580 Change const & change = lookupChange(i);
1581 if (change != running_change)
1582 flushString(os, write_buffer);
1583 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1584 running_change = change;
1589 // Write font changes
1590 Font font2 = getFontSettings(bparams, i);
1591 if (font2 != font1) {
1592 flushString(os, write_buffer);
1593 font2.lyxWriteChanges(font1, os);
1598 char_type const c = d->text_[i];
1601 if (Inset const * inset = getInset(i)) {
1602 flushString(os, write_buffer);
1603 if (inset->directWrite()) {
1604 // international char, let it write
1605 // code directly so it's shorter in
1611 os << "\\begin_inset ";
1613 os << "\n\\end_inset\n\n";
1616 // FIXME This can be removed again once the mystery
1617 // crash has been resolved.
1622 flushString(os, write_buffer);
1623 os << "\n\\backslash\n";
1627 flushString(os, write_buffer);
1628 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1635 if ((column > 70 && c == ' ')
1637 flushString(os, write_buffer);
1641 // this check is to amend a bug. LyX sometimes
1642 // inserts '\0' this could cause problems.
1644 write_buffer.push_back(c);
1646 LYXERR0("NUL char in structure.");
1652 flushString(os, write_buffer);
1653 os << "\n\\end_layout\n";
1654 // FIXME This can be removed again once the mystery
1655 // crash has been resolved.
1660 void Paragraph::validate(LaTeXFeatures & features) const
1662 d->validate(features);
1663 bool fragile = features.runparams().moving_arg;
1664 fragile |= layout().needprotect;
1665 if (inInset().getLayout().isNeedProtect())
1667 if (needsCProtection(fragile))
1668 features.require("cprotect");
1672 void Paragraph::insert(pos_type start, docstring const & str,
1673 Font const & font, Change const & change)
1675 for (size_t i = 0, n = str.size(); i != n ; ++i)
1676 insertChar(start + i, str[i], font, change);
1680 void Paragraph::appendChar(char_type c, Font const & font,
1681 Change const & change)
1684 d->changes_.insert(change, d->text_.size());
1685 // when appending characters, no need to update tables
1686 d->text_.push_back(c);
1687 setFont(d->text_.size() - 1, font);
1688 d->requestSpellCheck(d->text_.size() - 1);
1692 void Paragraph::appendString(docstring const & s, Font const & font,
1693 Change const & change)
1695 pos_type end = s.size();
1696 size_t oldsize = d->text_.size();
1697 size_t newsize = oldsize + end;
1698 size_t capacity = d->text_.capacity();
1699 if (newsize >= capacity)
1700 d->text_.reserve(max(capacity + 100, newsize));
1702 // when appending characters, no need to update tables
1705 // FIXME: Optimize this!
1706 for (size_t i = oldsize; i != newsize; ++i) {
1708 d->changes_.insert(change, i);
1709 d->requestSpellCheck(i);
1711 d->fontlist_.set(oldsize, font);
1712 d->fontlist_.set(newsize - 1, font);
1716 void Paragraph::insertChar(pos_type pos, char_type c,
1719 d->insertChar(pos, c, Change(trackChanges ?
1720 Change::INSERTED : Change::UNCHANGED));
1724 void Paragraph::insertChar(pos_type pos, char_type c,
1725 Font const & font, bool trackChanges)
1727 d->insertChar(pos, c, Change(trackChanges ?
1728 Change::INSERTED : Change::UNCHANGED));
1733 void Paragraph::insertChar(pos_type pos, char_type c,
1734 Font const & font, Change const & change)
1736 d->insertChar(pos, c, change);
1741 void Paragraph::resetFonts(Font const & font)
1743 d->fontlist_.clear();
1744 d->fontlist_.set(0, font);
1745 d->fontlist_.set(d->text_.size() - 1, font);
1748 // Gets uninstantiated font setting at position.
1749 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1753 LYXERR0("pos: " << pos << " size: " << size());
1757 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1758 if (cit != d->fontlist_.end())
1761 if (pos == size() && !empty())
1762 return getFontSettings(bparams, pos - 1);
1764 // Optimisation: avoid a full font instantiation if there is no
1765 // language change from previous call.
1766 static Font previous_font;
1767 static Language const * previous_lang = nullptr;
1768 Language const * lang = getParLanguage(bparams);
1769 if (lang != previous_lang) {
1770 previous_lang = lang;
1771 previous_font = Font(inherit_font, lang);
1773 return previous_font;
1777 FontSpan Paragraph::fontSpan(pos_type pos) const
1779 LBUFERR(pos <= size());
1782 return FontSpan(pos, pos);
1785 FontList::const_iterator cit = d->fontlist_.begin();
1786 FontList::const_iterator end = d->fontlist_.end();
1787 for (; cit != end; ++cit) {
1788 if (cit->pos() >= pos) {
1789 if (pos >= beginOfBody())
1790 return FontSpan(max(start, beginOfBody()),
1793 return FontSpan(start,
1794 min(beginOfBody() - 1,
1797 start = cit->pos() + 1;
1800 // This should not happen, but if so, we take no chances.
1801 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1802 LASSERT(false, return FontSpan(pos, pos));
1806 // Gets uninstantiated font setting at position 0
1807 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1809 if (!empty() && !d->fontlist_.empty())
1810 return d->fontlist_.begin()->font();
1812 // Optimisation: avoid a full font instantiation if there is no
1813 // language change from previous call.
1814 static Font previous_font;
1815 static Language const * previous_lang = nullptr;
1816 if (bparams.language != previous_lang) {
1817 previous_lang = bparams.language;
1818 previous_font = Font(inherit_font, bparams.language);
1821 return previous_font;
1825 // Gets the fully instantiated font at a given position in a paragraph
1826 // This is basically the same function as Text::GetFont() in text2.cpp.
1827 // The difference is that this one is used for generating the LaTeX file,
1828 // and thus cosmetic "improvements" are disallowed: This has to deliver
1829 // the true picture of the buffer. (Asger)
1830 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1831 Font const & outerfont) const
1835 Font font = getFontSettings(bparams, pos);
1837 pos_type const body_pos = beginOfBody();
1838 FontInfo & fi = font.fontInfo();
1840 fi.realize(d->layout_->labelfont);
1842 fi.realize(d->layout_->font);
1844 fi.realize(outerfont.fontInfo());
1845 fi.realize(bparams.getFont().fontInfo());
1851 Font const Paragraph::getLabelFont
1852 (BufferParams const & bparams, Font const & outerfont) const
1854 FontInfo tmpfont = d->layout_->labelfont;
1855 tmpfont.realize(outerfont.fontInfo());
1856 tmpfont.realize(bparams.getFont().fontInfo());
1857 return Font(tmpfont, getParLanguage(bparams));
1861 Font const Paragraph::getLayoutFont
1862 (BufferParams const & bparams, Font const & outerfont) const
1864 FontInfo tmpfont = d->layout_->font;
1865 tmpfont.realize(outerfont.fontInfo());
1866 tmpfont.realize(bparams.getFont().fontInfo());
1867 return Font(tmpfont, getParLanguage(bparams));
1871 char_type Paragraph::getUChar(BufferParams const & bparams,
1872 OutputParams const & rp,
1875 char_type c = d->text_[pos];
1877 // Return unchanged character in LTR languages
1878 // or if we use poylglossia/bidi (XeTeX).
1879 if (rp.useBidiPackage()
1880 || !getFontSettings(bparams, pos).isRightToLeft())
1883 // Without polyglossia/bidi, we need to account for some special cases.
1884 // FIXME This needs to be audited!
1886 // * The input is as expected for all delimiters
1887 // => checked for Hebrew!
1888 // * The output matches the display in the LyX workarea
1889 // => checked for Hebrew!
1890 // * The special cases below are really necessary
1891 // => checked for Hebrew!
1892 // * In arabic_arabi, brackets are transformed to Arabic
1893 // Ornate Parentheses. Is this is really wanted?
1895 string const & lang = getFontSettings(bparams, pos).language()->lang();
1898 // 1. In the following languages, parentheses need to be reversed.
1899 // Also with polyglodia/luabidi
1900 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
1902 // 2. In the following languages, brackets don't need to be reversed.
1903 bool const reversebrackets = lang != "arabic_arabtex"
1904 && lang != "arabic_arabi"
1907 // Now swap delimiters if needed.
1918 if (reversebrackets)
1922 if (reversebrackets)
1943 void Paragraph::setFont(pos_type pos, Font const & font)
1945 LASSERT(pos <= size(), return);
1947 // First, reduce font against layout/label font
1948 // Update: The setCharFont() routine in text2.cpp already
1949 // reduces font, so we don't need to do that here. (Asger)
1951 d->fontlist_.set(pos, font);
1955 void Paragraph::makeSameLayout(Paragraph const & par)
1957 d->layout_ = par.d->layout_;
1958 d->params_ = par.d->params_;
1962 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1964 if (isFreeSpacing())
1970 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1971 if (eraseChar(pos, trackChanges))
1977 return count > 0 || pos > 0;
1981 bool Paragraph::hasSameLayout(Paragraph const & par) const
1983 return par.d->layout_ == d->layout_
1984 && d->params_.sameLayout(par.d->params_);
1988 depth_type Paragraph::getDepth() const
1990 return d->params_.depth();
1994 depth_type Paragraph::getMaxDepthAfter() const
1996 if (d->layout_->isEnvironment())
1997 return d->params_.depth() + 1;
1999 return d->params_.depth();
2003 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2005 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2006 return getDefaultAlign(bparams);
2008 return d->params_.align();
2012 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2014 LyXAlignment res = layout().align;
2015 if (isRTL(bparams)) {
2017 if (res == LYX_ALIGN_LEFT)
2018 res = LYX_ALIGN_RIGHT;
2019 else if (res == LYX_ALIGN_RIGHT)
2020 res = LYX_ALIGN_LEFT;
2026 docstring const & Paragraph::labelString() const
2028 return d->params_.labelString();
2032 // the next two functions are for the manual labels
2033 docstring const Paragraph::getLabelWidthString() const
2035 if (d->layout_->margintype == MARGIN_MANUAL
2036 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2037 return d->params_.labelWidthString();
2039 return _("Senseless with this layout!");
2043 void Paragraph::setLabelWidthString(docstring const & s)
2045 d->params_.labelWidthString(s);
2049 docstring Paragraph::expandLabel(Layout const & layout,
2050 BufferParams const & bparams) const
2052 return expandParagraphLabel(layout, bparams, true);
2056 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2057 BufferParams const & bparams) const
2059 return expandParagraphLabel(layout, bparams, false);
2063 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2064 BufferParams const & bparams, bool process_appendix) const
2066 DocumentClass const & tclass = bparams.documentClass();
2067 string const & lang = getParLanguage(bparams)->code();
2068 bool const in_appendix = process_appendix && d->params_.appendix();
2069 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2071 if (fmt.empty() && !layout.counter.empty())
2072 return tclass.counters().theCounter(layout.counter, lang);
2074 // handle 'inherited level parts' in 'fmt',
2075 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2076 size_t const i = fmt.find('@', 0);
2077 if (i != docstring::npos) {
2078 size_t const j = fmt.find('@', i + 1);
2079 if (j != docstring::npos) {
2080 docstring parent(fmt, i + 1, j - i - 1);
2081 docstring label = from_ascii("??");
2082 if (tclass.hasLayout(parent))
2083 label = expandParagraphLabel(tclass[parent], bparams,
2085 fmt = docstring(fmt, 0, i) + label
2086 + docstring(fmt, j + 1, docstring::npos);
2090 return tclass.counters().counterLabel(fmt, lang);
2094 void Paragraph::applyLayout(Layout const & new_layout)
2096 d->layout_ = &new_layout;
2097 LyXAlignment const oldAlign = d->params_.align();
2099 if (!(oldAlign & d->layout_->alignpossible)) {
2100 frontend::Alert::warning(_("Alignment not permitted"),
2101 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2102 d->params_.align(LYX_ALIGN_LAYOUT);
2107 pos_type Paragraph::beginOfBody() const
2109 return d->begin_of_body_;
2113 void Paragraph::setBeginOfBody()
2115 if (d->layout_->labeltype != LABEL_MANUAL) {
2116 d->begin_of_body_ = 0;
2120 // Unroll the first two cycles of the loop
2121 // and remember the previous character to
2122 // remove unnecessary getChar() calls
2124 pos_type end = size();
2125 bool prev_char_deleted = false;
2126 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2129 char_type previous_char = d->text_[i];
2130 if (!(isNewline(i) || isEnvSeparator(i))) {
2132 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2133 char_type temp = d->text_[i];
2134 prev_char_deleted = isDeleted(i);
2135 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2138 previous_char = temp;
2144 d->begin_of_body_ = i;
2148 bool Paragraph::allowParagraphCustomization() const
2150 return inInset().allowParagraphCustomization();
2154 bool Paragraph::usePlainLayout() const
2156 return inInset().usePlainLayout();
2160 bool Paragraph::isPassThru() const
2162 return inInset().isPassThru() || d->layout_->pass_thru;
2167 // paragraphs inside floats need different alignment tags to avoid
2170 bool noTrivlistCentering(InsetCode code)
2172 return code == FLOAT_CODE
2173 || code == WRAP_CODE
2174 || code == CELL_CODE;
2178 string correction(string const & orig)
2180 if (orig == "flushleft")
2181 return "raggedright";
2182 if (orig == "flushright")
2183 return "raggedleft";
2184 if (orig == "center")
2190 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2191 InsetCode code, bool const lastpar, int & col)
2193 string macro = suffix + "{";
2194 if (noTrivlistCentering(code)) {
2196 // the last paragraph in non-trivlist-aligned
2197 // context is special (to avoid unwanted whitespace)
2198 if (suffix == "\\begin") {
2199 macro = "\\" + correction(env) + "{}";
2200 os << from_ascii(macro);
2201 col += macro.size();
2206 macro += correction(env);
2210 if (suffix == "\\par\\end") {
2214 os << from_ascii(macro);
2215 col += macro.size();
2216 if (suffix == "\\begin") {
2226 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2227 otexstream & os, OutputParams const & runparams) const
2232 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2233 (layout_->toggle_indent != ITOGGLE_NEVER) :
2234 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2236 if (canindent && params_.noindent() && !layout_->pass_thru) {
2237 os << "\\noindent ";
2241 LyXAlignment const curAlign = params_.align();
2243 if (curAlign == layout_->align)
2247 case LYX_ALIGN_NONE:
2248 case LYX_ALIGN_BLOCK:
2249 case LYX_ALIGN_LAYOUT:
2250 case LYX_ALIGN_SPECIAL:
2251 case LYX_ALIGN_DECIMAL:
2253 case LYX_ALIGN_LEFT:
2254 case LYX_ALIGN_RIGHT:
2255 case LYX_ALIGN_CENTER:
2256 if (runparams.moving_arg) {
2263 string const begin_tag = "\\begin";
2264 InsetCode code = ownerCode();
2265 bool const lastpar = runparams.isLastPar;
2266 // RTL in classic (PDF)LaTeX (without the Bidi package)
2267 // Luabibdi (used by LuaTeX) behaves like classic
2268 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2269 && !runparams.useBidiPackage();
2272 case LYX_ALIGN_NONE:
2273 case LYX_ALIGN_BLOCK:
2274 case LYX_ALIGN_LAYOUT:
2275 case LYX_ALIGN_SPECIAL:
2276 case LYX_ALIGN_DECIMAL:
2278 case LYX_ALIGN_LEFT: {
2280 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2281 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2283 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2285 } case LYX_ALIGN_RIGHT: {
2287 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2288 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2290 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2292 } case LYX_ALIGN_CENTER: {
2293 corrected_env(os, begin_tag, "center", code, lastpar, column);
2302 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2303 otexstream & os, OutputParams const & runparams) const
2305 LyXAlignment const curAlign = params_.align();
2307 if (curAlign == layout_->align)
2311 case LYX_ALIGN_NONE:
2312 case LYX_ALIGN_BLOCK:
2313 case LYX_ALIGN_LAYOUT:
2314 case LYX_ALIGN_SPECIAL:
2315 case LYX_ALIGN_DECIMAL:
2317 case LYX_ALIGN_LEFT:
2318 case LYX_ALIGN_RIGHT:
2319 case LYX_ALIGN_CENTER:
2320 if (runparams.moving_arg)
2325 bool output = false;
2327 string const end_tag = "\\par\\end";
2328 InsetCode code = ownerCode();
2329 bool const lastpar = runparams.isLastPar;
2330 // RTL in classic (PDF)LaTeX (without the Bidi package)
2331 // Luabibdi (used by LuaTeX) behaves like classic
2332 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2333 && !runparams.useBidiPackage();
2336 case LYX_ALIGN_NONE:
2337 case LYX_ALIGN_BLOCK:
2338 case LYX_ALIGN_LAYOUT:
2339 case LYX_ALIGN_SPECIAL:
2340 case LYX_ALIGN_DECIMAL:
2342 case LYX_ALIGN_LEFT: {
2344 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2345 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2347 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2349 } case LYX_ALIGN_RIGHT: {
2351 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2352 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2354 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2356 } case LYX_ALIGN_CENTER: {
2357 corrected_env(os, end_tag, "center", code, lastpar, col);
2362 return output || lastpar;
2366 // This one spits out the text of the paragraph
2367 void Paragraph::latex(BufferParams const & bparams,
2368 Font const & outerfont,
2370 OutputParams const & runparams,
2371 int start_pos, int end_pos, bool force) const
2373 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2375 // FIXME This check should not be needed. Perhaps issue an
2376 // error if it triggers.
2377 Layout const & style = inInset().forcePlainLayout() ?
2378 bparams.documentClass().plainLayout() : *d->layout_;
2380 if (!force && style.inpreamble)
2383 bool const allowcust = allowParagraphCustomization();
2385 // Current base font for all inherited font changes, without any
2386 // change caused by an individual character, except for the language:
2387 // It is set to the language of the first character.
2388 // As long as we are in the label, this font is the base font of the
2389 // label. Before the first body character it is set to the base font
2393 // If there is an open font-encoding changing command (script wrapper),
2394 // alien_script is set to its name
2395 string alien_script;
2398 // Maybe we have to create a optional argument.
2399 pos_type body_pos = beginOfBody();
2400 unsigned int column = 0;
2403 // the optional argument is kept in curly brackets in
2404 // case it contains a ']'
2405 // This is not strictly needed, but if this is changed it
2406 // would be a file format change, and tex2lyx would need
2407 // to be adjusted, since it unconditionally removes the
2408 // braces when it parses \item.
2411 basefont = getLabelFont(bparams, outerfont);
2413 basefont = getLayoutFont(bparams, outerfont);
2416 // Which font is currently active?
2417 Font running_font(basefont);
2418 // Do we have an open font change?
2419 bool open_font = false;
2421 Change runningChange = Change(Change::UNCHANGED);
2423 Encoding const * const prev_encoding = runparams.encoding;
2425 os.texrow().start(id(), 0);
2427 // if the paragraph is empty, the loop will not be entered at all
2429 // For InTitle commands, we have already opened a group
2430 // in output_latex::TeXOnePar.
2431 if (style.isCommand() && !style.intitle) {
2435 if (!style.leftdelim().empty()) {
2436 os << style.leftdelim();
2437 column += style.leftdelim().size();
2440 column += d->startTeXParParams(bparams, os, runparams);
2443 // Whether a \par can be issued for insets typeset inline with text.
2444 // Yes if greater than 0. This has to be static.
2445 THREAD_LOCAL_STATIC int parInline = 0;
2447 for (pos_type i = 0; i < size(); ++i) {
2448 // First char in paragraph or after label?
2449 if (i == body_pos) {
2452 bool needPar = false;
2453 column += running_font.latexWriteEndChanges(
2454 os, bparams, runparams,
2455 basefont, basefont, needPar);
2458 basefont = getLayoutFont(bparams, outerfont);
2459 running_font = basefont;
2461 column += Changes::latexMarkChange(os, bparams,
2462 runningChange, Change(Change::UNCHANGED),
2464 runningChange = Change(Change::UNCHANGED);
2469 // For InTitle commands, we have already opened a group
2470 // in output_latex::TeXOnePar.
2471 if (style.isCommand() && !style.intitle) {
2476 if (!style.leftdelim().empty()) {
2477 os << style.leftdelim();
2478 column += style.leftdelim().size();
2482 column += d->startTeXParParams(bparams, os,
2486 runparams.wasDisplayMath = runparams.inDisplayMath;
2487 runparams.inDisplayMath = false;
2488 bool deleted_display_math = false;
2489 Change const & change = runparams.inDeletedInset
2490 ? runparams.changeOfDeletedInset : lookupChange(i);
2492 char_type const c = d->text_[i];
2494 // Check whether a display math inset follows
2496 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2498 runparams.ctObject = getInset(i)->CtObject(runparams);
2500 InsetMath const * im = getInset(i)->asInsetMath();
2501 if (im && im->asHullInset()
2502 && im->asHullInset()->outerDisplay()) {
2503 runparams.inDisplayMath = true;
2504 // runparams.inDeletedInset will be set by
2505 // latexInset later, but we need this info
2506 // before it is called. On the other hand, we
2507 // cannot set it here because it is a counter.
2508 deleted_display_math = isDeleted(i);
2510 if (bparams.output_changes && deleted_display_math
2511 && runningChange == change
2512 && change.type == Change::DELETED
2513 && !os.afterParbreak()) {
2514 // A display math in the same paragraph follows.
2515 // We have to close and then reopen \lyxdeleted,
2516 // otherwise the math will be shifted up.
2517 OutputParams rp = runparams;
2519 bool needPar = false;
2520 column += running_font.latexWriteEndChanges(
2521 os, bparams, rp, basefont,
2525 basefont = (body_pos > i) ? getLabelFont(bparams, outerfont)
2526 : getLayoutFont(bparams, outerfont);
2527 running_font = basefont;
2528 column += Changes::latexMarkChange(os, bparams,
2529 Change(Change::INSERTED), change, rp);
2533 if (bparams.output_changes && runningChange != change) {
2534 if (!alien_script.empty()) {
2537 alien_script.clear();
2540 bool needPar = false;
2541 column += running_font.latexWriteEndChanges(
2542 os, bparams, runparams,
2543 basefont, basefont, needPar);
2546 basefont = (body_pos > i) ? getLabelFont(bparams, outerfont)
2547 : getLayoutFont(bparams, outerfont);
2548 running_font = basefont;
2549 column += Changes::latexMarkChange(os, bparams, runningChange,
2551 runningChange = change;
2554 // do not output text which is marked deleted
2555 // if change tracking output is disabled
2556 if (!bparams.output_changes && change.deleted()) {
2562 // Fully instantiated font
2563 Font const current_font = getFont(bparams, i, outerfont);
2565 Font const last_font = running_font;
2566 bool const in_ct_deletion = (bparams.output_changes
2567 && runningChange == change
2568 && change.type == Change::DELETED
2569 && !os.afterParbreak());
2571 // Do we need to close the previous font?
2573 (current_font != running_font ||
2574 current_font.language() != running_font.language()))
2576 // ensure there is no open script-wrapper
2577 if (!alien_script.empty()) {
2580 alien_script.clear();
2582 bool needPar = false;
2583 if (in_ct_deletion) {
2584 // We have to close and then reopen \lyxdeleted,
2585 // as strikeout needs to be on lowest level.
2589 column += running_font.latexWriteEndChanges(
2590 os, bparams, runparams, basefont,
2591 (i == body_pos-1) ? basefont : current_font,
2593 if (in_ct_deletion) {
2594 // We have to close and then reopen \lyxdeleted,
2595 // as strikeout needs to be on lowest level.
2596 OutputParams rp = runparams;
2597 column += Changes::latexMarkChange(os, bparams,
2598 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2600 running_font = basefont;
2604 // if necessary, close language environment before opening CJK
2605 string const running_lang = running_font.language()->babel();
2606 string const lang_end_command = lyxrc.language_command_end;
2607 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2608 && !running_lang.empty()
2609 && running_lang == openLanguageName()
2610 && current_font.language()->encoding()->package() == Encoding::CJK) {
2611 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2612 os << from_ascii(end_tag);
2613 column += end_tag.length();
2617 // Switch file encoding if necessary (and allowed)
2618 if (!runparams.pass_thru && !style.pass_thru &&
2619 runparams.encoding->package() != Encoding::none &&
2620 current_font.language()->encoding()->package() != Encoding::none) {
2621 pair<bool, int> const enc_switch =
2622 switchEncoding(os.os(), bparams, runparams,
2623 *(current_font.language()->encoding()));
2624 if (enc_switch.first) {
2625 column += enc_switch.second;
2626 runparams.encoding = current_font.language()->encoding();
2630 // A display math inset inside an ulem command will be output
2631 // as a box of width \linewidth, so we have to either disable
2632 // indentation if the inset starts a paragraph, or start a new
2633 // line to accommodate such box. This has to be done before
2634 // writing any font changing commands.
2635 if (runparams.inDisplayMath && !deleted_display_math
2636 && runparams.inulemcmd) {
2637 if (os.afterParbreak())
2643 // Do we need to change font?
2644 if ((current_font != running_font ||
2645 current_font.language() != running_font.language())
2646 && i != body_pos - 1)
2648 if (in_ct_deletion) {
2649 // We have to close and then reopen \lyxdeleted,
2650 // as strikeout needs to be on lowest level.
2651 bool needPar = false;
2652 OutputParams rp = runparams;
2653 column += running_font.latexWriteEndChanges(
2654 os, bparams, rp, basefont,
2659 odocstringstream ods;
2660 column += current_font.latexWriteStartChanges(ods, bparams,
2661 runparams, basefont,
2663 // Check again for display math in ulem commands as a
2664 // font change may also occur just before a math inset.
2665 if (runparams.inDisplayMath && !deleted_display_math
2666 && runparams.inulemcmd) {
2667 if (os.afterParbreak())
2672 running_font = current_font;
2674 docstring fontchange = ods.str();
2675 // check whether the fontchange ends with a \\textcolor
2676 // modifier and the text starts with a space (bug 4473)
2677 docstring const last_modifier = rsplit(fontchange, '\\');
2678 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2679 os << fontchange << from_ascii("{}");
2680 // check if the fontchange ends with a trailing blank
2681 // (like "\small " (see bug 3382)
2682 else if (suffixIs(fontchange, ' ') && c == ' ')
2683 os << fontchange.substr(0, fontchange.size() - 1)
2684 << from_ascii("{}");
2687 if (in_ct_deletion) {
2688 // We have to close and then reopen \lyxdeleted,
2689 // as strikeout needs to be on lowest level.
2690 OutputParams rp = runparams;
2691 column += Changes::latexMarkChange(os, bparams,
2692 Change(Change::UNCHANGED), change, rp);
2696 // FIXME: think about end_pos implementation...
2697 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2698 // FIXME: integrate this case in latexSpecialChar
2699 // Do not print the separation of the optional argument
2700 // if style.pass_thru is false. This works because
2701 // latexSpecialChar ignores spaces if
2702 // style.pass_thru is false.
2703 if (i != body_pos - 1) {
2704 if (d->simpleTeXBlanks(bparams, runparams, os,
2705 i, column, current_font, style)) {
2706 // A surrogate pair was output. We
2707 // must not call latexSpecialChar
2708 // in this iteration, since it would output
2709 // the combining character again.
2716 OutputParams rp = runparams;
2717 rp.free_spacing = style.free_spacing;
2718 rp.local_font = ¤t_font;
2719 rp.intitle = style.intitle;
2721 // Two major modes: LaTeX or plain
2722 // Handle here those cases common to both modes
2723 // and then split to handle the two modes separately.
2724 if (c == META_INSET) {
2725 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2726 // Greyedout notes and, in general, all insets
2727 // with InsetLayout::isDisplay() == false,
2728 // are typeset inline with the text. So, we
2729 // can add a \par to the last paragraph of
2730 // such insets only if nothing else follows.
2731 bool incremented = false;
2732 Inset const * inset = getInset(i);
2733 InsetText const * textinset = inset
2734 ? inset->asInsetText()
2736 if (i + 1 == size() && textinset
2737 && !inset->getLayout().isDisplay()) {
2738 ParagraphList const & pars =
2739 textinset->text().paragraphs();
2740 pit_type const pit = pars.size() - 1;
2741 Font const lastfont =
2742 pit < 0 || pars[pit].empty()
2743 ? pars[pit].getLayoutFont(
2746 : pars[pit].getFont(bparams,
2747 pars[pit].size() - 1,
2749 if (lastfont.fontInfo().size() !=
2750 basefont.fontInfo().size()) {
2755 d->latexInset(bparams, os, rp, running_font,
2756 basefont, outerfont, open_font,
2757 runningChange, style, i, column);
2761 if (runparams.ctObject == OutputParams::CT_DISPLAYOBJECT
2762 || runparams.ctObject == OutputParams::CT_UDISPLAYOBJECT) {
2763 // Close \lyx*deleted and force its
2764 // reopening (if needed)
2767 runningChange = Change(Change::UNCHANGED);
2768 runparams.ctObject = OutputParams::CT_NORMAL;
2771 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2772 if (!bparams.useNonTeXFonts)
2773 script = Encodings::isKnownScriptChar(c);
2774 if (script != alien_script) {
2775 if (!alien_script.empty()) {
2777 alien_script.clear();
2779 string fontenc = running_font.language()->fontenc(bparams);
2781 && !Encodings::fontencSupportsScript(fontenc, script)) {
2782 column += script.length() + 2;
2783 os << "\\" << script << "{";
2784 alien_script = script;
2788 d->latexSpecialChar(os, bparams, rp, running_font,
2789 alien_script, style, i, end_pos, column);
2790 } catch (EncodingException & e) {
2791 if (runparams.dryrun) {
2792 os << "<" << _("LyX Warning: ")
2793 << _("uncodable character") << " '";
2797 // add location information and throw again.
2805 // Set the encoding to that returned from latexSpecialChar (see
2806 // comment for encoding member in OutputParams.h)
2807 runparams.encoding = rp.encoding;
2809 // Also carry on the info on a closed ulem command for insets
2810 // such as Note that do not produce any output, so that no
2811 // command is ever executed but its opening was recorded.
2812 runparams.inulemcmd = rp.inulemcmd;
2814 // And finally, pass the post_macros upstream
2815 runparams.post_macro = rp.post_macro;
2818 // Close wrapper for alien script
2819 if (!alien_script.empty()) {
2821 alien_script.clear();
2824 // If we have an open font definition, we have to close it
2826 // Make sure that \\par is done with the font of the last
2827 // character if this has another size as the default.
2828 // This is necessary because LaTeX (and LyX on the screen)
2829 // calculates the space between the baselines according
2830 // to this font. (Matthias)
2832 // We must not change the font for the last paragraph
2833 // of non-multipar insets, tabular cells or commands,
2834 // since this produces unwanted whitespace.
2836 Font const font = empty()
2837 ? getLayoutFont(bparams, outerfont)
2838 : getFont(bparams, size() - 1, outerfont);
2840 InsetText const * textinset = inInset().asInsetText();
2842 bool const maintext = textinset
2843 ? textinset->text().isMainText()
2846 size_t const numpars = textinset
2847 ? textinset->text().paragraphs().size()
2850 bool needPar = false;
2852 if (style.resfont.size() != font.fontInfo().size()
2853 && (!runparams.isLastPar || maintext
2854 || (numpars > 1 && d->ownerCode() != CELL_CODE
2855 && (inInset().getLayout().isDisplay()
2857 && !style.isCommand()) {
2860 #ifdef FIXED_LANGUAGE_END_DETECTION
2862 running_font.latexWriteEndChanges(os, bparams,
2863 runparams, basefont,
2864 next_->getFont(bparams, 0, outerfont),
2867 running_font.latexWriteEndChanges(os, bparams,
2868 runparams, basefont, basefont, needPar);
2871 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2872 //FIXME: there as we start another \selectlanguage with the next paragraph if
2873 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2874 running_font.latexWriteEndChanges(os, bparams, runparams,
2875 basefont, basefont, needPar);
2878 // The \par could not be inserted at the same nesting
2879 // level of the font size change, so do it now.
2880 os << "{\\" << font.latexSize() << "\\par}";
2884 column += Changes::latexMarkChange(os, bparams, runningChange,
2885 Change(Change::UNCHANGED), runparams);
2887 // Needed if there is an optional argument but no contents.
2888 if (body_pos > 0 && body_pos == size()) {
2892 if (!style.rightdelim().empty()) {
2893 os << style.rightdelim();
2894 column += style.rightdelim().size();
2897 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2898 && runparams.encoding != prev_encoding) {
2899 runparams.encoding = prev_encoding;
2900 os << setEncoding(prev_encoding->iconvName());
2903 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2907 bool Paragraph::emptyTag() const
2909 for (pos_type i = 0; i < size(); ++i) {
2910 if (Inset const * inset = getInset(i)) {
2911 InsetCode lyx_code = inset->lyxCode();
2912 // FIXME testing like that is wrong. What is
2914 if (lyx_code != TOC_CODE &&
2915 lyx_code != INCLUDE_CODE &&
2916 lyx_code != GRAPHICS_CODE &&
2917 lyx_code != ERT_CODE &&
2918 lyx_code != LISTINGS_CODE &&
2919 lyx_code != FLOAT_CODE &&
2920 lyx_code != TABULAR_CODE) {
2924 char_type c = d->text_[i];
2925 if (c != ' ' && c != '\t')
2933 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2936 for (pos_type i = 0; i < size(); ++i) {
2937 if (Inset const * inset = getInset(i)) {
2938 InsetCode lyx_code = inset->lyxCode();
2939 if (lyx_code == LABEL_CODE) {
2940 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2941 docstring const & id = il->getParam("name");
2942 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2950 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2954 for (i = 0; i < size(); ++i) {
2955 if (Inset const * inset = getInset(i)) {
2956 inset->docbook(os, runparams);
2958 char_type c = d->text_[i];
2961 os << sgml::escapeChar(c);
2968 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2972 for (i = 0; i < size(); ++i) {
2973 if (Inset const * inset = getInset(i)) {
2974 inset->xhtml(xs, runparams);
2976 char_type c = d->text_[i];
2986 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2989 pos_type size = text_.size();
2990 for (pos_type i = initial; i < size; ++i) {
2991 Font font = owner_->getFont(buf.params(), i, outerfont);
2992 if (text_[i] == META_INSET)
2994 if (i != initial && font != font_old)
3003 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3005 OutputParams const & runparams,
3006 Font const & outerfont,
3007 pos_type initial) const
3009 bool emph_flag = false;
3011 Layout const & style = *d->layout_;
3013 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3015 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3018 // parsing main loop
3019 for (pos_type i = initial; i < size(); ++i) {
3020 Font font = getFont(buf.params(), i, outerfont);
3022 // handle <emphasis> tag
3023 if (font_old.emph() != font.fontInfo().emph()) {
3024 if (font.fontInfo().emph() == FONT_ON) {
3027 } else if (i != initial) {
3028 os << "</emphasis>";
3033 if (Inset const * inset = getInset(i)) {
3034 inset->docbook(os, runparams);
3036 char_type c = d->text_[i];
3038 if (style.pass_thru)
3041 os << sgml::escapeChar(c);
3043 font_old = font.fontInfo();
3047 os << "</emphasis>";
3050 if (style.free_spacing)
3052 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3058 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
3059 vector<html::EndFontTag> & tagsToClose,
3060 bool & flag, FontState curstate, html::FontTypes type)
3062 if (curstate == FONT_ON) {
3063 tagsToOpen.push_back(html::FontTag(type));
3066 tagsToClose.push_back(html::EndFontTag(type));
3073 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3075 OutputParams const & runparams,
3076 Font const & outerfont,
3077 bool start_paragraph, bool close_paragraph,
3078 pos_type initial) const
3082 // track whether we have opened these tags
3083 bool emph_flag = false;
3084 bool bold_flag = false;
3085 bool noun_flag = false;
3086 bool ubar_flag = false;
3087 bool dbar_flag = false;
3088 bool sout_flag = false;
3089 bool xout_flag = false;
3090 bool wave_flag = false;
3092 bool shap_flag = false;
3094 bool faml_flag = false;
3096 bool size_flag = false;
3098 Layout const & style = *d->layout_;
3100 if (start_paragraph)
3101 xs.startDivision(allowEmpty());
3104 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3106 FontShape curr_fs = INHERIT_SHAPE;
3107 FontFamily curr_fam = INHERIT_FAMILY;
3108 FontSize curr_size = INHERIT_SIZE;
3110 string const default_family =
3111 buf.masterBuffer()->params().fonts_default_family;
3113 vector<html::FontTag> tagsToOpen;
3114 vector<html::EndFontTag> tagsToClose;
3116 // parsing main loop
3117 for (pos_type i = initial; i < size(); ++i) {
3118 // let's not show deleted material in the output
3122 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3125 FontState curstate = font.fontInfo().emph();
3126 if (font_old.emph() != curstate)
3127 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3130 curstate = font.fontInfo().noun();
3131 if (font_old.noun() != curstate)
3132 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3135 curstate = font.fontInfo().underbar();
3136 if (font_old.underbar() != curstate)
3137 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3140 curstate = font.fontInfo().strikeout();
3141 if (font_old.strikeout() != curstate)
3142 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3145 curstate = font.fontInfo().xout();
3146 if (font_old.xout() != curstate)
3147 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3150 curstate = font.fontInfo().uuline();
3151 if (font_old.uuline() != curstate)
3152 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3155 curstate = font.fontInfo().uwave();
3156 if (font_old.uwave() != curstate)
3157 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3160 // a little hackish, but allows us to reuse what we have.
3161 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3162 if (font_old.series() != font.fontInfo().series())
3163 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3166 curr_fs = font.fontInfo().shape();
3167 FontShape old_fs = font_old.shape();
3168 if (old_fs != curr_fs) {
3172 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3175 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3177 case SMALLCAPS_SHAPE:
3178 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3184 // the other tags are for internal use
3192 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3196 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3199 case SMALLCAPS_SHAPE:
3200 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3207 // the other tags are for internal use
3214 curr_fam = font.fontInfo().family();
3215 FontFamily old_fam = font_old.family();
3216 if (old_fam != curr_fam) {
3220 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3223 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3225 case TYPEWRITER_FAMILY:
3226 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3228 case INHERIT_FAMILY:
3231 // the other tags are for internal use
3239 // we will treat a "default" font family as roman, since we have
3240 // no other idea what to do.
3241 if (default_family != "rmdefault" && default_family != "default") {
3242 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3247 if (default_family != "sfdefault") {
3248 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3252 case TYPEWRITER_FAMILY:
3253 if (default_family != "ttdefault") {
3254 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3258 case INHERIT_FAMILY:
3261 // the other tags are for internal use
3268 curr_size = font.fontInfo().size();
3269 FontSize old_size = font_old.size();
3270 if (old_size != curr_size) {
3274 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3277 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3280 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3283 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3286 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3289 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3292 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3295 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3298 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3301 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3304 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3310 // the other tags are for internal use
3316 switch (curr_size) {
3318 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3322 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3326 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3330 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3334 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3338 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3342 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3346 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3350 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3354 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3358 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3365 // the other tags are for internal use
3372 // Other such tags? What about the other text ranges?
3374 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3375 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3376 for (; cit != cen; ++cit)
3379 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3380 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3381 for (; sit != sen; ++sit)
3384 tagsToClose.clear();
3387 Inset const * inset = getInset(i);
3389 if (!runparams.for_toc || inset->isInToc()) {
3390 OutputParams np = runparams;
3391 np.local_font = &font;
3392 // If the paragraph has size 1, then we are in the "special
3393 // case" where we do not output the containing paragraph info
3394 if (!inset->getLayout().htmlisblock() && size() != 1)
3395 np.html_in_par = true;
3396 retval += inset->xhtml(xs, np);
3399 char_type c = getUChar(buf.masterBuffer()->params(),
3401 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3402 xs << XHTMLStream::ESCAPE_NONE << " ";
3406 font_old = font.fontInfo();
3410 // I'm worried about what happens if a branch, say, is itself
3411 // wrapped in some font stuff. I think that will not work.
3413 if (close_paragraph)
3420 bool Paragraph::isHfill(pos_type pos) const
3422 Inset const * inset = getInset(pos);
3423 return inset && inset->isHfill();
3427 bool Paragraph::isNewline(pos_type pos) const
3429 // U+2028 LINE SEPARATOR
3430 // U+2029 PARAGRAPH SEPARATOR
3431 char_type const c = d->text_[pos];
3432 if (c == 0x2028 || c == 0x2029)
3434 Inset const * inset = getInset(pos);
3435 return inset && inset->lyxCode() == NEWLINE_CODE;
3439 bool Paragraph::isEnvSeparator(pos_type pos) const
3441 Inset const * inset = getInset(pos);
3442 return inset && inset->lyxCode() == SEPARATOR_CODE;
3446 bool Paragraph::isLineSeparator(pos_type pos) const
3448 char_type const c = d->text_[pos];
3449 if (isLineSeparatorChar(c))
3451 Inset const * inset = getInset(pos);
3452 return inset && inset->isLineSeparator();
3456 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
3460 if (ignore_deleted && isDeleted(pos))
3462 if (Inset const * inset = getInset(pos))
3463 return !inset->isLetter();
3464 // if we have a hard hyphen (no en- or emdash) or apostrophe
3465 // we pass this to the spell checker
3466 // FIXME: this method is subject to change, visit
3467 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3468 // to get an impression how complex this is.
3469 if (isHardHyphenOrApostrophe(pos))
3471 char_type const c = d->text_[pos];
3472 // We want to pass the escape chars to the spellchecker
3473 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3474 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3478 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3480 pos_type const psize = size();
3483 char_type const c = d->text_[pos];
3484 if (c != '-' && c != '\'')
3486 int nextpos = pos + 1;
3487 int prevpos = pos > 0 ? pos - 1 : 0;
3488 if ((nextpos == psize || isSpace(nextpos))
3489 && (pos == 0 || isSpace(prevpos)))
3495 bool Paragraph::needsCProtection(bool const fragile) const
3497 // first check the layout of the paragraph, but only in insets
3498 InsetText const * textinset = inInset().asInsetText();
3499 bool const maintext = textinset
3500 ? textinset->text().isMainText()
3503 if (!maintext && layout().needcprotect) {
3504 // Environments need cprotection regardless the content
3505 if (layout().latextype == LATEX_ENVIRONMENT)
3508 // Commands need cprotection if they contain specific chars
3509 int const nchars_escape = 9;
3510 static char_type const chars_escape[nchars_escape] = {
3511 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3513 docstring const pars = asString();
3514 for (int k = 0; k < nchars_escape; k++) {
3515 if (contains(pars, chars_escape[k]))
3520 // now check whether we have insets that need cprotection
3521 pos_type size = pos_type(d->text_.size());
3522 for (pos_type i = 0; i < size; ++i) {
3525 Inset const * ins = getInset(i);
3526 if (ins->needsCProtection(maintext, fragile))
3528 if (ins->getLayout().latextype() == InsetLayout::ENVIRONMENT)
3529 // Environments need cprotection regardless the content
3531 // Now check math environments
3532 InsetMath const * im = getInset(i)->asInsetMath();
3533 if (!im || im->cell(0).empty())
3535 switch(im->cell(0)[0]->lyxCode()) {
3536 case MATH_AMSARRAY_CODE:
3537 case MATH_SUBSTACK_CODE:
3539 case MATH_XYMATRIX_CODE:
3540 // these need cprotection
3551 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3553 return d->speller_state_.getRange(pos);
3557 bool Paragraph::isChar(pos_type pos) const
3559 if (Inset const * inset = getInset(pos))
3560 return inset->isChar();
3561 char_type const c = d->text_[pos];
3562 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3566 bool Paragraph::isSpace(pos_type pos) const
3568 if (Inset const * inset = getInset(pos))
3569 return inset->isSpace();
3570 char_type const c = d->text_[pos];
3571 return lyx::isSpace(c);
3576 Paragraph::getParLanguage(BufferParams const & bparams) const
3579 return getFirstFontSettings(bparams).language();
3580 // FIXME: we should check the prev par as well (Lgb)
3581 return bparams.language;
3585 bool Paragraph::isRTL(BufferParams const & bparams) const
3587 return getParLanguage(bparams)->rightToLeft()
3588 && !inInset().getLayout().forceLTR();
3592 void Paragraph::changeLanguage(BufferParams const & bparams,
3593 Language const * from, Language const * to)
3595 // change language including dummy font change at the end
3596 for (pos_type i = 0; i <= size(); ++i) {
3597 Font font = getFontSettings(bparams, i);
3598 if (font.language() == from) {
3599 font.setLanguage(to);
3601 d->requestSpellCheck(i);
3607 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3609 Language const * doc_language = bparams.language;
3610 for (auto const & f : d->fontlist_)
3611 if (f.font().language() != ignore_language &&
3612 f.font().language() != latex_language &&
3613 f.font().language() != doc_language)
3619 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3621 for (auto const & f : d->fontlist_) {
3622 Language const * lang = f.font().language();
3623 if (lang != ignore_language &&
3624 lang != latex_language)
3630 docstring Paragraph::asString(int options) const
3632 return asString(0, size(), options);
3636 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3638 odocstringstream os;
3641 && options & AS_STR_LABEL
3642 && !d->params_.labelString().empty())
3643 os << d->params_.labelString() << ' ';
3645 for (pos_type i = beg; i < end; ++i) {
3646 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3648 char_type const c = d->text_[i];
3649 if (isPrintable(c) || c == '\t'
3650 || (c == '\n' && (options & AS_STR_NEWLINES)))
3652 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3653 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3654 LASSERT(runparams != nullptr, return docstring());
3655 getInset(i)->plaintext(os, *runparams);
3657 getInset(i)->toString(os);
3666 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3667 bool const shorten, bool const label) const
3669 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3670 if (label && !labelString().empty())
3671 os += labelString() + ' ';
3672 if (!layout().isTocCaption())
3674 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3677 char_type const c = d->text_[i];
3680 else if (c == META_INSET)
3681 getInset(i)->forOutliner(os, tmplen, false);
3684 Text::shortenForOutliner(os, maxlen);
3688 void Paragraph::setInsetOwner(Inset const * inset)
3690 d->inset_owner_ = inset;
3694 int Paragraph::id() const
3700 void Paragraph::setId(int id)
3706 Layout const & Paragraph::layout() const
3712 void Paragraph::setLayout(Layout const & layout)
3714 d->layout_ = &layout;
3718 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3720 setLayout(tc.defaultLayout());
3724 void Paragraph::setPlainLayout(DocumentClass const & tc)
3726 setLayout(tc.plainLayout());
3730 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3732 if (usePlainLayout())
3733 setPlainLayout(tclass);
3735 setDefaultLayout(tclass);
3739 Inset const & Paragraph::inInset() const
3741 LBUFERR(d->inset_owner_);
3742 return *d->inset_owner_;
3746 ParagraphParameters & Paragraph::params()
3752 ParagraphParameters const & Paragraph::params() const
3758 bool Paragraph::isFreeSpacing() const
3760 if (d->layout_->free_spacing)
3762 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3766 bool Paragraph::allowEmpty() const
3768 if (d->layout_->keepempty)
3770 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3774 bool Paragraph::brokenBiblio() const
3776 // There is a problem if there is no bibitem at position 0 in
3777 // paragraphs that need one, if there is another bibitem in the
3778 // paragraph or if this paragraph is not supposed to have
3779 // a bibitem inset at all.
3780 return ((d->layout_->labeltype == LABEL_BIBLIO
3781 && (d->insetlist_.find(BIBITEM_CODE) != 0
3782 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
3783 || (d->layout_->labeltype != LABEL_BIBLIO
3784 && d->insetlist_.find(BIBITEM_CODE) != -1));
3788 int Paragraph::fixBiblio(Buffer const & buffer)
3790 // FIXME: when there was already an inset at 0, the return value is 1,
3791 // which does not tell whether another inset has been remove; the
3792 // cursor cannot be correctly updated.
3794 bool const track_changes = buffer.params().track_changes;
3795 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3797 // The case where paragraph is not BIBLIO
3798 if (d->layout_->labeltype != LABEL_BIBLIO) {
3799 if (bibitem_pos == -1)
3800 // No InsetBibitem => OK
3802 // There is an InsetBibitem: remove it!
3803 d->insetlist_.release(bibitem_pos);
3804 eraseChar(bibitem_pos, track_changes);
3805 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
3808 bool const hasbibitem0 = bibitem_pos == 0;
3810 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3811 // There was an InsetBibitem at pos 0,
3812 // and no other one => OK
3813 if (bibitem_pos == -1)
3815 // there is a bibitem at the 0 position, but since
3816 // there is a second one, we copy the second on the
3817 // first. We're assuming there are at most two of
3818 // these, which there should be.
3819 // FIXME: why does it make sense to do that rather
3820 // than keep the first? (JMarc)
3821 Inset * inset = releaseInset(bibitem_pos);
3822 d->insetlist_.begin()->inset = inset;
3823 return -bibitem_pos;
3826 // We need to create an inset at the beginning
3827 Inset * inset = nullptr;
3828 if (bibitem_pos > 0) {
3829 // there was one somewhere in the paragraph, let's move it
3830 inset = d->insetlist_.release(bibitem_pos);
3831 eraseChar(bibitem_pos, track_changes);
3834 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3835 InsetCommandParams(BIBITEM_CODE));
3837 Font font(inherit_font, buffer.params().language);
3838 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3839 : Change::UNCHANGED));
3841 // This is needed to get the counters right
3842 buffer.updateBuffer();
3847 void Paragraph::checkAuthors(AuthorList const & authorList)
3849 d->changes_.checkAuthors(authorList);
3853 bool Paragraph::isChanged(pos_type pos) const
3855 return lookupChange(pos).changed();
3859 bool Paragraph::isInserted(pos_type pos) const
3861 return lookupChange(pos).inserted();
3865 bool Paragraph::isDeleted(pos_type pos) const
3867 return lookupChange(pos).deleted();
3871 InsetList const & Paragraph::insetList() const
3873 return d->insetlist_;
3877 void Paragraph::setInsetBuffers(Buffer & b)
3879 d->insetlist_.setBuffer(b);
3883 void Paragraph::resetBuffer()
3885 d->insetlist_.resetBuffer();
3889 Inset * Paragraph::releaseInset(pos_type pos)
3891 Inset * inset = d->insetlist_.release(pos);
3892 /// does not honour change tracking!
3893 eraseChar(pos, false);
3898 Inset * Paragraph::getInset(pos_type pos)
3900 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3901 ? d->insetlist_.get(pos) : nullptr;
3905 Inset const * Paragraph::getInset(pos_type pos) const
3907 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3908 ? d->insetlist_.get(pos) : nullptr;
3912 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3913 pos_type & right, TextCase action)
3915 // process sequences of modified characters; in change
3916 // tracking mode, this approach results in much better
3917 // usability than changing case on a char-by-char basis
3918 // We also need to track the current font, since font
3919 // changes within sequences can occur.
3920 vector<pair<char_type, Font> > changes;
3922 bool const trackChanges = bparams.track_changes;
3924 bool capitalize = true;
3926 for (; pos < right; ++pos) {
3927 char_type oldChar = d->text_[pos];
3928 char_type newChar = oldChar;
3930 // ignore insets and don't play with deleted text!
3931 if (oldChar != META_INSET && !isDeleted(pos)) {
3933 case text_lowercase:
3934 newChar = lowercase(oldChar);
3936 case text_capitalization:
3938 newChar = uppercase(oldChar);
3942 case text_uppercase:
3943 newChar = uppercase(oldChar);
3948 if (isWordSeparator(pos) || isDeleted(pos)) {
3949 // permit capitalization again
3953 if (oldChar != newChar) {
3954 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3955 if (pos != right - 1)
3957 // step behind the changing area
3961 int erasePos = pos - changes.size();
3962 for (size_t i = 0; i < changes.size(); i++) {
3963 insertChar(pos, changes[i].first,
3966 if (!eraseChar(erasePos, trackChanges)) {
3969 ++right; // expand selection
3977 int Paragraph::find(docstring const & str, bool cs, bool mw,
3978 pos_type start_pos, bool del) const
3980 pos_type pos = start_pos;
3981 int const strsize = str.length();
3983 pos_type const parsize = d->text_.size();
3984 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3985 // Ignore "invisible" letters such as ligature breaks
3986 // and hyphenation chars while searching
3987 while (pos < parsize - 1 && isInset(pos)) {
3988 odocstringstream os;
3989 getInset(pos)->toString(os);
3990 if (!getInset(pos)->isLetter() || !os.str().empty())
3994 if (cs && str[i] != d->text_[pos])
3996 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3998 if (!del && isDeleted(pos))
4005 // if necessary, check whether string matches word
4007 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4010 && !isWordSeparator(pos))
4014 return pos - start_pos;
4018 char_type Paragraph::getChar(pos_type pos) const
4020 return d->text_[pos];
4024 pos_type Paragraph::size() const
4026 return d->text_.size();
4030 bool Paragraph::empty() const
4032 return d->text_.empty();
4036 bool Paragraph::isInset(pos_type pos) const
4038 return d->text_[pos] == META_INSET;
4042 bool Paragraph::isSeparator(pos_type pos) const
4044 //FIXME: Are we sure this can be the only separator?
4045 return d->text_[pos] == ' ';
4049 void Paragraph::deregisterWords()
4051 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4052 Private::LangWordsMap::const_iterator ite = d->words_.end();
4053 for (; itl != ite; ++itl) {
4054 WordList & wl = theWordList(itl->first);
4055 Private::Words::const_iterator it = (itl->second).begin();
4056 Private::Words::const_iterator et = (itl->second).end();
4057 for (; it != et; ++it)
4064 void Paragraph::locateWord(pos_type & from, pos_type & to,
4065 word_location const loc, bool const ignore_deleted) const
4068 case WHOLE_WORD_STRICT:
4069 if (from == 0 || from == size()
4070 || isWordSeparator(from, ignore_deleted)
4071 || isWordSeparator(from - 1, ignore_deleted)) {
4078 // If we are already at the beginning of a word, do nothing
4079 if (!from || isWordSeparator(from - 1, ignore_deleted))
4084 // always move the cursor to the beginning of previous word
4085 while (from && !isWordSeparator(from - 1, ignore_deleted))
4089 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4092 // no need to move the 'from' cursor
4096 while (to < size() && !isWordSeparator(to, ignore_deleted))
4101 void Paragraph::collectWords()
4103 for (pos_type pos = 0; pos < size(); ++pos) {
4104 if (isWordSeparator(pos))
4106 pos_type from = pos;
4107 locateWord(from, pos, WHOLE_WORD);
4108 // Work around MSVC warning: The statement
4109 // if (pos < from + lyxrc.completion_minlength)
4110 // triggers a signed vs. unsigned warning.
4111 // I don't know why this happens, it could be a MSVC bug, or
4112 // related to LLP64 (windows) vs. LP64 (unix) programming
4113 // model, or the C++ standard might be ambigous in the section
4114 // defining the "usual arithmetic conversions". However, using
4115 // a temporary variable is safe and works on all compilers.
4116 pos_type const endpos = from + lyxrc.completion_minlength;
4119 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4120 if (cit == d->fontlist_.end())
4122 Language const * lang = cit->font().language();
4123 docstring const word = asString(from, pos, AS_STR_NONE);
4124 d->words_[lang->lang()].insert(word);
4129 void Paragraph::registerWords()
4131 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4132 Private::LangWordsMap::const_iterator ite = d->words_.end();
4133 for (; itl != ite; ++itl) {
4134 WordList & wl = theWordList(itl->first);
4135 Private::Words::const_iterator it = (itl->second).begin();
4136 Private::Words::const_iterator et = (itl->second).end();
4137 for (; it != et; ++it)
4143 void Paragraph::updateWords()
4151 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4153 SkipPositionsIterator begin = skips.begin();
4154 SkipPositions::iterator end = skips.end();
4155 if (pos > 0 && begin < end) {
4157 if (end->last == pos - 1) {
4162 skips.insert(end, FontSpan(pos, pos));
4166 Language * Paragraph::Private::locateSpellRange(
4167 pos_type & from, pos_type & to,
4168 SkipPositions & skips) const
4170 // skip leading white space
4171 while (from < to && owner_->isWordSeparator(from))
4173 // don't check empty range
4176 // get current language
4177 Language * lang = getSpellLanguage(from);
4178 pos_type last = from;
4179 bool samelang = true;
4180 bool sameinset = true;
4181 while (last < to && samelang && sameinset) {
4182 // hop to end of word
4183 while (last < to && !owner_->isWordSeparator(last)) {
4184 if (owner_->getInset(last)) {
4185 appendSkipPosition(skips, last);
4186 } else if (owner_->isDeleted(last)) {
4187 appendSkipPosition(skips, last);
4191 // hop to next word while checking for insets
4192 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4193 if (Inset const * inset = owner_->getInset(last))
4194 sameinset = inset->isChar() && inset->isLetter();
4195 if (sameinset && owner_->isDeleted(last)) {
4196 appendSkipPosition(skips, last);
4201 if (sameinset && last < to) {
4202 // now check for language change
4203 samelang = lang == getSpellLanguage(last);
4206 // if language change detected backstep is needed
4214 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4217 const_cast<Language *>(owner_->getFontSettings(
4218 inset_owner_->buffer().params(), from).language());
4219 if (lang == inset_owner_->buffer().params().language
4220 && !lyxrc.spellchecker_alt_lang.empty()) {
4222 string const lang_variety =
4223 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4224 lang->setCode(lang_code);
4225 lang->setVariety(lang_variety);
4231 void Paragraph::requestSpellCheck(pos_type pos)
4233 d->requestSpellCheck(pos);
4237 bool Paragraph::needsSpellCheck() const
4239 SpellChecker::ChangeNumber speller_change_number = 0;
4240 if (theSpellChecker())
4241 speller_change_number = theSpellChecker()->changeNumber();
4242 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4243 d->speller_state_.needsCompleteRefresh(speller_change_number);
4245 return d->needsSpellCheck();
4249 bool Paragraph::Private::ignoreWord(docstring const & word) const
4251 // Ignore words with digits
4252 // FIXME: make this customizable
4253 // (note that some checkers ignore words with digits by default)
4254 docstring::const_iterator cit = word.begin();
4255 docstring::const_iterator const end = word.end();
4256 for (; cit != end; ++cit) {
4257 if (isNumber((*cit)))
4264 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4265 WordLangTuple & wl, docstring_list & suggestions,
4266 bool do_suggestion, bool check_learned) const
4268 SpellChecker::Result result = SpellChecker::WORD_OK;
4269 SpellChecker * speller = theSpellChecker();
4273 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4276 locateWord(from, to, WHOLE_WORD, true);
4277 if (from == to || from >= size())
4280 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4281 Language * lang = d->getSpellLanguage(from);
4283 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4286 wl = WordLangTuple(word, lang);
4291 if (needsSpellCheck() || check_learned) {
4293 if (!d->ignoreWord(word)) {
4294 bool const trailing_dot = to < size() && d->text_[to] == '.';
4295 result = speller->check(wl);
4296 if (SpellChecker::misspelled(result) && trailing_dot) {
4297 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4298 result = speller->check(wl);
4299 if (!SpellChecker::misspelled(result)) {
4300 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4302 from << ".." << to << "]");
4304 // spell check with dot appended failed too
4305 // restore original word/lang value
4306 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4307 wl = WordLangTuple(word, lang);
4311 if (!SpellChecker::misspelled(result)) {
4312 // area up to the begin of the next word is not misspelled
4313 while (end < size() && isWordSeparator(end))
4316 d->setMisspelled(from, end, result);
4318 result = d->speller_state_.getState(from);
4322 suggestions.clear();
4324 if (SpellChecker::misspelled(result)) {
4325 LYXERR(Debug::GUI, "misspelled word: \"" <<
4327 from << ".." << to << "]");
4329 speller->suggest(wl, suggestions);
4335 void Paragraph::anonymize()
4337 // This is a very crude anonymization for now
4338 for (char_type & c : d->text_)
4339 if (isLetterChar(c) || isNumber(c))
4344 void Paragraph::Private::markMisspelledWords(
4345 pos_type const & first, pos_type const & last,
4346 SpellChecker::Result result,
4347 docstring const & word,
4348 SkipPositions const & skips)
4350 if (!SpellChecker::misspelled(result)) {
4351 setMisspelled(first, last, SpellChecker::WORD_OK);
4355 SpellChecker * speller = theSpellChecker();
4356 // locate and enumerate the error positions
4357 int nerrors = speller->numMisspelledWords();
4359 SkipPositionsIterator it = skips.begin();
4360 SkipPositionsIterator et = skips.end();
4361 for (int index = 0; index < nerrors; ++index) {
4364 speller->misspelledWord(index, wstart, wlen);
4365 /// should not happen if speller supports range checks
4366 if (!wlen) continue;
4367 docstring const misspelled = word.substr(wstart, wlen);
4368 wstart += first + numskipped;
4369 if (snext < wstart) {
4370 /// mark the range of correct spelling
4371 numskipped += countSkips(it, et, wstart);
4372 setMisspelled(snext,
4373 wstart - 1, SpellChecker::WORD_OK);
4375 snext = wstart + wlen;
4376 numskipped += countSkips(it, et, snext);
4377 /// mark the range of misspelling
4378 setMisspelled(wstart, snext, result);
4379 LYXERR(Debug::GUI, "misspelled word: \"" <<
4380 misspelled << "\" [" <<
4381 wstart << ".." << (snext-1) << "]");
4384 if (snext <= last) {
4385 /// mark the range of correct spelling at end
4386 setMisspelled(snext, last, SpellChecker::WORD_OK);
4391 void Paragraph::spellCheck() const
4393 SpellChecker * speller = theSpellChecker();
4394 if (!speller || empty() ||!needsSpellCheck())
4398 d->rangeOfSpellCheck(start, endpos);
4399 if (speller->canCheckParagraph()) {
4400 // loop until we leave the range
4401 for (pos_type first = start; first < endpos; ) {
4402 pos_type last = endpos;
4403 Private::SkipPositions skips;
4404 Language * lang = d->locateSpellRange(first, last, skips);
4405 if (first >= endpos)
4407 // start the spell checker on the unit of meaning
4408 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4409 WordLangTuple wl = WordLangTuple(word, lang);
4410 SpellChecker::Result result = word.size() ?
4411 speller->check(wl) : SpellChecker::WORD_OK;
4412 d->markMisspelledWords(first, last, result, word, skips);
4416 static docstring_list suggestions;
4417 pos_type to = endpos;
4418 while (start < endpos) {
4420 spellCheck(start, to, wl, suggestions, false);
4424 d->readySpellCheck();
4428 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4430 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4431 if (result || pos <= 0 || pos > size())
4433 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4434 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4439 string Paragraph::magicLabel() const
4442 ss << "magicparlabel-" << id();