3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
93 /////////////////////////////////////////////////////////////////////
97 /////////////////////////////////////////////////////////////////////
99 class SpellResultRange {
101 SpellResultRange(FontSpan range, SpellChecker::Result result)
102 : range_(range), result_(result)
105 FontSpan const & range() const { return range_; }
107 void range(FontSpan const & r) { range_ = r; }
109 SpellChecker::Result result() const { return result_; }
111 void result(SpellChecker::Result r) { result_ = r; }
113 bool contains(pos_type pos) const { return range_.contains(pos); }
115 bool covered(FontSpan const & r) const
117 // 1. first of new range inside current range or
118 // 2. last of new range inside current range or
119 // 3. first of current range inside new range or
120 // 4. last of current range inside new range
121 //FIXME: is this the same as !range_.intersect(r).empty() ?
122 return range_.contains(r.first) || range_.contains(r.last) ||
123 r.contains(range_.first) || r.contains(range_.last);
126 void shift(pos_type pos, int offset)
128 if (range_.first > pos) {
129 range_.first += offset;
130 range_.last += offset;
131 } else if (range_.last >= pos) {
132 range_.last += offset;
137 SpellChecker::Result result_ ;
141 /////////////////////////////////////////////////////////////////////
145 /////////////////////////////////////////////////////////////////////
147 class SpellCheckerState {
151 needs_refresh_ = true;
152 current_change_number_ = 0;
155 void setRange(FontSpan const & fp, SpellChecker::Result state)
158 RangesIterator et = ranges_.end();
159 RangesIterator it = ranges_.begin();
160 for (; it != et; ++it) {
161 if (!it->covered(fp))
162 result.push_back(SpellResultRange(it->range(), it->result()));
163 else if (state == SpellChecker::WORD_OK) {
164 // trim or split the current misspelled range
165 // store misspelled ranges only
166 FontSpan range = it->range();
167 if (fp.first > range.first) {
168 // misspelled area in front of WORD_OK
169 range.last = fp.first - 1;
170 result.push_back(SpellResultRange(range, it->result()));
173 if (fp.last < range.last) {
174 // misspelled area after WORD_OK range
175 range.first = fp.last + 1;
176 result.push_back(SpellResultRange(range, it->result()));
181 if (state != SpellChecker::WORD_OK)
182 ranges_.push_back(SpellResultRange(fp, state));
185 void increasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, 1);
191 void decreasePosAfterPos(pos_type pos)
193 correctRangesAfterPos(pos, -1);
197 void refreshLast(pos_type pos)
199 if (pos < refresh_.last)
203 SpellChecker::Result getState(pos_type pos) const
205 SpellChecker::Result result = SpellChecker::WORD_OK;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 FontSpan const & getRange(pos_type pos) const
218 /// empty span to indicate mismatch
219 static FontSpan empty_;
220 RangesIterator et = ranges_.end();
221 RangesIterator it = ranges_.begin();
222 for (; it != et; ++it) {
223 if(it->contains(pos)) {
230 bool needsRefresh() const
232 return needs_refresh_;
235 SpellChecker::ChangeNumber currentChangeNumber() const
237 return current_change_number_;
240 void refreshRange(pos_type & first, pos_type & last) const
242 first = refresh_.first;
243 last = refresh_.last;
246 void needsRefresh(pos_type pos)
248 if (needs_refresh_ && pos != -1) {
249 if (pos < refresh_.first)
250 refresh_.first = pos;
251 if (pos > refresh_.last)
253 } else if (pos != -1) {
254 // init request check for neighbour positions too
255 refresh_.first = pos > 0 ? pos - 1 : 0;
256 // no need for special end of paragraph check
257 refresh_.last = pos + 1;
259 needs_refresh_ = pos != -1;
262 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
264 needs_refresh_ = true;
267 current_change_number_ = change_number;
270 typedef vector<SpellResultRange> Ranges;
271 typedef Ranges::const_iterator RangesIterator;
273 /// the area of the paragraph with pending spell check
276 /// spell state cache version number
277 SpellChecker::ChangeNumber current_change_number_;
280 void correctRangesAfterPos(pos_type pos, int offset)
282 RangesIterator et = ranges_.end();
283 Ranges::iterator it = ranges_.begin();
284 for (; it != et; ++it) {
285 it->shift(pos, offset);
291 /////////////////////////////////////////////////////////////////////
293 // Paragraph::Private
295 /////////////////////////////////////////////////////////////////////
297 class Paragraph::Private
299 // Enforce our own "copy" constructor
300 Private(Private const &) = delete;
301 Private & operator=(Private const &) = delete;
302 // Unique ID generator
303 static int make_id();
306 Private(Paragraph * owner, Layout const & layout);
307 /// "Copy constructor"
308 Private(Private const &, Paragraph * owner);
309 /// Copy constructor from \p beg to \p end
310 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
313 void insertChar(pos_type pos, char_type c, Change const & change);
315 /// Output the surrogate pair formed by \p c and \p next to \p os.
316 /// \return the number of characters written.
317 int latexSurrogatePair(BufferParams const &, otexstream & os,
318 char_type c, char_type next,
319 OutputParams const &);
321 /// Output a space in appropriate formatting (or a surrogate pair
322 /// if the next character is a combining character).
323 /// \return whether a surrogate pair was output.
324 bool simpleTeXBlanks(BufferParams const &,
325 OutputParams const &,
328 unsigned int & column,
330 Layout const & style);
332 /// Output consecutive unicode chars, belonging to the same script as
333 /// specified by the latex macro \p ltx, to \p os starting from \p i.
334 /// \return the number of characters written.
335 int writeScriptChars(BufferParams const &, OutputParams const &,
337 docstring const & ltx,
338 Change const &, Encoding const &,
339 std::string const, pos_type & i);
341 /// This could go to ParagraphParameters if we want to.
342 int startTeXParParams(BufferParams const &, otexstream &,
343 OutputParams const &) const;
345 /// This could go to ParagraphParameters if we want to.
346 bool endTeXParParams(BufferParams const &, otexstream &,
347 OutputParams const &) const;
350 void latexInset(BufferParams const &,
355 Font const & outerfont,
357 Change & running_change,
358 Layout const & style,
360 unsigned int & column);
363 void latexSpecialChar(
365 BufferParams const & bparams,
366 OutputParams const & runparams,
367 Font const & running_font,
368 Change const & running_change,
369 Layout const & style,
372 unsigned int & column);
379 unsigned int & column);
385 unsigned int & column);
391 unsigned int & column);
394 void validate(LaTeXFeatures & features) const;
396 /// Checks if the paragraph contains only text and no inset or font change.
397 bool onlyText(Buffer const & buf, Font const & outerfont,
398 pos_type initial) const;
400 /// a vector of speller skip positions
401 typedef vector<FontSpan> SkipPositions;
402 typedef SkipPositions::const_iterator SkipPositionsIterator;
404 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
406 Language * getSpellLanguage(pos_type const from) const;
408 Language * locateSpellRange(pos_type & from, pos_type & to,
409 SkipPositions & skips) const;
411 bool hasSpellerChange() const
413 SpellChecker::ChangeNumber speller_change_number = 0;
414 if (theSpellChecker())
415 speller_change_number = theSpellChecker()->changeNumber();
416 return speller_change_number > speller_state_.currentChangeNumber();
419 bool ignoreWord(docstring const & word) const ;
421 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
423 pos_type textsize = owner_->size();
424 // check for sane arguments
425 if (to <= from || from >= textsize)
427 FontSpan fp = FontSpan(from, to - 1);
428 speller_state_.setRange(fp, state);
431 void requestSpellCheck(pos_type pos)
434 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
436 speller_state_.needsRefresh(pos);
439 void readySpellCheck()
441 speller_state_.needsRefresh(-1);
444 bool needsSpellCheck() const
446 return speller_state_.needsRefresh();
449 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
451 speller_state_.refreshRange(first, last);
453 last = owner_->size();
456 pos_type endpos = last;
457 owner_->locateWord(first, endpos, WHOLE_WORD);
460 owner_->locateWord(last, endpos, WHOLE_WORD);
465 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
469 while (it != et && it->first < start) {
470 int skip = it->last - it->first + 1;
478 void markMisspelledWords(pos_type const & first, pos_type const & last,
479 SpellChecker::Result result,
480 docstring const & word,
481 SkipPositions const & skips);
483 InsetCode ownerCode() const
485 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
488 /// Which Paragraph owns us?
492 Inset const * inset_owner_;
501 ParagraphParameters params_;
503 /// for recording and looking up changes
507 InsetList insetlist_;
510 pos_type begin_of_body_;
512 typedef docstring TextContainer;
516 typedef set<docstring> Words;
517 typedef map<string, Words> LangWordsMap;
521 Layout const * layout_;
523 SpellCheckerState speller_state_;
527 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
528 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
535 int Paragraph::Private::make_id()
537 // The id is unique per session across buffers because it is used in
538 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
541 static atomic_uint next_id(0);
546 Paragraph::Private::Private(Private const & p, Paragraph * owner)
547 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
549 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
550 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
553 requestSpellCheck(p.text_.size());
557 Paragraph::Private::Private(Private const & p, Paragraph * owner,
558 pos_type beg, pos_type end)
559 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
560 params_(p.params_), changes_(p.changes_),
561 insetlist_(p.insetlist_, beg, end),
562 begin_of_body_(p.begin_of_body_), words_(p.words_),
565 if (beg >= pos_type(p.text_.size()))
567 text_ = p.text_.substr(beg, end - beg);
569 FontList::const_iterator fcit = fontlist_.begin();
570 FontList::const_iterator fend = fontlist_.end();
571 for (; fcit != fend; ++fcit) {
572 if (fcit->pos() < beg)
574 if (fcit->pos() >= end) {
575 // Add last entry in the fontlist_.
576 fontlist_.set(text_.size() - 1, fcit->font());
579 // Add a new entry in the fontlist_.
580 fontlist_.set(fcit->pos() - beg, fcit->font());
582 requestSpellCheck(p.text_.size());
586 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
587 bool output_active, TocBackend & backend) const
589 d->changes_.addToToc(cdit, buf, output_active, backend);
593 void Paragraph::addChangesToBuffer(Buffer const & buf) const
595 d->changes_.updateBuffer(buf);
599 bool Paragraph::isChangeUpdateRequired() const
601 return d->changes_.isUpdateRequired();
605 bool Paragraph::isDeleted(pos_type start, pos_type end) const
607 LASSERT(start >= 0 && start <= size(), return false);
608 LASSERT(end > start && end <= size() + 1, return false);
610 return d->changes_.isDeleted(start, end);
614 bool Paragraph::isChanged(pos_type start, pos_type end) const
616 LASSERT(start >= 0 && start <= size(), return false);
617 LASSERT(end > start && end <= size() + 1, return false);
619 return d->changes_.isChanged(start, end);
623 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
625 // keep the logic here in sync with the logic of eraseChars()
629 Change const & change = d->changes_.lookup(size());
630 return change.inserted() && change.currentAuthor();
634 void Paragraph::setChange(Change const & change)
636 // beware of the imaginary end-of-par character!
637 d->changes_.set(change, 0, size() + 1);
640 * Propagate the change recursively - but not in case of DELETED!
642 * Imagine that your co-author makes changes in an existing inset. He
643 * sends your document to you and you come to the conclusion that the
644 * inset should go completely. If you erase it, LyX must not delete all
645 * text within the inset. Otherwise, the change tracked insertions of
646 * your co-author get lost and there is no way to restore them later.
648 * Conclusion: An inset's content should remain untouched if you delete it
651 if (!change.deleted()) {
652 for (pos_type pos = 0; pos < size(); ++pos) {
653 if (Inset * inset = getInset(pos))
654 inset->setChange(change);
660 void Paragraph::setChange(pos_type pos, Change const & change)
662 LASSERT(pos >= 0 && pos <= size(), return);
663 d->changes_.set(change, pos);
665 // see comment in setChange(Change const &) above
666 if (!change.deleted() && pos < size())
667 if (Inset * inset = getInset(pos))
668 inset->setChange(change);
672 Change const & Paragraph::lookupChange(pos_type pos) const
674 LBUFERR(pos >= 0 && pos <= size());
675 return d->changes_.lookup(pos);
679 void Paragraph::acceptChanges(pos_type start, pos_type end)
681 LASSERT(start >= 0 && start <= size(), return);
682 LASSERT(end > start && end <= size() + 1, return);
684 for (pos_type pos = start; pos < end; ++pos) {
685 switch (lookupChange(pos).type) {
686 case Change::UNCHANGED:
687 // accept changes in nested inset
688 if (Inset * inset = getInset(pos))
689 inset->acceptChanges();
692 case Change::INSERTED:
693 d->changes_.set(Change(Change::UNCHANGED), pos);
694 // also accept changes in nested inset
695 if (Inset * inset = getInset(pos))
696 inset->acceptChanges();
699 case Change::DELETED:
700 // Suppress access to non-existent
701 // "end-of-paragraph char"
703 eraseChar(pos, false);
714 void Paragraph::rejectChanges(pos_type start, pos_type end)
716 LASSERT(start >= 0 && start <= size(), return);
717 LASSERT(end > start && end <= size() + 1, return);
719 for (pos_type pos = start; pos < end; ++pos) {
720 switch (lookupChange(pos).type) {
721 case Change::UNCHANGED:
722 // reject changes in nested inset
723 if (Inset * inset = getInset(pos))
724 inset->rejectChanges();
727 case Change::INSERTED:
728 // Suppress access to non-existent
729 // "end-of-paragraph char"
731 eraseChar(pos, false);
737 case Change::DELETED:
738 d->changes_.set(Change(Change::UNCHANGED), pos);
740 // Do NOT reject changes within a deleted inset!
741 // There may be insertions of a co-author inside of it!
749 void Paragraph::Private::insertChar(pos_type pos, char_type c,
750 Change const & change)
752 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
755 changes_.insert(change, pos);
757 // This is actually very common when parsing buffers (and
758 // maybe inserting ascii text)
759 if (pos == pos_type(text_.size())) {
760 // when appending characters, no need to update tables
762 // but we want spell checking
763 requestSpellCheck(pos);
767 text_.insert(text_.begin() + pos, c);
769 // Update the font table.
770 fontlist_.increasePosAfterPos(pos);
773 insetlist_.increasePosAfterPos(pos);
775 // Update list of misspelled positions
776 speller_state_.increasePosAfterPos(pos);
780 bool Paragraph::insertInset(pos_type pos, Inset * inset,
781 Font const & font, Change const & change)
783 LASSERT(inset, return false);
784 LASSERT(pos >= 0 && pos <= size(), return false);
786 // Paragraph::insertInset() can be used in cut/copy/paste operation where
787 // d->inset_owner_ is not set yet.
788 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
791 d->insertChar(pos, META_INSET, change);
792 LASSERT(d->text_[pos] == META_INSET, return false);
794 // Add a new entry in the insetlist_.
795 d->insetlist_.insert(inset, pos);
797 // Some insets require run of spell checker
798 requestSpellCheck(pos);
804 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
806 LASSERT(pos >= 0 && pos <= size(), return false);
808 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
811 Change change = d->changes_.lookup(pos);
813 // set the character to DELETED if
814 // a) it was previously unchanged or
815 // b) it was inserted by a co-author
817 if (!change.changed() ||
818 (change.inserted() && !change.currentAuthor())) {
819 setChange(pos, Change(Change::DELETED));
820 // request run of spell checker
821 requestSpellCheck(pos);
825 if (change.deleted())
829 // Don't physically access the imaginary end-of-paragraph character.
830 // eraseChar() can only mark it as DELETED. A physical deletion of
831 // end-of-par must be handled externally.
837 d->changes_.erase(pos);
839 // if it is an inset, delete the inset entry
840 if (d->text_[pos] == META_INSET)
841 d->insetlist_.erase(pos);
843 d->text_.erase(d->text_.begin() + pos);
845 // Update the fontlist_
846 d->fontlist_.erase(pos);
848 // Update the insetlist_
849 d->insetlist_.decreasePosAfterPos(pos);
851 // Update list of misspelled positions
852 d->speller_state_.decreasePosAfterPos(pos);
853 d->speller_state_.refreshLast(size());
859 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
861 LASSERT(start >= 0 && start <= size(), return 0);
862 LASSERT(end >= start && end <= size() + 1, return 0);
865 for (pos_type count = end - start; count; --count) {
866 if (!eraseChar(i, trackChanges))
873 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
874 otexstream & os, char_type c, char_type next,
875 OutputParams const & runparams)
877 // Writing next here may circumvent a possible font change between
878 // c and next. Since next is only output if it forms a surrogate pair
879 // with c we can ignore this:
880 // A font change inside a surrogate pair does not make sense and is
881 // hopefully impossible to input.
882 // FIXME: change tracking
883 // Is this correct WRT change tracking?
884 Encoding const & encoding = *(runparams.encoding);
885 docstring latex1 = encoding.latexChar(next).first;
886 if (runparams.inIPA) {
887 string const tipashortcut = Encodings::TIPAShortcut(next);
888 if (!tipashortcut.empty()) {
889 latex1 = from_ascii(tipashortcut);
892 docstring latex2 = encoding.latexChar(c).first;
894 if (docstring(1, next) == latex1) {
895 // The encoding supports the combination:
896 // output as is (combining char after base char).
897 os << latex2 << latex1;
898 return latex1.length() + latex2.length();
901 // Handle combining characters in "script" context (i.e., \textgreek and \textcyrillic)
902 docstring::size_type const brace1 = latex2.find_first_of(from_ascii("{"));
903 docstring::size_type const brace2 = latex2.find_last_of(from_ascii("}"));
904 string script = to_ascii(latex2.substr(1, brace1 - 1));
905 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
906 // whether they are encodable or not (it only depends on the font encoding)
907 if (!runparams.isFullUnicode())
908 // This will get us a script value to deal with below
909 Encodings::isKnownScriptChar(c, script);
913 if (runparams.local_font)
914 fontenc = runparams.local_font->language()->fontenc(bparams);
916 fontenc = bparams.language->fontenc(bparams);
917 docstring scriptmacro;
919 if (script == "textgreek" || script == "textcyrillic") {
920 // We separate the script macro (\text[greek|cyr]) from the rest,
921 // since we need to include the combining char in it (#6463).
922 // This is "the rest":
925 latex2 = latex2.substr(pos, length);
926 // We only need the script macro with non-native font encodings
927 if (Encodings::needsScriptWrapper(script, fontenc)) {
928 scriptmacro = from_ascii("\\" + script + "{");
929 cb = from_ascii("}");
935 // polutonikogreek does not play nice with brackets
936 if (!runparams.local_font
937 || runparams.local_font->language()->lang() != "polutonikogreek") {
938 lb = from_ascii("{");
939 rb = from_ascii("}");
942 os << scriptmacro << latex1 << lb << latex2 << rb << cb;
943 return latex1.length() + latex2.length() + lb.length() + rb.length() + cb.length();
947 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
948 OutputParams const & runparams,
951 unsigned int & column,
953 Layout const & style)
955 if (style.pass_thru || runparams.pass_thru)
958 if (i + 1 < int(text_.size())) {
959 char_type next = text_[i + 1];
960 if (Encodings::isCombiningChar(next)) {
961 // This space has an accent, so we must always output it.
962 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
967 if (runparams.linelen > 0
968 && column > runparams.linelen
970 && text_[i - 1] != ' '
971 && (i + 1 < int(text_.size()))
972 // same in FreeSpacing mode
973 && !owner_->isFreeSpacing()
974 // In typewriter mode, we want to avoid
975 // ! . ? : at the end of a line
976 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
977 && (text_[i - 1] == '.'
978 || text_[i - 1] == '?'
979 || text_[i - 1] == ':'
980 || text_[i - 1] == '!'))) {
982 os.texrow().start(owner_->id(), i + 1);
984 } else if (style.free_spacing) {
993 int Paragraph::Private::writeScriptChars(BufferParams const & bparams,
994 OutputParams const & runparams,
996 docstring const & ltx,
997 Change const & runningChange,
998 Encoding const & encoding,
999 string const fontenc,
1002 // FIXME: modifying i here is not very nice...
1004 // We only arrive here when character text_[i] could not be translated
1005 // into the current latex encoding (or its latex translation has been forced,)
1006 // and it belongs to a known script.
1007 // Parameter ltx contains the latex translation of text_[i] as specified
1008 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
1009 // The latex macro name "textXXX" specifies the script to which text_[i]
1010 // belongs and we use it in order to check whether characters from the
1011 // same script immediately follow, such that we can collect them in a
1012 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
1013 // for the first char but only "<spec>" for all subsequent chars.
1014 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
1015 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
1016 string script = to_ascii(ltx.substr(1, brace1 - 1));
1018 int length = brace2;
1019 bool closing_brace = true;
1020 if (!Encodings::needsScriptWrapper(script, fontenc)) {
1021 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
1024 closing_brace = false;
1026 os << ltx.substr(pos, length);
1027 int size = text_.size();
1028 while (i + 1 < size) {
1029 char_type const next = text_[i + 1];
1030 // Stop here if next character belongs to another script
1031 // or there is a change in change tracking status.
1032 if (!Encodings::isKnownScriptChar(next, script) ||
1033 runningChange != owner_->lookupChange(i + 1))
1037 FontList::const_iterator cit = fontlist_.begin();
1038 FontList::const_iterator end = fontlist_.end();
1039 for (; cit != end; ++cit) {
1040 if (cit->pos() >= i && !found) {
1041 prev_font = cit->font();
1044 if (cit->pos() >= i + 1)
1047 // Stop here if there is a font attribute or encoding change.
1048 if (found && cit != end && prev_font != cit->font())
1051 // Check whether we have a combining pair
1052 char_type next_next = '\0';
1054 next_next = text_[i + 2];
1055 if (Encodings::isCombiningChar(next_next)) {
1056 length += latexSurrogatePair(bparams, os, next, next_next, runparams) - 1;
1062 docstring const latex = encoding.latexChar(next).first;
1063 docstring::size_type const b1 =
1064 latex.find_first_of(from_ascii("{"));
1065 docstring::size_type const b2 =
1066 latex.find_last_of(from_ascii("}"));
1067 int const len = b2 - b1 - 1;
1068 os << latex.substr(b1 + 1, len);
1072 if (closing_brace) {
1080 void Paragraph::Private::latexInset(BufferParams const & bparams,
1082 OutputParams & runparams,
1083 Font & running_font,
1085 Font const & outerfont,
1087 Change & running_change,
1088 Layout const & style,
1090 unsigned int & column)
1092 Inset * inset = owner_->getInset(i);
1095 if (style.pass_thru) {
1096 odocstringstream ods;
1097 inset->plaintext(ods, runparams);
1102 // FIXME: move this to InsetNewline::latex
1103 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1104 // newlines are handled differently here than
1105 // the default in simpleTeXSpecialChars().
1106 if (!style.newline_allowed) {
1110 bool needPar = false;
1111 column += running_font.latexWriteEndChanges(
1112 os, bparams, runparams,
1113 basefont, basefont, needPar);
1117 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1120 basefont = owner_->getLayoutFont(bparams, outerfont);
1121 running_font = basefont;
1123 if (runparams.moving_arg)
1127 os.texrow().start(owner_->id(), i + 1);
1131 if (owner_->isDeleted(i)) {
1132 if( ++runparams.inDeletedInset == 1)
1133 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1136 if (inset->canTrackChanges()) {
1137 column += Changes::latexMarkChange(os, bparams, running_change,
1138 Change(Change::UNCHANGED), runparams);
1139 running_change = Change(Change::UNCHANGED);
1143 odocstream::pos_type const len = os.os().tellp();
1145 if (inset->forceLTR()
1146 && running_font.isRightToLeft()
1147 // ERT is an exception, it should be output with no
1148 // decorations at all
1149 && inset->lyxCode() != ERT_CODE) {
1150 if (runparams.use_polyglossia) {
1151 if (style.isEnvironment())
1152 os << "\\begin{LTR}";
1154 } else if (running_font.language()->lang() == "farsi"
1155 || running_font.language()->lang() == "arabic_arabi")
1156 os << "\\textLR{" << termcmd;
1162 // FIXME: Bug: we can have an empty font change here!
1163 // if there has just been a font change, we are going to close it
1164 // right now, which means stupid latex code like \textsf{}. AFAIK,
1165 // this does not harm dvi output. A minor bug, thus (JMarc)
1167 // Some insets cannot be inside a font change command.
1168 // However, even such insets *can* be placed in \L or \R
1169 // or their equivalents (for RTL language switches), so we don't
1170 // close the language in those cases.
1171 // ArabTeX, though, cannot handle this special behavior, it seems.
1172 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1173 || running_font.language()->lang() == "arabic_arabtex";
1174 if (open_font && !inset->inheritFont()) {
1175 bool needPar = false;
1176 bool closeLanguage = arabtex
1177 || basefont.isRightToLeft() == running_font.isRightToLeft();
1178 unsigned int count = running_font.latexWriteEndChanges(os,
1179 bparams, runparams, basefont, basefont,
1180 needPar, closeLanguage);
1182 // if any font properties were closed, update the running_font,
1183 // making sure, however, to leave the language as it was
1185 // FIXME: probably a better way to keep track of the old
1186 // language, than copying the entire font?
1187 Font const copy_font(running_font);
1188 basefont = owner_->getLayoutFont(bparams, outerfont);
1189 running_font = basefont;
1191 running_font.setLanguage(copy_font.language());
1192 // leave font open if language is still open
1193 open_font = (running_font.language() == basefont.language());
1195 runparams.local_font = &basefont;
1199 size_t const previous_row_count = os.texrow().rows();
1202 runparams.lastid = id_;
1203 runparams.lastpos = i;
1204 inset->latex(os, runparams);
1205 } catch (EncodingException & e) {
1206 // add location information and throw again.
1213 if (runparams.use_polyglossia && style.isEnvironment())
1219 if (os.texrow().rows() > previous_row_count) {
1220 os.texrow().start(owner_->id(), i + 1);
1223 column += (unsigned int)(os.os().tellp() - len);
1226 if (owner_->isDeleted(i))
1227 --runparams.inDeletedInset;
1231 void Paragraph::Private::latexSpecialChar(otexstream & os,
1232 BufferParams const & bparams,
1233 OutputParams const & runparams,
1234 Font const & running_font,
1235 Change const & running_change,
1236 Layout const & style,
1239 unsigned int & column)
1241 char_type const c = owner_->getUChar(bparams, runparams, i);
1243 if (style.pass_thru || runparams.pass_thru
1244 || contains(style.pass_thru_chars, c)
1245 || contains(runparams.pass_thru_chars, c)) {
1247 Encoding const * const enc = runparams.encoding;
1248 if (enc && !enc->encodable(c))
1249 throw EncodingException(c);
1255 // TIPA uses its own T3 encoding
1256 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1258 // If T1 font encoding is used, use the special
1259 // characters it provides.
1260 // NOTE: Some languages reset the font encoding internally to a
1261 // non-standard font encoding. If we are using such a language,
1262 // we do not output special T1 chars.
1263 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1264 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1265 && latexSpecialT1(c, os, i, column))
1267 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1268 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1269 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1272 // Otherwise, we use what LaTeX provides us.
1275 os << "\\textbackslash" << termcmd;
1279 os << "\\textless" << termcmd;
1283 os << "\\textgreater" << termcmd;
1287 os << "\\textbar" << termcmd;
1292 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1293 (end_pos == -1 || i + 1 < end_pos) &&
1294 text_[i+1] == '-') {
1295 // Prevent "--" becoming an en dash and "---" an em dash.
1296 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1302 os << "\\textquotedbl" << termcmd;
1307 case '%': case '#': case '{':
1315 os << "\\textasciitilde" << termcmd;
1320 os << "\\textasciicircum" << termcmd;
1327 // avoid being mistaken for optional arguments
1335 // Blanks are printed before font switching.
1336 // Sure? I am not! (try nice-latex)
1337 // I am sure it's correct. LyX might be smarter
1338 // in the future, but for now, nothing wrong is
1344 // XeTeX's dash behaviour is determined via a global setting
1345 if (bparams.use_dash_ligatures
1346 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1348 // TODO #10961: && not in inset Flex Code
1349 // TODO #10961: && not in layout LyXCode
1350 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1367 Encoding const & encoding = *(runparams.encoding);
1368 char_type next = '\0';
1369 if (i + 1 < int(text_.size())) {
1370 next = text_[i + 1];
1371 if (Encodings::isCombiningChar(next)) {
1372 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1378 pair<docstring, bool> latex = encoding.latexChar(c);
1379 docstring nextlatex;
1380 bool nexttipas = false;
1381 string nexttipashortcut;
1382 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1383 nextlatex = encoding.latexChar(next).first;
1384 if (runparams.inIPA) {
1385 nexttipashortcut = Encodings::TIPAShortcut(next);
1386 nexttipas = !nexttipashortcut.empty();
1390 if (runparams.inIPA) {
1391 string const tipashortcut = Encodings::TIPAShortcut(c);
1392 if (!tipashortcut.empty()) {
1393 latex.first = from_ascii(tipashortcut);
1394 latex.second = false;
1399 fontenc = running_font.language()->fontenc(bparams);
1400 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
1401 // whether they are encodable or not (it only depends on the font encoding)
1402 if (!runparams.isFullUnicode() && Encodings::isKnownScriptChar(c, script)) {
1403 docstring const wrapper = from_ascii("\\" + script + "{");
1404 docstring ltx = latex.first;
1405 if (!prefixIs(ltx, wrapper))
1406 ltx = wrapper + latex.first + from_ascii("}");
1407 column += writeScriptChars(bparams, runparams, os, ltx, running_change,
1408 encoding, fontenc, i) - 1;
1409 } else if (latex.second
1410 && ((!prefixIs(nextlatex, '\\')
1411 && !prefixIs(nextlatex, '{')
1412 && !prefixIs(nextlatex, '}'))
1414 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1416 // Prevent eating of a following
1417 // space or command corruption by
1418 // following characters
1419 if (next == ' ' || next == '\0') {
1420 column += latex.first.length() + 1;
1421 os << latex.first << "{}";
1423 column += latex.first.length();
1424 os << latex.first << " ";
1427 column += latex.first.length() - 1;
1435 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1436 pos_type i, unsigned int & column)
1442 // In T1 encoding, these characters exist
1443 // but we should avoid ligatures
1444 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1446 os << "\\textcompwordmark" << termcmd;
1453 // soul.sty breaks with \char`\"
1454 os << "\\textquotedbl" << termcmd;
1463 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1464 pos_type i, unsigned int & column)
1466 // TU encoding is currently on par with T1.
1467 return latexSpecialT1(c, os, i, column);
1471 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1472 pos_type /*i*/, unsigned int & column)
1482 os << "\\textvertline" << termcmd;
1491 void Paragraph::Private::validate(LaTeXFeatures & features) const
1493 if (layout_->inpreamble && inset_owner_) {
1494 // FIXME: Using a string stream here circumvents the encoding
1495 // switching machinery of odocstream. Therefore the
1496 // output is wrong if this paragraph contains content
1497 // that needs to switch encoding.
1498 Buffer const & buf = inset_owner_->buffer();
1499 otexstringstream os;
1500 os << layout_->preamble();
1501 size_t const length = os.length();
1502 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1503 features.runparams(), string(), 0, -1, true);
1504 if (os.length() > length)
1505 features.addPreambleSnippet(os.release(), true);
1508 if (features.runparams().flavor == OutputParams::HTML
1509 && layout_->htmltitle()) {
1510 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1513 // check the params.
1514 if (!params_.spacing().isDefault())
1515 features.require("setspace");
1518 features.useLayout(layout_->name());
1521 fontlist_.validate(features);
1523 // then the indentation
1524 if (!params_.leftIndent().zero())
1525 features.require("ParagraphLeftIndent");
1528 InsetList::const_iterator icit = insetlist_.begin();
1529 InsetList::const_iterator iend = insetlist_.end();
1530 for (; icit != iend; ++icit) {
1532 features.inDeletedInset(owner_->isDeleted(icit->pos));
1533 if (icit->inset->lyxCode() == FOOT_CODE) {
1534 // FIXME: an item inset would make things much easier.
1535 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1536 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1537 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1538 && (icit->pos < begin_of_body_
1539 || (icit->pos == begin_of_body_
1540 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1541 features.saveNoteEnv("description");
1543 icit->inset->validate(features);
1544 features.inDeletedInset(false);
1545 if (layout_->needprotect &&
1546 icit->inset->lyxCode() == FOOT_CODE)
1547 features.require("NeedLyXFootnoteCode");
1551 // then the contents
1552 BufferParams const bp = features.runparams().is_child
1553 ? features.buffer().masterParams() : features.buffer().params();
1554 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1555 char_type c = text_[i];
1556 CharInfo const & ci = Encodings::unicodeCharInfo(c);
1558 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1559 features.require("textquotedblp");
1560 else if (bp.main_font_encoding() != "T1"
1561 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1562 features.require("textquotedbl");
1563 } else if (ci.textfeature() && contains(ci.textpreamble(), '=')) {
1564 // features that depend on the font or input encoding
1565 string feats = ci.textpreamble();
1566 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1567 if (fontenc.empty())
1568 fontenc = features.runparams().main_fontenc;
1569 while (!feats.empty()) {
1571 feats = split(feats, feat, ',');
1572 if (contains(feat, "!=")) {
1573 // a feature that is required except for the spcified
1574 // font or input encodings
1576 string const contexts = ltrim(split(feat, realfeature, '!'), "=");
1577 // multiple encodings are separated by semicolon
1578 vector<string> context = getVectorFromString(contexts, ";");
1579 // require feature if the context matches neither current font
1580 // nor input encoding
1581 if (std::find(context.begin(), context.end(), fontenc) == context.end()
1582 && std::find(context.begin(), context.end(),
1583 features.runparams().encoding->name()) == context.end())
1584 features.require(realfeature);
1585 } else if (contains(feat, '=')) {
1586 // a feature that is required only for the spcified
1587 // font or input encodings
1589 string const contexts = split(feat, realfeature, '=');
1590 // multiple encodings are separated by semicolon
1591 vector<string> context = getVectorFromString(contexts, ";");
1592 // require feature if the context matches either current font
1593 // or input encoding
1594 if (std::find(context.begin(), context.end(), fontenc) != context.end()
1595 || std::find(context.begin(), context.end(),
1596 features.runparams().encoding->name()) != context.end())
1597 features.require(realfeature);
1600 } else if (!bp.use_dash_ligatures
1601 && (c == 0x2013 || c == 0x2014)
1602 && bp.useNonTeXFonts
1603 && features.runparams().flavor == OutputParams::XETEX)
1604 // XeTeX's dash behaviour is determined via a global setting
1605 features.require("xetexdashbreakstate");
1606 BufferEncodings::validate(c, features);
1610 /////////////////////////////////////////////////////////////////////
1614 /////////////////////////////////////////////////////////////////////
1617 Layout const emptyParagraphLayout;
1620 Paragraph::Paragraph()
1621 : d(new Paragraph::Private(this, emptyParagraphLayout))
1628 Paragraph::Paragraph(Paragraph const & par)
1629 : itemdepth(par.itemdepth),
1630 d(new Paragraph::Private(*par.d, this))
1636 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1637 : itemdepth(par.itemdepth),
1638 d(new Paragraph::Private(*par.d, this, beg, end))
1644 Paragraph & Paragraph::operator=(Paragraph const & par)
1646 // needed as we will destroy the private part before copying it
1648 itemdepth = par.itemdepth;
1652 d = new Private(*par.d, this);
1659 Paragraph::~Paragraph()
1668 // this shall be called just before every "os << ..." action.
1669 void flushString(ostream & os, docstring & s)
1678 void Paragraph::write(ostream & os, BufferParams const & bparams,
1679 depth_type & dth) const
1681 // The beginning or end of a deeper (i.e. nested) area?
1682 if (dth != d->params_.depth()) {
1683 if (d->params_.depth() > dth) {
1684 while (d->params_.depth() > dth) {
1685 os << "\n\\begin_deeper";
1689 while (d->params_.depth() < dth) {
1690 os << "\n\\end_deeper";
1696 // First write the layout
1697 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1699 d->params_.write(os);
1701 Font font1(inherit_font, bparams.language);
1703 Change running_change = Change(Change::UNCHANGED);
1705 // this string is used as a buffer to avoid repetitive calls
1706 // to to_utf8(), which turn out to be expensive (JMarc)
1707 docstring write_buffer;
1710 for (pos_type i = 0; i <= size(); ++i) {
1712 Change const & change = lookupChange(i);
1713 if (change != running_change)
1714 flushString(os, write_buffer);
1715 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1716 running_change = change;
1721 // Write font changes
1722 Font font2 = getFontSettings(bparams, i);
1723 if (font2 != font1) {
1724 flushString(os, write_buffer);
1725 font2.lyxWriteChanges(font1, os);
1730 char_type const c = d->text_[i];
1733 if (Inset const * inset = getInset(i)) {
1734 flushString(os, write_buffer);
1735 if (inset->directWrite()) {
1736 // international char, let it write
1737 // code directly so it's shorter in
1743 os << "\\begin_inset ";
1745 os << "\n\\end_inset\n\n";
1748 // FIXME This can be removed again once the mystery
1749 // crash has been resolved.
1754 flushString(os, write_buffer);
1755 os << "\n\\backslash\n";
1759 flushString(os, write_buffer);
1760 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1767 if ((column > 70 && c == ' ')
1769 flushString(os, write_buffer);
1773 // this check is to amend a bug. LyX sometimes
1774 // inserts '\0' this could cause problems.
1776 write_buffer.push_back(c);
1778 LYXERR0("NUL char in structure.");
1784 flushString(os, write_buffer);
1785 os << "\n\\end_layout\n";
1786 // FIXME This can be removed again once the mystery
1787 // crash has been resolved.
1792 void Paragraph::validate(LaTeXFeatures & features) const
1794 d->validate(features);
1795 bool fragile = features.runparams().moving_arg;
1796 fragile |= layout().needprotect;
1797 if (needsCProtection(fragile))
1798 features.require("cprotect");
1802 void Paragraph::insert(pos_type start, docstring const & str,
1803 Font const & font, Change const & change)
1805 for (size_t i = 0, n = str.size(); i != n ; ++i)
1806 insertChar(start + i, str[i], font, change);
1810 void Paragraph::appendChar(char_type c, Font const & font,
1811 Change const & change)
1814 d->changes_.insert(change, d->text_.size());
1815 // when appending characters, no need to update tables
1816 d->text_.push_back(c);
1817 setFont(d->text_.size() - 1, font);
1818 d->requestSpellCheck(d->text_.size() - 1);
1822 void Paragraph::appendString(docstring const & s, Font const & font,
1823 Change const & change)
1825 pos_type end = s.size();
1826 size_t oldsize = d->text_.size();
1827 size_t newsize = oldsize + end;
1828 size_t capacity = d->text_.capacity();
1829 if (newsize >= capacity)
1830 d->text_.reserve(max(capacity + 100, newsize));
1832 // when appending characters, no need to update tables
1835 // FIXME: Optimize this!
1836 for (size_t i = oldsize; i != newsize; ++i) {
1838 d->changes_.insert(change, i);
1839 d->requestSpellCheck(i);
1841 d->fontlist_.set(oldsize, font);
1842 d->fontlist_.set(newsize - 1, font);
1846 void Paragraph::insertChar(pos_type pos, char_type c,
1849 d->insertChar(pos, c, Change(trackChanges ?
1850 Change::INSERTED : Change::UNCHANGED));
1854 void Paragraph::insertChar(pos_type pos, char_type c,
1855 Font const & font, bool trackChanges)
1857 d->insertChar(pos, c, Change(trackChanges ?
1858 Change::INSERTED : Change::UNCHANGED));
1863 void Paragraph::insertChar(pos_type pos, char_type c,
1864 Font const & font, Change const & change)
1866 d->insertChar(pos, c, change);
1871 void Paragraph::resetFonts(Font const & font)
1873 d->fontlist_.clear();
1874 d->fontlist_.set(0, font);
1875 d->fontlist_.set(d->text_.size() - 1, font);
1878 // Gets uninstantiated font setting at position.
1879 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1883 LYXERR0("pos: " << pos << " size: " << size());
1887 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1888 if (cit != d->fontlist_.end())
1891 if (pos == size() && !empty())
1892 return getFontSettings(bparams, pos - 1);
1894 // Optimisation: avoid a full font instantiation if there is no
1895 // language change from previous call.
1896 static Font previous_font;
1897 static Language const * previous_lang = 0;
1898 Language const * lang = getParLanguage(bparams);
1899 if (lang != previous_lang) {
1900 previous_lang = lang;
1901 previous_font = Font(inherit_font, lang);
1903 return previous_font;
1907 FontSpan Paragraph::fontSpan(pos_type pos) const
1909 LBUFERR(pos <= size());
1912 return FontSpan(pos, pos);
1915 FontList::const_iterator cit = d->fontlist_.begin();
1916 FontList::const_iterator end = d->fontlist_.end();
1917 for (; cit != end; ++cit) {
1918 if (cit->pos() >= pos) {
1919 if (pos >= beginOfBody())
1920 return FontSpan(max(start, beginOfBody()),
1923 return FontSpan(start,
1924 min(beginOfBody() - 1,
1927 start = cit->pos() + 1;
1930 // This should not happen, but if so, we take no chances.
1931 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1932 LASSERT(false, return FontSpan(pos, pos));
1936 // Gets uninstantiated font setting at position 0
1937 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1939 if (!empty() && !d->fontlist_.empty())
1940 return d->fontlist_.begin()->font();
1942 // Optimisation: avoid a full font instantiation if there is no
1943 // language change from previous call.
1944 static Font previous_font;
1945 static Language const * previous_lang = 0;
1946 if (bparams.language != previous_lang) {
1947 previous_lang = bparams.language;
1948 previous_font = Font(inherit_font, bparams.language);
1951 return previous_font;
1955 // Gets the fully instantiated font at a given position in a paragraph
1956 // This is basically the same function as Text::GetFont() in text2.cpp.
1957 // The difference is that this one is used for generating the LaTeX file,
1958 // and thus cosmetic "improvements" are disallowed: This has to deliver
1959 // the true picture of the buffer. (Asger)
1960 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1961 Font const & outerfont) const
1965 Font font = getFontSettings(bparams, pos);
1967 pos_type const body_pos = beginOfBody();
1968 FontInfo & fi = font.fontInfo();
1970 fi.realize(d->layout_->labelfont);
1972 fi.realize(d->layout_->font);
1974 fi.realize(outerfont.fontInfo());
1975 fi.realize(bparams.getFont().fontInfo());
1981 Font const Paragraph::getLabelFont
1982 (BufferParams const & bparams, Font const & outerfont) const
1984 FontInfo tmpfont = d->layout_->labelfont;
1985 tmpfont.realize(outerfont.fontInfo());
1986 tmpfont.realize(bparams.getFont().fontInfo());
1987 return Font(tmpfont, getParLanguage(bparams));
1991 Font const Paragraph::getLayoutFont
1992 (BufferParams const & bparams, Font const & outerfont) const
1994 FontInfo tmpfont = d->layout_->font;
1995 tmpfont.realize(outerfont.fontInfo());
1996 tmpfont.realize(bparams.getFont().fontInfo());
1997 return Font(tmpfont, getParLanguage(bparams));
2001 char_type Paragraph::getUChar(BufferParams const & bparams,
2002 OutputParams const & rp,
2005 char_type c = d->text_[pos];
2007 // Return unchanged character in LTR languages.
2008 if (!getFontSettings(bparams, pos).isRightToLeft())
2011 // FIXME This is a complete mess due to all the language-specific
2012 // special cases. We need to unify this eventually, but this
2013 // requires a file format change and some thought.
2014 // We also need to unify the input of parentheses in different RTL
2015 // languages. Currently, some have their own methods (Arabic:
2016 // 18599/lyxsvn, Hebrew: e5f42f67d/lyxgit), some don't (Urdu, Syriac).
2017 // Also note that the representation in the LyX file is probably wrong
2018 // (see FIXME in TextMetrics::breakRow).
2019 // Most likely, we should simply rely on Qt's unicode handling here.
2020 string const & lang = getFontSettings(bparams, pos).language()->lang();
2022 // With polyglossia, brackets and stuff need not be reversed in RTL scripts
2023 // FIXME: The special casing for Hebrew parens is due to the special
2024 // handling on input (for Hebrew in e5f42f67d/lyxgit); see #8251.
2026 if (rp.use_polyglossia) {
2029 if (lang == "hebrew")
2033 if (lang == "hebrew")
2040 // In the following languages, brackets don't need to be reversed.
2041 // Furthermore, in arabic_arabi, they are transformed to Arabic
2042 // Ornate Parentheses (dunno if this is really wanted)
2043 bool const reversebrackets = lang != "arabic_arabtex"
2044 && lang != "arabic_arabi"
2049 if (reversebrackets)
2053 if (reversebrackets)
2074 void Paragraph::setFont(pos_type pos, Font const & font)
2076 LASSERT(pos <= size(), return);
2078 // First, reduce font against layout/label font
2079 // Update: The setCharFont() routine in text2.cpp already
2080 // reduces font, so we don't need to do that here. (Asger)
2082 d->fontlist_.set(pos, font);
2086 void Paragraph::makeSameLayout(Paragraph const & par)
2088 d->layout_ = par.d->layout_;
2089 d->params_ = par.d->params_;
2093 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2095 if (isFreeSpacing())
2101 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2102 if (eraseChar(pos, trackChanges))
2108 return count > 0 || pos > 0;
2112 bool Paragraph::hasSameLayout(Paragraph const & par) const
2114 return par.d->layout_ == d->layout_
2115 && d->params_.sameLayout(par.d->params_);
2119 depth_type Paragraph::getDepth() const
2121 return d->params_.depth();
2125 depth_type Paragraph::getMaxDepthAfter() const
2127 if (d->layout_->isEnvironment())
2128 return d->params_.depth() + 1;
2130 return d->params_.depth();
2134 LyXAlignment Paragraph::getAlign() const
2136 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2137 return d->layout_->align;
2139 return d->params_.align();
2143 docstring const & Paragraph::labelString() const
2145 return d->params_.labelString();
2149 // the next two functions are for the manual labels
2150 docstring const Paragraph::getLabelWidthString() const
2152 if (d->layout_->margintype == MARGIN_MANUAL
2153 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2154 return d->params_.labelWidthString();
2156 return _("Senseless with this layout!");
2160 void Paragraph::setLabelWidthString(docstring const & s)
2162 d->params_.labelWidthString(s);
2166 docstring Paragraph::expandLabel(Layout const & layout,
2167 BufferParams const & bparams) const
2169 return expandParagraphLabel(layout, bparams, true);
2173 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2174 BufferParams const & bparams) const
2176 return expandParagraphLabel(layout, bparams, false);
2180 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2181 BufferParams const & bparams, bool process_appendix) const
2183 DocumentClass const & tclass = bparams.documentClass();
2184 string const & lang = getParLanguage(bparams)->code();
2185 bool const in_appendix = process_appendix && d->params_.appendix();
2186 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2188 if (fmt.empty() && !layout.counter.empty())
2189 return tclass.counters().theCounter(layout.counter, lang);
2191 // handle 'inherited level parts' in 'fmt',
2192 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2193 size_t const i = fmt.find('@', 0);
2194 if (i != docstring::npos) {
2195 size_t const j = fmt.find('@', i + 1);
2196 if (j != docstring::npos) {
2197 docstring parent(fmt, i + 1, j - i - 1);
2198 docstring label = from_ascii("??");
2199 if (tclass.hasLayout(parent))
2200 label = expandParagraphLabel(tclass[parent], bparams,
2202 fmt = docstring(fmt, 0, i) + label
2203 + docstring(fmt, j + 1, docstring::npos);
2207 return tclass.counters().counterLabel(fmt, lang);
2211 void Paragraph::applyLayout(Layout const & new_layout)
2213 d->layout_ = &new_layout;
2214 LyXAlignment const oldAlign = d->params_.align();
2216 if (!(oldAlign & d->layout_->alignpossible)) {
2217 frontend::Alert::warning(_("Alignment not permitted"),
2218 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2219 d->params_.align(LYX_ALIGN_LAYOUT);
2224 pos_type Paragraph::beginOfBody() const
2226 return d->begin_of_body_;
2230 void Paragraph::setBeginOfBody()
2232 if (d->layout_->labeltype != LABEL_MANUAL) {
2233 d->begin_of_body_ = 0;
2237 // Unroll the first two cycles of the loop
2238 // and remember the previous character to
2239 // remove unnecessary getChar() calls
2241 pos_type end = size();
2242 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2245 char_type previous_char = d->text_[i];
2246 if (!(isNewline(i) || isEnvSeparator(i))) {
2248 while (i < end && previous_char != ' ') {
2249 char_type temp = d->text_[i];
2250 if (isNewline(i) || isEnvSeparator(i))
2253 previous_char = temp;
2259 d->begin_of_body_ = i;
2263 bool Paragraph::allowParagraphCustomization() const
2265 return inInset().allowParagraphCustomization();
2269 bool Paragraph::usePlainLayout() const
2271 return inInset().usePlainLayout();
2275 bool Paragraph::isPassThru() const
2277 return inInset().isPassThru() || d->layout_->pass_thru;
2282 // paragraphs inside floats need different alignment tags to avoid
2285 bool noTrivlistCentering(InsetCode code)
2287 return code == FLOAT_CODE
2288 || code == WRAP_CODE
2289 || code == CELL_CODE;
2293 string correction(string const & orig)
2295 if (orig == "flushleft")
2296 return "raggedright";
2297 if (orig == "flushright")
2298 return "raggedleft";
2299 if (orig == "center")
2305 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2306 InsetCode code, bool const lastpar, int & col)
2308 string macro = suffix + "{";
2309 if (noTrivlistCentering(code)) {
2311 // the last paragraph in non-trivlist-aligned
2312 // context is special (to avoid unwanted whitespace)
2313 if (suffix == "\\begin") {
2314 macro = "\\" + correction(env) + "{}";
2315 os << from_ascii(macro);
2316 col += macro.size();
2321 macro += correction(env);
2325 if (suffix == "\\par\\end") {
2329 os << from_ascii(macro);
2330 col += macro.size();
2331 if (suffix == "\\begin") {
2341 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2342 otexstream & os, OutputParams const & runparams) const
2347 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2348 (layout_->toggle_indent != ITOGGLE_NEVER) :
2349 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2351 if (canindent && params_.noindent() && !layout_->pass_thru) {
2352 os << "\\noindent ";
2356 LyXAlignment const curAlign = params_.align();
2358 if (curAlign == layout_->align)
2362 case LYX_ALIGN_NONE:
2363 case LYX_ALIGN_BLOCK:
2364 case LYX_ALIGN_LAYOUT:
2365 case LYX_ALIGN_SPECIAL:
2366 case LYX_ALIGN_DECIMAL:
2368 case LYX_ALIGN_LEFT:
2369 case LYX_ALIGN_RIGHT:
2370 case LYX_ALIGN_CENTER:
2371 if (runparams.moving_arg) {
2378 string const begin_tag = "\\begin";
2379 InsetCode code = ownerCode();
2380 bool const lastpar = runparams.isLastPar;
2383 case LYX_ALIGN_NONE:
2384 case LYX_ALIGN_BLOCK:
2385 case LYX_ALIGN_LAYOUT:
2386 case LYX_ALIGN_SPECIAL:
2387 case LYX_ALIGN_DECIMAL:
2389 case LYX_ALIGN_LEFT: {
2390 if (!owner_->getParLanguage(bparams)->rightToLeft())
2391 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2393 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2395 } case LYX_ALIGN_RIGHT: {
2396 if (!owner_->getParLanguage(bparams)->rightToLeft())
2397 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2399 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2401 } case LYX_ALIGN_CENTER: {
2402 corrected_env(os, begin_tag, "center", code, lastpar, column);
2411 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2412 otexstream & os, OutputParams const & runparams) const
2414 LyXAlignment const curAlign = params_.align();
2416 if (curAlign == layout_->align)
2420 case LYX_ALIGN_NONE:
2421 case LYX_ALIGN_BLOCK:
2422 case LYX_ALIGN_LAYOUT:
2423 case LYX_ALIGN_SPECIAL:
2424 case LYX_ALIGN_DECIMAL:
2426 case LYX_ALIGN_LEFT:
2427 case LYX_ALIGN_RIGHT:
2428 case LYX_ALIGN_CENTER:
2429 if (runparams.moving_arg)
2434 bool output = false;
2436 string const end_tag = "\\par\\end";
2437 InsetCode code = ownerCode();
2438 bool const lastpar = runparams.isLastPar;
2441 case LYX_ALIGN_NONE:
2442 case LYX_ALIGN_BLOCK:
2443 case LYX_ALIGN_LAYOUT:
2444 case LYX_ALIGN_SPECIAL:
2445 case LYX_ALIGN_DECIMAL:
2447 case LYX_ALIGN_LEFT: {
2448 if (!owner_->getParLanguage(bparams)->rightToLeft())
2449 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2451 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2453 } case LYX_ALIGN_RIGHT: {
2454 if (!owner_->getParLanguage(bparams)->rightToLeft())
2455 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2457 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2459 } case LYX_ALIGN_CENTER: {
2460 corrected_env(os, end_tag, "center", code, lastpar, col);
2465 return output || lastpar;
2469 // This one spits out the text of the paragraph
2470 void Paragraph::latex(BufferParams const & bparams,
2471 Font const & outerfont,
2473 OutputParams const & runparams,
2474 int start_pos, int end_pos, bool force) const
2476 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2478 // FIXME This check should not be needed. Perhaps issue an
2479 // error if it triggers.
2480 Layout const & style = inInset().forcePlainLayout() ?
2481 bparams.documentClass().plainLayout() : *d->layout_;
2483 if (!force && style.inpreamble)
2486 bool const allowcust = allowParagraphCustomization();
2488 // Current base font for all inherited font changes, without any
2489 // change caused by an individual character, except for the language:
2490 // It is set to the language of the first character.
2491 // As long as we are in the label, this font is the base font of the
2492 // label. Before the first body character it is set to the base font
2496 // Maybe we have to create a optional argument.
2497 pos_type body_pos = beginOfBody();
2498 unsigned int column = 0;
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, outerfont);
2511 basefont = getLayoutFont(bparams, 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 = Change(Change::UNCHANGED);
2521 Encoding const * const prev_encoding = runparams.encoding;
2523 os.texrow().start(id(), 0);
2525 // if the paragraph is empty, the loop will not be entered at all
2527 // For InTitle commands, we have already opened a group
2528 // in output_latex::TeXOnePar.
2529 if (style.isCommand() && !style.intitle) {
2533 if (!style.leftdelim().empty()) {
2534 os << style.leftdelim();
2535 column += style.leftdelim().size();
2538 column += d->startTeXParParams(bparams, os, runparams);
2541 // Whether a \par can be issued for insets typeset inline with text.
2542 // Yes if greater than 0. This has to be static.
2543 THREAD_LOCAL_STATIC int parInline = 0;
2545 for (pos_type i = 0; i < size(); ++i) {
2546 // First char in paragraph or after label?
2547 if (i == body_pos) {
2550 bool needPar = false;
2551 column += running_font.latexWriteEndChanges(
2552 os, bparams, runparams,
2553 basefont, basefont, needPar);
2556 basefont = getLayoutFont(bparams, outerfont);
2557 running_font = basefont;
2559 column += Changes::latexMarkChange(os, bparams,
2560 runningChange, Change(Change::UNCHANGED),
2562 runningChange = Change(Change::UNCHANGED);
2567 // For InTitle commands, we have already opened a group
2568 // in output_latex::TeXOnePar.
2569 if (style.isCommand() && !style.intitle) {
2574 if (!style.leftdelim().empty()) {
2575 os << style.leftdelim();
2576 column += style.leftdelim().size();
2580 column += d->startTeXParParams(bparams, os,
2584 runparams.wasDisplayMath = runparams.inDisplayMath;
2585 runparams.inDisplayMath = false;
2586 bool deleted_display_math = false;
2587 Change const & change = runparams.inDeletedInset
2588 ? runparams.changeOfDeletedInset : lookupChange(i);
2590 // Check whether a display math inset follows
2591 if (d->text_[i] == META_INSET
2592 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2593 InsetMath const * im = getInset(i)->asInsetMath();
2594 if (im && im->asHullInset()
2595 && im->asHullInset()->outerDisplay()) {
2596 runparams.inDisplayMath = true;
2597 // runparams.inDeletedInset will be set by
2598 // latexInset later, but we need this info
2599 // before it is called. On the other hand, we
2600 // cannot set it here because it is a counter.
2601 deleted_display_math = isDeleted(i);
2603 if (bparams.output_changes && deleted_display_math
2604 && runningChange == change
2605 && change.type == Change::DELETED
2606 && !os.afterParbreak()) {
2607 // A display math in the same paragraph follows.
2608 // We have to close and then reopen \lyxdeleted,
2609 // otherwise the math will be shifted up.
2610 OutputParams rp = runparams;
2612 bool needPar = false;
2613 column += running_font.latexWriteEndChanges(
2614 os, bparams, rp, basefont,
2618 basefont = getLayoutFont(bparams, outerfont);
2619 running_font = basefont;
2620 column += Changes::latexMarkChange(os, bparams,
2621 Change(Change::INSERTED), change, rp);
2625 if (bparams.output_changes && runningChange != change) {
2627 bool needPar = false;
2628 column += running_font.latexWriteEndChanges(
2629 os, bparams, runparams,
2630 basefont, basefont, needPar);
2633 basefont = getLayoutFont(bparams, outerfont);
2634 running_font = basefont;
2635 column += Changes::latexMarkChange(os, bparams, runningChange,
2637 runningChange = change;
2640 // do not output text which is marked deleted
2641 // if change tracking output is disabled
2642 if (!bparams.output_changes && change.deleted()) {
2648 // Fully instantiated font
2649 Font const current_font = getFont(bparams, i, outerfont);
2651 Font const last_font = running_font;
2653 // Do we need to close the previous font?
2655 (current_font != running_font ||
2656 current_font.language() != running_font.language()))
2658 bool needPar = false;
2659 column += running_font.latexWriteEndChanges(
2660 os, bparams, runparams, basefont,
2661 (i == body_pos-1) ? basefont : current_font,
2663 running_font = basefont;
2667 string const running_lang = runparams.use_polyglossia ?
2668 running_font.language()->polyglossia() : running_font.language()->babel();
2669 // close babel's font environment before opening CJK.
2670 string const lang_end_command = runparams.use_polyglossia ?
2671 "\\end{$$lang}" : lyxrc.language_command_end;
2672 bool const using_begin_end = runparams.use_polyglossia ||
2673 !lang_end_command.empty();
2674 if (!running_lang.empty() &&
2675 (!using_begin_end || running_lang == openLanguageName()) &&
2676 current_font.language()->encoding()->package() == Encoding::CJK) {
2677 string end_tag = subst(lang_end_command,
2680 os << from_ascii(end_tag);
2681 column += end_tag.length();
2682 if (using_begin_end)
2686 // Switch file encoding if necessary (and allowed)
2687 if (!runparams.pass_thru && !style.pass_thru &&
2688 runparams.encoding->package() != Encoding::none &&
2689 current_font.language()->encoding()->package() != Encoding::none) {
2690 pair<bool, int> const enc_switch =
2691 switchEncoding(os.os(), bparams, runparams,
2692 *(current_font.language()->encoding()));
2693 if (enc_switch.first) {
2694 column += enc_switch.second;
2695 runparams.encoding = current_font.language()->encoding();
2699 char_type const c = d->text_[i];
2701 // A display math inset inside an ulem command will be output
2702 // as a box of width \linewidth, so we have to either disable
2703 // indentation if the inset starts a paragraph, or start a new
2704 // line to accommodate such box. This has to be done before
2705 // writing any font changing commands.
2706 if (runparams.inDisplayMath && !deleted_display_math
2707 && runparams.inulemcmd) {
2708 if (os.afterParbreak())
2714 // Do we need to change font?
2715 if ((current_font != running_font ||
2716 current_font.language() != running_font.language()) &&
2719 odocstringstream ods;
2720 column += current_font.latexWriteStartChanges(ods, bparams,
2721 runparams, basefont,
2723 // Check again for display math in ulem commands as a
2724 // font change may also occur just before a math inset.
2725 if (runparams.inDisplayMath && !deleted_display_math
2726 && runparams.inulemcmd) {
2727 if (os.afterParbreak())
2732 running_font = current_font;
2734 docstring fontchange = ods.str();
2735 // check whether the fontchange ends with a \\textcolor
2736 // modifier and the text starts with a space (bug 4473)
2737 docstring const last_modifier = rsplit(fontchange, '\\');
2738 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2739 os << fontchange << from_ascii("{}");
2740 // check if the fontchange ends with a trailing blank
2741 // (like "\small " (see bug 3382)
2742 else if (suffixIs(fontchange, ' ') && c == ' ')
2743 os << fontchange.substr(0, fontchange.size() - 1)
2744 << from_ascii("{}");
2749 // FIXME: think about end_pos implementation...
2750 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2751 // FIXME: integrate this case in latexSpecialChar
2752 // Do not print the separation of the optional argument
2753 // if style.pass_thru is false. This works because
2754 // latexSpecialChar ignores spaces if
2755 // style.pass_thru is false.
2756 if (i != body_pos - 1) {
2757 if (d->simpleTeXBlanks(bparams, runparams, os,
2758 i, column, current_font, style)) {
2759 // A surrogate pair was output. We
2760 // must not call latexSpecialChar
2761 // in this iteration, since it would output
2762 // the combining character again.
2769 OutputParams rp = runparams;
2770 rp.free_spacing = style.free_spacing;
2771 rp.local_font = ¤t_font;
2772 rp.intitle = style.intitle;
2774 // Two major modes: LaTeX or plain
2775 // Handle here those cases common to both modes
2776 // and then split to handle the two modes separately.
2777 if (c == META_INSET) {
2778 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2779 // Greyedout notes and, in general, all insets
2780 // with InsetLayout::isDisplay() == false,
2781 // are typeset inline with the text. So, we
2782 // can add a \par to the last paragraph of
2783 // such insets only if nothing else follows.
2784 bool incremented = false;
2785 Inset const * inset = getInset(i);
2786 InsetText const * textinset = inset
2787 ? inset->asInsetText()
2789 if (i + 1 == size() && textinset
2790 && !inset->getLayout().isDisplay()) {
2791 ParagraphList const & pars =
2792 textinset->text().paragraphs();
2793 pit_type const pit = pars.size() - 1;
2794 Font const lastfont =
2795 pit < 0 || pars[pit].empty()
2796 ? pars[pit].getLayoutFont(
2799 : pars[pit].getFont(bparams,
2800 pars[pit].size() - 1,
2802 if (lastfont.fontInfo().size() !=
2803 basefont.fontInfo().size()) {
2808 d->latexInset(bparams, os, rp, running_font,
2809 basefont, outerfont, open_font,
2810 runningChange, style, i, column);
2814 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2816 d->latexSpecialChar(os, bparams, rp,
2817 running_font, runningChange,
2818 style, i, end_pos, column);
2819 } catch (EncodingException & e) {
2820 if (runparams.dryrun) {
2821 os << "<" << _("LyX Warning: ")
2822 << _("uncodable character") << " '";
2826 // add location information and throw again.
2834 // Set the encoding to that returned from latexSpecialChar (see
2835 // comment for encoding member in OutputParams.h)
2836 runparams.encoding = rp.encoding;
2838 // Also carry on the info on a closed ulem command for insets
2839 // such as Note that do not produce any output, so that no
2840 // command is ever executed but its opening was recorded.
2841 runparams.inulemcmd = rp.inulemcmd;
2844 // If we have an open font definition, we have to close it
2846 // Make sure that \\par is done with the font of the last
2847 // character if this has another size as the default.
2848 // This is necessary because LaTeX (and LyX on the screen)
2849 // calculates the space between the baselines according
2850 // to this font. (Matthias)
2852 // We must not change the font for the last paragraph
2853 // of non-multipar insets, tabular cells or commands,
2854 // since this produces unwanted whitespace.
2856 Font const font = empty()
2857 ? getLayoutFont(bparams, outerfont)
2858 : getFont(bparams, size() - 1, outerfont);
2860 InsetText const * textinset = inInset().asInsetText();
2862 bool const maintext = textinset
2863 ? textinset->text().isMainText()
2866 size_t const numpars = textinset
2867 ? textinset->text().paragraphs().size()
2870 bool needPar = false;
2872 if (style.resfont.size() != font.fontInfo().size()
2873 && (!runparams.isLastPar || maintext
2874 || (numpars > 1 && d->ownerCode() != CELL_CODE
2875 && (inInset().getLayout().isDisplay()
2877 && !style.isCommand()) {
2880 #ifdef FIXED_LANGUAGE_END_DETECTION
2882 running_font.latexWriteEndChanges(os, bparams,
2883 runparams, basefont,
2884 next_->getFont(bparams, 0, outerfont),
2887 running_font.latexWriteEndChanges(os, bparams,
2888 runparams, basefont, basefont, needPar);
2891 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2892 //FIXME: there as we start another \selectlanguage with the next paragraph if
2893 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2894 running_font.latexWriteEndChanges(os, bparams, runparams,
2895 basefont, basefont, needPar);
2898 // The \par could not be inserted at the same nesting
2899 // level of the font size change, so do it now.
2900 os << "{\\" << font.latexSize() << "\\par}";
2904 column += Changes::latexMarkChange(os, bparams, runningChange,
2905 Change(Change::UNCHANGED), runparams);
2907 // Needed if there is an optional argument but no contents.
2908 if (body_pos > 0 && body_pos == size()) {
2912 if (!style.rightdelim().empty()) {
2913 os << style.rightdelim();
2914 column += style.rightdelim().size();
2917 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2918 && runparams.encoding != prev_encoding) {
2919 runparams.encoding = prev_encoding;
2920 os << setEncoding(prev_encoding->iconvName());
2923 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2927 bool Paragraph::emptyTag() const
2929 for (pos_type i = 0; i < size(); ++i) {
2930 if (Inset const * inset = getInset(i)) {
2931 InsetCode lyx_code = inset->lyxCode();
2932 // FIXME testing like that is wrong. What is
2934 if (lyx_code != TOC_CODE &&
2935 lyx_code != INCLUDE_CODE &&
2936 lyx_code != GRAPHICS_CODE &&
2937 lyx_code != ERT_CODE &&
2938 lyx_code != LISTINGS_CODE &&
2939 lyx_code != FLOAT_CODE &&
2940 lyx_code != TABULAR_CODE) {
2944 char_type c = d->text_[i];
2945 if (c != ' ' && c != '\t')
2953 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2956 for (pos_type i = 0; i < size(); ++i) {
2957 if (Inset const * inset = getInset(i)) {
2958 InsetCode lyx_code = inset->lyxCode();
2959 if (lyx_code == LABEL_CODE) {
2960 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2961 docstring const & id = il->getParam("name");
2962 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2970 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2974 for (i = 0; i < size(); ++i) {
2975 if (Inset const * inset = getInset(i)) {
2976 inset->docbook(os, runparams);
2978 char_type c = d->text_[i];
2981 os << sgml::escapeChar(c);
2988 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2992 for (i = 0; i < size(); ++i) {
2993 if (Inset const * inset = getInset(i)) {
2994 inset->xhtml(xs, runparams);
2996 char_type c = d->text_[i];
3006 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
3009 pos_type size = text_.size();
3010 for (pos_type i = initial; i < size; ++i) {
3011 Font font = owner_->getFont(buf.params(), i, outerfont);
3012 if (text_[i] == META_INSET)
3014 if (i != initial && font != font_old)
3023 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
3025 OutputParams const & runparams,
3026 Font const & outerfont,
3027 pos_type initial) const
3029 bool emph_flag = false;
3031 Layout const & style = *d->layout_;
3033 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3035 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3038 // parsing main loop
3039 for (pos_type i = initial; i < size(); ++i) {
3040 Font font = getFont(buf.params(), i, outerfont);
3042 // handle <emphasis> tag
3043 if (font_old.emph() != font.fontInfo().emph()) {
3044 if (font.fontInfo().emph() == FONT_ON) {
3047 } else if (i != initial) {
3048 os << "</emphasis>";
3053 if (Inset const * inset = getInset(i)) {
3054 inset->docbook(os, runparams);
3056 char_type c = d->text_[i];
3058 if (style.pass_thru)
3061 os << sgml::escapeChar(c);
3063 font_old = font.fontInfo();
3067 os << "</emphasis>";
3070 if (style.free_spacing)
3072 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3078 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
3079 vector<html::EndFontTag> & tagsToClose,
3080 bool & flag, FontState curstate, html::FontTypes type)
3082 if (curstate == FONT_ON) {
3083 tagsToOpen.push_back(html::FontTag(type));
3086 tagsToClose.push_back(html::EndFontTag(type));
3093 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3095 OutputParams const & runparams,
3096 Font const & outerfont,
3097 bool start_paragraph, bool close_paragraph,
3098 pos_type initial) const
3102 // track whether we have opened these tags
3103 bool emph_flag = false;
3104 bool bold_flag = false;
3105 bool noun_flag = false;
3106 bool ubar_flag = false;
3107 bool dbar_flag = false;
3108 bool sout_flag = false;
3109 bool xout_flag = false;
3110 bool wave_flag = false;
3112 bool shap_flag = false;
3114 bool faml_flag = false;
3116 bool size_flag = false;
3118 Layout const & style = *d->layout_;
3120 if (start_paragraph)
3121 xs.startDivision(allowEmpty());
3124 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3126 FontShape curr_fs = INHERIT_SHAPE;
3127 FontFamily curr_fam = INHERIT_FAMILY;
3128 FontSize curr_size = FONT_SIZE_INHERIT;
3130 string const default_family =
3131 buf.masterBuffer()->params().fonts_default_family;
3133 vector<html::FontTag> tagsToOpen;
3134 vector<html::EndFontTag> tagsToClose;
3136 // parsing main loop
3137 for (pos_type i = initial; i < size(); ++i) {
3138 // let's not show deleted material in the output
3142 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3145 FontState curstate = font.fontInfo().emph();
3146 if (font_old.emph() != curstate)
3147 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3150 curstate = font.fontInfo().noun();
3151 if (font_old.noun() != curstate)
3152 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3155 curstate = font.fontInfo().underbar();
3156 if (font_old.underbar() != curstate)
3157 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3160 curstate = font.fontInfo().strikeout();
3161 if (font_old.strikeout() != curstate)
3162 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3165 curstate = font.fontInfo().xout();
3166 if (font_old.xout() != curstate)
3167 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3170 curstate = font.fontInfo().uuline();
3171 if (font_old.uuline() != curstate)
3172 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3175 curstate = font.fontInfo().uwave();
3176 if (font_old.uwave() != curstate)
3177 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3180 // a little hackish, but allows us to reuse what we have.
3181 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3182 if (font_old.series() != font.fontInfo().series())
3183 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3186 curr_fs = font.fontInfo().shape();
3187 FontShape old_fs = font_old.shape();
3188 if (old_fs != curr_fs) {
3192 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3195 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3197 case SMALLCAPS_SHAPE:
3198 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3204 // the other tags are for internal use
3212 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3216 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3219 case SMALLCAPS_SHAPE:
3220 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3227 // the other tags are for internal use
3234 curr_fam = font.fontInfo().family();
3235 FontFamily old_fam = font_old.family();
3236 if (old_fam != curr_fam) {
3240 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3243 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3245 case TYPEWRITER_FAMILY:
3246 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3248 case INHERIT_FAMILY:
3251 // the other tags are for internal use
3259 // we will treat a "default" font family as roman, since we have
3260 // no other idea what to do.
3261 if (default_family != "rmdefault" && default_family != "default") {
3262 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3267 if (default_family != "sfdefault") {
3268 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3272 case TYPEWRITER_FAMILY:
3273 if (default_family != "ttdefault") {
3274 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3278 case INHERIT_FAMILY:
3281 // the other tags are for internal use
3288 curr_size = font.fontInfo().size();
3289 FontSize old_size = font_old.size();
3290 if (old_size != curr_size) {
3293 case FONT_SIZE_TINY:
3294 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3296 case FONT_SIZE_SCRIPT:
3297 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3299 case FONT_SIZE_FOOTNOTE:
3300 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3302 case FONT_SIZE_SMALL:
3303 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3305 case FONT_SIZE_LARGE:
3306 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3308 case FONT_SIZE_LARGER:
3309 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3311 case FONT_SIZE_LARGEST:
3312 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3314 case FONT_SIZE_HUGE:
3315 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3317 case FONT_SIZE_HUGER:
3318 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3320 case FONT_SIZE_INCREASE:
3321 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3323 case FONT_SIZE_DECREASE:
3324 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3326 case FONT_SIZE_INHERIT:
3327 case FONT_SIZE_NORMAL:
3330 // the other tags are for internal use
3336 switch (curr_size) {
3337 case FONT_SIZE_TINY:
3338 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3341 case FONT_SIZE_SCRIPT:
3342 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3345 case FONT_SIZE_FOOTNOTE:
3346 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3349 case FONT_SIZE_SMALL:
3350 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3353 case FONT_SIZE_LARGE:
3354 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3357 case FONT_SIZE_LARGER:
3358 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3361 case FONT_SIZE_LARGEST:
3362 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3365 case FONT_SIZE_HUGE:
3366 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3369 case FONT_SIZE_HUGER:
3370 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3373 case FONT_SIZE_INCREASE:
3374 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3377 case FONT_SIZE_DECREASE:
3378 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3381 case FONT_SIZE_NORMAL:
3382 case FONT_SIZE_INHERIT:
3385 // the other tags are for internal use
3392 // Other such tags? What about the other text ranges?
3394 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3395 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3396 for (; cit != cen; ++cit)
3399 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3400 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3401 for (; sit != sen; ++sit)
3404 tagsToClose.clear();
3407 Inset const * inset = getInset(i);
3409 if (!runparams.for_toc || inset->isInToc()) {
3410 OutputParams np = runparams;
3411 np.local_font = &font;
3412 // If the paragraph has size 1, then we are in the "special
3413 // case" where we do not output the containing paragraph info
3414 if (!inset->getLayout().htmlisblock() && size() != 1)
3415 np.html_in_par = true;
3416 retval += inset->xhtml(xs, np);
3419 char_type c = getUChar(buf.masterBuffer()->params(),
3423 font_old = font.fontInfo();
3427 // I'm worried about what happens if a branch, say, is itself
3428 // wrapped in some font stuff. I think that will not work.
3430 if (close_paragraph)
3437 bool Paragraph::isHfill(pos_type pos) const
3439 Inset const * inset = getInset(pos);
3440 return inset && inset->isHfill();
3444 bool Paragraph::isNewline(pos_type pos) const
3446 // U+2028 LINE SEPARATOR
3447 // U+2029 PARAGRAPH SEPARATOR
3448 char_type const c = d->text_[pos];
3449 if (c == 0x2028 || c == 0x2029)
3451 Inset const * inset = getInset(pos);
3452 return inset && inset->lyxCode() == NEWLINE_CODE;
3456 bool Paragraph::isEnvSeparator(pos_type pos) const
3458 Inset const * inset = getInset(pos);
3459 return inset && inset->lyxCode() == SEPARATOR_CODE;
3463 bool Paragraph::isLineSeparator(pos_type pos) const
3465 char_type const c = d->text_[pos];
3466 if (isLineSeparatorChar(c))
3468 Inset const * inset = getInset(pos);
3469 return inset && inset->isLineSeparator();
3473 bool Paragraph::isWordSeparator(pos_type pos) const
3477 if (Inset const * inset = getInset(pos))
3478 return !inset->isLetter();
3479 // if we have a hard hyphen (no en- or emdash) or apostrophe
3480 // we pass this to the spell checker
3481 // FIXME: this method is subject to change, visit
3482 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3483 // to get an impression how complex this is.
3484 if (isHardHyphenOrApostrophe(pos))
3486 char_type const c = d->text_[pos];
3487 // We want to pass the escape chars to the spellchecker
3488 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3489 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3493 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3495 pos_type const psize = size();
3498 char_type const c = d->text_[pos];
3499 if (c != '-' && c != '\'')
3501 int nextpos = pos + 1;
3502 int prevpos = pos > 0 ? pos - 1 : 0;
3503 if ((nextpos == psize || isSpace(nextpos))
3504 && (pos == 0 || isSpace(prevpos)))
3510 bool Paragraph::needsCProtection(bool const fragile) const
3512 // first check the layout of the paragraph, but only in insets
3513 InsetText const * textinset = inInset().asInsetText();
3514 bool const maintext = textinset
3515 ? textinset->text().isMainText()
3518 if (!maintext && layout().needcprotect) {
3519 // Environments need cprotection regardless the content
3520 if (layout().latextype == LATEX_ENVIRONMENT)
3523 // Commands need cprotection if they contain specific chars
3524 int const nchars_escape = 9;
3525 static char_type const chars_escape[nchars_escape] = {
3526 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3528 docstring const pars = asString();
3529 for (int k = 0; k < nchars_escape; k++) {
3530 if (contains(pars, chars_escape[k]))
3535 // now check whether we have insets that need cprotection
3536 pos_type size = d->text_.size();
3537 for (pos_type i = 0; i < size; ++i)
3538 if (isInset(i) && getInset(i)->needsCProtection(maintext, fragile))
3545 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3547 return d->speller_state_.getRange(pos);
3551 bool Paragraph::isChar(pos_type pos) const
3553 if (Inset const * inset = getInset(pos))
3554 return inset->isChar();
3555 char_type const c = d->text_[pos];
3556 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3560 bool Paragraph::isSpace(pos_type pos) const
3562 if (Inset const * inset = getInset(pos))
3563 return inset->isSpace();
3564 char_type const c = d->text_[pos];
3565 return lyx::isSpace(c);
3570 Paragraph::getParLanguage(BufferParams const & bparams) const
3573 return getFirstFontSettings(bparams).language();
3574 // FIXME: we should check the prev par as well (Lgb)
3575 return bparams.language;
3579 bool Paragraph::isRTL(BufferParams const & bparams) const
3581 return getParLanguage(bparams)->rightToLeft()
3582 && !inInset().getLayout().forceLTR();
3586 void Paragraph::changeLanguage(BufferParams const & bparams,
3587 Language const * from, Language const * to)
3589 // change language including dummy font change at the end
3590 for (pos_type i = 0; i <= size(); ++i) {
3591 Font font = getFontSettings(bparams, i);
3592 if (font.language() == from) {
3593 font.setLanguage(to);
3595 d->requestSpellCheck(i);
3601 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3603 Language const * doc_language = bparams.language;
3604 for (auto const & f : d->fontlist_)
3605 if (f.font().language() != ignore_language &&
3606 f.font().language() != latex_language &&
3607 f.font().language() != doc_language)
3613 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3615 for (auto const & f : d->fontlist_) {
3616 Language const * lang = f.font().language();
3617 if (lang != ignore_language &&
3618 lang != latex_language)
3624 docstring Paragraph::asString(int options) const
3626 return asString(0, size(), options);
3630 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3632 odocstringstream os;
3635 && options & AS_STR_LABEL
3636 && !d->params_.labelString().empty())
3637 os << d->params_.labelString() << ' ';
3639 for (pos_type i = beg; i < end; ++i) {
3640 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3642 char_type const c = d->text_[i];
3643 if (isPrintable(c) || c == '\t'
3644 || (c == '\n' && (options & AS_STR_NEWLINES)))
3646 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3647 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3648 LASSERT(runparams != 0, return docstring());
3649 getInset(i)->plaintext(os, *runparams);
3651 getInset(i)->toString(os);
3660 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3661 bool const shorten, bool const label) const
3663 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3664 if (label && !labelString().empty())
3665 os += labelString() + ' ';
3666 if (!layout().isTocCaption())
3668 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3671 char_type const c = d->text_[i];
3674 else if (c == META_INSET)
3675 getInset(i)->forOutliner(os, tmplen, false);
3678 Text::shortenForOutliner(os, maxlen);
3682 void Paragraph::setInsetOwner(Inset const * inset)
3684 d->inset_owner_ = inset;
3688 int Paragraph::id() const
3694 void Paragraph::setId(int id)
3700 Layout const & Paragraph::layout() const
3706 void Paragraph::setLayout(Layout const & layout)
3708 d->layout_ = &layout;
3712 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3714 setLayout(tc.defaultLayout());
3718 void Paragraph::setPlainLayout(DocumentClass const & tc)
3720 setLayout(tc.plainLayout());
3724 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3726 if (usePlainLayout())
3727 setPlainLayout(tclass);
3729 setDefaultLayout(tclass);
3733 Inset const & Paragraph::inInset() const
3735 LBUFERR(d->inset_owner_);
3736 return *d->inset_owner_;
3740 ParagraphParameters & Paragraph::params()
3746 ParagraphParameters const & Paragraph::params() const
3752 bool Paragraph::isFreeSpacing() const
3754 if (d->layout_->free_spacing)
3756 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3760 bool Paragraph::allowEmpty() const
3762 if (d->layout_->keepempty)
3764 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3768 bool Paragraph::brokenBiblio() const
3770 // there is a problem if there is no bibitem at position 0 or
3771 // if there is another bibitem in the paragraph.
3772 return d->layout_->labeltype == LABEL_BIBLIO
3773 && (d->insetlist_.find(BIBITEM_CODE) != 0
3774 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3778 int Paragraph::fixBiblio(Buffer const & buffer)
3780 // FIXME: What about the case where paragraph is not BIBLIO
3781 // but there is an InsetBibitem?
3782 // FIXME: when there was already an inset at 0, the return value is 1,
3783 // which does not tell whether another inset has been remove; the
3784 // cursor cannot be correctly updated.
3786 if (d->layout_->labeltype != LABEL_BIBLIO)
3789 bool const track_changes = buffer.params().track_changes;
3790 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3791 bool const hasbibitem0 = bibitem_pos == 0;
3794 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3795 // There was an InsetBibitem at pos 0, and no other one => OK
3796 if (bibitem_pos == -1)
3798 // there is a bibitem at the 0 position, but since
3799 // there is a second one, we copy the second on the
3800 // first. We're assuming there are at most two of
3801 // these, which there should be.
3802 // FIXME: why does it make sense to do that rather
3803 // than keep the first? (JMarc)
3804 Inset * inset = releaseInset(bibitem_pos);
3805 d->insetlist_.begin()->inset = inset;
3806 return -bibitem_pos;
3809 // We need to create an inset at the beginning
3811 if (bibitem_pos > 0) {
3812 // there was one somewhere in the paragraph, let's move it
3813 inset = d->insetlist_.release(bibitem_pos);
3814 eraseChar(bibitem_pos, track_changes);
3817 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3818 InsetCommandParams(BIBITEM_CODE));
3820 Font font(inherit_font, buffer.params().language);
3821 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3822 : Change::UNCHANGED));
3828 void Paragraph::checkAuthors(AuthorList const & authorList)
3830 d->changes_.checkAuthors(authorList);
3834 bool Paragraph::isChanged(pos_type pos) const
3836 return lookupChange(pos).changed();
3840 bool Paragraph::isInserted(pos_type pos) const
3842 return lookupChange(pos).inserted();
3846 bool Paragraph::isDeleted(pos_type pos) const
3848 return lookupChange(pos).deleted();
3852 InsetList const & Paragraph::insetList() const
3854 return d->insetlist_;
3858 void Paragraph::setInsetBuffers(Buffer & b)
3860 d->insetlist_.setBuffer(b);
3864 void Paragraph::resetBuffer()
3866 d->insetlist_.resetBuffer();
3870 Inset * Paragraph::releaseInset(pos_type pos)
3872 Inset * inset = d->insetlist_.release(pos);
3873 /// does not honour change tracking!
3874 eraseChar(pos, false);
3879 Inset * Paragraph::getInset(pos_type pos)
3881 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3882 ? d->insetlist_.get(pos) : 0;
3886 Inset const * Paragraph::getInset(pos_type pos) const
3888 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3889 ? d->insetlist_.get(pos) : 0;
3893 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3894 pos_type & right, TextCase action)
3896 // process sequences of modified characters; in change
3897 // tracking mode, this approach results in much better
3898 // usability than changing case on a char-by-char basis
3899 // We also need to track the current font, since font
3900 // changes within sequences can occur.
3901 vector<pair<char_type, Font> > changes;
3903 bool const trackChanges = bparams.track_changes;
3905 bool capitalize = true;
3907 for (; pos < right; ++pos) {
3908 char_type oldChar = d->text_[pos];
3909 char_type newChar = oldChar;
3911 // ignore insets and don't play with deleted text!
3912 if (oldChar != META_INSET && !isDeleted(pos)) {
3914 case text_lowercase:
3915 newChar = lowercase(oldChar);
3917 case text_capitalization:
3919 newChar = uppercase(oldChar);
3923 case text_uppercase:
3924 newChar = uppercase(oldChar);
3929 if (isWordSeparator(pos) || isDeleted(pos)) {
3930 // permit capitalization again
3934 if (oldChar != newChar) {
3935 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3936 if (pos != right - 1)
3938 // step behind the changing area
3942 int erasePos = pos - changes.size();
3943 for (size_t i = 0; i < changes.size(); i++) {
3944 insertChar(pos, changes[i].first,
3947 if (!eraseChar(erasePos, trackChanges)) {
3950 ++right; // expand selection
3958 int Paragraph::find(docstring const & str, bool cs, bool mw,
3959 pos_type start_pos, bool del) const
3961 pos_type pos = start_pos;
3962 int const strsize = str.length();
3964 pos_type const parsize = d->text_.size();
3965 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3966 // Ignore "invisible" letters such as ligature breaks
3967 // and hyphenation chars while searching
3968 while (pos < parsize - 1 && isInset(pos)) {
3969 odocstringstream os;
3970 getInset(pos)->toString(os);
3971 if (!getInset(pos)->isLetter() || !os.str().empty())
3975 if (cs && str[i] != d->text_[pos])
3977 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3979 if (!del && isDeleted(pos))
3986 // if necessary, check whether string matches word
3988 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3991 && !isWordSeparator(pos))
3995 return pos - start_pos;
3999 char_type Paragraph::getChar(pos_type pos) const
4001 return d->text_[pos];
4005 pos_type Paragraph::size() const
4007 return d->text_.size();
4011 bool Paragraph::empty() const
4013 return d->text_.empty();
4017 bool Paragraph::isInset(pos_type pos) const
4019 return d->text_[pos] == META_INSET;
4023 bool Paragraph::isSeparator(pos_type pos) const
4025 //FIXME: Are we sure this can be the only separator?
4026 return d->text_[pos] == ' ';
4030 void Paragraph::deregisterWords()
4032 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4033 Private::LangWordsMap::const_iterator ite = d->words_.end();
4034 for (; itl != ite; ++itl) {
4035 WordList & wl = theWordList(itl->first);
4036 Private::Words::const_iterator it = (itl->second).begin();
4037 Private::Words::const_iterator et = (itl->second).end();
4038 for (; it != et; ++it)
4045 void Paragraph::locateWord(pos_type & from, pos_type & to,
4046 word_location const loc) const
4049 case WHOLE_WORD_STRICT:
4050 if (from == 0 || from == size()
4051 || isWordSeparator(from)
4052 || isWordSeparator(from - 1)) {
4059 // If we are already at the beginning of a word, do nothing
4060 if (!from || isWordSeparator(from - 1))
4065 // always move the cursor to the beginning of previous word
4066 while (from && !isWordSeparator(from - 1))
4070 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4073 // no need to move the 'from' cursor
4077 while (to < size() && !isWordSeparator(to))
4082 void Paragraph::collectWords()
4084 for (pos_type pos = 0; pos < size(); ++pos) {
4085 if (isWordSeparator(pos))
4087 pos_type from = pos;
4088 locateWord(from, pos, WHOLE_WORD);
4089 // Work around MSVC warning: The statement
4090 // if (pos < from + lyxrc.completion_minlength)
4091 // triggers a signed vs. unsigned warning.
4092 // I don't know why this happens, it could be a MSVC bug, or
4093 // related to LLP64 (windows) vs. LP64 (unix) programming
4094 // model, or the C++ standard might be ambigous in the section
4095 // defining the "usual arithmetic conversions". However, using
4096 // a temporary variable is safe and works on all compilers.
4097 pos_type const endpos = from + lyxrc.completion_minlength;
4100 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4101 if (cit == d->fontlist_.end())
4103 Language const * lang = cit->font().language();
4104 docstring const word = asString(from, pos, AS_STR_NONE);
4105 d->words_[lang->lang()].insert(word);
4110 void Paragraph::registerWords()
4112 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4113 Private::LangWordsMap::const_iterator ite = d->words_.end();
4114 for (; itl != ite; ++itl) {
4115 WordList & wl = theWordList(itl->first);
4116 Private::Words::const_iterator it = (itl->second).begin();
4117 Private::Words::const_iterator et = (itl->second).end();
4118 for (; it != et; ++it)
4124 void Paragraph::updateWords()
4132 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4134 SkipPositionsIterator begin = skips.begin();
4135 SkipPositions::iterator end = skips.end();
4136 if (pos > 0 && begin < end) {
4138 if (end->last == pos - 1) {
4143 skips.insert(end, FontSpan(pos, pos));
4147 Language * Paragraph::Private::locateSpellRange(
4148 pos_type & from, pos_type & to,
4149 SkipPositions & skips) const
4151 // skip leading white space
4152 while (from < to && owner_->isWordSeparator(from))
4154 // don't check empty range
4157 // get current language
4158 Language * lang = getSpellLanguage(from);
4159 pos_type last = from;
4160 bool samelang = true;
4161 bool sameinset = true;
4162 while (last < to && samelang && sameinset) {
4163 // hop to end of word
4164 while (last < to && !owner_->isWordSeparator(last)) {
4165 if (owner_->getInset(last)) {
4166 appendSkipPosition(skips, last);
4167 } else if (owner_->isDeleted(last)) {
4168 appendSkipPosition(skips, last);
4172 // hop to next word while checking for insets
4173 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4174 if (Inset const * inset = owner_->getInset(last))
4175 sameinset = inset->isChar() && inset->isLetter();
4176 if (sameinset && owner_->isDeleted(last)) {
4177 appendSkipPosition(skips, last);
4182 if (sameinset && last < to) {
4183 // now check for language change
4184 samelang = lang == getSpellLanguage(last);
4187 // if language change detected backstep is needed
4195 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4198 const_cast<Language *>(owner_->getFontSettings(
4199 inset_owner_->buffer().params(), from).language());
4200 if (lang == inset_owner_->buffer().params().language
4201 && !lyxrc.spellchecker_alt_lang.empty()) {
4203 string const lang_variety =
4204 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4205 lang->setCode(lang_code);
4206 lang->setVariety(lang_variety);
4212 void Paragraph::requestSpellCheck(pos_type pos)
4214 d->requestSpellCheck(pos);
4218 bool Paragraph::needsSpellCheck() const
4220 SpellChecker::ChangeNumber speller_change_number = 0;
4221 if (theSpellChecker())
4222 speller_change_number = theSpellChecker()->changeNumber();
4223 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4224 d->speller_state_.needsCompleteRefresh(speller_change_number);
4226 return d->needsSpellCheck();
4230 bool Paragraph::Private::ignoreWord(docstring const & word) const
4232 // Ignore words with digits
4233 // FIXME: make this customizable
4234 // (note that some checkers ignore words with digits by default)
4235 docstring::const_iterator cit = word.begin();
4236 docstring::const_iterator const end = word.end();
4237 for (; cit != end; ++cit) {
4238 if (isNumber((*cit)))
4245 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4246 WordLangTuple & wl, docstring_list & suggestions,
4247 bool do_suggestion, bool check_learned) const
4249 SpellChecker::Result result = SpellChecker::WORD_OK;
4250 SpellChecker * speller = theSpellChecker();
4254 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4257 locateWord(from, to, WHOLE_WORD);
4258 if (from == to || from >= size())
4261 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4262 Language * lang = d->getSpellLanguage(from);
4264 if (getFontSettings(d->inset_owner_->buffer().params(), from).fontInfo().nospellcheck() == FONT_ON)
4267 wl = WordLangTuple(word, lang);
4272 if (needsSpellCheck() || check_learned) {
4274 if (!d->ignoreWord(word)) {
4275 bool const trailing_dot = to < size() && d->text_[to] == '.';
4276 result = speller->check(wl);
4277 if (SpellChecker::misspelled(result) && trailing_dot) {
4278 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4279 result = speller->check(wl);
4280 if (!SpellChecker::misspelled(result)) {
4281 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4283 from << ".." << to << "]");
4285 // spell check with dot appended failed too
4286 // restore original word/lang value
4287 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4288 wl = WordLangTuple(word, lang);
4292 if (!SpellChecker::misspelled(result)) {
4293 // area up to the begin of the next word is not misspelled
4294 while (end < size() && isWordSeparator(end))
4297 d->setMisspelled(from, end, result);
4299 result = d->speller_state_.getState(from);
4303 suggestions.clear();
4305 if (SpellChecker::misspelled(result)) {
4306 LYXERR(Debug::GUI, "misspelled word: \"" <<
4308 from << ".." << to << "]");
4310 speller->suggest(wl, suggestions);
4316 void Paragraph::anonymize()
4318 // This is a very crude anonymization for now
4319 for (char_type & c : d->text_)
4320 if (isLetterChar(c) || isNumber(c))
4325 void Paragraph::Private::markMisspelledWords(
4326 pos_type const & first, pos_type const & last,
4327 SpellChecker::Result result,
4328 docstring const & word,
4329 SkipPositions const & skips)
4331 if (!SpellChecker::misspelled(result)) {
4332 setMisspelled(first, last, SpellChecker::WORD_OK);
4336 SpellChecker * speller = theSpellChecker();
4337 // locate and enumerate the error positions
4338 int nerrors = speller->numMisspelledWords();
4340 SkipPositionsIterator it = skips.begin();
4341 SkipPositionsIterator et = skips.end();
4342 for (int index = 0; index < nerrors; ++index) {
4345 speller->misspelledWord(index, wstart, wlen);
4346 /// should not happen if speller supports range checks
4347 if (!wlen) continue;
4348 docstring const misspelled = word.substr(wstart, wlen);
4349 wstart += first + numskipped;
4350 if (snext < wstart) {
4351 /// mark the range of correct spelling
4352 numskipped += countSkips(it, et, wstart);
4353 setMisspelled(snext,
4354 wstart - 1, SpellChecker::WORD_OK);
4356 snext = wstart + wlen;
4357 numskipped += countSkips(it, et, snext);
4358 /// mark the range of misspelling
4359 setMisspelled(wstart, snext, result);
4360 LYXERR(Debug::GUI, "misspelled word: \"" <<
4361 misspelled << "\" [" <<
4362 wstart << ".." << (snext-1) << "]");
4365 if (snext <= last) {
4366 /// mark the range of correct spelling at end
4367 setMisspelled(snext, last, SpellChecker::WORD_OK);
4372 void Paragraph::spellCheck() const
4374 SpellChecker * speller = theSpellChecker();
4375 if (!speller || empty() ||!needsSpellCheck())
4379 d->rangeOfSpellCheck(start, endpos);
4380 if (speller->canCheckParagraph()) {
4381 // loop until we leave the range
4382 for (pos_type first = start; first < endpos; ) {
4383 pos_type last = endpos;
4384 Private::SkipPositions skips;
4385 Language * lang = d->locateSpellRange(first, last, skips);
4386 if (first >= endpos)
4388 // start the spell checker on the unit of meaning
4389 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4390 WordLangTuple wl = WordLangTuple(word, lang);
4391 SpellChecker::Result result = word.size() ?
4392 speller->check(wl) : SpellChecker::WORD_OK;
4393 d->markMisspelledWords(first, last, result, word, skips);
4397 static docstring_list suggestions;
4398 pos_type to = endpos;
4399 while (start < endpos) {
4401 spellCheck(start, to, wl, suggestions, false);
4405 d->readySpellCheck();
4409 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4411 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4412 if (result || pos <= 0 || pos > size())
4414 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4415 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4420 string Paragraph::magicLabel() const
4423 ss << "magicparlabel-" << id();