3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
93 /////////////////////////////////////////////////////////////////////
97 /////////////////////////////////////////////////////////////////////
99 class SpellResultRange {
101 SpellResultRange(FontSpan range, SpellChecker::Result result)
102 : range_(range), result_(result)
105 FontSpan const & range() const { return range_; }
107 void range(FontSpan const & r) { range_ = r; }
109 SpellChecker::Result result() const { return result_; }
111 void result(SpellChecker::Result r) { result_ = r; }
113 bool contains(pos_type pos) const { return range_.contains(pos); }
115 bool covered(FontSpan const & r) const
117 // 1. first of new range inside current range or
118 // 2. last of new range inside current range or
119 // 3. first of current range inside new range or
120 // 4. last of current range inside new range
121 //FIXME: is this the same as !range_.intersect(r).empty() ?
122 return range_.contains(r.first) || range_.contains(r.last) ||
123 r.contains(range_.first) || r.contains(range_.last);
126 void shift(pos_type pos, int offset)
128 if (range_.first > pos) {
129 range_.first += offset;
130 range_.last += offset;
131 } else if (range_.last >= pos) {
132 range_.last += offset;
137 SpellChecker::Result result_ ;
141 /////////////////////////////////////////////////////////////////////
145 /////////////////////////////////////////////////////////////////////
147 class SpellCheckerState {
151 needs_refresh_ = true;
152 current_change_number_ = 0;
155 void setRange(FontSpan const & fp, SpellChecker::Result state)
158 RangesIterator et = ranges_.end();
159 RangesIterator it = ranges_.begin();
160 for (; it != et; ++it) {
161 if (!it->covered(fp))
162 result.push_back(SpellResultRange(it->range(), it->result()));
163 else if (state == SpellChecker::WORD_OK) {
164 // trim or split the current misspelled range
165 // store misspelled ranges only
166 FontSpan range = it->range();
167 if (fp.first > range.first) {
168 // misspelled area in front of WORD_OK
169 range.last = fp.first - 1;
170 result.push_back(SpellResultRange(range, it->result()));
173 if (fp.last < range.last) {
174 // misspelled area after WORD_OK range
175 range.first = fp.last + 1;
176 result.push_back(SpellResultRange(range, it->result()));
181 if (state != SpellChecker::WORD_OK)
182 ranges_.push_back(SpellResultRange(fp, state));
185 void increasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, 1);
191 void decreasePosAfterPos(pos_type pos)
193 correctRangesAfterPos(pos, -1);
197 void refreshLast(pos_type pos)
199 if (pos < refresh_.last)
203 SpellChecker::Result getState(pos_type pos) const
205 SpellChecker::Result result = SpellChecker::WORD_OK;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 FontSpan const & getRange(pos_type pos) const
218 /// empty span to indicate mismatch
219 static FontSpan empty_;
220 RangesIterator et = ranges_.end();
221 RangesIterator it = ranges_.begin();
222 for (; it != et; ++it) {
223 if(it->contains(pos)) {
230 bool needsRefresh() const
232 return needs_refresh_;
235 SpellChecker::ChangeNumber currentChangeNumber() const
237 return current_change_number_;
240 void refreshRange(pos_type & first, pos_type & last) const
242 first = refresh_.first;
243 last = refresh_.last;
246 void needsRefresh(pos_type pos)
248 if (needs_refresh_ && pos != -1) {
249 if (pos < refresh_.first)
250 refresh_.first = pos;
251 if (pos > refresh_.last)
253 } else if (pos != -1) {
254 // init request check for neighbour positions too
255 refresh_.first = pos > 0 ? pos - 1 : 0;
256 // no need for special end of paragraph check
257 refresh_.last = pos + 1;
259 needs_refresh_ = pos != -1;
262 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
264 needs_refresh_ = true;
267 current_change_number_ = change_number;
270 typedef vector<SpellResultRange> Ranges;
271 typedef Ranges::const_iterator RangesIterator;
273 /// the area of the paragraph with pending spell check
276 /// spell state cache version number
277 SpellChecker::ChangeNumber current_change_number_;
280 void correctRangesAfterPos(pos_type pos, int offset)
282 RangesIterator et = ranges_.end();
283 Ranges::iterator it = ranges_.begin();
284 for (; it != et; ++it) {
285 it->shift(pos, offset);
291 /////////////////////////////////////////////////////////////////////
293 // Paragraph::Private
295 /////////////////////////////////////////////////////////////////////
297 class Paragraph::Private
299 // Enforce our own "copy" constructor
300 Private(Private const &) = delete;
301 Private & operator=(Private const &) = delete;
302 // Unique ID generator
303 static int make_id();
306 Private(Paragraph * owner, Layout const & layout);
307 /// "Copy constructor"
308 Private(Private const &, Paragraph * owner);
309 /// Copy constructor from \p beg to \p end
310 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
313 void insertChar(pos_type pos, char_type c, Change const & change);
315 /// Output the surrogate pair formed by \p c and \p next to \p os.
316 /// \return the number of characters written.
317 int latexSurrogatePair(BufferParams const &, otexstream & os,
318 char_type c, char_type next,
319 OutputParams const &);
321 /// Output a space in appropriate formatting (or a surrogate pair
322 /// if the next character is a combining character).
323 /// \return whether a surrogate pair was output.
324 bool simpleTeXBlanks(BufferParams const &,
325 OutputParams const &,
328 unsigned int & column,
330 Layout const & style);
332 /// Output consecutive unicode chars, belonging to the same script as
333 /// specified by the latex macro \p ltx, to \p os starting from \p i.
334 /// \return the number of characters written.
335 int writeScriptChars(BufferParams const &, OutputParams const &,
337 docstring const & ltx,
338 Change const &, Encoding const &,
339 std::string const, pos_type & i);
341 /// This could go to ParagraphParameters if we want to.
342 int startTeXParParams(BufferParams const &, otexstream &,
343 OutputParams const &) const;
345 /// This could go to ParagraphParameters if we want to.
346 bool endTeXParParams(BufferParams const &, otexstream &,
347 OutputParams const &) const;
350 void latexInset(BufferParams const &,
355 Font const & outerfont,
357 Change & running_change,
358 Layout const & style,
360 unsigned int & column);
363 void latexSpecialChar(
365 BufferParams const & bparams,
366 OutputParams const & runparams,
367 Font const & running_font,
368 Change const & running_change,
369 Layout const & style,
372 unsigned int & column);
379 unsigned int & column);
385 unsigned int & column);
391 unsigned int & column);
394 void validate(LaTeXFeatures & features) const;
396 /// Checks if the paragraph contains only text and no inset or font change.
397 bool onlyText(Buffer const & buf, Font const & outerfont,
398 pos_type initial) const;
400 /// a vector of speller skip positions
401 typedef vector<FontSpan> SkipPositions;
402 typedef SkipPositions::const_iterator SkipPositionsIterator;
404 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
406 Language * getSpellLanguage(pos_type const from) const;
408 Language * locateSpellRange(pos_type & from, pos_type & to,
409 SkipPositions & skips) const;
411 bool hasSpellerChange() const
413 SpellChecker::ChangeNumber speller_change_number = 0;
414 if (theSpellChecker())
415 speller_change_number = theSpellChecker()->changeNumber();
416 return speller_change_number > speller_state_.currentChangeNumber();
419 bool ignoreWord(docstring const & word) const ;
421 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
423 pos_type textsize = owner_->size();
424 // check for sane arguments
425 if (to <= from || from >= textsize)
427 FontSpan fp = FontSpan(from, to - 1);
428 speller_state_.setRange(fp, state);
431 void requestSpellCheck(pos_type pos)
434 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
436 speller_state_.needsRefresh(pos);
439 void readySpellCheck()
441 speller_state_.needsRefresh(-1);
444 bool needsSpellCheck() const
446 return speller_state_.needsRefresh();
449 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
451 speller_state_.refreshRange(first, last);
453 last = owner_->size();
456 pos_type endpos = last;
457 owner_->locateWord(first, endpos, WHOLE_WORD);
460 owner_->locateWord(last, endpos, WHOLE_WORD);
465 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
469 while (it != et && it->first < start) {
470 int skip = it->last - it->first + 1;
478 void markMisspelledWords(pos_type const & first, pos_type const & last,
479 SpellChecker::Result result,
480 docstring const & word,
481 SkipPositions const & skips);
483 InsetCode ownerCode() const
485 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
488 /// Which Paragraph owns us?
492 Inset const * inset_owner_;
501 ParagraphParameters params_;
503 /// for recording and looking up changes
507 InsetList insetlist_;
510 pos_type begin_of_body_;
512 typedef docstring TextContainer;
516 typedef set<docstring> Words;
517 typedef map<string, Words> LangWordsMap;
521 Layout const * layout_;
523 SpellCheckerState speller_state_;
527 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
528 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
535 int Paragraph::Private::make_id()
537 // The id is unique per session across buffers because it is used in
538 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
541 static atomic_uint next_id(0);
546 Paragraph::Private::Private(Private const & p, Paragraph * owner)
547 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
549 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
550 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
553 requestSpellCheck(p.text_.size());
557 Paragraph::Private::Private(Private const & p, Paragraph * owner,
558 pos_type beg, pos_type end)
559 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
560 params_(p.params_), changes_(p.changes_),
561 insetlist_(p.insetlist_, beg, end),
562 begin_of_body_(p.begin_of_body_), words_(p.words_),
565 if (beg >= pos_type(p.text_.size()))
567 text_ = p.text_.substr(beg, end - beg);
569 FontList::const_iterator fcit = fontlist_.begin();
570 FontList::const_iterator fend = fontlist_.end();
571 for (; fcit != fend; ++fcit) {
572 if (fcit->pos() < beg)
574 if (fcit->pos() >= end) {
575 // Add last entry in the fontlist_.
576 fontlist_.set(text_.size() - 1, fcit->font());
579 // Add a new entry in the fontlist_.
580 fontlist_.set(fcit->pos() - beg, fcit->font());
582 requestSpellCheck(p.text_.size());
586 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
587 bool output_active, TocBackend & backend) const
589 d->changes_.addToToc(cdit, buf, output_active, backend);
593 void Paragraph::addChangesToBuffer(Buffer const & buf) const
595 d->changes_.updateBuffer(buf);
599 bool Paragraph::isChangeUpdateRequired() const
601 return d->changes_.isUpdateRequired();
605 bool Paragraph::isDeleted(pos_type start, pos_type end) const
607 LASSERT(start >= 0 && start <= size(), return false);
608 LASSERT(end > start && end <= size() + 1, return false);
610 return d->changes_.isDeleted(start, end);
614 bool Paragraph::isChanged(pos_type start, pos_type end) const
616 LASSERT(start >= 0 && start <= size(), return false);
617 LASSERT(end > start && end <= size() + 1, return false);
619 return d->changes_.isChanged(start, end);
623 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
625 // keep the logic here in sync with the logic of eraseChars()
629 Change const & change = d->changes_.lookup(size());
630 return change.inserted() && change.currentAuthor();
634 void Paragraph::setChange(Change const & change)
636 // beware of the imaginary end-of-par character!
637 d->changes_.set(change, 0, size() + 1);
640 * Propagate the change recursively - but not in case of DELETED!
642 * Imagine that your co-author makes changes in an existing inset. He
643 * sends your document to you and you come to the conclusion that the
644 * inset should go completely. If you erase it, LyX must not delete all
645 * text within the inset. Otherwise, the change tracked insertions of
646 * your co-author get lost and there is no way to restore them later.
648 * Conclusion: An inset's content should remain untouched if you delete it
651 if (!change.deleted()) {
652 for (pos_type pos = 0; pos < size(); ++pos) {
653 if (Inset * inset = getInset(pos))
654 inset->setChange(change);
660 void Paragraph::setChange(pos_type pos, Change const & change)
662 LASSERT(pos >= 0 && pos <= size(), return);
663 d->changes_.set(change, pos);
665 // see comment in setChange(Change const &) above
666 if (!change.deleted() && pos < size())
667 if (Inset * inset = getInset(pos))
668 inset->setChange(change);
672 Change const & Paragraph::lookupChange(pos_type pos) const
674 LBUFERR(pos >= 0 && pos <= size());
675 return d->changes_.lookup(pos);
679 void Paragraph::acceptChanges(pos_type start, pos_type end)
681 LASSERT(start >= 0 && start <= size(), return);
682 LASSERT(end > start && end <= size() + 1, return);
684 for (pos_type pos = start; pos < end; ++pos) {
685 switch (lookupChange(pos).type) {
686 case Change::UNCHANGED:
687 // accept changes in nested inset
688 if (Inset * inset = getInset(pos))
689 inset->acceptChanges();
692 case Change::INSERTED:
693 d->changes_.set(Change(Change::UNCHANGED), pos);
694 // also accept changes in nested inset
695 if (Inset * inset = getInset(pos))
696 inset->acceptChanges();
699 case Change::DELETED:
700 // Suppress access to non-existent
701 // "end-of-paragraph char"
703 eraseChar(pos, false);
714 void Paragraph::rejectChanges(pos_type start, pos_type end)
716 LASSERT(start >= 0 && start <= size(), return);
717 LASSERT(end > start && end <= size() + 1, return);
719 for (pos_type pos = start; pos < end; ++pos) {
720 switch (lookupChange(pos).type) {
721 case Change::UNCHANGED:
722 // reject changes in nested inset
723 if (Inset * inset = getInset(pos))
724 inset->rejectChanges();
727 case Change::INSERTED:
728 // Suppress access to non-existent
729 // "end-of-paragraph char"
731 eraseChar(pos, false);
737 case Change::DELETED:
738 d->changes_.set(Change(Change::UNCHANGED), pos);
740 // Do NOT reject changes within a deleted inset!
741 // There may be insertions of a co-author inside of it!
749 void Paragraph::Private::insertChar(pos_type pos, char_type c,
750 Change const & change)
752 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
755 changes_.insert(change, pos);
757 // This is actually very common when parsing buffers (and
758 // maybe inserting ascii text)
759 if (pos == pos_type(text_.size())) {
760 // when appending characters, no need to update tables
762 // but we want spell checking
763 requestSpellCheck(pos);
767 text_.insert(text_.begin() + pos, c);
769 // Update the font table.
770 fontlist_.increasePosAfterPos(pos);
773 insetlist_.increasePosAfterPos(pos);
775 // Update list of misspelled positions
776 speller_state_.increasePosAfterPos(pos);
780 bool Paragraph::insertInset(pos_type pos, Inset * inset,
781 Font const & font, Change const & change)
783 LASSERT(inset, return false);
784 LASSERT(pos >= 0 && pos <= size(), return false);
786 // Paragraph::insertInset() can be used in cut/copy/paste operation where
787 // d->inset_owner_ is not set yet.
788 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
791 d->insertChar(pos, META_INSET, change);
792 LASSERT(d->text_[pos] == META_INSET, return false);
794 // Add a new entry in the insetlist_.
795 d->insetlist_.insert(inset, pos);
797 // Some insets require run of spell checker
798 requestSpellCheck(pos);
804 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
806 LASSERT(pos >= 0 && pos <= size(), return false);
808 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
811 Change change = d->changes_.lookup(pos);
813 // set the character to DELETED if
814 // a) it was previously unchanged or
815 // b) it was inserted by a co-author
817 if (!change.changed() ||
818 (change.inserted() && !change.currentAuthor())) {
819 setChange(pos, Change(Change::DELETED));
820 // request run of spell checker
821 requestSpellCheck(pos);
825 if (change.deleted())
829 // Don't physically access the imaginary end-of-paragraph character.
830 // eraseChar() can only mark it as DELETED. A physical deletion of
831 // end-of-par must be handled externally.
837 d->changes_.erase(pos);
839 // if it is an inset, delete the inset entry
840 if (d->text_[pos] == META_INSET)
841 d->insetlist_.erase(pos);
843 d->text_.erase(d->text_.begin() + pos);
845 // Update the fontlist_
846 d->fontlist_.erase(pos);
848 // Update the insetlist_
849 d->insetlist_.decreasePosAfterPos(pos);
851 // Update list of misspelled positions
852 d->speller_state_.decreasePosAfterPos(pos);
853 d->speller_state_.refreshLast(size());
859 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
861 LASSERT(start >= 0 && start <= size(), return 0);
862 LASSERT(end >= start && end <= size() + 1, return 0);
865 for (pos_type count = end - start; count; --count) {
866 if (!eraseChar(i, trackChanges))
873 int Paragraph::Private::latexSurrogatePair(BufferParams const & bparams,
874 otexstream & os, char_type c, char_type next,
875 OutputParams const & runparams)
877 // Writing next here may circumvent a possible font change between
878 // c and next. Since next is only output if it forms a surrogate pair
879 // with c we can ignore this:
880 // A font change inside a surrogate pair does not make sense and is
881 // hopefully impossible to input.
882 // FIXME: change tracking
883 // Is this correct WRT change tracking?
884 Encoding const & encoding = *(runparams.encoding);
885 docstring latex1 = encoding.latexChar(next).first;
886 if (runparams.inIPA) {
887 string const tipashortcut = Encodings::TIPAShortcut(next);
888 if (!tipashortcut.empty()) {
889 latex1 = from_ascii(tipashortcut);
892 docstring latex2 = encoding.latexChar(c).first;
894 if (docstring(1, next) == latex1) {
895 // The encoding supports the combination:
896 // output as is (combining char after base char).
897 os << latex2 << latex1;
898 return latex1.length() + latex2.length();
901 // Handle combining characters in "script" context (i.e., \textgreek and \textcyrillic)
902 docstring::size_type const brace1 = latex2.find_first_of(from_ascii("{"));
903 docstring::size_type const brace2 = latex2.find_last_of(from_ascii("}"));
904 string script = to_ascii(latex2.substr(1, brace1 - 1));
905 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
906 // whether they are encodable or not (it only depends on the font encoding)
907 if (!runparams.isFullUnicode())
908 // This will get us a script value to deal with below
909 Encodings::isKnownScriptChar(c, script);
913 if (runparams.local_font)
914 fontenc = runparams.local_font->language()->fontenc(bparams);
916 fontenc = runparams.main_fontenc;
917 docstring scriptmacro;
919 if (script == "textgreek" || script == "textcyrillic") {
920 // We separate the script macro (\text[greek|cyr]) from the rest,
921 // since we need to include the combining char in it (#6463).
922 // This is "the rest":
925 latex2 = latex2.substr(pos, length);
926 // We only need the script macro with non-native font encodings
927 if (Encodings::needsScriptWrapper(script, fontenc)) {
928 scriptmacro = from_ascii("\\" + script + "{");
929 cb = from_ascii("}");
935 // polutonikogreek does not play nice with brackets
936 if (!runparams.local_font
937 || runparams.local_font->language()->lang() != "polutonikogreek") {
938 lb = from_ascii("{");
939 rb = from_ascii("}");
942 os << scriptmacro << latex1 << lb << latex2 << rb << cb;
943 return latex1.length() + latex2.length() + lb.length() + rb.length() + cb.length();
947 bool Paragraph::Private::simpleTeXBlanks(BufferParams const & bparams,
948 OutputParams const & runparams,
951 unsigned int & column,
953 Layout const & style)
955 if (style.pass_thru || runparams.pass_thru)
958 if (i + 1 < int(text_.size())) {
959 char_type next = text_[i + 1];
960 if (Encodings::isCombiningChar(next)) {
961 // This space has an accent, so we must always output it.
962 column += latexSurrogatePair(bparams, os, ' ', next, runparams) - 1;
967 if (runparams.linelen > 0
968 && column > runparams.linelen
970 && text_[i - 1] != ' '
971 && (i + 1 < int(text_.size()))
972 // same in FreeSpacing mode
973 && !owner_->isFreeSpacing()
974 // In typewriter mode, we want to avoid
975 // ! . ? : at the end of a line
976 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
977 && (text_[i - 1] == '.'
978 || text_[i - 1] == '?'
979 || text_[i - 1] == ':'
980 || text_[i - 1] == '!'))) {
982 os.texrow().start(owner_->id(), i + 1);
984 } else if (style.free_spacing) {
993 int Paragraph::Private::writeScriptChars(BufferParams const & bparams,
994 OutputParams const & runparams,
996 docstring const & ltx,
997 Change const & runningChange,
998 Encoding const & encoding,
999 string const fontenc,
1002 // FIXME: modifying i here is not very nice...
1004 // We only arrive here when character text_[i] could not be translated
1005 // into the current latex encoding (or its latex translation has been forced,)
1006 // and it belongs to a known script.
1007 // Parameter ltx contains the latex translation of text_[i] as specified
1008 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
1009 // The latex macro name "textXXX" specifies the script to which text_[i]
1010 // belongs and we use it in order to check whether characters from the
1011 // same script immediately follow, such that we can collect them in a
1012 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
1013 // for the first char but only "<spec>" for all subsequent chars.
1014 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
1015 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
1016 string script = to_ascii(ltx.substr(1, brace1 - 1));
1018 int length = brace2;
1019 bool closing_brace = true;
1020 if (!Encodings::needsScriptWrapper(script, fontenc)) {
1021 // Correct font encoding is being used, so we can avoid \text[greek|cyr].
1024 closing_brace = false;
1026 os << ltx.substr(pos, length);
1027 int size = text_.size();
1028 while (i + 1 < size) {
1029 char_type const next = text_[i + 1];
1030 // Stop here if next character belongs to another script
1031 // or there is a change in change tracking status.
1032 if (!Encodings::isKnownScriptChar(next, script) ||
1033 runningChange != owner_->lookupChange(i + 1))
1037 FontList::const_iterator cit = fontlist_.begin();
1038 FontList::const_iterator end = fontlist_.end();
1039 for (; cit != end; ++cit) {
1040 if (cit->pos() >= i && !found) {
1041 prev_font = cit->font();
1044 if (cit->pos() >= i + 1)
1047 // Stop here if there is a font attribute or encoding change.
1048 if (found && cit != end && prev_font != cit->font())
1051 // Check whether we have a combining pair
1052 char_type next_next = '\0';
1054 next_next = text_[i + 2];
1055 if (Encodings::isCombiningChar(next_next)) {
1056 length += latexSurrogatePair(bparams, os, next, next_next, runparams) - 1;
1062 docstring const latex = encoding.latexChar(next).first;
1063 docstring::size_type const b1 =
1064 latex.find_first_of(from_ascii("{"));
1065 docstring::size_type const b2 =
1066 latex.find_last_of(from_ascii("}"));
1067 int const len = b2 - b1 - 1;
1068 os << latex.substr(b1 + 1, len);
1072 if (closing_brace) {
1080 void Paragraph::Private::latexInset(BufferParams const & bparams,
1082 OutputParams & runparams,
1083 Font & running_font,
1085 Font const & outerfont,
1087 Change & running_change,
1088 Layout const & style,
1090 unsigned int & column)
1092 Inset * inset = owner_->getInset(i);
1095 if (style.pass_thru) {
1096 odocstringstream ods;
1097 inset->plaintext(ods, runparams);
1102 // FIXME: move this to InsetNewline::latex
1103 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1104 // newlines are handled differently here than
1105 // the default in simpleTeXSpecialChars().
1106 if (!style.newline_allowed) {
1110 bool needPar = false;
1111 column += running_font.latexWriteEndChanges(
1112 os, bparams, runparams,
1113 basefont, basefont, needPar);
1117 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1120 basefont = owner_->getLayoutFont(bparams, outerfont);
1121 running_font = basefont;
1123 if (runparams.moving_arg)
1127 os.texrow().start(owner_->id(), i + 1);
1131 if (owner_->isDeleted(i)) {
1132 if( ++runparams.inDeletedInset == 1)
1133 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1136 if (inset->canTrackChanges()) {
1137 column += Changes::latexMarkChange(os, bparams, running_change,
1138 Change(Change::UNCHANGED), runparams);
1139 running_change = Change(Change::UNCHANGED);
1143 odocstream::pos_type const len = os.os().tellp();
1145 if (inset->forceLTR()
1146 && !runparams.use_polyglossia
1147 && running_font.isRightToLeft()
1148 // ERT is an exception, it should be output with no
1149 // decorations at all
1150 && inset->lyxCode() != ERT_CODE) {
1151 if (running_font.language()->lang() == "farsi")
1152 os << "\\beginL" << termcmd;
1158 // FIXME: Bug: we can have an empty font change here!
1159 // if there has just been a font change, we are going to close it
1160 // right now, which means stupid latex code like \textsf{}. AFAIK,
1161 // this does not harm dvi output. A minor bug, thus (JMarc)
1163 // Some insets cannot be inside a font change command.
1164 // However, even such insets *can* be placed in \L or \R
1165 // or their equivalents (for RTL language switches), so we don't
1166 // close the language in those cases.
1167 // ArabTeX, though, cannot handle this special behavior, it seems.
1168 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1169 || running_font.language()->lang() == "arabic_arabtex";
1170 if (open_font && !inset->inheritFont()) {
1171 bool needPar = false;
1172 bool closeLanguage = arabtex
1173 || basefont.isRightToLeft() == running_font.isRightToLeft();
1174 unsigned int count = running_font.latexWriteEndChanges(os,
1175 bparams, runparams, basefont, basefont,
1176 needPar, closeLanguage);
1178 // if any font properties were closed, update the running_font,
1179 // making sure, however, to leave the language as it was
1181 // FIXME: probably a better way to keep track of the old
1182 // language, than copying the entire font?
1183 Font const copy_font(running_font);
1184 basefont = owner_->getLayoutFont(bparams, outerfont);
1185 running_font = basefont;
1187 running_font.setLanguage(copy_font.language());
1188 // leave font open if language is still open
1189 open_font = (running_font.language() == basefont.language());
1191 runparams.local_font = &basefont;
1195 size_t const previous_row_count = os.texrow().rows();
1198 runparams.lastid = id_;
1199 runparams.lastpos = i;
1200 inset->latex(os, runparams);
1201 } catch (EncodingException & e) {
1202 // add location information and throw again.
1209 if (running_font.language()->lang() == "farsi")
1210 os << "\\endL" << termcmd;
1215 if (os.texrow().rows() > previous_row_count) {
1216 os.texrow().start(owner_->id(), i + 1);
1219 column += (unsigned int)(os.os().tellp() - len);
1222 if (owner_->isDeleted(i))
1223 --runparams.inDeletedInset;
1227 void Paragraph::Private::latexSpecialChar(otexstream & os,
1228 BufferParams const & bparams,
1229 OutputParams const & runparams,
1230 Font const & running_font,
1231 Change const & running_change,
1232 Layout const & style,
1235 unsigned int & column)
1237 // With polyglossia, brackets and stuff need not be reversed
1238 // in RTL scripts (see bug #8251)
1239 char_type const c = (runparams.use_polyglossia) ?
1240 owner_->getUChar(bparams, i) : text_[i];
1242 if (style.pass_thru || runparams.pass_thru
1243 || contains(style.pass_thru_chars, c)
1244 || contains(runparams.pass_thru_chars, c)) {
1246 Encoding const * const enc = runparams.encoding;
1247 if (enc && !enc->encodable(c))
1248 throw EncodingException(c);
1254 // TIPA uses its own T3 encoding
1255 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1257 // If T1 font encoding is used, use the special
1258 // characters it provides.
1259 // NOTE: Some languages reset the font encoding internally to a
1260 // non-standard font encoding. If we are using such a language,
1261 // we do not output special T1 chars.
1262 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1263 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1264 && latexSpecialT1(c, os, i, column))
1266 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1267 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1268 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1271 // Otherwise, we use what LaTeX provides us.
1274 os << "\\textbackslash" << termcmd;
1278 os << "\\textless" << termcmd;
1282 os << "\\textgreater" << termcmd;
1286 os << "\\textbar" << termcmd;
1291 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1292 (end_pos == -1 || i + 1 < end_pos) &&
1293 text_[i+1] == '-') {
1294 // Prevent "--" becoming an en dash and "---" an em dash.
1295 // (Within \ttfamily, "---" is merged to en dash + hyphen.)
1301 os << "\\textquotedbl" << termcmd;
1306 case '%': case '#': case '{':
1314 os << "\\textasciitilde" << termcmd;
1319 os << "\\textasciicircum" << termcmd;
1326 // avoid being mistaken for optional arguments
1334 // Blanks are printed before font switching.
1335 // Sure? I am not! (try nice-latex)
1336 // I am sure it's correct. LyX might be smarter
1337 // in the future, but for now, nothing wrong is
1343 // XeTeX's dash behaviour is determined via a global setting
1344 if (bparams.use_dash_ligatures
1345 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1347 // TODO #10961: && not in inset Flex Code
1348 // TODO #10961: && not in layout LyXCode
1349 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1366 Encoding const & encoding = *(runparams.encoding);
1367 char_type next = '\0';
1368 if (i + 1 < int(text_.size())) {
1369 next = text_[i + 1];
1370 if (Encodings::isCombiningChar(next)) {
1371 column += latexSurrogatePair(bparams, os, c, next, runparams) - 1;
1377 pair<docstring, bool> latex = encoding.latexChar(c);
1378 docstring nextlatex;
1379 bool nexttipas = false;
1380 string nexttipashortcut;
1381 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1382 nextlatex = encoding.latexChar(next).first;
1383 if (runparams.inIPA) {
1384 nexttipashortcut = Encodings::TIPAShortcut(next);
1385 nexttipas = !nexttipashortcut.empty();
1389 if (runparams.inIPA) {
1390 string const tipashortcut = Encodings::TIPAShortcut(c);
1391 if (!tipashortcut.empty()) {
1392 latex.first = from_ascii(tipashortcut);
1393 latex.second = false;
1398 if (running_font.language()->lang() == bparams.language->lang())
1399 fontenc = runparams.main_fontenc;
1401 fontenc = running_font.language()->fontenc(bparams);
1402 // "Script chars" need to embraced in \textcyrillic and \textgreek notwithstanding
1403 // whether they are encodable or not (it only depends on the font encoding)
1404 if (!runparams.isFullUnicode() && Encodings::isKnownScriptChar(c, script)) {
1405 docstring const wrapper = from_ascii("\\" + script + "{");
1406 docstring ltx = latex.first;
1407 if (!prefixIs(ltx, wrapper))
1408 ltx = wrapper + latex.first + from_ascii("}");
1409 column += writeScriptChars(bparams, runparams, os, ltx, running_change,
1410 encoding, fontenc, i) - 1;
1411 } else if (latex.second
1412 && ((!prefixIs(nextlatex, '\\')
1413 && !prefixIs(nextlatex, '{')
1414 && !prefixIs(nextlatex, '}'))
1416 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1418 // Prevent eating of a following
1419 // space or command corruption by
1420 // following characters
1421 if (next == ' ' || next == '\0') {
1422 column += latex.first.length() + 1;
1423 os << latex.first << "{}";
1425 column += latex.first.length();
1426 os << latex.first << " ";
1429 column += latex.first.length() - 1;
1437 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1438 pos_type i, unsigned int & column)
1444 // In T1 encoding, these characters exist
1445 // but we should avoid ligatures
1446 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1448 os << "\\textcompwordmark" << termcmd;
1455 // soul.sty breaks with \char`\"
1456 os << "\\textquotedbl" << termcmd;
1465 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1466 pos_type i, unsigned int & column)
1468 // TU encoding is currently on par with T1.
1469 return latexSpecialT1(c, os, i, column);
1473 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1474 pos_type /*i*/, unsigned int & column)
1484 os << "\\textvertline" << termcmd;
1493 void Paragraph::Private::validate(LaTeXFeatures & features) const
1495 if (layout_->inpreamble && inset_owner_) {
1496 // FIXME: Using a string stream here circumvents the encoding
1497 // switching machinery of odocstream. Therefore the
1498 // output is wrong if this paragraph contains content
1499 // that needs to switch encoding.
1500 Buffer const & buf = inset_owner_->buffer();
1501 otexstringstream os;
1502 os << layout_->preamble();
1503 size_t const length = os.length();
1504 TeXOnePar(buf, buf.text(), buf.getParFromID(owner_->id()).pit(), os,
1505 features.runparams(), string(), 0, -1, true);
1506 if (os.length() > length)
1507 features.addPreambleSnippet(os.release(), true);
1510 if (features.runparams().flavor == OutputParams::HTML
1511 && layout_->htmltitle()) {
1512 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1515 // check the params.
1516 if (!params_.spacing().isDefault())
1517 features.require("setspace");
1520 features.useLayout(layout_->name());
1523 fontlist_.validate(features);
1525 // then the indentation
1526 if (!params_.leftIndent().zero())
1527 features.require("ParagraphLeftIndent");
1530 InsetList::const_iterator icit = insetlist_.begin();
1531 InsetList::const_iterator iend = insetlist_.end();
1532 for (; icit != iend; ++icit) {
1534 features.inDeletedInset(owner_->isDeleted(icit->pos));
1535 if (icit->inset->lyxCode() == FOOT_CODE) {
1536 // FIXME: an item inset would make things much easier.
1537 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1538 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1539 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1540 && (icit->pos < begin_of_body_
1541 || (icit->pos == begin_of_body_
1542 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1543 features.saveNoteEnv("description");
1545 icit->inset->validate(features);
1546 features.inDeletedInset(false);
1547 if (layout_->needprotect &&
1548 icit->inset->lyxCode() == FOOT_CODE)
1549 features.require("NeedLyXFootnoteCode");
1553 // then the contents
1554 BufferParams const bp = features.runparams().is_child
1555 ? features.buffer().masterParams() : features.buffer().params();
1556 string bscript = "textbaltic";
1557 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1558 char_type c = text_[i];
1560 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1561 features.require("textquotedblp");
1562 else if (bp.main_font_encoding() != "T1"
1563 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1564 features.require("textquotedbl");
1565 } else if (Encodings::isKnownScriptChar(c, bscript)){
1566 string fontenc = (&owner_->getFontSettings(bp, i))->language()->fontenc(bp);
1567 if (fontenc.empty())
1568 fontenc = features.runparams().main_fontenc;
1569 if (Encodings::needsScriptWrapper("textbaltic", fontenc))
1570 features.require("textbalticdefs");
1571 } else if (!bp.use_dash_ligatures
1572 && (c == 0x2013 || c == 0x2014)
1573 && bp.useNonTeXFonts
1574 && features.runparams().flavor == OutputParams::XETEX)
1575 // XeTeX's dash behaviour is determined via a global setting
1576 features.require("xetexdashbreakstate");
1577 BufferEncodings::validate(c, features);
1581 /////////////////////////////////////////////////////////////////////
1585 /////////////////////////////////////////////////////////////////////
1588 Layout const emptyParagraphLayout;
1591 Paragraph::Paragraph()
1592 : d(new Paragraph::Private(this, emptyParagraphLayout))
1599 Paragraph::Paragraph(Paragraph const & par)
1600 : itemdepth(par.itemdepth),
1601 d(new Paragraph::Private(*par.d, this))
1607 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1608 : itemdepth(par.itemdepth),
1609 d(new Paragraph::Private(*par.d, this, beg, end))
1615 Paragraph & Paragraph::operator=(Paragraph const & par)
1617 // needed as we will destroy the private part before copying it
1619 itemdepth = par.itemdepth;
1623 d = new Private(*par.d, this);
1630 Paragraph::~Paragraph()
1639 // this shall be called just before every "os << ..." action.
1640 void flushString(ostream & os, docstring & s)
1649 void Paragraph::write(ostream & os, BufferParams const & bparams,
1650 depth_type & dth) const
1652 // The beginning or end of a deeper (i.e. nested) area?
1653 if (dth != d->params_.depth()) {
1654 if (d->params_.depth() > dth) {
1655 while (d->params_.depth() > dth) {
1656 os << "\n\\begin_deeper";
1660 while (d->params_.depth() < dth) {
1661 os << "\n\\end_deeper";
1667 // First write the layout
1668 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1670 d->params_.write(os);
1672 Font font1(inherit_font, bparams.language);
1674 Change running_change = Change(Change::UNCHANGED);
1676 // this string is used as a buffer to avoid repetitive calls
1677 // to to_utf8(), which turn out to be expensive (JMarc)
1678 docstring write_buffer;
1681 for (pos_type i = 0; i <= size(); ++i) {
1683 Change const & change = lookupChange(i);
1684 if (change != running_change)
1685 flushString(os, write_buffer);
1686 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1687 running_change = change;
1692 // Write font changes
1693 Font font2 = getFontSettings(bparams, i);
1694 if (font2 != font1) {
1695 flushString(os, write_buffer);
1696 font2.lyxWriteChanges(font1, os);
1701 char_type const c = d->text_[i];
1704 if (Inset const * inset = getInset(i)) {
1705 flushString(os, write_buffer);
1706 if (inset->directWrite()) {
1707 // international char, let it write
1708 // code directly so it's shorter in
1714 os << "\\begin_inset ";
1716 os << "\n\\end_inset\n\n";
1719 // FIXME This can be removed again once the mystery
1720 // crash has been resolved.
1725 flushString(os, write_buffer);
1726 os << "\n\\backslash\n";
1730 flushString(os, write_buffer);
1731 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1738 if ((column > 70 && c == ' ')
1740 flushString(os, write_buffer);
1744 // this check is to amend a bug. LyX sometimes
1745 // inserts '\0' this could cause problems.
1747 write_buffer.push_back(c);
1749 LYXERR0("NUL char in structure.");
1755 flushString(os, write_buffer);
1756 os << "\n\\end_layout\n";
1757 // FIXME This can be removed again once the mystery
1758 // crash has been resolved.
1763 void Paragraph::validate(LaTeXFeatures & features) const
1765 d->validate(features);
1766 if (needsCProtection())
1767 features.require("cprotect");
1771 void Paragraph::insert(pos_type start, docstring const & str,
1772 Font const & font, Change const & change)
1774 for (size_t i = 0, n = str.size(); i != n ; ++i)
1775 insertChar(start + i, str[i], font, change);
1779 void Paragraph::appendChar(char_type c, Font const & font,
1780 Change const & change)
1783 d->changes_.insert(change, d->text_.size());
1784 // when appending characters, no need to update tables
1785 d->text_.push_back(c);
1786 setFont(d->text_.size() - 1, font);
1787 d->requestSpellCheck(d->text_.size() - 1);
1791 void Paragraph::appendString(docstring const & s, Font const & font,
1792 Change const & change)
1794 pos_type end = s.size();
1795 size_t oldsize = d->text_.size();
1796 size_t newsize = oldsize + end;
1797 size_t capacity = d->text_.capacity();
1798 if (newsize >= capacity)
1799 d->text_.reserve(max(capacity + 100, newsize));
1801 // when appending characters, no need to update tables
1804 // FIXME: Optimize this!
1805 for (size_t i = oldsize; i != newsize; ++i) {
1807 d->changes_.insert(change, i);
1808 d->requestSpellCheck(i);
1810 d->fontlist_.set(oldsize, font);
1811 d->fontlist_.set(newsize - 1, font);
1815 void Paragraph::insertChar(pos_type pos, char_type c,
1818 d->insertChar(pos, c, Change(trackChanges ?
1819 Change::INSERTED : Change::UNCHANGED));
1823 void Paragraph::insertChar(pos_type pos, char_type c,
1824 Font const & font, bool trackChanges)
1826 d->insertChar(pos, c, Change(trackChanges ?
1827 Change::INSERTED : Change::UNCHANGED));
1832 void Paragraph::insertChar(pos_type pos, char_type c,
1833 Font const & font, Change const & change)
1835 d->insertChar(pos, c, change);
1840 void Paragraph::resetFonts(Font const & font)
1842 d->fontlist_.clear();
1843 d->fontlist_.set(0, font);
1844 d->fontlist_.set(d->text_.size() - 1, font);
1847 // Gets uninstantiated font setting at position.
1848 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1852 LYXERR0("pos: " << pos << " size: " << size());
1856 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1857 if (cit != d->fontlist_.end())
1860 if (pos == size() && !empty())
1861 return getFontSettings(bparams, pos - 1);
1863 // Optimisation: avoid a full font instantiation if there is no
1864 // language change from previous call.
1865 static Font previous_font;
1866 static Language const * previous_lang = 0;
1867 Language const * lang = getParLanguage(bparams);
1868 if (lang != previous_lang) {
1869 previous_lang = lang;
1870 previous_font = Font(inherit_font, lang);
1872 return previous_font;
1876 FontSpan Paragraph::fontSpan(pos_type pos) const
1878 LBUFERR(pos <= size());
1881 return FontSpan(pos, pos);
1884 FontList::const_iterator cit = d->fontlist_.begin();
1885 FontList::const_iterator end = d->fontlist_.end();
1886 for (; cit != end; ++cit) {
1887 if (cit->pos() >= pos) {
1888 if (pos >= beginOfBody())
1889 return FontSpan(max(start, beginOfBody()),
1892 return FontSpan(start,
1893 min(beginOfBody() - 1,
1896 start = cit->pos() + 1;
1899 // This should not happen, but if so, we take no chances.
1900 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1901 LASSERT(false, return FontSpan(pos, pos));
1905 // Gets uninstantiated font setting at position 0
1906 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1908 if (!empty() && !d->fontlist_.empty())
1909 return d->fontlist_.begin()->font();
1911 // Optimisation: avoid a full font instantiation if there is no
1912 // language change from previous call.
1913 static Font previous_font;
1914 static Language const * previous_lang = 0;
1915 if (bparams.language != previous_lang) {
1916 previous_lang = bparams.language;
1917 previous_font = Font(inherit_font, bparams.language);
1920 return previous_font;
1924 // Gets the fully instantiated font at a given position in a paragraph
1925 // This is basically the same function as Text::GetFont() in text2.cpp.
1926 // The difference is that this one is used for generating the LaTeX file,
1927 // and thus cosmetic "improvements" are disallowed: This has to deliver
1928 // the true picture of the buffer. (Asger)
1929 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1930 Font const & outerfont) const
1934 Font font = getFontSettings(bparams, pos);
1936 pos_type const body_pos = beginOfBody();
1937 FontInfo & fi = font.fontInfo();
1939 fi.realize(d->layout_->labelfont);
1941 fi.realize(d->layout_->font);
1943 fi.realize(outerfont.fontInfo());
1944 fi.realize(bparams.getFont().fontInfo());
1950 Font const Paragraph::getLabelFont
1951 (BufferParams const & bparams, Font const & outerfont) const
1953 FontInfo tmpfont = d->layout_->labelfont;
1954 tmpfont.realize(outerfont.fontInfo());
1955 tmpfont.realize(bparams.getFont().fontInfo());
1956 return Font(tmpfont, getParLanguage(bparams));
1960 Font const Paragraph::getLayoutFont
1961 (BufferParams const & bparams, Font const & outerfont) const
1963 FontInfo tmpfont = d->layout_->font;
1964 tmpfont.realize(outerfont.fontInfo());
1965 tmpfont.realize(bparams.getFont().fontInfo());
1966 return Font(tmpfont, getParLanguage(bparams));
1970 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1972 char_type c = d->text_[pos];
1973 if (!getFontSettings(bparams, pos).isRightToLeft())
1976 // FIXME: The arabic special casing is due to the difference of arabic
1977 // round brackets input introduced in r18599. Check if this should be
1978 // unified with Hebrew or at least if all bracket types should be
1979 // handled the same (file format change in either case).
1980 string const & lang = getFontSettings(bparams, pos).language()->lang();
1981 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1986 uc = arabic ? c : ')';
1989 uc = arabic ? c : '(';
2015 void Paragraph::setFont(pos_type pos, Font const & font)
2017 LASSERT(pos <= size(), return);
2019 // First, reduce font against layout/label font
2020 // Update: The setCharFont() routine in text2.cpp already
2021 // reduces font, so we don't need to do that here. (Asger)
2023 d->fontlist_.set(pos, font);
2027 void Paragraph::makeSameLayout(Paragraph const & par)
2029 d->layout_ = par.d->layout_;
2030 d->params_ = par.d->params_;
2034 bool Paragraph::stripLeadingSpaces(bool trackChanges)
2036 if (isFreeSpacing())
2042 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2043 if (eraseChar(pos, trackChanges))
2049 return count > 0 || pos > 0;
2053 bool Paragraph::hasSameLayout(Paragraph const & par) const
2055 return par.d->layout_ == d->layout_
2056 && d->params_.sameLayout(par.d->params_);
2060 depth_type Paragraph::getDepth() const
2062 return d->params_.depth();
2066 depth_type Paragraph::getMaxDepthAfter() const
2068 if (d->layout_->isEnvironment())
2069 return d->params_.depth() + 1;
2071 return d->params_.depth();
2075 LyXAlignment Paragraph::getAlign() const
2077 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2078 return d->layout_->align;
2080 return d->params_.align();
2084 docstring const & Paragraph::labelString() const
2086 return d->params_.labelString();
2090 // the next two functions are for the manual labels
2091 docstring const Paragraph::getLabelWidthString() const
2093 if (d->layout_->margintype == MARGIN_MANUAL
2094 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2095 return d->params_.labelWidthString();
2097 return _("Senseless with this layout!");
2101 void Paragraph::setLabelWidthString(docstring const & s)
2103 d->params_.labelWidthString(s);
2107 docstring Paragraph::expandLabel(Layout const & layout,
2108 BufferParams const & bparams) const
2110 return expandParagraphLabel(layout, bparams, true);
2114 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2115 BufferParams const & bparams) const
2117 return expandParagraphLabel(layout, bparams, false);
2121 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2122 BufferParams const & bparams, bool process_appendix) const
2124 DocumentClass const & tclass = bparams.documentClass();
2125 string const & lang = getParLanguage(bparams)->code();
2126 bool const in_appendix = process_appendix && d->params_.appendix();
2127 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2129 if (fmt.empty() && !layout.counter.empty())
2130 return tclass.counters().theCounter(layout.counter, lang);
2132 // handle 'inherited level parts' in 'fmt',
2133 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2134 size_t const i = fmt.find('@', 0);
2135 if (i != docstring::npos) {
2136 size_t const j = fmt.find('@', i + 1);
2137 if (j != docstring::npos) {
2138 docstring parent(fmt, i + 1, j - i - 1);
2139 docstring label = from_ascii("??");
2140 if (tclass.hasLayout(parent))
2141 label = expandParagraphLabel(tclass[parent], bparams,
2143 fmt = docstring(fmt, 0, i) + label
2144 + docstring(fmt, j + 1, docstring::npos);
2148 return tclass.counters().counterLabel(fmt, lang);
2152 void Paragraph::applyLayout(Layout const & new_layout)
2154 d->layout_ = &new_layout;
2155 LyXAlignment const oldAlign = d->params_.align();
2157 if (!(oldAlign & d->layout_->alignpossible)) {
2158 frontend::Alert::warning(_("Alignment not permitted"),
2159 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2160 d->params_.align(LYX_ALIGN_LAYOUT);
2165 pos_type Paragraph::beginOfBody() const
2167 return d->begin_of_body_;
2171 void Paragraph::setBeginOfBody()
2173 if (d->layout_->labeltype != LABEL_MANUAL) {
2174 d->begin_of_body_ = 0;
2178 // Unroll the first two cycles of the loop
2179 // and remember the previous character to
2180 // remove unnecessary getChar() calls
2182 pos_type end = size();
2183 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2186 char_type previous_char = d->text_[i];
2187 if (!(isNewline(i) || isEnvSeparator(i))) {
2189 while (i < end && previous_char != ' ') {
2190 char_type temp = d->text_[i];
2191 if (isNewline(i) || isEnvSeparator(i))
2194 previous_char = temp;
2200 d->begin_of_body_ = i;
2204 bool Paragraph::allowParagraphCustomization() const
2206 return inInset().allowParagraphCustomization();
2210 bool Paragraph::usePlainLayout() const
2212 return inInset().usePlainLayout();
2216 bool Paragraph::isPassThru() const
2218 return inInset().isPassThru() || d->layout_->pass_thru;
2223 // paragraphs inside floats need different alignment tags to avoid
2226 bool noTrivlistCentering(InsetCode code)
2228 return code == FLOAT_CODE
2229 || code == WRAP_CODE
2230 || code == CELL_CODE;
2234 string correction(string const & orig)
2236 if (orig == "flushleft")
2237 return "raggedright";
2238 if (orig == "flushright")
2239 return "raggedleft";
2240 if (orig == "center")
2246 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2247 InsetCode code, bool const lastpar, int & col)
2249 string macro = suffix + "{";
2250 if (noTrivlistCentering(code)) {
2252 // the last paragraph in non-trivlist-aligned
2253 // context is special (to avoid unwanted whitespace)
2254 if (suffix == "\\begin") {
2255 macro = "\\" + correction(env) + "{}";
2256 os << from_ascii(macro);
2257 col += macro.size();
2262 macro += correction(env);
2266 if (suffix == "\\par\\end") {
2270 os << from_ascii(macro);
2271 col += macro.size();
2272 if (suffix == "\\begin") {
2282 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2283 otexstream & os, OutputParams const & runparams) const
2288 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2289 (layout_->toggle_indent != ITOGGLE_NEVER) :
2290 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2292 if (canindent && params_.noindent() && !layout_->pass_thru) {
2293 os << "\\noindent ";
2297 LyXAlignment const curAlign = params_.align();
2299 if (curAlign == layout_->align)
2303 case LYX_ALIGN_NONE:
2304 case LYX_ALIGN_BLOCK:
2305 case LYX_ALIGN_LAYOUT:
2306 case LYX_ALIGN_SPECIAL:
2307 case LYX_ALIGN_DECIMAL:
2309 case LYX_ALIGN_LEFT:
2310 case LYX_ALIGN_RIGHT:
2311 case LYX_ALIGN_CENTER:
2312 if (runparams.moving_arg) {
2319 string const begin_tag = "\\begin";
2320 InsetCode code = ownerCode();
2321 bool const lastpar = runparams.isLastPar;
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 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2332 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2334 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2336 } case LYX_ALIGN_RIGHT: {
2337 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2338 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2340 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2342 } case LYX_ALIGN_CENTER: {
2343 corrected_env(os, begin_tag, "center", code, lastpar, column);
2352 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2353 otexstream & os, OutputParams const & runparams) const
2355 LyXAlignment const curAlign = params_.align();
2357 if (curAlign == layout_->align)
2361 case LYX_ALIGN_NONE:
2362 case LYX_ALIGN_BLOCK:
2363 case LYX_ALIGN_LAYOUT:
2364 case LYX_ALIGN_SPECIAL:
2365 case LYX_ALIGN_DECIMAL:
2367 case LYX_ALIGN_LEFT:
2368 case LYX_ALIGN_RIGHT:
2369 case LYX_ALIGN_CENTER:
2370 if (runparams.moving_arg)
2375 bool output = false;
2377 string const end_tag = "\\par\\end";
2378 InsetCode code = ownerCode();
2379 bool const lastpar = runparams.isLastPar;
2382 case LYX_ALIGN_NONE:
2383 case LYX_ALIGN_BLOCK:
2384 case LYX_ALIGN_LAYOUT:
2385 case LYX_ALIGN_SPECIAL:
2386 case LYX_ALIGN_DECIMAL:
2388 case LYX_ALIGN_LEFT: {
2389 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2390 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2392 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2394 } case LYX_ALIGN_RIGHT: {
2395 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2396 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2398 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2400 } case LYX_ALIGN_CENTER: {
2401 corrected_env(os, end_tag, "center", code, lastpar, col);
2406 return output || lastpar;
2410 // This one spits out the text of the paragraph
2411 void Paragraph::latex(BufferParams const & bparams,
2412 Font const & outerfont,
2414 OutputParams const & runparams,
2415 int start_pos, int end_pos, bool force) const
2417 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2419 // FIXME This check should not be needed. Perhaps issue an
2420 // error if it triggers.
2421 Layout const & style = inInset().forcePlainLayout() ?
2422 bparams.documentClass().plainLayout() : *d->layout_;
2424 if (!force && style.inpreamble)
2427 bool const allowcust = allowParagraphCustomization();
2429 // Current base font for all inherited font changes, without any
2430 // change caused by an individual character, except for the language:
2431 // It is set to the language of the first character.
2432 // As long as we are in the label, this font is the base font of the
2433 // label. Before the first body character it is set to the base font
2437 // Maybe we have to create a optional argument.
2438 pos_type body_pos = beginOfBody();
2439 unsigned int column = 0;
2442 // the optional argument is kept in curly brackets in
2443 // case it contains a ']'
2444 // This is not strictly needed, but if this is changed it
2445 // would be a file format change, and tex2lyx would need
2446 // to be adjusted, since it unconditionally removes the
2447 // braces when it parses \item.
2450 basefont = getLabelFont(bparams, outerfont);
2452 basefont = getLayoutFont(bparams, outerfont);
2455 // Which font is currently active?
2456 Font running_font(basefont);
2457 // Do we have an open font change?
2458 bool open_font = false;
2460 Change runningChange = Change(Change::UNCHANGED);
2462 Encoding const * const prev_encoding = runparams.encoding;
2464 os.texrow().start(id(), 0);
2466 // if the paragraph is empty, the loop will not be entered at all
2468 // For InTitle commands, we have already opened a group
2469 // in output_latex::TeXOnePar.
2470 if (style.isCommand() && !style.intitle) {
2474 if (!style.leftdelim().empty()) {
2475 os << style.leftdelim();
2476 column += style.leftdelim().size();
2479 column += d->startTeXParParams(bparams, os, runparams);
2482 // Whether a \par can be issued for insets typeset inline with text.
2483 // Yes if greater than 0. This has to be static.
2484 THREAD_LOCAL_STATIC int parInline = 0;
2486 for (pos_type i = 0; i < size(); ++i) {
2487 // First char in paragraph or after label?
2488 if (i == body_pos) {
2491 bool needPar = false;
2492 column += running_font.latexWriteEndChanges(
2493 os, bparams, runparams,
2494 basefont, basefont, needPar);
2497 basefont = getLayoutFont(bparams, outerfont);
2498 running_font = basefont;
2500 column += Changes::latexMarkChange(os, bparams,
2501 runningChange, Change(Change::UNCHANGED),
2503 runningChange = Change(Change::UNCHANGED);
2508 // For InTitle commands, we have already opened a group
2509 // in output_latex::TeXOnePar.
2510 if (style.isCommand() && !style.intitle) {
2515 if (!style.leftdelim().empty()) {
2516 os << style.leftdelim();
2517 column += style.leftdelim().size();
2521 column += d->startTeXParParams(bparams, os,
2525 runparams.wasDisplayMath = runparams.inDisplayMath;
2526 runparams.inDisplayMath = false;
2527 bool deleted_display_math = false;
2528 Change const & change = runparams.inDeletedInset
2529 ? runparams.changeOfDeletedInset : lookupChange(i);
2531 // Check whether a display math inset follows
2532 if (d->text_[i] == META_INSET
2533 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2534 InsetMath const * im = getInset(i)->asInsetMath();
2535 if (im && im->asHullInset()
2536 && im->asHullInset()->outerDisplay()) {
2537 runparams.inDisplayMath = true;
2538 // runparams.inDeletedInset will be set by
2539 // latexInset later, but we need this info
2540 // before it is called. On the other hand, we
2541 // cannot set it here because it is a counter.
2542 deleted_display_math = isDeleted(i);
2544 if (bparams.output_changes && deleted_display_math
2545 && runningChange == change
2546 && change.type == Change::DELETED
2547 && !os.afterParbreak()) {
2548 // A display math in the same paragraph follows.
2549 // We have to close and then reopen \lyxdeleted,
2550 // otherwise the math will be shifted up.
2551 OutputParams rp = runparams;
2553 bool needPar = false;
2554 column += running_font.latexWriteEndChanges(
2555 os, bparams, rp, basefont,
2559 basefont = getLayoutFont(bparams, outerfont);
2560 running_font = basefont;
2561 column += Changes::latexMarkChange(os, bparams,
2562 Change(Change::INSERTED), change, rp);
2566 if (bparams.output_changes && runningChange != change) {
2568 bool needPar = false;
2569 column += running_font.latexWriteEndChanges(
2570 os, bparams, runparams,
2571 basefont, basefont, needPar);
2574 basefont = getLayoutFont(bparams, outerfont);
2575 running_font = basefont;
2576 column += Changes::latexMarkChange(os, bparams, runningChange,
2578 runningChange = change;
2581 // do not output text which is marked deleted
2582 // if change tracking output is disabled
2583 if (!bparams.output_changes && change.deleted()) {
2589 // Fully instantiated font
2590 Font const current_font = getFont(bparams, i, outerfont);
2592 Font const last_font = running_font;
2594 // Do we need to close the previous font?
2596 (current_font != running_font ||
2597 current_font.language() != running_font.language()))
2599 bool needPar = false;
2600 column += running_font.latexWriteEndChanges(
2601 os, bparams, runparams, basefont,
2602 (i == body_pos-1) ? basefont : current_font,
2604 running_font = basefont;
2608 string const running_lang = runparams.use_polyglossia ?
2609 running_font.language()->polyglossia() : running_font.language()->babel();
2610 // close babel's font environment before opening CJK.
2611 string const lang_end_command = runparams.use_polyglossia ?
2612 "\\end{$$lang}" : lyxrc.language_command_end;
2613 bool const using_begin_end = runparams.use_polyglossia ||
2614 !lang_end_command.empty();
2615 if (!running_lang.empty() &&
2616 (!using_begin_end || running_lang == openLanguageName()) &&
2617 current_font.language()->encoding()->package() == Encoding::CJK) {
2618 string end_tag = subst(lang_end_command,
2621 os << from_ascii(end_tag);
2622 column += end_tag.length();
2623 if (using_begin_end)
2627 // Switch file encoding if necessary (and allowed)
2628 if (!runparams.pass_thru && !style.pass_thru &&
2629 runparams.encoding->package() != Encoding::none &&
2630 current_font.language()->encoding()->package() != Encoding::none) {
2631 pair<bool, int> const enc_switch =
2632 switchEncoding(os.os(), bparams, runparams,
2633 *(current_font.language()->encoding()));
2634 if (enc_switch.first) {
2635 column += enc_switch.second;
2636 runparams.encoding = current_font.language()->encoding();
2640 char_type const c = d->text_[i];
2642 // A display math inset inside an ulem command will be output
2643 // as a box of width \linewidth, so we have to either disable
2644 // indentation if the inset starts a paragraph, or start a new
2645 // line to accommodate such box. This has to be done before
2646 // writing any font changing commands.
2647 if (runparams.inDisplayMath && !deleted_display_math
2648 && runparams.inulemcmd) {
2649 if (os.afterParbreak())
2655 // Do we need to change font?
2656 if ((current_font != running_font ||
2657 current_font.language() != running_font.language()) &&
2660 odocstringstream ods;
2661 column += current_font.latexWriteStartChanges(ods, bparams,
2662 runparams, basefont,
2664 // Check again for display math in ulem commands as a
2665 // font change may also occur just before a math inset.
2666 if (runparams.inDisplayMath && !deleted_display_math
2667 && runparams.inulemcmd) {
2668 if (os.afterParbreak())
2673 running_font = current_font;
2675 docstring fontchange = ods.str();
2676 // check whether the fontchange ends with a \\textcolor
2677 // modifier and the text starts with a space (bug 4473)
2678 docstring const last_modifier = rsplit(fontchange, '\\');
2679 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2680 os << fontchange << from_ascii("{}");
2681 // check if the fontchange ends with a trailing blank
2682 // (like "\small " (see bug 3382)
2683 else if (suffixIs(fontchange, ' ') && c == ' ')
2684 os << fontchange.substr(0, fontchange.size() - 1)
2685 << from_ascii("{}");
2690 // FIXME: think about end_pos implementation...
2691 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2692 // FIXME: integrate this case in latexSpecialChar
2693 // Do not print the separation of the optional argument
2694 // if style.pass_thru is false. This works because
2695 // latexSpecialChar ignores spaces if
2696 // style.pass_thru is false.
2697 if (i != body_pos - 1) {
2698 if (d->simpleTeXBlanks(bparams, runparams, os,
2699 i, column, current_font, style)) {
2700 // A surrogate pair was output. We
2701 // must not call latexSpecialChar
2702 // in this iteration, since it would output
2703 // the combining character again.
2710 OutputParams rp = runparams;
2711 rp.free_spacing = style.free_spacing;
2712 rp.local_font = ¤t_font;
2713 rp.intitle = style.intitle;
2715 // Two major modes: LaTeX or plain
2716 // Handle here those cases common to both modes
2717 // and then split to handle the two modes separately.
2718 if (c == META_INSET) {
2719 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2720 // Greyedout notes and, in general, all insets
2721 // with InsetLayout::isDisplay() == false,
2722 // are typeset inline with the text. So, we
2723 // can add a \par to the last paragraph of
2724 // such insets only if nothing else follows.
2725 bool incremented = false;
2726 Inset const * inset = getInset(i);
2727 InsetText const * textinset = inset
2728 ? inset->asInsetText()
2730 if (i + 1 == size() && textinset
2731 && !inset->getLayout().isDisplay()) {
2732 ParagraphList const & pars =
2733 textinset->text().paragraphs();
2734 pit_type const pit = pars.size() - 1;
2735 Font const lastfont =
2736 pit < 0 || pars[pit].empty()
2737 ? pars[pit].getLayoutFont(
2740 : pars[pit].getFont(bparams,
2741 pars[pit].size() - 1,
2743 if (lastfont.fontInfo().size() !=
2744 basefont.fontInfo().size()) {
2749 d->latexInset(bparams, os, rp, running_font,
2750 basefont, outerfont, open_font,
2751 runningChange, style, i, column);
2755 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2757 d->latexSpecialChar(os, bparams, rp,
2758 running_font, runningChange,
2759 style, i, end_pos, column);
2760 } catch (EncodingException & e) {
2761 if (runparams.dryrun) {
2762 os << "<" << _("LyX Warning: ")
2763 << _("uncodable character") << " '";
2767 // add location information and throw again.
2775 // Set the encoding to that returned from latexSpecialChar (see
2776 // comment for encoding member in OutputParams.h)
2777 runparams.encoding = rp.encoding;
2779 // Also carry on the info on a closed ulem command for insets
2780 // such as Note that do not produce any output, so that no
2781 // command is ever executed but its opening was recorded.
2782 runparams.inulemcmd = rp.inulemcmd;
2785 // If we have an open font definition, we have to close it
2787 // Make sure that \\par is done with the font of the last
2788 // character if this has another size as the default.
2789 // This is necessary because LaTeX (and LyX on the screen)
2790 // calculates the space between the baselines according
2791 // to this font. (Matthias)
2793 // We must not change the font for the last paragraph
2794 // of non-multipar insets, tabular cells or commands,
2795 // since this produces unwanted whitespace.
2797 Font const font = empty()
2798 ? getLayoutFont(bparams, outerfont)
2799 : getFont(bparams, size() - 1, outerfont);
2801 InsetText const * textinset = inInset().asInsetText();
2803 bool const maintext = textinset
2804 ? textinset->text().isMainText()
2807 size_t const numpars = textinset
2808 ? textinset->text().paragraphs().size()
2811 bool needPar = false;
2813 if (style.resfont.size() != font.fontInfo().size()
2814 && (!runparams.isLastPar || maintext
2815 || (numpars > 1 && d->ownerCode() != CELL_CODE
2816 && (inInset().getLayout().isDisplay()
2818 && !style.isCommand()) {
2821 #ifdef FIXED_LANGUAGE_END_DETECTION
2823 running_font.latexWriteEndChanges(os, bparams,
2824 runparams, basefont,
2825 next_->getFont(bparams, 0, outerfont),
2828 running_font.latexWriteEndChanges(os, bparams,
2829 runparams, basefont, basefont, needPar);
2832 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2833 //FIXME: there as we start another \selectlanguage with the next paragraph if
2834 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2835 running_font.latexWriteEndChanges(os, bparams, runparams,
2836 basefont, basefont, needPar);
2839 // The \par could not be inserted at the same nesting
2840 // level of the font size change, so do it now.
2841 os << "{\\" << font.latexSize() << "\\par}";
2845 column += Changes::latexMarkChange(os, bparams, runningChange,
2846 Change(Change::UNCHANGED), runparams);
2848 // Needed if there is an optional argument but no contents.
2849 if (body_pos > 0 && body_pos == size()) {
2853 if (!style.rightdelim().empty()) {
2854 os << style.rightdelim();
2855 column += style.rightdelim().size();
2858 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2859 && runparams.encoding != prev_encoding) {
2860 runparams.encoding = prev_encoding;
2861 os << setEncoding(prev_encoding->iconvName());
2864 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2868 bool Paragraph::emptyTag() const
2870 for (pos_type i = 0; i < size(); ++i) {
2871 if (Inset const * inset = getInset(i)) {
2872 InsetCode lyx_code = inset->lyxCode();
2873 // FIXME testing like that is wrong. What is
2875 if (lyx_code != TOC_CODE &&
2876 lyx_code != INCLUDE_CODE &&
2877 lyx_code != GRAPHICS_CODE &&
2878 lyx_code != ERT_CODE &&
2879 lyx_code != LISTINGS_CODE &&
2880 lyx_code != FLOAT_CODE &&
2881 lyx_code != TABULAR_CODE) {
2885 char_type c = d->text_[i];
2886 if (c != ' ' && c != '\t')
2894 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2897 for (pos_type i = 0; i < size(); ++i) {
2898 if (Inset const * inset = getInset(i)) {
2899 InsetCode lyx_code = inset->lyxCode();
2900 if (lyx_code == LABEL_CODE) {
2901 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2902 docstring const & id = il->getParam("name");
2903 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2911 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2915 for (i = 0; i < size(); ++i) {
2916 if (Inset const * inset = getInset(i)) {
2917 inset->docbook(os, runparams);
2919 char_type c = d->text_[i];
2922 os << sgml::escapeChar(c);
2929 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2933 for (i = 0; i < size(); ++i) {
2934 if (Inset const * inset = getInset(i)) {
2935 inset->xhtml(xs, runparams);
2937 char_type c = d->text_[i];
2947 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2950 pos_type size = text_.size();
2951 for (pos_type i = initial; i < size; ++i) {
2952 Font font = owner_->getFont(buf.params(), i, outerfont);
2953 if (text_[i] == META_INSET)
2955 if (i != initial && font != font_old)
2964 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2966 OutputParams const & runparams,
2967 Font const & outerfont,
2968 pos_type initial) const
2970 bool emph_flag = false;
2972 Layout const & style = *d->layout_;
2974 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2976 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2979 // parsing main loop
2980 for (pos_type i = initial; i < size(); ++i) {
2981 Font font = getFont(buf.params(), i, outerfont);
2983 // handle <emphasis> tag
2984 if (font_old.emph() != font.fontInfo().emph()) {
2985 if (font.fontInfo().emph() == FONT_ON) {
2988 } else if (i != initial) {
2989 os << "</emphasis>";
2994 if (Inset const * inset = getInset(i)) {
2995 inset->docbook(os, runparams);
2997 char_type c = d->text_[i];
2999 if (style.pass_thru)
3002 os << sgml::escapeChar(c);
3004 font_old = font.fontInfo();
3008 os << "</emphasis>";
3011 if (style.free_spacing)
3013 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
3019 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
3020 vector<html::EndFontTag> & tagsToClose,
3021 bool & flag, FontState curstate, html::FontTypes type)
3023 if (curstate == FONT_ON) {
3024 tagsToOpen.push_back(html::FontTag(type));
3027 tagsToClose.push_back(html::EndFontTag(type));
3034 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
3036 OutputParams const & runparams,
3037 Font const & outerfont,
3038 bool start_paragraph, bool close_paragraph,
3039 pos_type initial) const
3043 // track whether we have opened these tags
3044 bool emph_flag = false;
3045 bool bold_flag = false;
3046 bool noun_flag = false;
3047 bool ubar_flag = false;
3048 bool dbar_flag = false;
3049 bool sout_flag = false;
3050 bool xout_flag = false;
3051 bool wave_flag = false;
3053 bool shap_flag = false;
3055 bool faml_flag = false;
3057 bool size_flag = false;
3059 Layout const & style = *d->layout_;
3061 if (start_paragraph)
3062 xs.startDivision(allowEmpty());
3065 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3067 FontShape curr_fs = INHERIT_SHAPE;
3068 FontFamily curr_fam = INHERIT_FAMILY;
3069 FontSize curr_size = FONT_SIZE_INHERIT;
3071 string const default_family =
3072 buf.masterBuffer()->params().fonts_default_family;
3074 vector<html::FontTag> tagsToOpen;
3075 vector<html::EndFontTag> tagsToClose;
3077 // parsing main loop
3078 for (pos_type i = initial; i < size(); ++i) {
3079 // let's not show deleted material in the output
3083 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3086 FontState curstate = font.fontInfo().emph();
3087 if (font_old.emph() != curstate)
3088 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3091 curstate = font.fontInfo().noun();
3092 if (font_old.noun() != curstate)
3093 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3096 curstate = font.fontInfo().underbar();
3097 if (font_old.underbar() != curstate)
3098 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3101 curstate = font.fontInfo().strikeout();
3102 if (font_old.strikeout() != curstate)
3103 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3106 curstate = font.fontInfo().xout();
3107 if (font_old.xout() != curstate)
3108 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3111 curstate = font.fontInfo().uuline();
3112 if (font_old.uuline() != curstate)
3113 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3116 curstate = font.fontInfo().uwave();
3117 if (font_old.uwave() != curstate)
3118 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3121 // a little hackish, but allows us to reuse what we have.
3122 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3123 if (font_old.series() != font.fontInfo().series())
3124 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3127 curr_fs = font.fontInfo().shape();
3128 FontShape old_fs = font_old.shape();
3129 if (old_fs != curr_fs) {
3133 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3136 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3138 case SMALLCAPS_SHAPE:
3139 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3145 // the other tags are for internal use
3153 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3157 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3160 case SMALLCAPS_SHAPE:
3161 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3168 // the other tags are for internal use
3175 curr_fam = font.fontInfo().family();
3176 FontFamily old_fam = font_old.family();
3177 if (old_fam != curr_fam) {
3181 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3184 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3186 case TYPEWRITER_FAMILY:
3187 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3189 case INHERIT_FAMILY:
3192 // the other tags are for internal use
3200 // we will treat a "default" font family as roman, since we have
3201 // no other idea what to do.
3202 if (default_family != "rmdefault" && default_family != "default") {
3203 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3208 if (default_family != "sfdefault") {
3209 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3213 case TYPEWRITER_FAMILY:
3214 if (default_family != "ttdefault") {
3215 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3219 case INHERIT_FAMILY:
3222 // the other tags are for internal use
3229 curr_size = font.fontInfo().size();
3230 FontSize old_size = font_old.size();
3231 if (old_size != curr_size) {
3234 case FONT_SIZE_TINY:
3235 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3237 case FONT_SIZE_SCRIPT:
3238 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3240 case FONT_SIZE_FOOTNOTE:
3241 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3243 case FONT_SIZE_SMALL:
3244 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3246 case FONT_SIZE_LARGE:
3247 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3249 case FONT_SIZE_LARGER:
3250 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3252 case FONT_SIZE_LARGEST:
3253 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3255 case FONT_SIZE_HUGE:
3256 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3258 case FONT_SIZE_HUGER:
3259 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3261 case FONT_SIZE_INCREASE:
3262 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3264 case FONT_SIZE_DECREASE:
3265 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3267 case FONT_SIZE_INHERIT:
3268 case FONT_SIZE_NORMAL:
3271 // the other tags are for internal use
3277 switch (curr_size) {
3278 case FONT_SIZE_TINY:
3279 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3282 case FONT_SIZE_SCRIPT:
3283 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3286 case FONT_SIZE_FOOTNOTE:
3287 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3290 case FONT_SIZE_SMALL:
3291 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3294 case FONT_SIZE_LARGE:
3295 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3298 case FONT_SIZE_LARGER:
3299 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3302 case FONT_SIZE_LARGEST:
3303 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3306 case FONT_SIZE_HUGE:
3307 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3310 case FONT_SIZE_HUGER:
3311 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3314 case FONT_SIZE_INCREASE:
3315 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3318 case FONT_SIZE_DECREASE:
3319 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3322 case FONT_SIZE_NORMAL:
3323 case FONT_SIZE_INHERIT:
3326 // the other tags are for internal use
3333 // Other such tags? What about the other text ranges?
3335 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3336 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3337 for (; cit != cen; ++cit)
3340 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3341 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3342 for (; sit != sen; ++sit)
3345 tagsToClose.clear();
3348 Inset const * inset = getInset(i);
3350 if (!runparams.for_toc || inset->isInToc()) {
3351 OutputParams np = runparams;
3352 np.local_font = &font;
3353 // If the paragraph has size 1, then we are in the "special
3354 // case" where we do not output the containing paragraph info
3355 if (!inset->getLayout().htmlisblock() && size() != 1)
3356 np.html_in_par = true;
3357 retval += inset->xhtml(xs, np);
3360 char_type c = getUChar(buf.masterBuffer()->params(), i);
3363 font_old = font.fontInfo();
3367 // I'm worried about what happens if a branch, say, is itself
3368 // wrapped in some font stuff. I think that will not work.
3370 if (close_paragraph)
3377 bool Paragraph::isHfill(pos_type pos) const
3379 Inset const * inset = getInset(pos);
3380 return inset && inset->isHfill();
3384 bool Paragraph::isNewline(pos_type pos) const
3386 // U+2028 LINE SEPARATOR
3387 // U+2029 PARAGRAPH SEPARATOR
3388 char_type const c = d->text_[pos];
3389 if (c == 0x2028 || c == 0x2029)
3391 Inset const * inset = getInset(pos);
3392 return inset && inset->lyxCode() == NEWLINE_CODE;
3396 bool Paragraph::isEnvSeparator(pos_type pos) const
3398 Inset const * inset = getInset(pos);
3399 return inset && inset->lyxCode() == SEPARATOR_CODE;
3403 bool Paragraph::isLineSeparator(pos_type pos) const
3405 char_type const c = d->text_[pos];
3406 if (isLineSeparatorChar(c))
3408 Inset const * inset = getInset(pos);
3409 return inset && inset->isLineSeparator();
3413 bool Paragraph::isWordSeparator(pos_type pos) const
3417 if (Inset const * inset = getInset(pos))
3418 return !inset->isLetter();
3419 // if we have a hard hyphen (no en- or emdash) or apostrophe
3420 // we pass this to the spell checker
3421 // FIXME: this method is subject to change, visit
3422 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3423 // to get an impression how complex this is.
3424 if (isHardHyphenOrApostrophe(pos))
3426 char_type const c = d->text_[pos];
3427 // We want to pass the escape chars to the spellchecker
3428 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3429 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3433 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3435 pos_type const psize = size();
3438 char_type const c = d->text_[pos];
3439 if (c != '-' && c != '\'')
3441 int nextpos = pos + 1;
3442 int prevpos = pos > 0 ? pos - 1 : 0;
3443 if ((nextpos == psize || isSpace(nextpos))
3444 && (pos == 0 || isSpace(prevpos)))
3450 bool Paragraph::needsCProtection() const
3452 // first check the layout of the paragraph, but only in insets
3453 InsetText const * textinset = inInset().asInsetText();
3454 bool const maintext = textinset
3455 ? textinset->text().isMainText()
3458 if (!maintext && layout().needcprotect) {
3459 // Environments need cprotection regardless the content
3460 if (layout().latextype == LATEX_ENVIRONMENT)
3463 // Commands need cprotection if they contain specific chars
3464 int const nchars_escape = 9;
3465 static char_type const chars_escape[nchars_escape] = {
3466 '&', '_', '$', '%', '#', '^', '{', '}', '\\'};
3468 docstring const pars = asString();
3469 for (int k = 0; k < nchars_escape; k++) {
3470 if (contains(pars, chars_escape[k]))
3475 // now check whether we have insets that need cprotection
3476 pos_type size = d->text_.size();
3477 for (pos_type i = 0; i < size; ++i)
3478 if (isInset(i) && getInset(i)->needsCProtection(maintext))
3485 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3487 return d->speller_state_.getRange(pos);
3491 bool Paragraph::isChar(pos_type pos) const
3493 if (Inset const * inset = getInset(pos))
3494 return inset->isChar();
3495 char_type const c = d->text_[pos];
3496 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3500 bool Paragraph::isSpace(pos_type pos) const
3502 if (Inset const * inset = getInset(pos))
3503 return inset->isSpace();
3504 char_type const c = d->text_[pos];
3505 return lyx::isSpace(c);
3510 Paragraph::getParLanguage(BufferParams const & bparams) const
3513 return getFirstFontSettings(bparams).language();
3514 // FIXME: we should check the prev par as well (Lgb)
3515 return bparams.language;
3519 bool Paragraph::isRTL(BufferParams const & bparams) const
3521 return getParLanguage(bparams)->rightToLeft()
3522 && !inInset().getLayout().forceLTR();
3526 void Paragraph::changeLanguage(BufferParams const & bparams,
3527 Language const * from, Language const * to)
3529 // change language including dummy font change at the end
3530 for (pos_type i = 0; i <= size(); ++i) {
3531 Font font = getFontSettings(bparams, i);
3532 if (font.language() == from) {
3533 font.setLanguage(to);
3535 d->requestSpellCheck(i);
3541 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3543 Language const * doc_language = bparams.language;
3544 for (auto const & f : d->fontlist_)
3545 if (f.font().language() != ignore_language &&
3546 f.font().language() != latex_language &&
3547 f.font().language() != doc_language)
3553 void Paragraph::getLanguages(std::set<Language const *> & langs) const
3555 for (auto const & f : d->fontlist_) {
3556 Language const * lang = f.font().language();
3557 if (lang != ignore_language &&
3558 lang != latex_language)
3564 docstring Paragraph::asString(int options) const
3566 return asString(0, size(), options);
3570 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3572 odocstringstream os;
3575 && options & AS_STR_LABEL
3576 && !d->params_.labelString().empty())
3577 os << d->params_.labelString() << ' ';
3579 for (pos_type i = beg; i < end; ++i) {
3580 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3582 char_type const c = d->text_[i];
3583 if (isPrintable(c) || c == '\t'
3584 || (c == '\n' && (options & AS_STR_NEWLINES)))
3586 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3587 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3588 LASSERT(runparams != 0, return docstring());
3589 getInset(i)->plaintext(os, *runparams);
3591 getInset(i)->toString(os);
3600 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3601 bool const shorten, bool const label) const
3603 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3604 if (label && !labelString().empty())
3605 os += labelString() + ' ';
3606 if (!layout().isTocCaption())
3608 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3611 char_type const c = d->text_[i];
3614 else if (c == META_INSET)
3615 getInset(i)->forOutliner(os, tmplen, false);
3618 Text::shortenForOutliner(os, maxlen);
3622 void Paragraph::setInsetOwner(Inset const * inset)
3624 d->inset_owner_ = inset;
3628 int Paragraph::id() const
3634 void Paragraph::setId(int id)
3640 Layout const & Paragraph::layout() const
3646 void Paragraph::setLayout(Layout const & layout)
3648 d->layout_ = &layout;
3652 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3654 setLayout(tc.defaultLayout());
3658 void Paragraph::setPlainLayout(DocumentClass const & tc)
3660 setLayout(tc.plainLayout());
3664 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3666 if (usePlainLayout())
3667 setPlainLayout(tclass);
3669 setDefaultLayout(tclass);
3673 Inset const & Paragraph::inInset() const
3675 LBUFERR(d->inset_owner_);
3676 return *d->inset_owner_;
3680 ParagraphParameters & Paragraph::params()
3686 ParagraphParameters const & Paragraph::params() const
3692 bool Paragraph::isFreeSpacing() const
3694 if (d->layout_->free_spacing)
3696 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3700 bool Paragraph::allowEmpty() const
3702 if (d->layout_->keepempty)
3704 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3708 bool Paragraph::brokenBiblio() const
3710 // there is a problem if there is no bibitem at position 0 or
3711 // if there is another bibitem in the paragraph.
3712 return d->layout_->labeltype == LABEL_BIBLIO
3713 && (d->insetlist_.find(BIBITEM_CODE) != 0
3714 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3718 int Paragraph::fixBiblio(Buffer const & buffer)
3720 // FIXME: What about the case where paragraph is not BIBLIO
3721 // but there is an InsetBibitem?
3722 // FIXME: when there was already an inset at 0, the return value is 1,
3723 // which does not tell whether another inset has been remove; the
3724 // cursor cannot be correctly updated.
3726 if (d->layout_->labeltype != LABEL_BIBLIO)
3729 bool const track_changes = buffer.params().track_changes;
3730 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3731 bool const hasbibitem0 = bibitem_pos == 0;
3734 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3735 // There was an InsetBibitem at pos 0, and no other one => OK
3736 if (bibitem_pos == -1)
3738 // there is a bibitem at the 0 position, but since
3739 // there is a second one, we copy the second on the
3740 // first. We're assuming there are at most two of
3741 // these, which there should be.
3742 // FIXME: why does it make sense to do that rather
3743 // than keep the first? (JMarc)
3744 Inset * inset = releaseInset(bibitem_pos);
3745 d->insetlist_.begin()->inset = inset;
3746 return -bibitem_pos;
3749 // We need to create an inset at the beginning
3751 if (bibitem_pos > 0) {
3752 // there was one somewhere in the paragraph, let's move it
3753 inset = d->insetlist_.release(bibitem_pos);
3754 eraseChar(bibitem_pos, track_changes);
3757 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3758 InsetCommandParams(BIBITEM_CODE));
3760 Font font(inherit_font, buffer.params().language);
3761 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3762 : Change::UNCHANGED));
3768 void Paragraph::checkAuthors(AuthorList const & authorList)
3770 d->changes_.checkAuthors(authorList);
3774 bool Paragraph::isChanged(pos_type pos) const
3776 return lookupChange(pos).changed();
3780 bool Paragraph::isInserted(pos_type pos) const
3782 return lookupChange(pos).inserted();
3786 bool Paragraph::isDeleted(pos_type pos) const
3788 return lookupChange(pos).deleted();
3792 InsetList const & Paragraph::insetList() const
3794 return d->insetlist_;
3798 void Paragraph::setInsetBuffers(Buffer & b)
3800 d->insetlist_.setBuffer(b);
3804 void Paragraph::resetBuffer()
3806 d->insetlist_.resetBuffer();
3810 Inset * Paragraph::releaseInset(pos_type pos)
3812 Inset * inset = d->insetlist_.release(pos);
3813 /// does not honour change tracking!
3814 eraseChar(pos, false);
3819 Inset * Paragraph::getInset(pos_type pos)
3821 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3822 ? d->insetlist_.get(pos) : 0;
3826 Inset const * Paragraph::getInset(pos_type pos) const
3828 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3829 ? d->insetlist_.get(pos) : 0;
3833 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3834 pos_type & right, TextCase action)
3836 // process sequences of modified characters; in change
3837 // tracking mode, this approach results in much better
3838 // usability than changing case on a char-by-char basis
3839 // We also need to track the current font, since font
3840 // changes within sequences can occur.
3841 vector<pair<char_type, Font> > changes;
3843 bool const trackChanges = bparams.track_changes;
3845 bool capitalize = true;
3847 for (; pos < right; ++pos) {
3848 char_type oldChar = d->text_[pos];
3849 char_type newChar = oldChar;
3851 // ignore insets and don't play with deleted text!
3852 if (oldChar != META_INSET && !isDeleted(pos)) {
3854 case text_lowercase:
3855 newChar = lowercase(oldChar);
3857 case text_capitalization:
3859 newChar = uppercase(oldChar);
3863 case text_uppercase:
3864 newChar = uppercase(oldChar);
3869 if (isWordSeparator(pos) || isDeleted(pos)) {
3870 // permit capitalization again
3874 if (oldChar != newChar) {
3875 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3876 if (pos != right - 1)
3878 // step behind the changing area
3882 int erasePos = pos - changes.size();
3883 for (size_t i = 0; i < changes.size(); i++) {
3884 insertChar(pos, changes[i].first,
3887 if (!eraseChar(erasePos, trackChanges)) {
3890 ++right; // expand selection
3898 int Paragraph::find(docstring const & str, bool cs, bool mw,
3899 pos_type start_pos, bool del) const
3901 pos_type pos = start_pos;
3902 int const strsize = str.length();
3904 pos_type const parsize = d->text_.size();
3905 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3906 // Ignore "invisible" letters such as ligature breaks
3907 // and hyphenation chars while searching
3908 while (pos < parsize - 1 && isInset(pos)) {
3909 odocstringstream os;
3910 getInset(pos)->toString(os);
3911 if (!getInset(pos)->isLetter() || !os.str().empty())
3915 if (cs && str[i] != d->text_[pos])
3917 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3919 if (!del && isDeleted(pos))
3926 // if necessary, check whether string matches word
3928 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3931 && !isWordSeparator(pos))
3935 return pos - start_pos;
3939 char_type Paragraph::getChar(pos_type pos) const
3941 return d->text_[pos];
3945 pos_type Paragraph::size() const
3947 return d->text_.size();
3951 bool Paragraph::empty() const
3953 return d->text_.empty();
3957 bool Paragraph::isInset(pos_type pos) const
3959 return d->text_[pos] == META_INSET;
3963 bool Paragraph::isSeparator(pos_type pos) const
3965 //FIXME: Are we sure this can be the only separator?
3966 return d->text_[pos] == ' ';
3970 void Paragraph::deregisterWords()
3972 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3973 Private::LangWordsMap::const_iterator ite = d->words_.end();
3974 for (; itl != ite; ++itl) {
3975 WordList & wl = theWordList(itl->first);
3976 Private::Words::const_iterator it = (itl->second).begin();
3977 Private::Words::const_iterator et = (itl->second).end();
3978 for (; it != et; ++it)
3985 void Paragraph::locateWord(pos_type & from, pos_type & to,
3986 word_location const loc) const
3989 case WHOLE_WORD_STRICT:
3990 if (from == 0 || from == size()
3991 || isWordSeparator(from)
3992 || isWordSeparator(from - 1)) {
3999 // If we are already at the beginning of a word, do nothing
4000 if (!from || isWordSeparator(from - 1))
4005 // always move the cursor to the beginning of previous word
4006 while (from && !isWordSeparator(from - 1))
4010 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
4013 // no need to move the 'from' cursor
4017 while (to < size() && !isWordSeparator(to))
4022 void Paragraph::collectWords()
4024 for (pos_type pos = 0; pos < size(); ++pos) {
4025 if (isWordSeparator(pos))
4027 pos_type from = pos;
4028 locateWord(from, pos, WHOLE_WORD);
4029 // Work around MSVC warning: The statement
4030 // if (pos < from + lyxrc.completion_minlength)
4031 // triggers a signed vs. unsigned warning.
4032 // I don't know why this happens, it could be a MSVC bug, or
4033 // related to LLP64 (windows) vs. LP64 (unix) programming
4034 // model, or the C++ standard might be ambigous in the section
4035 // defining the "usual arithmetic conversions". However, using
4036 // a temporary variable is safe and works on all compilers.
4037 pos_type const endpos = from + lyxrc.completion_minlength;
4040 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
4041 if (cit == d->fontlist_.end())
4043 Language const * lang = cit->font().language();
4044 docstring const word = asString(from, pos, AS_STR_NONE);
4045 d->words_[lang->lang()].insert(word);
4050 void Paragraph::registerWords()
4052 Private::LangWordsMap::const_iterator itl = d->words_.begin();
4053 Private::LangWordsMap::const_iterator ite = d->words_.end();
4054 for (; itl != ite; ++itl) {
4055 WordList & wl = theWordList(itl->first);
4056 Private::Words::const_iterator it = (itl->second).begin();
4057 Private::Words::const_iterator et = (itl->second).end();
4058 for (; it != et; ++it)
4064 void Paragraph::updateWords()
4072 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4074 SkipPositionsIterator begin = skips.begin();
4075 SkipPositions::iterator end = skips.end();
4076 if (pos > 0 && begin < end) {
4078 if (end->last == pos - 1) {
4083 skips.insert(end, FontSpan(pos, pos));
4087 Language * Paragraph::Private::locateSpellRange(
4088 pos_type & from, pos_type & to,
4089 SkipPositions & skips) const
4091 // skip leading white space
4092 while (from < to && owner_->isWordSeparator(from))
4094 // don't check empty range
4097 // get current language
4098 Language * lang = getSpellLanguage(from);
4099 pos_type last = from;
4100 bool samelang = true;
4101 bool sameinset = true;
4102 while (last < to && samelang && sameinset) {
4103 // hop to end of word
4104 while (last < to && !owner_->isWordSeparator(last)) {
4105 if (owner_->getInset(last)) {
4106 appendSkipPosition(skips, last);
4107 } else if (owner_->isDeleted(last)) {
4108 appendSkipPosition(skips, last);
4112 // hop to next word while checking for insets
4113 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4114 if (Inset const * inset = owner_->getInset(last))
4115 sameinset = inset->isChar() && inset->isLetter();
4116 if (sameinset && owner_->isDeleted(last)) {
4117 appendSkipPosition(skips, last);
4122 if (sameinset && last < to) {
4123 // now check for language change
4124 samelang = lang == getSpellLanguage(last);
4127 // if language change detected backstep is needed
4135 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4138 const_cast<Language *>(owner_->getFontSettings(
4139 inset_owner_->buffer().params(), from).language());
4140 if (lang == inset_owner_->buffer().params().language
4141 && !lyxrc.spellchecker_alt_lang.empty()) {
4143 string const lang_variety =
4144 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4145 lang->setCode(lang_code);
4146 lang->setVariety(lang_variety);
4152 void Paragraph::requestSpellCheck(pos_type pos)
4154 d->requestSpellCheck(pos);
4158 bool Paragraph::needsSpellCheck() const
4160 SpellChecker::ChangeNumber speller_change_number = 0;
4161 if (theSpellChecker())
4162 speller_change_number = theSpellChecker()->changeNumber();
4163 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4164 d->speller_state_.needsCompleteRefresh(speller_change_number);
4166 return d->needsSpellCheck();
4170 bool Paragraph::Private::ignoreWord(docstring const & word) const
4172 // Ignore words with digits
4173 // FIXME: make this customizable
4174 // (note that some checkers ignore words with digits by default)
4175 docstring::const_iterator cit = word.begin();
4176 docstring::const_iterator const end = word.end();
4177 for (; cit != end; ++cit) {
4178 if (isNumber((*cit)))
4185 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4186 WordLangTuple & wl, docstring_list & suggestions,
4187 bool do_suggestion, bool check_learned) const
4189 SpellChecker::Result result = SpellChecker::WORD_OK;
4190 SpellChecker * speller = theSpellChecker();
4194 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4197 locateWord(from, to, WHOLE_WORD);
4198 if (from == to || from >= size())
4201 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4202 Language * lang = d->getSpellLanguage(from);
4204 wl = WordLangTuple(word, lang);
4209 if (needsSpellCheck() || check_learned) {
4211 if (!d->ignoreWord(word)) {
4212 bool const trailing_dot = to < size() && d->text_[to] == '.';
4213 result = speller->check(wl);
4214 if (SpellChecker::misspelled(result) && trailing_dot) {
4215 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4216 result = speller->check(wl);
4217 if (!SpellChecker::misspelled(result)) {
4218 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4220 from << ".." << to << "]");
4222 // spell check with dot appended failed too
4223 // restore original word/lang value
4224 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4225 wl = WordLangTuple(word, lang);
4229 if (!SpellChecker::misspelled(result)) {
4230 // area up to the begin of the next word is not misspelled
4231 while (end < size() && isWordSeparator(end))
4234 d->setMisspelled(from, end, result);
4236 result = d->speller_state_.getState(from);
4240 suggestions.clear();
4242 if (SpellChecker::misspelled(result)) {
4243 LYXERR(Debug::GUI, "misspelled word: \"" <<
4245 from << ".." << to << "]");
4247 speller->suggest(wl, suggestions);
4253 void Paragraph::anonymize()
4255 // This is a very crude anonymization for now
4256 for (char_type & c : d->text_)
4257 if (isLetterChar(c) || isNumber(c))
4262 void Paragraph::Private::markMisspelledWords(
4263 pos_type const & first, pos_type const & last,
4264 SpellChecker::Result result,
4265 docstring const & word,
4266 SkipPositions const & skips)
4268 if (!SpellChecker::misspelled(result)) {
4269 setMisspelled(first, last, SpellChecker::WORD_OK);
4273 SpellChecker * speller = theSpellChecker();
4274 // locate and enumerate the error positions
4275 int nerrors = speller->numMisspelledWords();
4277 SkipPositionsIterator it = skips.begin();
4278 SkipPositionsIterator et = skips.end();
4279 for (int index = 0; index < nerrors; ++index) {
4282 speller->misspelledWord(index, wstart, wlen);
4283 /// should not happen if speller supports range checks
4284 if (!wlen) continue;
4285 docstring const misspelled = word.substr(wstart, wlen);
4286 wstart += first + numskipped;
4287 if (snext < wstart) {
4288 /// mark the range of correct spelling
4289 numskipped += countSkips(it, et, wstart);
4290 setMisspelled(snext,
4291 wstart - 1, SpellChecker::WORD_OK);
4293 snext = wstart + wlen;
4294 numskipped += countSkips(it, et, snext);
4295 /// mark the range of misspelling
4296 setMisspelled(wstart, snext, result);
4297 LYXERR(Debug::GUI, "misspelled word: \"" <<
4298 misspelled << "\" [" <<
4299 wstart << ".." << (snext-1) << "]");
4302 if (snext <= last) {
4303 /// mark the range of correct spelling at end
4304 setMisspelled(snext, last, SpellChecker::WORD_OK);
4309 void Paragraph::spellCheck() const
4311 SpellChecker * speller = theSpellChecker();
4312 if (!speller || empty() ||!needsSpellCheck())
4316 d->rangeOfSpellCheck(start, endpos);
4317 if (speller->canCheckParagraph()) {
4318 // loop until we leave the range
4319 for (pos_type first = start; first < endpos; ) {
4320 pos_type last = endpos;
4321 Private::SkipPositions skips;
4322 Language * lang = d->locateSpellRange(first, last, skips);
4323 if (first >= endpos)
4325 // start the spell checker on the unit of meaning
4326 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4327 WordLangTuple wl = WordLangTuple(word, lang);
4328 SpellChecker::Result result = word.size() ?
4329 speller->check(wl) : SpellChecker::WORD_OK;
4330 d->markMisspelledWords(first, last, result, word, skips);
4334 static docstring_list suggestions;
4335 pos_type to = endpos;
4336 while (start < endpos) {
4338 spellCheck(start, to, wl, suggestions, false);
4342 d->readySpellCheck();
4346 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4348 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4349 if (result || pos <= 0 || pos > size())
4351 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4352 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4357 string Paragraph::magicLabel() const
4360 ss << "magicparlabel-" << id();