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 &, pos_type & i);
336 /// This could go to ParagraphParameters if we want to.
337 int startTeXParParams(BufferParams const &, otexstream &,
338 OutputParams const &) const;
340 /// This could go to ParagraphParameters if we want to.
341 bool endTeXParParams(BufferParams const &, otexstream &,
342 OutputParams const &) const;
345 void latexInset(BufferParams const &,
350 Font const & outerfont,
352 Change & running_change,
353 Layout const & style,
355 unsigned int & column);
358 void latexSpecialChar(
360 BufferParams const & bparams,
361 OutputParams const & runparams,
362 Font const & running_font,
363 Change const & running_change,
364 Layout const & style,
367 unsigned int & column);
374 unsigned int & column);
380 unsigned int & column);
386 unsigned int & column);
389 void validate(LaTeXFeatures & features) const;
391 /// Checks if the paragraph contains only text and no inset or font change.
392 bool onlyText(Buffer const & buf, Font const & outerfont,
393 pos_type initial) const;
395 /// a vector of speller skip positions
396 typedef vector<FontSpan> SkipPositions;
397 typedef SkipPositions::const_iterator SkipPositionsIterator;
399 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
401 Language * getSpellLanguage(pos_type const from) const;
403 Language * locateSpellRange(pos_type & from, pos_type & to,
404 SkipPositions & skips) const;
406 bool hasSpellerChange() const
408 SpellChecker::ChangeNumber speller_change_number = 0;
409 if (theSpellChecker())
410 speller_change_number = theSpellChecker()->changeNumber();
411 return speller_change_number > speller_state_.currentChangeNumber();
414 bool ignoreWord(docstring const & word) const ;
416 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
418 pos_type textsize = owner_->size();
419 // check for sane arguments
420 if (to <= from || from >= textsize)
422 FontSpan fp = FontSpan(from, to - 1);
423 speller_state_.setRange(fp, state);
426 void requestSpellCheck(pos_type pos)
429 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
431 speller_state_.needsRefresh(pos);
434 void readySpellCheck()
436 speller_state_.needsRefresh(-1);
439 bool needsSpellCheck() const
441 return speller_state_.needsRefresh();
444 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
446 speller_state_.refreshRange(first, last);
448 last = owner_->size();
451 pos_type endpos = last;
452 owner_->locateWord(first, endpos, WHOLE_WORD);
455 owner_->locateWord(last, endpos, WHOLE_WORD);
460 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
464 while (it != et && it->first < start) {
465 int skip = it->last - it->first + 1;
473 void markMisspelledWords(pos_type const & first, pos_type const & last,
474 SpellChecker::Result result,
475 docstring const & word,
476 SkipPositions const & skips);
478 InsetCode ownerCode() const
480 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
483 /// Which Paragraph owns us?
487 Inset const * inset_owner_;
496 ParagraphParameters params_;
498 /// for recording and looking up changes
502 InsetList insetlist_;
505 pos_type begin_of_body_;
507 typedef docstring TextContainer;
511 typedef set<docstring> Words;
512 typedef map<string, Words> LangWordsMap;
516 Layout const * layout_;
518 SpellCheckerState speller_state_;
522 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
523 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
530 int Paragraph::Private::make_id()
532 // The id is unique per session across buffers because it is used in
533 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
536 static atomic_uint next_id(0);
541 Paragraph::Private::Private(Private const & p, Paragraph * owner)
542 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
544 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
545 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
548 requestSpellCheck(p.text_.size());
552 Paragraph::Private::Private(Private const & p, Paragraph * owner,
553 pos_type beg, pos_type end)
554 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
555 params_(p.params_), changes_(p.changes_),
556 insetlist_(p.insetlist_, beg, end),
557 begin_of_body_(p.begin_of_body_), words_(p.words_),
560 if (beg >= pos_type(p.text_.size()))
562 text_ = p.text_.substr(beg, end - beg);
564 FontList::const_iterator fcit = fontlist_.begin();
565 FontList::const_iterator fend = fontlist_.end();
566 for (; fcit != fend; ++fcit) {
567 if (fcit->pos() < beg)
569 if (fcit->pos() >= end) {
570 // Add last entry in the fontlist_.
571 fontlist_.set(text_.size() - 1, fcit->font());
574 // Add a new entry in the fontlist_.
575 fontlist_.set(fcit->pos() - beg, fcit->font());
577 requestSpellCheck(p.text_.size());
581 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
582 bool output_active, TocBackend & backend) const
584 d->changes_.addToToc(cdit, buf, output_active, backend);
588 void Paragraph::addChangesToBuffer(Buffer const & buf) const
590 d->changes_.updateBuffer(buf);
594 bool Paragraph::isChangeUpdateRequired() const
596 return d->changes_.isUpdateRequired();
600 bool Paragraph::isDeleted(pos_type start, pos_type end) const
602 LASSERT(start >= 0 && start <= size(), return false);
603 LASSERT(end > start && end <= size() + 1, return false);
605 return d->changes_.isDeleted(start, end);
609 bool Paragraph::isChanged(pos_type start, pos_type end) const
611 LASSERT(start >= 0 && start <= size(), return false);
612 LASSERT(end > start && end <= size() + 1, return false);
614 return d->changes_.isChanged(start, end);
618 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
620 // keep the logic here in sync with the logic of eraseChars()
624 Change const & change = d->changes_.lookup(size());
625 return change.inserted() && change.currentAuthor();
629 void Paragraph::setChange(Change const & change)
631 // beware of the imaginary end-of-par character!
632 d->changes_.set(change, 0, size() + 1);
635 * Propagate the change recursively - but not in case of DELETED!
637 * Imagine that your co-author makes changes in an existing inset. He
638 * sends your document to you and you come to the conclusion that the
639 * inset should go completely. If you erase it, LyX must not delete all
640 * text within the inset. Otherwise, the change tracked insertions of
641 * your co-author get lost and there is no way to restore them later.
643 * Conclusion: An inset's content should remain untouched if you delete it
646 if (!change.deleted()) {
647 for (pos_type pos = 0; pos < size(); ++pos) {
648 if (Inset * inset = getInset(pos))
649 inset->setChange(change);
655 void Paragraph::setChange(pos_type pos, Change const & change)
657 LASSERT(pos >= 0 && pos <= size(), return);
658 d->changes_.set(change, pos);
660 // see comment in setChange(Change const &) above
661 if (!change.deleted() && pos < size())
662 if (Inset * inset = getInset(pos))
663 inset->setChange(change);
667 Change const & Paragraph::lookupChange(pos_type pos) const
669 LBUFERR(pos >= 0 && pos <= size());
670 return d->changes_.lookup(pos);
674 void Paragraph::acceptChanges(pos_type start, pos_type end)
676 LASSERT(start >= 0 && start <= size(), return);
677 LASSERT(end > start && end <= size() + 1, return);
679 for (pos_type pos = start; pos < end; ++pos) {
680 switch (lookupChange(pos).type) {
681 case Change::UNCHANGED:
682 // accept changes in nested inset
683 if (Inset * inset = getInset(pos))
684 inset->acceptChanges();
687 case Change::INSERTED:
688 d->changes_.set(Change(Change::UNCHANGED), pos);
689 // also accept changes in nested inset
690 if (Inset * inset = getInset(pos))
691 inset->acceptChanges();
694 case Change::DELETED:
695 // Suppress access to non-existent
696 // "end-of-paragraph char"
698 eraseChar(pos, false);
709 void Paragraph::rejectChanges(pos_type start, pos_type end)
711 LASSERT(start >= 0 && start <= size(), return);
712 LASSERT(end > start && end <= size() + 1, return);
714 for (pos_type pos = start; pos < end; ++pos) {
715 switch (lookupChange(pos).type) {
716 case Change::UNCHANGED:
717 // reject changes in nested inset
718 if (Inset * inset = getInset(pos))
719 inset->rejectChanges();
722 case Change::INSERTED:
723 // Suppress access to non-existent
724 // "end-of-paragraph char"
726 eraseChar(pos, false);
732 case Change::DELETED:
733 d->changes_.set(Change(Change::UNCHANGED), pos);
735 // Do NOT reject changes within a deleted inset!
736 // There may be insertions of a co-author inside of it!
744 void Paragraph::Private::insertChar(pos_type pos, char_type c,
745 Change const & change)
747 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
750 changes_.insert(change, pos);
752 // This is actually very common when parsing buffers (and
753 // maybe inserting ascii text)
754 if (pos == pos_type(text_.size())) {
755 // when appending characters, no need to update tables
757 // but we want spell checking
758 requestSpellCheck(pos);
762 text_.insert(text_.begin() + pos, c);
764 // Update the font table.
765 fontlist_.increasePosAfterPos(pos);
768 insetlist_.increasePosAfterPos(pos);
770 // Update list of misspelled positions
771 speller_state_.increasePosAfterPos(pos);
775 bool Paragraph::insertInset(pos_type pos, Inset * inset,
776 Font const & font, Change const & change)
778 LASSERT(inset, return false);
779 LASSERT(pos >= 0 && pos <= size(), return false);
781 // Paragraph::insertInset() can be used in cut/copy/paste operation where
782 // d->inset_owner_ is not set yet.
783 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
786 d->insertChar(pos, META_INSET, change);
787 LASSERT(d->text_[pos] == META_INSET, return false);
789 // Add a new entry in the insetlist_.
790 d->insetlist_.insert(inset, pos);
792 // Some insets require run of spell checker
793 requestSpellCheck(pos);
799 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
801 LASSERT(pos >= 0 && pos <= size(), return false);
803 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
806 Change change = d->changes_.lookup(pos);
808 // set the character to DELETED if
809 // a) it was previously unchanged or
810 // b) it was inserted by a co-author
812 if (!change.changed() ||
813 (change.inserted() && !change.currentAuthor())) {
814 setChange(pos, Change(Change::DELETED));
815 // request run of spell checker
816 requestSpellCheck(pos);
820 if (change.deleted())
824 // Don't physically access the imaginary end-of-paragraph character.
825 // eraseChar() can only mark it as DELETED. A physical deletion of
826 // end-of-par must be handled externally.
832 d->changes_.erase(pos);
834 // if it is an inset, delete the inset entry
835 if (d->text_[pos] == META_INSET)
836 d->insetlist_.erase(pos);
838 d->text_.erase(d->text_.begin() + pos);
840 // Update the fontlist_
841 d->fontlist_.erase(pos);
843 // Update the insetlist_
844 d->insetlist_.decreasePosAfterPos(pos);
846 // Update list of misspelled positions
847 d->speller_state_.decreasePosAfterPos(pos);
848 d->speller_state_.refreshLast(size());
854 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
856 LASSERT(start >= 0 && start <= size(), return 0);
857 LASSERT(end >= start && end <= size() + 1, return 0);
860 for (pos_type count = end - start; count; --count) {
861 if (!eraseChar(i, trackChanges))
868 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
869 char_type next, OutputParams const & runparams)
871 // Writing next here may circumvent a possible font change between
872 // c and next. Since next is only output if it forms a surrogate pair
873 // with c we can ignore this:
874 // A font change inside a surrogate pair does not make sense and is
875 // hopefully impossible to input.
876 // FIXME: change tracking
877 // Is this correct WRT change tracking?
878 Encoding const & encoding = *(runparams.encoding);
879 docstring latex1 = encoding.latexChar(next).first;
880 if (runparams.inIPA) {
881 string const tipashortcut = Encodings::TIPAShortcut(next);
882 if (!tipashortcut.empty()) {
883 latex1 = from_ascii(tipashortcut);
886 docstring const latex2 = encoding.latexChar(c).first;
887 if (docstring(1, next) == latex1) {
888 // the encoding supports the combination
889 os << latex2 << latex1;
890 return latex1.length() + latex2.length();
891 } else if (runparams.local_font &&
892 runparams.local_font->language()->lang() == "polutonikogreek") {
893 // polutonikogreek only works without the brackets
894 os << latex1 << latex2;
895 return latex1.length() + latex2.length();
897 os << latex1 << '{' << latex2 << '}';
898 return latex1.length() + latex2.length() + 2;
902 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
905 unsigned int & column,
907 Layout const & style)
909 if (style.pass_thru || runparams.pass_thru)
912 if (i + 1 < int(text_.size())) {
913 char_type next = text_[i + 1];
914 if (Encodings::isCombiningChar(next)) {
915 // This space has an accent, so we must always output it.
916 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
921 if (runparams.linelen > 0
922 && column > runparams.linelen
924 && text_[i - 1] != ' '
925 && (i + 1 < int(text_.size()))
926 // same in FreeSpacing mode
927 && !owner_->isFreeSpacing()
928 // In typewriter mode, we want to avoid
929 // ! . ? : at the end of a line
930 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
931 && (text_[i - 1] == '.'
932 || text_[i - 1] == '?'
933 || text_[i - 1] == ':'
934 || text_[i - 1] == '!'))) {
936 os.texrow().start(owner_->id(), i + 1);
938 } else if (style.free_spacing) {
947 int Paragraph::Private::writeScriptChars(otexstream & os,
948 docstring const & ltx,
949 Change const & runningChange,
950 Encoding const & encoding,
953 // FIXME: modifying i here is not very nice...
955 // We only arrive here when character text_[i] could not be translated
956 // into the current latex encoding (or its latex translation has been forced,)
957 // and it belongs to a known script.
958 // TODO: We need \textcyr and \textgreek wrappers also for characters
959 // that can be encoded in the "LaTeX encoding" but not in the
960 // current *font encoding*.
961 // (See #9681 for details and test)
962 // Parameter ltx contains the latex translation of text_[i] as specified
963 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
964 // The latex macro name "textXXX" specifies the script to which text_[i]
965 // belongs and we use it in order to check whether characters from the
966 // same script immediately follow, such that we can collect them in a
967 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
968 // for the first char but only "<spec>" for all subsequent chars.
969 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
970 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
971 string script = to_ascii(ltx.substr(1, brace1 - 1));
974 bool closing_brace = true;
975 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
976 // Correct encoding is being used, so we can avoid \textgreek.
977 // TODO: wrong test: we need to check the *font encoding*
978 // (i.e. the active language and its FontEncoding tag)
979 // instead of the LaTeX *input encoding*!
980 // See #9637 for details and test-cases.
983 closing_brace = false;
985 os << ltx.substr(pos, length);
986 int size = text_.size();
987 while (i + 1 < size) {
988 char_type const next = text_[i + 1];
989 // Stop here if next character belongs to another script
990 // or there is a change in change tracking status.
991 if (!Encodings::isKnownScriptChar(next, script) ||
992 runningChange != owner_->lookupChange(i + 1))
996 FontList::const_iterator cit = fontlist_.begin();
997 FontList::const_iterator end = fontlist_.end();
998 for (; cit != end; ++cit) {
999 if (cit->pos() >= i && !found) {
1000 prev_font = cit->font();
1003 if (cit->pos() >= i + 1)
1006 // Stop here if there is a font attribute or encoding change.
1007 if (found && cit != end && prev_font != cit->font())
1009 docstring const latex = encoding.latexChar(next).first;
1010 docstring::size_type const b1 =
1011 latex.find_first_of(from_ascii("{"));
1012 docstring::size_type const b2 =
1013 latex.find_last_of(from_ascii("}"));
1014 int const len = b2 - b1 - 1;
1015 os << latex.substr(b1 + 1, len);
1019 if (closing_brace) {
1027 void Paragraph::Private::latexInset(BufferParams const & bparams,
1029 OutputParams & runparams,
1030 Font & running_font,
1032 Font const & outerfont,
1034 Change & running_change,
1035 Layout const & style,
1037 unsigned int & column)
1039 Inset * inset = owner_->getInset(i);
1042 if (style.pass_thru) {
1043 odocstringstream ods;
1044 inset->plaintext(ods, runparams);
1049 // FIXME: move this to InsetNewline::latex
1050 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1051 // newlines are handled differently here than
1052 // the default in simpleTeXSpecialChars().
1053 if (!style.newline_allowed) {
1057 bool needPar = false;
1058 column += running_font.latexWriteEndChanges(
1059 os, bparams, runparams,
1060 basefont, basefont, needPar);
1064 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1067 basefont = owner_->getLayoutFont(bparams, outerfont);
1068 running_font = basefont;
1070 if (runparams.moving_arg)
1074 os.texrow().start(owner_->id(), i + 1);
1078 if (owner_->isDeleted(i)) {
1079 if( ++runparams.inDeletedInset == 1)
1080 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1083 if (inset->canTrackChanges()) {
1084 column += Changes::latexMarkChange(os, bparams, running_change,
1085 Change(Change::UNCHANGED), runparams);
1086 running_change = Change(Change::UNCHANGED);
1090 odocstream::pos_type const len = os.os().tellp();
1092 if (inset->forceLTR()
1093 && running_font.isRightToLeft()
1094 // ERT is an exception, it should be output with no
1095 // decorations at all
1096 && inset->lyxCode() != ERT_CODE) {
1097 if (runparams.use_polyglossia) {
1099 } else if (running_font.language()->lang() == "farsi"
1100 || running_font.language()->lang() == "arabic_arabi")
1101 os << "\\textLR{" << termcmd;
1107 // FIXME: Bug: we can have an empty font change here!
1108 // if there has just been a font change, we are going to close it
1109 // right now, which means stupid latex code like \textsf{}. AFAIK,
1110 // this does not harm dvi output. A minor bug, thus (JMarc)
1112 // Some insets cannot be inside a font change command.
1113 // However, even such insets *can* be placed in \L or \R
1114 // or their equivalents (for RTL language switches), so we don't
1115 // close the language in those cases.
1116 // ArabTeX, though, cannot handle this special behavior, it seems.
1117 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1118 || running_font.language()->lang() == "arabic_arabtex";
1119 if (open_font && !inset->inheritFont()) {
1120 bool needPar = false;
1121 bool closeLanguage = arabtex
1122 || basefont.isRightToLeft() == running_font.isRightToLeft();
1123 unsigned int count = running_font.latexWriteEndChanges(os,
1124 bparams, runparams, basefont, basefont,
1125 needPar, closeLanguage);
1127 // if any font properties were closed, update the running_font,
1128 // making sure, however, to leave the language as it was
1130 // FIXME: probably a better way to keep track of the old
1131 // language, than copying the entire font?
1132 Font const copy_font(running_font);
1133 basefont = owner_->getLayoutFont(bparams, outerfont);
1134 running_font = basefont;
1136 running_font.setLanguage(copy_font.language());
1137 // leave font open if language is still open
1138 open_font = (running_font.language() == basefont.language());
1140 runparams.local_font = &basefont;
1144 size_t const previous_row_count = os.texrow().rows();
1147 runparams.lastid = id_;
1148 runparams.lastpos = i;
1149 inset->latex(os, runparams);
1150 } catch (EncodingException & e) {
1151 // add location information and throw again.
1160 if (os.texrow().rows() > previous_row_count) {
1161 os.texrow().start(owner_->id(), i + 1);
1164 column += (unsigned int)(os.os().tellp() - len);
1167 if (owner_->isDeleted(i))
1168 --runparams.inDeletedInset;
1172 void Paragraph::Private::latexSpecialChar(otexstream & os,
1173 BufferParams const & bparams,
1174 OutputParams const & runparams,
1175 Font const & running_font,
1176 Change const & running_change,
1177 Layout const & style,
1180 unsigned int & column)
1182 char_type const c = owner_->getUChar(bparams, runparams, i);
1184 if (style.pass_thru || runparams.pass_thru
1185 || contains(style.pass_thru_chars, c)
1186 || contains(runparams.pass_thru_chars, c)) {
1188 Encoding const * const enc = runparams.encoding;
1189 if (enc && !enc->encodable(c))
1190 throw EncodingException(c);
1196 // TIPA uses its own T3 encoding
1197 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1199 // If T1 font encoding is used, use the special
1200 // characters it provides.
1201 // NOTE: Some languages reset the font encoding internally to a
1202 // non-standard font encoding. If we are using such a language,
1203 // we do not output special T1 chars.
1204 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1205 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1206 && latexSpecialT1(c, os, i, column))
1208 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1209 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1210 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1213 // Otherwise, we use what LaTeX provides us.
1216 os << "\\textbackslash" << termcmd;
1220 os << "\\textless" << termcmd;
1224 os << "\\textgreater" << termcmd;
1228 os << "\\textbar" << termcmd;
1233 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1234 (end_pos == -1 || i + 1 < end_pos) &&
1235 text_[i+1] == '-') {
1236 // Prevent "--" becoming an endash and "---" becoming
1238 // Within \ttfamily, "--" is merged to "-" (no endash)
1239 // so we avoid this rather irritating ligature as well
1245 os << "\\textquotedbl" << termcmd;
1250 case '%': case '#': case '{':
1258 os << "\\textasciitilde" << termcmd;
1263 os << "\\textasciicircum" << termcmd;
1270 // avoid being mistaken for optional arguments
1278 // Blanks are printed before font switching.
1279 // Sure? I am not! (try nice-latex)
1280 // I am sure it's correct. LyX might be smarter
1281 // in the future, but for now, nothing wrong is
1287 // XeTeX's dash behaviour is determined via a global setting
1288 if (bparams.use_dash_ligatures
1289 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1290 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1307 Encoding const & encoding = *(runparams.encoding);
1308 char_type next = '\0';
1309 if (i + 1 < int(text_.size())) {
1310 next = text_[i + 1];
1311 if (Encodings::isCombiningChar(next)) {
1312 column += latexSurrogatePair(os, c, next, runparams) - 1;
1318 pair<docstring, bool> latex = encoding.latexChar(c);
1319 docstring nextlatex;
1320 bool nexttipas = false;
1321 string nexttipashortcut;
1322 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1323 nextlatex = encoding.latexChar(next).first;
1324 if (runparams.inIPA) {
1325 nexttipashortcut = Encodings::TIPAShortcut(next);
1326 nexttipas = !nexttipashortcut.empty();
1330 if (runparams.inIPA) {
1331 string const tipashortcut = Encodings::TIPAShortcut(c);
1332 if (!tipashortcut.empty()) {
1333 latex.first = from_ascii(tipashortcut);
1334 latex.second = false;
1338 if (Encodings::isKnownScriptChar(c, script)
1339 && prefixIs(latex.first, from_ascii("\\" + script)))
1340 column += writeScriptChars(os, latex.first,
1341 running_change, encoding, i) - 1;
1342 else if (latex.second
1343 && ((!prefixIs(nextlatex, '\\')
1344 && !prefixIs(nextlatex, '{')
1345 && !prefixIs(nextlatex, '}'))
1347 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1349 // Prevent eating of a following
1350 // space or command corruption by
1351 // following characters
1352 if (next == ' ' || next == '\0') {
1353 column += latex.first.length() + 1;
1354 os << latex.first << "{}";
1356 column += latex.first.length();
1357 os << latex.first << " ";
1360 column += latex.first.length() - 1;
1368 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1369 pos_type i, unsigned int & column)
1375 // In T1 encoding, these characters exist
1376 // but we should avoid ligatures
1377 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1379 os << "\\textcompwordmark" << termcmd;
1386 // soul.sty breaks with \char`\"
1387 os << "\\textquotedbl" << termcmd;
1396 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1397 pos_type i, unsigned int & column)
1399 // TU encoding is currently on par with T1.
1400 return latexSpecialT1(c, os, i, column);
1404 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1405 pos_type /*i*/, unsigned int & column)
1415 os << "\\textvertline" << termcmd;
1419 os << "\\textendash" << termcmd;
1423 os << "\\textemdash" << termcmd;
1432 void Paragraph::Private::validate(LaTeXFeatures & features) const
1434 if (layout_->inpreamble && inset_owner_) {
1435 // FIXME: Using a string stream here circumvents the encoding
1436 // switching machinery of odocstream. Therefore the
1437 // output is wrong if this paragraph contains content
1438 // that needs to switch encoding.
1439 Buffer const & buf = inset_owner_->buffer();
1440 otexstringstream os;
1441 os << layout_->preamble();
1442 size_t const length = os.length();
1443 TeXOnePar(buf, *inset_owner_->getText(int(buf.getParFromID(owner_->id()).idx())),
1444 buf.getParFromID(owner_->id()).pit(), os,
1445 features.runparams(), string(), 0, -1, true);
1446 if (os.length() > length)
1447 features.addPreambleSnippet(os.release(), true);
1450 if (features.runparams().flavor == OutputParams::HTML
1451 && layout_->htmltitle()) {
1452 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1455 // check the params.
1456 if (!params_.spacing().isDefault())
1457 features.require("setspace");
1460 features.useLayout(layout_->name());
1463 fontlist_.validate(features);
1465 // then the indentation
1466 if (!params_.leftIndent().zero())
1467 features.require("ParagraphLeftIndent");
1470 InsetList::const_iterator icit = insetlist_.begin();
1471 InsetList::const_iterator iend = insetlist_.end();
1472 for (; icit != iend; ++icit) {
1474 features.inDeletedInset(owner_->isDeleted(icit->pos));
1475 if (icit->inset->lyxCode() == FOOT_CODE) {
1476 // FIXME: an item inset would make things much easier.
1477 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1478 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1479 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1480 && (icit->pos < begin_of_body_
1481 || (icit->pos == begin_of_body_
1482 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1483 features.saveNoteEnv("description");
1485 icit->inset->validate(features);
1486 features.inDeletedInset(false);
1487 if (layout_->needprotect &&
1488 icit->inset->lyxCode() == FOOT_CODE)
1489 features.require("NeedLyXFootnoteCode");
1493 // then the contents
1494 BufferParams const bp = features.runparams().is_child
1495 ? features.buffer().masterParams() : features.buffer().params();
1496 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1497 char_type c = text_[i];
1499 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1500 features.require("textquotedblp");
1501 else if (bp.main_font_encoding() != "T1"
1502 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1503 features.require("textquotedbl");
1505 if (!bp.use_dash_ligatures
1506 && (c == 0x2013 || c == 0x2014)
1507 && bp.useNonTeXFonts
1508 && features.runparams().flavor == OutputParams::XETEX)
1509 // XeTeX's dash behaviour is determined via a global setting
1510 features.require("xetexdashbreakstate");
1511 BufferEncodings::validate(c, features);
1515 /////////////////////////////////////////////////////////////////////
1519 /////////////////////////////////////////////////////////////////////
1522 Layout const emptyParagraphLayout;
1525 Paragraph::Paragraph()
1526 : d(new Paragraph::Private(this, emptyParagraphLayout))
1533 Paragraph::Paragraph(Paragraph const & par)
1534 : itemdepth(par.itemdepth),
1535 d(new Paragraph::Private(*par.d, this))
1541 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1542 : itemdepth(par.itemdepth),
1543 d(new Paragraph::Private(*par.d, this, beg, end))
1549 Paragraph & Paragraph::operator=(Paragraph const & par)
1551 // needed as we will destroy the private part before copying it
1553 itemdepth = par.itemdepth;
1557 d = new Private(*par.d, this);
1564 Paragraph::~Paragraph()
1573 // this shall be called just before every "os << ..." action.
1574 void flushString(ostream & os, docstring & s)
1583 void Paragraph::write(ostream & os, BufferParams const & bparams,
1584 depth_type & dth) const
1586 // The beginning or end of a deeper (i.e. nested) area?
1587 if (dth != d->params_.depth()) {
1588 if (d->params_.depth() > dth) {
1589 while (d->params_.depth() > dth) {
1590 os << "\n\\begin_deeper";
1594 while (d->params_.depth() < dth) {
1595 os << "\n\\end_deeper";
1601 // First write the layout
1602 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1604 d->params_.write(os);
1606 Font font1(inherit_font, bparams.language);
1608 Change running_change = Change(Change::UNCHANGED);
1610 // this string is used as a buffer to avoid repetitive calls
1611 // to to_utf8(), which turn out to be expensive (JMarc)
1612 docstring write_buffer;
1615 for (pos_type i = 0; i <= size(); ++i) {
1617 Change const & change = lookupChange(i);
1618 if (change != running_change)
1619 flushString(os, write_buffer);
1620 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1621 running_change = change;
1626 // Write font changes
1627 Font font2 = getFontSettings(bparams, i);
1628 if (font2 != font1) {
1629 flushString(os, write_buffer);
1630 font2.lyxWriteChanges(font1, os);
1635 char_type const c = d->text_[i];
1638 if (Inset const * inset = getInset(i)) {
1639 flushString(os, write_buffer);
1640 if (inset->directWrite()) {
1641 // international char, let it write
1642 // code directly so it's shorter in
1648 os << "\\begin_inset ";
1650 os << "\n\\end_inset\n\n";
1653 // FIXME This can be removed again once the mystery
1654 // crash has been resolved.
1659 flushString(os, write_buffer);
1660 os << "\n\\backslash\n";
1664 flushString(os, write_buffer);
1665 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1672 if ((column > 70 && c == ' ')
1674 flushString(os, write_buffer);
1678 // this check is to amend a bug. LyX sometimes
1679 // inserts '\0' this could cause problems.
1681 write_buffer.push_back(c);
1683 LYXERR0("NUL char in structure.");
1689 flushString(os, write_buffer);
1690 os << "\n\\end_layout\n";
1691 // FIXME This can be removed again once the mystery
1692 // crash has been resolved.
1697 void Paragraph::validate(LaTeXFeatures & features) const
1699 d->validate(features);
1703 void Paragraph::insert(pos_type start, docstring const & str,
1704 Font const & font, Change const & change)
1706 for (size_t i = 0, n = str.size(); i != n ; ++i)
1707 insertChar(start + i, str[i], font, change);
1711 void Paragraph::appendChar(char_type c, Font const & font,
1712 Change const & change)
1715 d->changes_.insert(change, d->text_.size());
1716 // when appending characters, no need to update tables
1717 d->text_.push_back(c);
1718 setFont(d->text_.size() - 1, font);
1719 d->requestSpellCheck(d->text_.size() - 1);
1723 void Paragraph::appendString(docstring const & s, Font const & font,
1724 Change const & change)
1726 pos_type end = s.size();
1727 size_t oldsize = d->text_.size();
1728 size_t newsize = oldsize + end;
1729 size_t capacity = d->text_.capacity();
1730 if (newsize >= capacity)
1731 d->text_.reserve(max(capacity + 100, newsize));
1733 // when appending characters, no need to update tables
1736 // FIXME: Optimize this!
1737 for (size_t i = oldsize; i != newsize; ++i) {
1739 d->changes_.insert(change, i);
1740 d->requestSpellCheck(i);
1742 d->fontlist_.set(oldsize, font);
1743 d->fontlist_.set(newsize - 1, font);
1747 void Paragraph::insertChar(pos_type pos, char_type c,
1750 d->insertChar(pos, c, Change(trackChanges ?
1751 Change::INSERTED : Change::UNCHANGED));
1755 void Paragraph::insertChar(pos_type pos, char_type c,
1756 Font const & font, bool trackChanges)
1758 d->insertChar(pos, c, Change(trackChanges ?
1759 Change::INSERTED : Change::UNCHANGED));
1764 void Paragraph::insertChar(pos_type pos, char_type c,
1765 Font const & font, Change const & change)
1767 d->insertChar(pos, c, change);
1772 void Paragraph::resetFonts(Font const & font)
1774 d->fontlist_.clear();
1775 d->fontlist_.set(0, font);
1776 d->fontlist_.set(d->text_.size() - 1, font);
1779 // Gets uninstantiated font setting at position.
1780 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1784 LYXERR0("pos: " << pos << " size: " << size());
1788 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1789 if (cit != d->fontlist_.end())
1792 if (pos == size() && !empty())
1793 return getFontSettings(bparams, pos - 1);
1795 // Optimisation: avoid a full font instantiation if there is no
1796 // language change from previous call.
1797 static Font previous_font;
1798 static Language const * previous_lang = 0;
1799 Language const * lang = getParLanguage(bparams);
1800 if (lang != previous_lang) {
1801 previous_lang = lang;
1802 previous_font = Font(inherit_font, lang);
1804 return previous_font;
1808 FontSpan Paragraph::fontSpan(pos_type pos) const
1810 LBUFERR(pos <= size());
1813 return FontSpan(pos, pos);
1816 FontList::const_iterator cit = d->fontlist_.begin();
1817 FontList::const_iterator end = d->fontlist_.end();
1818 for (; cit != end; ++cit) {
1819 if (cit->pos() >= pos) {
1820 if (pos >= beginOfBody())
1821 return FontSpan(max(start, beginOfBody()),
1824 return FontSpan(start,
1825 min(beginOfBody() - 1,
1828 start = cit->pos() + 1;
1831 // This should not happen, but if so, we take no chances.
1832 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1833 LASSERT(false, return FontSpan(pos, pos));
1837 // Gets uninstantiated font setting at position 0
1838 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1840 if (!empty() && !d->fontlist_.empty())
1841 return d->fontlist_.begin()->font();
1843 // Optimisation: avoid a full font instantiation if there is no
1844 // language change from previous call.
1845 static Font previous_font;
1846 static Language const * previous_lang = 0;
1847 if (bparams.language != previous_lang) {
1848 previous_lang = bparams.language;
1849 previous_font = Font(inherit_font, bparams.language);
1852 return previous_font;
1856 // Gets the fully instantiated font at a given position in a paragraph
1857 // This is basically the same function as Text::GetFont() in text2.cpp.
1858 // The difference is that this one is used for generating the LaTeX file,
1859 // and thus cosmetic "improvements" are disallowed: This has to deliver
1860 // the true picture of the buffer. (Asger)
1861 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1862 Font const & outerfont) const
1866 Font font = getFontSettings(bparams, pos);
1868 pos_type const body_pos = beginOfBody();
1869 FontInfo & fi = font.fontInfo();
1871 fi.realize(d->layout_->labelfont);
1873 fi.realize(d->layout_->font);
1875 fi.realize(outerfont.fontInfo());
1876 fi.realize(bparams.getFont().fontInfo());
1882 Font const Paragraph::getLabelFont
1883 (BufferParams const & bparams, Font const & outerfont) const
1885 FontInfo tmpfont = d->layout_->labelfont;
1886 tmpfont.realize(outerfont.fontInfo());
1887 tmpfont.realize(bparams.getFont().fontInfo());
1888 return Font(tmpfont, getParLanguage(bparams));
1892 Font const Paragraph::getLayoutFont
1893 (BufferParams const & bparams, Font const & outerfont) const
1895 FontInfo tmpfont = d->layout_->font;
1896 tmpfont.realize(outerfont.fontInfo());
1897 tmpfont.realize(bparams.getFont().fontInfo());
1898 return Font(tmpfont, getParLanguage(bparams));
1902 char_type Paragraph::getUChar(BufferParams const & bparams,
1903 OutputParams const & rp,
1906 char_type c = d->text_[pos];
1908 // Return unchanged character in LTR languages.
1909 if (!getFontSettings(bparams, pos).isRightToLeft())
1912 // FIXME This is a complete mess due to all the language-specific
1913 // special cases. We need to unify this eventually, but this
1914 // requires a file format change and some thought.
1915 // We also need to unify the input of parentheses in different RTL
1916 // languages. Currently, some have their own methods (Arabic:
1917 // 18599/lyxsvn, Hebrew: e5f42f67d/lyxgit), some don't (Urdu, Syriac).
1918 // Also note that the representation in the LyX file is probably wrong
1919 // (see FIXME in TextMetrics::breakRow).
1920 // Most likely, we should simply rely on Qt's unicode handling here.
1921 string const & lang = getFontSettings(bparams, pos).language()->lang();
1923 // With polyglossia, brackets and stuff need not be reversed in RTL scripts
1924 // FIXME: The special casing for Hebrew parens is due to the special
1925 // handling on input (for Hebrew in e5f42f67d/lyxgit); see #8251.
1927 if (rp.use_polyglossia) {
1930 if (lang == "hebrew")
1934 if (lang == "hebrew")
1941 // In the following languages, brackets don't need to be reversed.
1942 // Furthermore, in arabic_arabi, they are transformed to Arabic
1943 // Ornate Parentheses (dunno if this is really wanted)
1944 bool const reversebrackets = lang != "arabic_arabtex"
1945 && lang != "arabic_arabi"
1950 if (reversebrackets)
1954 if (reversebrackets)
1975 void Paragraph::setFont(pos_type pos, Font const & font)
1977 LASSERT(pos <= size(), return);
1979 // First, reduce font against layout/label font
1980 // Update: The setCharFont() routine in text2.cpp already
1981 // reduces font, so we don't need to do that here. (Asger)
1983 d->fontlist_.set(pos, font);
1987 void Paragraph::makeSameLayout(Paragraph const & par)
1989 d->layout_ = par.d->layout_;
1990 d->params_ = par.d->params_;
1994 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1996 if (isFreeSpacing())
2002 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2003 if (eraseChar(pos, trackChanges))
2009 return count > 0 || pos > 0;
2013 bool Paragraph::hasSameLayout(Paragraph const & par) const
2015 return par.d->layout_ == d->layout_
2016 && d->params_.sameLayout(par.d->params_);
2020 depth_type Paragraph::getDepth() const
2022 return d->params_.depth();
2026 depth_type Paragraph::getMaxDepthAfter() const
2028 if (d->layout_->isEnvironment())
2029 return d->params_.depth() + 1;
2031 return d->params_.depth();
2035 LyXAlignment Paragraph::getAlign() const
2037 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2038 return d->layout_->align;
2040 return d->params_.align();
2044 docstring const & Paragraph::labelString() const
2046 return d->params_.labelString();
2050 // the next two functions are for the manual labels
2051 docstring const Paragraph::getLabelWidthString() const
2053 if (d->layout_->margintype == MARGIN_MANUAL
2054 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2055 return d->params_.labelWidthString();
2057 return _("Senseless with this layout!");
2061 void Paragraph::setLabelWidthString(docstring const & s)
2063 d->params_.labelWidthString(s);
2067 docstring Paragraph::expandLabel(Layout const & layout,
2068 BufferParams const & bparams) const
2070 return expandParagraphLabel(layout, bparams, true);
2074 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2075 BufferParams const & bparams) const
2077 return expandParagraphLabel(layout, bparams, false);
2081 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2082 BufferParams const & bparams, bool process_appendix) const
2084 DocumentClass const & tclass = bparams.documentClass();
2085 string const & lang = getParLanguage(bparams)->code();
2086 bool const in_appendix = process_appendix && d->params_.appendix();
2087 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2089 if (fmt.empty() && !layout.counter.empty())
2090 return tclass.counters().theCounter(layout.counter, lang);
2092 // handle 'inherited level parts' in 'fmt',
2093 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2094 size_t const i = fmt.find('@', 0);
2095 if (i != docstring::npos) {
2096 size_t const j = fmt.find('@', i + 1);
2097 if (j != docstring::npos) {
2098 docstring parent(fmt, i + 1, j - i - 1);
2099 docstring label = from_ascii("??");
2100 if (tclass.hasLayout(parent))
2101 label = expandParagraphLabel(tclass[parent], bparams,
2103 fmt = docstring(fmt, 0, i) + label
2104 + docstring(fmt, j + 1, docstring::npos);
2108 return tclass.counters().counterLabel(fmt, lang);
2112 void Paragraph::applyLayout(Layout const & new_layout)
2114 d->layout_ = &new_layout;
2115 LyXAlignment const oldAlign = d->params_.align();
2117 if (!(oldAlign & d->layout_->alignpossible)) {
2118 frontend::Alert::warning(_("Alignment not permitted"),
2119 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2120 d->params_.align(LYX_ALIGN_LAYOUT);
2125 pos_type Paragraph::beginOfBody() const
2127 return d->begin_of_body_;
2131 void Paragraph::setBeginOfBody()
2133 if (d->layout_->labeltype != LABEL_MANUAL) {
2134 d->begin_of_body_ = 0;
2138 // Unroll the first two cycles of the loop
2139 // and remember the previous character to
2140 // remove unnecessary getChar() calls
2142 pos_type end = size();
2143 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2146 char_type previous_char = d->text_[i];
2147 if (!(isNewline(i) || isEnvSeparator(i))) {
2149 while (i < end && previous_char != ' ') {
2150 char_type temp = d->text_[i];
2151 if (isNewline(i) || isEnvSeparator(i))
2154 previous_char = temp;
2160 d->begin_of_body_ = i;
2164 bool Paragraph::allowParagraphCustomization() const
2166 return inInset().allowParagraphCustomization();
2170 bool Paragraph::usePlainLayout() const
2172 return inInset().usePlainLayout();
2176 bool Paragraph::isPassThru() const
2178 return inInset().isPassThru() || d->layout_->pass_thru;
2183 // paragraphs inside floats need different alignment tags to avoid
2186 bool noTrivlistCentering(InsetCode code)
2188 return code == FLOAT_CODE
2189 || code == WRAP_CODE
2190 || code == CELL_CODE;
2194 string correction(string const & orig)
2196 if (orig == "flushleft")
2197 return "raggedright";
2198 if (orig == "flushright")
2199 return "raggedleft";
2200 if (orig == "center")
2206 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2207 InsetCode code, bool const lastpar, int & col)
2209 string macro = suffix + "{";
2210 if (noTrivlistCentering(code)) {
2212 // the last paragraph in non-trivlist-aligned
2213 // context is special (to avoid unwanted whitespace)
2214 if (suffix == "\\begin") {
2215 macro = "\\" + correction(env) + "{}";
2216 os << from_ascii(macro);
2217 col += macro.size();
2222 macro += correction(env);
2226 if (suffix == "\\par\\end") {
2230 os << from_ascii(macro);
2231 col += macro.size();
2232 if (suffix == "\\begin") {
2242 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2243 otexstream & os, OutputParams const & runparams) const
2248 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2249 (layout_->toggle_indent != ITOGGLE_NEVER) :
2250 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2252 if (canindent && params_.noindent() && !layout_->pass_thru) {
2253 os << "\\noindent ";
2257 LyXAlignment const curAlign = params_.align();
2259 if (curAlign == layout_->align)
2263 case LYX_ALIGN_NONE:
2264 case LYX_ALIGN_BLOCK:
2265 case LYX_ALIGN_LAYOUT:
2266 case LYX_ALIGN_SPECIAL:
2267 case LYX_ALIGN_DECIMAL:
2269 case LYX_ALIGN_LEFT:
2270 case LYX_ALIGN_RIGHT:
2271 case LYX_ALIGN_CENTER:
2272 if (runparams.moving_arg) {
2279 string const begin_tag = "\\begin";
2280 InsetCode code = ownerCode();
2281 bool const lastpar = runparams.isLastPar;
2282 // RTL without the Bidi package switches the left/right logic
2283 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2284 && !runparams.use_polyglossia;
2287 case LYX_ALIGN_NONE:
2288 case LYX_ALIGN_BLOCK:
2289 case LYX_ALIGN_LAYOUT:
2290 case LYX_ALIGN_SPECIAL:
2291 case LYX_ALIGN_DECIMAL:
2293 case LYX_ALIGN_LEFT: {
2295 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2297 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2299 } case LYX_ALIGN_RIGHT: {
2301 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2303 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2305 } case LYX_ALIGN_CENTER: {
2306 corrected_env(os, begin_tag, "center", code, lastpar, column);
2315 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2316 otexstream & os, OutputParams const & runparams) const
2318 LyXAlignment const curAlign = params_.align();
2320 if (curAlign == layout_->align)
2324 case LYX_ALIGN_NONE:
2325 case LYX_ALIGN_BLOCK:
2326 case LYX_ALIGN_LAYOUT:
2327 case LYX_ALIGN_SPECIAL:
2328 case LYX_ALIGN_DECIMAL:
2330 case LYX_ALIGN_LEFT:
2331 case LYX_ALIGN_RIGHT:
2332 case LYX_ALIGN_CENTER:
2333 if (runparams.moving_arg)
2338 bool output = false;
2340 string const end_tag = "\\par\\end";
2341 InsetCode code = ownerCode();
2342 bool const lastpar = runparams.isLastPar;
2343 // RTL without the Bidi package switches the left/right logic
2344 bool const rtl_classic = owner_->getParLanguage(bparams)->rightToLeft()
2345 && !runparams.use_polyglossia;
2348 case LYX_ALIGN_NONE:
2349 case LYX_ALIGN_BLOCK:
2350 case LYX_ALIGN_LAYOUT:
2351 case LYX_ALIGN_SPECIAL:
2352 case LYX_ALIGN_DECIMAL:
2354 case LYX_ALIGN_LEFT: {
2356 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2358 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2360 } case LYX_ALIGN_RIGHT: {
2362 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2364 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2366 } case LYX_ALIGN_CENTER: {
2367 corrected_env(os, end_tag, "center", code, lastpar, col);
2372 return output || lastpar;
2376 // This one spits out the text of the paragraph
2377 void Paragraph::latex(BufferParams const & bparams,
2378 Font const & outerfont,
2380 OutputParams const & runparams,
2381 int start_pos, int end_pos, bool force) const
2383 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2385 // FIXME This check should not be needed. Perhaps issue an
2386 // error if it triggers.
2387 Layout const & style = inInset().forcePlainLayout() ?
2388 bparams.documentClass().plainLayout() : *d->layout_;
2390 if (!force && style.inpreamble)
2393 bool const allowcust = allowParagraphCustomization();
2395 // Current base font for all inherited font changes, without any
2396 // change caused by an individual character, except for the language:
2397 // It is set to the language of the first character.
2398 // As long as we are in the label, this font is the base font of the
2399 // label. Before the first body character it is set to the base font
2403 // Maybe we have to create a optional argument.
2404 pos_type body_pos = beginOfBody();
2405 unsigned int column = 0;
2408 // the optional argument is kept in curly brackets in
2409 // case it contains a ']'
2410 // This is not strictly needed, but if this is changed it
2411 // would be a file format change, and tex2lyx would need
2412 // to be adjusted, since it unconditionally removes the
2413 // braces when it parses \item.
2416 basefont = getLabelFont(bparams, outerfont);
2418 basefont = getLayoutFont(bparams, outerfont);
2421 // Which font is currently active?
2422 Font running_font(basefont);
2423 // Do we have an open font change?
2424 bool open_font = false;
2426 Change runningChange = Change(Change::UNCHANGED);
2428 Encoding const * const prev_encoding = runparams.encoding;
2430 os.texrow().start(id(), 0);
2432 // if the paragraph is empty, the loop will not be entered at all
2434 // For InTitle commands, we have already opened a group
2435 // in output_latex::TeXOnePar.
2436 if (style.isCommand() && !style.intitle) {
2440 if (!style.leftdelim().empty()) {
2441 os << style.leftdelim();
2442 column += style.leftdelim().size();
2445 column += d->startTeXParParams(bparams, os, runparams);
2448 // Whether a \par can be issued for insets typeset inline with text.
2449 // Yes if greater than 0. This has to be static.
2450 THREAD_LOCAL_STATIC int parInline = 0;
2452 for (pos_type i = 0; i < size(); ++i) {
2453 // First char in paragraph or after label?
2454 if (i == body_pos) {
2457 bool needPar = false;
2458 column += running_font.latexWriteEndChanges(
2459 os, bparams, runparams,
2460 basefont, basefont, needPar);
2463 basefont = getLayoutFont(bparams, outerfont);
2464 running_font = basefont;
2466 column += Changes::latexMarkChange(os, bparams,
2467 runningChange, Change(Change::UNCHANGED),
2469 runningChange = Change(Change::UNCHANGED);
2474 // For InTitle commands, we have already opened a group
2475 // in output_latex::TeXOnePar.
2476 if (style.isCommand() && !style.intitle) {
2481 if (!style.leftdelim().empty()) {
2482 os << style.leftdelim();
2483 column += style.leftdelim().size();
2487 column += d->startTeXParParams(bparams, os,
2491 runparams.wasDisplayMath = runparams.inDisplayMath;
2492 runparams.inDisplayMath = false;
2493 bool deleted_display_math = false;
2494 Change const & change = runparams.inDeletedInset
2495 ? runparams.changeOfDeletedInset : lookupChange(i);
2497 // Check whether a display math inset follows
2498 if (d->text_[i] == META_INSET
2499 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2500 InsetMath const * im = getInset(i)->asInsetMath();
2501 if (im && im->asHullInset()
2502 && im->asHullInset()->outerDisplay()) {
2503 runparams.inDisplayMath = true;
2504 // runparams.inDeletedInset will be set by
2505 // latexInset later, but we need this info
2506 // before it is called. On the other hand, we
2507 // cannot set it here because it is a counter.
2508 deleted_display_math = isDeleted(i);
2510 if (bparams.output_changes && deleted_display_math
2511 && runningChange == change
2512 && change.type == Change::DELETED
2513 && !os.afterParbreak()) {
2514 // A display math in the same paragraph follows.
2515 // We have to close and then reopen \lyxdeleted,
2516 // otherwise the math will be shifted up.
2517 OutputParams rp = runparams;
2519 bool needPar = false;
2520 column += running_font.latexWriteEndChanges(
2521 os, bparams, rp, basefont,
2525 basefont = getLayoutFont(bparams, outerfont);
2526 running_font = basefont;
2527 column += Changes::latexMarkChange(os, bparams,
2528 Change(Change::INSERTED), change, rp);
2532 if (bparams.output_changes && runningChange != change) {
2534 bool needPar = false;
2535 column += running_font.latexWriteEndChanges(
2536 os, bparams, runparams,
2537 basefont, basefont, needPar);
2540 basefont = getLayoutFont(bparams, outerfont);
2541 running_font = basefont;
2542 column += Changes::latexMarkChange(os, bparams, runningChange,
2544 runningChange = change;
2547 // do not output text which is marked deleted
2548 // if change tracking output is disabled
2549 if (!bparams.output_changes && change.deleted()) {
2555 // Fully instantiated font
2556 Font const current_font = getFont(bparams, i, outerfont);
2558 Font const last_font = running_font;
2560 // Do we need to close the previous font?
2562 (current_font != running_font ||
2563 current_font.language() != running_font.language()))
2565 bool needPar = false;
2566 column += running_font.latexWriteEndChanges(
2567 os, bparams, runparams, basefont,
2568 (i == body_pos-1) ? basefont : current_font,
2570 running_font = basefont;
2574 string const running_lang = runparams.use_polyglossia ?
2575 running_font.language()->polyglossia() : running_font.language()->babel();
2576 // close babel's font environment before opening CJK.
2577 string const lang_end_command = runparams.use_polyglossia ?
2578 "\\end{$$lang}" : lyxrc.language_command_end;
2579 bool const using_begin_end = runparams.use_polyglossia ||
2580 !lang_end_command.empty();
2581 if (!running_lang.empty() &&
2582 (!using_begin_end || running_lang == openLanguageName()) &&
2583 current_font.language()->encoding()->package() == Encoding::CJK) {
2584 string end_tag = subst(lang_end_command,
2587 os << from_ascii(end_tag);
2588 column += end_tag.length();
2589 if (using_begin_end)
2593 // Switch file encoding if necessary (and allowed)
2594 if (!runparams.pass_thru && !style.pass_thru &&
2595 runparams.encoding->package() != Encoding::none &&
2596 current_font.language()->encoding()->package() != Encoding::none) {
2597 pair<bool, int> const enc_switch =
2598 switchEncoding(os.os(), bparams, runparams,
2599 *(current_font.language()->encoding()));
2600 if (enc_switch.first) {
2601 column += enc_switch.second;
2602 runparams.encoding = current_font.language()->encoding();
2606 char_type const c = d->text_[i];
2608 // A display math inset inside an ulem command will be output
2609 // as a box of width \linewidth, so we have to either disable
2610 // indentation if the inset starts a paragraph, or start a new
2611 // line to accommodate such box. This has to be done before
2612 // writing any font changing commands.
2613 if (runparams.inDisplayMath && !deleted_display_math
2614 && runparams.inulemcmd) {
2615 if (os.afterParbreak())
2621 // Do we need to change font?
2622 if ((current_font != running_font ||
2623 current_font.language() != running_font.language()) &&
2626 odocstringstream ods;
2627 column += current_font.latexWriteStartChanges(ods, bparams,
2628 runparams, basefont,
2630 // Check again for display math in ulem commands as a
2631 // font change may also occur just before a math inset.
2632 if (runparams.inDisplayMath && !deleted_display_math
2633 && runparams.inulemcmd) {
2634 if (os.afterParbreak())
2639 running_font = current_font;
2641 docstring fontchange = ods.str();
2642 // check whether the fontchange ends with a \\textcolor
2643 // modifier and the text starts with a space (bug 4473)
2644 docstring const last_modifier = rsplit(fontchange, '\\');
2645 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2646 os << fontchange << from_ascii("{}");
2647 // check if the fontchange ends with a trailing blank
2648 // (like "\small " (see bug 3382)
2649 else if (suffixIs(fontchange, ' ') && c == ' ')
2650 os << fontchange.substr(0, fontchange.size() - 1)
2651 << from_ascii("{}");
2656 // FIXME: think about end_pos implementation...
2657 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2658 // FIXME: integrate this case in latexSpecialChar
2659 // Do not print the separation of the optional argument
2660 // if style.pass_thru is false. This works because
2661 // latexSpecialChar ignores spaces if
2662 // style.pass_thru is false.
2663 if (i != body_pos - 1) {
2664 if (d->simpleTeXBlanks(runparams, os,
2665 i, column, current_font, style)) {
2666 // A surrogate pair was output. We
2667 // must not call latexSpecialChar
2668 // in this iteration, since it would output
2669 // the combining character again.
2676 OutputParams rp = runparams;
2677 rp.free_spacing = style.free_spacing;
2678 rp.local_font = ¤t_font;
2679 rp.intitle = style.intitle;
2681 // Two major modes: LaTeX or plain
2682 // Handle here those cases common to both modes
2683 // and then split to handle the two modes separately.
2684 if (c == META_INSET) {
2685 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2686 // Greyedout notes and, in general, all insets
2687 // with InsetLayout::isDisplay() == false,
2688 // are typeset inline with the text. So, we
2689 // can add a \par to the last paragraph of
2690 // such insets only if nothing else follows.
2691 bool incremented = false;
2692 Inset const * inset = getInset(i);
2693 InsetText const * textinset = inset
2694 ? inset->asInsetText()
2696 if (i + 1 == size() && textinset
2697 && !inset->getLayout().isDisplay()) {
2698 ParagraphList const & pars =
2699 textinset->text().paragraphs();
2700 pit_type const pit = pars.size() - 1;
2701 Font const last_font =
2702 pit < 0 || pars[pit].empty()
2703 ? pars[pit].getLayoutFont(
2706 : pars[pit].getFont(bparams,
2707 pars[pit].size() - 1,
2709 if (last_font.fontInfo().size() !=
2710 basefont.fontInfo().size()) {
2715 d->latexInset(bparams, os, rp, running_font,
2716 basefont, outerfont, open_font,
2717 runningChange, style, i, column);
2721 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2723 d->latexSpecialChar(os, bparams, rp,
2724 running_font, runningChange,
2725 style, i, end_pos, column);
2726 } catch (EncodingException & e) {
2727 if (runparams.dryrun) {
2728 os << "<" << _("LyX Warning: ")
2729 << _("uncodable character") << " '";
2733 // add location information and throw again.
2741 // Set the encoding to that returned from latexSpecialChar (see
2742 // comment for encoding member in OutputParams.h)
2743 runparams.encoding = rp.encoding;
2745 // Also carry on the info on a closed ulem command for insets
2746 // such as Note that do not produce any output, so that no
2747 // command is ever executed but its opening was recorded.
2748 runparams.inulemcmd = rp.inulemcmd;
2751 // If we have an open font definition, we have to close it
2753 // Make sure that \\par is done with the font of the last
2754 // character if this has another size as the default.
2755 // This is necessary because LaTeX (and LyX on the screen)
2756 // calculates the space between the baselines according
2757 // to this font. (Matthias)
2759 // We must not change the font for the last paragraph
2760 // of non-multipar insets, tabular cells or commands,
2761 // since this produces unwanted whitespace.
2763 Font const font = empty()
2764 ? getLayoutFont(bparams, outerfont)
2765 : getFont(bparams, size() - 1, outerfont);
2767 InsetText const * textinset = inInset().asInsetText();
2769 bool const maintext = textinset
2770 ? textinset->text().isMainText()
2773 size_t const numpars = textinset
2774 ? textinset->text().paragraphs().size()
2777 bool needPar = false;
2779 if (style.resfont.size() != font.fontInfo().size()
2780 && (!runparams.isLastPar || maintext
2781 || (numpars > 1 && d->ownerCode() != CELL_CODE
2782 && (inInset().getLayout().isDisplay()
2784 && !style.isCommand()) {
2787 #ifdef FIXED_LANGUAGE_END_DETECTION
2789 running_font.latexWriteEndChanges(os, bparams,
2790 runparams, basefont,
2791 next_->getFont(bparams, 0, outerfont),
2794 running_font.latexWriteEndChanges(os, bparams,
2795 runparams, basefont, basefont, needPar);
2798 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2799 //FIXME: there as we start another \selectlanguage with the next paragraph if
2800 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2801 running_font.latexWriteEndChanges(os, bparams, runparams,
2802 basefont, basefont, needPar);
2805 // The \par could not be inserted at the same nesting
2806 // level of the font size change, so do it now.
2807 os << "{\\" << font.latexSize() << "\\par}";
2811 column += Changes::latexMarkChange(os, bparams, runningChange,
2812 Change(Change::UNCHANGED), runparams);
2814 // Needed if there is an optional argument but no contents.
2815 if (body_pos > 0 && body_pos == size()) {
2819 if (!style.rightdelim().empty()) {
2820 os << style.rightdelim();
2821 column += style.rightdelim().size();
2824 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2825 && runparams.encoding != prev_encoding) {
2826 runparams.encoding = prev_encoding;
2827 os << setEncoding(prev_encoding->iconvName());
2830 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2834 bool Paragraph::emptyTag() const
2836 for (pos_type i = 0; i < size(); ++i) {
2837 if (Inset const * inset = getInset(i)) {
2838 InsetCode lyx_code = inset->lyxCode();
2839 // FIXME testing like that is wrong. What is
2841 if (lyx_code != TOC_CODE &&
2842 lyx_code != INCLUDE_CODE &&
2843 lyx_code != GRAPHICS_CODE &&
2844 lyx_code != ERT_CODE &&
2845 lyx_code != LISTINGS_CODE &&
2846 lyx_code != FLOAT_CODE &&
2847 lyx_code != TABULAR_CODE) {
2851 char_type c = d->text_[i];
2852 if (c != ' ' && c != '\t')
2860 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2863 for (pos_type i = 0; i < size(); ++i) {
2864 if (Inset const * inset = getInset(i)) {
2865 InsetCode lyx_code = inset->lyxCode();
2866 if (lyx_code == LABEL_CODE) {
2867 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2868 docstring const & id = il->getParam("name");
2869 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2877 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2881 for (i = 0; i < size(); ++i) {
2882 if (Inset const * inset = getInset(i)) {
2883 inset->docbook(os, runparams);
2885 char_type c = d->text_[i];
2888 os << sgml::escapeChar(c);
2895 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2899 for (i = 0; i < size(); ++i) {
2900 if (Inset const * inset = getInset(i)) {
2901 inset->xhtml(xs, runparams);
2903 char_type c = d->text_[i];
2913 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2916 pos_type size = text_.size();
2917 for (pos_type i = initial; i < size; ++i) {
2918 Font font = owner_->getFont(buf.params(), i, outerfont);
2919 if (text_[i] == META_INSET)
2921 if (i != initial && font != font_old)
2930 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2932 OutputParams const & runparams,
2933 Font const & outerfont,
2934 pos_type initial) const
2936 bool emph_flag = false;
2938 Layout const & style = *d->layout_;
2940 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2942 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2945 // parsing main loop
2946 for (pos_type i = initial; i < size(); ++i) {
2947 Font font = getFont(buf.params(), i, outerfont);
2949 // handle <emphasis> tag
2950 if (font_old.emph() != font.fontInfo().emph()) {
2951 if (font.fontInfo().emph() == FONT_ON) {
2954 } else if (i != initial) {
2955 os << "</emphasis>";
2960 if (Inset const * inset = getInset(i)) {
2961 inset->docbook(os, runparams);
2963 char_type c = d->text_[i];
2965 if (style.pass_thru)
2968 os << sgml::escapeChar(c);
2970 font_old = font.fontInfo();
2974 os << "</emphasis>";
2977 if (style.free_spacing)
2979 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2985 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2986 vector<html::EndFontTag> & tagsToClose,
2987 bool & flag, FontState curstate, html::FontTypes type)
2989 if (curstate == FONT_ON) {
2990 tagsToOpen.push_back(html::FontTag(type));
2993 tagsToClose.push_back(html::EndFontTag(type));
3000 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3002 OutputParams const & runparams,
3003 Font const & outerfont,
3004 bool start_paragraph, bool close_paragraph,
3005 pos_type initial) const
3009 // track whether we have opened these tags
3010 bool emph_flag = false;
3011 bool bold_flag = false;
3012 bool noun_flag = false;
3013 bool ubar_flag = false;
3014 bool dbar_flag = false;
3015 bool sout_flag = false;
3016 bool xout_flag = false;
3017 bool wave_flag = false;
3019 bool shap_flag = false;
3021 bool faml_flag = false;
3023 bool size_flag = false;
3025 Layout const & style = *d->layout_;
3027 if (start_paragraph)
3028 xs.startDivision(allowEmpty());
3031 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3033 FontShape curr_fs = INHERIT_SHAPE;
3034 FontFamily curr_fam = INHERIT_FAMILY;
3035 FontSize curr_size = FONT_SIZE_INHERIT;
3037 string const default_family =
3038 buf.masterBuffer()->params().fonts_default_family;
3040 vector<html::FontTag> tagsToOpen;
3041 vector<html::EndFontTag> tagsToClose;
3043 // parsing main loop
3044 for (pos_type i = initial; i < size(); ++i) {
3045 // let's not show deleted material in the output
3049 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3052 FontState curstate = font.fontInfo().emph();
3053 if (font_old.emph() != curstate)
3054 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3057 curstate = font.fontInfo().noun();
3058 if (font_old.noun() != curstate)
3059 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3062 curstate = font.fontInfo().underbar();
3063 if (font_old.underbar() != curstate)
3064 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3067 curstate = font.fontInfo().strikeout();
3068 if (font_old.strikeout() != curstate)
3069 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3072 curstate = font.fontInfo().xout();
3073 if (font_old.xout() != curstate)
3074 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3077 curstate = font.fontInfo().uuline();
3078 if (font_old.uuline() != curstate)
3079 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3082 curstate = font.fontInfo().uwave();
3083 if (font_old.uwave() != curstate)
3084 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3087 // a little hackish, but allows us to reuse what we have.
3088 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3089 if (font_old.series() != font.fontInfo().series())
3090 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3093 curr_fs = font.fontInfo().shape();
3094 FontShape old_fs = font_old.shape();
3095 if (old_fs != curr_fs) {
3099 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3102 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3104 case SMALLCAPS_SHAPE:
3105 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3111 // the other tags are for internal use
3119 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3123 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3126 case SMALLCAPS_SHAPE:
3127 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3134 // the other tags are for internal use
3141 curr_fam = font.fontInfo().family();
3142 FontFamily old_fam = font_old.family();
3143 if (old_fam != curr_fam) {
3147 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3150 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3152 case TYPEWRITER_FAMILY:
3153 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3155 case INHERIT_FAMILY:
3158 // the other tags are for internal use
3166 // we will treat a "default" font family as roman, since we have
3167 // no other idea what to do.
3168 if (default_family != "rmdefault" && default_family != "default") {
3169 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3174 if (default_family != "sfdefault") {
3175 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3179 case TYPEWRITER_FAMILY:
3180 if (default_family != "ttdefault") {
3181 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3185 case INHERIT_FAMILY:
3188 // the other tags are for internal use
3195 curr_size = font.fontInfo().size();
3196 FontSize old_size = font_old.size();
3197 if (old_size != curr_size) {
3200 case FONT_SIZE_TINY:
3201 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3203 case FONT_SIZE_SCRIPT:
3204 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3206 case FONT_SIZE_FOOTNOTE:
3207 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3209 case FONT_SIZE_SMALL:
3210 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3212 case FONT_SIZE_LARGE:
3213 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3215 case FONT_SIZE_LARGER:
3216 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3218 case FONT_SIZE_LARGEST:
3219 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3221 case FONT_SIZE_HUGE:
3222 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3224 case FONT_SIZE_HUGER:
3225 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3227 case FONT_SIZE_INCREASE:
3228 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3230 case FONT_SIZE_DECREASE:
3231 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3233 case FONT_SIZE_INHERIT:
3234 case FONT_SIZE_NORMAL:
3237 // the other tags are for internal use
3243 switch (curr_size) {
3244 case FONT_SIZE_TINY:
3245 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3248 case FONT_SIZE_SCRIPT:
3249 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3252 case FONT_SIZE_FOOTNOTE:
3253 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3256 case FONT_SIZE_SMALL:
3257 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3260 case FONT_SIZE_LARGE:
3261 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3264 case FONT_SIZE_LARGER:
3265 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3268 case FONT_SIZE_LARGEST:
3269 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3272 case FONT_SIZE_HUGE:
3273 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3276 case FONT_SIZE_HUGER:
3277 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3280 case FONT_SIZE_INCREASE:
3281 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3284 case FONT_SIZE_DECREASE:
3285 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3288 case FONT_SIZE_NORMAL:
3289 case FONT_SIZE_INHERIT:
3292 // the other tags are for internal use
3299 // Other such tags? What about the other text ranges?
3301 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3302 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3303 for (; cit != cen; ++cit)
3306 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3307 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3308 for (; sit != sen; ++sit)
3311 tagsToClose.clear();
3314 Inset const * inset = getInset(i);
3316 if (!runparams.for_toc || inset->isInToc()) {
3317 OutputParams np = runparams;
3318 np.local_font = &font;
3319 // If the paragraph has size 1, then we are in the "special
3320 // case" where we do not output the containing paragraph info
3321 if (!inset->getLayout().htmlisblock() && size() != 1)
3322 np.html_in_par = true;
3323 retval += inset->xhtml(xs, np);
3326 char_type c = getUChar(buf.masterBuffer()->params(),
3328 if (c == ' ' && (style.free_spacing || runparams.free_spacing))
3329 xs << XHTMLStream::ESCAPE_NONE << " ";
3333 font_old = font.fontInfo();
3337 // I'm worried about what happens if a branch, say, is itself
3338 // wrapped in some font stuff. I think that will not work.
3340 if (close_paragraph)
3347 bool Paragraph::isHfill(pos_type pos) const
3349 Inset const * inset = getInset(pos);
3350 return inset && inset->isHfill();
3354 bool Paragraph::isNewline(pos_type pos) const
3356 // U+2028 LINE SEPARATOR
3357 // U+2029 PARAGRAPH SEPARATOR
3358 char_type const c = d->text_[pos];
3359 if (c == 0x2028 || c == 0x2029)
3361 Inset const * inset = getInset(pos);
3362 return inset && inset->lyxCode() == NEWLINE_CODE;
3366 bool Paragraph::isEnvSeparator(pos_type pos) const
3368 Inset const * inset = getInset(pos);
3369 return inset && inset->lyxCode() == SEPARATOR_CODE;
3373 bool Paragraph::isLineSeparator(pos_type pos) const
3375 char_type const c = d->text_[pos];
3376 if (isLineSeparatorChar(c))
3378 Inset const * inset = getInset(pos);
3379 return inset && inset->isLineSeparator();
3383 bool Paragraph::isWordSeparator(pos_type pos) const
3387 if (Inset const * inset = getInset(pos))
3388 return !inset->isLetter();
3389 // if we have a hard hyphen (no en- or emdash) or apostrophe
3390 // we pass this to the spell checker
3391 // FIXME: this method is subject to change, visit
3392 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3393 // to get an impression how complex this is.
3394 if (isHardHyphenOrApostrophe(pos))
3396 char_type const c = d->text_[pos];
3397 // We want to pass the escape chars to the spellchecker
3398 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3399 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3403 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3405 pos_type const psize = size();
3408 char_type const c = d->text_[pos];
3409 if (c != '-' && c != '\'')
3411 int nextpos = pos + 1;
3412 int prevpos = pos > 0 ? pos - 1 : 0;
3413 if ((nextpos == psize || isSpace(nextpos))
3414 && (pos == 0 || isSpace(prevpos)))
3420 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3422 return d->speller_state_.getRange(pos);
3426 bool Paragraph::isChar(pos_type pos) const
3428 if (Inset const * inset = getInset(pos))
3429 return inset->isChar();
3430 char_type const c = d->text_[pos];
3431 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3435 bool Paragraph::isSpace(pos_type pos) const
3437 if (Inset const * inset = getInset(pos))
3438 return inset->isSpace();
3439 char_type const c = d->text_[pos];
3440 return lyx::isSpace(c);
3445 Paragraph::getParLanguage(BufferParams const & bparams) const
3448 return getFirstFontSettings(bparams).language();
3449 // FIXME: we should check the prev par as well (Lgb)
3450 return bparams.language;
3454 bool Paragraph::isRTL(BufferParams const & bparams) const
3456 return getParLanguage(bparams)->rightToLeft()
3457 && !inInset().getLayout().forceLTR();
3461 void Paragraph::changeLanguage(BufferParams const & bparams,
3462 Language const * from, Language const * to)
3464 // change language including dummy font change at the end
3465 for (pos_type i = 0; i <= size(); ++i) {
3466 Font font = getFontSettings(bparams, i);
3467 if (font.language() == from) {
3468 font.setLanguage(to);
3470 d->requestSpellCheck(i);
3476 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3478 Language const * doc_language = bparams.language;
3479 FontList::const_iterator cit = d->fontlist_.begin();
3480 FontList::const_iterator end = d->fontlist_.end();
3482 for (; cit != end; ++cit)
3483 if (cit->font().language() != ignore_language &&
3484 cit->font().language() != latex_language &&
3485 cit->font().language() != doc_language)
3491 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3493 FontList::const_iterator cit = d->fontlist_.begin();
3494 FontList::const_iterator end = d->fontlist_.end();
3496 for (; cit != end; ++cit) {
3497 Language const * lang = cit->font().language();
3498 if (lang != ignore_language &&
3499 lang != latex_language)
3500 languages.insert(lang);
3505 docstring Paragraph::asString(int options) const
3507 return asString(0, size(), options);
3511 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3513 odocstringstream os;
3516 && options & AS_STR_LABEL
3517 && !d->params_.labelString().empty())
3518 os << d->params_.labelString() << ' ';
3520 for (pos_type i = beg; i < end; ++i) {
3521 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3523 char_type const c = d->text_[i];
3524 if (isPrintable(c) || c == '\t'
3525 || (c == '\n' && (options & AS_STR_NEWLINES)))
3527 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3528 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3529 LASSERT(runparams != 0, return docstring());
3530 getInset(i)->plaintext(os, *runparams);
3532 getInset(i)->toString(os);
3541 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3542 bool const shorten, bool const label) const
3544 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3545 if (label && !labelString().empty())
3546 os += labelString() + ' ';
3547 if (!layout().isTocCaption())
3549 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3552 char_type const c = d->text_[i];
3555 else if (c == META_INSET)
3556 getInset(i)->forOutliner(os, tmplen, false);
3559 Text::shortenForOutliner(os, maxlen);
3563 void Paragraph::setInsetOwner(Inset const * inset)
3565 d->inset_owner_ = inset;
3569 int Paragraph::id() const
3575 void Paragraph::setId(int id)
3581 Layout const & Paragraph::layout() const
3587 void Paragraph::setLayout(Layout const & layout)
3589 d->layout_ = &layout;
3593 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3595 setLayout(tc.defaultLayout());
3599 void Paragraph::setPlainLayout(DocumentClass const & tc)
3601 setLayout(tc.plainLayout());
3605 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3607 if (usePlainLayout())
3608 setPlainLayout(tclass);
3610 setDefaultLayout(tclass);
3614 Inset const & Paragraph::inInset() const
3616 LBUFERR(d->inset_owner_);
3617 return *d->inset_owner_;
3621 ParagraphParameters & Paragraph::params()
3627 ParagraphParameters const & Paragraph::params() const
3633 bool Paragraph::isFreeSpacing() const
3635 if (d->layout_->free_spacing)
3637 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3641 bool Paragraph::allowEmpty() const
3643 if (d->layout_->keepempty)
3645 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3649 bool Paragraph::brokenBiblio() const
3651 // There is a problem if there is no bibitem at position 0 in
3652 // paragraphs that need one, if there is another bibitem in the
3653 // paragraph or if this paragraph is not supposed to have
3654 // a bibitem inset at all.
3655 return ((d->layout_->labeltype == LABEL_BIBLIO
3656 && (d->insetlist_.find(BIBITEM_CODE) != 0
3657 || d->insetlist_.find(BIBITEM_CODE, 1) > 0))
3658 || (d->layout_->labeltype != LABEL_BIBLIO
3659 && d->insetlist_.find(BIBITEM_CODE) != -1));
3663 int Paragraph::fixBiblio(Buffer const & buffer)
3665 // FIXME: when there was already an inset at 0, the return value is 1,
3666 // which does not tell whether another inset has been remove; the
3667 // cursor cannot be correctly updated.
3669 bool const track_changes = buffer.params().track_changes;
3670 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3672 // The case where paragraph is not BIBLIO
3673 if (d->layout_->labeltype != LABEL_BIBLIO) {
3674 if (bibitem_pos == -1)
3675 // No InsetBibitem => OK
3677 // There is an InsetBibitem: remove it!
3678 d->insetlist_.release(bibitem_pos);
3679 eraseChar(bibitem_pos, track_changes);
3680 return (bibitem_pos == 0) ? -1 : -bibitem_pos;
3683 bool const hasbibitem0 = bibitem_pos == 0;
3685 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3686 // There was an InsetBibitem at pos 0,
3687 // and no other one => OK
3688 if (bibitem_pos == -1)
3690 // there is a bibitem at the 0 position, but since
3691 // there is a second one, we copy the second on the
3692 // first. We're assuming there are at most two of
3693 // these, which there should be.
3694 // FIXME: why does it make sense to do that rather
3695 // than keep the first? (JMarc)
3696 Inset * inset = releaseInset(bibitem_pos);
3697 d->insetlist_.begin()->inset = inset;
3698 return -bibitem_pos;
3701 // We need to create an inset at the beginning
3702 Inset * inset = nullptr;
3703 if (bibitem_pos > 0) {
3704 // there was one somewhere in the paragraph, let's move it
3705 inset = d->insetlist_.release(bibitem_pos);
3706 eraseChar(bibitem_pos, track_changes);
3709 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3710 InsetCommandParams(BIBITEM_CODE));
3712 Font font(inherit_font, buffer.params().language);
3713 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3714 : Change::UNCHANGED));
3716 // This is needed to get the counters right
3717 buffer.updateBuffer();
3722 void Paragraph::checkAuthors(AuthorList const & authorList)
3724 d->changes_.checkAuthors(authorList);
3728 bool Paragraph::isChanged(pos_type pos) const
3730 return lookupChange(pos).changed();
3734 bool Paragraph::isInserted(pos_type pos) const
3736 return lookupChange(pos).inserted();
3740 bool Paragraph::isDeleted(pos_type pos) const
3742 return lookupChange(pos).deleted();
3746 InsetList const & Paragraph::insetList() const
3748 return d->insetlist_;
3752 void Paragraph::setBuffer(Buffer & b)
3754 d->insetlist_.setBuffer(b);
3758 void Paragraph::resetBuffer()
3760 d->insetlist_.resetBuffer();
3764 Inset * Paragraph::releaseInset(pos_type pos)
3766 Inset * inset = d->insetlist_.release(pos);
3767 /// does not honour change tracking!
3768 eraseChar(pos, false);
3773 Inset * Paragraph::getInset(pos_type pos)
3775 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3776 ? d->insetlist_.get(pos) : 0;
3780 Inset const * Paragraph::getInset(pos_type pos) const
3782 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3783 ? d->insetlist_.get(pos) : 0;
3787 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3788 pos_type & right, TextCase action)
3790 // process sequences of modified characters; in change
3791 // tracking mode, this approach results in much better
3792 // usability than changing case on a char-by-char basis
3793 // We also need to track the current font, since font
3794 // changes within sequences can occur.
3795 vector<pair<char_type, Font> > changes;
3797 bool const trackChanges = bparams.track_changes;
3799 bool capitalize = true;
3801 for (; pos < right; ++pos) {
3802 char_type oldChar = d->text_[pos];
3803 char_type newChar = oldChar;
3805 // ignore insets and don't play with deleted text!
3806 if (oldChar != META_INSET && !isDeleted(pos)) {
3808 case text_lowercase:
3809 newChar = lowercase(oldChar);
3811 case text_capitalization:
3813 newChar = uppercase(oldChar);
3817 case text_uppercase:
3818 newChar = uppercase(oldChar);
3823 if (isWordSeparator(pos) || isDeleted(pos)) {
3824 // permit capitalization again
3828 if (oldChar != newChar) {
3829 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3830 if (pos != right - 1)
3832 // step behind the changing area
3836 int erasePos = pos - changes.size();
3837 for (size_t i = 0; i < changes.size(); i++) {
3838 insertChar(pos, changes[i].first,
3841 if (!eraseChar(erasePos, trackChanges)) {
3844 ++right; // expand selection
3852 int Paragraph::find(docstring const & str, bool cs, bool mw,
3853 pos_type start_pos, bool del) const
3855 pos_type pos = start_pos;
3856 int const strsize = str.length();
3858 pos_type const parsize = d->text_.size();
3859 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3860 // Ignore "invisible" letters such as ligature breaks
3861 // and hyphenation chars while searching
3862 while (pos < parsize - 1 && isInset(pos)) {
3863 odocstringstream os;
3864 getInset(pos)->toString(os);
3865 if (!getInset(pos)->isLetter() || !os.str().empty())
3869 if (cs && str[i] != d->text_[pos])
3871 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3873 if (!del && isDeleted(pos))
3880 // if necessary, check whether string matches word
3882 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3885 && !isWordSeparator(pos))
3889 return pos - start_pos;
3893 char_type Paragraph::getChar(pos_type pos) const
3895 return d->text_[pos];
3899 pos_type Paragraph::size() const
3901 return d->text_.size();
3905 bool Paragraph::empty() const
3907 return d->text_.empty();
3911 bool Paragraph::isInset(pos_type pos) const
3913 return d->text_[pos] == META_INSET;
3917 bool Paragraph::isSeparator(pos_type pos) const
3919 //FIXME: Are we sure this can be the only separator?
3920 return d->text_[pos] == ' ';
3924 void Paragraph::deregisterWords()
3926 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3927 Private::LangWordsMap::const_iterator ite = d->words_.end();
3928 for (; itl != ite; ++itl) {
3929 WordList & wl = theWordList(itl->first);
3930 Private::Words::const_iterator it = (itl->second).begin();
3931 Private::Words::const_iterator et = (itl->second).end();
3932 for (; it != et; ++it)
3939 void Paragraph::locateWord(pos_type & from, pos_type & to,
3940 word_location const loc) const
3943 case WHOLE_WORD_STRICT:
3944 if (from == 0 || from == size()
3945 || isWordSeparator(from)
3946 || isWordSeparator(from - 1)) {
3953 // If we are already at the beginning of a word, do nothing
3954 if (!from || isWordSeparator(from - 1))
3959 // always move the cursor to the beginning of previous word
3960 while (from && !isWordSeparator(from - 1))
3964 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3967 // no need to move the 'from' cursor
3971 while (to < size() && !isWordSeparator(to))
3976 void Paragraph::collectWords()
3978 for (pos_type pos = 0; pos < size(); ++pos) {
3979 if (isWordSeparator(pos))
3981 pos_type from = pos;
3982 locateWord(from, pos, WHOLE_WORD);
3983 // Work around MSVC warning: The statement
3984 // if (pos < from + lyxrc.completion_minlength)
3985 // triggers a signed vs. unsigned warning.
3986 // I don't know why this happens, it could be a MSVC bug, or
3987 // related to LLP64 (windows) vs. LP64 (unix) programming
3988 // model, or the C++ standard might be ambigous in the section
3989 // defining the "usual arithmetic conversions". However, using
3990 // a temporary variable is safe and works on all compilers.
3991 pos_type const endpos = from + lyxrc.completion_minlength;
3994 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3995 if (cit == d->fontlist_.end())
3997 Language const * lang = cit->font().language();
3998 docstring const word = asString(from, pos, AS_STR_NONE);
3999 d->words_[lang->lang()].insert(word);
4004 void Paragraph::registerWords()
4006 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4007 Private::LangWordsMap::const_iterator ite = d->words_.end();
4008 for (; itl != ite; ++itl) {
4009 WordList & wl = theWordList(itl->first);
4010 Private::Words::const_iterator it = (itl->second).begin();
4011 Private::Words::const_iterator et = (itl->second).end();
4012 for (; it != et; ++it)
4018 void Paragraph::updateWords()
4026 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4028 SkipPositionsIterator begin = skips.begin();
4029 SkipPositions::iterator end = skips.end();
4030 if (pos > 0 && begin < end) {
4032 if (end->last == pos - 1) {
4037 skips.insert(end, FontSpan(pos, pos));
4041 Language * Paragraph::Private::locateSpellRange(
4042 pos_type & from, pos_type & to,
4043 SkipPositions & skips) const
4045 // skip leading white space
4046 while (from < to && owner_->isWordSeparator(from))
4048 // don't check empty range
4051 // get current language
4052 Language * lang = getSpellLanguage(from);
4053 pos_type last = from;
4054 bool samelang = true;
4055 bool sameinset = true;
4056 while (last < to && samelang && sameinset) {
4057 // hop to end of word
4058 while (last < to && !owner_->isWordSeparator(last)) {
4059 if (owner_->getInset(last)) {
4060 appendSkipPosition(skips, last);
4061 } else if (owner_->isDeleted(last)) {
4062 appendSkipPosition(skips, last);
4066 // hop to next word while checking for insets
4067 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4068 if (Inset const * inset = owner_->getInset(last))
4069 sameinset = inset->isChar() && inset->isLetter();
4070 if (sameinset && owner_->isDeleted(last)) {
4071 appendSkipPosition(skips, last);
4076 if (sameinset && last < to) {
4077 // now check for language change
4078 samelang = lang == getSpellLanguage(last);
4081 // if language change detected backstep is needed
4089 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4092 const_cast<Language *>(owner_->getFontSettings(
4093 inset_owner_->buffer().params(), from).language());
4094 if (lang == inset_owner_->buffer().params().language
4095 && !lyxrc.spellchecker_alt_lang.empty()) {
4097 string const lang_variety =
4098 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4099 lang->setCode(lang_code);
4100 lang->setVariety(lang_variety);
4106 void Paragraph::requestSpellCheck(pos_type pos)
4108 d->requestSpellCheck(pos);
4112 bool Paragraph::needsSpellCheck() const
4114 SpellChecker::ChangeNumber speller_change_number = 0;
4115 if (theSpellChecker())
4116 speller_change_number = theSpellChecker()->changeNumber();
4117 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4118 d->speller_state_.needsCompleteRefresh(speller_change_number);
4120 return d->needsSpellCheck();
4124 bool Paragraph::Private::ignoreWord(docstring const & word) const
4126 // Ignore words with digits
4127 // FIXME: make this customizable
4128 // (note that some checkers ignore words with digits by default)
4129 docstring::const_iterator cit = word.begin();
4130 docstring::const_iterator const end = word.end();
4131 for (; cit != end; ++cit) {
4132 if (isNumber((*cit)))
4139 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4140 WordLangTuple & wl, docstring_list & suggestions,
4141 bool do_suggestion, bool check_learned) const
4143 SpellChecker::Result result = SpellChecker::WORD_OK;
4144 SpellChecker * speller = theSpellChecker();
4148 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4151 locateWord(from, to, WHOLE_WORD);
4152 if (from == to || from >= size())
4155 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4156 Language * lang = d->getSpellLanguage(from);
4158 wl = WordLangTuple(word, lang);
4163 if (needsSpellCheck() || check_learned) {
4165 if (!d->ignoreWord(word)) {
4166 bool const trailing_dot = to < size() && d->text_[to] == '.';
4167 result = speller->check(wl);
4168 if (SpellChecker::misspelled(result) && trailing_dot) {
4169 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4170 result = speller->check(wl);
4171 if (!SpellChecker::misspelled(result)) {
4172 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4174 from << ".." << to << "]");
4176 // spell check with dot appended failed too
4177 // restore original word/lang value
4178 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4179 wl = WordLangTuple(word, lang);
4183 if (!SpellChecker::misspelled(result)) {
4184 // area up to the begin of the next word is not misspelled
4185 while (end < size() && isWordSeparator(end))
4188 d->setMisspelled(from, end, result);
4190 result = d->speller_state_.getState(from);
4194 suggestions.clear();
4196 if (SpellChecker::misspelled(result)) {
4197 LYXERR(Debug::GUI, "misspelled word: \"" <<
4199 from << ".." << to << "]");
4201 speller->suggest(wl, suggestions);
4207 void Paragraph::anonymize()
4209 // This is a very crude anonymization for now
4210 for (char_type & c : d->text_)
4211 if (isLetterChar(c) || isNumber(c))
4216 void Paragraph::Private::markMisspelledWords(
4217 pos_type const & first, pos_type const & last,
4218 SpellChecker::Result result,
4219 docstring const & word,
4220 SkipPositions const & skips)
4222 if (!SpellChecker::misspelled(result)) {
4223 setMisspelled(first, last, SpellChecker::WORD_OK);
4227 SpellChecker * speller = theSpellChecker();
4228 // locate and enumerate the error positions
4229 int nerrors = speller->numMisspelledWords();
4231 SkipPositionsIterator it = skips.begin();
4232 SkipPositionsIterator et = skips.end();
4233 for (int index = 0; index < nerrors; ++index) {
4236 speller->misspelledWord(index, wstart, wlen);
4237 /// should not happen if speller supports range checks
4238 if (!wlen) continue;
4239 docstring const misspelled = word.substr(wstart, wlen);
4240 wstart += first + numskipped;
4241 if (snext < wstart) {
4242 /// mark the range of correct spelling
4243 numskipped += countSkips(it, et, wstart);
4244 setMisspelled(snext,
4245 wstart - 1, SpellChecker::WORD_OK);
4247 snext = wstart + wlen;
4248 numskipped += countSkips(it, et, snext);
4249 /// mark the range of misspelling
4250 setMisspelled(wstart, snext, result);
4251 LYXERR(Debug::GUI, "misspelled word: \"" <<
4252 misspelled << "\" [" <<
4253 wstart << ".." << (snext-1) << "]");
4256 if (snext <= last) {
4257 /// mark the range of correct spelling at end
4258 setMisspelled(snext, last, SpellChecker::WORD_OK);
4263 void Paragraph::spellCheck() const
4265 SpellChecker * speller = theSpellChecker();
4266 if (!speller || empty() ||!needsSpellCheck())
4270 d->rangeOfSpellCheck(start, endpos);
4271 if (speller->canCheckParagraph()) {
4272 // loop until we leave the range
4273 for (pos_type first = start; first < endpos; ) {
4274 pos_type last = endpos;
4275 Private::SkipPositions skips;
4276 Language * lang = d->locateSpellRange(first, last, skips);
4277 if (first >= endpos)
4279 // start the spell checker on the unit of meaning
4280 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4281 WordLangTuple wl = WordLangTuple(word, lang);
4282 SpellChecker::Result result = word.size() ?
4283 speller->check(wl) : SpellChecker::WORD_OK;
4284 d->markMisspelledWords(first, last, result, word, skips);
4288 static docstring_list suggestions;
4289 pos_type to = endpos;
4290 while (start < endpos) {
4292 spellCheck(start, to, wl, suggestions, false);
4296 d->readySpellCheck();
4300 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4302 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4303 if (result || pos <= 0 || pos > size())
4305 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4306 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4311 string Paragraph::magicLabel() const
4314 ss << "magicparlabel-" << id();