3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Kimberly Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
24 #include "BufferParams.h"
25 #include "BufferEncodings.h"
28 #include "InsetList.h"
30 #include "LaTeXFeatures.h"
35 #include "OutputParams.h"
36 #include "output_latex.h"
37 #include "output_xhtml.h"
38 #include "output_docbook.h"
39 #include "ParagraphParameters.h"
40 #include "SpellChecker.h"
41 #include "texstream.h"
44 #include "TextClass.h"
45 #include "WordLangTuple.h"
48 #include "frontends/alert.h"
50 #include "insets/InsetArgument.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
54 #include "insets/InsetText.h"
56 #include "mathed/InsetMathHull.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
71 using namespace lyx::support;
73 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
74 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
75 #define THREAD_LOCAL_STATIC static __thread
76 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
77 #define THREAD_LOCAL_STATIC static __declspec(thread)
79 #define THREAD_LOCAL_STATIC thread_local static
84 /////////////////////////////////////////////////////////////////////
88 /////////////////////////////////////////////////////////////////////
90 class SpellResultRange {
92 SpellResultRange(FontSpan range, SpellChecker::Result result)
93 : range_(range), result_(result)
96 FontSpan const & range() const { return range_; }
98 void range(FontSpan const & r) { range_ = r; }
100 SpellChecker::Result result() const { return result_; }
102 void result(SpellChecker::Result r) { result_ = r; }
104 bool contains(pos_type pos) const { return range_.contains(pos); }
106 bool covered(FontSpan const & r) const
108 // 1. first of new range inside current range or
109 // 2. last of new range inside current range or
110 // 3. first of current range inside new range or
111 // 4. last of current range inside new range
112 //FIXME: is this the same as !range_.intersect(r).empty() ?
113 return range_.contains(r.first) || range_.contains(r.last) ||
114 r.contains(range_.first) || r.contains(range_.last);
117 void shift(pos_type pos, int offset)
119 if (range_.first > pos) {
120 range_.first += offset;
121 range_.last += offset;
122 } else if (range_.last >= pos) {
123 range_.last += offset;
128 SpellChecker::Result result_ ;
132 /////////////////////////////////////////////////////////////////////
136 /////////////////////////////////////////////////////////////////////
138 class SpellCheckerState {
142 needs_refresh_ = true;
143 current_change_number_ = 0;
146 void setRange(FontSpan const & fp, SpellChecker::Result state)
149 RangesIterator et = ranges_.end();
150 RangesIterator it = ranges_.begin();
151 for (; it != et; ++it) {
152 if (!it->covered(fp))
153 result.push_back(SpellResultRange(it->range(), it->result()));
154 else if (state == SpellChecker::WORD_OK) {
155 // trim or split the current misspelled range
156 // store misspelled ranges only
157 FontSpan range = it->range();
158 if (fp.first > range.first) {
159 // misspelled area in front of WORD_OK
160 range.last = fp.first - 1;
161 result.push_back(SpellResultRange(range, it->result()));
164 if (fp.last < range.last) {
165 // misspelled area after WORD_OK range
166 range.first = fp.last + 1;
167 result.push_back(SpellResultRange(range, it->result()));
172 if (state != SpellChecker::WORD_OK)
173 ranges_.push_back(SpellResultRange(fp, state));
176 void increasePosAfterPos(pos_type pos)
178 correctRangesAfterPos(pos, 1);
182 void decreasePosAfterPos(pos_type pos)
184 correctRangesAfterPos(pos, -1);
188 void refreshLast(pos_type pos)
190 if (pos < refresh_.last)
194 SpellChecker::Result getState(pos_type pos) const
196 SpellChecker::Result result = SpellChecker::WORD_OK;
197 RangesIterator et = ranges_.end();
198 RangesIterator it = ranges_.begin();
199 for (; it != et; ++it) {
200 if(it->contains(pos)) {
207 FontSpan const & getRange(pos_type pos) const
209 /// empty span to indicate mismatch
210 static FontSpan empty_;
211 RangesIterator et = ranges_.end();
212 RangesIterator it = ranges_.begin();
213 for (; it != et; ++it) {
214 if(it->contains(pos)) {
221 bool needsRefresh() const
223 return needs_refresh_;
226 SpellChecker::ChangeNumber currentChangeNumber() const
228 return current_change_number_;
231 void refreshRange(pos_type & first, pos_type & last) const
233 first = refresh_.first;
234 last = refresh_.last;
237 void needsRefresh(pos_type pos)
239 if (needs_refresh_ && pos != -1) {
240 if (pos < refresh_.first)
241 refresh_.first = pos;
242 if (pos > refresh_.last)
244 } else if (pos != -1) {
245 // init request check for neighbour positions too
246 refresh_.first = pos > 0 ? pos - 1 : 0;
247 // no need for special end of paragraph check
248 refresh_.last = pos + 1;
250 needs_refresh_ = pos != -1;
253 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
255 needs_refresh_ = true;
258 current_change_number_ = change_number;
261 typedef vector<SpellResultRange> Ranges;
262 typedef Ranges::const_iterator RangesIterator;
264 /// the area of the paragraph with pending spell check
266 /// spell state cache version number
267 SpellChecker::ChangeNumber current_change_number_;
271 void correctRangesAfterPos(pos_type pos, int offset)
273 RangesIterator et = ranges_.end();
274 Ranges::iterator it = ranges_.begin();
275 for (; it != et; ++it) {
276 it->shift(pos, offset);
282 /////////////////////////////////////////////////////////////////////
284 // Paragraph::Private
286 /////////////////////////////////////////////////////////////////////
288 class Paragraph::Private
290 // Enforce our own "copy" constructor
291 Private(Private const &) = delete;
292 Private & operator=(Private const &) = delete;
293 // Unique ID generator
294 static int make_id();
297 Private(Paragraph * owner, Layout const & layout);
298 /// "Copy constructor"
299 Private(Private const &, Paragraph * owner);
300 /// Copy constructor from \p beg to \p end
301 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
304 void insertChar(pos_type pos, char_type c, Change const & change);
306 /// Output the surrogate pair formed by \p c and \p next to \p os.
307 /// \return the number of characters written.
308 int latexSurrogatePair(BufferParams const &, otexstream & os,
309 char_type c, char_type next,
310 OutputParams const &);
312 /// Output a space in appropriate formatting (or a surrogate pair
313 /// if the next character is a combining character).
314 /// \return whether a surrogate pair was output.
315 bool simpleTeXBlanks(BufferParams const &,
316 OutputParams const &,
319 unsigned int & column,
321 Layout const & style);
323 /// This could go to ParagraphParameters if we want to.
324 int startTeXParParams(BufferParams const &, otexstream &,
325 OutputParams const &) const;
327 /// This could go to ParagraphParameters if we want to.
328 bool endTeXParParams(BufferParams const &, otexstream &,
329 OutputParams const &) const;
332 void latexInset(BufferParams const &,
337 Font const & outerfont,
339 Change & running_change,
340 Layout const & style,
342 unsigned int & column,
343 bool const fontswitch_inset,
344 bool const closeLanguage,
345 bool const lang_switched_at_inset);
348 void latexSpecialChar(
350 BufferParams const & bparams,
351 OutputParams const & runparams,
352 Font const & running_font,
353 string & alien_script,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column) const;
370 unsigned int & column) const;
376 unsigned int & column) const;
379 void validate(LaTeXFeatures & features) const;
381 /// Checks if the paragraph contains only text and no inset or font change.
382 bool onlyText(Buffer const & buf, Font const & outerfont,
383 pos_type initial) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD, true);
445 owner_->locateWord(last, endpos, WHOLE_WORD, true);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 long skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
483 ParagraphParameters params_;
485 /// for recording and looking up changes
489 InsetList insetlist_;
492 pos_type begin_of_body_;
494 typedef docstring TextContainer;
498 typedef set<docstring> Words;
499 typedef map<string, Words> LangWordsMap;
503 Layout const * layout_;
505 SpellCheckerState speller_state_;
511 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
512 : owner_(owner), inset_owner_(nullptr), begin_of_body_(0), layout_(&layout), id_(-1)
519 int Paragraph::Private::make_id()
521 // The id is unique per session across buffers because it is used in
522 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
525 static int next_id(0);
530 Paragraph::Private::Private(Private const & p, Paragraph * owner)
531 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
532 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
533 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
534 layout_(p.layout_), id_(make_id())
536 requestSpellCheck(p.text_.size());
540 Paragraph::Private::Private(Private const & p, Paragraph * owner,
541 pos_type beg, pos_type end)
542 : owner_(owner), inset_owner_(p.inset_owner_),
543 params_(p.params_), changes_(p.changes_),
544 insetlist_(p.insetlist_, beg, end),
545 begin_of_body_(p.begin_of_body_), words_(p.words_),
546 layout_(p.layout_), id_(make_id())
548 if (beg >= pos_type(p.text_.size()))
550 text_ = p.text_.substr(beg, end - beg);
552 FontList::const_iterator fcit = fontlist_.begin();
553 FontList::const_iterator fend = fontlist_.end();
554 for (; fcit != fend; ++fcit) {
555 if (fcit->pos() < beg)
557 if (fcit->pos() >= end) {
558 // Add last entry in the fontlist_.
559 fontlist_.set(text_.size() - 1, fcit->font());
562 // Add a new entry in the fontlist_.
563 fontlist_.set(fcit->pos() - beg, fcit->font());
565 requestSpellCheck(p.text_.size());
569 /////////////////////////////////////////////////////////////////////
573 /////////////////////////////////////////////////////////////////////
577 /** This helper class should be instantiated at the start of methods
578 * that can create or merge changes. If as a result the value of
579 * Paragraph::isChanged is modified, it makes sure that updateBuffer()
582 struct ChangesMonitor {
584 ChangesMonitor(Paragraph & par)
585 : par_(par), was_changed_(par.isChanged()) {}
589 /* We may need to run updateBuffer to check whether the buffer
590 * contains changes (and toggle the changes toolbar). We do it
592 * 1. the `changedness' of the paragraph has changed,
593 * 2. and we are not in the situation where the buffer has changes
594 * and new changes are added to the paragraph.
597 if (par_.isChanged() != was_changed_
598 && par_.inInset().isBufferValid()
599 && !(par_.inInset().buffer().areChangesPresent() && par_.isChanged()))
600 par_.inInset().buffer().forceUpdate();
601 } catch(support::ExceptionMessage const &) {}
606 Paragraph const & par_;
613 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
614 bool output_active, TocBackend & backend) const
616 d->changes_.addToToc(cdit, buf, output_active, backend);
620 bool Paragraph::isDeleted(pos_type start, pos_type end) const
622 LASSERT(start >= 0 && start <= size(), return false);
623 LASSERT(end > start && end <= size() + 1, return false);
625 return d->changes_.isDeleted(start, end);
629 bool Paragraph::isChanged(pos_type start, pos_type end) const
631 LASSERT(start >= 0 && start <= size(), return false);
632 LASSERT(end > start && end <= size() + 1, return false);
634 return d->changes_.isChanged(start, end);
637 // FIXME: Ideally the diverse isChanged() methods should account for that!
638 bool Paragraph::hasChangedInsets(pos_type start, pos_type end) const
640 LASSERT(start >= 0 && start <= size(), return false);
641 LASSERT(end > start && end <= size() + 1, return false);
643 for (auto const & icit : d->insetlist_) {
644 if (icit.pos < start)
648 if (icit.inset && icit.inset->isChanged())
654 bool Paragraph::isChanged() const
656 return d->changes_.isChanged();
660 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
662 // keep the logic here in sync with the logic of eraseChars()
666 Change const & change = d->changes_.lookup(size());
667 return change.inserted() && change.currentAuthor();
670 Change Paragraph::parEndChange() const
672 return d->changes_.lookup(size());
676 void Paragraph::setChange(Change const & change)
678 // Make sure that Buffer::hasChangesPresent is updated
679 ChangesMonitor cm(*this);
681 // beware of the imaginary end-of-par character!
682 d->changes_.set(change, 0, size() + 1);
685 * Propagate the change recursively - but not in case of DELETED!
687 * Imagine that your co-author makes changes in an existing inset. He
688 * sends your document to you and you come to the conclusion that the
689 * inset should go completely. If you erase it, LyX must not delete all
690 * text within the inset. Otherwise, the change tracked insertions of
691 * your co-author get lost and there is no way to restore them later.
693 * Conclusion: An inset's content should remain untouched if you delete it
696 if (!change.deleted()) {
697 for (pos_type pos = 0; pos < size(); ++pos) {
698 if (Inset * inset = getInset(pos))
699 inset->setChange(change);
705 void Paragraph::setChange(pos_type pos, Change const & change)
707 // Make sure that Buffer::hasChangesPresent is updated
708 ChangesMonitor cm(*this);
710 LASSERT(pos >= 0 && pos <= size(), return);
711 d->changes_.set(change, pos);
713 // see comment in setChange(Change const &) above
714 if (!change.deleted() && pos < size())
715 if (Inset * inset = getInset(pos))
716 inset->setChange(change);
720 Change const & Paragraph::lookupChange(pos_type pos) const
722 LBUFERR(pos >= 0 && pos <= size());
723 return d->changes_.lookup(pos);
727 void Paragraph::acceptChanges(pos_type start, pos_type end)
729 // Make sure that Buffer::hasChangesPresent is updated
730 ChangesMonitor cm(*this);
732 LASSERT(start >= 0 && start <= size(), return);
733 LASSERT(end > start && end <= size() + 1, return);
735 for (pos_type pos = start; pos < end; ++pos) {
736 switch (lookupChange(pos).type) {
737 case Change::UNCHANGED:
738 // accept changes in nested inset
739 if (Inset * inset = getInset(pos))
740 inset->acceptChanges();
743 case Change::INSERTED:
744 d->changes_.set(Change(Change::UNCHANGED), pos);
745 // also accept changes in nested inset
746 if (Inset * inset = getInset(pos))
747 inset->acceptChanges();
750 case Change::DELETED:
751 // Suppress access to non-existent
752 // "end-of-paragraph char"
754 eraseChar(pos, false);
765 void Paragraph::rejectChanges(pos_type start, pos_type end)
767 LASSERT(start >= 0 && start <= size(), return);
768 LASSERT(end > start && end <= size() + 1, return);
770 // Make sure that Buffer::hasChangesPresent is updated
771 ChangesMonitor cm(*this);
773 for (pos_type pos = start; pos < end; ++pos) {
774 switch (lookupChange(pos).type) {
775 case Change::UNCHANGED:
776 // reject changes in nested inset
777 if (Inset * inset = getInset(pos))
778 inset->rejectChanges();
781 case Change::INSERTED:
782 // Suppress access to non-existent
783 // "end-of-paragraph char"
785 eraseChar(pos, false);
791 case Change::DELETED:
792 d->changes_.set(Change(Change::UNCHANGED), pos);
794 // Do NOT reject changes within a deleted inset!
795 // There may be insertions of a co-author inside of it!
803 void Paragraph::Private::insertChar(pos_type pos, char_type c,
804 Change const & change)
806 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
808 // Make sure that Buffer::hasChangesPresent is updated
809 ChangesMonitor cm(*owner_);
812 changes_.insert(change, pos);
814 // This is actually very common when parsing buffers (and
815 // maybe inserting ascii text)
816 if (pos == pos_type(text_.size())) {
817 // when appending characters, no need to update tables
819 // but we want spell checking
820 requestSpellCheck(pos);
824 text_.insert(text_.begin() + pos, c);
826 // Update the font table.
827 fontlist_.increasePosAfterPos(pos);
830 insetlist_.increasePosAfterPos(pos);
832 // Update list of misspelled positions
833 speller_state_.increasePosAfterPos(pos);
837 bool Paragraph::insertInset(pos_type pos, Inset * inset,
838 Font const & font, Change const & change)
840 LASSERT(inset, return false);
841 LASSERT(pos >= 0 && pos <= size(), return false);
843 // Make sure that Buffer::hasChangesPresent is updated
844 ChangesMonitor cm(*this);
846 // Paragraph::insertInset() can be used in cut/copy/paste operation where
847 // d->inset_owner_ is not set yet.
848 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
851 d->insertChar(pos, META_INSET, change);
852 LASSERT(d->text_[pos] == META_INSET, return false);
854 // Add a new entry in the insetlist_.
855 d->insetlist_.insert(inset, pos);
857 // Some insets require run of spell checker
858 requestSpellCheck(pos);
864 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
866 LASSERT(pos >= 0 && pos <= size(), return false);
868 // Make sure that Buffer::hasChangesPresent is updated
869 ChangesMonitor cm(*this);
871 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
874 Change change = d->changes_.lookup(pos);
876 // set the character to DELETED if
877 // a) it was previously unchanged or
878 // b) it was inserted by a co-author
880 if (!change.changed() ||
881 (change.inserted() && !change.currentAuthor())) {
882 setChange(pos, Change(Change::DELETED));
883 // request run of spell checker
884 requestSpellCheck(pos);
888 if (change.deleted())
892 // Don't physically access the imaginary end-of-paragraph character.
893 // eraseChar() can only mark it as DELETED. A physical deletion of
894 // end-of-par must be handled externally.
900 d->changes_.erase(pos);
902 // if it is an inset, delete the inset entry
903 if (d->text_[pos] == META_INSET)
904 d->insetlist_.erase(pos);
906 d->text_.erase(d->text_.begin() + pos);
908 // Update the fontlist_
909 d->fontlist_.erase(pos);
911 // Update the insetlist_
912 d->insetlist_.decreasePosAfterPos(pos);
914 // Update list of misspelled positions
915 d->speller_state_.decreasePosAfterPos(pos);
916 d->speller_state_.refreshLast(size());
922 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
924 LASSERT(start >= 0 && start <= size(), return 0);
925 LASSERT(end >= start && end <= size() + 1, return 0);
928 for (pos_type count = end - start; count; --count) {
929 if (!eraseChar(i, trackChanges))
936 // Handle combining characters
937 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
938 otexstream & os, char_type c, char_type next,
939 OutputParams const & runparams)
941 // Writing next here may circumvent a possible font change between
942 // c and next. Since next is only output if it forms a surrogate pair
943 // with c we can ignore this:
944 // A font change inside a surrogate pair does not make sense and is
945 // hopefully impossible to input.
946 // FIXME: change tracking
947 // Is this correct WRT change tracking?
948 Encoding const & encoding = *(runparams.encoding);
949 docstring latex1 = encoding.latexChar(next).first;
950 if (runparams.inIPA) {
951 string const tipashortcut = Encodings::TIPAShortcut(next);
952 if (!tipashortcut.empty()) {
953 latex1 = from_ascii(tipashortcut);
956 docstring latex2 = encoding.latexChar(c).first;
958 if (bparams.useNonTeXFonts || docstring(1, next) == latex1) {
959 // Encoding supports the combination:
960 // output as is (combining char after base char).
961 os << latex2 << latex1;
962 return latex1.length() + latex2.length();
965 os << latex1 << "{" << latex2 << "}";
966 return latex1.length() + latex2.length() + 2;
970 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
971 OutputParams const & runparams,
974 unsigned int & column,
976 Layout const & style)
978 if (style.pass_thru || runparams.pass_thru)
981 if (i + 1 < int(text_.size())) {
982 char_type next = text_[i + 1];
983 if (Encodings::isCombiningChar(next)) {
984 // This space has an accent, so we must always output it.
985 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
990 if (runparams.linelen > 0
991 && column > runparams.linelen
993 && text_[i - 1] != ' '
994 && (i + 1 < int(text_.size()))
995 // same in FreeSpacing mode
996 && !owner_->isFreeSpacing()
997 // In typewriter mode, we want to avoid
998 // ! . ? : at the end of a line
999 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
1000 && (text_[i - 1] == '.'
1001 || text_[i - 1] == '?'
1002 || text_[i - 1] == ':'
1003 || text_[i - 1] == '!'))) {
1005 os.texrow().start(owner_->id(), i + 1);
1007 } else if (style.free_spacing) {
1016 void Paragraph::Private::latexInset(BufferParams const & bparams,
1018 OutputParams & runparams,
1019 Font & running_font,
1021 Font const & outerfont,
1023 Change & running_change,
1024 Layout const & style,
1026 unsigned int & column,
1027 bool const fontswitch_inset,
1028 bool const closeLanguage,
1029 bool const lang_switched_at_inset)
1031 Inset * inset = owner_->getInset(i);
1034 if (style.pass_thru) {
1035 odocstringstream ods;
1036 inset->plaintext(ods, runparams);
1041 // FIXME: move this to InsetNewline::latex
1042 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1043 // newlines are handled differently here than
1044 // the default in simpleTeXSpecialChars().
1045 if (!style.newline_allowed) {
1049 bool needPar = false;
1050 column += running_font.latexWriteEndChanges(
1051 os, bparams, runparams,
1052 basefont, basefont, needPar);
1056 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1059 basefont = owner_->getLayoutFont(bparams, outerfont);
1060 running_font = basefont;
1062 if (runparams.moving_arg)
1066 os.texrow().start(owner_->id(), i + 1);
1070 if (owner_->isDeleted(i)) {
1071 if( ++runparams.inDeletedInset == 1)
1072 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1075 if (inset->canTrackChanges()) {
1076 column += Changes::latexMarkChange(os, bparams, running_change,
1077 Change(Change::UNCHANGED), runparams);
1078 running_change = Change(Change::UNCHANGED);
1082 odocstream::pos_type const len = os.os().tellp();
1084 if (inset->forceLTR(runparams)
1085 && running_font.isRightToLeft()
1086 // ERT is an exception, it should be output with no
1087 // decorations at all
1088 && inset->lyxCode() != ERT_CODE) {
1089 if (runparams.use_polyglossia) {
1091 } else if (running_font.language()->lang() == "farsi"
1092 || running_font.language()->lang() == "arabic_arabi")
1093 os << "\\textLR{" << termcmd;
1099 if (open_font && fontswitch_inset) {
1100 bool lang_closed = false;
1101 // Close language if needed
1102 if (closeLanguage && !lang_switched_at_inset) {
1103 // We need prev_font here as language changes directly at inset
1104 // will only be started inside the inset.
1105 Font const prev_font = (i > 0) ?
1106 owner_->getFont(bparams, i - 1, outerfont)
1108 Font tmpfont(basefont);
1109 tmpfont.setLanguage(prev_font.language());
1110 bool needPar = false;
1111 unsigned int count = tmpfont.latexWriteEndChanges(os, bparams, runparams,
1113 needPar, closeLanguage);
1115 lang_closed = count > 0;
1117 // Update the running_font, making sure, however,
1118 // to leave the language as it was.
1119 // FIXME: probably a better way to keep track of the old
1120 // language, than copying the entire font?
1121 Font const copy_font(running_font);
1122 basefont = owner_->getLayoutFont(bparams, outerfont);
1123 running_font = basefont;
1125 running_font.setLanguage(copy_font.language());
1126 OutputParams rp = runparams;
1127 rp.encoding = basefont.language()->encoding();
1128 // For these, we use switches, so they should be taken as
1129 // base inside the inset.
1130 basefont.fontInfo().setSize(copy_font.fontInfo().size());
1131 basefont.fontInfo().setFamily(copy_font.fontInfo().family());
1132 basefont.fontInfo().setSeries(copy_font.fontInfo().series());
1133 // Now re-do font changes in a way needed here
1134 // (using switches with multi-par insets)
1135 InsetText const * textinset = inset->asInsetText();
1136 bool const cprotect = textinset
1137 ? textinset->hasCProtectContent(runparams.moving_arg)
1138 && !textinset->text().isMainText()
1140 unsigned int count2 = basefont.latexWriteStartChanges(os, bparams,
1146 if (count2 == 0 && (lang_closed || lang_switched_at_inset))
1150 runparams.local_font = &basefont;
1153 if (fontswitch_inset && !closeLanguage) {
1154 // The directionality has been switched at inset.
1155 // Force markup inside.
1156 runparams.local_font = &basefont;
1159 size_t const previous_row_count = os.texrow().rows();
1162 runparams.lastid = id_;
1163 runparams.lastpos = i;
1164 inset->latex(os, runparams);
1165 } catch (EncodingException & e) {
1166 // add location information and throw again.
1175 if (os.texrow().rows() > previous_row_count) {
1176 os.texrow().start(owner_->id(), i + 1);
1179 column += (unsigned int)(os.os().tellp() - len);
1182 if (owner_->isDeleted(i))
1183 --runparams.inDeletedInset;
1187 void Paragraph::Private::latexSpecialChar(otexstream & os,
1188 BufferParams const & bparams,
1189 OutputParams const & runparams,
1190 Font const & running_font,
1191 string & alien_script,
1192 Layout const & style,
1195 unsigned int & column)
1197 char_type const c = owner_->getUChar(bparams, runparams, i);
1199 if (style.pass_thru || runparams.pass_thru || (runparams.for_searchAdv != OutputParams::NoSearch)
1200 || contains(style.pass_thru_chars, c)
1201 || contains(runparams.pass_thru_chars, c)) {
1202 if (runparams.for_searchAdv != OutputParams::NoSearch) {
1206 os << "\\braceleft ";
1208 os << "\\braceright ";
1212 else if (c != '\0') {
1213 Encoding const * const enc = runparams.encoding;
1214 if (enc && !enc->encodable(c))
1215 throw EncodingException(c);
1221 // TIPA uses its own T3 encoding
1222 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1224 // If T1 font encoding is used, use the special
1225 // characters it provides.
1226 // NOTE: Some languages reset the font encoding internally to a
1227 // non-standard font encoding. If we are using such a language,
1228 // we do not output special T1 chars.
1229 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1230 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1231 && latexSpecialT1(c, os, i, column))
1233 // NOTE: "fontspec" (non-TeX fonts) sets the font encoding to "TU" (untill 2017 "EU1" or "EU2")
1234 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1235 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1238 // Otherwise, we use what LaTeX provides us.
1241 os << "\\textbackslash" << termcmd;
1245 os << "\\textless" << termcmd;
1249 os << "\\textgreater" << termcmd;
1253 os << "\\textbar" << termcmd;
1258 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1259 (end_pos == -1 || i + 1 < end_pos) &&
1260 text_[i+1] == '-') {
1261 // Prevent "--" becoming an en dash and "---" an em dash.
1262 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1268 os << "\\textquotedbl" << termcmd;
1273 case '%': case '#': case '{':
1281 os << "\\textasciitilde" << termcmd;
1286 os << "\\textasciicircum" << termcmd;
1293 // avoid being mistaken for optional arguments
1301 // Blanks are printed before font switching.
1302 // Sure? I am not! (try nice-latex)
1303 // I am sure it's correct. LyX might be smarter
1304 // in the future, but for now, nothing wrong is
1310 // XeTeX's dash behaviour is determined via a global setting
1311 if (bparams.use_dash_ligatures
1312 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1314 // TODO #10961: && not in inset Flex Code
1315 // TODO #10961: && not in layout LyXCode
1316 && (!bparams.useNonTeXFonts || runparams.flavor != Flavor::XeTeX)) {
1333 Encoding const & encoding = *(runparams.encoding);
1334 char_type next = '\0';
1335 if (i + 1 < int(text_.size())) {
1336 next = text_[i + 1];
1337 if (Encodings::isCombiningChar(next)) {
1338 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1343 pair<docstring, bool> latex = encoding.latexChar(c);
1344 docstring nextlatex;
1345 bool nexttipas = false;
1346 string nexttipashortcut;
1347 if (next != '\0' && next != META_INSET && !encoding.encodable(next)) {
1348 nextlatex = encoding.latexChar(next).first;
1349 if (runparams.inIPA) {
1350 nexttipashortcut = Encodings::TIPAShortcut(next);
1351 nexttipas = !nexttipashortcut.empty();
1355 if (runparams.inIPA) {
1356 string const tipashortcut = Encodings::TIPAShortcut(c);
1357 if (!tipashortcut.empty()) {
1358 latex.first = from_ascii(tipashortcut);
1359 latex.second = false;
1363 // eventually close "script wrapper" command (see `Paragraph::latex`)
1364 if (!alien_script.empty()
1365 && alien_script != Encodings::isKnownScriptChar(next)) {
1366 column += latex.first.length();
1367 alien_script.clear();
1368 os << latex.first << "}";
1372 && ((!prefixIs(nextlatex, '\\')
1373 && !prefixIs(nextlatex, '{')
1374 && !prefixIs(nextlatex, '}'))
1376 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1378 // Prevent eating of a following space or command corruption by
1379 // following characters
1380 if (next == ' ' || next == '\0') {
1381 column += latex.first.length() + 1;
1382 os << latex.first << "{}";
1384 column += latex.first.length();
1385 os << latex.first << " ";
1388 column += latex.first.length() - 1;
1396 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1397 pos_type i, unsigned int & column) const
1403 // In T1 encoding, these characters exist
1404 // but we should avoid ligatures
1405 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1407 os << "\\textcompwordmark" << termcmd;
1414 // soul.sty breaks with \char`\"
1415 os << "\\textquotedbl" << termcmd;
1424 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1425 pos_type i, unsigned int & column) const
1427 // TU encoding is currently on par with T1.
1428 return latexSpecialT1(c, os, i, column);
1432 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1433 pos_type /*i*/, unsigned int & column) const
1443 os << "\\textvertline" << termcmd;
1452 void Paragraph::Private::validate(LaTeXFeatures & features) const
1454 if (layout_->inpreamble && inset_owner_) {
1455 // FIXME: Using a string stream here circumvents the encoding
1456 // switching machinery of odocstream. Therefore the
1457 // output is wrong if this paragraph contains content
1458 // that needs to switch encoding.
1459 Buffer const & buf = inset_owner_->buffer();
1460 otexstringstream os;
1461 os << layout_->preamble();
1462 size_t const length = os.length();
1463 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1464 buf.getParFromID(owner_->id()).pit(), os,
1465 features.runparams(), string(), 0, -1, true);
1466 if (os.length() > length)
1467 features.addPreambleSnippet(os.release(), true);
1470 if (features.runparams().flavor == Flavor::Html
1471 && layout_->htmltitle()) {
1472 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1475 // check the params.
1476 if (!params_.spacing().isDefault())
1477 features.require("setspace");
1480 features.useLayout(layout_->name());
1483 fontlist_.validate(features);
1485 // then the indentation
1486 if (!params_.leftIndent().zero())
1487 features.require("ParagraphLeftIndent");
1490 InsetList::const_iterator icit = insetlist_.begin();
1491 InsetList::const_iterator iend = insetlist_.end();
1492 for (; icit != iend; ++icit) {
1494 features.inDeletedInset(owner_->isDeleted(icit->pos));
1495 if (icit->inset->lyxCode() == FOOT_CODE) {
1496 // FIXME: an item inset would make things much easier.
1497 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1498 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1499 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1500 && (icit->pos < begin_of_body_
1501 || (icit->pos == begin_of_body_
1502 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1503 features.saveNoteEnv("description");
1505 icit->inset->validate(features);
1506 features.inDeletedInset(false);
1507 if (layout_->needprotect &&
1508 icit->inset->lyxCode() == FOOT_CODE)
1509 features.require("NeedLyXFootnoteCode");
1513 // then the contents
1514 BufferParams const bp = features.runparams().is_child
1515 ? features.buffer().masterParams() : features.buffer().params();
1516 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1517 char_type c = text_[i];
1518 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1520 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1521 features.require("textquotedblp");
1522 else if (bp.main_font_encoding() != "T1"
1523 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1524 features.require("textquotedbl");
1525 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1526 // features that depend on the font or input encoding
1527 string feats = ci.textpreamble();
1528 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1529 if (fontenc.empty())
1530 fontenc = features.runparams().main_fontenc;
1531 while (!feats.empty()) {
1533 feats = split(feats, feat, ',');
1534 if (contains(feat, "!=")) {
1535 // a feature that is required except for the spcified
1536 // font or input encodings
1538 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1539 // multiple encodings are separated by semicolon
1540 vector<string> context = getVectorFromString(contexts, ";");
1541 // require feature if the context matches neither current font
1542 // nor input encoding
1543 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1544 && std::find(context.begin(), context.end(),
1545 features.runparams().encoding->name()) == context.end())
1546 features.require(realfeature);
1547 } else if (contains(feat, '=')) {
1548 // a feature that is required only for the spcified
1549 // font or input encodings
1551 string const contexts = split(feat, realfeature, '=');
1552 // multiple encodings are separated by semicolon
1553 vector<string> context = getVectorFromString(contexts, ";");
1554 // require feature if the context matches either current font
1555 // or input encoding
1556 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1557 || std::find(context.begin(), context.end(),
1558 features.runparams().encoding->name()) != context.end())
1559 features.require(realfeature);
1562 } else if (!bp.use_dash_ligatures
1563 && (c == 0x2013 || c == 0x2014)
1564 && bp.useNonTeXFonts
1565 && features.runparams().flavor == Flavor::XeTeX)
1566 // XeTeX's dash behaviour is determined via a global setting
1567 features.require("xetexdashbreakstate");
1568 BufferEncodings::validate(c, features);
1572 /////////////////////////////////////////////////////////////////////
1576 /////////////////////////////////////////////////////////////////////
1579 Layout const emptyParagraphLayout;
1582 Paragraph::Paragraph()
1583 : d(new Paragraph::Private(this, emptyParagraphLayout))
1590 Paragraph::Paragraph(Paragraph const & par)
1591 : itemdepth(par.itemdepth),
1592 d(new Paragraph::Private(*par.d, this))
1598 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1599 : itemdepth(par.itemdepth),
1600 d(new Paragraph::Private(*par.d, this, beg, end))
1606 Paragraph & Paragraph::operator=(Paragraph const & par)
1608 // needed as we will destroy the private part before copying it
1610 itemdepth = par.itemdepth;
1614 d = new Private(*par.d, this);
1621 Paragraph::~Paragraph()
1630 // this shall be called just before every "os << ..." action.
1631 void flushString(ostream & os, docstring & s)
1640 void Paragraph::write(ostream & os, BufferParams const & bparams,
1641 depth_type & depth) const
1643 // The beginning or end of a deeper (i.e. nested) area?
1644 if (depth != d->params_.depth()) {
1645 if (d->params_.depth() > depth) {
1646 while (d->params_.depth() > depth) {
1647 os << "\n\\begin_deeper";
1651 while (d->params_.depth() < depth) {
1652 os << "\n\\end_deeper";
1658 // First write the layout
1659 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1661 d->params_.write(os);
1663 Font font1(inherit_font, bparams.language);
1665 Change running_change = Change(Change::UNCHANGED);
1667 // this string is used as a buffer to avoid repetitive calls
1668 // to to_utf8(), which turn out to be expensive (JMarc)
1669 docstring write_buffer;
1672 for (pos_type i = 0; i <= size(); ++i) {
1674 Change const & change = lookupChange(i);
1675 if (change != running_change)
1676 flushString(os, write_buffer);
1677 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1678 running_change = change;
1683 // Write font changes
1684 Font font2 = getFontSettings(bparams, i);
1685 if (font2 != font1) {
1686 flushString(os, write_buffer);
1687 font2.lyxWriteChanges(font1, os);
1692 char_type const c = d->text_[i];
1695 if (Inset const * inset = getInset(i)) {
1696 flushString(os, write_buffer);
1697 if (inset->directWrite()) {
1698 // international char, let it write
1699 // code directly so it's shorter in
1705 os << "\\begin_inset ";
1707 os << "\n\\end_inset\n\n";
1710 // FIXME This can be removed again once the mystery
1711 // crash has been resolved.
1716 flushString(os, write_buffer);
1717 os << "\n\\backslash\n";
1721 flushString(os, write_buffer);
1722 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1729 if ((column > 70 && c == ' ')
1731 flushString(os, write_buffer);
1735 // this check is to amend a bug. LyX sometimes
1736 // inserts '\0' this could cause problems.
1738 write_buffer.push_back(c);
1740 LYXERR0("NUL char in structure.");
1746 flushString(os, write_buffer);
1747 os << "\n\\end_layout\n";
1748 // FIXME This can be removed again once the mystery
1749 // crash has been resolved.
1754 void Paragraph::validate(LaTeXFeatures & features) const
1756 d->validate(features);
1757 bool fragile = features.runparams().moving_arg;
1758 fragile |= layout().needprotect;
1759 if (inInset().getLayout().isNeedProtect())
1761 if (needsCProtection(fragile))
1762 features.require("cprotect");
1766 void Paragraph::insert(pos_type pos, docstring const & str,
1767 Font const & font, Change const & change)
1769 for (size_t i = 0, n = str.size(); i != n ; ++i)
1770 insertChar(pos + i, str[i], font, change);
1774 void Paragraph::appendChar(char_type c, Font const & font,
1775 Change const & change)
1777 // Make sure that Buffer::hasChangesPresent is updated
1778 ChangesMonitor cm(*this);
1781 d->changes_.insert(change, d->text_.size());
1782 // when appending characters, no need to update tables
1783 d->text_.push_back(c);
1784 setFont(d->text_.size() - 1, font);
1785 d->requestSpellCheck(d->text_.size() - 1);
1789 void Paragraph::appendString(docstring const & s, Font const & font,
1790 Change const & change)
1792 // Make sure that Buffer::hasChangesPresent is updated
1793 ChangesMonitor cm(*this);
1795 pos_type end = s.size();
1796 size_t oldsize = d->text_.size();
1797 size_t newsize = oldsize + end;
1798 size_t capacity = d->text_.capacity();
1799 if (newsize >= capacity)
1800 d->text_.reserve(max(capacity + 100, newsize));
1802 // when appending characters, no need to update tables
1805 // FIXME: Optimize this!
1806 for (size_t i = oldsize; i != newsize; ++i) {
1808 d->changes_.insert(change, i);
1809 d->requestSpellCheck(i);
1811 d->fontlist_.set(oldsize, font);
1812 d->fontlist_.set(newsize - 1, font);
1816 void Paragraph::insertChar(pos_type pos, char_type c,
1819 d->insertChar(pos, c, Change(trackChanges ?
1820 Change::INSERTED : Change::UNCHANGED));
1824 void Paragraph::insertChar(pos_type pos, char_type c,
1825 Font const & font, bool trackChanges)
1827 d->insertChar(pos, c, Change(trackChanges ?
1828 Change::INSERTED : Change::UNCHANGED));
1833 void Paragraph::insertChar(pos_type pos, char_type c,
1834 Font const & font, Change const & change)
1836 d->insertChar(pos, c, change);
1841 void Paragraph::resetFonts(Font const & font)
1843 d->fontlist_.clear();
1844 d->fontlist_.set(0, font);
1845 d->fontlist_.set(d->text_.size() - 1, font);
1848 // Gets uninstantiated font setting at position.
1849 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1853 LYXERR0("pos: " << pos << " size: " << size());
1857 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1858 if (cit != d->fontlist_.end())
1861 if (pos == size() && !empty())
1862 return getFontSettings(bparams, pos - 1);
1864 // Optimisation: avoid a full font instantiation if there is no
1865 // language change from previous call.
1866 static Font previous_font;
1867 static Language const * previous_lang = nullptr;
1868 Language const * lang = getParLanguage(bparams);
1869 if (lang != previous_lang) {
1870 previous_lang = lang;
1871 previous_font = Font(inherit_font, lang);
1873 return previous_font;
1877 FontSpan Paragraph::fontSpan(pos_type pos) const
1879 LBUFERR(pos <= size());
1882 return FontSpan(pos, pos);
1885 FontList::const_iterator cit = d->fontlist_.begin();
1886 FontList::const_iterator end = d->fontlist_.end();
1887 for (; cit != end; ++cit) {
1888 if (cit->pos() >= pos) {
1889 if (pos >= beginOfBody())
1890 return FontSpan(max(start, beginOfBody()),
1893 return FontSpan(start,
1894 min(beginOfBody() - 1,
1897 start = cit->pos() + 1;
1900 // This should not happen, but if so, we take no chances.
1901 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1902 LASSERT(false, return FontSpan(pos, pos));
1906 // Gets uninstantiated font setting at position 0
1907 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1909 if (!empty() && !d->fontlist_.empty())
1910 return d->fontlist_.begin()->font();
1912 // Optimisation: avoid a full font instantiation if there is no
1913 // language change from previous call.
1914 static Font previous_font;
1915 static Language const * previous_lang = nullptr;
1916 if (bparams.language != previous_lang) {
1917 previous_lang = bparams.language;
1918 previous_font = Font(inherit_font, bparams.language);
1921 return previous_font;
1925 // Gets the fully instantiated font at a given position in a paragraph
1926 // This is basically the same function as Text::GetFont() in text2.cpp.
1927 // The difference is that this one is used for generating the LaTeX file,
1928 // and thus cosmetic "improvements" are disallowed: This has to deliver
1929 // the true picture of the buffer. (Asger)
1930 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1931 Font const & outerfont) const
1935 Font font = getFontSettings(bparams, pos);
1937 pos_type const body_pos = beginOfBody();
1938 FontInfo & fi = font.fontInfo();
1940 fi.realize(d->layout_->labelfont);
1942 fi.realize(d->layout_->font);
1944 fi.realize(outerfont.fontInfo());
1945 fi.realize(bparams.getFont().fontInfo());
1951 Font const Paragraph::getLabelFont
1952 (BufferParams const & bparams, Font const & outerfont) const
1954 FontInfo tmpfont = d->layout_->labelfont;
1955 tmpfont.realize(outerfont.fontInfo());
1956 tmpfont.realize(bparams.getFont().fontInfo());
1957 return Font(tmpfont, getParLanguage(bparams));
1961 Font const Paragraph::getLayoutFont
1962 (BufferParams const & bparams, Font const & outerfont) const
1964 FontInfo tmpfont = d->layout_->font;
1965 tmpfont.realize(outerfont.fontInfo());
1966 tmpfont.realize(bparams.getFont().fontInfo());
1967 return Font(tmpfont, getParLanguage(bparams));
1971 char_type Paragraph::getUChar(BufferParams const & bparams,
1972 OutputParams const & rp,
1975 char_type c = d->text_[pos];
1977 // Return unchanged character in LTR languages
1978 // or if we use poylglossia/bidi (XeTeX).
1979 if (rp.useBidiPackage()
1980 || !getFontSettings(bparams, pos).isRightToLeft())
1983 // Without polyglossia/bidi, we need to account for some special cases.
1984 // FIXME This needs to be audited!
1986 // * The input is as expected for all delimiters
1987 // => checked for Hebrew!
1988 // * The output matches the display in the LyX workarea
1989 // => checked for Hebrew!
1990 // * The special cases below are really necessary
1991 // => checked for Hebrew!
1992 // * In arabic_arabi, brackets are transformed to Arabic
1993 // Ornate Parentheses. Is this is really wanted?
1995 string const & lang = getFontSettings(bparams, pos).language()->lang();
1998 // 1. In the following languages, parentheses need to be reversed.
1999 // Also with polyglodia/luabidi
2000 bool const reverseparens = (lang == "hebrew" || rp.use_polyglossia);
2002 // 2. In the following languages, brackets don't need to be reversed.
2003 bool const reversebrackets = lang != "arabic_arabtex"
2004 && lang != "arabic_arabi"
2007 // Now swap delimiters if needed.
2018 if (reversebrackets)
2022 if (reversebrackets)
2043 void Paragraph::setFont(pos_type pos, Font const & font)
2045 LASSERT(pos <= size(), return);
2047 // First, reduce font against layout/label font
2048 // Update: The setCharFont() routine in text2.cpp already
2049 // reduces font, so we don't need to do that here. (Asger)
2051 d->fontlist_.set(pos, font);
2055 void Paragraph::makeSameLayout(Paragraph const & par)
2057 d->layout_ = par.d->layout_;
2058 d->params_ = par.d->params_;
2062 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2064 if (isFreeSpacing())
2070 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2071 if (eraseChar(pos, trackChanges))
2077 return count > 0 || pos > 0;
2081 bool Paragraph::hasSameLayout(Paragraph const & par) const
2083 return par.d->layout_ == d->layout_
2084 && d->params_.sameLayout(par.d->params_);
2088 depth_type Paragraph::getDepth() const
2090 return d->params_.depth();
2094 depth_type Paragraph::getMaxDepthAfter() const
2096 if (d->layout_->isEnvironment())
2097 return d->params_.depth() + 1;
2099 return d->params_.depth();
2103 LyXAlignment Paragraph::getAlign(BufferParams const & bparams) const
2105 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2106 return getDefaultAlign(bparams);
2108 return d->params_.align();
2112 LyXAlignment Paragraph::getDefaultAlign(BufferParams const & bparams) const
2114 LyXAlignment res = layout().align;
2115 if (isRTL(bparams)) {
2117 if (res == LYX_ALIGN_LEFT)
2118 res = LYX_ALIGN_RIGHT;
2119 else if (res == LYX_ALIGN_RIGHT)
2120 res = LYX_ALIGN_LEFT;
2126 docstring const & Paragraph::labelString() const
2128 return d->params_.labelString();
2132 // the next two functions are for the manual labels
2133 docstring const Paragraph::getLabelWidthString() const
2135 if (d->layout_->margintype == MARGIN_MANUAL
2136 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2137 return d->params_.labelWidthString();
2139 return _("Senseless with this layout!");
2143 void Paragraph::setLabelWidthString(docstring const & s)
2145 d->params_.labelWidthString(s);
2149 docstring Paragraph::expandLabel(Layout const & layout,
2150 BufferParams const & bparams) const
2152 return expandParagraphLabel(layout, bparams, true);
2156 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2157 BufferParams const & bparams, bool process_appendix) const
2159 DocumentClass const & tclass = bparams.documentClass();
2160 string const & lang = getParLanguage(bparams)->code();
2161 bool const in_appendix = process_appendix && d->params_.appendix();
2162 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2164 if (fmt.empty() && !layout.counter.empty())
2165 return tclass.counters().theCounter(layout.counter, lang);
2167 // handle 'inherited level parts' in 'fmt',
2168 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2169 size_t const i = fmt.find('@', 0);
2170 if (i != docstring::npos) {
2171 size_t const j = fmt.find('@', i + 1);
2172 if (j != docstring::npos) {
2173 docstring parent(fmt, i + 1, j - i - 1);
2174 docstring label = from_ascii("??");
2175 if (tclass.hasLayout(parent))
2176 label = expandParagraphLabel(tclass[parent], bparams,
2178 fmt = docstring(fmt, 0, i) + label
2179 + docstring(fmt, j + 1, docstring::npos);
2183 return tclass.counters().counterLabel(fmt, lang);
2187 void Paragraph::applyLayout(Layout const & new_layout)
2189 d->layout_ = &new_layout;
2190 LyXAlignment const oldAlign = d->params_.align();
2192 if (!(oldAlign & d->layout_->alignpossible)) {
2193 frontend::Alert::warning(_("Alignment not permitted"),
2194 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2195 d->params_.align(LYX_ALIGN_LAYOUT);
2200 pos_type Paragraph::beginOfBody() const
2202 return d->begin_of_body_;
2206 void Paragraph::setBeginOfBody()
2208 if (d->layout_->labeltype != LABEL_MANUAL) {
2209 d->begin_of_body_ = 0;
2213 // Unroll the first two cycles of the loop
2214 // and remember the previous character to
2215 // remove unnecessary getChar() calls
2217 pos_type end = size();
2218 bool prev_char_deleted = false;
2219 if (i < end && (!(isNewline(i) || isEnvSeparator(i)) || isDeleted(i))) {
2222 char_type previous_char = d->text_[i];
2223 if (!(isNewline(i) || isEnvSeparator(i))) {
2225 while (i < end && (previous_char != ' ' || prev_char_deleted)) {
2226 char_type temp = d->text_[i];
2227 prev_char_deleted = isDeleted(i);
2228 if (!isDeleted(i) && (isNewline(i) || isEnvSeparator(i)))
2231 previous_char = temp;
2237 d->begin_of_body_ = i;
2241 bool Paragraph::allowParagraphCustomization() const
2243 return inInset().allowParagraphCustomization();
2247 bool Paragraph::usePlainLayout() const
2249 return inInset().usePlainLayout();
2253 bool Paragraph::isPassThru() const
2255 return inInset().isPassThru() || d->layout_->pass_thru;
2260 // paragraphs inside floats need different alignment tags to avoid
2263 bool noTrivlistCentering(InsetCode code)
2265 return code == FLOAT_CODE
2266 || code == WRAP_CODE
2267 || code == CELL_CODE;
2271 string correction(string const & orig)
2273 if (orig == "flushleft")
2274 return "raggedright";
2275 if (orig == "flushright")
2276 return "raggedleft";
2277 if (orig == "center")
2283 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2284 InsetCode code, bool const lastpar, int & col)
2286 string macro = suffix + "{";
2287 if (noTrivlistCentering(code)) {
2289 // the last paragraph in non-trivlist-aligned
2290 // context is special (to avoid unwanted whitespace)
2291 if (suffix == "\\begin") {
2292 macro = "\\" + correction(env) + "{}";
2293 os << from_ascii(macro);
2294 col += macro.size();
2299 macro += correction(env);
2303 if (suffix == "\\par\\end") {
2307 os << from_ascii(macro);
2308 col += macro.size();
2309 if (suffix == "\\begin") {
2319 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2320 otexstream & os, OutputParams const & runparams) const
2325 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2326 (layout_->toggle_indent != ITOGGLE_NEVER) :
2327 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2329 if (canindent && params_.noindent() && !layout_->pass_thru) {
2330 os << "\\noindent ";
2334 LyXAlignment const curAlign = params_.align();
2336 if (curAlign == layout_->align)
2340 case LYX_ALIGN_NONE:
2341 case LYX_ALIGN_BLOCK:
2342 case LYX_ALIGN_LAYOUT:
2343 case LYX_ALIGN_SPECIAL:
2344 case LYX_ALIGN_DECIMAL:
2346 case LYX_ALIGN_LEFT:
2347 case LYX_ALIGN_RIGHT:
2348 case LYX_ALIGN_CENTER:
2349 if (runparams.moving_arg) {
2356 string const begin_tag = "\\begin";
2357 InsetCode code = ownerCode();
2358 bool const lastpar = runparams.isLastPar;
2359 // RTL in classic (PDF)LaTeX (without the Bidi package)
2360 // Luabibdi (used by LuaTeX) behaves like classic
2361 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2362 && !runparams.useBidiPackage();
2365 case LYX_ALIGN_NONE:
2366 case LYX_ALIGN_BLOCK:
2367 case LYX_ALIGN_LAYOUT:
2368 case LYX_ALIGN_SPECIAL:
2369 case LYX_ALIGN_DECIMAL:
2371 case LYX_ALIGN_LEFT: {
2373 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2374 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2376 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2378 } case LYX_ALIGN_RIGHT: {
2380 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2381 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2383 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2385 } case LYX_ALIGN_CENTER: {
2386 corrected_env(os, begin_tag, "center", code, lastpar, column);
2395 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2396 otexstream & os, OutputParams const & runparams) const
2398 LyXAlignment const curAlign = params_.align();
2400 if (curAlign == layout_->align)
2404 case LYX_ALIGN_NONE:
2405 case LYX_ALIGN_BLOCK:
2406 case LYX_ALIGN_LAYOUT:
2407 case LYX_ALIGN_SPECIAL:
2408 case LYX_ALIGN_DECIMAL:
2410 case LYX_ALIGN_LEFT:
2411 case LYX_ALIGN_RIGHT:
2412 case LYX_ALIGN_CENTER:
2413 if (runparams.moving_arg)
2418 bool output = false;
2420 string const end_tag = "\\par\\end";
2421 InsetCode code = ownerCode();
2422 bool const lastpar = runparams.isLastPar;
2423 // RTL in classic (PDF)LaTeX (without the Bidi package)
2424 // Luabibdi (used by LuaTeX) behaves like classic
2425 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2426 && !runparams.useBidiPackage();
2429 case LYX_ALIGN_NONE:
2430 case LYX_ALIGN_BLOCK:
2431 case LYX_ALIGN_LAYOUT:
2432 case LYX_ALIGN_SPECIAL:
2433 case LYX_ALIGN_DECIMAL:
2435 case LYX_ALIGN_LEFT: {
2437 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2438 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2440 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2442 } case LYX_ALIGN_RIGHT: {
2444 // Classic (PDF)LaTeX switches the left/right logic in RTL mode
2445 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2447 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2449 } case LYX_ALIGN_CENTER: {
2450 corrected_env(os, end_tag, "center", code, lastpar, col);
2455 return output || lastpar;
2459 // This one spits out the text of the paragraph
2460 void Paragraph::latex(BufferParams const & bparams,
2461 Font const & outerfont,
2463 OutputParams const & runparams,
2464 int start_pos, int end_pos, bool force) const
2466 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2468 // FIXME This check should not be needed. Perhaps issue an
2469 // error if it triggers.
2470 Layout const & style = inInset().forcePlainLayout() ?
2471 bparams.documentClass().plainLayout() : *d->layout_;
2473 if (!force && style.inpreamble)
2476 bool const allowcust = allowParagraphCustomization();
2478 // Current base font for all inherited font changes, without any
2479 // change caused by an individual character, except for the language:
2480 // It is set to the language of the first character.
2481 // As long as we are in the label, this font is the base font of the
2482 // label. Before the first body character it is set to the base font
2486 // If there is an open font-encoding changing command (script wrapper),
2487 // alien_script is set to its name
2488 string alien_script;
2491 // Maybe we have to create a optional argument.
2492 pos_type body_pos = beginOfBody();
2493 unsigned int column = 0;
2495 // If we are inside an non inheritFont() inset, the real outerfont is local_font
2496 Font const real_outerfont = (!inInset().inheritFont()
2497 && runparams.local_font != nullptr)
2498 ? Font(runparams.local_font->fontInfo()) : outerfont;
2501 // the optional argument is kept in curly brackets in
2502 // case it contains a ']'
2503 // This is not strictly needed, but if this is changed it
2504 // would be a file format change, and tex2lyx would need
2505 // to be adjusted, since it unconditionally removes the
2506 // braces when it parses \item.
2509 basefont = getLabelFont(bparams, real_outerfont);
2511 basefont = getLayoutFont(bparams, real_outerfont);
2514 // Which font is currently active?
2515 Font running_font(basefont);
2516 // Do we have an open font change?
2517 bool open_font = false;
2519 Change runningChange =
2520 runparams.inDeletedInset && !inInset().canTrackChanges()
2521 ? runparams.changeOfDeletedInset : Change(Change::UNCHANGED);
2523 Encoding const * const prev_encoding = runparams.encoding;
2525 os.texrow().start(id(), 0);
2527 // if the paragraph is empty, the loop will not be entered at all
2529 // For InTitle commands, we have already opened a group
2530 // in output_latex::TeXOnePar.
2531 if (style.isCommand() && !style.intitle) {
2535 if (!style.leftdelim().empty()) {
2536 os << style.leftdelim();
2537 column += style.leftdelim().size();
2540 column += d->startTeXParParams(bparams, os, runparams);
2543 // Whether a \par can be issued for insets typeset inline with text.
2544 // Yes if greater than 0. This has to be static.
2545 THREAD_LOCAL_STATIC int parInline = 0;
2547 for (pos_type i = 0; i < size(); ++i) {
2548 // First char in paragraph or after label?
2549 if (i == body_pos) {
2552 bool needPar = false;
2553 column += running_font.latexWriteEndChanges(
2554 os, bparams, runparams,
2555 basefont, basefont, needPar);
2558 basefont = getLayoutFont(bparams, real_outerfont);
2559 running_font = basefont;
2561 column += Changes::latexMarkChange(os, bparams,
2562 runningChange, Change(Change::UNCHANGED),
2564 runningChange = Change(Change::UNCHANGED);
2566 os << (isEnvSeparator(i) ? "}]~" : "}] ");
2569 // For InTitle commands, we have already opened a group
2570 // in output_latex::TeXOnePar.
2571 if (style.isCommand() && !style.intitle) {
2576 if (!style.leftdelim().empty()) {
2577 os << style.leftdelim();
2578 column += style.leftdelim().size();
2582 column += d->startTeXParParams(bparams, os,
2586 runparams.wasDisplayMath = runparams.inDisplayMath;
2587 runparams.inDisplayMath = false;
2588 bool deleted_display_math = false;
2589 Change const & change = runparams.inDeletedInset
2590 ? runparams.changeOfDeletedInset : lookupChange(i);
2592 char_type const c = d->text_[i];
2594 // Check whether a display math inset follows
2595 bool output_changes;
2596 if (runparams.for_searchAdv == OutputParams::NoSearch)
2597 output_changes = bparams.output_changes;
2599 output_changes = (runparams.for_searchAdv == OutputParams::SearchWithDeleted);
2601 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2603 runparams.ctObject = getInset(i)->getCtObject(runparams);
2605 InsetMath const * im = getInset(i)->asInsetMath();
2606 if (im && im->asHullInset()
2607 && im->asHullInset()->outerDisplay()) {
2608 runparams.inDisplayMath = true;
2609 // runparams.inDeletedInset will be set by
2610 // latexInset later, but we need this info
2611 // before it is called. On the other hand, we
2612 // cannot set it here because it is a counter.
2613 deleted_display_math = isDeleted(i);
2615 if (output_changes && deleted_display_math
2616 && runningChange == change
2617 && change.type == Change::DELETED
2618 && !os.afterParbreak()) {
2619 // A display math in the same paragraph follows.
2620 // We have to close and then reopen \lyxdeleted,
2621 // otherwise the math will be shifted up.
2622 OutputParams rp = runparams;
2624 bool needPar = false;
2625 column += running_font.latexWriteEndChanges(
2626 os, bparams, rp, basefont,
2630 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2631 : getLayoutFont(bparams, real_outerfont);
2632 running_font = basefont;
2633 column += Changes::latexMarkChange(os, bparams,
2634 Change(Change::INSERTED), change, rp);
2638 if (output_changes && runningChange != change) {
2639 if (!alien_script.empty()) {
2642 alien_script.clear();
2645 bool needPar = false;
2646 column += running_font.latexWriteEndChanges(
2647 os, bparams, runparams,
2648 basefont, basefont, needPar);
2651 basefont = (body_pos > i) ? getLabelFont(bparams, real_outerfont)
2652 : getLayoutFont(bparams, real_outerfont);
2653 running_font = basefont;
2654 column += Changes::latexMarkChange(os, bparams, runningChange,
2656 runningChange = change;
2659 // do not output text which is marked deleted
2660 // if change tracking output is disabled
2661 if (!output_changes && change.deleted()) {
2667 // Fully instantiated font
2668 Font current_font = getFont(bparams, i, outerfont);
2670 Font const prev_font = (i > 0) ?
2671 getFont(bparams, i - 1, outerfont)
2674 Font const last_font = running_font;
2675 bool const in_ct_deletion = (output_changes
2676 && runningChange == change
2677 && change.type == Change::DELETED
2678 && !os.afterParbreak());
2679 // Insets where font switches are used (rather than font commands)
2680 bool const fontswitch_inset =
2683 && getInset(i)->allowMultiPar()
2684 && getInset(i)->lyxCode() != ERT_CODE
2685 && getInset(i)->producesOutput();
2687 bool closeLanguage = false;
2688 bool lang_switched_at_inset = false;
2689 if (fontswitch_inset) {
2690 // Some insets cannot be inside a font change command.
2691 // However, even such insets *can* be placed in \L or \R
2692 // or their equivalents (for RTL language switches),
2693 // so we don't close the language in those cases
2694 // (= differing isRightToLeft()).
2695 // ArabTeX, though, doesn't seem to handle this special behavior.
2696 closeLanguage = basefont.isRightToLeft() == current_font.isRightToLeft()
2697 || basefont.language()->lang() == "arabic_arabtex"
2698 || current_font.language()->lang() == "arabic_arabtex";
2699 // We need to check prev_font as language changes directly at inset
2700 // will only be started inside the inset.
2701 lang_switched_at_inset = prev_font.language() != current_font.language();
2704 // Do we need to close the previous font?
2705 bool langClosed = false;
2707 ((current_font != running_font
2708 || current_font.language() != running_font.language())
2709 || (fontswitch_inset
2710 && (current_font == prev_font))))
2712 // ensure there is no open script-wrapper
2713 if (!alien_script.empty()) {
2716 alien_script.clear();
2718 if (in_ct_deletion) {
2719 // We have to close and then reopen \lyxdeleted,
2720 // as strikeout needs to be on lowest level.
2725 // Force language closing
2726 current_font.setLanguage(basefont.language());
2727 Font const nextfont = (i == body_pos-1) ? basefont : current_font;
2728 bool needPar = false;
2729 column += running_font.latexWriteEndChanges(
2730 os, bparams, runparams, basefont,
2732 if (in_ct_deletion) {
2733 // We have to close and then reopen \lyxdeleted,
2734 // as strikeout needs to be on lowest level.
2735 OutputParams rp = runparams;
2736 column += Changes::latexMarkChange(os, bparams,
2737 Change(Change::UNCHANGED), Change(Change::DELETED), rp);
2740 // Has the language been closed in the latexWriteEndChanges() call above?
2741 langClosed = running_font.language() != basefont.language()
2742 && running_font.language() != nextfont.language()
2743 && (running_font.language()->encoding()->package() != Encoding::CJK);
2744 running_font = basefont;
2747 // if necessary, close language environment before opening CJK
2748 string const running_lang = running_font.language()->babel();
2749 string const lang_end_command = lyxrc.language_command_end;
2750 if (!lang_end_command.empty() && !bparams.useNonTeXFonts
2751 && !running_lang.empty()
2752 && running_lang == openLanguageName()
2753 && current_font.language()->encoding()->package() == Encoding::CJK) {
2754 string end_tag = subst(lang_end_command, "$$lang", running_lang);
2755 os << from_ascii(end_tag);
2756 column += end_tag.length();
2760 // Switch file encoding if necessary (and allowed)
2761 if ((!fontswitch_inset || closeLanguage)
2762 && !runparams.pass_thru && !style.pass_thru &&
2763 runparams.encoding->package() != Encoding::none &&
2764 current_font.language()->encoding()->package() != Encoding::none) {
2765 pair<bool, int> const enc_switch =
2766 switchEncoding(os.os(), bparams, runparams,
2767 *(current_font.language()->encoding()));
2768 if (enc_switch.first) {
2769 column += enc_switch.second;
2770 runparams.encoding = current_font.language()->encoding();
2774 // A display math inset inside an ulem command will be output
2775 // as a box of width \linewidth, so we have to either disable
2776 // indentation if the inset starts a paragraph, or start a new
2777 // line to accommodate such box. This has to be done before
2778 // writing any font changing commands.
2779 if (runparams.inDisplayMath && !deleted_display_math
2780 && runparams.inulemcmd) {
2781 if (os.afterParbreak())
2787 // Do we need to change font?
2788 if ((current_font != running_font ||
2789 current_font.language() != running_font.language())
2790 && i != body_pos - 1)
2792 if (!fontswitch_inset) {
2793 if (in_ct_deletion) {
2794 // We have to close and then reopen \lyxdeleted,
2795 // as strikeout needs to be on lowest level.
2796 OutputParams rp = runparams;
2797 bool needPar = false;
2798 column += running_font.latexWriteEndChanges(
2799 os, bparams, rp, basefont,
2804 otexstringstream ots;
2805 InsetText const * textinset = inInset().asInsetText();
2806 bool const cprotect = textinset
2807 ? textinset->hasCProtectContent(runparams.moving_arg)
2808 && !textinset->text().isMainText()
2810 column += current_font.latexWriteStartChanges(ots, bparams,
2811 runparams, basefont, last_font, false,
2813 // Check again for display math in ulem commands as a
2814 // font change may also occur just before a math inset.
2815 if (runparams.inDisplayMath && !deleted_display_math
2816 && runparams.inulemcmd) {
2817 if (os.afterParbreak())
2822 running_font = current_font;
2824 docstring fontchange = ots.str();
2826 // check whether the fontchange ends with a \\textcolor
2827 // modifier and the text starts with a space. If so we
2828 // need to add } in order to prevent \\textcolor from gobbling
2829 // the space (bug 4473).
2830 docstring const last_modifier = rsplit(fontchange, '\\');
2831 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2832 os << from_ascii("{}");
2833 else if (ots.terminateCommand())
2835 if (in_ct_deletion) {
2836 // We have to close and then reopen \lyxdeleted,
2837 // as strikeout needs to be on lowest level.
2838 OutputParams rp = runparams;
2839 column += Changes::latexMarkChange(os, bparams,
2840 Change(Change::UNCHANGED), change, rp);
2843 running_font = current_font;
2844 open_font = !langClosed;
2848 // FIXME: think about end_pos implementation...
2849 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2850 // FIXME: integrate this case in latexSpecialChar
2851 // Do not print the separation of the optional argument
2852 // if style.pass_thru is false. This works because
2853 // latexSpecialChar ignores spaces if
2854 // style.pass_thru is false.
2855 if (i != body_pos - 1) {
2856 if (d->simpleTeXBlanks(bparams, runparams, os,
2857 i, column, current_font, style)) {
2858 // A surrogate pair was output. We
2859 // must not call latexSpecialChar
2860 // in this iteration, since it would output
2861 // the combining character again.
2868 OutputParams rp = runparams;
2869 rp.free_spacing = style.free_spacing;
2870 rp.local_font = ¤t_font;
2871 rp.intitle = style.intitle;
2873 // Two major modes: LaTeX or plain
2874 // Handle here those cases common to both modes
2875 // and then split to handle the two modes separately.
2876 if (c == META_INSET) {
2877 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2878 // Greyedout notes and, in general, all insets
2879 // with InsetLayout::isDisplay() == false,
2880 // are typeset inline with the text. So, we
2881 // can add a \par to the last paragraph of
2882 // such insets only if nothing else follows.
2883 bool incremented = false;
2884 Inset const * inset = getInset(i);
2885 InsetText const * textinset = inset
2886 ? inset->asInsetText()
2888 if (i + 1 == size() && textinset
2889 && !inset->getLayout().isDisplay()) {
2890 ParagraphList const & pars =
2891 textinset->text().paragraphs();
2892 pit_type const pit = pars.size() - 1;
2893 Font const lastfont =
2894 pit < 0 || pars[pit].empty()
2895 ? pars[pit].getLayoutFont(
2898 : pars[pit].getFont(bparams,
2899 pars[pit].size() - 1,
2901 if (lastfont.fontInfo().size() !=
2902 basefont.fontInfo().size()) {
2907 // We need to restore parts of this after insets with
2908 // allowMultiPar() true
2909 Font const save_basefont = basefont;
2910 d->latexInset(bparams, os, rp, running_font,
2911 basefont, real_outerfont, open_font,
2912 runningChange, style, i, column, fontswitch_inset,
2913 closeLanguage, lang_switched_at_inset);
2914 if (fontswitch_inset) {
2916 bool needPar = false;
2917 column += running_font.latexWriteEndChanges(
2918 os, bparams, runparams,
2919 basefont, basefont, needPar);
2922 basefont.fontInfo().setSize(save_basefont.fontInfo().size());
2923 basefont.fontInfo().setFamily(save_basefont.fontInfo().family());
2924 basefont.fontInfo().setSeries(save_basefont.fontInfo().series());
2929 if (runparams.ctObject == CtObject::DisplayObject
2930 || runparams.ctObject == CtObject::UDisplayObject) {
2931 // Close \lyx*deleted and force its
2932 // reopening (if needed)
2935 runningChange = Change(Change::UNCHANGED);
2936 runparams.ctObject = CtObject::Normal;
2939 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2940 if (!bparams.useNonTeXFonts)
2941 script = Encodings::isKnownScriptChar(c);
2942 if (script != alien_script) {
2943 if (!alien_script.empty()) {
2945 alien_script.clear();
2947 string fontenc = running_font.language()->fontenc(bparams);
2949 && !Encodings::fontencSupportsScript(fontenc, script)) {
2950 column += script.length() + 2;
2951 os << "\\" << script << "{";
2952 alien_script = script;
2956 d->latexSpecialChar(os, bparams, rp, running_font,
2957 alien_script, style, i, end_pos, column);
2958 } catch (EncodingException & e) {
2959 if (runparams.dryrun) {
2960 os << "<" << _("LyX Warning: ")
2961 << _("uncodable character") << " '";
2965 // add location information and throw again.
2973 // Set the encoding to that returned from latexSpecialChar (see
2974 // comment for encoding member in OutputParams.h)
2975 runparams.encoding = rp.encoding;
2977 // Also carry on the info on a closed ulem command for insets
2978 // such as Note that do not produce any output, so that no
2979 // command is ever executed but its opening was recorded.
2980 runparams.inulemcmd = rp.inulemcmd;
2982 // These need to be passed upstream as well
2983 runparams.need_maketitle = rp.need_maketitle;
2984 runparams.have_maketitle = rp.have_maketitle;
2986 // And finally, pass the post_macros upstream
2987 runparams.post_macro = rp.post_macro;
2990 // Close wrapper for alien script
2991 if (!alien_script.empty()) {
2993 alien_script.clear();
2996 Font const font = empty()
2997 ? getLayoutFont(bparams, real_outerfont)
2998 : getFont(bparams, size() - 1, real_outerfont);
3000 InsetText const * textinset = inInset().asInsetText();
3002 bool const maintext = textinset
3003 ? textinset->text().isMainText()
3006 size_t const numpars = textinset
3007 ? textinset->text().paragraphs().size()
3010 bool needPar = false;
3012 if (style.resfont.size() != font.fontInfo().size()
3013 && (!runparams.isLastPar || maintext
3014 || (numpars > 1 && d->ownerCode() != CELL_CODE
3015 && (inInset().getLayout().isDisplay()
3017 && !style.isCommand()) {
3021 // If we have an open font definition, we have to close it
3023 // Make sure that \\par is done with the font of the last
3024 // character if this has another size as the default.
3025 // This is necessary because LaTeX (and LyX on the screen)
3026 // calculates the space between the baselines according
3027 // to this font. (Matthias)
3029 // We must not change the font for the last paragraph
3030 // of non-multipar insets, tabular cells or commands,
3031 // since this produces unwanted whitespace.
3032 #ifdef FIXED_LANGUAGE_END_DETECTION
3034 running_font.latexWriteEndChanges(os, bparams,
3035 runparams, basefont,
3036 next_->getFont(bparams, 0, outerfont),
3039 running_font.latexWriteEndChanges(os, bparams,
3040 runparams, basefont, basefont, needPar);
3043 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
3044 //FIXME: there as we start another \selectlanguage with the next paragraph if
3045 //FIXME: we are in need of this. This should be fixed sometime (Jug)
3046 running_font.latexWriteEndChanges(os, bparams, runparams,
3047 basefont, basefont, needPar);
3051 // The \par could not be inserted at the same nesting
3052 // level of the font size change, so do it now.
3053 os << "{\\" << font.latexSize() << "\\par}";
3056 if (!runparams.inDeletedInset || inInset().canTrackChanges())
3057 column += Changes::latexMarkChange(os, bparams, runningChange,
3058 Change(Change::UNCHANGED), runparams);
3060 // Needed if there is an optional argument but no contents.
3061 if (body_pos > 0 && body_pos == size()) {
3065 if (!style.rightdelim().empty()) {
3066 os << style.rightdelim();
3067 column += style.rightdelim().size();
3070 if (allowcust && d->endTeXParParams(bparams, os, runparams)
3071 && runparams.encoding != prev_encoding) {
3072 runparams.encoding = prev_encoding;
3073 os << setEncoding(prev_encoding->iconvName());
3076 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
3080 bool Paragraph::emptyTag() const
3082 for (pos_type i = 0; i < size(); ++i) {
3083 if (Inset const * inset = getInset(i)) {
3084 InsetCode lyx_code = inset->lyxCode();
3085 // FIXME testing like that is wrong. What is
3087 if (lyx_code != TOC_CODE &&
3088 lyx_code != INCLUDE_CODE &&
3089 lyx_code != GRAPHICS_CODE &&
3090 lyx_code != ERT_CODE &&
3091 lyx_code != LISTINGS_CODE &&
3092 lyx_code != FLOAT_CODE &&
3093 lyx_code != TABULAR_CODE) {
3097 char_type c = d->text_[i];
3098 if (c != ' ' && c != '\t')
3106 string Paragraph::getID(Buffer const &, OutputParams const &)
3109 for (pos_type i = 0; i < size(); ++i) {
3110 if (Inset const * inset = getInset(i)) {
3111 InsetCode lyx_code = inset->lyxCode();
3112 if (lyx_code == LABEL_CODE) {
3113 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
3114 docstring const & id = il->getParam("name");
3115 return "id='" + to_utf8(xml::cleanID(id)) + "'";
3123 pos_type Paragraph::firstWordDocBook(XMLStream & xs, OutputParams const & runparams) const
3126 for (i = 0; i < size(); ++i) {
3127 if (Inset const * inset = getInset(i)) {
3128 inset->docbook(xs, runparams);
3130 char_type c = d->text_[i];
3140 pos_type Paragraph::firstWordLyXHTML(XMLStream & xs, OutputParams const & runparams)
3144 for (i = 0; i < size(); ++i) {
3145 if (Inset const * inset = getInset(i)) {
3146 inset->xhtml(xs, runparams);
3148 char_type c = d->text_[i];
3158 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3161 pos_type size = text_.size();
3162 for (pos_type i = initial; i < size; ++i) {
3163 Font font = owner_->getFont(buf.params(), i, outerfont);
3164 if (text_[i] == META_INSET)
3166 if (i != initial && font != font_old)
3177 void doFontSwitchDocBook(vector<xml::FontTag> & tagsToOpen,
3178 vector<xml::EndFontTag> & tagsToClose,
3179 bool & flag, FontState curstate, xml::FontTypes type)
3181 if (curstate == FONT_ON) {
3182 tagsToOpen.push_back(docbookStartFontTag(type));
3185 tagsToClose.push_back(docbookEndFontTag(type));
3190 class OptionalFontType {
3195 OptionalFontType(): ft(xml::FT_EMPH), has_value(false) {} // A possible value at random for ft.
3196 OptionalFontType(xml::FontTypes ft): ft(ft), has_value(true) {}
3199 OptionalFontType fontShapeToXml(FontShape fs)
3203 return {xml::FT_ITALIC};
3205 return {xml::FT_SLANTED};
3206 case SMALLCAPS_SHAPE:
3207 return {xml::FT_SMALLCAPS};
3212 // the other tags are for internal use
3218 OptionalFontType fontFamilyToXml(FontFamily fm)
3222 return {xml::FT_ROMAN};
3224 return {xml::FT_SANS};
3225 case TYPEWRITER_FAMILY:
3226 return {xml::FT_TYPE};
3227 case INHERIT_FAMILY:
3230 // the other tags are for internal use
3236 OptionalFontType fontSizeToXml(FontSize fs)
3240 return {xml::FT_SIZE_TINY};
3242 return {xml::FT_SIZE_SCRIPT};
3244 return {xml::FT_SIZE_FOOTNOTE};
3246 return {xml::FT_SIZE_SMALL};
3248 return {xml::FT_SIZE_LARGE};
3250 return {xml::FT_SIZE_LARGER};
3252 return {xml::FT_SIZE_LARGEST};
3254 return {xml::FT_SIZE_HUGE};
3256 return {xml::FT_SIZE_HUGER};
3258 return {xml::FT_SIZE_INCREASE};
3260 return {xml::FT_SIZE_DECREASE};
3265 // the other tags are for internal use
3271 struct DocBookFontState
3273 FontShape curr_fs = INHERIT_SHAPE;
3274 FontFamily curr_fam = INHERIT_FAMILY;
3275 FontSize curr_size = INHERIT_SIZE;
3277 // track whether we have opened these tags
3278 bool emph_flag = false;
3279 bool bold_flag = false;
3280 bool noun_flag = false;
3281 bool ubar_flag = false;
3282 bool dbar_flag = false;
3283 bool sout_flag = false;
3284 bool xout_flag = false;
3285 bool wave_flag = false;
3287 bool shap_flag = false;
3289 bool faml_flag = false;
3291 bool size_flag = false;
3294 std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>> computeDocBookFontSwitch(FontInfo const & font_old,
3296 std::string const & default_family,
3297 DocBookFontState & fs)
3299 vector<xml::FontTag> tagsToOpen;
3300 vector<xml::EndFontTag> tagsToClose;
3303 FontState curstate = font.fontInfo().emph();
3304 if (font_old.emph() != curstate)
3305 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.emph_flag, curstate, xml::FT_EMPH);
3308 curstate = font.fontInfo().noun();
3309 if (font_old.noun() != curstate)
3310 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.noun_flag, curstate, xml::FT_NOUN);
3313 curstate = font.fontInfo().underbar();
3314 if (font_old.underbar() != curstate)
3315 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.ubar_flag, curstate, xml::FT_UBAR);
3318 curstate = font.fontInfo().strikeout();
3319 if (font_old.strikeout() != curstate)
3320 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.sout_flag, curstate, xml::FT_SOUT);
3323 curstate = font.fontInfo().xout();
3324 if (font_old.xout() != curstate)
3325 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.xout_flag, curstate, xml::FT_XOUT);
3328 curstate = font.fontInfo().uuline();
3329 if (font_old.uuline() != curstate)
3330 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.dbar_flag, curstate, xml::FT_DBAR);
3333 curstate = font.fontInfo().uwave();
3334 if (font_old.uwave() != curstate)
3335 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.wave_flag, curstate, xml::FT_WAVE);
3338 // a little hackish, but allows us to reuse what we have.
3339 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3340 if (font_old.series() != font.fontInfo().series())
3341 doFontSwitchDocBook(tagsToOpen, tagsToClose, fs.bold_flag, curstate, xml::FT_BOLD);
3344 fs.curr_fs = font.fontInfo().shape();
3345 FontShape old_fs = font_old.shape();
3346 if (old_fs != fs.curr_fs) {
3348 OptionalFontType tag = fontShapeToXml(old_fs);
3350 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3351 fs.shap_flag = false;
3354 OptionalFontType tag = fontShapeToXml(fs.curr_fs);
3356 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3360 fs.curr_fam = font.fontInfo().family();
3361 FontFamily old_fam = font_old.family();
3362 if (old_fam != fs.curr_fam) {
3364 OptionalFontType tag = fontFamilyToXml(old_fam);
3366 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3367 fs.faml_flag = false;
3369 switch (fs.curr_fam) {
3371 // we will treat a "default" font family as roman, since we have
3372 // no other idea what to do.
3373 if (default_family != "rmdefault" && default_family != "default") {
3374 tagsToOpen.push_back(docbookStartFontTag(xml::FT_ROMAN));
3375 fs.faml_flag = true;
3379 if (default_family != "sfdefault") {
3380 tagsToOpen.push_back(docbookStartFontTag(xml::FT_SANS));
3381 fs.faml_flag = true;
3384 case TYPEWRITER_FAMILY:
3385 if (default_family != "ttdefault") {
3386 tagsToOpen.push_back(docbookStartFontTag(xml::FT_TYPE));
3387 fs.faml_flag = true;
3390 case INHERIT_FAMILY:
3393 // the other tags are for internal use
3400 fs.curr_size = font.fontInfo().size();
3401 FontSize old_size = font_old.size();
3402 if (old_size != fs.curr_size) {
3404 OptionalFontType tag = fontSizeToXml(old_size);
3406 tagsToClose.push_back(docbookEndFontTag(tag.ft));
3407 fs.size_flag = false;
3410 OptionalFontType tag = fontSizeToXml(fs.curr_size);
3411 if (tag.has_value) {
3412 tagsToOpen.push_back(docbookStartFontTag(tag.ft));
3413 fs.size_flag = true;
3417 return std::tuple<vector<xml::FontTag>, vector<xml::EndFontTag>>(tagsToOpen, tagsToClose);
3420 } // anonymous namespace
3423 std::tuple<std::vector<docstring>, std::vector<docstring>, std::vector<docstring>>
3424 Paragraph::simpleDocBookOnePar(Buffer const & buf,
3425 OutputParams const & runparams,
3426 Font const & outerfont,
3429 bool ignore_fonts) const
3431 std::vector<docstring> prependedParagraphs;
3432 std::vector<docstring> generatedParagraphs;
3433 std::vector<docstring> appendedParagraphs;
3434 odocstringstream os;
3436 // If there is an argument that must be output before the main tag, do it before handling the rest of the paragraph.
3437 // Also tag all arguments that shouldn't go in the main content right now, so that they are never generated at the
3439 OutputParams rp = runparams;
3440 for (pos_type i = initial; i < size(); ++i) {
3441 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3442 const InsetArgument * arg = getInset(i)->asInsetArgument();
3443 if (arg->docbookargumentbeforemaintag()) {
3444 auto xs_local = XMLStream(os);
3445 arg->docbook(xs_local, rp);
3447 prependedParagraphs.push_back(os.str());
3448 os.str(from_ascii(""));
3450 rp.docbook_prepended_arguments.insert(arg);
3451 } else if (arg->docbookargumentaftermaintag()) {
3452 rp.docbook_appended_arguments.insert(arg);
3457 // State variables for the main loop.
3458 auto xs = new XMLStream(os); // XMLStream has no copy constructor: to create a new object, the only solution
3459 // is to hold a pointer to the XMLStream (xs = XMLStream(os) is not allowed once the first object is built).
3460 std::vector<char_type> delayedChars; // When a font tag ends with a space, output it after the closing font tag.
3461 // This requires to store delayed characters at some point.
3463 DocBookFontState fs; // Track whether we have opened font tags
3464 DocBookFontState old_fs = fs;
3466 Layout const & style = *d->layout_;
3467 FontInfo font_old = style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3468 string const default_family = buf.masterBuffer()->params().fonts_default_family;
3470 vector<xml::FontTag> tagsToOpen;
3471 vector<xml::EndFontTag> tagsToClose;
3473 // Parsing main loop.
3474 for (pos_type i = initial; i < size(); ++i) {
3475 bool ignore_fonts_i = ignore_fonts
3476 || style.docbooknofontinside()
3477 || (getInset(i) && getInset(i)->getLayout().docbooknofontinside());
3479 // Don't show deleted material in the output.
3483 // If this is an InsetNewline, generate a new paragraph. Also reset the fonts, so that tags are closed in
3485 if (getInset(i) && getInset(i)->lyxCode() == NEWLINE_CODE) {
3486 if (!ignore_fonts_i)
3487 xs->closeFontTags();
3489 // Output one paragraph (i.e. one string entry in generatedParagraphs).
3490 generatedParagraphs.push_back(os.str());
3492 // Create a new XMLStream for the new paragraph, completely independent from the previous one. This implies
3493 // that the string stream must be reset.
3494 os.str(from_ascii(""));
3496 xs = new XMLStream(os);
3498 // Restore the fonts for the new paragraph, so that the right tags are opened for the new entry.
3499 if (!ignore_fonts_i) {
3500 font_old = outerfont.fontInfo();
3505 // Determine which tags should be opened or closed regarding fonts.
3506 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3507 tie(tagsToOpen, tagsToClose) = computeDocBookFontSwitch(font_old, font, default_family, fs);
3509 if (!ignore_fonts_i) {
3510 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3511 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3512 for (; cit != cen; ++cit)
3516 // Deal with the delayed characters *after* closing font tags.
3517 if (!delayedChars.empty()) {
3518 for (char_type c: delayedChars)
3520 delayedChars.clear();
3523 if (!ignore_fonts_i) {
3524 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3525 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3526 for (; sit != sen; ++sit)
3529 tagsToClose.clear();
3533 // Finally, write the next character or inset.
3534 if (Inset const * inset = getInset(i)) {
3535 bool inset_is_argument_elsewhere = getInset(i)->asInsetArgument() &&
3536 rp.docbook_appended_arguments.find(inset->asInsetArgument()) != rp.docbook_appended_arguments.end() &&
3537 rp.docbook_prepended_arguments.find(inset->asInsetArgument()) != rp.docbook_prepended_arguments.end();
3539 if ((!rp.for_toc || inset->isInToc()) && !inset_is_argument_elsewhere) {
3540 // Arguments may need to be output
3541 OutputParams np = rp;
3542 np.local_font = &font;
3544 // TODO: special case will bite here.
3545 np.docbook_in_par = true;
3546 inset->docbook(*xs, np);
3549 char_type c = getUChar(buf.masterBuffer()->params(), rp, i);
3550 if (lyx::isSpace(c) && !ignore_fonts)
3551 delayedChars.push_back(c);
3555 font_old = font.fontInfo();
3558 // FIXME, this code is just imported from XHTML
3559 // I'm worried about what happens if a branch, say, is itself
3560 // wrapped in some font stuff. I think that will not work.
3562 xs->closeFontTags();
3564 // Deal with the delayed characters *after* closing font tags.
3565 if (!delayedChars.empty())
3566 for (char_type c: delayedChars)
3569 // In listings, new lines (i.e. \n characters in the output) are very important. Avoid generating one for the
3570 // last line to get a clean output.
3571 if (rp.docbook_in_listing && !is_last_par)
3574 // Finalise the last (and most likely only) paragraph.
3575 generatedParagraphs.push_back(os.str());
3576 os.str(from_ascii(""));
3579 // If there is an argument that must be output after the main tag, do it after handling the rest of the paragraph.
3580 for (pos_type i = initial; i < size(); ++i) {
3581 if (getInset(i) && getInset(i)->lyxCode() == ARG_CODE) {
3582 const InsetArgument * arg = getInset(i)->asInsetArgument();
3583 if (arg->docbookargumentaftermaintag()) {
3584 // Don't use rp, as this argument would not generate anything.
3585 auto xs_local = XMLStream(os);
3586 arg->docbook(xs_local, runparams);
3588 appendedParagraphs.push_back(os.str());
3589 os.str(from_ascii(""));
3594 return std::make_tuple(prependedParagraphs, generatedParagraphs, appendedParagraphs);
3600 void doFontSwitchXHTML(vector<xml::FontTag> & tagsToOpen,
3601 vector<xml::EndFontTag> & tagsToClose,
3602 bool & flag, FontState curstate, xml::FontTypes type)
3604 if (curstate == FONT_ON) {
3605 tagsToOpen.push_back(xhtmlStartFontTag(type));
3608 tagsToClose.push_back(xhtmlEndFontTag(type));
3613 } // anonymous namespace
3616 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3618 OutputParams const & runparams,
3619 Font const & outerfont,
3620 bool start_paragraph, bool close_paragraph,
3621 pos_type initial) const
3625 // track whether we have opened these tags
3626 bool emph_flag = false;
3627 bool bold_flag = false;
3628 bool noun_flag = false;
3629 bool ubar_flag = false;
3630 bool dbar_flag = false;
3631 bool sout_flag = false;
3632 bool xout_flag = false;
3633 bool wave_flag = false;
3635 bool shap_flag = false;
3637 bool faml_flag = false;
3639 bool size_flag = false;
3641 Layout const & style = *d->layout_;
3643 if (start_paragraph)
3644 xs.startDivision(allowEmpty());
3647 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3649 FontShape curr_fs = INHERIT_SHAPE;
3650 FontFamily curr_fam = INHERIT_FAMILY;
3651 FontSize curr_size = INHERIT_SIZE;
3653 string const default_family =
3654 buf.masterBuffer()->params().fonts_default_family;
3656 vector<xml::FontTag> tagsToOpen;
3657 vector<xml::EndFontTag> tagsToClose;
3659 // parsing main loop
3660 for (pos_type i = initial; i < size(); ++i) {
3661 // let's not show deleted material in the output
3665 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3668 FontState curstate = font.fontInfo().emph();
3669 if (font_old.emph() != curstate)
3670 doFontSwitchXHTML(tagsToOpen, tagsToClose, emph_flag, curstate, xml::FT_EMPH);
3673 curstate = font.fontInfo().noun();
3674 if (font_old.noun() != curstate)
3675 doFontSwitchXHTML(tagsToOpen, tagsToClose, noun_flag, curstate, xml::FT_NOUN);
3678 curstate = font.fontInfo().underbar();
3679 if (font_old.underbar() != curstate)
3680 doFontSwitchXHTML(tagsToOpen, tagsToClose, ubar_flag, curstate, xml::FT_UBAR);
3683 curstate = font.fontInfo().strikeout();
3684 if (font_old.strikeout() != curstate)
3685 doFontSwitchXHTML(tagsToOpen, tagsToClose, sout_flag, curstate, xml::FT_SOUT);
3688 curstate = font.fontInfo().xout();
3689 if (font_old.xout() != curstate)
3690 doFontSwitchXHTML(tagsToOpen, tagsToClose, xout_flag, curstate, xml::FT_XOUT);
3693 curstate = font.fontInfo().uuline();
3694 if (font_old.uuline() != curstate)
3695 doFontSwitchXHTML(tagsToOpen, tagsToClose, dbar_flag, curstate, xml::FT_DBAR);
3698 curstate = font.fontInfo().uwave();
3699 if (font_old.uwave() != curstate)
3700 doFontSwitchXHTML(tagsToOpen, tagsToClose, wave_flag, curstate, xml::FT_WAVE);
3703 // a little hackish, but allows us to reuse what we have.
3704 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3705 if (font_old.series() != font.fontInfo().series())
3706 doFontSwitchXHTML(tagsToOpen, tagsToClose, bold_flag, curstate, xml::FT_BOLD);
3709 curr_fs = font.fontInfo().shape();
3710 FontShape old_fs = font_old.shape();
3711 if (old_fs != curr_fs) {
3715 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ITALIC));
3718 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SLANTED));
3720 case SMALLCAPS_SHAPE:
3721 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SMALLCAPS));
3727 // the other tags are for internal use
3735 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ITALIC));
3739 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SLANTED));
3742 case SMALLCAPS_SHAPE:
3743 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SMALLCAPS));
3750 // the other tags are for internal use
3757 curr_fam = font.fontInfo().family();
3758 FontFamily old_fam = font_old.family();
3759 if (old_fam != curr_fam) {
3763 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_ROMAN));
3766 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SANS));
3768 case TYPEWRITER_FAMILY:
3769 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_TYPE));
3771 case INHERIT_FAMILY:
3774 // the other tags are for internal use
3782 // we will treat a "default" font family as roman, since we have
3783 // no other idea what to do.
3784 if (default_family != "rmdefault" && default_family != "default") {
3785 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_ROMAN));
3790 if (default_family != "sfdefault") {
3791 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SANS));
3795 case TYPEWRITER_FAMILY:
3796 if (default_family != "ttdefault") {
3797 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_TYPE));
3801 case INHERIT_FAMILY:
3804 // the other tags are for internal use
3811 curr_size = font.fontInfo().size();
3812 FontSize old_size = font_old.size();
3813 if (old_size != curr_size) {
3817 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_TINY));
3820 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SCRIPT));
3823 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_FOOTNOTE));
3826 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_SMALL));
3829 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGE));
3832 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGER));
3835 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_LARGEST));
3838 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGE));
3841 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_HUGER));
3844 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_INCREASE));
3847 tagsToClose.emplace_back(xhtmlEndFontTag(xml::FT_SIZE_DECREASE));
3853 // the other tags are for internal use
3859 switch (curr_size) {
3861 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_TINY));
3865 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SCRIPT));
3869 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_FOOTNOTE));
3873 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_SMALL));
3877 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGE));
3881 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGER));
3885 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_LARGEST));
3889 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGE));
3893 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_HUGER));
3897 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_INCREASE));
3901 tagsToOpen.emplace_back(xhtmlStartFontTag(xml::FT_SIZE_DECREASE));
3908 // the other tags are for internal use
3915 // Other such tags? What about the other text ranges?
3917 vector<xml::EndFontTag>::const_iterator cit = tagsToClose.begin();
3918 vector<xml::EndFontTag>::const_iterator cen = tagsToClose.end();
3919 for (; cit != cen; ++cit)
3922 vector<xml::FontTag>::const_iterator sit = tagsToOpen.begin();
3923 vector<xml::FontTag>::const_iterator sen = tagsToOpen.end();
3924 for (; sit != sen; ++sit)
3927 tagsToClose.clear();
3930 Inset const * inset = getInset(i);
3932 if (!runparams.for_toc || inset->isInToc()) {
3933 OutputParams np = runparams;
3934 np.local_font = &font;
3935 // If the paragraph has size 1, then we are in the "special
3936 // case" where we do not output the containing paragraph info
3937 if (!inset->getLayout().htmlisblock() && size() != 1)
3938 np.html_in_par = true;
3939 retval += inset->xhtml(xs, np);
3942 char_type c = getUChar(buf.masterBuffer()->params(),
3944 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3945 xs << XMLStream::ESCAPE_NONE << " ";
3949 font_old = font.fontInfo();
3953 // I'm worried about what happens if a branch, say, is itself
3954 // wrapped in some font stuff. I think that will not work.
3956 if (close_paragraph)
3963 bool Paragraph::isHfill(pos_type pos) const
3965 Inset const * inset = getInset(pos);
3966 return inset && inset->isHfill();
3970 bool Paragraph::isNewline(pos_type pos) const
3972 // U+2028 LINE SEPARATOR
3973 // U+2029 PARAGRAPH SEPARATOR
3974 char_type const c = d->text_[pos];
3975 if (c == 0x2028 || c == 0x2029)
3977 Inset const * inset = getInset(pos);
3978 return inset && inset->lyxCode() == NEWLINE_CODE;
3982 bool Paragraph::isEnvSeparator(pos_type pos) const
3984 Inset const * inset = getInset(pos);
3985 return inset && inset->lyxCode() == SEPARATOR_CODE;
3989 bool Paragraph::isLineSeparator(pos_type pos) const
3991 char_type const c = d->text_[pos];
3992 if (isLineSeparatorChar(c))
3994 Inset const * inset = getInset(pos);
3995 return inset && inset->isLineSeparator();
3999 bool Paragraph::isWordSeparator(pos_type pos, bool const ignore_deleted) const
4003 if (ignore_deleted && isDeleted(pos))
4005 if (Inset const * inset = getInset(pos))
4006 return !inset->isLetter();
4007 // if we have a hard hyphen (no en- or emdash) or apostrophe
4008 // we pass this to the spell checker
4009 // FIXME: this method is subject to change, visit
4010 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
4011 // to get an impression how complex this is.
4012 if (isHardHyphenOrApostrophe(pos))
4014 char_type const c = d->text_[pos];
4015 // We want to pass the escape chars to the spellchecker
4016 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
4017 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
4021 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
4023 pos_type const psize = size();
4026 char_type const c = d->text_[pos];
4027 if (c != '-' && c != '\'')
4029 pos_type nextpos = pos + 1;
4030 pos_type prevpos = pos > 0 ? pos - 1 : 0;
4031 if ((nextpos == psize || isSpace(nextpos))
4032 && (pos == 0 || isSpace(prevpos)))
4038 bool Paragraph::needsCProtection(bool const fragile) const
4040 // first check the layout of the paragraph, but only in insets
4041 InsetText const * textinset = inInset().asInsetText();
4042 bool const maintext = textinset
4043 ? textinset->text().isMainText()
4046 if (!maintext && layout().needcprotect) {
4047 // Environments need cprotection regardless the content
4048 if (layout().latextype == LATEX_ENVIRONMENT)
4051 // Commands need cprotection if they contain specific chars
4052 int const nchars_escape = 9;
4053 static char_type const chars_escape[nchars_escape] = {
4054 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
4056 docstring const pars = asString();
4057 for (int k = 0; k < nchars_escape; k++) {
4058 if (contains(pars, chars_escape[k]))
4063 // now check whether we have insets that need cprotection
4064 pos_type size = pos_type(d->text_.size());
4065 for (pos_type i = 0; i < size; ++i) {
4068 Inset const * ins = getInset(i);
4069 if (ins->needsCProtection(maintext, fragile))
4071 // Now check math environments
4072 InsetMath const * im = getInset(i)->asInsetMath();
4073 if (!im || im->cell(0).empty())
4075 switch(im->cell(0)[0]->lyxCode()) {
4076 case MATH_AMSARRAY_CODE:
4077 case MATH_SUBSTACK_CODE:
4079 case MATH_XYMATRIX_CODE:
4080 // these need cprotection
4091 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
4093 return d->speller_state_.getRange(pos);
4097 bool Paragraph::isChar(pos_type pos) const
4099 if (Inset const * inset = getInset(pos))
4100 return inset->isChar();
4101 char_type const c = d->text_[pos];
4102 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
4106 bool Paragraph::isSpace(pos_type pos) const
4108 if (Inset const * inset = getInset(pos))
4109 return inset->isSpace();
4110 char_type const c = d->text_[pos];
4111 return lyx::isSpace(c);
4116 Paragraph::getParLanguage(BufferParams const & bparams) const
4119 return getFirstFontSettings(bparams).language();
4120 // FIXME: we should check the prev par as well (Lgb)
4121 return bparams.language;
4125 bool Paragraph::isRTL(BufferParams const & bparams) const
4127 return getParLanguage(bparams)->rightToLeft()
4128 && !inInset().getLayout().forceLTR();
4132 void Paragraph::changeLanguage(BufferParams const & bparams,
4133 Language const * from, Language const * to)
4135 // change language including dummy font change at the end
4136 for (pos_type i = 0; i <= size(); ++i) {
4137 Font font = getFontSettings(bparams, i);
4138 if (font.language() == from) {
4139 font.setLanguage(to);
4141 d->requestSpellCheck(i);
4147 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
4149 Language const * doc_language = bparams.language;
4150 for (auto const & f : d->fontlist_)
4151 if (f.font().language() != ignore_language &&
4152 f.font().language() != latex_language &&
4153 f.font().language() != doc_language)
4159 void Paragraph::getLanguages(std::set<Language const *> & langs) const
4161 for (auto const & f : d->fontlist_) {
4162 Language const * lang = f.font().language();
4163 if (lang != ignore_language &&
4164 lang != latex_language)
4170 docstring Paragraph::asString(int options) const
4172 return asString(0, size(), options);
4176 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
4178 odocstringstream os;
4181 && options & AS_STR_LABEL
4182 && !d->params_.labelString().empty())
4183 os << d->params_.labelString() << ' ';
4185 for (pos_type i = beg; i < end; ++i) {
4186 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
4188 char_type const c = d->text_[i];
4189 if (isPrintable(c) || c == '\t'
4190 || (c == '\n' && (options & AS_STR_NEWLINES)))
4192 else if (c == META_INSET && (options & AS_STR_INSETS)) {
4193 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
4194 LASSERT(runparams != nullptr, return docstring());
4195 getInset(i)->plaintext(os, *runparams);
4196 } else if (c == META_INSET && (options & AS_STR_MATHED)
4197 && getInset(i)->lyxCode() == REF_CODE) {
4198 Buffer const & buf = getInset(i)->buffer();
4199 OutputParams rp(&buf.params().encoding());
4200 Font const font(inherit_font, buf.params().language);
4201 rp.local_font = &font;
4203 getInset(i)->latex(ots, rp);
4205 getInset(i)->toString(os);
4214 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
4215 bool const shorten, bool const label) const
4217 size_t tmplen = shorten ? maxlen + 1 : maxlen;
4218 if (label && !labelString().empty())
4219 os += labelString() + ' ';
4220 if (!layout().isTocCaption())
4222 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
4225 char_type const c = d->text_[i];
4228 else if (c == META_INSET)
4229 getInset(i)->forOutliner(os, tmplen, false);
4232 Text::shortenForOutliner(os, maxlen);
4236 void Paragraph::setInsetOwner(Inset const * inset)
4238 d->inset_owner_ = inset;
4242 int Paragraph::id() const
4248 void Paragraph::setId(int id)
4254 Layout const & Paragraph::layout() const
4260 void Paragraph::setLayout(Layout const & layout)
4262 d->layout_ = &layout;
4266 void Paragraph::setDefaultLayout(DocumentClass const & tc)
4268 setLayout(tc.defaultLayout());
4272 void Paragraph::setPlainLayout(DocumentClass const & tc)
4274 setLayout(tc.plainLayout());
4278 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tc)
4280 if (usePlainLayout())
4283 setDefaultLayout(tc);
4287 Inset const & Paragraph::inInset() const
4289 LBUFERR(d->inset_owner_);
4290 return *d->inset_owner_;
4294 ParagraphParameters & Paragraph::params()
4300 ParagraphParameters const & Paragraph::params() const
4306 bool Paragraph::isFreeSpacing() const
4308 if (d->layout_->free_spacing)
4310 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
4314 bool Paragraph::allowEmpty() const
4316 if (d->layout_->keepempty)
4318 return d->inset_owner_ && d->inset_owner_->allowEmpty();
4322 bool Paragraph::brokenBiblio() const
4324 // There is a problem if there is no bibitem at position 0 in
4325 // paragraphs that need one, if there is another bibitem in the
4326 // paragraph or if this paragraph is not supposed to have
4327 // a bibitem inset at all.
4328 return ((d->layout_->labeltype == LABEL_BIBLIO
4329 && (d->insetlist_.find(BIBITEM_CODE) != 0
4330 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
4331 || (d->layout_->labeltype != LABEL_BIBLIO
4332 && d->insetlist_.find(BIBITEM_CODE) != -1));
4336 int Paragraph::fixBiblio(Buffer const & buffer)
4338 // FIXME: when there was already an inset at 0, the return value is 1,
4339 // which does not tell whether another inset has been removed; the
4340 // cursor cannot be correctly updated.
4342 bool const track_changes = buffer.params().track_changes;
4343 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
4345 // The case where paragraph is not BIBLIO
4346 if (d->layout_->labeltype != LABEL_BIBLIO) {
4347 if (bibitem_pos == -1)
4348 // No InsetBibitem => OK
4350 // There is an InsetBibitem: remove it!
4351 d->insetlist_.release(bibitem_pos);
4352 eraseChar(bibitem_pos, track_changes);
4353 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
4356 bool const hasbibitem0 = bibitem_pos == 0;
4358 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
4359 // There was an InsetBibitem at pos 0,
4360 // and no other one => OK
4361 if (bibitem_pos == -1)
4363 // there is a bibitem at the 0 position, but since
4364 // there is a second one, we copy the second on the
4365 // first. We're assuming there are at most two of
4366 // these, which there should be.
4367 // FIXME: why does it make sense to do that rather
4368 // than keep the first? (JMarc)
4369 Inset * inset = releaseInset(bibitem_pos);
4370 d->insetlist_.begin()->inset = inset;
4371 // This needs to be done to update the counter (#8499)
4372 buffer.updateBuffer();
4373 return -bibitem_pos;
4376 // We need to create an inset at the beginning
4377 Inset * inset = nullptr;
4378 if (bibitem_pos > 0) {
4379 // there was one somewhere in the paragraph, let's move it
4380 inset = d->insetlist_.release(bibitem_pos);
4381 eraseChar(bibitem_pos, track_changes);
4384 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
4385 InsetCommandParams(BIBITEM_CODE));
4387 Font font(inherit_font, buffer.params().language);
4388 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
4389 : Change::UNCHANGED));
4391 // This is needed to get the counters right
4392 buffer.updateBuffer();
4397 void Paragraph::checkAuthors(AuthorList const & authorList)
4399 d->changes_.checkAuthors(authorList);
4403 bool Paragraph::isChanged(pos_type pos) const
4405 return lookupChange(pos).changed();
4409 bool Paragraph::isInserted(pos_type pos) const
4411 return lookupChange(pos).inserted();
4415 bool Paragraph::isDeleted(pos_type pos) const
4417 return lookupChange(pos).deleted();
4421 InsetList const & Paragraph::insetList() const
4423 return d->insetlist_;
4427 void Paragraph::setInsetBuffers(Buffer & b)
4429 d->insetlist_.setBuffer(b);
4433 void Paragraph::resetBuffer()
4435 d->insetlist_.resetBuffer();
4439 Inset * Paragraph::releaseInset(pos_type pos)
4441 Inset * inset = d->insetlist_.release(pos);
4442 /// does not honour change tracking!
4443 eraseChar(pos, false);
4448 Inset * Paragraph::getInset(pos_type pos)
4450 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4451 ? d->insetlist_.get(pos) : nullptr;
4455 Inset const * Paragraph::getInset(pos_type pos) const
4457 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
4458 ? d->insetlist_.get(pos) : nullptr;
4462 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
4463 pos_type & right, TextCase action)
4465 // process sequences of modified characters; in change
4466 // tracking mode, this approach results in much better
4467 // usability than changing case on a char-by-char basis
4468 // We also need to track the current font, since font
4469 // changes within sequences can occur.
4470 vector<pair<char_type, Font> > changes;
4472 bool const trackChanges = bparams.track_changes;
4474 bool capitalize = true;
4476 for (; pos < right; ++pos) {
4477 char_type oldChar = d->text_[pos];
4478 char_type newChar = oldChar;
4480 // ignore insets and don't play with deleted text!
4481 if (oldChar != META_INSET && !isDeleted(pos)) {
4483 case text_lowercase:
4484 newChar = lowercase(oldChar);
4486 case text_capitalization:
4488 newChar = uppercase(oldChar);
4492 case text_uppercase:
4493 newChar = uppercase(oldChar);
4498 if (isWordSeparator(pos) || isDeleted(pos)) {
4499 // permit capitalization again
4503 if (oldChar != newChar) {
4504 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
4505 if (pos != right - 1)
4507 // step behind the changing area
4511 int erasePos = pos - changes.size();
4512 for (auto const & change : changes) {
4513 insertChar(pos, change.first, change.second, trackChanges);
4514 if (!eraseChar(erasePos, trackChanges)) {
4517 ++right; // expand selection
4525 int Paragraph::find(docstring const & str, bool cs, bool mw,
4526 pos_type start_pos, bool del) const
4528 pos_type pos = start_pos;
4529 int const strsize = str.length();
4531 pos_type const parsize = d->text_.size();
4532 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
4533 // ignore deleted matter
4534 if (!del && isDeleted(pos)) {
4535 if (pos == parsize - 1)
4541 // Ignore "invisible" letters such as ligature breaks
4542 // and hyphenation chars while searching
4543 bool nonmatch = false;
4544 while (pos < parsize && isInset(pos)) {
4545 Inset const * inset = getInset(pos);
4546 if (!inset->isLetter() && !inset->isChar())
4548 odocstringstream os;
4549 inset->toString(os);
4550 docstring const insetstring = os.str();
4551 if (!insetstring.empty()) {
4552 int const insetstringsize = insetstring.length();
4553 for (int j = 0; j < insetstringsize && pos < parsize; ++i, ++j) {
4554 if ((cs && str[i] != insetstring[j])
4555 || (!cs && uppercase(str[i]) != uppercase(insetstring[j]))) {
4563 if (nonmatch || i == strsize)
4565 if (cs && str[i] != d->text_[pos])
4567 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
4574 // if necessary, check whether string matches word
4576 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
4579 && !isWordSeparator(pos))
4583 return pos - start_pos;
4587 char_type Paragraph::getChar(pos_type pos) const
4589 return d->text_[pos];
4593 pos_type Paragraph::size() const
4595 return d->text_.size();
4599 bool Paragraph::empty() const
4601 return d->text_.empty();
4605 bool Paragraph::isInset(pos_type pos) const
4607 return d->text_[pos] == META_INSET;
4611 bool Paragraph::isSeparator(pos_type pos) const
4613 //FIXME: Are we sure this can be the only separator?
4614 return d->text_[pos] == ' ';
4618 void Paragraph::deregisterWords()
4620 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4621 Private::LangWordsMap::const_iterator ite = d->words_.end();
4622 for (; itl != ite; ++itl) {
4623 WordList & wl = theWordList(itl->first);
4624 Private::Words::const_iterator it = (itl->second).begin();
4625 Private::Words::const_iterator et = (itl->second).end();
4626 for (; it != et; ++it)
4633 void Paragraph::locateWord(pos_type & from, pos_type & to,
4634 word_location const loc, bool const ignore_deleted) const
4637 case WHOLE_WORD_STRICT:
4638 if (from == 0 || from == size()
4639 || isWordSeparator(from, ignore_deleted)
4640 || isWordSeparator(from - 1, ignore_deleted)) {
4647 // If we are already at the beginning of a word, do nothing
4648 if (!from || isWordSeparator(from - 1, ignore_deleted))
4653 // always move the cursor to the beginning of previous word
4654 while (from && !isWordSeparator(from - 1, ignore_deleted))
4658 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4661 // no need to move the 'from' cursor
4665 while (to < size() && !isWordSeparator(to, ignore_deleted))
4670 void Paragraph::collectWords()
4672 for (pos_type pos = 0; pos < size(); ++pos) {
4673 if (isWordSeparator(pos))
4675 pos_type from = pos;
4676 locateWord(from, pos, WHOLE_WORD);
4677 // Work around MSVC warning: The statement
4678 // if (pos < from + lyxrc.completion_minlength)
4679 // triggers a signed vs. unsigned warning.
4680 // I don't know why this happens, it could be a MSVC bug, or
4681 // related to LLP64 (windows) vs. LP64 (unix) programming
4682 // model, or the C++ standard might be ambigous in the section
4683 // defining the "usual arithmetic conversions". However, using
4684 // a temporary variable is safe and works on all compilers.
4685 pos_type const endpos = from + lyxrc.completion_minlength;
4688 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4689 if (cit == d->fontlist_.end())
4691 Language const * lang = cit->font().language();
4692 docstring const word = asString(from, pos, AS_STR_NONE);
4693 d->words_[lang->lang()].insert(word);
4698 void Paragraph::registerWords()
4700 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4701 Private::LangWordsMap::const_iterator ite = d->words_.end();
4702 for (; itl != ite; ++itl) {
4703 WordList & wl = theWordList(itl->first);
4704 Private::Words::const_iterator it = (itl->second).begin();
4705 Private::Words::const_iterator et = (itl->second).end();
4706 for (; it != et; ++it)
4712 void Paragraph::updateWords()
4720 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4722 SkipPositionsIterator begin = skips.begin();
4723 SkipPositions::iterator end = skips.end();
4724 if (pos > 0 && begin < end) {
4726 if (end->last == pos - 1) {
4731 skips.insert(end, FontSpan(pos, pos));
4735 Language * Paragraph::Private::locateSpellRange(
4736 pos_type & from, pos_type & to,
4737 SkipPositions & skips) const
4739 // skip leading white space
4740 while (from < to && owner_->isWordSeparator(from))
4742 // don't check empty range
4745 // get current language
4746 Language * lang = getSpellLanguage(from);
4747 pos_type last = from;
4748 bool samelang = true;
4749 bool sameinset = true;
4750 while (last < to && samelang && sameinset) {
4751 // hop to end of word
4752 while (last < to && !owner_->isWordSeparator(last)) {
4753 Inset const * inset = owner_->getInset(last);
4754 if (inset && dynamic_cast<const InsetSpecialChar *>(inset)) {
4755 // check for "invisible" letters such as ligature breaks
4756 odocstringstream os;
4757 inset->toString(os);
4758 if (os.str().length() != 0) {
4759 // avoid spell check of visible special char insets
4760 // stop the loop in front of the special char inset
4765 appendSkipPosition(skips, last);
4766 } else if (owner_->isDeleted(last)) {
4767 appendSkipPosition(skips, last);
4771 // hop to next word while checking for insets
4772 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4773 if (Inset const * inset = owner_->getInset(last))
4774 sameinset = inset->isChar() && inset->isLetter();
4775 if (sameinset && owner_->isDeleted(last)) {
4776 appendSkipPosition(skips, last);
4781 if (sameinset && last < to) {
4782 // now check for language change
4783 samelang = lang == getSpellLanguage(last);
4786 // if language change detected backstep is needed
4794 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4797 const_cast<Language *>(owner_->getFontSettings(
4798 inset_owner_->buffer().params(), from).language());
4799 if (lang == inset_owner_->buffer().params().language
4800 && !lyxrc.spellchecker_alt_lang.empty()) {
4802 string const lang_variety =
4803 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4804 lang->setCode(lang_code);
4805 lang->setVariety(lang_variety);
4811 void Paragraph::requestSpellCheck(pos_type pos)
4813 d->requestSpellCheck(pos);
4817 bool Paragraph::needsSpellCheck() const
4819 SpellChecker::ChangeNumber speller_change_number = 0;
4820 if (theSpellChecker())
4821 speller_change_number = theSpellChecker()->changeNumber();
4822 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4823 d->speller_state_.needsCompleteRefresh(speller_change_number);
4825 return d->needsSpellCheck();
4829 bool Paragraph::Private::ignoreWord(docstring const & word) const
4831 // Ignore words with digits
4832 // FIXME: make this customizable
4833 // (note that some checkers ignore words with digits by default)
4834 docstring::const_iterator cit = word.begin();
4835 docstring::const_iterator const end = word.end();
4836 for (; cit != end; ++cit) {
4837 if (isNumber((*cit)))
4844 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4845 WordLangTuple & wl, docstring_list & suggestions,
4846 bool do_suggestion, bool check_learned) const
4848 SpellChecker::Result result = SpellChecker::WORD_OK;
4849 SpellChecker * speller = theSpellChecker();
4853 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4856 locateWord(from, to, WHOLE_WORD, true);
4857 if (from == to || from >= size())
4860 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4861 Language * lang = d->getSpellLanguage(from);
4863 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4866 wl = WordLangTuple(word, lang);
4871 if (needsSpellCheck() || check_learned) {
4873 if (!d->ignoreWord(word)) {
4874 bool const trailing_dot = to < size() && d->text_[to] == '.';
4875 result = speller->check(wl);
4876 if (SpellChecker::misspelled(result) && trailing_dot) {
4877 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4878 result = speller->check(wl);
4879 if (!SpellChecker::misspelled(result)) {
4880 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4882 from << ".." << to << "]");
4884 // spell check with dot appended failed too
4885 // restore original word/lang value
4886 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4887 wl = WordLangTuple(word, lang);
4891 if (!SpellChecker::misspelled(result)) {
4892 // area up to the begin of the next word is not misspelled
4893 while (end < size() && isWordSeparator(end))
4896 d->setMisspelled(from, end, result);
4898 result = d->speller_state_.getState(from);
4902 suggestions.clear();
4904 if (SpellChecker::misspelled(result)) {
4905 LYXERR(Debug::GUI, "misspelled word: \"" <<
4907 from << ".." << to << "]");
4909 speller->suggest(wl, suggestions);
4915 void Paragraph::anonymize()
4917 // This is a very crude anonymization for now
4918 for (char_type & c : d->text_)
4919 if (isLetterChar(c) || isNumber(c))
4924 void Paragraph::Private::markMisspelledWords(
4925 pos_type const & first, pos_type const & last,
4926 SpellChecker::Result result,
4927 docstring const & word,
4928 SkipPositions const & skips)
4930 if (!SpellChecker::misspelled(result)) {
4931 setMisspelled(first, last, SpellChecker::WORD_OK);
4935 SpellChecker * speller = theSpellChecker();
4936 // locate and enumerate the error positions
4937 int nerrors = speller->numMisspelledWords();
4939 SkipPositionsIterator it = skips.begin();
4940 SkipPositionsIterator et = skips.end();
4941 for (int index = 0; index < nerrors; ++index) {
4944 speller->misspelledWord(index, wstart, wlen);
4945 /// should not happen if speller supports range checks
4946 if (!wlen) continue;
4947 docstring const misspelled = word.substr(wstart, wlen);
4948 wstart += first + numskipped;
4949 if (snext < wstart) {
4950 /// mark the range of correct spelling
4951 numskipped += countSkips(it, et, wstart);
4952 setMisspelled(snext,
4953 wstart - 1, SpellChecker::WORD_OK);
4955 snext = wstart + wlen;
4956 numskipped += countSkips(it, et, snext);
4957 /// mark the range of misspelling
4958 setMisspelled(wstart, snext, result);
4959 LYXERR(Debug::GUI, "misspelled word: \"" <<
4960 misspelled << "\" [" <<
4961 wstart << ".." << (snext-1) << "]");
4964 if (snext <= last) {
4965 /// mark the range of correct spelling at end
4966 setMisspelled(snext, last, SpellChecker::WORD_OK);
4971 void Paragraph::spellCheck() const
4973 SpellChecker * speller = theSpellChecker();
4974 if (!speller || empty() ||!needsSpellCheck())
4978 d->rangeOfSpellCheck(start, endpos);
4979 if (speller->canCheckParagraph()) {
4980 // loop until we leave the range
4981 for (pos_type first = start; first < endpos; ) {
4982 pos_type last = endpos;
4983 Private::SkipPositions skips;
4984 Language * lang = d->locateSpellRange(first, last, skips);
4985 if (first >= endpos)
4987 // start the spell checker on the unit of meaning
4988 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4989 WordLangTuple wl = WordLangTuple(word, lang);
4990 SpellChecker::Result result = !word.empty() ?
4991 speller->check(wl) : SpellChecker::WORD_OK;
4992 d->markMisspelledWords(first, last, result, word, skips);
4996 static docstring_list suggestions;
4997 pos_type to = endpos;
4998 while (start < endpos) {
5000 spellCheck(start, to, wl, suggestions, false);
5004 d->readySpellCheck();
5008 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
5010 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
5011 if (result || pos <= 0 || pos > size())
5013 if (check_boundary && (pos == size() || isWordSeparator(pos)))
5014 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
5019 string Paragraph::magicLabel() const
5022 ss << "magicparlabel-" << id();