3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
55 #include "insets/InsetText.h"
57 #include "mathed/InsetMathHull.h"
59 #include "support/debug.h"
60 #include "support/docstring_list.h"
61 #include "support/ExceptionMessage.h"
62 #include "support/gettext.h"
63 #include "support/lassert.h"
64 #include "support/lstrings.h"
65 #include "support/textutils.h"
72 using namespace lyx::support;
74 // OSX clang, gcc < 4.8.0, and msvc < 2015 do not support C++11 thread_local
75 #if defined(__APPLE__) || (defined(__GNUC__) && __GNUC__ == 4 && __GNUC_MINOR__ < 8)
76 #define THREAD_LOCAL_STATIC static __thread
77 #elif defined(_MSC_VER) && (_MSC_VER < 1900)
78 #define THREAD_LOCAL_STATIC static __declspec(thread)
80 #define THREAD_LOCAL_STATIC thread_local static
87 /// Inset identifier (above 0x10ffff, for ucs-4)
88 char_type const META_INSET = 0x200001;
93 /////////////////////////////////////////////////////////////////////
97 /////////////////////////////////////////////////////////////////////
99 class SpellResultRange {
101 SpellResultRange(FontSpan range, SpellChecker::Result result)
102 : range_(range), result_(result)
105 FontSpan const & range() const { return range_; }
107 void range(FontSpan const & r) { range_ = r; }
109 SpellChecker::Result result() const { return result_; }
111 void result(SpellChecker::Result r) { result_ = r; }
113 bool contains(pos_type pos) const { return range_.contains(pos); }
115 bool covered(FontSpan const & r) const
117 // 1. first of new range inside current range or
118 // 2. last of new range inside current range or
119 // 3. first of current range inside new range or
120 // 4. last of current range inside new range
121 //FIXME: is this the same as !range_.intersect(r).empty() ?
122 return range_.contains(r.first) || range_.contains(r.last) ||
123 r.contains(range_.first) || r.contains(range_.last);
126 void shift(pos_type pos, int offset)
128 if (range_.first > pos) {
129 range_.first += offset;
130 range_.last += offset;
131 } else if (range_.last >= pos) {
132 range_.last += offset;
137 SpellChecker::Result result_ ;
141 /////////////////////////////////////////////////////////////////////
145 /////////////////////////////////////////////////////////////////////
147 class SpellCheckerState {
151 needs_refresh_ = true;
152 current_change_number_ = 0;
155 void setRange(FontSpan const & fp, SpellChecker::Result state)
158 RangesIterator et = ranges_.end();
159 RangesIterator it = ranges_.begin();
160 for (; it != et; ++it) {
161 if (!it->covered(fp))
162 result.push_back(SpellResultRange(it->range(), it->result()));
163 else if (state == SpellChecker::WORD_OK) {
164 // trim or split the current misspelled range
165 // store misspelled ranges only
166 FontSpan range = it->range();
167 if (fp.first > range.first) {
168 // misspelled area in front of WORD_OK
169 range.last = fp.first - 1;
170 result.push_back(SpellResultRange(range, it->result()));
173 if (fp.last < range.last) {
174 // misspelled area after WORD_OK range
175 range.first = fp.last + 1;
176 result.push_back(SpellResultRange(range, it->result()));
181 if (state != SpellChecker::WORD_OK)
182 ranges_.push_back(SpellResultRange(fp, state));
185 void increasePosAfterPos(pos_type pos)
187 correctRangesAfterPos(pos, 1);
191 void decreasePosAfterPos(pos_type pos)
193 correctRangesAfterPos(pos, -1);
197 void refreshLast(pos_type pos)
199 if (pos < refresh_.last)
203 SpellChecker::Result getState(pos_type pos) const
205 SpellChecker::Result result = SpellChecker::WORD_OK;
206 RangesIterator et = ranges_.end();
207 RangesIterator it = ranges_.begin();
208 for (; it != et; ++it) {
209 if(it->contains(pos)) {
216 FontSpan const & getRange(pos_type pos) const
218 /// empty span to indicate mismatch
219 static FontSpan empty_;
220 RangesIterator et = ranges_.end();
221 RangesIterator it = ranges_.begin();
222 for (; it != et; ++it) {
223 if(it->contains(pos)) {
230 bool needsRefresh() const
232 return needs_refresh_;
235 SpellChecker::ChangeNumber currentChangeNumber() const
237 return current_change_number_;
240 void refreshRange(pos_type & first, pos_type & last) const
242 first = refresh_.first;
243 last = refresh_.last;
246 void needsRefresh(pos_type pos)
248 if (needs_refresh_ && pos != -1) {
249 if (pos < refresh_.first)
250 refresh_.first = pos;
251 if (pos > refresh_.last)
253 } else if (pos != -1) {
254 // init request check for neighbour positions too
255 refresh_.first = pos > 0 ? pos - 1 : 0;
256 // no need for special end of paragraph check
257 refresh_.last = pos + 1;
259 needs_refresh_ = pos != -1;
262 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
264 needs_refresh_ = true;
267 current_change_number_ = change_number;
270 typedef vector<SpellResultRange> Ranges;
271 typedef Ranges::const_iterator RangesIterator;
273 /// the area of the paragraph with pending spell check
276 /// spell state cache version number
277 SpellChecker::ChangeNumber current_change_number_;
280 void correctRangesAfterPos(pos_type pos, int offset)
282 RangesIterator et = ranges_.end();
283 Ranges::iterator it = ranges_.begin();
284 for (; it != et; ++it) {
285 it->shift(pos, offset);
291 /////////////////////////////////////////////////////////////////////
293 // Paragraph::Private
295 /////////////////////////////////////////////////////////////////////
297 class Paragraph::Private
299 // Enforce our own "copy" constructor
300 Private(Private const &) = delete;
301 Private & operator=(Private const &) = delete;
302 // Unique ID generator
303 static int make_id();
306 Private(Paragraph * owner, Layout const & layout);
307 /// "Copy constructor"
308 Private(Private const &, Paragraph * owner);
309 /// Copy constructor from \p beg to \p end
310 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
313 void insertChar(pos_type pos, char_type c, Change const & change);
315 /// Output the surrogate pair formed by \p c and \p next to \p os.
316 /// \return the number of characters written.
317 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
318 OutputParams const &);
320 /// Output a space in appropriate formatting (or a surrogate pair
321 /// if the next character is a combining character).
322 /// \return whether a surrogate pair was output.
323 bool simpleTeXBlanks(OutputParams const &,
326 unsigned int & column,
328 Layout const & style);
330 /// Output consecutive unicode chars, belonging to the same script as
331 /// specified by the latex macro \p ltx, to \p os starting from \p i.
332 /// \return the number of characters written.
333 int writeScriptChars(otexstream & os, docstring const & ltx,
334 Change const &, Encoding const &, pos_type & i);
336 /// This could go to ParagraphParameters if we want to.
337 int startTeXParParams(BufferParams const &, otexstream &,
338 OutputParams const &) const;
340 /// This could go to ParagraphParameters if we want to.
341 bool endTeXParParams(BufferParams const &, otexstream &,
342 OutputParams const &) const;
345 void latexInset(BufferParams const &,
350 Font const & outerfont,
352 Change & running_change,
353 Layout const & style,
355 unsigned int & column);
358 void latexSpecialChar(
360 BufferParams const & bparams,
361 OutputParams const & runparams,
362 Font const & running_font,
363 Change const & running_change,
364 Layout const & style,
367 unsigned int & column);
374 unsigned int & column);
380 unsigned int & column);
386 unsigned int & column);
389 void validate(LaTeXFeatures & features) const;
391 /// Checks if the paragraph contains only text and no inset or font change.
392 bool onlyText(Buffer const & buf, Font const & outerfont,
393 pos_type initial) const;
395 /// a vector of speller skip positions
396 typedef vector<FontSpan> SkipPositions;
397 typedef SkipPositions::const_iterator SkipPositionsIterator;
399 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
401 Language * getSpellLanguage(pos_type const from) const;
403 Language * locateSpellRange(pos_type & from, pos_type & to,
404 SkipPositions & skips) const;
406 bool hasSpellerChange() const
408 SpellChecker::ChangeNumber speller_change_number = 0;
409 if (theSpellChecker())
410 speller_change_number = theSpellChecker()->changeNumber();
411 return speller_change_number > speller_state_.currentChangeNumber();
414 bool ignoreWord(docstring const & word) const ;
416 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
418 pos_type textsize = owner_->size();
419 // check for sane arguments
420 if (to <= from || from >= textsize)
422 FontSpan fp = FontSpan(from, to - 1);
423 speller_state_.setRange(fp, state);
426 void requestSpellCheck(pos_type pos)
429 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
431 speller_state_.needsRefresh(pos);
434 void readySpellCheck()
436 speller_state_.needsRefresh(-1);
439 bool needsSpellCheck() const
441 return speller_state_.needsRefresh();
444 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
446 speller_state_.refreshRange(first, last);
448 last = owner_->size();
451 pos_type endpos = last;
452 owner_->locateWord(first, endpos, WHOLE_WORD);
455 owner_->locateWord(last, endpos, WHOLE_WORD);
460 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
464 while (it != et && it->first < start) {
465 int skip = it->last - it->first + 1;
473 void markMisspelledWords(pos_type const & first, pos_type const & last,
474 SpellChecker::Result result,
475 docstring const & word,
476 SkipPositions const & skips);
478 InsetCode ownerCode() const
480 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
483 /// Which Paragraph owns us?
487 Inset const * inset_owner_;
496 ParagraphParameters params_;
498 /// for recording and looking up changes
502 InsetList insetlist_;
505 pos_type begin_of_body_;
507 typedef docstring TextContainer;
511 typedef set<docstring> Words;
512 typedef map<string, Words> LangWordsMap;
516 Layout const * layout_;
518 SpellCheckerState speller_state_;
522 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
523 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
530 int Paragraph::Private::make_id()
532 // The id is unique per session across buffers because it is used in
533 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
536 static atomic_uint next_id(0);
541 Paragraph::Private::Private(Private const & p, Paragraph * owner)
542 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
544 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
545 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
548 requestSpellCheck(p.text_.size());
552 Paragraph::Private::Private(Private const & p, Paragraph * owner,
553 pos_type beg, pos_type end)
554 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
555 params_(p.params_), changes_(p.changes_),
556 insetlist_(p.insetlist_, beg, end),
557 begin_of_body_(p.begin_of_body_), words_(p.words_),
560 if (beg >= pos_type(p.text_.size()))
562 text_ = p.text_.substr(beg, end - beg);
564 FontList::const_iterator fcit = fontlist_.begin();
565 FontList::const_iterator fend = fontlist_.end();
566 for (; fcit != fend; ++fcit) {
567 if (fcit->pos() < beg)
569 if (fcit->pos() >= end) {
570 // Add last entry in the fontlist_.
571 fontlist_.set(text_.size() - 1, fcit->font());
574 // Add a new entry in the fontlist_.
575 fontlist_.set(fcit->pos() - beg, fcit->font());
577 requestSpellCheck(p.text_.size());
581 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
582 bool output_active, TocBackend & backend) const
584 d->changes_.addToToc(cdit, buf, output_active, backend);
588 void Paragraph::addChangesToBuffer(Buffer const & buf) const
590 d->changes_.updateBuffer(buf);
594 bool Paragraph::isChangeUpdateRequired() const
596 return d->changes_.isUpdateRequired();
600 bool Paragraph::isDeleted(pos_type start, pos_type end) const
602 LASSERT(start >= 0 && start <= size(), return false);
603 LASSERT(end > start && end <= size() + 1, return false);
605 return d->changes_.isDeleted(start, end);
609 bool Paragraph::isChanged(pos_type start, pos_type end) const
611 LASSERT(start >= 0 && start <= size(), return false);
612 LASSERT(end > start && end <= size() + 1, return false);
614 return d->changes_.isChanged(start, end);
618 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
620 // keep the logic here in sync with the logic of eraseChars()
624 Change const & change = d->changes_.lookup(size());
625 return change.inserted() && change.currentAuthor();
629 void Paragraph::setChange(Change const & change)
631 // beware of the imaginary end-of-par character!
632 d->changes_.set(change, 0, size() + 1);
635 * Propagate the change recursively - but not in case of DELETED!
637 * Imagine that your co-author makes changes in an existing inset. He
638 * sends your document to you and you come to the conclusion that the
639 * inset should go completely. If you erase it, LyX must not delete all
640 * text within the inset. Otherwise, the change tracked insertions of
641 * your co-author get lost and there is no way to restore them later.
643 * Conclusion: An inset's content should remain untouched if you delete it
646 if (!change.deleted()) {
647 for (pos_type pos = 0; pos < size(); ++pos) {
648 if (Inset * inset = getInset(pos))
649 inset->setChange(change);
655 void Paragraph::setChange(pos_type pos, Change const & change)
657 LASSERT(pos >= 0 && pos <= size(), return);
658 d->changes_.set(change, pos);
660 // see comment in setChange(Change const &) above
661 if (!change.deleted() && pos < size())
662 if (Inset * inset = getInset(pos))
663 inset->setChange(change);
667 Change const & Paragraph::lookupChange(pos_type pos) const
669 LBUFERR(pos >= 0 && pos <= size());
670 return d->changes_.lookup(pos);
674 void Paragraph::acceptChanges(pos_type start, pos_type end)
676 LASSERT(start >= 0 && start <= size(), return);
677 LASSERT(end > start && end <= size() + 1, return);
679 for (pos_type pos = start; pos < end; ++pos) {
680 switch (lookupChange(pos).type) {
681 case Change::UNCHANGED:
682 // accept changes in nested inset
683 if (Inset * inset = getInset(pos))
684 inset->acceptChanges();
687 case Change::INSERTED:
688 d->changes_.set(Change(Change::UNCHANGED), pos);
689 // also accept changes in nested inset
690 if (Inset * inset = getInset(pos))
691 inset->acceptChanges();
694 case Change::DELETED:
695 // Suppress access to non-existent
696 // "end-of-paragraph char"
698 eraseChar(pos, false);
709 void Paragraph::rejectChanges(pos_type start, pos_type end)
711 LASSERT(start >= 0 && start <= size(), return);
712 LASSERT(end > start && end <= size() + 1, return);
714 for (pos_type pos = start; pos < end; ++pos) {
715 switch (lookupChange(pos).type) {
716 case Change::UNCHANGED:
717 // reject changes in nested inset
718 if (Inset * inset = getInset(pos))
719 inset->rejectChanges();
722 case Change::INSERTED:
723 // Suppress access to non-existent
724 // "end-of-paragraph char"
726 eraseChar(pos, false);
732 case Change::DELETED:
733 d->changes_.set(Change(Change::UNCHANGED), pos);
735 // Do NOT reject changes within a deleted inset!
736 // There may be insertions of a co-author inside of it!
744 void Paragraph::Private::insertChar(pos_type pos, char_type c,
745 Change const & change)
747 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
750 changes_.insert(change, pos);
752 // This is actually very common when parsing buffers (and
753 // maybe inserting ascii text)
754 if (pos == pos_type(text_.size())) {
755 // when appending characters, no need to update tables
757 // but we want spell checking
758 requestSpellCheck(pos);
762 text_.insert(text_.begin() + pos, c);
764 // Update the font table.
765 fontlist_.increasePosAfterPos(pos);
768 insetlist_.increasePosAfterPos(pos);
770 // Update list of misspelled positions
771 speller_state_.increasePosAfterPos(pos);
775 bool Paragraph::insertInset(pos_type pos, Inset * inset,
776 Font const & font, Change const & change)
778 LASSERT(inset, return false);
779 LASSERT(pos >= 0 && pos <= size(), return false);
781 // Paragraph::insertInset() can be used in cut/copy/paste operation where
782 // d->inset_owner_ is not set yet.
783 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
786 d->insertChar(pos, META_INSET, change);
787 LASSERT(d->text_[pos] == META_INSET, return false);
789 // Add a new entry in the insetlist_.
790 d->insetlist_.insert(inset, pos);
792 // Some insets require run of spell checker
793 requestSpellCheck(pos);
799 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
801 LASSERT(pos >= 0 && pos <= size(), return false);
803 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
806 Change change = d->changes_.lookup(pos);
808 // set the character to DELETED if
809 // a) it was previously unchanged or
810 // b) it was inserted by a co-author
812 if (!change.changed() ||
813 (change.inserted() && !change.currentAuthor())) {
814 setChange(pos, Change(Change::DELETED));
815 // request run of spell checker
816 requestSpellCheck(pos);
820 if (change.deleted())
824 // Don't physically access the imaginary end-of-paragraph character.
825 // eraseChar() can only mark it as DELETED. A physical deletion of
826 // end-of-par must be handled externally.
832 d->changes_.erase(pos);
834 // if it is an inset, delete the inset entry
835 if (d->text_[pos] == META_INSET)
836 d->insetlist_.erase(pos);
838 d->text_.erase(d->text_.begin() + pos);
840 // Update the fontlist_
841 d->fontlist_.erase(pos);
843 // Update the insetlist_
844 d->insetlist_.decreasePosAfterPos(pos);
846 // Update list of misspelled positions
847 d->speller_state_.decreasePosAfterPos(pos);
848 d->speller_state_.refreshLast(size());
854 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
856 LASSERT(start >= 0 && start <= size(), return 0);
857 LASSERT(end >= start && end <= size() + 1, return 0);
860 for (pos_type count = end - start; count; --count) {
861 if (!eraseChar(i, trackChanges))
868 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
869 char_type next, OutputParams const & runparams)
871 // Writing next here may circumvent a possible font change between
872 // c and next. Since next is only output if it forms a surrogate pair
873 // with c we can ignore this:
874 // A font change inside a surrogate pair does not make sense and is
875 // hopefully impossible to input.
876 // FIXME: change tracking
877 // Is this correct WRT change tracking?
878 Encoding const & encoding = *(runparams.encoding);
879 docstring latex1 = encoding.latexChar(next).first;
880 if (runparams.inIPA) {
881 string const tipashortcut = Encodings::TIPAShortcut(next);
882 if (!tipashortcut.empty()) {
883 latex1 = from_ascii(tipashortcut);
886 docstring const latex2 = encoding.latexChar(c).first;
887 if (docstring(1, next) == latex1) {
888 // the encoding supports the combination
889 os << latex2 << latex1;
890 return latex1.length() + latex2.length();
891 } else if (runparams.local_font &&
892 runparams.local_font->language()->lang() == "polutonikogreek") {
893 // polutonikogreek only works without the brackets
894 os << latex1 << latex2;
895 return latex1.length() + latex2.length();
897 os << latex1 << '{' << latex2 << '}';
898 return latex1.length() + latex2.length() + 2;
902 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
905 unsigned int & column,
907 Layout const & style)
909 if (style.pass_thru || runparams.pass_thru)
912 if (i + 1 < int(text_.size())) {
913 char_type next = text_[i + 1];
914 if (Encodings::isCombiningChar(next)) {
915 // This space has an accent, so we must always output it.
916 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
921 if (runparams.linelen > 0
922 && column > runparams.linelen
924 && text_[i - 1] != ' '
925 && (i + 1 < int(text_.size()))
926 // same in FreeSpacing mode
927 && !owner_->isFreeSpacing()
928 // In typewriter mode, we want to avoid
929 // ! . ? : at the end of a line
930 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
931 && (text_[i - 1] == '.'
932 || text_[i - 1] == '?'
933 || text_[i - 1] == ':'
934 || text_[i - 1] == '!'))) {
936 os.texrow().start(owner_->id(), i + 1);
938 } else if (style.free_spacing) {
947 int Paragraph::Private::writeScriptChars(otexstream & os,
948 docstring const & ltx,
949 Change const & runningChange,
950 Encoding const & encoding,
953 // FIXME: modifying i here is not very nice...
955 // We only arrive here when character text_[i] could not be translated
956 // into the current latex encoding (or its latex translation has been forced,)
957 // and it belongs to a known script.
958 // TODO: We need \textcyr and \textgreek wrappers also for characters
959 // that can be encoded in the "LaTeX encoding" but not in the
960 // current *font encoding*.
961 // (See #9681 for details and test)
962 // Parameter ltx contains the latex translation of text_[i] as specified
963 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
964 // The latex macro name "textXXX" specifies the script to which text_[i]
965 // belongs and we use it in order to check whether characters from the
966 // same script immediately follow, such that we can collect them in a
967 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
968 // for the first char but only "<spec>" for all subsequent chars.
969 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
970 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
971 string script = to_ascii(ltx.substr(1, brace1 - 1));
974 bool closing_brace = true;
975 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
976 // Correct encoding is being used, so we can avoid \textgreek.
977 // TODO: wrong test: we need to check the *font encoding*
978 // (i.e. the active language and its FontEncoding tag)
979 // instead of the LaTeX *input encoding*!
980 // See #9637 for details and test-cases.
983 closing_brace = false;
985 os << ltx.substr(pos, length);
986 int size = text_.size();
987 while (i + 1 < size) {
988 char_type const next = text_[i + 1];
989 // Stop here if next character belongs to another script
990 // or there is a change in change tracking status.
991 if (!Encodings::isKnownScriptChar(next, script) ||
992 runningChange != owner_->lookupChange(i + 1))
996 FontList::const_iterator cit = fontlist_.begin();
997 FontList::const_iterator end = fontlist_.end();
998 for (; cit != end; ++cit) {
999 if (cit->pos() >= i && !found) {
1000 prev_font = cit->font();
1003 if (cit->pos() >= i + 1)
1006 // Stop here if there is a font attribute or encoding change.
1007 if (found && cit != end && prev_font != cit->font())
1009 docstring const latex = encoding.latexChar(next).first;
1010 docstring::size_type const b1 =
1011 latex.find_first_of(from_ascii("{"));
1012 docstring::size_type const b2 =
1013 latex.find_last_of(from_ascii("}"));
1014 int const len = b2 - b1 - 1;
1015 os << latex.substr(b1 + 1, len);
1019 if (closing_brace) {
1027 void Paragraph::Private::latexInset(BufferParams const & bparams,
1029 OutputParams & runparams,
1030 Font & running_font,
1032 Font const & outerfont,
1034 Change & running_change,
1035 Layout const & style,
1037 unsigned int & column)
1039 Inset * inset = owner_->getInset(i);
1042 if (style.pass_thru) {
1043 odocstringstream ods;
1044 inset->plaintext(ods, runparams);
1049 // FIXME: move this to InsetNewline::latex
1050 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1051 // newlines are handled differently here than
1052 // the default in simpleTeXSpecialChars().
1053 if (!style.newline_allowed) {
1057 bool needPar = false;
1058 column += running_font.latexWriteEndChanges(
1059 os, bparams, runparams,
1060 basefont, basefont, needPar);
1064 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1067 basefont = owner_->getLayoutFont(bparams, outerfont);
1068 running_font = basefont;
1070 if (runparams.moving_arg)
1074 os.texrow().start(owner_->id(), i + 1);
1078 if (owner_->isDeleted(i)) {
1079 if( ++runparams.inDeletedInset == 1)
1080 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1083 if (inset->canTrackChanges()) {
1084 column += Changes::latexMarkChange(os, bparams, running_change,
1085 Change(Change::UNCHANGED), runparams);
1086 running_change = Change(Change::UNCHANGED);
1090 odocstream::pos_type const len = os.os().tellp();
1092 if (inset->forceLTR()
1093 && !runparams.use_polyglossia
1094 && running_font.isRightToLeft()
1095 // ERT is an exception, it should be output with no
1096 // decorations at all
1097 && inset->lyxCode() != ERT_CODE) {
1098 if (running_font.language()->lang() == "farsi")
1099 os << "\\beginL" << termcmd;
1105 // FIXME: Bug: we can have an empty font change here!
1106 // if there has just been a font change, we are going to close it
1107 // right now, which means stupid latex code like \textsf{}. AFAIK,
1108 // this does not harm dvi output. A minor bug, thus (JMarc)
1110 // Some insets cannot be inside a font change command.
1111 // However, even such insets *can* be placed in \L or \R
1112 // or their equivalents (for RTL language switches), so we don't
1113 // close the language in those cases.
1114 // ArabTeX, though, cannot handle this special behavior, it seems.
1115 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1116 || running_font.language()->lang() == "arabic_arabtex";
1117 if (open_font && !inset->inheritFont()) {
1118 bool needPar = false;
1119 bool closeLanguage = arabtex
1120 || basefont.isRightToLeft() == running_font.isRightToLeft();
1121 unsigned int count = running_font.latexWriteEndChanges(os,
1122 bparams, runparams, basefont, basefont,
1123 needPar, closeLanguage);
1125 // if any font properties were closed, update the running_font,
1126 // making sure, however, to leave the language as it was
1128 // FIXME: probably a better way to keep track of the old
1129 // language, than copying the entire font?
1130 Font const copy_font(running_font);
1131 basefont = owner_->getLayoutFont(bparams, outerfont);
1132 running_font = basefont;
1134 running_font.setLanguage(copy_font.language());
1135 // leave font open if language is still open
1136 open_font = (running_font.language() == basefont.language());
1138 runparams.local_font = &basefont;
1142 size_t const previous_row_count = os.texrow().rows();
1145 runparams.lastid = id_;
1146 runparams.lastpos = i;
1147 inset->latex(os, runparams);
1148 } catch (EncodingException & e) {
1149 // add location information and throw again.
1156 if (running_font.language()->lang() == "farsi")
1157 os << "\\endL" << termcmd;
1162 if (os.texrow().rows() > previous_row_count) {
1163 os.texrow().start(owner_->id(), i + 1);
1166 column += (unsigned int)(os.os().tellp() - len);
1169 if (owner_->isDeleted(i))
1170 --runparams.inDeletedInset;
1174 void Paragraph::Private::latexSpecialChar(otexstream & os,
1175 BufferParams const & bparams,
1176 OutputParams const & runparams,
1177 Font const & running_font,
1178 Change const & running_change,
1179 Layout const & style,
1182 unsigned int & column)
1184 // With polyglossia, brackets and stuff need not be reversed
1185 // in RTL scripts (see bug #8251)
1186 char_type const c = (runparams.use_polyglossia) ?
1187 owner_->getUChar(bparams, i) : text_[i];
1189 if (style.pass_thru || runparams.pass_thru
1190 || contains(style.pass_thru_chars, c)
1191 || contains(runparams.pass_thru_chars, c)) {
1193 Encoding const * const enc = runparams.encoding;
1194 if (enc && !enc->encodable(c))
1195 throw EncodingException(c);
1201 // TIPA uses its own T3 encoding
1202 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1204 // If T1 font encoding is used, use the special
1205 // characters it provides.
1206 // NOTE: Some languages reset the font encoding internally to a
1207 // non-standard font encoding. If we are using such a language,
1208 // we do not output special T1 chars.
1209 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1210 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1211 && latexSpecialT1(c, os, i, column))
1213 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1214 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1215 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1218 // Otherwise, we use what LaTeX provides us.
1221 os << "\\textbackslash" << termcmd;
1225 os << "\\textless" << termcmd;
1229 os << "\\textgreater" << termcmd;
1233 os << "\\textbar" << termcmd;
1238 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1239 (end_pos == -1 || i + 1 < end_pos) &&
1240 text_[i+1] == '-') {
1241 // Prevent "--" becoming an endash and "---" becoming
1243 // Within \ttfamily, "--" is merged to "-" (no endash)
1244 // so we avoid this rather irritating ligature as well
1250 os << "\\textquotedbl" << termcmd;
1255 case '%': case '#': case '{':
1263 os << "\\textasciitilde" << termcmd;
1268 os << "\\textasciicircum" << termcmd;
1275 // avoid being mistaken for optional arguments
1283 // Blanks are printed before font switching.
1284 // Sure? I am not! (try nice-latex)
1285 // I am sure it's correct. LyX might be smarter
1286 // in the future, but for now, nothing wrong is
1292 // XeTeX's dash behaviour is determined via a global setting
1293 if (bparams.use_dash_ligatures
1294 && owner_->getFontSettings(bparams, i).fontInfo().family() != TYPEWRITER_FAMILY
1295 && (!bparams.useNonTeXFonts || runparams.flavor != OutputParams::XETEX)) {
1312 Encoding const & encoding = *(runparams.encoding);
1313 char_type next = '\0';
1314 if (i + 1 < int(text_.size())) {
1315 next = text_[i + 1];
1316 if (Encodings::isCombiningChar(next)) {
1317 column += latexSurrogatePair(os, c, next, runparams) - 1;
1323 pair<docstring, bool> latex = encoding.latexChar(c);
1324 docstring nextlatex;
1325 bool nexttipas = false;
1326 string nexttipashortcut;
1327 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1328 nextlatex = encoding.latexChar(next).first;
1329 if (runparams.inIPA) {
1330 nexttipashortcut = Encodings::TIPAShortcut(next);
1331 nexttipas = !nexttipashortcut.empty();
1335 if (runparams.inIPA) {
1336 string const tipashortcut = Encodings::TIPAShortcut(c);
1337 if (!tipashortcut.empty()) {
1338 latex.first = from_ascii(tipashortcut);
1339 latex.second = false;
1343 if (Encodings::isKnownScriptChar(c, script)
1344 && prefixIs(latex.first, from_ascii("\\" + script)))
1345 column += writeScriptChars(os, latex.first,
1346 running_change, encoding, i) - 1;
1347 else if (latex.second
1348 && ((!prefixIs(nextlatex, '\\')
1349 && !prefixIs(nextlatex, '{')
1350 && !prefixIs(nextlatex, '}'))
1352 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1354 // Prevent eating of a following
1355 // space or command corruption by
1356 // following characters
1357 if (next == ' ' || next == '\0') {
1358 column += latex.first.length() + 1;
1359 os << latex.first << "{}";
1361 column += latex.first.length();
1362 os << latex.first << " ";
1365 column += latex.first.length() - 1;
1373 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1374 pos_type i, unsigned int & column)
1380 // In T1 encoding, these characters exist
1381 // but we should avoid ligatures
1382 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1384 os << "\\textcompwordmark" << termcmd;
1391 // soul.sty breaks with \char`\"
1392 os << "\\textquotedbl" << termcmd;
1401 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1402 pos_type i, unsigned int & column)
1404 // TU encoding is currently on par with T1.
1405 return latexSpecialT1(c, os, i, column);
1409 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1410 pos_type /*i*/, unsigned int & column)
1420 os << "\\textvertline" << termcmd;
1424 os << "\\textendash" << termcmd;
1428 os << "\\textemdash" << termcmd;
1437 void Paragraph::Private::validate(LaTeXFeatures & features) const
1439 Buffer const & buf = inset_owner_->buffer();
1440 BufferParams const & bp = features.runparams().is_child
1441 ? buf.masterParams() : buf.params();
1442 if (layout_->inpreamble && inset_owner_) {
1443 bool const is_command = layout_->latextype == LATEX_COMMAND;
1445 // Using a string stream here circumvents the encoding
1446 // switching machinery of odocstream. Therefore the
1447 // output is wrong if this paragraph contains content
1448 // that needs to switch encoding.
1449 otexstringstream os;
1450 os << layout_->preamble();
1452 os << '\\' << from_ascii(layout_->latexname());
1453 // we have to provide all the optional arguments here, even though
1454 // the last one is the only one we care about.
1455 // Separate handling of optional argument inset.
1456 if (!layout_->latexargs().empty()) {
1457 OutputParams rp = features.runparams();
1458 rp.local_font = &owner_->getFirstFontSettings(bp);
1459 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1461 os << from_ascii(layout_->latexparam());
1463 size_t const length = os.length();
1464 // this will output "{" at the beginning, but not at the end
1465 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1466 if (os.length() > length) {
1469 if (!layout_->postcommandargs().empty()) {
1470 OutputParams rp = features.runparams();
1471 rp.local_font = &owner_->getFirstFontSettings(bp);
1472 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1475 features.addPreambleSnippet(os.release(), true);
1479 if (features.runparams().flavor == OutputParams::HTML
1480 && layout_->htmltitle()) {
1481 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1484 // check the params.
1485 if (!params_.spacing().isDefault())
1486 features.require("setspace");
1489 features.useLayout(layout_->name());
1492 fontlist_.validate(features);
1494 // then the indentation
1495 if (!params_.leftIndent().zero())
1496 features.require("ParagraphLeftIndent");
1499 InsetList::const_iterator icit = insetlist_.begin();
1500 InsetList::const_iterator iend = insetlist_.end();
1501 for (; icit != iend; ++icit) {
1503 features.inDeletedInset(owner_->isDeleted(icit->pos));
1504 if (icit->inset->lyxCode() == FOOT_CODE) {
1505 // FIXME: an item inset would make things much easier.
1506 if ((layout_->latextype == LATEX_LIST_ENVIRONMENT
1507 || (layout_->latextype == LATEX_ITEM_ENVIRONMENT
1508 && layout_->margintype == MARGIN_FIRST_DYNAMIC))
1509 && (icit->pos < begin_of_body_
1510 || (icit->pos == begin_of_body_
1511 && (icit->pos == 0 || text_[icit->pos - 1] != ' '))))
1512 features.saveNoteEnv("description");
1514 icit->inset->validate(features);
1515 features.inDeletedInset(false);
1516 if (layout_->needprotect &&
1517 icit->inset->lyxCode() == FOOT_CODE)
1518 features.require("NeedLyXFootnoteCode");
1522 // then the contents
1523 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1524 char_type c = text_[i];
1526 if (features.runparams().isFullUnicode() && bp.useNonTeXFonts)
1527 features.require("textquotedblp");
1528 else if (bp.main_font_encoding() != "T1"
1529 || ((&owner_->getFontSettings(bp, i))->language()->internalFontEncoding()))
1530 features.require("textquotedbl");
1532 if (!bp.use_dash_ligatures
1533 && (c == 0x2013 || c == 0x2014)
1534 && bp.useNonTeXFonts
1535 && features.runparams().flavor == OutputParams::XETEX)
1536 // XeTeX's dash behaviour is determined via a global setting
1537 features.require("xetexdashbreakstate");
1538 BufferEncodings::validate(c, features);
1542 /////////////////////////////////////////////////////////////////////
1546 /////////////////////////////////////////////////////////////////////
1549 Layout const emptyParagraphLayout;
1552 Paragraph::Paragraph()
1553 : d(new Paragraph::Private(this, emptyParagraphLayout))
1560 Paragraph::Paragraph(Paragraph const & par)
1561 : itemdepth(par.itemdepth),
1562 d(new Paragraph::Private(*par.d, this))
1568 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1569 : itemdepth(par.itemdepth),
1570 d(new Paragraph::Private(*par.d, this, beg, end))
1576 Paragraph & Paragraph::operator=(Paragraph const & par)
1578 // needed as we will destroy the private part before copying it
1580 itemdepth = par.itemdepth;
1584 d = new Private(*par.d, this);
1591 Paragraph::~Paragraph()
1600 // this shall be called just before every "os << ..." action.
1601 void flushString(ostream & os, docstring & s)
1610 void Paragraph::write(ostream & os, BufferParams const & bparams,
1611 depth_type & dth) const
1613 // The beginning or end of a deeper (i.e. nested) area?
1614 if (dth != d->params_.depth()) {
1615 if (d->params_.depth() > dth) {
1616 while (d->params_.depth() > dth) {
1617 os << "\n\\begin_deeper";
1621 while (d->params_.depth() < dth) {
1622 os << "\n\\end_deeper";
1628 // First write the layout
1629 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1631 d->params_.write(os);
1633 Font font1(inherit_font, bparams.language);
1635 Change running_change = Change(Change::UNCHANGED);
1637 // this string is used as a buffer to avoid repetitive calls
1638 // to to_utf8(), which turn out to be expensive (JMarc)
1639 docstring write_buffer;
1642 for (pos_type i = 0; i <= size(); ++i) {
1644 Change const & change = lookupChange(i);
1645 if (change != running_change)
1646 flushString(os, write_buffer);
1647 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1648 running_change = change;
1653 // Write font changes
1654 Font font2 = getFontSettings(bparams, i);
1655 if (font2 != font1) {
1656 flushString(os, write_buffer);
1657 font2.lyxWriteChanges(font1, os);
1662 char_type const c = d->text_[i];
1665 if (Inset const * inset = getInset(i)) {
1666 flushString(os, write_buffer);
1667 if (inset->directWrite()) {
1668 // international char, let it write
1669 // code directly so it's shorter in
1675 os << "\\begin_inset ";
1677 os << "\n\\end_inset\n\n";
1680 // FIXME This can be removed again once the mystery
1681 // crash has been resolved.
1686 flushString(os, write_buffer);
1687 os << "\n\\backslash\n";
1691 flushString(os, write_buffer);
1692 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1699 if ((column > 70 && c == ' ')
1701 flushString(os, write_buffer);
1705 // this check is to amend a bug. LyX sometimes
1706 // inserts '\0' this could cause problems.
1708 write_buffer.push_back(c);
1710 LYXERR0("NUL char in structure.");
1716 flushString(os, write_buffer);
1717 os << "\n\\end_layout\n";
1718 // FIXME This can be removed again once the mystery
1719 // crash has been resolved.
1724 void Paragraph::validate(LaTeXFeatures & features) const
1726 d->validate(features);
1730 void Paragraph::insert(pos_type start, docstring const & str,
1731 Font const & font, Change const & change)
1733 for (size_t i = 0, n = str.size(); i != n ; ++i)
1734 insertChar(start + i, str[i], font, change);
1738 void Paragraph::appendChar(char_type c, Font const & font,
1739 Change const & change)
1742 d->changes_.insert(change, d->text_.size());
1743 // when appending characters, no need to update tables
1744 d->text_.push_back(c);
1745 setFont(d->text_.size() - 1, font);
1746 d->requestSpellCheck(d->text_.size() - 1);
1750 void Paragraph::appendString(docstring const & s, Font const & font,
1751 Change const & change)
1753 pos_type end = s.size();
1754 size_t oldsize = d->text_.size();
1755 size_t newsize = oldsize + end;
1756 size_t capacity = d->text_.capacity();
1757 if (newsize >= capacity)
1758 d->text_.reserve(max(capacity + 100, newsize));
1760 // when appending characters, no need to update tables
1763 // FIXME: Optimize this!
1764 for (size_t i = oldsize; i != newsize; ++i) {
1766 d->changes_.insert(change, i);
1767 d->requestSpellCheck(i);
1769 d->fontlist_.set(oldsize, font);
1770 d->fontlist_.set(newsize - 1, font);
1774 void Paragraph::insertChar(pos_type pos, char_type c,
1777 d->insertChar(pos, c, Change(trackChanges ?
1778 Change::INSERTED : Change::UNCHANGED));
1782 void Paragraph::insertChar(pos_type pos, char_type c,
1783 Font const & font, bool trackChanges)
1785 d->insertChar(pos, c, Change(trackChanges ?
1786 Change::INSERTED : Change::UNCHANGED));
1791 void Paragraph::insertChar(pos_type pos, char_type c,
1792 Font const & font, Change const & change)
1794 d->insertChar(pos, c, change);
1799 void Paragraph::resetFonts(Font const & font)
1801 d->fontlist_.clear();
1802 d->fontlist_.set(0, font);
1803 d->fontlist_.set(d->text_.size() - 1, font);
1806 // Gets uninstantiated font setting at position.
1807 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1811 LYXERR0("pos: " << pos << " size: " << size());
1815 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1816 if (cit != d->fontlist_.end())
1819 if (pos == size() && !empty())
1820 return getFontSettings(bparams, pos - 1);
1822 // Optimisation: avoid a full font instantiation if there is no
1823 // language change from previous call.
1824 static Font previous_font;
1825 static Language const * previous_lang = 0;
1826 Language const * lang = getParLanguage(bparams);
1827 if (lang != previous_lang) {
1828 previous_lang = lang;
1829 previous_font = Font(inherit_font, lang);
1831 return previous_font;
1835 FontSpan Paragraph::fontSpan(pos_type pos) const
1837 LBUFERR(pos <= size());
1840 return FontSpan(pos, pos);
1843 FontList::const_iterator cit = d->fontlist_.begin();
1844 FontList::const_iterator end = d->fontlist_.end();
1845 for (; cit != end; ++cit) {
1846 if (cit->pos() >= pos) {
1847 if (pos >= beginOfBody())
1848 return FontSpan(max(start, beginOfBody()),
1851 return FontSpan(start,
1852 min(beginOfBody() - 1,
1855 start = cit->pos() + 1;
1858 // This should not happen, but if so, we take no chances.
1859 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1860 LASSERT(false, return FontSpan(pos, pos));
1864 // Gets uninstantiated font setting at position 0
1865 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1867 if (!empty() && !d->fontlist_.empty())
1868 return d->fontlist_.begin()->font();
1870 // Optimisation: avoid a full font instantiation if there is no
1871 // language change from previous call.
1872 static Font previous_font;
1873 static Language const * previous_lang = 0;
1874 if (bparams.language != previous_lang) {
1875 previous_lang = bparams.language;
1876 previous_font = Font(inherit_font, bparams.language);
1879 return previous_font;
1883 // Gets the fully instantiated font at a given position in a paragraph
1884 // This is basically the same function as Text::GetFont() in text2.cpp.
1885 // The difference is that this one is used for generating the LaTeX file,
1886 // and thus cosmetic "improvements" are disallowed: This has to deliver
1887 // the true picture of the buffer. (Asger)
1888 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1889 Font const & outerfont) const
1893 Font font = getFontSettings(bparams, pos);
1895 pos_type const body_pos = beginOfBody();
1896 FontInfo & fi = font.fontInfo();
1898 fi.realize(d->layout_->labelfont);
1900 fi.realize(d->layout_->font);
1902 fi.realize(outerfont.fontInfo());
1903 fi.realize(bparams.getFont().fontInfo());
1909 Font const Paragraph::getLabelFont
1910 (BufferParams const & bparams, Font const & outerfont) const
1912 FontInfo tmpfont = d->layout_->labelfont;
1913 tmpfont.realize(outerfont.fontInfo());
1914 tmpfont.realize(bparams.getFont().fontInfo());
1915 return Font(tmpfont, getParLanguage(bparams));
1919 Font const Paragraph::getLayoutFont
1920 (BufferParams const & bparams, Font const & outerfont) const
1922 FontInfo tmpfont = d->layout_->font;
1923 tmpfont.realize(outerfont.fontInfo());
1924 tmpfont.realize(bparams.getFont().fontInfo());
1925 return Font(tmpfont, getParLanguage(bparams));
1929 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1931 char_type c = d->text_[pos];
1932 if (!getFontSettings(bparams, pos).isRightToLeft())
1935 // FIXME: The arabic special casing is due to the difference of arabic
1936 // round brackets input introduced in r18599. Check if this should be
1937 // unified with Hebrew or at least if all bracket types should be
1938 // handled the same (file format change in either case).
1939 string const & lang = getFontSettings(bparams, pos).language()->lang();
1940 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1945 uc = arabic ? c : ')';
1948 uc = arabic ? c : '(';
1974 void Paragraph::setFont(pos_type pos, Font const & font)
1976 LASSERT(pos <= size(), return);
1978 // First, reduce font against layout/label font
1979 // Update: The setCharFont() routine in text2.cpp already
1980 // reduces font, so we don't need to do that here. (Asger)
1982 d->fontlist_.set(pos, font);
1986 void Paragraph::makeSameLayout(Paragraph const & par)
1988 d->layout_ = par.d->layout_;
1989 d->params_ = par.d->params_;
1993 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1995 if (isFreeSpacing())
2001 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
2002 if (eraseChar(pos, trackChanges))
2008 return count > 0 || pos > 0;
2012 bool Paragraph::hasSameLayout(Paragraph const & par) const
2014 return par.d->layout_ == d->layout_
2015 && d->params_.sameLayout(par.d->params_);
2019 depth_type Paragraph::getDepth() const
2021 return d->params_.depth();
2025 depth_type Paragraph::getMaxDepthAfter() const
2027 if (d->layout_->isEnvironment())
2028 return d->params_.depth() + 1;
2030 return d->params_.depth();
2034 LyXAlignment Paragraph::getAlign() const
2036 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2037 return d->layout_->align;
2039 return d->params_.align();
2043 docstring const & Paragraph::labelString() const
2045 return d->params_.labelString();
2049 // the next two functions are for the manual labels
2050 docstring const Paragraph::getLabelWidthString() const
2052 if (d->layout_->margintype == MARGIN_MANUAL
2053 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2054 return d->params_.labelWidthString();
2056 return _("Senseless with this layout!");
2060 void Paragraph::setLabelWidthString(docstring const & s)
2062 d->params_.labelWidthString(s);
2066 docstring Paragraph::expandLabel(Layout const & layout,
2067 BufferParams const & bparams) const
2069 return expandParagraphLabel(layout, bparams, true);
2073 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2074 BufferParams const & bparams) const
2076 return expandParagraphLabel(layout, bparams, false);
2080 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2081 BufferParams const & bparams, bool process_appendix) const
2083 DocumentClass const & tclass = bparams.documentClass();
2084 string const & lang = getParLanguage(bparams)->code();
2085 bool const in_appendix = process_appendix && d->params_.appendix();
2086 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2088 if (fmt.empty() && !layout.counter.empty())
2089 return tclass.counters().theCounter(layout.counter, lang);
2091 // handle 'inherited level parts' in 'fmt',
2092 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2093 size_t const i = fmt.find('@', 0);
2094 if (i != docstring::npos) {
2095 size_t const j = fmt.find('@', i + 1);
2096 if (j != docstring::npos) {
2097 docstring parent(fmt, i + 1, j - i - 1);
2098 docstring label = from_ascii("??");
2099 if (tclass.hasLayout(parent))
2100 label = expandParagraphLabel(tclass[parent], bparams,
2102 fmt = docstring(fmt, 0, i) + label
2103 + docstring(fmt, j + 1, docstring::npos);
2107 return tclass.counters().counterLabel(fmt, lang);
2111 void Paragraph::applyLayout(Layout const & new_layout)
2113 d->layout_ = &new_layout;
2114 LyXAlignment const oldAlign = d->params_.align();
2116 if (!(oldAlign & d->layout_->alignpossible)) {
2117 frontend::Alert::warning(_("Alignment not permitted"),
2118 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2119 d->params_.align(LYX_ALIGN_LAYOUT);
2124 pos_type Paragraph::beginOfBody() const
2126 return d->begin_of_body_;
2130 void Paragraph::setBeginOfBody()
2132 if (d->layout_->labeltype != LABEL_MANUAL) {
2133 d->begin_of_body_ = 0;
2137 // Unroll the first two cycles of the loop
2138 // and remember the previous character to
2139 // remove unnecessary getChar() calls
2141 pos_type end = size();
2142 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2145 char_type previous_char = d->text_[i];
2146 if (!(isNewline(i) || isEnvSeparator(i))) {
2148 while (i < end && previous_char != ' ') {
2149 char_type temp = d->text_[i];
2150 if (isNewline(i) || isEnvSeparator(i))
2153 previous_char = temp;
2159 d->begin_of_body_ = i;
2163 bool Paragraph::allowParagraphCustomization() const
2165 return inInset().allowParagraphCustomization();
2169 bool Paragraph::usePlainLayout() const
2171 return inInset().usePlainLayout();
2175 bool Paragraph::isPassThru() const
2177 return inInset().isPassThru() || d->layout_->pass_thru;
2182 // paragraphs inside floats need different alignment tags to avoid
2185 bool noTrivlistCentering(InsetCode code)
2187 return code == FLOAT_CODE
2188 || code == WRAP_CODE
2189 || code == CELL_CODE;
2193 string correction(string const & orig)
2195 if (orig == "flushleft")
2196 return "raggedright";
2197 if (orig == "flushright")
2198 return "raggedleft";
2199 if (orig == "center")
2205 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2206 InsetCode code, bool const lastpar, int & col)
2208 string macro = suffix + "{";
2209 if (noTrivlistCentering(code)) {
2211 // the last paragraph in non-trivlist-aligned
2212 // context is special (to avoid unwanted whitespace)
2213 if (suffix == "\\begin") {
2214 macro = "\\" + correction(env) + "{}";
2215 os << from_ascii(macro);
2216 col += macro.size();
2221 macro += correction(env);
2225 if (suffix == "\\par\\end") {
2229 os << from_ascii(macro);
2230 col += macro.size();
2231 if (suffix == "\\begin") {
2241 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2242 otexstream & os, OutputParams const & runparams) const
2247 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2248 (layout_->toggle_indent != ITOGGLE_NEVER) :
2249 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2251 if (canindent && params_.noindent() && !layout_->pass_thru) {
2252 os << "\\noindent ";
2256 LyXAlignment const curAlign = params_.align();
2258 if (curAlign == layout_->align)
2262 case LYX_ALIGN_NONE:
2263 case LYX_ALIGN_BLOCK:
2264 case LYX_ALIGN_LAYOUT:
2265 case LYX_ALIGN_SPECIAL:
2266 case LYX_ALIGN_DECIMAL:
2268 case LYX_ALIGN_LEFT:
2269 case LYX_ALIGN_RIGHT:
2270 case LYX_ALIGN_CENTER:
2271 if (runparams.moving_arg) {
2278 string const begin_tag = "\\begin";
2279 InsetCode code = ownerCode();
2280 bool const lastpar = runparams.isLastPar;
2283 case LYX_ALIGN_NONE:
2284 case LYX_ALIGN_BLOCK:
2285 case LYX_ALIGN_LAYOUT:
2286 case LYX_ALIGN_SPECIAL:
2287 case LYX_ALIGN_DECIMAL:
2289 case LYX_ALIGN_LEFT: {
2290 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2291 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2293 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2295 } case LYX_ALIGN_RIGHT: {
2296 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2297 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2299 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2301 } case LYX_ALIGN_CENTER: {
2302 corrected_env(os, begin_tag, "center", code, lastpar, column);
2311 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2312 otexstream & os, OutputParams const & runparams) const
2314 LyXAlignment const curAlign = params_.align();
2316 if (curAlign == layout_->align)
2320 case LYX_ALIGN_NONE:
2321 case LYX_ALIGN_BLOCK:
2322 case LYX_ALIGN_LAYOUT:
2323 case LYX_ALIGN_SPECIAL:
2324 case LYX_ALIGN_DECIMAL:
2326 case LYX_ALIGN_LEFT:
2327 case LYX_ALIGN_RIGHT:
2328 case LYX_ALIGN_CENTER:
2329 if (runparams.moving_arg)
2334 bool output = false;
2336 string const end_tag = "\\par\\end";
2337 InsetCode code = ownerCode();
2338 bool const lastpar = runparams.isLastPar;
2341 case LYX_ALIGN_NONE:
2342 case LYX_ALIGN_BLOCK:
2343 case LYX_ALIGN_LAYOUT:
2344 case LYX_ALIGN_SPECIAL:
2345 case LYX_ALIGN_DECIMAL:
2347 case LYX_ALIGN_LEFT: {
2348 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2349 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2351 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2353 } case LYX_ALIGN_RIGHT: {
2354 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2355 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2357 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2359 } case LYX_ALIGN_CENTER: {
2360 corrected_env(os, end_tag, "center", code, lastpar, col);
2365 return output || lastpar;
2369 // This one spits out the text of the paragraph
2370 void Paragraph::latex(BufferParams const & bparams,
2371 Font const & outerfont,
2373 OutputParams const & runparams,
2374 int start_pos, int end_pos, bool force) const
2376 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2378 // FIXME This check should not be needed. Perhaps issue an
2379 // error if it triggers.
2380 Layout const & style = inInset().forcePlainLayout() ?
2381 bparams.documentClass().plainLayout() : *d->layout_;
2383 if (!force && style.inpreamble)
2386 bool const allowcust = allowParagraphCustomization();
2388 // Current base font for all inherited font changes, without any
2389 // change caused by an individual character, except for the language:
2390 // It is set to the language of the first character.
2391 // As long as we are in the label, this font is the base font of the
2392 // label. Before the first body character it is set to the base font
2396 // Maybe we have to create a optional argument.
2397 pos_type body_pos = beginOfBody();
2398 unsigned int column = 0;
2401 // the optional argument is kept in curly brackets in
2402 // case it contains a ']'
2403 // This is not strictly needed, but if this is changed it
2404 // would be a file format change, and tex2lyx would need
2405 // to be adjusted, since it unconditionally removes the
2406 // braces when it parses \item.
2409 basefont = getLabelFont(bparams, outerfont);
2411 basefont = getLayoutFont(bparams, outerfont);
2414 // Which font is currently active?
2415 Font running_font(basefont);
2416 // Do we have an open font change?
2417 bool open_font = false;
2419 Change runningChange = Change(Change::UNCHANGED);
2421 Encoding const * const prev_encoding = runparams.encoding;
2423 os.texrow().start(id(), 0);
2425 // if the paragraph is empty, the loop will not be entered at all
2427 // For InTitle commands, we have already opened a group
2428 // in output_latex::TeXOnePar.
2429 if (style.isCommand() && (!style.intitle || style.inpreamble)) {
2433 if (!style.leftdelim().empty()) {
2434 os << style.leftdelim();
2435 column += style.leftdelim().size();
2438 column += d->startTeXParParams(bparams, os, runparams);
2441 // Whether a \par can be issued for insets typeset inline with text.
2442 // Yes if greater than 0. This has to be static.
2443 THREAD_LOCAL_STATIC int parInline = 0;
2445 for (pos_type i = 0; i < size(); ++i) {
2446 // First char in paragraph or after label?
2447 if (i == body_pos) {
2450 bool needPar = false;
2451 column += running_font.latexWriteEndChanges(
2452 os, bparams, runparams,
2453 basefont, basefont, needPar);
2456 basefont = getLayoutFont(bparams, outerfont);
2457 running_font = basefont;
2459 column += Changes::latexMarkChange(os, bparams,
2460 runningChange, Change(Change::UNCHANGED),
2462 runningChange = Change(Change::UNCHANGED);
2467 // For InTitle commands, we have already opened a group
2468 // in output_latex::TeXOnePar.
2469 if (style.isCommand() && (!style.intitle || style.inpreamble)) {
2474 if (!style.leftdelim().empty()) {
2475 os << style.leftdelim();
2476 column += style.leftdelim().size();
2480 column += d->startTeXParParams(bparams, os,
2484 runparams.wasDisplayMath = runparams.inDisplayMath;
2485 runparams.inDisplayMath = false;
2486 bool deleted_display_math = false;
2487 Change const & change = runparams.inDeletedInset
2488 ? runparams.changeOfDeletedInset : lookupChange(i);
2490 // Check whether a display math inset follows
2491 if (d->text_[i] == META_INSET
2492 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2493 InsetMath const * im = getInset(i)->asInsetMath();
2494 if (im && im->asHullInset()
2495 && im->asHullInset()->outerDisplay()) {
2496 runparams.inDisplayMath = true;
2497 // runparams.inDeletedInset will be set by
2498 // latexInset later, but we need this info
2499 // before it is called. On the other hand, we
2500 // cannot set it here because it is a counter.
2501 deleted_display_math = isDeleted(i);
2503 if (bparams.output_changes && deleted_display_math
2504 && runningChange == change
2505 && change.type == Change::DELETED
2506 && !os.afterParbreak()) {
2507 // A display math in the same paragraph follows.
2508 // We have to close and then reopen \lyxdeleted,
2509 // otherwise the math will be shifted up.
2510 OutputParams rp = runparams;
2512 bool needPar = false;
2513 column += running_font.latexWriteEndChanges(
2514 os, bparams, rp, basefont,
2518 basefont = getLayoutFont(bparams, outerfont);
2519 running_font = basefont;
2520 column += Changes::latexMarkChange(os, bparams,
2521 Change(Change::INSERTED), change, rp);
2525 if (bparams.output_changes && runningChange != change) {
2527 bool needPar = false;
2528 column += running_font.latexWriteEndChanges(
2529 os, bparams, runparams,
2530 basefont, basefont, needPar);
2533 basefont = getLayoutFont(bparams, outerfont);
2534 running_font = basefont;
2535 column += Changes::latexMarkChange(os, bparams, runningChange,
2537 runningChange = change;
2540 // do not output text which is marked deleted
2541 // if change tracking output is disabled
2542 if (!bparams.output_changes && change.deleted()) {
2548 // Fully instantiated font
2549 Font const current_font = getFont(bparams, i, outerfont);
2551 Font const last_font = running_font;
2553 // Do we need to close the previous font?
2555 (current_font != running_font ||
2556 current_font.language() != running_font.language()))
2558 bool needPar = false;
2559 column += running_font.latexWriteEndChanges(
2560 os, bparams, runparams, basefont,
2561 (i == body_pos-1) ? basefont : current_font,
2563 running_font = basefont;
2567 string const running_lang = runparams.use_polyglossia ?
2568 running_font.language()->polyglossia() : running_font.language()->babel();
2569 // close babel's font environment before opening CJK.
2570 string const lang_end_command = runparams.use_polyglossia ?
2571 "\\end{$$lang}" : lyxrc.language_command_end;
2572 bool const using_begin_end = runparams.use_polyglossia ||
2573 !lang_end_command.empty();
2574 if (!running_lang.empty() &&
2575 (!using_begin_end || running_lang == openLanguageName()) &&
2576 current_font.language()->encoding()->package() == Encoding::CJK) {
2577 string end_tag = subst(lang_end_command,
2580 os << from_ascii(end_tag);
2581 column += end_tag.length();
2582 if (using_begin_end)
2586 // Switch file encoding if necessary (and allowed)
2587 if (!runparams.pass_thru && !style.pass_thru &&
2588 runparams.encoding->package() != Encoding::none &&
2589 current_font.language()->encoding()->package() != Encoding::none) {
2590 pair<bool, int> const enc_switch =
2591 switchEncoding(os.os(), bparams, runparams,
2592 *(current_font.language()->encoding()));
2593 if (enc_switch.first) {
2594 column += enc_switch.second;
2595 runparams.encoding = current_font.language()->encoding();
2599 char_type const c = d->text_[i];
2601 // A display math inset inside an ulem command will be output
2602 // as a box of width \linewidth, so we have to either disable
2603 // indentation if the inset starts a paragraph, or start a new
2604 // line to accommodate such box. This has to be done before
2605 // writing any font changing commands.
2606 if (runparams.inDisplayMath && !deleted_display_math
2607 && runparams.inulemcmd) {
2608 if (os.afterParbreak())
2614 // Do we need to change font?
2615 if ((current_font != running_font ||
2616 current_font.language() != running_font.language()) &&
2619 odocstringstream ods;
2620 column += current_font.latexWriteStartChanges(ods, bparams,
2621 runparams, basefont,
2623 // Check again for display math in ulem commands as a
2624 // font change may also occur just before a math inset.
2625 if (runparams.inDisplayMath && !deleted_display_math
2626 && runparams.inulemcmd) {
2627 if (os.afterParbreak())
2632 running_font = current_font;
2634 docstring fontchange = ods.str();
2635 // check whether the fontchange ends with a \\textcolor
2636 // modifier and the text starts with a space (bug 4473)
2637 docstring const last_modifier = rsplit(fontchange, '\\');
2638 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2639 os << fontchange << from_ascii("{}");
2640 // check if the fontchange ends with a trailing blank
2641 // (like "\small " (see bug 3382)
2642 else if (suffixIs(fontchange, ' ') && c == ' ')
2643 os << fontchange.substr(0, fontchange.size() - 1)
2644 << from_ascii("{}");
2649 // FIXME: think about end_pos implementation...
2650 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2651 // FIXME: integrate this case in latexSpecialChar
2652 // Do not print the separation of the optional argument
2653 // if style.pass_thru is false. This works because
2654 // latexSpecialChar ignores spaces if
2655 // style.pass_thru is false.
2656 if (i != body_pos - 1) {
2657 if (d->simpleTeXBlanks(runparams, os,
2658 i, column, current_font, style)) {
2659 // A surrogate pair was output. We
2660 // must not call latexSpecialChar
2661 // in this iteration, since it would output
2662 // the combining character again.
2669 OutputParams rp = runparams;
2670 rp.free_spacing = style.free_spacing;
2671 rp.local_font = ¤t_font;
2672 rp.intitle = style.intitle;
2674 // Two major modes: LaTeX or plain
2675 // Handle here those cases common to both modes
2676 // and then split to handle the two modes separately.
2677 if (c == META_INSET) {
2678 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2679 // Greyedout notes and, in general, all insets
2680 // with InsetLayout::isDisplay() == false,
2681 // are typeset inline with the text. So, we
2682 // can add a \par to the last paragraph of
2683 // such insets only if nothing else follows.
2684 bool incremented = false;
2685 Inset const * inset = getInset(i);
2686 InsetText const * textinset = inset
2687 ? inset->asInsetText()
2689 if (i + 1 == size() && textinset
2690 && !inset->getLayout().isDisplay()) {
2691 ParagraphList const & pars =
2692 textinset->text().paragraphs();
2693 pit_type const pit = pars.size() - 1;
2694 Font const last_font =
2695 pit < 0 || pars[pit].empty()
2696 ? pars[pit].getLayoutFont(
2699 : pars[pit].getFont(bparams,
2700 pars[pit].size() - 1,
2702 if (last_font.fontInfo().size() !=
2703 basefont.fontInfo().size()) {
2708 d->latexInset(bparams, os, rp, running_font,
2709 basefont, outerfont, open_font,
2710 runningChange, style, i, column);
2714 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2716 d->latexSpecialChar(os, bparams, rp,
2717 running_font, runningChange,
2718 style, i, end_pos, column);
2719 } catch (EncodingException & e) {
2720 if (runparams.dryrun) {
2721 os << "<" << _("LyX Warning: ")
2722 << _("uncodable character") << " '";
2726 // add location information and throw again.
2734 // Set the encoding to that returned from latexSpecialChar (see
2735 // comment for encoding member in OutputParams.h)
2736 runparams.encoding = rp.encoding;
2738 // Also carry on the info on a closed ulem command for insets
2739 // such as Note that do not produce any output, so that no
2740 // command is ever executed but its opening was recorded.
2741 runparams.inulemcmd = rp.inulemcmd;
2744 // If we have an open font definition, we have to close it
2746 // Make sure that \\par is done with the font of the last
2747 // character if this has another size as the default.
2748 // This is necessary because LaTeX (and LyX on the screen)
2749 // calculates the space between the baselines according
2750 // to this font. (Matthias)
2752 // We must not change the font for the last paragraph
2753 // of non-multipar insets, tabular cells or commands,
2754 // since this produces unwanted whitespace.
2756 Font const font = empty()
2757 ? getLayoutFont(bparams, outerfont)
2758 : getFont(bparams, size() - 1, outerfont);
2760 InsetText const * textinset = inInset().asInsetText();
2762 bool const maintext = textinset
2763 ? textinset->text().isMainText()
2766 size_t const numpars = textinset
2767 ? textinset->text().paragraphs().size()
2770 bool needPar = false;
2772 if (style.resfont.size() != font.fontInfo().size()
2773 && (!runparams.isLastPar || maintext
2774 || (numpars > 1 && d->ownerCode() != CELL_CODE
2775 && (inInset().getLayout().isDisplay()
2777 && !style.isCommand()) {
2780 #ifdef FIXED_LANGUAGE_END_DETECTION
2782 running_font.latexWriteEndChanges(os, bparams,
2783 runparams, basefont,
2784 next_->getFont(bparams, 0, outerfont),
2787 running_font.latexWriteEndChanges(os, bparams,
2788 runparams, basefont, basefont, needPar);
2791 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2792 //FIXME: there as we start another \selectlanguage with the next paragraph if
2793 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2794 running_font.latexWriteEndChanges(os, bparams, runparams,
2795 basefont, basefont, needPar);
2798 // The \par could not be inserted at the same nesting
2799 // level of the font size change, so do it now.
2800 os << "{\\" << font.latexSize() << "\\par}";
2804 column += Changes::latexMarkChange(os, bparams, runningChange,
2805 Change(Change::UNCHANGED), runparams);
2807 // Needed if there is an optional argument but no contents.
2808 if (body_pos > 0 && body_pos == size()) {
2812 if (!style.rightdelim().empty()) {
2813 os << style.rightdelim();
2814 column += style.rightdelim().size();
2817 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2818 && runparams.encoding != prev_encoding) {
2819 runparams.encoding = prev_encoding;
2820 os << setEncoding(prev_encoding->iconvName());
2823 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2827 bool Paragraph::emptyTag() const
2829 for (pos_type i = 0; i < size(); ++i) {
2830 if (Inset const * inset = getInset(i)) {
2831 InsetCode lyx_code = inset->lyxCode();
2832 // FIXME testing like that is wrong. What is
2834 if (lyx_code != TOC_CODE &&
2835 lyx_code != INCLUDE_CODE &&
2836 lyx_code != GRAPHICS_CODE &&
2837 lyx_code != ERT_CODE &&
2838 lyx_code != LISTINGS_CODE &&
2839 lyx_code != FLOAT_CODE &&
2840 lyx_code != TABULAR_CODE) {
2844 char_type c = d->text_[i];
2845 if (c != ' ' && c != '\t')
2853 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2856 for (pos_type i = 0; i < size(); ++i) {
2857 if (Inset const * inset = getInset(i)) {
2858 InsetCode lyx_code = inset->lyxCode();
2859 if (lyx_code == LABEL_CODE) {
2860 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2861 docstring const & id = il->getParam("name");
2862 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2870 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2874 for (i = 0; i < size(); ++i) {
2875 if (Inset const * inset = getInset(i)) {
2876 inset->docbook(os, runparams);
2878 char_type c = d->text_[i];
2881 os << sgml::escapeChar(c);
2888 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2892 for (i = 0; i < size(); ++i) {
2893 if (Inset const * inset = getInset(i)) {
2894 inset->xhtml(xs, runparams);
2896 char_type c = d->text_[i];
2906 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2909 pos_type size = text_.size();
2910 for (pos_type i = initial; i < size; ++i) {
2911 Font font = owner_->getFont(buf.params(), i, outerfont);
2912 if (text_[i] == META_INSET)
2914 if (i != initial && font != font_old)
2923 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2925 OutputParams const & runparams,
2926 Font const & outerfont,
2927 pos_type initial) const
2929 bool emph_flag = false;
2931 Layout const & style = *d->layout_;
2933 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2935 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2938 // parsing main loop
2939 for (pos_type i = initial; i < size(); ++i) {
2940 Font font = getFont(buf.params(), i, outerfont);
2942 // handle <emphasis> tag
2943 if (font_old.emph() != font.fontInfo().emph()) {
2944 if (font.fontInfo().emph() == FONT_ON) {
2947 } else if (i != initial) {
2948 os << "</emphasis>";
2953 if (Inset const * inset = getInset(i)) {
2954 inset->docbook(os, runparams);
2956 char_type c = d->text_[i];
2958 if (style.pass_thru)
2961 os << sgml::escapeChar(c);
2963 font_old = font.fontInfo();
2967 os << "</emphasis>";
2970 if (style.free_spacing)
2972 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2978 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2979 vector<html::EndFontTag> & tagsToClose,
2980 bool & flag, FontState curstate, html::FontTypes type)
2982 if (curstate == FONT_ON) {
2983 tagsToOpen.push_back(html::FontTag(type));
2986 tagsToClose.push_back(html::EndFontTag(type));
2993 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2995 OutputParams const & runparams,
2996 Font const & outerfont,
2997 bool start_paragraph, bool close_paragraph,
2998 pos_type initial) const
3002 // track whether we have opened these tags
3003 bool emph_flag = false;
3004 bool bold_flag = false;
3005 bool noun_flag = false;
3006 bool ubar_flag = false;
3007 bool dbar_flag = false;
3008 bool sout_flag = false;
3009 bool xout_flag = false;
3010 bool wave_flag = false;
3012 bool shap_flag = false;
3014 bool faml_flag = false;
3016 bool size_flag = false;
3018 Layout const & style = *d->layout_;
3020 if (start_paragraph)
3021 xs.startDivision(allowEmpty());
3024 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
3026 FontShape curr_fs = INHERIT_SHAPE;
3027 FontFamily curr_fam = INHERIT_FAMILY;
3028 FontSize curr_size = FONT_SIZE_INHERIT;
3030 string const default_family =
3031 buf.masterBuffer()->params().fonts_default_family;
3033 vector<html::FontTag> tagsToOpen;
3034 vector<html::EndFontTag> tagsToClose;
3036 // parsing main loop
3037 for (pos_type i = initial; i < size(); ++i) {
3038 // let's not show deleted material in the output
3042 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
3045 FontState curstate = font.fontInfo().emph();
3046 if (font_old.emph() != curstate)
3047 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
3050 curstate = font.fontInfo().noun();
3051 if (font_old.noun() != curstate)
3052 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
3055 curstate = font.fontInfo().underbar();
3056 if (font_old.underbar() != curstate)
3057 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
3060 curstate = font.fontInfo().strikeout();
3061 if (font_old.strikeout() != curstate)
3062 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
3065 curstate = font.fontInfo().xout();
3066 if (font_old.xout() != curstate)
3067 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
3070 curstate = font.fontInfo().uuline();
3071 if (font_old.uuline() != curstate)
3072 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
3075 curstate = font.fontInfo().uwave();
3076 if (font_old.uwave() != curstate)
3077 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
3080 // a little hackish, but allows us to reuse what we have.
3081 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
3082 if (font_old.series() != font.fontInfo().series())
3083 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
3086 curr_fs = font.fontInfo().shape();
3087 FontShape old_fs = font_old.shape();
3088 if (old_fs != curr_fs) {
3092 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
3095 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
3097 case SMALLCAPS_SHAPE:
3098 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
3104 // the other tags are for internal use
3112 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
3116 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
3119 case SMALLCAPS_SHAPE:
3120 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
3127 // the other tags are for internal use
3134 curr_fam = font.fontInfo().family();
3135 FontFamily old_fam = font_old.family();
3136 if (old_fam != curr_fam) {
3140 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
3143 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
3145 case TYPEWRITER_FAMILY:
3146 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
3148 case INHERIT_FAMILY:
3151 // the other tags are for internal use
3159 // we will treat a "default" font family as roman, since we have
3160 // no other idea what to do.
3161 if (default_family != "rmdefault" && default_family != "default") {
3162 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3167 if (default_family != "sfdefault") {
3168 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3172 case TYPEWRITER_FAMILY:
3173 if (default_family != "ttdefault") {
3174 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3178 case INHERIT_FAMILY:
3181 // the other tags are for internal use
3188 curr_size = font.fontInfo().size();
3189 FontSize old_size = font_old.size();
3190 if (old_size != curr_size) {
3193 case FONT_SIZE_TINY:
3194 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3196 case FONT_SIZE_SCRIPT:
3197 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3199 case FONT_SIZE_FOOTNOTE:
3200 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3202 case FONT_SIZE_SMALL:
3203 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3205 case FONT_SIZE_LARGE:
3206 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3208 case FONT_SIZE_LARGER:
3209 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3211 case FONT_SIZE_LARGEST:
3212 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3214 case FONT_SIZE_HUGE:
3215 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3217 case FONT_SIZE_HUGER:
3218 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3220 case FONT_SIZE_INCREASE:
3221 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3223 case FONT_SIZE_DECREASE:
3224 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3226 case FONT_SIZE_INHERIT:
3227 case FONT_SIZE_NORMAL:
3230 // the other tags are for internal use
3236 switch (curr_size) {
3237 case FONT_SIZE_TINY:
3238 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3241 case FONT_SIZE_SCRIPT:
3242 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3245 case FONT_SIZE_FOOTNOTE:
3246 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3249 case FONT_SIZE_SMALL:
3250 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3253 case FONT_SIZE_LARGE:
3254 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3257 case FONT_SIZE_LARGER:
3258 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3261 case FONT_SIZE_LARGEST:
3262 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3265 case FONT_SIZE_HUGE:
3266 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3269 case FONT_SIZE_HUGER:
3270 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3273 case FONT_SIZE_INCREASE:
3274 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3277 case FONT_SIZE_DECREASE:
3278 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3281 case FONT_SIZE_NORMAL:
3282 case FONT_SIZE_INHERIT:
3285 // the other tags are for internal use
3292 // Other such tags? What about the other text ranges?
3294 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3295 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3296 for (; cit != cen; ++cit)
3299 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3300 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3301 for (; sit != sen; ++sit)
3304 tagsToClose.clear();
3307 Inset const * inset = getInset(i);
3309 if (!runparams.for_toc || inset->isInToc()) {
3310 OutputParams np = runparams;
3311 np.local_font = &font;
3312 // If the paragraph has size 1, then we are in the "special
3313 // case" where we do not output the containing paragraph info
3314 if (!inset->getLayout().htmlisblock() && size() != 1)
3315 np.html_in_par = true;
3316 retval += inset->xhtml(xs, np);
3319 char_type c = getUChar(buf.masterBuffer()->params(), i);
3322 font_old = font.fontInfo();
3326 // I'm worried about what happens if a branch, say, is itself
3327 // wrapped in some font stuff. I think that will not work.
3329 if (close_paragraph)
3336 bool Paragraph::isHfill(pos_type pos) const
3338 Inset const * inset = getInset(pos);
3339 return inset && inset->isHfill();
3343 bool Paragraph::isNewline(pos_type pos) const
3345 // U+2028 LINE SEPARATOR
3346 // U+2029 PARAGRAPH SEPARATOR
3347 char_type const c = d->text_[pos];
3348 if (c == 0x2028 || c == 0x2029)
3350 Inset const * inset = getInset(pos);
3351 return inset && inset->lyxCode() == NEWLINE_CODE;
3355 bool Paragraph::isEnvSeparator(pos_type pos) const
3357 Inset const * inset = getInset(pos);
3358 return inset && inset->lyxCode() == SEPARATOR_CODE;
3362 bool Paragraph::isLineSeparator(pos_type pos) const
3364 char_type const c = d->text_[pos];
3365 if (isLineSeparatorChar(c))
3367 Inset const * inset = getInset(pos);
3368 return inset && inset->isLineSeparator();
3372 bool Paragraph::isWordSeparator(pos_type pos) const
3376 if (Inset const * inset = getInset(pos))
3377 return !inset->isLetter();
3378 // if we have a hard hyphen (no en- or emdash) or apostrophe
3379 // we pass this to the spell checker
3380 // FIXME: this method is subject to change, visit
3381 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3382 // to get an impression how complex this is.
3383 if (isHardHyphenOrApostrophe(pos))
3385 char_type const c = d->text_[pos];
3386 // We want to pass the escape chars to the spellchecker
3387 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3388 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3392 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3394 pos_type const psize = size();
3397 char_type const c = d->text_[pos];
3398 if (c != '-' && c != '\'')
3400 int nextpos = pos + 1;
3401 int prevpos = pos > 0 ? pos - 1 : 0;
3402 if ((nextpos == psize || isSpace(nextpos))
3403 && (pos == 0 || isSpace(prevpos)))
3409 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3411 return d->speller_state_.getRange(pos);
3415 bool Paragraph::isChar(pos_type pos) const
3417 if (Inset const * inset = getInset(pos))
3418 return inset->isChar();
3419 char_type const c = d->text_[pos];
3420 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3424 bool Paragraph::isSpace(pos_type pos) const
3426 if (Inset const * inset = getInset(pos))
3427 return inset->isSpace();
3428 char_type const c = d->text_[pos];
3429 return lyx::isSpace(c);
3434 Paragraph::getParLanguage(BufferParams const & bparams) const
3437 return getFirstFontSettings(bparams).language();
3438 // FIXME: we should check the prev par as well (Lgb)
3439 return bparams.language;
3443 bool Paragraph::isRTL(BufferParams const & bparams) const
3445 return getParLanguage(bparams)->rightToLeft()
3446 && !inInset().getLayout().forceLTR();
3450 void Paragraph::changeLanguage(BufferParams const & bparams,
3451 Language const * from, Language const * to)
3453 // change language including dummy font change at the end
3454 for (pos_type i = 0; i <= size(); ++i) {
3455 Font font = getFontSettings(bparams, i);
3456 if (font.language() == from) {
3457 font.setLanguage(to);
3459 d->requestSpellCheck(i);
3465 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3467 Language const * doc_language = bparams.language;
3468 FontList::const_iterator cit = d->fontlist_.begin();
3469 FontList::const_iterator end = d->fontlist_.end();
3471 for (; cit != end; ++cit)
3472 if (cit->font().language() != ignore_language &&
3473 cit->font().language() != latex_language &&
3474 cit->font().language() != doc_language)
3480 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3482 FontList::const_iterator cit = d->fontlist_.begin();
3483 FontList::const_iterator end = d->fontlist_.end();
3485 for (; cit != end; ++cit) {
3486 Language const * lang = cit->font().language();
3487 if (lang != ignore_language &&
3488 lang != latex_language)
3489 languages.insert(lang);
3494 docstring Paragraph::asString(int options) const
3496 return asString(0, size(), options);
3500 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3502 odocstringstream os;
3505 && options & AS_STR_LABEL
3506 && !d->params_.labelString().empty())
3507 os << d->params_.labelString() << ' ';
3509 for (pos_type i = beg; i < end; ++i) {
3510 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3512 char_type const c = d->text_[i];
3513 if (isPrintable(c) || c == '\t'
3514 || (c == '\n' && (options & AS_STR_NEWLINES)))
3516 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3517 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3518 LASSERT(runparams != 0, return docstring());
3519 getInset(i)->plaintext(os, *runparams);
3521 getInset(i)->toString(os);
3530 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3531 bool const shorten, bool const label) const
3533 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3534 if (label && !labelString().empty())
3535 os += labelString() + ' ';
3536 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3539 char_type const c = d->text_[i];
3542 else if (c == META_INSET)
3543 getInset(i)->forOutliner(os, tmplen, false);
3546 Text::shortenForOutliner(os, maxlen);
3550 void Paragraph::setInsetOwner(Inset const * inset)
3552 d->inset_owner_ = inset;
3556 int Paragraph::id() const
3562 void Paragraph::setId(int id)
3568 Layout const & Paragraph::layout() const
3574 void Paragraph::setLayout(Layout const & layout)
3576 d->layout_ = &layout;
3580 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3582 setLayout(tc.defaultLayout());
3586 void Paragraph::setPlainLayout(DocumentClass const & tc)
3588 setLayout(tc.plainLayout());
3592 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3594 if (usePlainLayout())
3595 setPlainLayout(tclass);
3597 setDefaultLayout(tclass);
3601 Inset const & Paragraph::inInset() const
3603 LBUFERR(d->inset_owner_);
3604 return *d->inset_owner_;
3608 ParagraphParameters & Paragraph::params()
3614 ParagraphParameters const & Paragraph::params() const
3620 bool Paragraph::isFreeSpacing() const
3622 if (d->layout_->free_spacing)
3624 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3628 bool Paragraph::allowEmpty() const
3630 if (d->layout_->keepempty)
3632 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3636 bool Paragraph::brokenBiblio() const
3638 // there is a problem if there is no bibitem at position 0 or
3639 // if there is another bibitem in the paragraph.
3640 return d->layout_->labeltype == LABEL_BIBLIO
3641 && (d->insetlist_.find(BIBITEM_CODE) != 0
3642 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3646 int Paragraph::fixBiblio(Buffer const & buffer)
3648 // FIXME: What about the case where paragraph is not BIBLIO
3649 // but there is an InsetBibitem?
3650 // FIXME: when there was already an inset at 0, the return value is 1,
3651 // which does not tell whether another inset has been remove; the
3652 // cursor cannot be correctly updated.
3654 if (d->layout_->labeltype != LABEL_BIBLIO)
3657 bool const track_changes = buffer.params().track_changes;
3658 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3659 bool const hasbibitem0 = bibitem_pos == 0;
3662 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3663 // There was an InsetBibitem at pos 0, and no other one => OK
3664 if (bibitem_pos == -1)
3666 // there is a bibitem at the 0 position, but since
3667 // there is a second one, we copy the second on the
3668 // first. We're assuming there are at most two of
3669 // these, which there should be.
3670 // FIXME: why does it make sense to do that rather
3671 // than keep the first? (JMarc)
3672 Inset * inset = releaseInset(bibitem_pos);
3673 d->insetlist_.begin()->inset = inset;
3674 return -bibitem_pos;
3677 // We need to create an inset at the beginning
3679 if (bibitem_pos > 0) {
3680 // there was one somewhere in the paragraph, let's move it
3681 inset = d->insetlist_.release(bibitem_pos);
3682 eraseChar(bibitem_pos, track_changes);
3685 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3686 InsetCommandParams(BIBITEM_CODE));
3688 Font font(inherit_font, buffer.params().language);
3689 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3690 : Change::UNCHANGED));
3696 void Paragraph::checkAuthors(AuthorList const & authorList)
3698 d->changes_.checkAuthors(authorList);
3702 bool Paragraph::isChanged(pos_type pos) const
3704 return lookupChange(pos).changed();
3708 bool Paragraph::isInserted(pos_type pos) const
3710 return lookupChange(pos).inserted();
3714 bool Paragraph::isDeleted(pos_type pos) const
3716 return lookupChange(pos).deleted();
3720 InsetList const & Paragraph::insetList() const
3722 return d->insetlist_;
3726 void Paragraph::setInsetBuffers(Buffer & b)
3728 d->insetlist_.setBuffer(b);
3732 void Paragraph::resetBuffer()
3734 d->insetlist_.resetBuffer();
3738 Inset * Paragraph::releaseInset(pos_type pos)
3740 Inset * inset = d->insetlist_.release(pos);
3741 /// does not honour change tracking!
3742 eraseChar(pos, false);
3747 Inset * Paragraph::getInset(pos_type pos)
3749 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3750 ? d->insetlist_.get(pos) : 0;
3754 Inset const * Paragraph::getInset(pos_type pos) const
3756 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3757 ? d->insetlist_.get(pos) : 0;
3761 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3762 pos_type & right, TextCase action)
3764 // process sequences of modified characters; in change
3765 // tracking mode, this approach results in much better
3766 // usability than changing case on a char-by-char basis
3767 // We also need to track the current font, since font
3768 // changes within sequences can occur.
3769 vector<pair<char_type, Font> > changes;
3771 bool const trackChanges = bparams.track_changes;
3773 bool capitalize = true;
3775 for (; pos < right; ++pos) {
3776 char_type oldChar = d->text_[pos];
3777 char_type newChar = oldChar;
3779 // ignore insets and don't play with deleted text!
3780 if (oldChar != META_INSET && !isDeleted(pos)) {
3782 case text_lowercase:
3783 newChar = lowercase(oldChar);
3785 case text_capitalization:
3787 newChar = uppercase(oldChar);
3791 case text_uppercase:
3792 newChar = uppercase(oldChar);
3797 if (isWordSeparator(pos) || isDeleted(pos)) {
3798 // permit capitalization again
3802 if (oldChar != newChar) {
3803 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3804 if (pos != right - 1)
3806 // step behind the changing area
3810 int erasePos = pos - changes.size();
3811 for (size_t i = 0; i < changes.size(); i++) {
3812 insertChar(pos, changes[i].first,
3815 if (!eraseChar(erasePos, trackChanges)) {
3818 ++right; // expand selection
3826 int Paragraph::find(docstring const & str, bool cs, bool mw,
3827 pos_type start_pos, bool del) const
3829 pos_type pos = start_pos;
3830 int const strsize = str.length();
3832 pos_type const parsize = d->text_.size();
3833 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3834 // Ignore "invisible" letters such as ligature breaks
3835 // and hyphenation chars while searching
3836 while (pos < parsize - 1 && isInset(pos)) {
3837 odocstringstream os;
3838 getInset(pos)->toString(os);
3839 if (!getInset(pos)->isLetter() || !os.str().empty())
3843 if (cs && str[i] != d->text_[pos])
3845 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3847 if (!del && isDeleted(pos))
3854 // if necessary, check whether string matches word
3856 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3859 && !isWordSeparator(pos))
3863 return pos - start_pos;
3867 char_type Paragraph::getChar(pos_type pos) const
3869 return d->text_[pos];
3873 pos_type Paragraph::size() const
3875 return d->text_.size();
3879 bool Paragraph::empty() const
3881 return d->text_.empty();
3885 bool Paragraph::isInset(pos_type pos) const
3887 return d->text_[pos] == META_INSET;
3891 bool Paragraph::isSeparator(pos_type pos) const
3893 //FIXME: Are we sure this can be the only separator?
3894 return d->text_[pos] == ' ';
3898 void Paragraph::deregisterWords()
3900 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3901 Private::LangWordsMap::const_iterator ite = d->words_.end();
3902 for (; itl != ite; ++itl) {
3903 WordList & wl = theWordList(itl->first);
3904 Private::Words::const_iterator it = (itl->second).begin();
3905 Private::Words::const_iterator et = (itl->second).end();
3906 for (; it != et; ++it)
3913 void Paragraph::locateWord(pos_type & from, pos_type & to,
3914 word_location const loc) const
3917 case WHOLE_WORD_STRICT:
3918 if (from == 0 || from == size()
3919 || isWordSeparator(from)
3920 || isWordSeparator(from - 1)) {
3927 // If we are already at the beginning of a word, do nothing
3928 if (!from || isWordSeparator(from - 1))
3933 // always move the cursor to the beginning of previous word
3934 while (from && !isWordSeparator(from - 1))
3938 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3941 // no need to move the 'from' cursor
3945 while (to < size() && !isWordSeparator(to))
3950 void Paragraph::collectWords()
3952 for (pos_type pos = 0; pos < size(); ++pos) {
3953 if (isWordSeparator(pos))
3955 pos_type from = pos;
3956 locateWord(from, pos, WHOLE_WORD);
3957 // Work around MSVC warning: The statement
3958 // if (pos < from + lyxrc.completion_minlength)
3959 // triggers a signed vs. unsigned warning.
3960 // I don't know why this happens, it could be a MSVC bug, or
3961 // related to LLP64 (windows) vs. LP64 (unix) programming
3962 // model, or the C++ standard might be ambigous in the section
3963 // defining the "usual arithmetic conversions". However, using
3964 // a temporary variable is safe and works on all compilers.
3965 pos_type const endpos = from + lyxrc.completion_minlength;
3968 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3969 if (cit == d->fontlist_.end())
3971 Language const * lang = cit->font().language();
3972 docstring const word = asString(from, pos, AS_STR_NONE);
3973 d->words_[lang->lang()].insert(word);
3978 void Paragraph::registerWords()
3980 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3981 Private::LangWordsMap::const_iterator ite = d->words_.end();
3982 for (; itl != ite; ++itl) {
3983 WordList & wl = theWordList(itl->first);
3984 Private::Words::const_iterator it = (itl->second).begin();
3985 Private::Words::const_iterator et = (itl->second).end();
3986 for (; it != et; ++it)
3992 void Paragraph::updateWords()
4000 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
4002 SkipPositionsIterator begin = skips.begin();
4003 SkipPositions::iterator end = skips.end();
4004 if (pos > 0 && begin < end) {
4006 if (end->last == pos - 1) {
4011 skips.insert(end, FontSpan(pos, pos));
4015 Language * Paragraph::Private::locateSpellRange(
4016 pos_type & from, pos_type & to,
4017 SkipPositions & skips) const
4019 // skip leading white space
4020 while (from < to && owner_->isWordSeparator(from))
4022 // don't check empty range
4025 // get current language
4026 Language * lang = getSpellLanguage(from);
4027 pos_type last = from;
4028 bool samelang = true;
4029 bool sameinset = true;
4030 while (last < to && samelang && sameinset) {
4031 // hop to end of word
4032 while (last < to && !owner_->isWordSeparator(last)) {
4033 if (owner_->getInset(last)) {
4034 appendSkipPosition(skips, last);
4035 } else if (owner_->isDeleted(last)) {
4036 appendSkipPosition(skips, last);
4040 // hop to next word while checking for insets
4041 while (sameinset && last < to && owner_->isWordSeparator(last)) {
4042 if (Inset const * inset = owner_->getInset(last))
4043 sameinset = inset->isChar() && inset->isLetter();
4044 if (sameinset && owner_->isDeleted(last)) {
4045 appendSkipPosition(skips, last);
4050 if (sameinset && last < to) {
4051 // now check for language change
4052 samelang = lang == getSpellLanguage(last);
4055 // if language change detected backstep is needed
4063 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
4066 const_cast<Language *>(owner_->getFontSettings(
4067 inset_owner_->buffer().params(), from).language());
4068 if (lang == inset_owner_->buffer().params().language
4069 && !lyxrc.spellchecker_alt_lang.empty()) {
4071 string const lang_variety =
4072 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
4073 lang->setCode(lang_code);
4074 lang->setVariety(lang_variety);
4080 void Paragraph::requestSpellCheck(pos_type pos)
4082 d->requestSpellCheck(pos);
4086 bool Paragraph::needsSpellCheck() const
4088 SpellChecker::ChangeNumber speller_change_number = 0;
4089 if (theSpellChecker())
4090 speller_change_number = theSpellChecker()->changeNumber();
4091 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
4092 d->speller_state_.needsCompleteRefresh(speller_change_number);
4094 return d->needsSpellCheck();
4098 bool Paragraph::Private::ignoreWord(docstring const & word) const
4100 // Ignore words with digits
4101 // FIXME: make this customizable
4102 // (note that some checkers ignore words with digits by default)
4103 docstring::const_iterator cit = word.begin();
4104 docstring::const_iterator const end = word.end();
4105 for (; cit != end; ++cit) {
4106 if (isNumber((*cit)))
4113 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
4114 WordLangTuple & wl, docstring_list & suggestions,
4115 bool do_suggestion, bool check_learned) const
4117 SpellChecker::Result result = SpellChecker::WORD_OK;
4118 SpellChecker * speller = theSpellChecker();
4122 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
4125 locateWord(from, to, WHOLE_WORD);
4126 if (from == to || from >= size())
4129 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4130 Language * lang = d->getSpellLanguage(from);
4132 wl = WordLangTuple(word, lang);
4137 if (needsSpellCheck() || check_learned) {
4139 if (!d->ignoreWord(word)) {
4140 bool const trailing_dot = to < size() && d->text_[to] == '.';
4141 result = speller->check(wl);
4142 if (SpellChecker::misspelled(result) && trailing_dot) {
4143 wl = WordLangTuple(word.append(from_ascii(".")), lang);
4144 result = speller->check(wl);
4145 if (!SpellChecker::misspelled(result)) {
4146 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
4148 from << ".." << to << "]");
4150 // spell check with dot appended failed too
4151 // restore original word/lang value
4152 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4153 wl = WordLangTuple(word, lang);
4157 if (!SpellChecker::misspelled(result)) {
4158 // area up to the begin of the next word is not misspelled
4159 while (end < size() && isWordSeparator(end))
4162 d->setMisspelled(from, end, result);
4164 result = d->speller_state_.getState(from);
4168 suggestions.clear();
4170 if (SpellChecker::misspelled(result)) {
4171 LYXERR(Debug::GUI, "misspelled word: \"" <<
4173 from << ".." << to << "]");
4175 speller->suggest(wl, suggestions);
4181 void Paragraph::Private::markMisspelledWords(
4182 pos_type const & first, pos_type const & last,
4183 SpellChecker::Result result,
4184 docstring const & word,
4185 SkipPositions const & skips)
4187 if (!SpellChecker::misspelled(result)) {
4188 setMisspelled(first, last, SpellChecker::WORD_OK);
4192 SpellChecker * speller = theSpellChecker();
4193 // locate and enumerate the error positions
4194 int nerrors = speller->numMisspelledWords();
4196 SkipPositionsIterator it = skips.begin();
4197 SkipPositionsIterator et = skips.end();
4198 for (int index = 0; index < nerrors; ++index) {
4201 speller->misspelledWord(index, wstart, wlen);
4202 /// should not happen if speller supports range checks
4203 if (!wlen) continue;
4204 docstring const misspelled = word.substr(wstart, wlen);
4205 wstart += first + numskipped;
4206 if (snext < wstart) {
4207 /// mark the range of correct spelling
4208 numskipped += countSkips(it, et, wstart);
4209 setMisspelled(snext,
4210 wstart - 1, SpellChecker::WORD_OK);
4212 snext = wstart + wlen;
4213 numskipped += countSkips(it, et, snext);
4214 /// mark the range of misspelling
4215 setMisspelled(wstart, snext, result);
4216 LYXERR(Debug::GUI, "misspelled word: \"" <<
4217 misspelled << "\" [" <<
4218 wstart << ".." << (snext-1) << "]");
4221 if (snext <= last) {
4222 /// mark the range of correct spelling at end
4223 setMisspelled(snext, last, SpellChecker::WORD_OK);
4228 void Paragraph::spellCheck() const
4230 SpellChecker * speller = theSpellChecker();
4231 if (!speller || empty() ||!needsSpellCheck())
4235 d->rangeOfSpellCheck(start, endpos);
4236 if (speller->canCheckParagraph()) {
4237 // loop until we leave the range
4238 for (pos_type first = start; first < endpos; ) {
4239 pos_type last = endpos;
4240 Private::SkipPositions skips;
4241 Language * lang = d->locateSpellRange(first, last, skips);
4242 if (first >= endpos)
4244 // start the spell checker on the unit of meaning
4245 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4246 WordLangTuple wl = WordLangTuple(word, lang);
4247 SpellChecker::Result result = word.size() ?
4248 speller->check(wl) : SpellChecker::WORD_OK;
4249 d->markMisspelledWords(first, last, result, word, skips);
4253 static docstring_list suggestions;
4254 pos_type to = endpos;
4255 while (start < endpos) {
4257 spellCheck(start, to, wl, suggestions, false);
4261 d->readySpellCheck();
4265 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4267 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4268 if (result || pos <= 0 || pos > size())
4270 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4271 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4276 string Paragraph::magicLabel() const
4279 ss << "magicparlabel-" << id();