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"
56 #include "mathed/InsetMathHull.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
71 using namespace lyx::support;
77 /// Inset identifier (above 0x10ffff, for ucs-4)
78 char_type const META_INSET = 0x200001;
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 class SpellResultRange {
91 SpellResultRange(FontSpan range, SpellChecker::Result result)
92 : range_(range), result_(result)
95 FontSpan const & range() const { return range_; }
97 void range(FontSpan const & r) { range_ = r; }
99 SpellChecker::Result result() const { return result_; }
101 void result(SpellChecker::Result r) { result_ = r; }
103 bool contains(pos_type pos) const { return range_.contains(pos); }
105 bool covered(FontSpan const & r) const
107 // 1. first of new range inside current range or
108 // 2. last of new range inside current range or
109 // 3. first of current range inside new range or
110 // 4. last of current range inside new range
111 //FIXME: is this the same as !range_.intersect(r).empty() ?
112 return range_.contains(r.first) || range_.contains(r.last) ||
113 r.contains(range_.first) || r.contains(range_.last);
116 void shift(pos_type pos, int offset)
118 if (range_.first > pos) {
119 range_.first += offset;
120 range_.last += offset;
121 } else if (range_.last >= pos) {
122 range_.last += offset;
127 SpellChecker::Result result_ ;
131 /////////////////////////////////////////////////////////////////////
135 /////////////////////////////////////////////////////////////////////
137 class SpellCheckerState {
141 needs_refresh_ = true;
142 current_change_number_ = 0;
145 void setRange(FontSpan const & fp, SpellChecker::Result state)
148 RangesIterator et = ranges_.end();
149 RangesIterator it = ranges_.begin();
150 for (; it != et; ++it) {
151 if (!it->covered(fp))
152 result.push_back(SpellResultRange(it->range(), it->result()));
153 else if (state == SpellChecker::WORD_OK) {
154 // trim or split the current misspelled range
155 // store misspelled ranges only
156 FontSpan range = it->range();
157 if (fp.first > range.first) {
158 // misspelled area in front of WORD_OK
159 range.last = fp.first - 1;
160 result.push_back(SpellResultRange(range, it->result()));
163 if (fp.last < range.last) {
164 // misspelled area after WORD_OK range
165 range.first = fp.last + 1;
166 result.push_back(SpellResultRange(range, it->result()));
171 if (state != SpellChecker::WORD_OK)
172 ranges_.push_back(SpellResultRange(fp, state));
175 void increasePosAfterPos(pos_type pos)
177 correctRangesAfterPos(pos, 1);
181 void decreasePosAfterPos(pos_type pos)
183 correctRangesAfterPos(pos, -1);
187 void refreshLast(pos_type pos)
189 if (pos < refresh_.last)
193 SpellChecker::Result getState(pos_type pos) const
195 SpellChecker::Result result = SpellChecker::WORD_OK;
196 RangesIterator et = ranges_.end();
197 RangesIterator it = ranges_.begin();
198 for (; it != et; ++it) {
199 if(it->contains(pos)) {
206 FontSpan const & getRange(pos_type pos) const
208 /// empty span to indicate mismatch
209 static FontSpan empty_;
210 RangesIterator et = ranges_.end();
211 RangesIterator it = ranges_.begin();
212 for (; it != et; ++it) {
213 if(it->contains(pos)) {
220 bool needsRefresh() const
222 return needs_refresh_;
225 SpellChecker::ChangeNumber currentChangeNumber() const
227 return current_change_number_;
230 void refreshRange(pos_type & first, pos_type & last) const
232 first = refresh_.first;
233 last = refresh_.last;
236 void needsRefresh(pos_type pos)
238 if (needs_refresh_ && pos != -1) {
239 if (pos < refresh_.first)
240 refresh_.first = pos;
241 if (pos > refresh_.last)
243 } else if (pos != -1) {
244 // init request check for neighbour positions too
245 refresh_.first = pos > 0 ? pos - 1 : 0;
246 // no need for special end of paragraph check
247 refresh_.last = pos + 1;
249 needs_refresh_ = pos != -1;
252 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
254 needs_refresh_ = true;
257 current_change_number_ = change_number;
260 typedef vector<SpellResultRange> Ranges;
261 typedef Ranges::const_iterator RangesIterator;
263 /// the area of the paragraph with pending spell check
266 /// spell state cache version number
267 SpellChecker::ChangeNumber current_change_number_;
270 void correctRangesAfterPos(pos_type pos, int offset)
272 RangesIterator et = ranges_.end();
273 Ranges::iterator it = ranges_.begin();
274 for (; it != et; ++it) {
275 it->shift(pos, offset);
281 /////////////////////////////////////////////////////////////////////
283 // Paragraph::Private
285 /////////////////////////////////////////////////////////////////////
287 class Paragraph::Private
289 // Enforce our own "copy" constructor
290 Private(Private const &) = delete;
291 Private & operator=(Private const &) = delete;
292 // Unique ID generator
293 static int make_id();
296 Private(Paragraph * owner, Layout const & layout);
297 /// "Copy constructor"
298 Private(Private const &, Paragraph * owner);
299 /// Copy constructor from \p beg to \p end
300 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
303 void insertChar(pos_type pos, char_type c, Change const & change);
305 /// Output the surrogate pair formed by \p c and \p next to \p os.
306 /// \return the number of characters written.
307 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
308 OutputParams const &);
310 /// Output a space in appropriate formatting (or a surrogate pair
311 /// if the next character is a combining character).
312 /// \return whether a surrogate pair was output.
313 bool simpleTeXBlanks(OutputParams const &,
316 unsigned int & column,
318 Layout const & style);
320 /// Output consecutive unicode chars, belonging to the same script as
321 /// specified by the latex macro \p ltx, to \p os starting from \p i.
322 /// \return the number of characters written.
323 int writeScriptChars(otexstream & os, docstring const & ltx,
324 Change const &, Encoding const &, pos_type & i);
326 /// This could go to ParagraphParameters if we want to.
327 int startTeXParParams(BufferParams const &, otexstream &,
328 OutputParams const &) const;
330 /// This could go to ParagraphParameters if we want to.
331 bool endTeXParParams(BufferParams const &, otexstream &,
332 OutputParams const &) const;
335 void latexInset(BufferParams const &,
340 Font const & outerfont,
342 Change & running_change,
343 Layout const & style,
345 unsigned int & column);
348 void latexSpecialChar(
350 BufferParams const & bparams,
351 OutputParams const & runparams,
352 Font const & running_font,
353 Change const & running_change,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column);
370 unsigned int & column);
376 unsigned int & column);
379 void validate(LaTeXFeatures & features) const;
381 /// Checks if the paragraph contains only text and no inset or font change.
382 bool onlyText(Buffer const & buf, Font const & outerfont,
383 pos_type initial) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD);
445 owner_->locateWord(last, endpos, WHOLE_WORD);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 int skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<string, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
512 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
513 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
520 int Paragraph::Private::make_id()
522 // The id is unique per session across buffers because it is used in
523 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
526 static atomic_uint next_id(0);
531 Paragraph::Private::Private(Private const & p, Paragraph * owner)
532 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
534 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
535 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
538 requestSpellCheck(p.text_.size());
542 Paragraph::Private::Private(Private const & p, Paragraph * owner,
543 pos_type beg, pos_type end)
544 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
545 params_(p.params_), changes_(p.changes_),
546 insetlist_(p.insetlist_, beg, end),
547 begin_of_body_(p.begin_of_body_), words_(p.words_),
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
572 bool output_active, TocBackend & backend) const
574 d->changes_.addToToc(cdit, buf, output_active, backend);
578 void Paragraph::addChangesToBuffer(Buffer const & buf) const
580 d->changes_.updateBuffer(buf);
584 bool Paragraph::isChangeUpdateRequired() const
586 return d->changes_.isUpdateRequired();
590 bool Paragraph::isDeleted(pos_type start, pos_type end) const
592 LASSERT(start >= 0 && start <= size(), return false);
593 LASSERT(end > start && end <= size() + 1, return false);
595 return d->changes_.isDeleted(start, end);
599 bool Paragraph::isChanged(pos_type start, pos_type end) const
601 LASSERT(start >= 0 && start <= size(), return false);
602 LASSERT(end > start && end <= size() + 1, return false);
604 return d->changes_.isChanged(start, end);
608 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
610 // keep the logic here in sync with the logic of eraseChars()
614 Change const & change = d->changes_.lookup(size());
615 return change.inserted() && change.currentAuthor();
619 void Paragraph::setChange(Change const & change)
621 // beware of the imaginary end-of-par character!
622 d->changes_.set(change, 0, size() + 1);
625 * Propagate the change recursively - but not in case of DELETED!
627 * Imagine that your co-author makes changes in an existing inset. He
628 * sends your document to you and you come to the conclusion that the
629 * inset should go completely. If you erase it, LyX must not delete all
630 * text within the inset. Otherwise, the change tracked insertions of
631 * your co-author get lost and there is no way to restore them later.
633 * Conclusion: An inset's content should remain untouched if you delete it
636 if (!change.deleted()) {
637 for (pos_type pos = 0; pos < size(); ++pos) {
638 if (Inset * inset = getInset(pos))
639 inset->setChange(change);
645 void Paragraph::setChange(pos_type pos, Change const & change)
647 LASSERT(pos >= 0 && pos <= size(), return);
648 d->changes_.set(change, pos);
650 // see comment in setChange(Change const &) above
651 if (!change.deleted() && pos < size())
652 if (Inset * inset = getInset(pos))
653 inset->setChange(change);
657 Change const & Paragraph::lookupChange(pos_type pos) const
659 LBUFERR(pos >= 0 && pos <= size());
660 return d->changes_.lookup(pos);
664 void Paragraph::acceptChanges(pos_type start, pos_type end)
666 LASSERT(start >= 0 && start <= size(), return);
667 LASSERT(end > start && end <= size() + 1, return);
669 for (pos_type pos = start; pos < end; ++pos) {
670 switch (lookupChange(pos).type) {
671 case Change::UNCHANGED:
672 // accept changes in nested inset
673 if (Inset * inset = getInset(pos))
674 inset->acceptChanges();
677 case Change::INSERTED:
678 d->changes_.set(Change(Change::UNCHANGED), pos);
679 // also accept changes in nested inset
680 if (Inset * inset = getInset(pos))
681 inset->acceptChanges();
684 case Change::DELETED:
685 // Suppress access to non-existent
686 // "end-of-paragraph char"
688 eraseChar(pos, false);
699 void Paragraph::rejectChanges(pos_type start, pos_type end)
701 LASSERT(start >= 0 && start <= size(), return);
702 LASSERT(end > start && end <= size() + 1, return);
704 for (pos_type pos = start; pos < end; ++pos) {
705 switch (lookupChange(pos).type) {
706 case Change::UNCHANGED:
707 // reject changes in nested inset
708 if (Inset * inset = getInset(pos))
709 inset->rejectChanges();
712 case Change::INSERTED:
713 // Suppress access to non-existent
714 // "end-of-paragraph char"
716 eraseChar(pos, false);
722 case Change::DELETED:
723 d->changes_.set(Change(Change::UNCHANGED), pos);
725 // Do NOT reject changes within a deleted inset!
726 // There may be insertions of a co-author inside of it!
734 void Paragraph::Private::insertChar(pos_type pos, char_type c,
735 Change const & change)
737 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
740 changes_.insert(change, pos);
742 // This is actually very common when parsing buffers (and
743 // maybe inserting ascii text)
744 if (pos == pos_type(text_.size())) {
745 // when appending characters, no need to update tables
747 // but we want spell checking
748 requestSpellCheck(pos);
752 text_.insert(text_.begin() + pos, c);
754 // Update the font table.
755 fontlist_.increasePosAfterPos(pos);
758 insetlist_.increasePosAfterPos(pos);
760 // Update list of misspelled positions
761 speller_state_.increasePosAfterPos(pos);
765 bool Paragraph::insertInset(pos_type pos, Inset * inset,
766 Font const & font, Change const & change)
768 LASSERT(inset, return false);
769 LASSERT(pos >= 0 && pos <= size(), return false);
771 // Paragraph::insertInset() can be used in cut/copy/paste operation where
772 // d->inset_owner_ is not set yet.
773 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
776 d->insertChar(pos, META_INSET, change);
777 LASSERT(d->text_[pos] == META_INSET, return false);
779 // Add a new entry in the insetlist_.
780 d->insetlist_.insert(inset, pos);
782 // Some insets require run of spell checker
783 requestSpellCheck(pos);
789 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
791 LASSERT(pos >= 0 && pos <= size(), return false);
793 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
796 Change change = d->changes_.lookup(pos);
798 // set the character to DELETED if
799 // a) it was previously unchanged or
800 // b) it was inserted by a co-author
802 if (!change.changed() ||
803 (change.inserted() && !change.currentAuthor())) {
804 setChange(pos, Change(Change::DELETED));
805 // request run of spell checker
806 requestSpellCheck(pos);
810 if (change.deleted())
814 // Don't physically access the imaginary end-of-paragraph character.
815 // eraseChar() can only mark it as DELETED. A physical deletion of
816 // end-of-par must be handled externally.
822 d->changes_.erase(pos);
824 // if it is an inset, delete the inset entry
825 if (d->text_[pos] == META_INSET)
826 d->insetlist_.erase(pos);
828 d->text_.erase(d->text_.begin() + pos);
830 // Update the fontlist_
831 d->fontlist_.erase(pos);
833 // Update the insetlist_
834 d->insetlist_.decreasePosAfterPos(pos);
836 // Update list of misspelled positions
837 d->speller_state_.decreasePosAfterPos(pos);
838 d->speller_state_.refreshLast(size());
844 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
846 LASSERT(start >= 0 && start <= size(), return 0);
847 LASSERT(end >= start && end <= size() + 1, return 0);
850 for (pos_type count = end - start; count; --count) {
851 if (!eraseChar(i, trackChanges))
858 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
859 char_type next, OutputParams const & runparams)
861 // Writing next here may circumvent a possible font change between
862 // c and next. Since next is only output if it forms a surrogate pair
863 // with c we can ignore this:
864 // A font change inside a surrogate pair does not make sense and is
865 // hopefully impossible to input.
866 // FIXME: change tracking
867 // Is this correct WRT change tracking?
868 Encoding const & encoding = *(runparams.encoding);
869 docstring latex1 = encoding.latexChar(next).first;
870 if (runparams.inIPA) {
871 string const tipashortcut = Encodings::TIPAShortcut(next);
872 if (!tipashortcut.empty()) {
873 latex1 = from_ascii(tipashortcut);
876 docstring const latex2 = encoding.latexChar(c).first;
877 if (docstring(1, next) == latex1) {
878 // the encoding supports the combination
879 os << latex2 << latex1;
880 return latex1.length() + latex2.length();
881 } else if (runparams.local_font &&
882 runparams.local_font->language()->lang() == "polutonikogreek") {
883 // polutonikogreek only works without the brackets
884 os << latex1 << latex2;
885 return latex1.length() + latex2.length();
887 os << latex1 << '{' << latex2 << '}';
888 return latex1.length() + latex2.length() + 2;
892 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
895 unsigned int & column,
897 Layout const & style)
899 if (style.pass_thru || runparams.pass_thru)
902 if (i + 1 < int(text_.size())) {
903 char_type next = text_[i + 1];
904 if (Encodings::isCombiningChar(next)) {
905 // This space has an accent, so we must always output it.
906 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
911 if (runparams.linelen > 0
912 && column > runparams.linelen
914 && text_[i - 1] != ' '
915 && (i + 1 < int(text_.size()))
916 // same in FreeSpacing mode
917 && !owner_->isFreeSpacing()
918 // In typewriter mode, we want to avoid
919 // ! . ? : at the end of a line
920 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
921 && (text_[i - 1] == '.'
922 || text_[i - 1] == '?'
923 || text_[i - 1] == ':'
924 || text_[i - 1] == '!'))) {
926 os.texrow().start(owner_->id(), i + 1);
928 } else if (style.free_spacing) {
937 int Paragraph::Private::writeScriptChars(otexstream & os,
938 docstring const & ltx,
939 Change const & runningChange,
940 Encoding const & encoding,
943 // FIXME: modifying i here is not very nice...
945 // We only arrive here when character text_[i] could not be translated
946 // into the current latex encoding (or its latex translation has been forced,)
947 // and it belongs to a known script.
948 // TODO: We need \textcyr and \textgreek wrappers also for characters
949 // that can be encoded in the "LaTeX encoding" but not in the
950 // current *font encoding*.
951 // (See #9681 for details and test)
952 // Parameter ltx contains the latex translation of text_[i] as specified
953 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
954 // The latex macro name "textXXX" specifies the script to which text_[i]
955 // belongs and we use it in order to check whether characters from the
956 // same script immediately follow, such that we can collect them in a
957 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
958 // for the first char but only "<spec>" for all subsequent chars.
959 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
960 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
961 string script = to_ascii(ltx.substr(1, brace1 - 1));
964 bool closing_brace = true;
965 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
966 // Correct encoding is being used, so we can avoid \textgreek.
967 // TODO: wrong test: we need to check the *font encoding*
968 // (i.e. the active language and its FontEncoding tag)
969 // instead of the LaTeX *input encoding*!
970 // See #9637 for details and test-cases.
973 closing_brace = false;
975 os << ltx.substr(pos, length);
976 int size = text_.size();
977 while (i + 1 < size) {
978 char_type const next = text_[i + 1];
979 // Stop here if next character belongs to another script
980 // or there is a change in change tracking status.
981 if (!Encodings::isKnownScriptChar(next, script) ||
982 runningChange != owner_->lookupChange(i + 1))
986 FontList::const_iterator cit = fontlist_.begin();
987 FontList::const_iterator end = fontlist_.end();
988 for (; cit != end; ++cit) {
989 if (cit->pos() >= i && !found) {
990 prev_font = cit->font();
993 if (cit->pos() >= i + 1)
996 // Stop here if there is a font attribute or encoding change.
997 if (found && cit != end && prev_font != cit->font())
999 docstring const latex = encoding.latexChar(next).first;
1000 docstring::size_type const b1 =
1001 latex.find_first_of(from_ascii("{"));
1002 docstring::size_type const b2 =
1003 latex.find_last_of(from_ascii("}"));
1004 int const len = b2 - b1 - 1;
1005 os << latex.substr(b1 + 1, len);
1009 if (closing_brace) {
1017 void Paragraph::Private::latexInset(BufferParams const & bparams,
1019 OutputParams & runparams,
1020 Font & running_font,
1022 Font const & outerfont,
1024 Change & running_change,
1025 Layout const & style,
1027 unsigned int & column)
1029 Inset * inset = owner_->getInset(i);
1032 if (style.pass_thru) {
1033 odocstringstream ods;
1034 inset->plaintext(ods, runparams);
1039 // FIXME: move this to InsetNewline::latex
1040 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1041 // newlines are handled differently here than
1042 // the default in simpleTeXSpecialChars().
1043 if (!style.newline_allowed) {
1047 column += running_font.latexWriteEndChanges(
1048 os, bparams, runparams,
1049 basefont, basefont);
1053 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1056 basefont = owner_->getLayoutFont(bparams, outerfont);
1057 running_font = basefont;
1059 if (runparams.moving_arg)
1063 os.texrow().start(owner_->id(), i + 1);
1067 if (owner_->isDeleted(i)) {
1068 if( ++runparams.inDeletedInset == 1)
1069 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1072 if (inset->canTrackChanges()) {
1073 column += Changes::latexMarkChange(os, bparams, running_change,
1074 Change(Change::UNCHANGED), runparams);
1075 running_change = Change(Change::UNCHANGED);
1079 odocstream::pos_type const len = os.os().tellp();
1081 if (inset->forceLTR()
1082 && !runparams.use_polyglossia
1083 && running_font.isRightToLeft()
1084 // ERT is an exception, it should be output with no
1085 // decorations at all
1086 && inset->lyxCode() != ERT_CODE) {
1087 if (running_font.language()->lang() == "farsi")
1088 os << "\\beginL" << termcmd;
1094 // FIXME: Bug: we can have an empty font change here!
1095 // if there has just been a font change, we are going to close it
1096 // right now, which means stupid latex code like \textsf{}. AFAIK,
1097 // this does not harm dvi output. A minor bug, thus (JMarc)
1099 // Some insets cannot be inside a font change command.
1100 // However, even such insets *can* be placed in \L or \R
1101 // or their equivalents (for RTL language switches), so we don't
1102 // close the language in those cases.
1103 // ArabTeX, though, cannot handle this special behavior, it seems.
1104 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1105 || running_font.language()->lang() == "arabic_arabtex";
1106 if (open_font && !inset->inheritFont()) {
1107 bool closeLanguage = arabtex
1108 || basefont.isRightToLeft() == running_font.isRightToLeft();
1109 unsigned int count = running_font.latexWriteEndChanges(os,
1110 bparams, runparams, basefont, basefont, closeLanguage);
1112 // if any font properties were closed, update the running_font,
1113 // making sure, however, to leave the language as it was
1115 // FIXME: probably a better way to keep track of the old
1116 // language, than copying the entire font?
1117 Font const copy_font(running_font);
1118 basefont = owner_->getLayoutFont(bparams, outerfont);
1119 running_font = basefont;
1121 running_font.setLanguage(copy_font.language());
1122 // leave font open if language is still open
1123 open_font = (running_font.language() == basefont.language());
1125 runparams.local_font = &basefont;
1129 size_t const previous_row_count = os.texrow().rows();
1132 runparams.lastid = id_;
1133 runparams.lastpos = i;
1134 inset->latex(os, runparams);
1135 } catch (EncodingException & e) {
1136 // add location information and throw again.
1143 if (running_font.language()->lang() == "farsi")
1144 os << "\\endL" << termcmd;
1149 if (os.texrow().rows() > previous_row_count) {
1150 os.texrow().start(owner_->id(), i + 1);
1153 column += (unsigned int)(os.os().tellp() - len);
1156 if (owner_->isDeleted(i))
1157 --runparams.inDeletedInset;
1161 void Paragraph::Private::latexSpecialChar(otexstream & os,
1162 BufferParams const & bparams,
1163 OutputParams const & runparams,
1164 Font const & running_font,
1165 Change const & running_change,
1166 Layout const & style,
1169 unsigned int & column)
1171 // With polyglossia, brackets and stuff need not be reversed
1172 // in RTL scripts (see bug #8251)
1173 char_type const c = (runparams.use_polyglossia) ?
1174 owner_->getUChar(bparams, i) : text_[i];
1176 if (style.pass_thru || runparams.pass_thru
1177 || contains(style.pass_thru_chars, c)
1178 || contains(runparams.pass_thru_chars, c)) {
1180 Encoding const * const enc = runparams.encoding;
1181 if (enc && !enc->encodable(c))
1182 throw EncodingException(c);
1188 // TIPA uses its own T3 encoding
1189 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1191 // If T1 font encoding is used, use the special
1192 // characters it provides.
1193 // NOTE: Some languages reset the font encoding internally to a
1194 // non-standard font encoding. If we are using such a language,
1195 // we do not output special T1 chars.
1196 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1197 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1198 && latexSpecialT1(c, os, i, column))
1200 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1201 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1202 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1205 // Otherwise, we use what LaTeX provides us.
1208 os << "\\textbackslash" << termcmd;
1212 os << "\\textless" << termcmd;
1216 os << "\\textgreater" << termcmd;
1220 os << "\\textbar" << termcmd;
1225 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1226 (end_pos == -1 || i + 1 < end_pos) &&
1227 text_[i+1] == '-') {
1228 // Prevent "--" becoming an endash and "---" becoming
1230 // Within \ttfamily, "--" is merged to "-" (no endash)
1231 // so we avoid this rather irritating ligature as well
1237 os << "\\char34" << termcmd;
1242 case '%': case '#': case '{':
1250 os << "\\textasciitilde" << termcmd;
1255 os << "\\textasciicircum" << termcmd;
1262 // avoid being mistaken for optional arguments
1270 // Blanks are printed before font switching.
1271 // Sure? I am not! (try nice-latex)
1272 // I am sure it's correct. LyX might be smarter
1273 // in the future, but for now, nothing wrong is
1281 Encoding const & encoding = *(runparams.encoding);
1282 char_type next = '\0';
1283 if (i + 1 < int(text_.size())) {
1284 next = text_[i + 1];
1285 if (Encodings::isCombiningChar(next)) {
1286 column += latexSurrogatePair(os, c, next, runparams) - 1;
1292 pair<docstring, bool> latex = encoding.latexChar(c);
1293 docstring nextlatex;
1294 bool nexttipas = false;
1295 string nexttipashortcut;
1296 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1297 nextlatex = encoding.latexChar(next).first;
1298 if (runparams.inIPA) {
1299 nexttipashortcut = Encodings::TIPAShortcut(next);
1300 nexttipas = !nexttipashortcut.empty();
1304 if (runparams.inIPA) {
1305 string const tipashortcut = Encodings::TIPAShortcut(c);
1306 if (!tipashortcut.empty()) {
1307 latex.first = from_ascii(tipashortcut);
1308 latex.second = false;
1312 if (Encodings::isKnownScriptChar(c, script)
1313 && prefixIs(latex.first, from_ascii("\\" + script)))
1314 column += writeScriptChars(os, latex.first,
1315 running_change, encoding, i) - 1;
1316 else if (latex.second
1317 && ((!prefixIs(nextlatex, '\\')
1318 && !prefixIs(nextlatex, '{')
1319 && !prefixIs(nextlatex, '}'))
1321 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1323 // Prevent eating of a following
1324 // space or command corruption by
1325 // following characters
1326 if (next == ' ' || next == '\0') {
1327 column += latex.first.length() + 1;
1328 os << latex.first << "{}";
1330 column += latex.first.length();
1331 os << latex.first << " ";
1334 column += latex.first.length() - 1;
1342 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1343 pos_type i, unsigned int & column)
1349 // In T1 encoding, these characters exist
1350 // but we should avoid ligatures
1351 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1353 os << "\\textcompwordmark" << termcmd;
1360 // soul.sty breaks with \char`\"
1361 os << "\\textquotedbl" << termcmd;
1370 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1371 pos_type i, unsigned int & column)
1373 // TU encoding is currently on par with T1.
1374 return latexSpecialT1(c, os, i, column);
1378 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1379 pos_type /*i*/, unsigned int & column)
1389 os << "\\textvertline" << termcmd;
1398 void Paragraph::Private::validate(LaTeXFeatures & features) const
1400 if (layout_->inpreamble && inset_owner_) {
1401 bool const is_command = layout_->latextype == LATEX_COMMAND;
1402 Buffer const & buf = inset_owner_->buffer();
1403 BufferParams const & bp = features.runparams().is_child
1404 ? buf.masterParams() : buf.params();
1406 // Using a string stream here circumvents the encoding
1407 // switching machinery of odocstream. Therefore the
1408 // output is wrong if this paragraph contains content
1409 // that needs to switch encoding.
1410 otexstringstream os;
1411 os << layout_->preamble();
1413 os << '\\' << from_ascii(layout_->latexname());
1414 // we have to provide all the optional arguments here, even though
1415 // the last one is the only one we care about.
1416 // Separate handling of optional argument inset.
1417 if (!layout_->latexargs().empty()) {
1418 OutputParams rp = features.runparams();
1419 rp.local_font = &owner_->getFirstFontSettings(bp);
1420 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1422 os << from_ascii(layout_->latexparam());
1424 size_t const length = os.length();
1425 // this will output "{" at the beginning, but not at the end
1426 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1427 if (os.length() > length) {
1430 if (!layout_->postcommandargs().empty()) {
1431 OutputParams rp = features.runparams();
1432 rp.local_font = &owner_->getFirstFontSettings(bp);
1433 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1436 features.addPreambleSnippet(os.release(), true);
1440 if (features.runparams().flavor == OutputParams::HTML
1441 && layout_->htmltitle()) {
1442 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1445 // check the params.
1446 if (!params_.spacing().isDefault())
1447 features.require("setspace");
1450 features.useLayout(layout_->name());
1453 fontlist_.validate(features);
1455 // then the indentation
1456 if (!params_.leftIndent().zero())
1457 features.require("ParagraphLeftIndent");
1460 InsetList::const_iterator icit = insetlist_.begin();
1461 InsetList::const_iterator iend = insetlist_.end();
1462 for (; icit != iend; ++icit) {
1464 features.inDeletedInset(owner_->isDeleted(icit->pos));
1465 icit->inset->validate(features);
1466 features.inDeletedInset(false);
1467 if (layout_->needprotect &&
1468 icit->inset->lyxCode() == FOOT_CODE)
1469 features.require("NeedLyXFootnoteCode");
1473 // then the contents
1474 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1475 BufferEncodings::validate(text_[i], features);
1479 /////////////////////////////////////////////////////////////////////
1483 /////////////////////////////////////////////////////////////////////
1486 Layout const emptyParagraphLayout;
1489 Paragraph::Paragraph()
1490 : d(new Paragraph::Private(this, emptyParagraphLayout))
1497 Paragraph::Paragraph(Paragraph const & par)
1498 : itemdepth(par.itemdepth),
1499 d(new Paragraph::Private(*par.d, this))
1505 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1506 : itemdepth(par.itemdepth),
1507 d(new Paragraph::Private(*par.d, this, beg, end))
1513 Paragraph & Paragraph::operator=(Paragraph const & par)
1515 // needed as we will destroy the private part before copying it
1517 itemdepth = par.itemdepth;
1521 d = new Private(*par.d, this);
1528 Paragraph::~Paragraph()
1537 // this shall be called just before every "os << ..." action.
1538 void flushString(ostream & os, docstring & s)
1547 void Paragraph::write(ostream & os, BufferParams const & bparams,
1548 depth_type & dth) const
1550 // The beginning or end of a deeper (i.e. nested) area?
1551 if (dth != d->params_.depth()) {
1552 if (d->params_.depth() > dth) {
1553 while (d->params_.depth() > dth) {
1554 os << "\n\\begin_deeper";
1558 while (d->params_.depth() < dth) {
1559 os << "\n\\end_deeper";
1565 // First write the layout
1566 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1568 d->params_.write(os);
1570 Font font1(inherit_font, bparams.language);
1572 Change running_change = Change(Change::UNCHANGED);
1574 // this string is used as a buffer to avoid repetitive calls
1575 // to to_utf8(), which turn out to be expensive (JMarc)
1576 docstring write_buffer;
1579 for (pos_type i = 0; i <= size(); ++i) {
1581 Change const & change = lookupChange(i);
1582 if (change != running_change)
1583 flushString(os, write_buffer);
1584 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1585 running_change = change;
1590 // Write font changes
1591 Font font2 = getFontSettings(bparams, i);
1592 if (font2 != font1) {
1593 flushString(os, write_buffer);
1594 font2.lyxWriteChanges(font1, os);
1599 char_type const c = d->text_[i];
1602 if (Inset const * inset = getInset(i)) {
1603 flushString(os, write_buffer);
1604 if (inset->directWrite()) {
1605 // international char, let it write
1606 // code directly so it's shorter in
1612 os << "\\begin_inset ";
1614 os << "\n\\end_inset\n\n";
1617 // FIXME This can be removed again once the mystery
1618 // crash has been resolved.
1623 flushString(os, write_buffer);
1624 os << "\n\\backslash\n";
1628 flushString(os, write_buffer);
1629 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1636 if ((column > 70 && c == ' ')
1638 flushString(os, write_buffer);
1642 // this check is to amend a bug. LyX sometimes
1643 // inserts '\0' this could cause problems.
1645 write_buffer.push_back(c);
1647 LYXERR0("NUL char in structure.");
1653 flushString(os, write_buffer);
1654 os << "\n\\end_layout\n";
1655 // FIXME This can be removed again once the mystery
1656 // crash has been resolved.
1661 void Paragraph::validate(LaTeXFeatures & features) const
1663 d->validate(features);
1667 void Paragraph::insert(pos_type start, docstring const & str,
1668 Font const & font, Change const & change)
1670 for (size_t i = 0, n = str.size(); i != n ; ++i)
1671 insertChar(start + i, str[i], font, change);
1675 void Paragraph::appendChar(char_type c, Font const & font,
1676 Change const & change)
1679 d->changes_.insert(change, d->text_.size());
1680 // when appending characters, no need to update tables
1681 d->text_.push_back(c);
1682 setFont(d->text_.size() - 1, font);
1683 d->requestSpellCheck(d->text_.size() - 1);
1687 void Paragraph::appendString(docstring const & s, Font const & font,
1688 Change const & change)
1690 pos_type end = s.size();
1691 size_t oldsize = d->text_.size();
1692 size_t newsize = oldsize + end;
1693 size_t capacity = d->text_.capacity();
1694 if (newsize >= capacity)
1695 d->text_.reserve(max(capacity + 100, newsize));
1697 // when appending characters, no need to update tables
1700 // FIXME: Optimize this!
1701 for (size_t i = oldsize; i != newsize; ++i) {
1703 d->changes_.insert(change, i);
1704 d->requestSpellCheck(i);
1706 d->fontlist_.set(oldsize, font);
1707 d->fontlist_.set(newsize - 1, font);
1711 void Paragraph::insertChar(pos_type pos, char_type c,
1714 d->insertChar(pos, c, Change(trackChanges ?
1715 Change::INSERTED : Change::UNCHANGED));
1719 void Paragraph::insertChar(pos_type pos, char_type c,
1720 Font const & font, bool trackChanges)
1722 d->insertChar(pos, c, Change(trackChanges ?
1723 Change::INSERTED : Change::UNCHANGED));
1728 void Paragraph::insertChar(pos_type pos, char_type c,
1729 Font const & font, Change const & change)
1731 d->insertChar(pos, c, change);
1736 void Paragraph::resetFonts(Font const & font)
1738 d->fontlist_.clear();
1739 d->fontlist_.set(0, font);
1740 d->fontlist_.set(d->text_.size() - 1, font);
1743 // Gets uninstantiated font setting at position.
1744 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1748 LYXERR0("pos: " << pos << " size: " << size());
1752 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1753 if (cit != d->fontlist_.end())
1756 if (pos == size() && !empty())
1757 return getFontSettings(bparams, pos - 1);
1759 // Optimisation: avoid a full font instantiation if there is no
1760 // language change from previous call.
1761 static Font previous_font;
1762 static Language const * previous_lang = 0;
1763 Language const * lang = getParLanguage(bparams);
1764 if (lang != previous_lang) {
1765 previous_lang = lang;
1766 previous_font = Font(inherit_font, lang);
1768 return previous_font;
1772 FontSpan Paragraph::fontSpan(pos_type pos) const
1774 LBUFERR(pos <= size());
1777 return FontSpan(pos, pos);
1780 FontList::const_iterator cit = d->fontlist_.begin();
1781 FontList::const_iterator end = d->fontlist_.end();
1782 for (; cit != end; ++cit) {
1783 if (cit->pos() >= pos) {
1784 if (pos >= beginOfBody())
1785 return FontSpan(max(start, beginOfBody()),
1788 return FontSpan(start,
1789 min(beginOfBody() - 1,
1792 start = cit->pos() + 1;
1795 // This should not happen, but if so, we take no chances.
1796 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1797 LASSERT(false, return FontSpan(pos, pos));
1801 // Gets uninstantiated font setting at position 0
1802 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1804 if (!empty() && !d->fontlist_.empty())
1805 return d->fontlist_.begin()->font();
1807 // Optimisation: avoid a full font instantiation if there is no
1808 // language change from previous call.
1809 static Font previous_font;
1810 static Language const * previous_lang = 0;
1811 if (bparams.language != previous_lang) {
1812 previous_lang = bparams.language;
1813 previous_font = Font(inherit_font, bparams.language);
1816 return previous_font;
1820 // Gets the fully instantiated font at a given position in a paragraph
1821 // This is basically the same function as Text::GetFont() in text2.cpp.
1822 // The difference is that this one is used for generating the LaTeX file,
1823 // and thus cosmetic "improvements" are disallowed: This has to deliver
1824 // the true picture of the buffer. (Asger)
1825 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1826 Font const & outerfont) const
1830 Font font = getFontSettings(bparams, pos);
1832 pos_type const body_pos = beginOfBody();
1833 FontInfo & fi = font.fontInfo();
1835 fi.realize(d->layout_->labelfont);
1837 fi.realize(d->layout_->font);
1839 fi.realize(outerfont.fontInfo());
1840 fi.realize(bparams.getFont().fontInfo());
1846 Font const Paragraph::getLabelFont
1847 (BufferParams const & bparams, Font const & outerfont) const
1849 FontInfo tmpfont = d->layout_->labelfont;
1850 tmpfont.realize(outerfont.fontInfo());
1851 tmpfont.realize(bparams.getFont().fontInfo());
1852 return Font(tmpfont, getParLanguage(bparams));
1856 Font const Paragraph::getLayoutFont
1857 (BufferParams const & bparams, Font const & outerfont) const
1859 FontInfo tmpfont = d->layout_->font;
1860 tmpfont.realize(outerfont.fontInfo());
1861 tmpfont.realize(bparams.getFont().fontInfo());
1862 return Font(tmpfont, getParLanguage(bparams));
1866 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1868 char_type c = d->text_[pos];
1869 if (!getFontSettings(bparams, pos).isRightToLeft())
1872 // FIXME: The arabic special casing is due to the difference of arabic
1873 // round brackets input introduced in r18599. Check if this should be
1874 // unified with Hebrew or at least if all bracket types should be
1875 // handled the same (file format change in either case).
1876 string const & lang = getFontSettings(bparams, pos).language()->lang();
1877 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1882 uc = arabic ? c : ')';
1885 uc = arabic ? c : '(';
1911 void Paragraph::setFont(pos_type pos, Font const & font)
1913 LASSERT(pos <= size(), return);
1915 // First, reduce font against layout/label font
1916 // Update: The setCharFont() routine in text2.cpp already
1917 // reduces font, so we don't need to do that here. (Asger)
1919 d->fontlist_.set(pos, font);
1923 void Paragraph::makeSameLayout(Paragraph const & par)
1925 d->layout_ = par.d->layout_;
1926 d->params_ = par.d->params_;
1930 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1932 if (isFreeSpacing())
1938 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1939 if (eraseChar(pos, trackChanges))
1945 return count > 0 || pos > 0;
1949 bool Paragraph::hasSameLayout(Paragraph const & par) const
1951 return par.d->layout_ == d->layout_
1952 && d->params_.sameLayout(par.d->params_);
1956 depth_type Paragraph::getDepth() const
1958 return d->params_.depth();
1962 depth_type Paragraph::getMaxDepthAfter() const
1964 if (d->layout_->isEnvironment())
1965 return d->params_.depth() + 1;
1967 return d->params_.depth();
1971 LyXAlignment Paragraph::getAlign() const
1973 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1974 return d->layout_->align;
1976 return d->params_.align();
1980 docstring const & Paragraph::labelString() const
1982 return d->params_.labelString();
1986 // the next two functions are for the manual labels
1987 docstring const Paragraph::getLabelWidthString() const
1989 if (d->layout_->margintype == MARGIN_MANUAL
1990 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1991 return d->params_.labelWidthString();
1993 return _("Senseless with this layout!");
1997 void Paragraph::setLabelWidthString(docstring const & s)
1999 d->params_.labelWidthString(s);
2003 docstring Paragraph::expandLabel(Layout const & layout,
2004 BufferParams const & bparams) const
2006 return expandParagraphLabel(layout, bparams, true);
2010 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2011 BufferParams const & bparams) const
2013 return expandParagraphLabel(layout, bparams, false);
2017 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2018 BufferParams const & bparams, bool process_appendix) const
2020 DocumentClass const & tclass = bparams.documentClass();
2021 string const & lang = getParLanguage(bparams)->code();
2022 bool const in_appendix = process_appendix && d->params_.appendix();
2023 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2025 if (fmt.empty() && !layout.counter.empty())
2026 return tclass.counters().theCounter(layout.counter, lang);
2028 // handle 'inherited level parts' in 'fmt',
2029 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2030 size_t const i = fmt.find('@', 0);
2031 if (i != docstring::npos) {
2032 size_t const j = fmt.find('@', i + 1);
2033 if (j != docstring::npos) {
2034 docstring parent(fmt, i + 1, j - i - 1);
2035 docstring label = from_ascii("??");
2036 if (tclass.hasLayout(parent))
2037 label = expandParagraphLabel(tclass[parent], bparams,
2039 fmt = docstring(fmt, 0, i) + label
2040 + docstring(fmt, j + 1, docstring::npos);
2044 return tclass.counters().counterLabel(fmt, lang);
2048 void Paragraph::applyLayout(Layout const & new_layout)
2050 d->layout_ = &new_layout;
2051 LyXAlignment const oldAlign = d->params_.align();
2053 if (!(oldAlign & d->layout_->alignpossible)) {
2054 frontend::Alert::warning(_("Alignment not permitted"),
2055 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2056 d->params_.align(LYX_ALIGN_LAYOUT);
2061 pos_type Paragraph::beginOfBody() const
2063 return d->begin_of_body_;
2067 void Paragraph::setBeginOfBody()
2069 if (d->layout_->labeltype != LABEL_MANUAL) {
2070 d->begin_of_body_ = 0;
2074 // Unroll the first two cycles of the loop
2075 // and remember the previous character to
2076 // remove unnecessary getChar() calls
2078 pos_type end = size();
2079 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2082 char_type previous_char = d->text_[i];
2083 if (!(isNewline(i) || isEnvSeparator(i))) {
2085 while (i < end && previous_char != ' ') {
2086 char_type temp = d->text_[i];
2087 if (isNewline(i) || isEnvSeparator(i))
2090 previous_char = temp;
2096 d->begin_of_body_ = i;
2100 bool Paragraph::allowParagraphCustomization() const
2102 return inInset().allowParagraphCustomization();
2106 bool Paragraph::usePlainLayout() const
2108 return inInset().usePlainLayout();
2112 bool Paragraph::isPassThru() const
2114 return inInset().isPassThru() || d->layout_->pass_thru;
2119 // paragraphs inside floats need different alignment tags to avoid
2122 bool noTrivlistCentering(InsetCode code)
2124 return code == FLOAT_CODE
2125 || code == WRAP_CODE
2126 || code == CELL_CODE;
2130 string correction(string const & orig)
2132 if (orig == "flushleft")
2133 return "raggedright";
2134 if (orig == "flushright")
2135 return "raggedleft";
2136 if (orig == "center")
2142 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2143 InsetCode code, bool const lastpar, int & col)
2145 string macro = suffix + "{";
2146 if (noTrivlistCentering(code)) {
2148 // the last paragraph in non-trivlist-aligned
2149 // context is special (to avoid unwanted whitespace)
2150 if (suffix == "\\begin") {
2151 macro = "\\" + correction(env) + "{}";
2152 os << from_ascii(macro);
2153 col += macro.size();
2158 macro += correction(env);
2162 if (suffix == "\\par\\end") {
2166 os << from_ascii(macro);
2167 col += macro.size();
2168 if (suffix == "\\begin") {
2178 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2179 otexstream & os, OutputParams const & runparams) const
2184 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2185 (layout_->toggle_indent != ITOGGLE_NEVER) :
2186 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2188 if (canindent && params_.noindent() && !layout_->pass_thru) {
2189 os << "\\noindent ";
2193 LyXAlignment const curAlign = params_.align();
2195 if (curAlign == layout_->align)
2199 case LYX_ALIGN_NONE:
2200 case LYX_ALIGN_BLOCK:
2201 case LYX_ALIGN_LAYOUT:
2202 case LYX_ALIGN_SPECIAL:
2203 case LYX_ALIGN_DECIMAL:
2205 case LYX_ALIGN_LEFT:
2206 case LYX_ALIGN_RIGHT:
2207 case LYX_ALIGN_CENTER:
2208 if (runparams.moving_arg) {
2215 string const begin_tag = "\\begin";
2216 InsetCode code = ownerCode();
2217 bool const lastpar = runparams.isLastPar;
2220 case LYX_ALIGN_NONE:
2221 case LYX_ALIGN_BLOCK:
2222 case LYX_ALIGN_LAYOUT:
2223 case LYX_ALIGN_SPECIAL:
2224 case LYX_ALIGN_DECIMAL:
2226 case LYX_ALIGN_LEFT: {
2227 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2228 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2230 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2232 } case LYX_ALIGN_RIGHT: {
2233 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2234 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2236 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2238 } case LYX_ALIGN_CENTER: {
2239 corrected_env(os, begin_tag, "center", code, lastpar, column);
2248 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2249 otexstream & os, OutputParams const & runparams) const
2251 LyXAlignment const curAlign = params_.align();
2253 if (curAlign == layout_->align)
2257 case LYX_ALIGN_NONE:
2258 case LYX_ALIGN_BLOCK:
2259 case LYX_ALIGN_LAYOUT:
2260 case LYX_ALIGN_SPECIAL:
2261 case LYX_ALIGN_DECIMAL:
2263 case LYX_ALIGN_LEFT:
2264 case LYX_ALIGN_RIGHT:
2265 case LYX_ALIGN_CENTER:
2266 if (runparams.moving_arg)
2271 bool output = false;
2273 string const end_tag = "\\par\\end";
2274 InsetCode code = ownerCode();
2275 bool const lastpar = runparams.isLastPar;
2278 case LYX_ALIGN_NONE:
2279 case LYX_ALIGN_BLOCK:
2280 case LYX_ALIGN_LAYOUT:
2281 case LYX_ALIGN_SPECIAL:
2282 case LYX_ALIGN_DECIMAL:
2284 case LYX_ALIGN_LEFT: {
2285 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2286 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2288 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2290 } case LYX_ALIGN_RIGHT: {
2291 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2292 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2294 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2296 } case LYX_ALIGN_CENTER: {
2297 corrected_env(os, end_tag, "center", code, lastpar, col);
2302 return output || lastpar;
2306 // This one spits out the text of the paragraph
2307 void Paragraph::latex(BufferParams const & bparams,
2308 Font const & outerfont,
2310 OutputParams const & runparams,
2311 int start_pos, int end_pos, bool force) const
2313 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2315 // FIXME This check should not be needed. Perhaps issue an
2316 // error if it triggers.
2317 Layout const & style = inInset().forcePlainLayout() ?
2318 bparams.documentClass().plainLayout() : *d->layout_;
2320 if (!force && style.inpreamble)
2323 bool const allowcust = allowParagraphCustomization();
2325 // Current base font for all inherited font changes, without any
2326 // change caused by an individual character, except for the language:
2327 // It is set to the language of the first character.
2328 // As long as we are in the label, this font is the base font of the
2329 // label. Before the first body character it is set to the base font
2333 // Maybe we have to create a optional argument.
2334 pos_type body_pos = beginOfBody();
2335 unsigned int column = 0;
2338 // the optional argument is kept in curly brackets in
2339 // case it contains a ']'
2340 // This is not strictly needed, but if this is changed it
2341 // would be a file format change, and tex2lyx would need
2342 // to be adjusted, since it unconditionally removes the
2343 // braces when it parses \item.
2346 basefont = getLabelFont(bparams, outerfont);
2348 basefont = getLayoutFont(bparams, outerfont);
2351 // Which font is currently active?
2352 Font running_font(basefont);
2353 // Do we have an open font change?
2354 bool open_font = false;
2356 Change runningChange = Change(Change::UNCHANGED);
2358 Encoding const * const prev_encoding = runparams.encoding;
2360 os.texrow().start(id(), 0);
2362 // if the paragraph is empty, the loop will not be entered at all
2364 if (style.isCommand()) {
2368 if (!style.leftdelim().empty()) {
2369 os << style.leftdelim();
2370 column += style.leftdelim().size();
2373 column += d->startTeXParParams(bparams, os, runparams);
2376 for (pos_type i = 0; i < size(); ++i) {
2377 // First char in paragraph or after label?
2378 if (i == body_pos) {
2381 column += running_font.latexWriteEndChanges(
2382 os, bparams, runparams,
2383 basefont, basefont);
2386 basefont = getLayoutFont(bparams, outerfont);
2387 running_font = basefont;
2389 column += Changes::latexMarkChange(os, bparams,
2390 runningChange, Change(Change::UNCHANGED),
2392 runningChange = Change(Change::UNCHANGED);
2397 if (style.isCommand()) {
2402 if (!style.leftdelim().empty()) {
2403 os << style.leftdelim();
2404 column += style.leftdelim().size();
2408 column += d->startTeXParParams(bparams, os,
2412 runparams.wasDisplayMath = runparams.inDisplayMath;
2413 runparams.inDisplayMath = false;
2414 bool deleted_display_math = false;
2416 // Check whether a display math inset follows
2417 if (d->text_[i] == META_INSET
2418 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2419 InsetMath const * im = getInset(i)->asInsetMath();
2420 if (im && im->asHullInset()
2421 && im->asHullInset()->outerDisplay()) {
2422 runparams.inDisplayMath = true;
2423 // runparams.inDeletedInset will be set by
2424 // latexInset later, but we need this info
2425 // before it is called. On the other hand, we
2426 // cannot set it here because it is a counter.
2427 deleted_display_math = isDeleted(i);
2431 Change const & change = runparams.inDeletedInset
2432 ? runparams.changeOfDeletedInset : lookupChange(i);
2434 if (bparams.output_changes && runningChange != change) {
2436 column += running_font.latexWriteEndChanges(
2437 os, bparams, runparams, basefont, basefont);
2440 basefont = getLayoutFont(bparams, outerfont);
2441 running_font = basefont;
2442 column += Changes::latexMarkChange(os, bparams, runningChange,
2444 runningChange = change;
2447 // do not output text which is marked deleted
2448 // if change tracking output is disabled
2449 if (!bparams.output_changes && change.deleted()) {
2455 // Fully instantiated font
2456 Font const current_font = getFont(bparams, i, outerfont);
2458 Font const last_font = running_font;
2460 // Do we need to close the previous font?
2462 (current_font != running_font ||
2463 current_font.language() != running_font.language()))
2465 column += running_font.latexWriteEndChanges(
2466 os, bparams, runparams, basefont,
2467 (i == body_pos-1) ? basefont : current_font);
2468 running_font = basefont;
2472 string const running_lang = runparams.use_polyglossia ?
2473 running_font.language()->polyglossia() : running_font.language()->babel();
2474 // close babel's font environment before opening CJK.
2475 string const lang_end_command = runparams.use_polyglossia ?
2476 "\\end{$$lang}" : lyxrc.language_command_end;
2477 if (!running_lang.empty() &&
2478 current_font.language()->encoding()->package() == Encoding::CJK) {
2479 string end_tag = subst(lang_end_command,
2482 os << from_ascii(end_tag);
2483 column += end_tag.length();
2484 if (runparams.use_polyglossia)
2485 popPolyglossiaLang();
2488 // Switch file encoding if necessary (and allowed)
2489 if (!runparams.pass_thru && !style.pass_thru &&
2490 runparams.encoding->package() != Encoding::none &&
2491 current_font.language()->encoding()->package() != Encoding::none) {
2492 pair<bool, int> const enc_switch =
2493 switchEncoding(os.os(), bparams, runparams,
2494 *(current_font.language()->encoding()));
2495 if (enc_switch.first) {
2496 column += enc_switch.second;
2497 runparams.encoding = current_font.language()->encoding();
2501 char_type const c = d->text_[i];
2503 // A display math inset inside an ulem command will be output
2504 // as a box of width \columnwidth, so we have to either disable
2505 // indentation if the inset starts a paragraph, or start a new
2506 // line to accommodate such box. This has to be done before
2507 // writing any font changing commands.
2508 if (runparams.inDisplayMath && !deleted_display_math
2509 && runparams.inulemcmd) {
2510 if (os.afterParbreak())
2516 // Do we need to change font?
2517 if ((current_font != running_font ||
2518 current_font.language() != running_font.language()) &&
2521 odocstringstream ods;
2522 column += current_font.latexWriteStartChanges(ods, bparams,
2523 runparams, basefont,
2525 // Check again for display math in ulem commands as a
2526 // font change may also occur just before a math inset.
2527 if (runparams.inDisplayMath && !deleted_display_math
2528 && runparams.inulemcmd) {
2529 if (os.afterParbreak())
2534 running_font = current_font;
2536 docstring fontchange = ods.str();
2537 // check whether the fontchange ends with a \\textcolor
2538 // modifier and the text starts with a space (bug 4473)
2539 docstring const last_modifier = rsplit(fontchange, '\\');
2540 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2541 os << fontchange << from_ascii("{}");
2542 // check if the fontchange ends with a trailing blank
2543 // (like "\small " (see bug 3382)
2544 else if (suffixIs(fontchange, ' ') && c == ' ')
2545 os << fontchange.substr(0, fontchange.size() - 1)
2546 << from_ascii("{}");
2551 // FIXME: think about end_pos implementation...
2552 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2553 // FIXME: integrate this case in latexSpecialChar
2554 // Do not print the separation of the optional argument
2555 // if style.pass_thru is false. This works because
2556 // latexSpecialChar ignores spaces if
2557 // style.pass_thru is false.
2558 if (i != body_pos - 1) {
2559 if (d->simpleTeXBlanks(runparams, os,
2560 i, column, current_font, style)) {
2561 // A surrogate pair was output. We
2562 // must not call latexSpecialChar
2563 // in this iteration, since it would output
2564 // the combining character again.
2571 OutputParams rp = runparams;
2572 rp.free_spacing = style.free_spacing;
2573 rp.local_font = ¤t_font;
2574 rp.intitle = style.intitle;
2576 // Two major modes: LaTeX or plain
2577 // Handle here those cases common to both modes
2578 // and then split to handle the two modes separately.
2579 if (c == META_INSET) {
2580 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2581 d->latexInset(bparams, os, rp, running_font,
2582 basefont, outerfont, open_font,
2583 runningChange, style, i, column);
2585 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2587 d->latexSpecialChar(os, bparams, rp,
2588 running_font, runningChange,
2589 style, i, end_pos, column);
2590 } catch (EncodingException & e) {
2591 if (runparams.dryrun) {
2592 os << "<" << _("LyX Warning: ")
2593 << _("uncodable character") << " '";
2597 // add location information and throw again.
2605 // Set the encoding to that returned from latexSpecialChar (see
2606 // comment for encoding member in OutputParams.h)
2607 runparams.encoding = rp.encoding;
2609 // Also carry on the info on a closed ulem command for insets
2610 // such as Note that do not produce any output, so that no
2611 // command is ever executed but its opening was recorded.
2612 runparams.inulemcmd = rp.inulemcmd;
2615 // If we have an open font definition, we have to close it
2617 #ifdef FIXED_LANGUAGE_END_DETECTION
2619 running_font.latexWriteEndChanges(os, bparams,
2620 runparams, basefont,
2621 next_->getFont(bparams, 0, outerfont));
2623 running_font.latexWriteEndChanges(os, bparams,
2624 runparams, basefont, basefont);
2627 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2628 //FIXME: there as we start another \selectlanguage with the next paragraph if
2629 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2630 running_font.latexWriteEndChanges(os, bparams, runparams,
2631 basefont, basefont);
2635 column += Changes::latexMarkChange(os, bparams, runningChange,
2636 Change(Change::UNCHANGED), runparams);
2638 // Needed if there is an optional argument but no contents.
2639 if (body_pos > 0 && body_pos == size()) {
2643 if (!style.rightdelim().empty()) {
2644 os << style.rightdelim();
2645 column += style.rightdelim().size();
2648 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2649 && runparams.encoding != prev_encoding) {
2650 runparams.encoding = prev_encoding;
2651 os << setEncoding(prev_encoding->iconvName());
2654 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2658 bool Paragraph::emptyTag() const
2660 for (pos_type i = 0; i < size(); ++i) {
2661 if (Inset const * inset = getInset(i)) {
2662 InsetCode lyx_code = inset->lyxCode();
2663 // FIXME testing like that is wrong. What is
2665 if (lyx_code != TOC_CODE &&
2666 lyx_code != INCLUDE_CODE &&
2667 lyx_code != GRAPHICS_CODE &&
2668 lyx_code != ERT_CODE &&
2669 lyx_code != LISTINGS_CODE &&
2670 lyx_code != FLOAT_CODE &&
2671 lyx_code != TABULAR_CODE) {
2675 char_type c = d->text_[i];
2676 if (c != ' ' && c != '\t')
2684 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2687 for (pos_type i = 0; i < size(); ++i) {
2688 if (Inset const * inset = getInset(i)) {
2689 InsetCode lyx_code = inset->lyxCode();
2690 if (lyx_code == LABEL_CODE) {
2691 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2692 docstring const & id = il->getParam("name");
2693 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2701 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2705 for (i = 0; i < size(); ++i) {
2706 if (Inset const * inset = getInset(i)) {
2707 inset->docbook(os, runparams);
2709 char_type c = d->text_[i];
2712 os << sgml::escapeChar(c);
2719 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2723 for (i = 0; i < size(); ++i) {
2724 if (Inset const * inset = getInset(i)) {
2725 inset->xhtml(xs, runparams);
2727 char_type c = d->text_[i];
2737 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2740 pos_type size = text_.size();
2741 for (pos_type i = initial; i < size; ++i) {
2742 Font font = owner_->getFont(buf.params(), i, outerfont);
2743 if (text_[i] == META_INSET)
2745 if (i != initial && font != font_old)
2754 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2756 OutputParams const & runparams,
2757 Font const & outerfont,
2758 pos_type initial) const
2760 bool emph_flag = false;
2762 Layout const & style = *d->layout_;
2764 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2766 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2769 // parsing main loop
2770 for (pos_type i = initial; i < size(); ++i) {
2771 Font font = getFont(buf.params(), i, outerfont);
2773 // handle <emphasis> tag
2774 if (font_old.emph() != font.fontInfo().emph()) {
2775 if (font.fontInfo().emph() == FONT_ON) {
2778 } else if (i != initial) {
2779 os << "</emphasis>";
2784 if (Inset const * inset = getInset(i)) {
2785 inset->docbook(os, runparams);
2787 char_type c = d->text_[i];
2789 if (style.pass_thru)
2792 os << sgml::escapeChar(c);
2794 font_old = font.fontInfo();
2798 os << "</emphasis>";
2801 if (style.free_spacing)
2803 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2809 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2810 vector<html::EndFontTag> & tagsToClose,
2811 bool & flag, FontState curstate, html::FontTypes type)
2813 if (curstate == FONT_ON) {
2814 tagsToOpen.push_back(html::FontTag(type));
2817 tagsToClose.push_back(html::EndFontTag(type));
2824 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2826 OutputParams const & runparams,
2827 Font const & outerfont,
2828 bool start_paragraph, bool close_paragraph,
2829 pos_type initial) const
2833 // track whether we have opened these tags
2834 bool emph_flag = false;
2835 bool bold_flag = false;
2836 bool noun_flag = false;
2837 bool ubar_flag = false;
2838 bool dbar_flag = false;
2839 bool sout_flag = false;
2840 bool wave_flag = false;
2842 bool shap_flag = false;
2844 bool faml_flag = false;
2846 bool size_flag = false;
2848 Layout const & style = *d->layout_;
2850 if (start_paragraph)
2851 xs.startDivision(allowEmpty());
2854 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2856 FontShape curr_fs = INHERIT_SHAPE;
2857 FontFamily curr_fam = INHERIT_FAMILY;
2858 FontSize curr_size = FONT_SIZE_INHERIT;
2860 string const default_family =
2861 buf.masterBuffer()->params().fonts_default_family;
2863 vector<html::FontTag> tagsToOpen;
2864 vector<html::EndFontTag> tagsToClose;
2866 // parsing main loop
2867 for (pos_type i = initial; i < size(); ++i) {
2868 // let's not show deleted material in the output
2872 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2875 FontState curstate = font.fontInfo().emph();
2876 if (font_old.emph() != curstate)
2877 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2880 curstate = font.fontInfo().noun();
2881 if (font_old.noun() != curstate)
2882 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2885 curstate = font.fontInfo().underbar();
2886 if (font_old.underbar() != curstate)
2887 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2890 curstate = font.fontInfo().strikeout();
2891 if (font_old.strikeout() != curstate)
2892 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2895 curstate = font.fontInfo().uuline();
2896 if (font_old.uuline() != curstate)
2897 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2900 curstate = font.fontInfo().uwave();
2901 if (font_old.uwave() != curstate)
2902 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2905 // a little hackish, but allows us to reuse what we have.
2906 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2907 if (font_old.series() != font.fontInfo().series())
2908 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2911 curr_fs = font.fontInfo().shape();
2912 FontShape old_fs = font_old.shape();
2913 if (old_fs != curr_fs) {
2917 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2920 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2922 case SMALLCAPS_SHAPE:
2923 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2929 // the other tags are for internal use
2937 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2941 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2944 case SMALLCAPS_SHAPE:
2945 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2952 // the other tags are for internal use
2959 curr_fam = font.fontInfo().family();
2960 FontFamily old_fam = font_old.family();
2961 if (old_fam != curr_fam) {
2965 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2968 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2970 case TYPEWRITER_FAMILY:
2971 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2973 case INHERIT_FAMILY:
2976 // the other tags are for internal use
2984 // we will treat a "default" font family as roman, since we have
2985 // no other idea what to do.
2986 if (default_family != "rmdefault" && default_family != "default") {
2987 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
2992 if (default_family != "sfdefault") {
2993 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
2997 case TYPEWRITER_FAMILY:
2998 if (default_family != "ttdefault") {
2999 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3003 case INHERIT_FAMILY:
3006 // the other tags are for internal use
3013 curr_size = font.fontInfo().size();
3014 FontSize old_size = font_old.size();
3015 if (old_size != curr_size) {
3018 case FONT_SIZE_TINY:
3019 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3021 case FONT_SIZE_SCRIPT:
3022 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3024 case FONT_SIZE_FOOTNOTE:
3025 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3027 case FONT_SIZE_SMALL:
3028 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3030 case FONT_SIZE_LARGE:
3031 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3033 case FONT_SIZE_LARGER:
3034 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3036 case FONT_SIZE_LARGEST:
3037 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3039 case FONT_SIZE_HUGE:
3040 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3042 case FONT_SIZE_HUGER:
3043 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3045 case FONT_SIZE_INCREASE:
3046 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3048 case FONT_SIZE_DECREASE:
3049 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3051 case FONT_SIZE_INHERIT:
3052 case FONT_SIZE_NORMAL:
3055 // the other tags are for internal use
3061 switch (curr_size) {
3062 case FONT_SIZE_TINY:
3063 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3066 case FONT_SIZE_SCRIPT:
3067 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3070 case FONT_SIZE_FOOTNOTE:
3071 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3074 case FONT_SIZE_SMALL:
3075 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3078 case FONT_SIZE_LARGE:
3079 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3082 case FONT_SIZE_LARGER:
3083 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3086 case FONT_SIZE_LARGEST:
3087 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3090 case FONT_SIZE_HUGE:
3091 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3094 case FONT_SIZE_HUGER:
3095 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3098 case FONT_SIZE_INCREASE:
3099 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3102 case FONT_SIZE_DECREASE:
3103 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3106 case FONT_SIZE_NORMAL:
3107 case FONT_SIZE_INHERIT:
3110 // the other tags are for internal use
3117 // Other such tags? What about the other text ranges?
3119 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3120 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3121 for (; cit != cen; ++cit)
3124 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3125 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3126 for (; sit != sen; ++sit)
3129 tagsToClose.clear();
3132 Inset const * inset = getInset(i);
3134 if (!runparams.for_toc || inset->isInToc()) {
3135 OutputParams np = runparams;
3136 np.local_font = &font;
3137 // If the paragraph has size 1, then we are in the "special
3138 // case" where we do not output the containing paragraph info
3139 if (!inset->getLayout().htmlisblock() && size() != 1)
3140 np.html_in_par = true;
3141 retval += inset->xhtml(xs, np);
3144 char_type c = getUChar(buf.masterBuffer()->params(), i);
3147 font_old = font.fontInfo();
3151 // I'm worried about what happens if a branch, say, is itself
3152 // wrapped in some font stuff. I think that will not work.
3154 if (close_paragraph)
3161 bool Paragraph::isHfill(pos_type pos) const
3163 Inset const * inset = getInset(pos);
3164 return inset && inset->isHfill();
3168 bool Paragraph::isNewline(pos_type pos) const
3170 // U+2028 LINE SEPARATOR
3171 // U+2029 PARAGRAPH SEPARATOR
3172 char_type const c = d->text_[pos];
3173 if (c == 0x2028 || c == 0x2029)
3175 Inset const * inset = getInset(pos);
3176 return inset && inset->lyxCode() == NEWLINE_CODE;
3180 bool Paragraph::isEnvSeparator(pos_type pos) const
3182 Inset const * inset = getInset(pos);
3183 return inset && inset->lyxCode() == SEPARATOR_CODE;
3187 bool Paragraph::isLineSeparator(pos_type pos) const
3189 char_type const c = d->text_[pos];
3190 if (isLineSeparatorChar(c))
3192 Inset const * inset = getInset(pos);
3193 return inset && inset->isLineSeparator();
3197 bool Paragraph::isWordSeparator(pos_type pos) const
3201 if (Inset const * inset = getInset(pos))
3202 return !inset->isLetter();
3203 // if we have a hard hyphen (no en- or emdash) or apostrophe
3204 // we pass this to the spell checker
3205 // FIXME: this method is subject to change, visit
3206 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3207 // to get an impression how complex this is.
3208 if (isHardHyphenOrApostrophe(pos))
3210 char_type const c = d->text_[pos];
3211 // We want to pass the escape chars to the spellchecker
3212 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3213 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3217 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3219 pos_type const psize = size();
3222 char_type const c = d->text_[pos];
3223 if (c != '-' && c != '\'')
3225 int nextpos = pos + 1;
3226 int prevpos = pos > 0 ? pos - 1 : 0;
3227 if ((nextpos == psize || isSpace(nextpos))
3228 && (pos == 0 || isSpace(prevpos)))
3234 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3236 return d->speller_state_.getRange(pos);
3240 bool Paragraph::isChar(pos_type pos) const
3242 if (Inset const * inset = getInset(pos))
3243 return inset->isChar();
3244 char_type const c = d->text_[pos];
3245 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3249 bool Paragraph::isSpace(pos_type pos) const
3251 if (Inset const * inset = getInset(pos))
3252 return inset->isSpace();
3253 char_type const c = d->text_[pos];
3254 return lyx::isSpace(c);
3259 Paragraph::getParLanguage(BufferParams const & bparams) const
3262 return getFirstFontSettings(bparams).language();
3263 // FIXME: we should check the prev par as well (Lgb)
3264 return bparams.language;
3268 bool Paragraph::isRTL(BufferParams const & bparams) const
3270 return getParLanguage(bparams)->rightToLeft()
3271 && !inInset().getLayout().forceLTR();
3275 void Paragraph::changeLanguage(BufferParams const & bparams,
3276 Language const * from, Language const * to)
3278 // change language including dummy font change at the end
3279 for (pos_type i = 0; i <= size(); ++i) {
3280 Font font = getFontSettings(bparams, i);
3281 if (font.language() == from) {
3282 font.setLanguage(to);
3284 d->requestSpellCheck(i);
3290 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3292 Language const * doc_language = bparams.language;
3293 FontList::const_iterator cit = d->fontlist_.begin();
3294 FontList::const_iterator end = d->fontlist_.end();
3296 for (; cit != end; ++cit)
3297 if (cit->font().language() != ignore_language &&
3298 cit->font().language() != latex_language &&
3299 cit->font().language() != doc_language)
3305 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3307 FontList::const_iterator cit = d->fontlist_.begin();
3308 FontList::const_iterator end = d->fontlist_.end();
3310 for (; cit != end; ++cit) {
3311 Language const * lang = cit->font().language();
3312 if (lang != ignore_language &&
3313 lang != latex_language)
3314 languages.insert(lang);
3319 docstring Paragraph::asString(int options) const
3321 return asString(0, size(), options);
3325 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3327 odocstringstream os;
3330 && options & AS_STR_LABEL
3331 && !d->params_.labelString().empty())
3332 os << d->params_.labelString() << ' ';
3334 for (pos_type i = beg; i < end; ++i) {
3335 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3337 char_type const c = d->text_[i];
3338 if (isPrintable(c) || c == '\t'
3339 || (c == '\n' && (options & AS_STR_NEWLINES)))
3341 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3342 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3343 LASSERT(runparams != 0, return docstring());
3344 getInset(i)->plaintext(os, *runparams);
3346 getInset(i)->toString(os);
3355 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3356 bool const shorten, bool const label) const
3358 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3359 if (label && !labelString().empty())
3360 os += labelString() + ' ';
3361 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3364 char_type const c = d->text_[i];
3367 else if (c == META_INSET)
3368 getInset(i)->forOutliner(os, tmplen, false);
3371 Text::shortenForOutliner(os, maxlen);
3375 void Paragraph::setInsetOwner(Inset const * inset)
3377 d->inset_owner_ = inset;
3381 int Paragraph::id() const
3387 void Paragraph::setId(int id)
3393 Layout const & Paragraph::layout() const
3399 void Paragraph::setLayout(Layout const & layout)
3401 d->layout_ = &layout;
3405 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3407 setLayout(tc.defaultLayout());
3411 void Paragraph::setPlainLayout(DocumentClass const & tc)
3413 setLayout(tc.plainLayout());
3417 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3419 if (usePlainLayout())
3420 setPlainLayout(tclass);
3422 setDefaultLayout(tclass);
3426 Inset const & Paragraph::inInset() const
3428 LBUFERR(d->inset_owner_);
3429 return *d->inset_owner_;
3433 ParagraphParameters & Paragraph::params()
3439 ParagraphParameters const & Paragraph::params() const
3445 bool Paragraph::isFreeSpacing() const
3447 if (d->layout_->free_spacing)
3449 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3453 bool Paragraph::allowEmpty() const
3455 if (d->layout_->keepempty)
3457 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3461 bool Paragraph::brokenBiblio() const
3463 // there is a problem if there is no bibitem at position 0 or
3464 // if there is another bibitem in the paragraph.
3465 return d->layout_->labeltype == LABEL_BIBLIO
3466 && (d->insetlist_.find(BIBITEM_CODE) != 0
3467 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3471 int Paragraph::fixBiblio(Buffer const & buffer)
3473 // FIXME: What about the case where paragraph is not BIBLIO
3474 // but there is an InsetBibitem?
3475 // FIXME: when there was already an inset at 0, the return value is 1,
3476 // which does not tell whether another inset has been remove; the
3477 // cursor cannot be correctly updated.
3479 if (d->layout_->labeltype != LABEL_BIBLIO)
3482 bool const track_changes = buffer.params().track_changes;
3483 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3484 bool const hasbibitem0 = bibitem_pos == 0;
3487 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3488 // There was an InsetBibitem at pos 0, and no other one => OK
3489 if (bibitem_pos == -1)
3491 // there is a bibitem at the 0 position, but since
3492 // there is a second one, we copy the second on the
3493 // first. We're assuming there are at most two of
3494 // these, which there should be.
3495 // FIXME: why does it make sense to do that rather
3496 // than keep the first? (JMarc)
3497 Inset * inset = releaseInset(bibitem_pos);
3498 d->insetlist_.begin()->inset = inset;
3499 return -bibitem_pos;
3502 // We need to create an inset at the beginning
3504 if (bibitem_pos > 0) {
3505 // there was one somewhere in the paragraph, let's move it
3506 inset = d->insetlist_.release(bibitem_pos);
3507 eraseChar(bibitem_pos, track_changes);
3510 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3511 InsetCommandParams(BIBITEM_CODE));
3513 Font font(inherit_font, buffer.params().language);
3514 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3515 : Change::UNCHANGED));
3521 void Paragraph::checkAuthors(AuthorList const & authorList)
3523 d->changes_.checkAuthors(authorList);
3527 bool Paragraph::isChanged(pos_type pos) const
3529 return lookupChange(pos).changed();
3533 bool Paragraph::isInserted(pos_type pos) const
3535 return lookupChange(pos).inserted();
3539 bool Paragraph::isDeleted(pos_type pos) const
3541 return lookupChange(pos).deleted();
3545 InsetList const & Paragraph::insetList() const
3547 return d->insetlist_;
3551 void Paragraph::setBuffer(Buffer & b)
3553 d->insetlist_.setBuffer(b);
3557 void Paragraph::resetBuffer()
3559 d->insetlist_.resetBuffer();
3563 Inset * Paragraph::releaseInset(pos_type pos)
3565 Inset * inset = d->insetlist_.release(pos);
3566 /// does not honour change tracking!
3567 eraseChar(pos, false);
3572 Inset * Paragraph::getInset(pos_type pos)
3574 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3575 ? d->insetlist_.get(pos) : 0;
3579 Inset const * Paragraph::getInset(pos_type pos) const
3581 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3582 ? d->insetlist_.get(pos) : 0;
3586 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3587 pos_type & right, TextCase action)
3589 // process sequences of modified characters; in change
3590 // tracking mode, this approach results in much better
3591 // usability than changing case on a char-by-char basis
3592 // We also need to track the current font, since font
3593 // changes within sequences can occur.
3594 vector<pair<char_type, Font> > changes;
3596 bool const trackChanges = bparams.track_changes;
3598 bool capitalize = true;
3600 for (; pos < right; ++pos) {
3601 char_type oldChar = d->text_[pos];
3602 char_type newChar = oldChar;
3604 // ignore insets and don't play with deleted text!
3605 if (oldChar != META_INSET && !isDeleted(pos)) {
3607 case text_lowercase:
3608 newChar = lowercase(oldChar);
3610 case text_capitalization:
3612 newChar = uppercase(oldChar);
3616 case text_uppercase:
3617 newChar = uppercase(oldChar);
3622 if (isWordSeparator(pos) || isDeleted(pos)) {
3623 // permit capitalization again
3627 if (oldChar != newChar) {
3628 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3629 if (pos != right - 1)
3631 // step behind the changing area
3635 int erasePos = pos - changes.size();
3636 for (size_t i = 0; i < changes.size(); i++) {
3637 insertChar(pos, changes[i].first,
3640 if (!eraseChar(erasePos, trackChanges)) {
3643 ++right; // expand selection
3651 int Paragraph::find(docstring const & str, bool cs, bool mw,
3652 pos_type start_pos, bool del) const
3654 pos_type pos = start_pos;
3655 int const strsize = str.length();
3657 pos_type const parsize = d->text_.size();
3658 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3659 // Ignore "invisible" letters such as ligature breaks
3660 // and hyphenation chars while searching
3661 while (pos < parsize - 1 && isInset(pos)) {
3662 odocstringstream os;
3663 getInset(pos)->toString(os);
3664 if (!getInset(pos)->isLetter() || !os.str().empty())
3668 if (cs && str[i] != d->text_[pos])
3670 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3672 if (!del && isDeleted(pos))
3679 // if necessary, check whether string matches word
3681 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3684 && !isWordSeparator(pos))
3688 return pos - start_pos;
3692 char_type Paragraph::getChar(pos_type pos) const
3694 return d->text_[pos];
3698 pos_type Paragraph::size() const
3700 return d->text_.size();
3704 bool Paragraph::empty() const
3706 return d->text_.empty();
3710 bool Paragraph::isInset(pos_type pos) const
3712 return d->text_[pos] == META_INSET;
3716 bool Paragraph::isSeparator(pos_type pos) const
3718 //FIXME: Are we sure this can be the only separator?
3719 return d->text_[pos] == ' ';
3723 void Paragraph::deregisterWords()
3725 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3726 Private::LangWordsMap::const_iterator ite = d->words_.end();
3727 for (; itl != ite; ++itl) {
3728 WordList & wl = theWordList(itl->first);
3729 Private::Words::const_iterator it = (itl->second).begin();
3730 Private::Words::const_iterator et = (itl->second).end();
3731 for (; it != et; ++it)
3738 void Paragraph::locateWord(pos_type & from, pos_type & to,
3739 word_location const loc) const
3742 case WHOLE_WORD_STRICT:
3743 if (from == 0 || from == size()
3744 || isWordSeparator(from)
3745 || isWordSeparator(from - 1)) {
3749 // no break here, we go to the next
3752 // If we are already at the beginning of a word, do nothing
3753 if (!from || isWordSeparator(from - 1))
3755 // no break here, we go to the next
3758 // always move the cursor to the beginning of previous word
3759 while (from && !isWordSeparator(from - 1))
3763 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3766 // no need to move the 'from' cursor
3770 while (to < size() && !isWordSeparator(to))
3775 void Paragraph::collectWords()
3777 for (pos_type pos = 0; pos < size(); ++pos) {
3778 if (isWordSeparator(pos))
3780 pos_type from = pos;
3781 locateWord(from, pos, WHOLE_WORD);
3782 // Work around MSVC warning: The statement
3783 // if (pos < from + lyxrc.completion_minlength)
3784 // triggers a signed vs. unsigned warning.
3785 // I don't know why this happens, it could be a MSVC bug, or
3786 // related to LLP64 (windows) vs. LP64 (unix) programming
3787 // model, or the C++ standard might be ambigous in the section
3788 // defining the "usual arithmetic conversions". However, using
3789 // a temporary variable is safe and works on all compilers.
3790 pos_type const endpos = from + lyxrc.completion_minlength;
3793 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3794 if (cit == d->fontlist_.end())
3796 Language const * lang = cit->font().language();
3797 docstring const word = asString(from, pos, AS_STR_NONE);
3798 d->words_[lang->lang()].insert(word);
3803 void Paragraph::registerWords()
3805 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3806 Private::LangWordsMap::const_iterator ite = d->words_.end();
3807 for (; itl != ite; ++itl) {
3808 WordList & wl = theWordList(itl->first);
3809 Private::Words::const_iterator it = (itl->second).begin();
3810 Private::Words::const_iterator et = (itl->second).end();
3811 for (; it != et; ++it)
3817 void Paragraph::updateWords()
3825 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3827 SkipPositionsIterator begin = skips.begin();
3828 SkipPositions::iterator end = skips.end();
3829 if (pos > 0 && begin < end) {
3831 if (end->last == pos - 1) {
3836 skips.insert(end, FontSpan(pos, pos));
3840 Language * Paragraph::Private::locateSpellRange(
3841 pos_type & from, pos_type & to,
3842 SkipPositions & skips) const
3844 // skip leading white space
3845 while (from < to && owner_->isWordSeparator(from))
3847 // don't check empty range
3850 // get current language
3851 Language * lang = getSpellLanguage(from);
3852 pos_type last = from;
3853 bool samelang = true;
3854 bool sameinset = true;
3855 while (last < to && samelang && sameinset) {
3856 // hop to end of word
3857 while (last < to && !owner_->isWordSeparator(last)) {
3858 if (owner_->getInset(last)) {
3859 appendSkipPosition(skips, last);
3860 } else if (owner_->isDeleted(last)) {
3861 appendSkipPosition(skips, last);
3865 // hop to next word while checking for insets
3866 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3867 if (Inset const * inset = owner_->getInset(last))
3868 sameinset = inset->isChar() && inset->isLetter();
3869 if (sameinset && owner_->isDeleted(last)) {
3870 appendSkipPosition(skips, last);
3875 if (sameinset && last < to) {
3876 // now check for language change
3877 samelang = lang == getSpellLanguage(last);
3880 // if language change detected backstep is needed
3888 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3891 const_cast<Language *>(owner_->getFontSettings(
3892 inset_owner_->buffer().params(), from).language());
3893 if (lang == inset_owner_->buffer().params().language
3894 && !lyxrc.spellchecker_alt_lang.empty()) {
3896 string const lang_variety =
3897 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3898 lang->setCode(lang_code);
3899 lang->setVariety(lang_variety);
3905 void Paragraph::requestSpellCheck(pos_type pos)
3907 d->requestSpellCheck(pos);
3911 bool Paragraph::needsSpellCheck() const
3913 SpellChecker::ChangeNumber speller_change_number = 0;
3914 if (theSpellChecker())
3915 speller_change_number = theSpellChecker()->changeNumber();
3916 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3917 d->speller_state_.needsCompleteRefresh(speller_change_number);
3919 return d->needsSpellCheck();
3923 bool Paragraph::Private::ignoreWord(docstring const & word) const
3925 // Ignore words with digits
3926 // FIXME: make this customizable
3927 // (note that some checkers ignore words with digits by default)
3928 docstring::const_iterator cit = word.begin();
3929 docstring::const_iterator const end = word.end();
3930 for (; cit != end; ++cit) {
3931 if (isNumber((*cit)))
3938 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3939 WordLangTuple & wl, docstring_list & suggestions,
3940 bool do_suggestion, bool check_learned) const
3942 SpellChecker::Result result = SpellChecker::WORD_OK;
3943 SpellChecker * speller = theSpellChecker();
3947 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3950 locateWord(from, to, WHOLE_WORD);
3951 if (from == to || from >= size())
3954 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3955 Language * lang = d->getSpellLanguage(from);
3957 wl = WordLangTuple(word, lang);
3962 if (needsSpellCheck() || check_learned) {
3964 if (!d->ignoreWord(word)) {
3965 bool const trailing_dot = to < size() && d->text_[to] == '.';
3966 result = speller->check(wl);
3967 if (SpellChecker::misspelled(result) && trailing_dot) {
3968 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3969 result = speller->check(wl);
3970 if (!SpellChecker::misspelled(result)) {
3971 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3973 from << ".." << to << "]");
3975 // spell check with dot appended failed too
3976 // restore original word/lang value
3977 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3978 wl = WordLangTuple(word, lang);
3982 if (!SpellChecker::misspelled(result)) {
3983 // area up to the begin of the next word is not misspelled
3984 while (end < size() && isWordSeparator(end))
3987 d->setMisspelled(from, end, result);
3989 result = d->speller_state_.getState(from);
3993 suggestions.clear();
3995 if (SpellChecker::misspelled(result)) {
3996 LYXERR(Debug::GUI, "misspelled word: \"" <<
3998 from << ".." << to << "]");
4000 speller->suggest(wl, suggestions);
4006 void Paragraph::Private::markMisspelledWords(
4007 pos_type const & first, pos_type const & last,
4008 SpellChecker::Result result,
4009 docstring const & word,
4010 SkipPositions const & skips)
4012 if (!SpellChecker::misspelled(result)) {
4013 setMisspelled(first, last, SpellChecker::WORD_OK);
4017 SpellChecker * speller = theSpellChecker();
4018 // locate and enumerate the error positions
4019 int nerrors = speller->numMisspelledWords();
4021 SkipPositionsIterator it = skips.begin();
4022 SkipPositionsIterator et = skips.end();
4023 for (int index = 0; index < nerrors; ++index) {
4026 speller->misspelledWord(index, wstart, wlen);
4027 /// should not happen if speller supports range checks
4028 if (!wlen) continue;
4029 docstring const misspelled = word.substr(wstart, wlen);
4030 wstart += first + numskipped;
4031 if (snext < wstart) {
4032 /// mark the range of correct spelling
4033 numskipped += countSkips(it, et, wstart);
4034 setMisspelled(snext,
4035 wstart - 1, SpellChecker::WORD_OK);
4037 snext = wstart + wlen;
4038 numskipped += countSkips(it, et, snext);
4039 /// mark the range of misspelling
4040 setMisspelled(wstart, snext, result);
4041 LYXERR(Debug::GUI, "misspelled word: \"" <<
4042 misspelled << "\" [" <<
4043 wstart << ".." << (snext-1) << "]");
4046 if (snext <= last) {
4047 /// mark the range of correct spelling at end
4048 setMisspelled(snext, last, SpellChecker::WORD_OK);
4053 void Paragraph::spellCheck() const
4055 SpellChecker * speller = theSpellChecker();
4056 if (!speller || empty() ||!needsSpellCheck())
4060 d->rangeOfSpellCheck(start, endpos);
4061 if (speller->canCheckParagraph()) {
4062 // loop until we leave the range
4063 for (pos_type first = start; first < endpos; ) {
4064 pos_type last = endpos;
4065 Private::SkipPositions skips;
4066 Language * lang = d->locateSpellRange(first, last, skips);
4067 if (first >= endpos)
4069 // start the spell checker on the unit of meaning
4070 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4071 WordLangTuple wl = WordLangTuple(word, lang);
4072 SpellChecker::Result result = word.size() ?
4073 speller->check(wl) : SpellChecker::WORD_OK;
4074 d->markMisspelledWords(first, last, result, word, skips);
4078 static docstring_list suggestions;
4079 pos_type to = endpos;
4080 while (start < endpos) {
4082 spellCheck(start, to, wl, suggestions, false);
4086 d->readySpellCheck();
4090 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4092 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4093 if (result || pos <= 0 || pos > size())
4095 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4096 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4101 string Paragraph::magicLabel() const
4104 ss << "magicparlabel-" << id();