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(otexstream & os, char_type c, char_type next,
318 OutputParams const &);
320 /// Output a space in appropriate formatting (or a surrogate pair
321 /// if the next character is a combining character).
322 /// \return whether a surrogate pair was output.
323 bool simpleTeXBlanks(OutputParams const &,
326 unsigned int & column,
328 Layout const & style);
330 /// Output consecutive unicode chars, belonging to the same script as
331 /// specified by the latex macro \p ltx, to \p os starting from \p i.
332 /// \return the number of characters written.
333 int writeScriptChars(otexstream & os, docstring const & ltx,
334 Change const &, Encoding const &,
335 std::string const, pos_type & i);
337 /// This could go to ParagraphParameters if we want to.
338 int startTeXParParams(BufferParams const &, otexstream &,
339 OutputParams const &) const;
341 /// This could go to ParagraphParameters if we want to.
342 bool endTeXParParams(BufferParams const &, otexstream &,
343 OutputParams const &) const;
346 void latexInset(BufferParams const &,
351 Font const & outerfont,
353 Change & running_change,
354 Layout const & style,
356 unsigned int & column);
359 void latexSpecialChar(
361 BufferParams const & bparams,
362 OutputParams const & runparams,
363 Font const & running_font,
364 Change const & running_change,
365 Layout const & style,
368 unsigned int & column);
375 unsigned int & column);
381 unsigned int & column);
387 unsigned int & column);
390 void validate(LaTeXFeatures & features) const;
392 /// Checks if the paragraph contains only text and no inset or font change.
393 bool onlyText(Buffer const & buf, Font const & outerfont,
394 pos_type initial) const;
396 /// a vector of speller skip positions
397 typedef vector<FontSpan> SkipPositions;
398 typedef SkipPositions::const_iterator SkipPositionsIterator;
400 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
402 Language * getSpellLanguage(pos_type const from) const;
404 Language * locateSpellRange(pos_type & from, pos_type & to,
405 SkipPositions & skips) const;
407 bool hasSpellerChange() const
409 SpellChecker::ChangeNumber speller_change_number = 0;
410 if (theSpellChecker())
411 speller_change_number = theSpellChecker()->changeNumber();
412 return speller_change_number > speller_state_.currentChangeNumber();
415 bool ignoreWord(docstring const & word) const ;
417 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
419 pos_type textsize = owner_->size();
420 // check for sane arguments
421 if (to <= from || from >= textsize)
423 FontSpan fp = FontSpan(from, to - 1);
424 speller_state_.setRange(fp, state);
427 void requestSpellCheck(pos_type pos)
430 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
432 speller_state_.needsRefresh(pos);
435 void readySpellCheck()
437 speller_state_.needsRefresh(-1);
440 bool needsSpellCheck() const
442 return speller_state_.needsRefresh();
445 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
447 speller_state_.refreshRange(first, last);
449 last = owner_->size();
452 pos_type endpos = last;
453 owner_->locateWord(first, endpos, WHOLE_WORD);
456 owner_->locateWord(last, endpos, WHOLE_WORD);
461 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
465 while (it != et && it->first < start) {
466 int skip = it->last - it->first + 1;
474 void markMisspelledWords(pos_type const & first, pos_type const & last,
475 SpellChecker::Result result,
476 docstring const & word,
477 SkipPositions const & skips);
479 InsetCode ownerCode() const
481 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
484 /// Which Paragraph owns us?
488 Inset const * inset_owner_;
497 ParagraphParameters params_;
499 /// for recording and looking up changes
503 InsetList insetlist_;
506 pos_type begin_of_body_;
508 typedef docstring TextContainer;
512 typedef set<docstring> Words;
513 typedef map<string, Words> LangWordsMap;
517 Layout const * layout_;
519 SpellCheckerState speller_state_;
523 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
524 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
531 int Paragraph::Private::make_id()
533 // The id is unique per session across buffers because it is used in
534 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
537 static atomic_uint next_id(0);
542 Paragraph::Private::Private(Private const & p, Paragraph * owner)
543 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
545 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
546 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
549 requestSpellCheck(p.text_.size());
553 Paragraph::Private::Private(Private const & p, Paragraph * owner,
554 pos_type beg, pos_type end)
555 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
556 params_(p.params_), changes_(p.changes_),
557 insetlist_(p.insetlist_, beg, end),
558 begin_of_body_(p.begin_of_body_), words_(p.words_),
561 if (beg >= pos_type(p.text_.size()))
563 text_ = p.text_.substr(beg, end - beg);
565 FontList::const_iterator fcit = fontlist_.begin();
566 FontList::const_iterator fend = fontlist_.end();
567 for (; fcit != fend; ++fcit) {
568 if (fcit->pos() < beg)
570 if (fcit->pos() >= end) {
571 // Add last entry in the fontlist_.
572 fontlist_.set(text_.size() - 1, fcit->font());
575 // Add a new entry in the fontlist_.
576 fontlist_.set(fcit->pos() - beg, fcit->font());
578 requestSpellCheck(p.text_.size());
582 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
583 bool output_active, TocBackend & backend) const
585 d->changes_.addToToc(cdit, buf, output_active, backend);
589 void Paragraph::addChangesToBuffer(Buffer const & buf) const
591 d->changes_.updateBuffer(buf);
595 bool Paragraph::isChangeUpdateRequired() const
597 return d->changes_.isUpdateRequired();
601 bool Paragraph::isDeleted(pos_type start, pos_type end) const
603 LASSERT(start >= 0 && start <= size(), return false);
604 LASSERT(end > start && end <= size() + 1, return false);
606 return d->changes_.isDeleted(start, end);
610 bool Paragraph::isChanged(pos_type start, pos_type end) const
612 LASSERT(start >= 0 && start <= size(), return false);
613 LASSERT(end > start && end <= size() + 1, return false);
615 return d->changes_.isChanged(start, end);
619 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
621 // keep the logic here in sync with the logic of eraseChars()
625 Change const & change = d->changes_.lookup(size());
626 return change.inserted() && change.currentAuthor();
630 void Paragraph::setChange(Change const & change)
632 // beware of the imaginary end-of-par character!
633 d->changes_.set(change, 0, size() + 1);
636 * Propagate the change recursively - but not in case of DELETED!
638 * Imagine that your co-author makes changes in an existing inset. He
639 * sends your document to you and you come to the conclusion that the
640 * inset should go completely. If you erase it, LyX must not delete all
641 * text within the inset. Otherwise, the change tracked insertions of
642 * your co-author get lost and there is no way to restore them later.
644 * Conclusion: An inset's content should remain untouched if you delete it
647 if (!change.deleted()) {
648 for (pos_type pos = 0; pos < size(); ++pos) {
649 if (Inset * inset = getInset(pos))
650 inset->setChange(change);
656 void Paragraph::setChange(pos_type pos, Change const & change)
658 LASSERT(pos >= 0 && pos <= size(), return);
659 d->changes_.set(change, pos);
661 // see comment in setChange(Change const &) above
662 if (!change.deleted() && pos < size())
663 if (Inset * inset = getInset(pos))
664 inset->setChange(change);
668 Change const & Paragraph::lookupChange(pos_type pos) const
670 LBUFERR(pos >= 0 && pos <= size());
671 return d->changes_.lookup(pos);
675 void Paragraph::acceptChanges(pos_type start, pos_type end)
677 LASSERT(start >= 0 && start <= size(), return);
678 LASSERT(end > start && end <= size() + 1, return);
680 for (pos_type pos = start; pos < end; ++pos) {
681 switch (lookupChange(pos).type) {
682 case Change::UNCHANGED:
683 // accept changes in nested inset
684 if (Inset * inset = getInset(pos))
685 inset->acceptChanges();
688 case Change::INSERTED:
689 d->changes_.set(Change(Change::UNCHANGED), pos);
690 // also accept changes in nested inset
691 if (Inset * inset = getInset(pos))
692 inset->acceptChanges();
695 case Change::DELETED:
696 // Suppress access to non-existent
697 // "end-of-paragraph char"
699 eraseChar(pos, false);
710 void Paragraph::rejectChanges(pos_type start, pos_type end)
712 LASSERT(start >= 0 && start <= size(), return);
713 LASSERT(end > start && end <= size() + 1, return);
715 for (pos_type pos = start; pos < end; ++pos) {
716 switch (lookupChange(pos).type) {
717 case Change::UNCHANGED:
718 // reject changes in nested inset
719 if (Inset * inset = getInset(pos))
720 inset->rejectChanges();
723 case Change::INSERTED:
724 // Suppress access to non-existent
725 // "end-of-paragraph char"
727 eraseChar(pos, false);
733 case Change::DELETED:
734 d->changes_.set(Change(Change::UNCHANGED), pos);
736 // Do NOT reject changes within a deleted inset!
737 // There may be insertions of a co-author inside of it!
745 void Paragraph::Private::insertChar(pos_type pos, char_type c,
746 Change const & change)
748 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
751 changes_.insert(change, pos);
753 // This is actually very common when parsing buffers (and
754 // maybe inserting ascii text)
755 if (pos == pos_type(text_.size())) {
756 // when appending characters, no need to update tables
758 // but we want spell checking
759 requestSpellCheck(pos);
763 text_.insert(text_.begin() + pos, c);
765 // Update the font table.
766 fontlist_.increasePosAfterPos(pos);
769 insetlist_.increasePosAfterPos(pos);
771 // Update list of misspelled positions
772 speller_state_.increasePosAfterPos(pos);
776 bool Paragraph::insertInset(pos_type pos, Inset * inset,
777 Font const & font, Change const & change)
779 LASSERT(inset, return false);
780 LASSERT(pos >= 0 && pos <= size(), return false);
782 // Paragraph::insertInset() can be used in cut/copy/paste operation where
783 // d->inset_owner_ is not set yet.
784 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
787 d->insertChar(pos, META_INSET, change);
788 LASSERT(d->text_[pos] == META_INSET, return false);
790 // Add a new entry in the insetlist_.
791 d->insetlist_.insert(inset, pos);
793 // Some insets require run of spell checker
794 requestSpellCheck(pos);
800 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
802 LASSERT(pos >= 0 && pos <= size(), return false);
804 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
807 Change change = d->changes_.lookup(pos);
809 // set the character to DELETED if
810 // a) it was previously unchanged or
811 // b) it was inserted by a co-author
813 if (!change.changed() ||
814 (change.inserted() && !change.currentAuthor())) {
815 setChange(pos, Change(Change::DELETED));
816 // request run of spell checker
817 requestSpellCheck(pos);
821 if (change.deleted())
825 // Don't physically access the imaginary end-of-paragraph character.
826 // eraseChar() can only mark it as DELETED. A physical deletion of
827 // end-of-par must be handled externally.
833 d->changes_.erase(pos);
835 // if it is an inset, delete the inset entry
836 if (d->text_[pos] == META_INSET)
837 d->insetlist_.erase(pos);
839 d->text_.erase(d->text_.begin() + pos);
841 // Update the fontlist_
842 d->fontlist_.erase(pos);
844 // Update the insetlist_
845 d->insetlist_.decreasePosAfterPos(pos);
847 // Update list of misspelled positions
848 d->speller_state_.decreasePosAfterPos(pos);
849 d->speller_state_.refreshLast(size());
855 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
857 LASSERT(start >= 0 && start <= size(), return 0);
858 LASSERT(end >= start && end <= size() + 1, return 0);
861 for (pos_type count = end - start; count; --count) {
862 if (!eraseChar(i, trackChanges))
869 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
870 char_type next, OutputParams const & runparams)
872 // Writing next here may circumvent a possible font change between
873 // c and next. Since next is only output if it forms a surrogate pair
874 // with c we can ignore this:
875 // A font change inside a surrogate pair does not make sense and is
876 // hopefully impossible to input.
877 // FIXME: change tracking
878 // Is this correct WRT change tracking?
879 Encoding const & encoding = *(runparams.encoding);
880 docstring latex1 = encoding.latexChar(next).first;
881 if (runparams.inIPA) {
882 string const tipashortcut = Encodings::TIPAShortcut(next);
883 if (!tipashortcut.empty()) {
884 latex1 = from_ascii(tipashortcut);
887 docstring latex2 = encoding.latexChar(c).first;
889 docstring::size_type const brace1 = latex2.find_first_of(from_ascii("{"));
890 docstring::size_type const brace2 = latex2.find_last_of(from_ascii("}"));
891 string script = to_ascii(latex2.substr(1, brace1 - 1));
895 if (runparams.local_font)
896 fontenc = runparams.local_font->language()->fontenc();
898 fontenc = runparams.main_fontenc;
899 if ((script == "textgreek" && fontenc == "LGR")
900 ||(script == "textcyr" && (fontenc == "T2A" || fontenc == "T2B"
901 || fontenc == "T2C" || fontenc == "X2"))) {
902 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
905 latex2 = latex2.substr(pos, length);
908 if (docstring(1, next) == latex1) {
909 // the encoding supports the combination
910 os << latex2 << latex1;
911 return latex1.length() + latex2.length();
912 } else if (runparams.local_font &&
913 runparams.local_font->language()->lang() == "polutonikogreek") {
914 // polutonikogreek only works without the brackets
915 os << latex1 << latex2;
916 return latex1.length() + latex2.length();
918 os << latex1 << '{' << latex2 << '}';
919 return latex1.length() + latex2.length() + 2;
923 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
926 unsigned int & column,
928 Layout const & style)
930 if (style.pass_thru || runparams.pass_thru)
933 if (i + 1 < int(text_.size())) {
934 char_type next = text_[i + 1];
935 if (Encodings::isCombiningChar(next)) {
936 // This space has an accent, so we must always output it.
937 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
942 if (runparams.linelen > 0
943 && column > runparams.linelen
945 && text_[i - 1] != ' '
946 && (i + 1 < int(text_.size()))
947 // same in FreeSpacing mode
948 && !owner_->isFreeSpacing()
949 // In typewriter mode, we want to avoid
950 // ! . ? : at the end of a line
951 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
952 && (text_[i - 1] == '.'
953 || text_[i - 1] == '?'
954 || text_[i - 1] == ':'
955 || text_[i - 1] == '!'))) {
957 os.texrow().start(owner_->id(), i + 1);
959 } else if (style.free_spacing) {
968 int Paragraph::Private::writeScriptChars(otexstream & os,
969 docstring const & ltx,
970 Change const & runningChange,
971 Encoding const & encoding,
972 string const fontenc,
975 // FIXME: modifying i here is not very nice...
977 // We only arrive here when character text_[i] could not be translated
978 // into the current latex encoding (or its latex translation has been forced,)
979 // and it belongs to a known script.
980 // Parameter ltx contains the latex translation of text_[i] as specified
981 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
982 // The latex macro name "textXXX" specifies the script to which text_[i]
983 // belongs and we use it in order to check whether characters from the
984 // same script immediately follow, such that we can collect them in a
985 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
986 // for the first char but only "<spec>" for all subsequent chars.
987 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
988 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
989 string script = to_ascii(ltx.substr(1, brace1 - 1));
992 bool closing_brace = true;
993 if ((script == "textgreek" && fontenc == "LGR")
994 ||(script == "textcyr" && (fontenc == "T2A" || fontenc == "T2B"
995 || fontenc == "T2C" || fontenc == "X2"))) {
996 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
999 closing_brace = false;
1001 os << ltx.substr(pos, length);
1002 int size = text_.size();
1003 while (i + 1 < size) {
1004 char_type const next = text_[i + 1];
1005 // Stop here if next character belongs to another script
1006 // or there is a change in change tracking status.
1007 if (!Encodings::isKnownScriptChar(next, script) ||
1008 runningChange != owner_->lookupChange(i + 1))
1012 FontList::const_iterator cit = fontlist_.begin();
1013 FontList::const_iterator end = fontlist_.end();
1014 for (; cit != end; ++cit) {
1015 if (cit->pos() >= i && !found) {
1016 prev_font = cit->font();
1019 if (cit->pos() >= i + 1)
1022 // Stop here if there is a font attribute or encoding change.
1023 if (found && cit != end && prev_font != cit->font())
1025 docstring const latex = encoding.latexChar(next).first;
1026 docstring::size_type const b1 =
1027 latex.find_first_of(from_ascii("{"));
1028 docstring::size_type const b2 =
1029 latex.find_last_of(from_ascii("}"));
1030 int const len = b2 - b1 - 1;
1031 os << latex.substr(b1 + 1, len);
1035 if (closing_brace) {
1043 void Paragraph::Private::latexInset(BufferParams const & bparams,
1045 OutputParams & runparams,
1046 Font & running_font,
1048 Font const & outerfont,
1050 Change & running_change,
1051 Layout const & style,
1053 unsigned int & column)
1055 Inset * inset = owner_->getInset(i);
1058 if (style.pass_thru) {
1059 odocstringstream ods;
1060 inset->plaintext(ods, runparams);
1065 // FIXME: move this to InsetNewline::latex
1066 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1067 // newlines are handled differently here than
1068 // the default in simpleTeXSpecialChars().
1069 if (!style.newline_allowed) {
1073 bool needPar = false;
1074 column += running_font.latexWriteEndChanges(
1075 os, bparams, runparams,
1076 basefont, basefont, needPar);
1080 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1083 basefont = owner_->getLayoutFont(bparams, outerfont);
1084 running_font = basefont;
1086 if (runparams.moving_arg)
1090 os.texrow().start(owner_->id(), i + 1);
1094 if (owner_->isDeleted(i)) {
1095 if( ++runparams.inDeletedInset == 1)
1096 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1099 if (inset->canTrackChanges()) {
1100 column += Changes::latexMarkChange(os, bparams, running_change,
1101 Change(Change::UNCHANGED), runparams);
1102 running_change = Change(Change::UNCHANGED);
1106 odocstream::pos_type const len = os.os().tellp();
1108 if (inset->forceLTR()
1109 && !runparams.use_polyglossia
1110 && running_font.isRightToLeft()
1111 // ERT is an exception, it should be output with no
1112 // decorations at all
1113 && inset->lyxCode() != ERT_CODE) {
1114 if (running_font.language()->lang() == "farsi")
1115 os << "\\beginL" << termcmd;
1121 // FIXME: Bug: we can have an empty font change here!
1122 // if there has just been a font change, we are going to close it
1123 // right now, which means stupid latex code like \textsf{}. AFAIK,
1124 // this does not harm dvi output. A minor bug, thus (JMarc)
1126 // Some insets cannot be inside a font change command.
1127 // However, even such insets *can* be placed in \L or \R
1128 // or their equivalents (for RTL language switches), so we don't
1129 // close the language in those cases.
1130 // ArabTeX, though, cannot handle this special behavior, it seems.
1131 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1132 || running_font.language()->lang() == "arabic_arabtex";
1133 if (open_font && !inset->inheritFont()) {
1134 bool needPar = false;
1135 bool closeLanguage = arabtex
1136 || basefont.isRightToLeft() == running_font.isRightToLeft();
1137 unsigned int count = running_font.latexWriteEndChanges(os,
1138 bparams, runparams, basefont, basefont,
1139 needPar, closeLanguage);
1141 // if any font properties were closed, update the running_font,
1142 // making sure, however, to leave the language as it was
1144 // FIXME: probably a better way to keep track of the old
1145 // language, than copying the entire font?
1146 Font const copy_font(running_font);
1147 basefont = owner_->getLayoutFont(bparams, outerfont);
1148 running_font = basefont;
1150 running_font.setLanguage(copy_font.language());
1151 // leave font open if language is still open
1152 open_font = (running_font.language() == basefont.language());
1154 runparams.local_font = &basefont;
1158 size_t const previous_row_count = os.texrow().rows();
1161 runparams.lastid = id_;
1162 runparams.lastpos = i;
1163 inset->latex(os, runparams);
1164 } catch (EncodingException & e) {
1165 // add location information and throw again.
1172 if (running_font.language()->lang() == "farsi")
1173 os << "\\endL" << termcmd;
1178 if (os.texrow().rows() > previous_row_count) {
1179 os.texrow().start(owner_->id(), i + 1);
1182 column += (unsigned int)(os.os().tellp() - len);
1185 if (owner_->isDeleted(i))
1186 --runparams.inDeletedInset;
1190 void Paragraph::Private::latexSpecialChar(otexstream & os,
1191 BufferParams const & bparams,
1192 OutputParams const & runparams,
1193 Font const & running_font,
1194 Change const & running_change,
1195 Layout const & style,
1198 unsigned int & column)
1200 // With polyglossia, brackets and stuff need not be reversed
1201 // in RTL scripts (see bug #8251)
1202 char_type const c = (runparams.use_polyglossia) ?
1203 owner_->getUChar(bparams, i) : text_[i];
1205 if (style.pass_thru || runparams.pass_thru
1206 || contains(style.pass_thru_chars, c)
1207 || contains(runparams.pass_thru_chars, c)) {
1209 Encoding const * const enc = runparams.encoding;
1210 if (enc && !enc->encodable(c))
1211 throw EncodingException(c);
1217 // TIPA uses its own T3 encoding
1218 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1220 // If T1 font encoding is used, use the special
1221 // characters it provides.
1222 // NOTE: Some languages reset the font encoding internally to a
1223 // non-standard font encoding. If we are using such a language,
1224 // we do not output special T1 chars.
1225 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1226 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1227 && latexSpecialT1(c, os, i, column))
1229 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1230 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1231 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1234 // Otherwise, we use what LaTeX provides us.
1237 os << "\\textbackslash" << termcmd;
1241 os << "\\textless" << termcmd;
1245 os << "\\textgreater" << termcmd;
1249 os << "\\textbar" << termcmd;
1254 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1255 (end_pos == -1 || i + 1 < end_pos) &&
1256 text_[i+1] == '-') {
1257 // Prevent "--" becoming an en dash and "---" an em dash.
1258 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1264 os << "\\textquotedbl" << termcmd;
1269 case '%': case '#': case '{':
1277 os << "\\textasciitilde" << termcmd;
1282 os << "\\textasciicircum" << termcmd;
1289 // avoid being mistaken for optional arguments
1297 // Blanks are printed before font switching.
1298 // Sure? I am not! (try nice-latex)
1299 // I am sure it's correct. LyX might be smarter
1300 // in the future, but for now, nothing wrong is
1306 // XeTeX's dash behaviour is determined via a global setting
1307 if (bparams.use_dash_ligatures
1308 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1310 // TODO #10961: && not in inset Flex Code
1311 // TODO #10961: && not in layout LyXCode
1312 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1329 Encoding const & encoding = *(runparams.encoding);
1330 char_type next = '\0';
1331 if (i + 1 < int(text_.size())) {
1332 next = text_[i + 1];
1333 if (Encodings::isCombiningChar(next)) {
1334 column += latexSurrogatePair(os, c, next, runparams) - 1;
1340 pair<docstring, bool> latex = encoding.latexChar(c);
1341 docstring nextlatex;
1342 bool nexttipas = false;
1343 string nexttipashortcut;
1344 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1345 nextlatex = encoding.latexChar(next).first;
1346 if (runparams.inIPA) {
1347 nexttipashortcut = Encodings::TIPAShortcut(next);
1348 nexttipas = !nexttipashortcut.empty();
1352 if (runparams.inIPA) {
1353 string const tipashortcut = Encodings::TIPAShortcut(c);
1354 if (!tipashortcut.empty()) {
1355 latex.first = from_ascii(tipashortcut);
1356 latex.second = false;
1361 if (running_font.language()->lang() == runparams.document_language)
1362 fontenc = runparams.main_fontenc;
1364 fontenc = running_font.language()->fontenc();
1365 if (Encodings::isKnownScriptChar(c, script)
1366 && prefixIs(latex.first, from_ascii("\\" + script)))
1367 column += writeScriptChars(os, latex.first,
1368 running_change, encoding,
1370 else if (latex.second
1371 && ((!prefixIs(nextlatex, '\\')
1372 && !prefixIs(nextlatex, '{')
1373 && !prefixIs(nextlatex, '}'))
1375 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1377 // Prevent eating of a following
1378 // space or command corruption by
1379 // following characters
1380 if (next == ' ' || next == '\0') {
1381 column += latex.first.length() + 1;
1382 os << latex.first << "{}";
1384 column += latex.first.length();
1385 os << latex.first << " ";
1388 column += latex.first.length() - 1;
1396 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1397 pos_type i, unsigned int & column)
1403 // In T1 encoding, these characters exist
1404 // but we should avoid ligatures
1405 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1407 os << "\\textcompwordmark" << termcmd;
1414 // soul.sty breaks with \char`\"
1415 os << "\\textquotedbl" << termcmd;
1424 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1425 pos_type i, unsigned int & column)
1427 // TU encoding is currently on par with T1.
1428 return latexSpecialT1(c, os, i, column);
1432 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1433 pos_type /*i*/, unsigned int & column)
1443 os << "\\textvertline" << termcmd;
1452 void Paragraph::Private::validate(LaTeXFeatures & features) const
1454 if (layout_->inpreamble && inset_owner_) {
1455 // FIXME: Using a string stream here circumvents the encoding
1456 // switching machinery of odocstream. Therefore the
1457 // output is wrong if this paragraph contains content
1458 // that needs to switch encoding.
1459 Buffer const & buf = inset_owner_->buffer();
1460 otexstringstream os;
1461 os << layout_->preamble();
1462 size_t const length = os.length();
1463 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1464 features.runparams(), string(), 0, -1, true);
1465 if (os.length() > length)
1466 features.addPreambleSnippet(os.release(), true);
1469 if (features.runparams().flavor == OutputParams::HTML
1470 && layout_->htmltitle()) {
1471 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1474 // check the params.
1475 if (!params_.spacing().isDefault())
1476 features.require("setspace");
1479 features.useLayout(layout_->name());
1482 fontlist_.validate(features);
1484 // then the indentation
1485 if (!params_.leftIndent().zero())
1486 features.require("ParagraphLeftIndent");
1489 InsetList::const_iterator icit = insetlist_.begin();
1490 InsetList::const_iterator iend = insetlist_.end();
1491 for (; icit != iend; ++icit) {
1493 features.inDeletedInset(owner_->isDeleted(icit->pos));
1494 if (icit->inset->lyxCode() == FOOT_CODE) {
1495 // FIXME: an item inset would make things much easier.
1496 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1497 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1498 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1499 && (icit->pos < begin_of_body_
1500 || (icit->pos == begin_of_body_
1501 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1502 features.saveNoteEnv("description");
1504 icit->inset->validate(features);
1505 features.inDeletedInset(false);
1506 if (layout_->needprotect &&
1507 icit->inset->lyxCode() == FOOT_CODE)
1508 features.require("NeedLyXFootnoteCode");
1512 // then the contents
1513 BufferParams const bp = features.runparams().is_child
1514 ? features.buffer().masterParams() : features.buffer().params();
1515 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1516 char_type c = text_[i];
1518 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1519 features.require("textquotedblp");
1520 else if (bp.main_font_encoding() != "T1"
1521 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1522 features.require("textquotedbl");
1524 if (!bp.use_dash_ligatures
1525 && (c == 0x2013 || c == 0x2014)
1526 && bp.useNonTeXFonts
1527 && features.runparams().flavor == OutputParams::XETEX)
1528 // XeTeX's dash behaviour is determined via a global setting
1529 features.require("xetexdashbreakstate");
1530 BufferEncodings::validate(c, features);
1534 /////////////////////////////////////////////////////////////////////
1538 /////////////////////////////////////////////////////////////////////
1541 Layout const emptyParagraphLayout;
1544 Paragraph::Paragraph()
1545 : d(new Paragraph::Private(this, emptyParagraphLayout))
1552 Paragraph::Paragraph(Paragraph const & par)
1553 : itemdepth(par.itemdepth),
1554 d(new Paragraph::Private(*par.d, this))
1560 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1561 : itemdepth(par.itemdepth),
1562 d(new Paragraph::Private(*par.d, this, beg, end))
1568 Paragraph & Paragraph::operator=(Paragraph const & par)
1570 // needed as we will destroy the private part before copying it
1572 itemdepth = par.itemdepth;
1576 d = new Private(*par.d, this);
1583 Paragraph::~Paragraph()
1592 // this shall be called just before every "os << ..." action.
1593 void flushString(ostream & os, docstring & s)
1602 void Paragraph::write(ostream & os, BufferParams const & bparams,
1603 depth_type & dth) const
1605 // The beginning or end of a deeper (i.e. nested) area?
1606 if (dth != d->params_.depth()) {
1607 if (d->params_.depth() > dth) {
1608 while (d->params_.depth() > dth) {
1609 os << "\n\\begin_deeper";
1613 while (d->params_.depth() < dth) {
1614 os << "\n\\end_deeper";
1620 // First write the layout
1621 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1623 d->params_.write(os);
1625 Font font1(inherit_font, bparams.language);
1627 Change running_change = Change(Change::UNCHANGED);
1629 // this string is used as a buffer to avoid repetitive calls
1630 // to to_utf8(), which turn out to be expensive (JMarc)
1631 docstring write_buffer;
1634 for (pos_type i = 0; i <= size(); ++i) {
1636 Change const & change = lookupChange(i);
1637 if (change != running_change)
1638 flushString(os, write_buffer);
1639 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1640 running_change = change;
1645 // Write font changes
1646 Font font2 = getFontSettings(bparams, i);
1647 if (font2 != font1) {
1648 flushString(os, write_buffer);
1649 font2.lyxWriteChanges(font1, os);
1654 char_type const c = d->text_[i];
1657 if (Inset const * inset = getInset(i)) {
1658 flushString(os, write_buffer);
1659 if (inset->directWrite()) {
1660 // international char, let it write
1661 // code directly so it's shorter in
1667 os << "\\begin_inset ";
1669 os << "\n\\end_inset\n\n";
1672 // FIXME This can be removed again once the mystery
1673 // crash has been resolved.
1678 flushString(os, write_buffer);
1679 os << "\n\\backslash\n";
1683 flushString(os, write_buffer);
1684 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1691 if ((column > 70 && c == ' ')
1693 flushString(os, write_buffer);
1697 // this check is to amend a bug. LyX sometimes
1698 // inserts '\0' this could cause problems.
1700 write_buffer.push_back(c);
1702 LYXERR0("NUL char in structure.");
1708 flushString(os, write_buffer);
1709 os << "\n\\end_layout\n";
1710 // FIXME This can be removed again once the mystery
1711 // crash has been resolved.
1716 void Paragraph::validate(LaTeXFeatures & features) const
1718 d->validate(features);
1719 if (needsCProtection())
1720 features.require("cprotect");
1724 void Paragraph::insert(pos_type start, docstring const & str,
1725 Font const & font, Change const & change)
1727 for (size_t i = 0, n = str.size(); i != n ; ++i)
1728 insertChar(start + i, str[i], font, change);
1732 void Paragraph::appendChar(char_type c, Font const & font,
1733 Change const & change)
1736 d->changes_.insert(change, d->text_.size());
1737 // when appending characters, no need to update tables
1738 d->text_.push_back(c);
1739 setFont(d->text_.size() - 1, font);
1740 d->requestSpellCheck(d->text_.size() - 1);
1744 void Paragraph::appendString(docstring const & s, Font const & font,
1745 Change const & change)
1747 pos_type end = s.size();
1748 size_t oldsize = d->text_.size();
1749 size_t newsize = oldsize + end;
1750 size_t capacity = d->text_.capacity();
1751 if (newsize >= capacity)
1752 d->text_.reserve(max(capacity + 100, newsize));
1754 // when appending characters, no need to update tables
1757 // FIXME: Optimize this!
1758 for (size_t i = oldsize; i != newsize; ++i) {
1760 d->changes_.insert(change, i);
1761 d->requestSpellCheck(i);
1763 d->fontlist_.set(oldsize, font);
1764 d->fontlist_.set(newsize - 1, font);
1768 void Paragraph::insertChar(pos_type pos, char_type c,
1771 d->insertChar(pos, c, Change(trackChanges ?
1772 Change::INSERTED : Change::UNCHANGED));
1776 void Paragraph::insertChar(pos_type pos, char_type c,
1777 Font const & font, bool trackChanges)
1779 d->insertChar(pos, c, Change(trackChanges ?
1780 Change::INSERTED : Change::UNCHANGED));
1785 void Paragraph::insertChar(pos_type pos, char_type c,
1786 Font const & font, Change const & change)
1788 d->insertChar(pos, c, change);
1793 void Paragraph::resetFonts(Font const & font)
1795 d->fontlist_.clear();
1796 d->fontlist_.set(0, font);
1797 d->fontlist_.set(d->text_.size() - 1, font);
1800 // Gets uninstantiated font setting at position.
1801 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1805 LYXERR0("pos: " << pos << " size: " << size());
1809 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1810 if (cit != d->fontlist_.end())
1813 if (pos == size() && !empty())
1814 return getFontSettings(bparams, pos - 1);
1816 // Optimisation: avoid a full font instantiation if there is no
1817 // language change from previous call.
1818 static Font previous_font;
1819 static Language const * previous_lang = 0;
1820 Language const * lang = getParLanguage(bparams);
1821 if (lang != previous_lang) {
1822 previous_lang = lang;
1823 previous_font = Font(inherit_font, lang);
1825 return previous_font;
1829 FontSpan Paragraph::fontSpan(pos_type pos) const
1831 LBUFERR(pos <= size());
1834 return FontSpan(pos, pos);
1837 FontList::const_iterator cit = d->fontlist_.begin();
1838 FontList::const_iterator end = d->fontlist_.end();
1839 for (; cit != end; ++cit) {
1840 if (cit->pos() >= pos) {
1841 if (pos >= beginOfBody())
1842 return FontSpan(max(start, beginOfBody()),
1845 return FontSpan(start,
1846 min(beginOfBody() - 1,
1849 start = cit->pos() + 1;
1852 // This should not happen, but if so, we take no chances.
1853 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1854 LASSERT(false, return FontSpan(pos, pos));
1858 // Gets uninstantiated font setting at position 0
1859 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1861 if (!empty() && !d->fontlist_.empty())
1862 return d->fontlist_.begin()->font();
1864 // Optimisation: avoid a full font instantiation if there is no
1865 // language change from previous call.
1866 static Font previous_font;
1867 static Language const * previous_lang = 0;
1868 if (bparams.language != previous_lang) {
1869 previous_lang = bparams.language;
1870 previous_font = Font(inherit_font, bparams.language);
1873 return previous_font;
1877 // Gets the fully instantiated font at a given position in a paragraph
1878 // This is basically the same function as Text::GetFont() in text2.cpp.
1879 // The difference is that this one is used for generating the LaTeX file,
1880 // and thus cosmetic "improvements" are disallowed: This has to deliver
1881 // the true picture of the buffer. (Asger)
1882 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1883 Font const & outerfont) const
1887 Font font = getFontSettings(bparams, pos);
1889 pos_type const body_pos = beginOfBody();
1890 FontInfo & fi = font.fontInfo();
1892 fi.realize(d->layout_->labelfont);
1894 fi.realize(d->layout_->font);
1896 fi.realize(outerfont.fontInfo());
1897 fi.realize(bparams.getFont().fontInfo());
1903 Font const Paragraph::getLabelFont
1904 (BufferParams const & bparams, Font const & outerfont) const
1906 FontInfo tmpfont = d->layout_->labelfont;
1907 tmpfont.realize(outerfont.fontInfo());
1908 tmpfont.realize(bparams.getFont().fontInfo());
1909 return Font(tmpfont, getParLanguage(bparams));
1913 Font const Paragraph::getLayoutFont
1914 (BufferParams const & bparams, Font const & outerfont) const
1916 FontInfo tmpfont = d->layout_->font;
1917 tmpfont.realize(outerfont.fontInfo());
1918 tmpfont.realize(bparams.getFont().fontInfo());
1919 return Font(tmpfont, getParLanguage(bparams));
1923 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1925 char_type c = d->text_[pos];
1926 if (!getFontSettings(bparams, pos).isRightToLeft())
1929 // FIXME: The arabic special casing is due to the difference of arabic
1930 // round brackets input introduced in r18599. Check if this should be
1931 // unified with Hebrew or at least if all bracket types should be
1932 // handled the same (file format change in either case).
1933 string const & lang = getFontSettings(bparams, pos).language()->lang();
1934 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1939 uc = arabic ? c : ')';
1942 uc = arabic ? c : '(';
1968 void Paragraph::setFont(pos_type pos, Font const & font)
1970 LASSERT(pos <= size(), return);
1972 // First, reduce font against layout/label font
1973 // Update: The setCharFont() routine in text2.cpp already
1974 // reduces font, so we don't need to do that here. (Asger)
1976 d->fontlist_.set(pos, font);
1980 void Paragraph::makeSameLayout(Paragraph const & par)
1982 d->layout_ = par.d->layout_;
1983 d->params_ = par.d->params_;
1987 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1989 if (isFreeSpacing())
1995 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1996 if (eraseChar(pos, trackChanges))
2002 return count > 0 || pos > 0;
2006 bool Paragraph::hasSameLayout(Paragraph const & par) const
2008 return par.d->layout_ == d->layout_
2009 && d->params_.sameLayout(par.d->params_);
2013 depth_type Paragraph::getDepth() const
2015 return d->params_.depth();
2019 depth_type Paragraph::getMaxDepthAfter() const
2021 if (d->layout_->isEnvironment())
2022 return d->params_.depth() + 1;
2024 return d->params_.depth();
2028 LyXAlignment Paragraph::getAlign() const
2030 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2031 return d->layout_->align;
2033 return d->params_.align();
2037 docstring const & Paragraph::labelString() const
2039 return d->params_.labelString();
2043 // the next two functions are for the manual labels
2044 docstring const Paragraph::getLabelWidthString() const
2046 if (d->layout_->margintype == MARGIN_MANUAL
2047 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2048 return d->params_.labelWidthString();
2050 return _("Senseless with this layout!");
2054 void Paragraph::setLabelWidthString(docstring const & s)
2056 d->params_.labelWidthString(s);
2060 docstring Paragraph::expandLabel(Layout const & layout,
2061 BufferParams const & bparams) const
2063 return expandParagraphLabel(layout, bparams, true);
2067 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2068 BufferParams const & bparams) const
2070 return expandParagraphLabel(layout, bparams, false);
2074 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2075 BufferParams const & bparams, bool process_appendix) const
2077 DocumentClass const & tclass = bparams.documentClass();
2078 string const & lang = getParLanguage(bparams)->code();
2079 bool const in_appendix = process_appendix && d->params_.appendix();
2080 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2082 if (fmt.empty() && !layout.counter.empty())
2083 return tclass.counters().theCounter(layout.counter, lang);
2085 // handle 'inherited level parts' in 'fmt',
2086 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2087 size_t const i = fmt.find('@', 0);
2088 if (i != docstring::npos) {
2089 size_t const j = fmt.find('@', i + 1);
2090 if (j != docstring::npos) {
2091 docstring parent(fmt, i + 1, j - i - 1);
2092 docstring label = from_ascii("??");
2093 if (tclass.hasLayout(parent))
2094 label = expandParagraphLabel(tclass[parent], bparams,
2096 fmt = docstring(fmt, 0, i) + label
2097 + docstring(fmt, j + 1, docstring::npos);
2101 return tclass.counters().counterLabel(fmt, lang);
2105 void Paragraph::applyLayout(Layout const & new_layout)
2107 d->layout_ = &new_layout;
2108 LyXAlignment const oldAlign = d->params_.align();
2110 if (!(oldAlign & d->layout_->alignpossible)) {
2111 frontend::Alert::warning(_("Alignment not permitted"),
2112 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2113 d->params_.align(LYX_ALIGN_LAYOUT);
2118 pos_type Paragraph::beginOfBody() const
2120 return d->begin_of_body_;
2124 void Paragraph::setBeginOfBody()
2126 if (d->layout_->labeltype != LABEL_MANUAL) {
2127 d->begin_of_body_ = 0;
2131 // Unroll the first two cycles of the loop
2132 // and remember the previous character to
2133 // remove unnecessary getChar() calls
2135 pos_type end = size();
2136 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2139 char_type previous_char = d->text_[i];
2140 if (!(isNewline(i) || isEnvSeparator(i))) {
2142 while (i < end && previous_char != ' ') {
2143 char_type temp = d->text_[i];
2144 if (isNewline(i) || isEnvSeparator(i))
2147 previous_char = temp;
2153 d->begin_of_body_ = i;
2157 bool Paragraph::allowParagraphCustomization() const
2159 return inInset().allowParagraphCustomization();
2163 bool Paragraph::usePlainLayout() const
2165 return inInset().usePlainLayout();
2169 bool Paragraph::isPassThru() const
2171 return inInset().isPassThru() || d->layout_->pass_thru;
2176 // paragraphs inside floats need different alignment tags to avoid
2179 bool noTrivlistCentering(InsetCode code)
2181 return code == FLOAT_CODE
2182 || code == WRAP_CODE
2183 || code == CELL_CODE;
2187 string correction(string const & orig)
2189 if (orig == "flushleft")
2190 return "raggedright";
2191 if (orig == "flushright")
2192 return "raggedleft";
2193 if (orig == "center")
2199 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2200 InsetCode code, bool const lastpar, int & col)
2202 string macro = suffix + "{";
2203 if (noTrivlistCentering(code)) {
2205 // the last paragraph in non-trivlist-aligned
2206 // context is special (to avoid unwanted whitespace)
2207 if (suffix == "\\begin") {
2208 macro = "\\" + correction(env) + "{}";
2209 os << from_ascii(macro);
2210 col += macro.size();
2215 macro += correction(env);
2219 if (suffix == "\\par\\end") {
2223 os << from_ascii(macro);
2224 col += macro.size();
2225 if (suffix == "\\begin") {
2235 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2236 otexstream & os, OutputParams const & runparams) const
2241 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2242 (layout_->toggle_indent != ITOGGLE_NEVER) :
2243 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2245 if (canindent && params_.noindent() && !layout_->pass_thru) {
2246 os << "\\noindent ";
2250 LyXAlignment const curAlign = params_.align();
2252 if (curAlign == layout_->align)
2256 case LYX_ALIGN_NONE:
2257 case LYX_ALIGN_BLOCK:
2258 case LYX_ALIGN_LAYOUT:
2259 case LYX_ALIGN_SPECIAL:
2260 case LYX_ALIGN_DECIMAL:
2262 case LYX_ALIGN_LEFT:
2263 case LYX_ALIGN_RIGHT:
2264 case LYX_ALIGN_CENTER:
2265 if (runparams.moving_arg) {
2272 string const begin_tag = "\\begin";
2273 InsetCode code = ownerCode();
2274 bool const lastpar = runparams.isLastPar;
2277 case LYX_ALIGN_NONE:
2278 case LYX_ALIGN_BLOCK:
2279 case LYX_ALIGN_LAYOUT:
2280 case LYX_ALIGN_SPECIAL:
2281 case LYX_ALIGN_DECIMAL:
2283 case LYX_ALIGN_LEFT: {
2284 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2285 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2287 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2289 } case LYX_ALIGN_RIGHT: {
2290 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2291 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2293 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2295 } case LYX_ALIGN_CENTER: {
2296 corrected_env(os, begin_tag, "center", code, lastpar, column);
2305 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2306 otexstream & os, OutputParams const & runparams) const
2308 LyXAlignment const curAlign = params_.align();
2310 if (curAlign == layout_->align)
2314 case LYX_ALIGN_NONE:
2315 case LYX_ALIGN_BLOCK:
2316 case LYX_ALIGN_LAYOUT:
2317 case LYX_ALIGN_SPECIAL:
2318 case LYX_ALIGN_DECIMAL:
2320 case LYX_ALIGN_LEFT:
2321 case LYX_ALIGN_RIGHT:
2322 case LYX_ALIGN_CENTER:
2323 if (runparams.moving_arg)
2328 bool output = false;
2330 string const end_tag = "\\par\\end";
2331 InsetCode code = ownerCode();
2332 bool const lastpar = runparams.isLastPar;
2335 case LYX_ALIGN_NONE:
2336 case LYX_ALIGN_BLOCK:
2337 case LYX_ALIGN_LAYOUT:
2338 case LYX_ALIGN_SPECIAL:
2339 case LYX_ALIGN_DECIMAL:
2341 case LYX_ALIGN_LEFT: {
2342 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2343 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2345 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2347 } case LYX_ALIGN_RIGHT: {
2348 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2349 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2351 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2353 } case LYX_ALIGN_CENTER: {
2354 corrected_env(os, end_tag, "center", code, lastpar, col);
2359 return output || lastpar;
2363 // This one spits out the text of the paragraph
2364 void Paragraph::latex(BufferParams const & bparams,
2365 Font const & outerfont,
2367 OutputParams const & runparams,
2368 int start_pos, int end_pos, bool force) const
2370 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2372 // FIXME This check should not be needed. Perhaps issue an
2373 // error if it triggers.
2374 Layout const & style = inInset().forcePlainLayout() ?
2375 bparams.documentClass().plainLayout() : *d->layout_;
2377 if (!force && style.inpreamble)
2380 bool const allowcust = allowParagraphCustomization();
2382 // Current base font for all inherited font changes, without any
2383 // change caused by an individual character, except for the language:
2384 // It is set to the language of the first character.
2385 // As long as we are in the label, this font is the base font of the
2386 // label. Before the first body character it is set to the base font
2390 // Maybe we have to create a optional argument.
2391 pos_type body_pos = beginOfBody();
2392 unsigned int column = 0;
2395 // the optional argument is kept in curly brackets in
2396 // case it contains a ']'
2397 // This is not strictly needed, but if this is changed it
2398 // would be a file format change, and tex2lyx would need
2399 // to be adjusted, since it unconditionally removes the
2400 // braces when it parses \item.
2403 basefont = getLabelFont(bparams, outerfont);
2405 basefont = getLayoutFont(bparams, outerfont);
2408 // Which font is currently active?
2409 Font running_font(basefont);
2410 // Do we have an open font change?
2411 bool open_font = false;
2413 Change runningChange = Change(Change::UNCHANGED);
2415 Encoding const * const prev_encoding = runparams.encoding;
2417 os.texrow().start(id(), 0);
2419 // if the paragraph is empty, the loop will not be entered at all
2421 // For InTitle commands, we have already opened a group
2422 // in output_latex::TeXOnePar.
2423 if (style.isCommand() && !style.intitle) {
2427 if (!style.leftdelim().empty()) {
2428 os << style.leftdelim();
2429 column += style.leftdelim().size();
2432 column += d->startTeXParParams(bparams, os, runparams);
2435 // Whether a \par can be issued for insets typeset inline with text.
2436 // Yes if greater than 0. This has to be static.
2437 THREAD_LOCAL_STATIC int parInline = 0;
2439 for (pos_type i = 0; i < size(); ++i) {
2440 // First char in paragraph or after label?
2441 if (i == body_pos) {
2444 bool needPar = false;
2445 column += running_font.latexWriteEndChanges(
2446 os, bparams, runparams,
2447 basefont, basefont, needPar);
2450 basefont = getLayoutFont(bparams, outerfont);
2451 running_font = basefont;
2453 column += Changes::latexMarkChange(os, bparams,
2454 runningChange, Change(Change::UNCHANGED),
2456 runningChange = Change(Change::UNCHANGED);
2461 // For InTitle commands, we have already opened a group
2462 // in output_latex::TeXOnePar.
2463 if (style.isCommand() && !style.intitle) {
2468 if (!style.leftdelim().empty()) {
2469 os << style.leftdelim();
2470 column += style.leftdelim().size();
2474 column += d->startTeXParParams(bparams, os,
2478 runparams.wasDisplayMath = runparams.inDisplayMath;
2479 runparams.inDisplayMath = false;
2480 bool deleted_display_math = false;
2481 Change const & change = runparams.inDeletedInset
2482 ? runparams.changeOfDeletedInset : lookupChange(i);
2484 // Check whether a display math inset follows
2485 if (d->text_[i] == META_INSET
2486 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2487 InsetMath const * im = getInset(i)->asInsetMath();
2488 if (im && im->asHullInset()
2489 && im->asHullInset()->outerDisplay()) {
2490 runparams.inDisplayMath = true;
2491 // runparams.inDeletedInset will be set by
2492 // latexInset later, but we need this info
2493 // before it is called. On the other hand, we
2494 // cannot set it here because it is a counter.
2495 deleted_display_math = isDeleted(i);
2497 if (bparams.output_changes && deleted_display_math
2498 && runningChange == change
2499 && change.type == Change::DELETED
2500 && !os.afterParbreak()) {
2501 // A display math in the same paragraph follows.
2502 // We have to close and then reopen \lyxdeleted,
2503 // otherwise the math will be shifted up.
2504 OutputParams rp = runparams;
2506 bool needPar = false;
2507 column += running_font.latexWriteEndChanges(
2508 os, bparams, rp, basefont,
2512 basefont = getLayoutFont(bparams, outerfont);
2513 running_font = basefont;
2514 column += Changes::latexMarkChange(os, bparams,
2515 Change(Change::INSERTED), change, rp);
2519 if (bparams.output_changes && runningChange != change) {
2521 bool needPar = false;
2522 column += running_font.latexWriteEndChanges(
2523 os, bparams, runparams,
2524 basefont, basefont, needPar);
2527 basefont = getLayoutFont(bparams, outerfont);
2528 running_font = basefont;
2529 column += Changes::latexMarkChange(os, bparams, runningChange,
2531 runningChange = change;
2534 // do not output text which is marked deleted
2535 // if change tracking output is disabled
2536 if (!bparams.output_changes && change.deleted()) {
2542 // Fully instantiated font
2543 Font const current_font = getFont(bparams, i, outerfont);
2545 Font const last_font = running_font;
2547 // Do we need to close the previous font?
2549 (current_font != running_font ||
2550 current_font.language() != running_font.language()))
2552 bool needPar = false;
2553 column += running_font.latexWriteEndChanges(
2554 os, bparams, runparams, basefont,
2555 (i == body_pos-1) ? basefont : current_font,
2557 running_font = basefont;
2561 string const running_lang = runparams.use_polyglossia ?
2562 running_font.language()->polyglossia() : running_font.language()->babel();
2563 // close babel's font environment before opening CJK.
2564 string const lang_end_command = runparams.use_polyglossia ?
2565 "\\end{$$lang}" : lyxrc.language_command_end;
2566 bool const using_begin_end = runparams.use_polyglossia ||
2567 !lang_end_command.empty();
2568 if (!running_lang.empty() &&
2569 (!using_begin_end || running_lang == openLanguageName()) &&
2570 current_font.language()->encoding()->package() == Encoding::CJK) {
2571 string end_tag = subst(lang_end_command,
2574 os << from_ascii(end_tag);
2575 column += end_tag.length();
2576 if (using_begin_end)
2580 // Switch file encoding if necessary (and allowed)
2581 if (!runparams.pass_thru && !style.pass_thru &&
2582 runparams.encoding->package() != Encoding::none &&
2583 current_font.language()->encoding()->package() != Encoding::none) {
2584 pair<bool, int> const enc_switch =
2585 switchEncoding(os.os(), bparams, runparams,
2586 *(current_font.language()->encoding()));
2587 if (enc_switch.first) {
2588 column += enc_switch.second;
2589 runparams.encoding = current_font.language()->encoding();
2593 char_type const c = d->text_[i];
2595 // A display math inset inside an ulem command will be output
2596 // as a box of width \linewidth, so we have to either disable
2597 // indentation if the inset starts a paragraph, or start a new
2598 // line to accommodate such box. This has to be done before
2599 // writing any font changing commands.
2600 if (runparams.inDisplayMath && !deleted_display_math
2601 && runparams.inulemcmd) {
2602 if (os.afterParbreak())
2608 // Do we need to change font?
2609 if ((current_font != running_font ||
2610 current_font.language() != running_font.language()) &&
2613 odocstringstream ods;
2614 column += current_font.latexWriteStartChanges(ods, bparams,
2615 runparams, basefont,
2617 // Check again for display math in ulem commands as a
2618 // font change may also occur just before a math inset.
2619 if (runparams.inDisplayMath && !deleted_display_math
2620 && runparams.inulemcmd) {
2621 if (os.afterParbreak())
2626 running_font = current_font;
2628 docstring fontchange = ods.str();
2629 // check whether the fontchange ends with a \\textcolor
2630 // modifier and the text starts with a space (bug 4473)
2631 docstring const last_modifier = rsplit(fontchange, '\\');
2632 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2633 os << fontchange << from_ascii("{}");
2634 // check if the fontchange ends with a trailing blank
2635 // (like "\small " (see bug 3382)
2636 else if (suffixIs(fontchange, ' ') && c == ' ')
2637 os << fontchange.substr(0, fontchange.size() - 1)
2638 << from_ascii("{}");
2643 // FIXME: think about end_pos implementation...
2644 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2645 // FIXME: integrate this case in latexSpecialChar
2646 // Do not print the separation of the optional argument
2647 // if style.pass_thru is false. This works because
2648 // latexSpecialChar ignores spaces if
2649 // style.pass_thru is false.
2650 if (i != body_pos - 1) {
2651 if (d->simpleTeXBlanks(runparams, os,
2652 i, column, current_font, style)) {
2653 // A surrogate pair was output. We
2654 // must not call latexSpecialChar
2655 // in this iteration, since it would output
2656 // the combining character again.
2663 OutputParams rp = runparams;
2664 rp.free_spacing = style.free_spacing;
2665 rp.local_font = ¤t_font;
2666 rp.intitle = style.intitle;
2668 // Two major modes: LaTeX or plain
2669 // Handle here those cases common to both modes
2670 // and then split to handle the two modes separately.
2671 if (c == META_INSET) {
2672 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2673 // Greyedout notes and, in general, all insets
2674 // with InsetLayout::isDisplay() == false,
2675 // are typeset inline with the text. So, we
2676 // can add a \par to the last paragraph of
2677 // such insets only if nothing else follows.
2678 bool incremented = false;
2679 Inset const * inset = getInset(i);
2680 InsetText const * textinset = inset
2681 ? inset->asInsetText()
2683 if (i + 1 == size() && textinset
2684 && !inset->getLayout().isDisplay()) {
2685 ParagraphList const & pars =
2686 textinset->text().paragraphs();
2687 pit_type const pit = pars.size() - 1;
2688 Font const lastfont =
2689 pit < 0 || pars[pit].empty()
2690 ? pars[pit].getLayoutFont(
2693 : pars[pit].getFont(bparams,
2694 pars[pit].size() - 1,
2696 if (lastfont.fontInfo().size() !=
2697 basefont.fontInfo().size()) {
2702 d->latexInset(bparams, os, rp, running_font,
2703 basefont, outerfont, open_font,
2704 runningChange, style, i, column);
2708 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2710 d->latexSpecialChar(os, bparams, rp,
2711 running_font, runningChange,
2712 style, i, end_pos, column);
2713 } catch (EncodingException & e) {
2714 if (runparams.dryrun) {
2715 os << "<" << _("LyX Warning: ")
2716 << _("uncodable character") << " '";
2720 // add location information and throw again.
2728 // Set the encoding to that returned from latexSpecialChar (see
2729 // comment for encoding member in OutputParams.h)
2730 runparams.encoding = rp.encoding;
2732 // Also carry on the info on a closed ulem command for insets
2733 // such as Note that do not produce any output, so that no
2734 // command is ever executed but its opening was recorded.
2735 runparams.inulemcmd = rp.inulemcmd;
2738 // If we have an open font definition, we have to close it
2740 // Make sure that \\par is done with the font of the last
2741 // character if this has another size as the default.
2742 // This is necessary because LaTeX (and LyX on the screen)
2743 // calculates the space between the baselines according
2744 // to this font. (Matthias)
2746 // We must not change the font for the last paragraph
2747 // of non-multipar insets, tabular cells or commands,
2748 // since this produces unwanted whitespace.
2750 Font const font = empty()
2751 ? getLayoutFont(bparams, outerfont)
2752 : getFont(bparams, size() - 1, outerfont);
2754 InsetText const * textinset = inInset().asInsetText();
2756 bool const maintext = textinset
2757 ? textinset->text().isMainText()
2760 size_t const numpars = textinset
2761 ? textinset->text().paragraphs().size()
2764 bool needPar = false;
2766 if (style.resfont.size() != font.fontInfo().size()
2767 && (!runparams.isLastPar || maintext
2768 || (numpars > 1 && d->ownerCode() != CELL_CODE
2769 && (inInset().getLayout().isDisplay()
2771 && !style.isCommand()) {
2774 #ifdef FIXED_LANGUAGE_END_DETECTION
2776 running_font.latexWriteEndChanges(os, bparams,
2777 runparams, basefont,
2778 next_->getFont(bparams, 0, outerfont),
2781 running_font.latexWriteEndChanges(os, bparams,
2782 runparams, basefont, basefont, needPar);
2785 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2786 //FIXME: there as we start another \selectlanguage with the next paragraph if
2787 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2788 running_font.latexWriteEndChanges(os, bparams, runparams,
2789 basefont, basefont, needPar);
2792 // The \par could not be inserted at the same nesting
2793 // level of the font size change, so do it now.
2794 os << "{\\" << font.latexSize() << "\\par}";
2798 column += Changes::latexMarkChange(os, bparams, runningChange,
2799 Change(Change::UNCHANGED), runparams);
2801 // Needed if there is an optional argument but no contents.
2802 if (body_pos > 0 && body_pos == size()) {
2806 if (!style.rightdelim().empty()) {
2807 os << style.rightdelim();
2808 column += style.rightdelim().size();
2811 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2812 && runparams.encoding != prev_encoding) {
2813 runparams.encoding = prev_encoding;
2814 os << setEncoding(prev_encoding->iconvName());
2817 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2821 bool Paragraph::emptyTag() const
2823 for (pos_type i = 0; i < size(); ++i) {
2824 if (Inset const * inset = getInset(i)) {
2825 InsetCode lyx_code = inset->lyxCode();
2826 // FIXME testing like that is wrong. What is
2828 if (lyx_code != TOC_CODE &&
2829 lyx_code != INCLUDE_CODE &&
2830 lyx_code != GRAPHICS_CODE &&
2831 lyx_code != ERT_CODE &&
2832 lyx_code != LISTINGS_CODE &&
2833 lyx_code != FLOAT_CODE &&
2834 lyx_code != TABULAR_CODE) {
2838 char_type c = d->text_[i];
2839 if (c != ' ' && c != '\t')
2847 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2850 for (pos_type i = 0; i < size(); ++i) {
2851 if (Inset const * inset = getInset(i)) {
2852 InsetCode lyx_code = inset->lyxCode();
2853 if (lyx_code == LABEL_CODE) {
2854 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2855 docstring const & id = il->getParam("name");
2856 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2864 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2868 for (i = 0; i < size(); ++i) {
2869 if (Inset const * inset = getInset(i)) {
2870 inset->docbook(os, runparams);
2872 char_type c = d->text_[i];
2875 os << sgml::escapeChar(c);
2882 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2886 for (i = 0; i < size(); ++i) {
2887 if (Inset const * inset = getInset(i)) {
2888 inset->xhtml(xs, runparams);
2890 char_type c = d->text_[i];
2900 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2903 pos_type size = text_.size();
2904 for (pos_type i = initial; i < size; ++i) {
2905 Font font = owner_->getFont(buf.params(), i, outerfont);
2906 if (text_[i] == META_INSET)
2908 if (i != initial && font != font_old)
2917 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2919 OutputParams const & runparams,
2920 Font const & outerfont,
2921 pos_type initial) const
2923 bool emph_flag = false;
2925 Layout const & style = *d->layout_;
2927 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2929 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2932 // parsing main loop
2933 for (pos_type i = initial; i < size(); ++i) {
2934 Font font = getFont(buf.params(), i, outerfont);
2936 // handle <emphasis> tag
2937 if (font_old.emph() != font.fontInfo().emph()) {
2938 if (font.fontInfo().emph() == FONT_ON) {
2941 } else if (i != initial) {
2942 os << "</emphasis>";
2947 if (Inset const * inset = getInset(i)) {
2948 inset->docbook(os, runparams);
2950 char_type c = d->text_[i];
2952 if (style.pass_thru)
2955 os << sgml::escapeChar(c);
2957 font_old = font.fontInfo();
2961 os << "</emphasis>";
2964 if (style.free_spacing)
2966 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2972 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2973 vector<html::EndFontTag> & tagsToClose,
2974 bool & flag, FontState curstate, html::FontTypes type)
2976 if (curstate == FONT_ON) {
2977 tagsToOpen.push_back(html::FontTag(type));
2980 tagsToClose.push_back(html::EndFontTag(type));
2987 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2989 OutputParams const & runparams,
2990 Font const & outerfont,
2991 bool start_paragraph, bool close_paragraph,
2992 pos_type initial) const
2996 // track whether we have opened these tags
2997 bool emph_flag = false;
2998 bool bold_flag = false;
2999 bool noun_flag = false;
3000 bool ubar_flag = false;
3001 bool dbar_flag = false;
3002 bool sout_flag = false;
3003 bool xout_flag = false;
3004 bool wave_flag = false;
3006 bool shap_flag = false;
3008 bool faml_flag = false;
3010 bool size_flag = false;
3012 Layout const & style = *d->layout_;
3014 if (start_paragraph)
3015 xs.startDivision(allowEmpty());
3018 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3020 FontShape curr_fs = INHERIT_SHAPE;
3021 FontFamily curr_fam = INHERIT_FAMILY;
3022 FontSize curr_size = FONT_SIZE_INHERIT;
3024 string const default_family =
3025 buf.masterBuffer()->params().fonts_default_family;
3027 vector<html::FontTag> tagsToOpen;
3028 vector<html::EndFontTag> tagsToClose;
3030 // parsing main loop
3031 for (pos_type i = initial; i < size(); ++i) {
3032 // let's not show deleted material in the output
3036 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3039 FontState curstate = font.fontInfo().emph();
3040 if (font_old.emph() != curstate)
3041 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3044 curstate = font.fontInfo().noun();
3045 if (font_old.noun() != curstate)
3046 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3049 curstate = font.fontInfo().underbar();
3050 if (font_old.underbar() != curstate)
3051 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3054 curstate = font.fontInfo().strikeout();
3055 if (font_old.strikeout() != curstate)
3056 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3059 curstate = font.fontInfo().xout();
3060 if (font_old.xout() != curstate)
3061 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3064 curstate = font.fontInfo().uuline();
3065 if (font_old.uuline() != curstate)
3066 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3069 curstate = font.fontInfo().uwave();
3070 if (font_old.uwave() != curstate)
3071 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3074 // a little hackish, but allows us to reuse what we have.
3075 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3076 if (font_old.series() != font.fontInfo().series())
3077 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3080 curr_fs = font.fontInfo().shape();
3081 FontShape old_fs = font_old.shape();
3082 if (old_fs != curr_fs) {
3086 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3089 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3091 case SMALLCAPS_SHAPE:
3092 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3098 // the other tags are for internal use
3106 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3110 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3113 case SMALLCAPS_SHAPE:
3114 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3121 // the other tags are for internal use
3128 curr_fam = font.fontInfo().family();
3129 FontFamily old_fam = font_old.family();
3130 if (old_fam != curr_fam) {
3134 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3137 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3139 case TYPEWRITER_FAMILY:
3140 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3142 case INHERIT_FAMILY:
3145 // the other tags are for internal use
3153 // we will treat a "default" font family as roman, since we have
3154 // no other idea what to do.
3155 if (default_family != "rmdefault" && default_family != "default") {
3156 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3161 if (default_family != "sfdefault") {
3162 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3166 case TYPEWRITER_FAMILY:
3167 if (default_family != "ttdefault") {
3168 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3172 case INHERIT_FAMILY:
3175 // the other tags are for internal use
3182 curr_size = font.fontInfo().size();
3183 FontSize old_size = font_old.size();
3184 if (old_size != curr_size) {
3187 case FONT_SIZE_TINY:
3188 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3190 case FONT_SIZE_SCRIPT:
3191 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3193 case FONT_SIZE_FOOTNOTE:
3194 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3196 case FONT_SIZE_SMALL:
3197 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3199 case FONT_SIZE_LARGE:
3200 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3202 case FONT_SIZE_LARGER:
3203 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3205 case FONT_SIZE_LARGEST:
3206 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3208 case FONT_SIZE_HUGE:
3209 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3211 case FONT_SIZE_HUGER:
3212 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3214 case FONT_SIZE_INCREASE:
3215 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3217 case FONT_SIZE_DECREASE:
3218 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3220 case FONT_SIZE_INHERIT:
3221 case FONT_SIZE_NORMAL:
3224 // the other tags are for internal use
3230 switch (curr_size) {
3231 case FONT_SIZE_TINY:
3232 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3235 case FONT_SIZE_SCRIPT:
3236 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3239 case FONT_SIZE_FOOTNOTE:
3240 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3243 case FONT_SIZE_SMALL:
3244 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3247 case FONT_SIZE_LARGE:
3248 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3251 case FONT_SIZE_LARGER:
3252 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3255 case FONT_SIZE_LARGEST:
3256 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3259 case FONT_SIZE_HUGE:
3260 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3263 case FONT_SIZE_HUGER:
3264 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3267 case FONT_SIZE_INCREASE:
3268 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3271 case FONT_SIZE_DECREASE:
3272 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3275 case FONT_SIZE_NORMAL:
3276 case FONT_SIZE_INHERIT:
3279 // the other tags are for internal use
3286 // Other such tags? What about the other text ranges?
3288 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3289 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3290 for (; cit != cen; ++cit)
3293 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3294 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3295 for (; sit != sen; ++sit)
3298 tagsToClose.clear();
3301 Inset const * inset = getInset(i);
3303 if (!runparams.for_toc || inset->isInToc()) {
3304 OutputParams np = runparams;
3305 np.local_font = &font;
3306 // If the paragraph has size 1, then we are in the "special
3307 // case" where we do not output the containing paragraph info
3308 if (!inset->getLayout().htmlisblock() && size() != 1)
3309 np.html_in_par = true;
3310 retval += inset->xhtml(xs, np);
3313 char_type c = getUChar(buf.masterBuffer()->params(), i);
3316 font_old = font.fontInfo();
3320 // I'm worried about what happens if a branch, say, is itself
3321 // wrapped in some font stuff. I think that will not work.
3323 if (close_paragraph)
3330 bool Paragraph::isHfill(pos_type pos) const
3332 Inset const * inset = getInset(pos);
3333 return inset && inset->isHfill();
3337 bool Paragraph::isNewline(pos_type pos) const
3339 // U+2028 LINE SEPARATOR
3340 // U+2029 PARAGRAPH SEPARATOR
3341 char_type const c = d->text_[pos];
3342 if (c == 0x2028 || c == 0x2029)
3344 Inset const * inset = getInset(pos);
3345 return inset && inset->lyxCode() == NEWLINE_CODE;
3349 bool Paragraph::isEnvSeparator(pos_type pos) const
3351 Inset const * inset = getInset(pos);
3352 return inset && inset->lyxCode() == SEPARATOR_CODE;
3356 bool Paragraph::isLineSeparator(pos_type pos) const
3358 char_type const c = d->text_[pos];
3359 if (isLineSeparatorChar(c))
3361 Inset const * inset = getInset(pos);
3362 return inset && inset->isLineSeparator();
3366 bool Paragraph::isWordSeparator(pos_type pos) const
3370 if (Inset const * inset = getInset(pos))
3371 return !inset->isLetter();
3372 // if we have a hard hyphen (no en- or emdash) or apostrophe
3373 // we pass this to the spell checker
3374 // FIXME: this method is subject to change, visit
3375 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3376 // to get an impression how complex this is.
3377 if (isHardHyphenOrApostrophe(pos))
3379 char_type const c = d->text_[pos];
3380 // We want to pass the escape chars to the spellchecker
3381 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3382 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3386 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3388 pos_type const psize = size();
3391 char_type const c = d->text_[pos];
3392 if (c != '-' && c != '\'')
3394 int nextpos = pos + 1;
3395 int prevpos = pos > 0 ? pos - 1 : 0;
3396 if ((nextpos == psize || isSpace(nextpos))
3397 && (pos == 0 || isSpace(prevpos)))
3403 bool Paragraph::needsCProtection() const
3405 // first check the layout of the paragraph
3406 if (layout().needcprotect) {
3407 // Environments need cprotection regardless the content
3408 if (layout().latextype == LATEX_ENVIRONMENT)
3411 // Commands need cprotection if they contain specific chars
3412 int const nchars_escape = 9;
3413 static char_type const chars_escape[nchars_escape] = {
3414 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3416 docstring const pars = asString();
3417 for (int k = 0; k < nchars_escape; k++) {
3418 if (contains(pars, chars_escape[k]))
3423 // now check whether we have insets that need cprotection
3424 pos_type size = d->text_.size();
3425 for (pos_type i = 0; i < size; ++i)
3426 if (isInset(i) && getInset(i)->needsCProtection())
3433 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3435 return d->speller_state_.getRange(pos);
3439 bool Paragraph::isChar(pos_type pos) const
3441 if (Inset const * inset = getInset(pos))
3442 return inset->isChar();
3443 char_type const c = d->text_[pos];
3444 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3448 bool Paragraph::isSpace(pos_type pos) const
3450 if (Inset const * inset = getInset(pos))
3451 return inset->isSpace();
3452 char_type const c = d->text_[pos];
3453 return lyx::isSpace(c);
3458 Paragraph::getParLanguage(BufferParams const & bparams) const
3461 return getFirstFontSettings(bparams).language();
3462 // FIXME: we should check the prev par as well (Lgb)
3463 return bparams.language;
3467 bool Paragraph::isRTL(BufferParams const & bparams) const
3469 return getParLanguage(bparams)->rightToLeft()
3470 && !inInset().getLayout().forceLTR();
3474 void Paragraph::changeLanguage(BufferParams const & bparams,
3475 Language const * from, Language const * to)
3477 // change language including dummy font change at the end
3478 for (pos_type i = 0; i <= size(); ++i) {
3479 Font font = getFontSettings(bparams, i);
3480 if (font.language() == from) {
3481 font.setLanguage(to);
3483 d->requestSpellCheck(i);
3489 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3491 Language const * doc_language = bparams.language;
3492 for (auto const & f : d->fontlist_)
3493 if (f.font().language() != ignore_language &&
3494 f.font().language() != latex_language &&
3495 f.font().language() != doc_language)
3501 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3503 for (auto const & f : d->fontlist_) {
3504 Language const * lang = f.font().language();
3505 if (lang != ignore_language &&
3506 lang != latex_language)
3512 docstring Paragraph::asString(int options) const
3514 return asString(0, size(), options);
3518 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3520 odocstringstream os;
3523 && options & AS_STR_LABEL
3524 && !d->params_.labelString().empty())
3525 os << d->params_.labelString() << ' ';
3527 for (pos_type i = beg; i < end; ++i) {
3528 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3530 char_type const c = d->text_[i];
3531 if (isPrintable(c) || c == '\t'
3532 || (c == '\n' && (options & AS_STR_NEWLINES)))
3534 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3535 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3536 LASSERT(runparams != 0, return docstring());
3537 getInset(i)->plaintext(os, *runparams);
3539 getInset(i)->toString(os);
3548 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3549 bool const shorten, bool const label) const
3551 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3552 if (label && !labelString().empty())
3553 os += labelString() + ' ';
3554 if (!layout().isTocCaption())
3556 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3559 char_type const c = d->text_[i];
3562 else if (c == META_INSET)
3563 getInset(i)->forOutliner(os, tmplen, false);
3566 Text::shortenForOutliner(os, maxlen);
3570 void Paragraph::setInsetOwner(Inset const * inset)
3572 d->inset_owner_ = inset;
3576 int Paragraph::id() const
3582 void Paragraph::setId(int id)
3588 Layout const & Paragraph::layout() const
3594 void Paragraph::setLayout(Layout const & layout)
3596 d->layout_ = &layout;
3600 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3602 setLayout(tc.defaultLayout());
3606 void Paragraph::setPlainLayout(DocumentClass const & tc)
3608 setLayout(tc.plainLayout());
3612 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3614 if (usePlainLayout())
3615 setPlainLayout(tclass);
3617 setDefaultLayout(tclass);
3621 Inset const & Paragraph::inInset() const
3623 LBUFERR(d->inset_owner_);
3624 return *d->inset_owner_;
3628 ParagraphParameters & Paragraph::params()
3634 ParagraphParameters const & Paragraph::params() const
3640 bool Paragraph::isFreeSpacing() const
3642 if (d->layout_->free_spacing)
3644 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3648 bool Paragraph::allowEmpty() const
3650 if (d->layout_->keepempty)
3652 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3656 bool Paragraph::brokenBiblio() const
3658 // there is a problem if there is no bibitem at position 0 or
3659 // if there is another bibitem in the paragraph.
3660 return d->layout_->labeltype == LABEL_BIBLIO
3661 && (d->insetlist_.find(BIBITEM_CODE) != 0
3662 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3666 int Paragraph::fixBiblio(Buffer const & buffer)
3668 // FIXME: What about the case where paragraph is not BIBLIO
3669 // but there is an InsetBibitem?
3670 // FIXME: when there was already an inset at 0, the return value is 1,
3671 // which does not tell whether another inset has been remove; the
3672 // cursor cannot be correctly updated.
3674 if (d->layout_->labeltype != LABEL_BIBLIO)
3677 bool const track_changes = buffer.params().track_changes;
3678 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3679 bool const hasbibitem0 = bibitem_pos == 0;
3682 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3683 // There was an InsetBibitem at pos 0, and no other one => OK
3684 if (bibitem_pos == -1)
3686 // there is a bibitem at the 0 position, but since
3687 // there is a second one, we copy the second on the
3688 // first. We're assuming there are at most two of
3689 // these, which there should be.
3690 // FIXME: why does it make sense to do that rather
3691 // than keep the first? (JMarc)
3692 Inset * inset = releaseInset(bibitem_pos);
3693 d->insetlist_.begin()->inset = inset;
3694 return -bibitem_pos;
3697 // We need to create an inset at the beginning
3699 if (bibitem_pos > 0) {
3700 // there was one somewhere in the paragraph, let's move it
3701 inset = d->insetlist_.release(bibitem_pos);
3702 eraseChar(bibitem_pos, track_changes);
3705 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3706 InsetCommandParams(BIBITEM_CODE));
3708 Font font(inherit_font, buffer.params().language);
3709 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3710 : Change::UNCHANGED));
3716 void Paragraph::checkAuthors(AuthorList const & authorList)
3718 d->changes_.checkAuthors(authorList);
3722 bool Paragraph::isChanged(pos_type pos) const
3724 return lookupChange(pos).changed();
3728 bool Paragraph::isInserted(pos_type pos) const
3730 return lookupChange(pos).inserted();
3734 bool Paragraph::isDeleted(pos_type pos) const
3736 return lookupChange(pos).deleted();
3740 InsetList const & Paragraph::insetList() const
3742 return d->insetlist_;
3746 void Paragraph::setInsetBuffers(Buffer & b)
3748 d->insetlist_.setBuffer(b);
3752 void Paragraph::resetBuffer()
3754 d->insetlist_.resetBuffer();
3758 Inset * Paragraph::releaseInset(pos_type pos)
3760 Inset * inset = d->insetlist_.release(pos);
3761 /// does not honour change tracking!
3762 eraseChar(pos, false);
3767 Inset * Paragraph::getInset(pos_type pos)
3769 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3770 ? d->insetlist_.get(pos) : 0;
3774 Inset const * Paragraph::getInset(pos_type pos) const
3776 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3777 ? d->insetlist_.get(pos) : 0;
3781 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3782 pos_type & right, TextCase action)
3784 // process sequences of modified characters; in change
3785 // tracking mode, this approach results in much better
3786 // usability than changing case on a char-by-char basis
3787 // We also need to track the current font, since font
3788 // changes within sequences can occur.
3789 vector<pair<char_type, Font> > changes;
3791 bool const trackChanges = bparams.track_changes;
3793 bool capitalize = true;
3795 for (; pos < right; ++pos) {
3796 char_type oldChar = d->text_[pos];
3797 char_type newChar = oldChar;
3799 // ignore insets and don't play with deleted text!
3800 if (oldChar != META_INSET && !isDeleted(pos)) {
3802 case text_lowercase:
3803 newChar = lowercase(oldChar);
3805 case text_capitalization:
3807 newChar = uppercase(oldChar);
3811 case text_uppercase:
3812 newChar = uppercase(oldChar);
3817 if (isWordSeparator(pos) || isDeleted(pos)) {
3818 // permit capitalization again
3822 if (oldChar != newChar) {
3823 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3824 if (pos != right - 1)
3826 // step behind the changing area
3830 int erasePos = pos - changes.size();
3831 for (size_t i = 0; i < changes.size(); i++) {
3832 insertChar(pos, changes[i].first,
3835 if (!eraseChar(erasePos, trackChanges)) {
3838 ++right; // expand selection
3846 int Paragraph::find(docstring const & str, bool cs, bool mw,
3847 pos_type start_pos, bool del) const
3849 pos_type pos = start_pos;
3850 int const strsize = str.length();
3852 pos_type const parsize = d->text_.size();
3853 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3854 // Ignore "invisible" letters such as ligature breaks
3855 // and hyphenation chars while searching
3856 while (pos < parsize - 1 && isInset(pos)) {
3857 odocstringstream os;
3858 getInset(pos)->toString(os);
3859 if (!getInset(pos)->isLetter() || !os.str().empty())
3863 if (cs && str[i] != d->text_[pos])
3865 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3867 if (!del && isDeleted(pos))
3874 // if necessary, check whether string matches word
3876 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3879 && !isWordSeparator(pos))
3883 return pos - start_pos;
3887 char_type Paragraph::getChar(pos_type pos) const
3889 return d->text_[pos];
3893 pos_type Paragraph::size() const
3895 return d->text_.size();
3899 bool Paragraph::empty() const
3901 return d->text_.empty();
3905 bool Paragraph::isInset(pos_type pos) const
3907 return d->text_[pos] == META_INSET;
3911 bool Paragraph::isSeparator(pos_type pos) const
3913 //FIXME: Are we sure this can be the only separator?
3914 return d->text_[pos] == ' ';
3918 void Paragraph::deregisterWords()
3920 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3921 Private::LangWordsMap::const_iterator ite = d->words_.end();
3922 for (; itl != ite; ++itl) {
3923 WordList & wl = theWordList(itl->first);
3924 Private::Words::const_iterator it = (itl->second).begin();
3925 Private::Words::const_iterator et = (itl->second).end();
3926 for (; it != et; ++it)
3933 void Paragraph::locateWord(pos_type & from, pos_type & to,
3934 word_location const loc) const
3937 case WHOLE_WORD_STRICT:
3938 if (from == 0 || from == size()
3939 || isWordSeparator(from)
3940 || isWordSeparator(from - 1)) {
3947 // If we are already at the beginning of a word, do nothing
3948 if (!from || isWordSeparator(from - 1))
3953 // always move the cursor to the beginning of previous word
3954 while (from && !isWordSeparator(from - 1))
3958 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3961 // no need to move the 'from' cursor
3965 while (to < size() && !isWordSeparator(to))
3970 void Paragraph::collectWords()
3972 for (pos_type pos = 0; pos < size(); ++pos) {
3973 if (isWordSeparator(pos))
3975 pos_type from = pos;
3976 locateWord(from, pos, WHOLE_WORD);
3977 // Work around MSVC warning: The statement
3978 // if (pos < from + lyxrc.completion_minlength)
3979 // triggers a signed vs. unsigned warning.
3980 // I don't know why this happens, it could be a MSVC bug, or
3981 // related to LLP64 (windows) vs. LP64 (unix) programming
3982 // model, or the C++ standard might be ambigous in the section
3983 // defining the "usual arithmetic conversions". However, using
3984 // a temporary variable is safe and works on all compilers.
3985 pos_type const endpos = from + lyxrc.completion_minlength;
3988 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3989 if (cit == d->fontlist_.end())
3991 Language const * lang = cit->font().language();
3992 docstring const word = asString(from, pos, AS_STR_NONE);
3993 d->words_[lang->lang()].insert(word);
3998 void Paragraph::registerWords()
4000 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4001 Private::LangWordsMap::const_iterator ite = d->words_.end();
4002 for (; itl != ite; ++itl) {
4003 WordList & wl = theWordList(itl->first);
4004 Private::Words::const_iterator it = (itl->second).begin();
4005 Private::Words::const_iterator et = (itl->second).end();
4006 for (; it != et; ++it)
4012 void Paragraph::updateWords()
4020 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4022 SkipPositionsIterator begin = skips.begin();
4023 SkipPositions::iterator end = skips.end();
4024 if (pos > 0 && begin < end) {
4026 if (end->last == pos - 1) {
4031 skips.insert(end, FontSpan(pos, pos));
4035 Language * Paragraph::Private::locateSpellRange(
4036 pos_type & from, pos_type & to,
4037 SkipPositions & skips) const
4039 // skip leading white space
4040 while (from < to && owner_->isWordSeparator(from))
4042 // don't check empty range
4045 // get current language
4046 Language * lang = getSpellLanguage(from);
4047 pos_type last = from;
4048 bool samelang = true;
4049 bool sameinset = true;
4050 while (last < to && samelang && sameinset) {
4051 // hop to end of word
4052 while (last < to && !owner_->isWordSeparator(last)) {
4053 if (owner_->getInset(last)) {
4054 appendSkipPosition(skips, last);
4055 } else if (owner_->isDeleted(last)) {
4056 appendSkipPosition(skips, last);
4060 // hop to next word while checking for insets
4061 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4062 if (Inset const * inset = owner_->getInset(last))
4063 sameinset = inset->isChar() && inset->isLetter();
4064 if (sameinset && owner_->isDeleted(last)) {
4065 appendSkipPosition(skips, last);
4070 if (sameinset && last < to) {
4071 // now check for language change
4072 samelang = lang == getSpellLanguage(last);
4075 // if language change detected backstep is needed
4083 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4086 const_cast<Language *>(owner_->getFontSettings(
4087 inset_owner_->buffer().params(), from).language());
4088 if (lang == inset_owner_->buffer().params().language
4089 && !lyxrc.spellchecker_alt_lang.empty()) {
4091 string const lang_variety =
4092 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4093 lang->setCode(lang_code);
4094 lang->setVariety(lang_variety);
4100 void Paragraph::requestSpellCheck(pos_type pos)
4102 d->requestSpellCheck(pos);
4106 bool Paragraph::needsSpellCheck() const
4108 SpellChecker::ChangeNumber speller_change_number = 0;
4109 if (theSpellChecker())
4110 speller_change_number = theSpellChecker()->changeNumber();
4111 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4112 d->speller_state_.needsCompleteRefresh(speller_change_number);
4114 return d->needsSpellCheck();
4118 bool Paragraph::Private::ignoreWord(docstring const & word) const
4120 // Ignore words with digits
4121 // FIXME: make this customizable
4122 // (note that some checkers ignore words with digits by default)
4123 docstring::const_iterator cit = word.begin();
4124 docstring::const_iterator const end = word.end();
4125 for (; cit != end; ++cit) {
4126 if (isNumber((*cit)))
4133 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4134 WordLangTuple & wl, docstring_list & suggestions,
4135 bool do_suggestion, bool check_learned) const
4137 SpellChecker::Result result = SpellChecker::WORD_OK;
4138 SpellChecker * speller = theSpellChecker();
4142 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4145 locateWord(from, to, WHOLE_WORD);
4146 if (from == to || from >= size())
4149 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4150 Language * lang = d->getSpellLanguage(from);
4152 wl = WordLangTuple(word, lang);
4157 if (needsSpellCheck() || check_learned) {
4159 if (!d->ignoreWord(word)) {
4160 bool const trailing_dot = to < size() && d->text_[to] == '.';
4161 result = speller->check(wl);
4162 if (SpellChecker::misspelled(result) && trailing_dot) {
4163 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4164 result = speller->check(wl);
4165 if (!SpellChecker::misspelled(result)) {
4166 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4168 from << ".." << to << "]");
4170 // spell check with dot appended failed too
4171 // restore original word/lang value
4172 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4173 wl = WordLangTuple(word, lang);
4177 if (!SpellChecker::misspelled(result)) {
4178 // area up to the begin of the next word is not misspelled
4179 while (end < size() && isWordSeparator(end))
4182 d->setMisspelled(from, end, result);
4184 result = d->speller_state_.getState(from);
4188 suggestions.clear();
4190 if (SpellChecker::misspelled(result)) {
4191 LYXERR(Debug::GUI, "misspelled word: \"" <<
4193 from << ".." << to << "]");
4195 speller->suggest(wl, suggestions);
4201 void Paragraph::anonymize()
4203 // This is a very crude anonymization for now
4204 for (char_type & c : d->text_)
4205 if (isLetterChar(c) || isNumber(c))
4210 void Paragraph::Private::markMisspelledWords(
4211 pos_type const & first, pos_type const & last,
4212 SpellChecker::Result result,
4213 docstring const & word,
4214 SkipPositions const & skips)
4216 if (!SpellChecker::misspelled(result)) {
4217 setMisspelled(first, last, SpellChecker::WORD_OK);
4221 SpellChecker * speller = theSpellChecker();
4222 // locate and enumerate the error positions
4223 int nerrors = speller->numMisspelledWords();
4225 SkipPositionsIterator it = skips.begin();
4226 SkipPositionsIterator et = skips.end();
4227 for (int index = 0; index < nerrors; ++index) {
4230 speller->misspelledWord(index, wstart, wlen);
4231 /// should not happen if speller supports range checks
4232 if (!wlen) continue;
4233 docstring const misspelled = word.substr(wstart, wlen);
4234 wstart += first + numskipped;
4235 if (snext < wstart) {
4236 /// mark the range of correct spelling
4237 numskipped += countSkips(it, et, wstart);
4238 setMisspelled(snext,
4239 wstart - 1, SpellChecker::WORD_OK);
4241 snext = wstart + wlen;
4242 numskipped += countSkips(it, et, snext);
4243 /// mark the range of misspelling
4244 setMisspelled(wstart, snext, result);
4245 LYXERR(Debug::GUI, "misspelled word: \"" <<
4246 misspelled << "\" [" <<
4247 wstart << ".." << (snext-1) << "]");
4250 if (snext <= last) {
4251 /// mark the range of correct spelling at end
4252 setMisspelled(snext, last, SpellChecker::WORD_OK);
4257 void Paragraph::spellCheck() const
4259 SpellChecker * speller = theSpellChecker();
4260 if (!speller || empty() ||!needsSpellCheck())
4264 d->rangeOfSpellCheck(start, endpos);
4265 if (speller->canCheckParagraph()) {
4266 // loop until we leave the range
4267 for (pos_type first = start; first < endpos; ) {
4268 pos_type last = endpos;
4269 Private::SkipPositions skips;
4270 Language * lang = d->locateSpellRange(first, last, skips);
4271 if (first >= endpos)
4273 // start the spell checker on the unit of meaning
4274 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4275 WordLangTuple wl = WordLangTuple(word, lang);
4276 SpellChecker::Result result = word.size() ?
4277 speller->check(wl) : SpellChecker::WORD_OK;
4278 d->markMisspelledWords(first, last, result, word, skips);
4282 static docstring_list suggestions;
4283 pos_type to = endpos;
4284 while (start < endpos) {
4286 spellCheck(start, to, wl, suggestions, false);
4290 d->readySpellCheck();
4294 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4296 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4297 if (result || pos <= 0 || pos > size())
4299 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4300 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4305 string Paragraph::magicLabel() const
4308 ss << "magicparlabel-" << id();