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 "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
55 #include "mathed/InsetMathHull.h"
57 #include "support/debug.h"
58 #include "support/docstring_list.h"
59 #include "support/ExceptionMessage.h"
60 #include "support/gettext.h"
61 #include "support/lassert.h"
62 #include "support/lstrings.h"
63 #include "support/textutils.h"
69 using namespace lyx::support;
75 /// Inset identifier (above 0x10ffff, for ucs-4)
76 char_type const META_INSET = 0x200001;
81 /////////////////////////////////////////////////////////////////////
85 /////////////////////////////////////////////////////////////////////
87 class SpellResultRange {
89 SpellResultRange(FontSpan range, SpellChecker::Result result)
90 : range_(range), result_(result)
93 FontSpan const & range() const { return range_; }
95 void range(FontSpan const & r) { range_ = r; }
97 SpellChecker::Result result() const { return result_; }
99 void result(SpellChecker::Result r) { result_ = r; }
101 bool contains(pos_type pos) const { return range_.contains(pos); }
103 bool covered(FontSpan const & r) const
105 // 1. first of new range inside current range or
106 // 2. last of new range inside current range or
107 // 3. first of current range inside new range or
108 // 4. last of current range inside new range
109 //FIXME: is this the same as !range_.intersect(r).empty() ?
110 return range_.contains(r.first) || range_.contains(r.last) ||
111 r.contains(range_.first) || r.contains(range_.last);
114 void shift(pos_type pos, int offset)
116 if (range_.first > pos) {
117 range_.first += offset;
118 range_.last += offset;
119 } else if (range_.last >= pos) {
120 range_.last += offset;
125 SpellChecker::Result result_ ;
129 /////////////////////////////////////////////////////////////////////
133 /////////////////////////////////////////////////////////////////////
135 class SpellCheckerState {
139 needs_refresh_ = true;
140 current_change_number_ = 0;
143 void setRange(FontSpan const & fp, SpellChecker::Result state)
146 RangesIterator et = ranges_.end();
147 RangesIterator it = ranges_.begin();
148 for (; it != et; ++it) {
149 if (!it->covered(fp))
150 result.push_back(SpellResultRange(it->range(), it->result()));
151 else if (state == SpellChecker::WORD_OK) {
152 // trim or split the current misspelled range
153 // store misspelled ranges only
154 FontSpan range = it->range();
155 if (fp.first > range.first) {
156 // misspelled area in front of WORD_OK
157 range.last = fp.first - 1;
158 result.push_back(SpellResultRange(range, it->result()));
161 if (fp.last < range.last) {
162 // misspelled area after WORD_OK range
163 range.first = fp.last + 1;
164 result.push_back(SpellResultRange(range, it->result()));
169 if (state != SpellChecker::WORD_OK)
170 ranges_.push_back(SpellResultRange(fp, state));
173 void increasePosAfterPos(pos_type pos)
175 correctRangesAfterPos(pos, 1);
179 void decreasePosAfterPos(pos_type pos)
181 correctRangesAfterPos(pos, -1);
185 void refreshLast(pos_type pos)
187 if (pos < refresh_.last)
191 SpellChecker::Result getState(pos_type pos) const
193 SpellChecker::Result result = SpellChecker::WORD_OK;
194 RangesIterator et = ranges_.end();
195 RangesIterator it = ranges_.begin();
196 for (; it != et; ++it) {
197 if(it->contains(pos)) {
204 FontSpan const & getRange(pos_type pos) const
206 /// empty span to indicate mismatch
207 static FontSpan empty_;
208 RangesIterator et = ranges_.end();
209 RangesIterator it = ranges_.begin();
210 for (; it != et; ++it) {
211 if(it->contains(pos)) {
218 bool needsRefresh() const
220 return needs_refresh_;
223 SpellChecker::ChangeNumber currentChangeNumber() const
225 return current_change_number_;
228 void refreshRange(pos_type & first, pos_type & last) const
230 first = refresh_.first;
231 last = refresh_.last;
234 void needsRefresh(pos_type pos)
236 if (needs_refresh_ && pos != -1) {
237 if (pos < refresh_.first)
238 refresh_.first = pos;
239 if (pos > refresh_.last)
241 } else if (pos != -1) {
242 // init request check for neighbour positions too
243 refresh_.first = pos > 0 ? pos - 1 : 0;
244 // no need for special end of paragraph check
245 refresh_.last = pos + 1;
247 needs_refresh_ = pos != -1;
250 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
252 needs_refresh_ = true;
255 current_change_number_ = change_number;
258 typedef vector<SpellResultRange> Ranges;
259 typedef Ranges::const_iterator RangesIterator;
261 /// the area of the paragraph with pending spell check
264 /// spell state cache version number
265 SpellChecker::ChangeNumber current_change_number_;
268 void correctRangesAfterPos(pos_type pos, int offset)
270 RangesIterator et = ranges_.end();
271 Ranges::iterator it = ranges_.begin();
272 for (; it != et; ++it) {
273 it->shift(pos, offset);
279 /////////////////////////////////////////////////////////////////////
281 // Paragraph::Private
283 /////////////////////////////////////////////////////////////////////
285 class Paragraph::Private
287 // Enforce our own "copy" constructor by declaring the standard one and
288 // the assignment operator private without implementing them.
289 Private(Private const &);
290 Private & operator=(Private const &);
293 Private(Paragraph * owner, Layout const & layout);
294 /// "Copy constructor"
295 Private(Private const &, Paragraph * owner);
296 /// Copy constructor from \p beg to \p end
297 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
300 void insertChar(pos_type pos, char_type c, Change const & change);
302 /// Output the surrogate pair formed by \p c and \p next to \p os.
303 /// \return the number of characters written.
304 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
305 OutputParams const &);
307 /// Output a space in appropriate formatting (or a surrogate pair
308 /// if the next character is a combining character).
309 /// \return whether a surrogate pair was output.
310 bool simpleTeXBlanks(OutputParams const &,
313 unsigned int & column,
315 Layout const & style);
317 /// Output consecutive unicode chars, belonging to the same script as
318 /// specified by the latex macro \p ltx, to \p os starting from \p i.
319 /// \return the number of characters written.
320 int writeScriptChars(otexstream & os, docstring const & ltx,
321 Change const &, Encoding const &, pos_type & i);
323 /// This could go to ParagraphParameters if we want to.
324 int startTeXParParams(BufferParams const &, otexstream &,
325 OutputParams const &) const;
327 /// This could go to ParagraphParameters if we want to.
328 bool endTeXParParams(BufferParams const &, otexstream &,
329 OutputParams const &) const;
332 void latexInset(BufferParams const &,
337 Font const & outerfont,
339 Change & running_change,
340 Layout const & style,
342 unsigned int & column);
345 void latexSpecialChar(
347 BufferParams const & bparams,
348 OutputParams const & runparams,
349 Font const & running_font,
350 Change const & running_change,
351 Layout const & style,
354 unsigned int & column);
361 unsigned int & column);
367 unsigned int & column);
370 void validate(LaTeXFeatures & features) const;
372 /// Checks if the paragraph contains only text and no inset or font change.
373 bool onlyText(Buffer const & buf, Font const & outerfont,
374 pos_type initial) const;
376 /// a vector of speller skip positions
377 typedef vector<FontSpan> SkipPositions;
378 typedef SkipPositions::const_iterator SkipPositionsIterator;
380 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
382 Language * getSpellLanguage(pos_type const from) const;
384 Language * locateSpellRange(pos_type & from, pos_type & to,
385 SkipPositions & skips) const;
387 bool hasSpellerChange() const
389 SpellChecker::ChangeNumber speller_change_number = 0;
390 if (theSpellChecker())
391 speller_change_number = theSpellChecker()->changeNumber();
392 return speller_change_number > speller_state_.currentChangeNumber();
395 bool ignoreWord(docstring const & word) const ;
397 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
399 pos_type textsize = owner_->size();
400 // check for sane arguments
401 if (to <= from || from >= textsize)
403 FontSpan fp = FontSpan(from, to - 1);
404 speller_state_.setRange(fp, state);
407 void requestSpellCheck(pos_type pos)
410 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
412 speller_state_.needsRefresh(pos);
415 void readySpellCheck()
417 speller_state_.needsRefresh(-1);
420 bool needsSpellCheck() const
422 return speller_state_.needsRefresh();
425 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
427 speller_state_.refreshRange(first, last);
429 last = owner_->size();
432 pos_type endpos = last;
433 owner_->locateWord(first, endpos, WHOLE_WORD);
436 owner_->locateWord(last, endpos, WHOLE_WORD);
441 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
445 while (it != et && it->first < start) {
446 int skip = it->last - it->first + 1;
454 void markMisspelledWords(pos_type const & first, pos_type const & last,
455 SpellChecker::Result result,
456 docstring const & word,
457 SkipPositions const & skips);
459 InsetCode ownerCode() const
461 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
464 /// Which Paragraph owns us?
468 Inset const * inset_owner_;
477 ParagraphParameters params_;
479 /// for recording and looking up changes
483 InsetList insetlist_;
486 pos_type begin_of_body_;
488 typedef docstring TextContainer;
492 typedef set<docstring> Words;
493 typedef map<string, Words> LangWordsMap;
497 Layout const * layout_;
499 SpellCheckerState speller_state_;
503 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
504 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
510 // Initialization of the counter for the paragraph id's,
512 // FIXME: There should be a more intelligent way to generate and use the
513 // paragraph ids per buffer instead a global static counter for all InsetText
514 // in the running program.
515 // However, this per-session id is used in LFUN_PARAGRAPH_GOTO to
516 // switch to a different buffer, as used in the outliner for instance.
517 static int paragraph_id = -1;
519 Paragraph::Private::Private(Private const & p, Paragraph * owner)
520 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
521 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
522 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
525 id_ = ++paragraph_id;
526 requestSpellCheck(p.text_.size());
530 Paragraph::Private::Private(Private const & p, Paragraph * owner,
531 pos_type beg, pos_type end)
532 : owner_(owner), inset_owner_(p.inset_owner_),
533 params_(p.params_), changes_(p.changes_),
534 insetlist_(p.insetlist_, beg, end),
535 begin_of_body_(p.begin_of_body_), words_(p.words_),
538 id_ = ++paragraph_id;
539 if (beg >= pos_type(p.text_.size()))
541 text_ = p.text_.substr(beg, end - beg);
543 FontList::const_iterator fcit = fontlist_.begin();
544 FontList::const_iterator fend = fontlist_.end();
545 for (; fcit != fend; ++fcit) {
546 if (fcit->pos() < beg)
548 if (fcit->pos() >= end) {
549 // Add last entry in the fontlist_.
550 fontlist_.set(text_.size() - 1, fcit->font());
553 // Add a new entry in the fontlist_.
554 fontlist_.set(fcit->pos() - beg, fcit->font());
556 requestSpellCheck(p.text_.size());
560 void Paragraph::addChangesToToc(DocIterator const & cdit,
561 Buffer const & buf, bool output_active) const
563 d->changes_.addToToc(cdit, buf, output_active);
567 void Paragraph::addChangesToBuffer(Buffer const & buf) const
569 d->changes_.updateBuffer(buf);
573 bool Paragraph::isChangeUpdateRequired() const
575 return d->changes_.isUpdateRequired();
579 bool Paragraph::isDeleted(pos_type start, pos_type end) const
581 LASSERT(start >= 0 && start <= size(), return false);
582 LASSERT(end > start && end <= size() + 1, return false);
584 return d->changes_.isDeleted(start, end);
588 bool Paragraph::isChanged(pos_type start, pos_type end) const
590 LASSERT(start >= 0 && start <= size(), return false);
591 LASSERT(end > start && end <= size() + 1, return false);
593 return d->changes_.isChanged(start, end);
597 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
599 // keep the logic here in sync with the logic of eraseChars()
603 Change const & change = d->changes_.lookup(size());
604 return change.inserted() && change.currentAuthor();
608 void Paragraph::setChange(Change const & change)
610 // beware of the imaginary end-of-par character!
611 d->changes_.set(change, 0, size() + 1);
614 * Propagate the change recursively - but not in case of DELETED!
616 * Imagine that your co-author makes changes in an existing inset. He
617 * sends your document to you and you come to the conclusion that the
618 * inset should go completely. If you erase it, LyX must not delete all
619 * text within the inset. Otherwise, the change tracked insertions of
620 * your co-author get lost and there is no way to restore them later.
622 * Conclusion: An inset's content should remain untouched if you delete it
625 if (!change.deleted()) {
626 for (pos_type pos = 0; pos < size(); ++pos) {
627 if (Inset * inset = getInset(pos))
628 inset->setChange(change);
634 void Paragraph::setChange(pos_type pos, Change const & change)
636 LASSERT(pos >= 0 && pos <= size(), return);
637 d->changes_.set(change, pos);
639 // see comment in setChange(Change const &) above
640 if (!change.deleted() && pos < size())
641 if (Inset * inset = getInset(pos))
642 inset->setChange(change);
646 Change const & Paragraph::lookupChange(pos_type pos) const
648 LBUFERR(pos >= 0 && pos <= size());
649 return d->changes_.lookup(pos);
653 void Paragraph::acceptChanges(pos_type start, pos_type end)
655 LASSERT(start >= 0 && start <= size(), return);
656 LASSERT(end > start && end <= size() + 1, return);
658 for (pos_type pos = start; pos < end; ++pos) {
659 switch (lookupChange(pos).type) {
660 case Change::UNCHANGED:
661 // accept changes in nested inset
662 if (Inset * inset = getInset(pos))
663 inset->acceptChanges();
666 case Change::INSERTED:
667 d->changes_.set(Change(Change::UNCHANGED), pos);
668 // also accept changes in nested inset
669 if (Inset * inset = getInset(pos))
670 inset->acceptChanges();
673 case Change::DELETED:
674 // Suppress access to non-existent
675 // "end-of-paragraph char"
677 eraseChar(pos, false);
688 void Paragraph::rejectChanges(pos_type start, pos_type end)
690 LASSERT(start >= 0 && start <= size(), return);
691 LASSERT(end > start && end <= size() + 1, return);
693 for (pos_type pos = start; pos < end; ++pos) {
694 switch (lookupChange(pos).type) {
695 case Change::UNCHANGED:
696 // reject changes in nested inset
697 if (Inset * inset = getInset(pos))
698 inset->rejectChanges();
701 case Change::INSERTED:
702 // Suppress access to non-existent
703 // "end-of-paragraph char"
705 eraseChar(pos, false);
711 case Change::DELETED:
712 d->changes_.set(Change(Change::UNCHANGED), pos);
714 // Do NOT reject changes within a deleted inset!
715 // There may be insertions of a co-author inside of it!
723 void Paragraph::Private::insertChar(pos_type pos, char_type c,
724 Change const & change)
726 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
729 changes_.insert(change, pos);
731 // This is actually very common when parsing buffers (and
732 // maybe inserting ascii text)
733 if (pos == pos_type(text_.size())) {
734 // when appending characters, no need to update tables
736 // but we want spell checking
737 requestSpellCheck(pos);
741 text_.insert(text_.begin() + pos, c);
743 // Update the font table.
744 fontlist_.increasePosAfterPos(pos);
747 insetlist_.increasePosAfterPos(pos);
749 // Update list of misspelled positions
750 speller_state_.increasePosAfterPos(pos);
754 bool Paragraph::insertInset(pos_type pos, Inset * inset,
755 Font const & font, Change const & change)
757 LASSERT(inset, return false);
758 LASSERT(pos >= 0 && pos <= size(), return false);
760 // Paragraph::insertInset() can be used in cut/copy/paste operation where
761 // d->inset_owner_ is not set yet.
762 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
765 d->insertChar(pos, META_INSET, change);
766 LASSERT(d->text_[pos] == META_INSET, return false);
768 // Add a new entry in the insetlist_.
769 d->insetlist_.insert(inset, pos);
771 // Some insets require run of spell checker
772 requestSpellCheck(pos);
778 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
780 LASSERT(pos >= 0 && pos <= size(), return false);
782 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
785 Change change = d->changes_.lookup(pos);
787 // set the character to DELETED if
788 // a) it was previously unchanged or
789 // b) it was inserted by a co-author
791 if (!change.changed() ||
792 (change.inserted() && !change.currentAuthor())) {
793 setChange(pos, Change(Change::DELETED));
794 // request run of spell checker
795 requestSpellCheck(pos);
799 if (change.deleted())
803 // Don't physically access the imaginary end-of-paragraph character.
804 // eraseChar() can only mark it as DELETED. A physical deletion of
805 // end-of-par must be handled externally.
811 d->changes_.erase(pos);
813 // if it is an inset, delete the inset entry
814 if (d->text_[pos] == META_INSET)
815 d->insetlist_.erase(pos);
817 d->text_.erase(d->text_.begin() + pos);
819 // Update the fontlist_
820 d->fontlist_.erase(pos);
822 // Update the insetlist_
823 d->insetlist_.decreasePosAfterPos(pos);
825 // Update list of misspelled positions
826 d->speller_state_.decreasePosAfterPos(pos);
827 d->speller_state_.refreshLast(size());
833 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
835 LASSERT(start >= 0 && start <= size(), return 0);
836 LASSERT(end >= start && end <= size() + 1, return 0);
839 for (pos_type count = end - start; count; --count) {
840 if (!eraseChar(i, trackChanges))
847 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
848 char_type next, OutputParams const & runparams)
850 // Writing next here may circumvent a possible font change between
851 // c and next. Since next is only output if it forms a surrogate pair
852 // with c we can ignore this:
853 // A font change inside a surrogate pair does not make sense and is
854 // hopefully impossible to input.
855 // FIXME: change tracking
856 // Is this correct WRT change tracking?
857 Encoding const & encoding = *(runparams.encoding);
858 docstring latex1 = encoding.latexChar(next).first;
859 if (runparams.inIPA) {
860 string const tipashortcut = Encodings::TIPAShortcut(next);
861 if (!tipashortcut.empty()) {
862 latex1 = from_ascii(tipashortcut);
865 docstring const latex2 = encoding.latexChar(c).first;
866 if (docstring(1, next) == latex1) {
867 // the encoding supports the combination
868 os << latex2 << latex1;
869 return latex1.length() + latex2.length();
870 } else if (runparams.local_font &&
871 runparams.local_font->language()->lang() == "polutonikogreek") {
872 // polutonikogreek only works without the brackets
873 os << latex1 << latex2;
874 return latex1.length() + latex2.length();
876 os << latex1 << '{' << latex2 << '}';
877 return latex1.length() + latex2.length() + 2;
881 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
884 unsigned int & column,
886 Layout const & style)
888 if (style.pass_thru || runparams.pass_thru)
891 if (i + 1 < int(text_.size())) {
892 char_type next = text_[i + 1];
893 if (Encodings::isCombiningChar(next)) {
894 // This space has an accent, so we must always output it.
895 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
900 if (runparams.linelen > 0
901 && column > runparams.linelen
903 && text_[i - 1] != ' '
904 && (i + 1 < int(text_.size()))
905 // same in FreeSpacing mode
906 && !owner_->isFreeSpacing()
907 // In typewriter mode, we want to avoid
908 // ! . ? : at the end of a line
909 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
910 && (text_[i - 1] == '.'
911 || text_[i - 1] == '?'
912 || text_[i - 1] == ':'
913 || text_[i - 1] == '!'))) {
915 os.texrow().start(owner_->id(), i + 1);
917 } else if (style.free_spacing) {
926 int Paragraph::Private::writeScriptChars(otexstream & os,
927 docstring const & ltx,
928 Change const & runningChange,
929 Encoding const & encoding,
932 // FIXME: modifying i here is not very nice...
934 // We only arrive here when character text_[i] could not be translated
935 // into the current latex encoding (or its latex translation has been forced,)
936 // and it belongs to a known script.
937 // TODO: We need \textcyr and \textgreek wrappers also for characters
938 // that can be encoded in the "LaTeX encoding" but not in the
939 // current *font encoding*.
940 // (See #9681 for details and test)
941 // Parameter ltx contains the latex translation of text_[i] as specified
942 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
943 // The latex macro name "textXXX" specifies the script to which text_[i]
944 // belongs and we use it in order to check whether characters from the
945 // same script immediately follow, such that we can collect them in a
946 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
947 // for the first char but only "<spec>" for all subsequent chars.
948 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
949 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
950 string script = to_ascii(ltx.substr(1, brace1 - 1));
953 bool closing_brace = true;
954 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
955 // Correct encoding is being used, so we can avoid \textgreek.
956 // TODO: wrong test: we need to check the *font encoding*
957 // (i.e. the active language and its FontEncoding tag)
958 // instead of the LaTeX *input encoding*!
959 // See #9637 for details and test-cases.
962 closing_brace = false;
964 os << ltx.substr(pos, length);
965 int size = text_.size();
966 while (i + 1 < size) {
967 char_type const next = text_[i + 1];
968 // Stop here if next character belongs to another script
969 // or there is a change in change tracking status.
970 if (!Encodings::isKnownScriptChar(next, script) ||
971 runningChange != owner_->lookupChange(i + 1))
975 FontList::const_iterator cit = fontlist_.begin();
976 FontList::const_iterator end = fontlist_.end();
977 for (; cit != end; ++cit) {
978 if (cit->pos() >= i && !found) {
979 prev_font = cit->font();
982 if (cit->pos() >= i + 1)
985 // Stop here if there is a font attribute or encoding change.
986 if (found && cit != end && prev_font != cit->font())
988 docstring const latex = encoding.latexChar(next).first;
989 docstring::size_type const b1 =
990 latex.find_first_of(from_ascii("{"));
991 docstring::size_type const b2 =
992 latex.find_last_of(from_ascii("}"));
993 int const len = b2 - b1 - 1;
994 os << latex.substr(b1 + 1, len);
1006 void Paragraph::Private::latexInset(BufferParams const & bparams,
1008 OutputParams & runparams,
1009 Font & running_font,
1011 Font const & outerfont,
1013 Change & running_change,
1014 Layout const & style,
1016 unsigned int & column)
1018 Inset * inset = owner_->getInset(i);
1021 if (style.pass_thru) {
1022 odocstringstream ods;
1023 inset->plaintext(ods, runparams);
1028 // FIXME: move this to InsetNewline::latex
1029 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1030 // newlines are handled differently here than
1031 // the default in simpleTeXSpecialChars().
1032 if (!style.newline_allowed) {
1036 column += running_font.latexWriteEndChanges(
1037 os, bparams, runparams,
1038 basefont, basefont);
1042 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1045 basefont = owner_->getLayoutFont(bparams, outerfont);
1046 running_font = basefont;
1048 if (runparams.moving_arg)
1052 os.texrow().start(owner_->id(), i + 1);
1056 if (owner_->isDeleted(i)) {
1057 if( ++runparams.inDeletedInset == 1)
1058 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1061 if (inset->canTrackChanges()) {
1062 column += Changes::latexMarkChange(os, bparams, running_change,
1063 Change(Change::UNCHANGED), runparams);
1064 running_change = Change(Change::UNCHANGED);
1068 odocstream::pos_type const len = os.os().tellp();
1070 if (inset->forceLTR()
1071 && !runparams.use_polyglossia
1072 && running_font.isRightToLeft()
1073 // ERT is an exception, it should be output with no
1074 // decorations at all
1075 && inset->lyxCode() != ERT_CODE) {
1076 if (running_font.language()->lang() == "farsi")
1083 // FIXME: Bug: we can have an empty font change here!
1084 // if there has just been a font change, we are going to close it
1085 // right now, which means stupid latex code like \textsf{}. AFAIK,
1086 // this does not harm dvi output. A minor bug, thus (JMarc)
1088 // Some insets cannot be inside a font change command.
1089 // However, even such insets *can* be placed in \L or \R
1090 // or their equivalents (for RTL language switches), so we don't
1091 // close the language in those cases.
1092 // ArabTeX, though, cannot handle this special behavior, it seems.
1093 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1094 || running_font.language()->lang() == "arabic_arabtex";
1095 if (open_font && !inset->inheritFont()) {
1096 bool closeLanguage = arabtex
1097 || basefont.isRightToLeft() == running_font.isRightToLeft();
1098 unsigned int count = running_font.latexWriteEndChanges(os,
1099 bparams, runparams, basefont, basefont, closeLanguage);
1101 // if any font properties were closed, update the running_font,
1102 // making sure, however, to leave the language as it was
1104 // FIXME: probably a better way to keep track of the old
1105 // language, than copying the entire font?
1106 Font const copy_font(running_font);
1107 basefont = owner_->getLayoutFont(bparams, outerfont);
1108 running_font = basefont;
1110 running_font.setLanguage(copy_font.language());
1111 // leave font open if language is still open
1112 open_font = (running_font.language() == basefont.language());
1114 runparams.local_font = &basefont;
1118 int prev_rows = os.texrow().rows();
1121 runparams.lastid = id_;
1122 runparams.lastpos = i;
1123 inset->latex(os, runparams);
1124 } catch (EncodingException & e) {
1125 // add location information and throw again.
1132 if (running_font.language()->lang() == "farsi")
1138 if (os.texrow().rows() > prev_rows) {
1139 os.texrow().start(owner_->id(), i + 1);
1142 column += (unsigned int)(os.os().tellp() - len);
1145 if (owner_->isDeleted(i))
1146 --runparams.inDeletedInset;
1150 void Paragraph::Private::latexSpecialChar(otexstream & os,
1151 BufferParams const & bparams,
1152 OutputParams const & runparams,
1153 Font const & running_font,
1154 Change const & running_change,
1155 Layout const & style,
1158 unsigned int & column)
1160 // With polyglossia, brackets and stuff need not be reversed
1161 // in RTL scripts (see bug #8251)
1162 char_type const c = (runparams.use_polyglossia) ?
1163 owner_->getUChar(bparams, i) : text_[i];
1165 if (style.pass_thru || runparams.pass_thru
1166 || contains(style.pass_thru_chars, c)
1167 || contains(runparams.pass_thru_chars, c)) {
1169 Encoding const * const enc = runparams.encoding;
1170 if (enc && !enc->encodable(c))
1171 throw EncodingException(c);
1177 // TIPA uses its own T3 encoding
1178 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1180 // If T1 font encoding is used, use the special
1181 // characters it provides.
1182 // NOTE: Some languages reset the font encoding internally to a
1183 // non-standard font encoding. If we are using such a language,
1184 // we do not output special T1 chars.
1185 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1186 && bparams.font_encoding() == "T1" && latexSpecialT1(c, os, i, column))
1189 // Otherwise, we use what LaTeX provides us.
1192 os << "\\textbackslash{}";
1196 os << "\\textless{}";
1200 os << "\\textgreater{}";
1204 os << "\\textbar{}";
1209 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1210 (end_pos == -1 || i + 1 < end_pos) &&
1211 text_[i+1] == '-') {
1212 // Prevent "--" becoming an endash and "---" becoming
1214 // Within \ttfamily, "--" is merged to "-" (no endash)
1215 // so we avoid this rather irritating ligature as well
1221 os << "\\char`\\\"{}";
1226 case '%': case '#': case '{':
1234 os << "\\textasciitilde{}";
1239 os << "\\textasciicircum{}";
1246 // avoid being mistaken for optional arguments
1254 // Blanks are printed before font switching.
1255 // Sure? I am not! (try nice-latex)
1256 // I am sure it's correct. LyX might be smarter
1257 // in the future, but for now, nothing wrong is
1265 Encoding const & encoding = *(runparams.encoding);
1266 char_type next = '\0';
1267 if (i + 1 < int(text_.size())) {
1268 next = text_[i + 1];
1269 if (Encodings::isCombiningChar(next)) {
1270 column += latexSurrogatePair(os, c, next, runparams) - 1;
1276 pair<docstring, bool> latex = encoding.latexChar(c);
1277 docstring nextlatex;
1278 bool nexttipas = false;
1279 string nexttipashortcut;
1280 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1281 nextlatex = encoding.latexChar(next).first;
1282 if (runparams.inIPA) {
1283 nexttipashortcut = Encodings::TIPAShortcut(next);
1284 nexttipas = !nexttipashortcut.empty();
1288 if (runparams.inIPA) {
1289 string const tipashortcut = Encodings::TIPAShortcut(c);
1290 if (!tipashortcut.empty()) {
1291 latex.first = from_ascii(tipashortcut);
1292 latex.second = false;
1296 if (Encodings::isKnownScriptChar(c, script)
1297 && prefixIs(latex.first, from_ascii("\\" + script)))
1298 column += writeScriptChars(os, latex.first,
1299 running_change, encoding, i) - 1;
1300 else if (latex.second
1301 && ((!prefixIs(nextlatex, '\\')
1302 && !prefixIs(nextlatex, '{')
1303 && !prefixIs(nextlatex, '}'))
1305 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1307 // Prevent eating of a following
1308 // space or command corruption by
1309 // following characters
1310 if (next == ' ' || next == '\0') {
1311 column += latex.first.length() + 1;
1312 os << latex.first << "{}";
1314 column += latex.first.length();
1315 os << latex.first << " ";
1318 column += latex.first.length() - 1;
1326 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1327 pos_type i, unsigned int & column)
1333 // In T1 encoding, these characters exist
1334 // but we should avoid ligatures
1335 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1337 os << "\\textcompwordmark{}";
1344 // soul.sty breaks with \char`\"
1345 os << "\\textquotedbl{}";
1354 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1355 pos_type /*i*/, unsigned int & column)
1365 os << "\\textvertline{}";
1374 void Paragraph::Private::validate(LaTeXFeatures & features) const
1376 if (layout_->inpreamble && inset_owner_) {
1377 bool const is_command = layout_->latextype == LATEX_COMMAND;
1378 Buffer const & buf = inset_owner_->buffer();
1379 BufferParams const & bp = features.runparams().is_child
1380 ? buf.masterParams() : buf.params();
1383 // Using a string stream here circumvents the encoding
1384 // switching machinery of odocstream. Therefore the
1385 // output is wrong if this paragraph contains content
1386 // that needs to switch encoding.
1387 odocstringstream ods;
1388 otexstream os(ods, texrow);
1390 os << '\\' << from_ascii(layout_->latexname());
1391 // we have to provide all the optional arguments here, even though
1392 // the last one is the only one we care about.
1393 // Separate handling of optional argument inset.
1394 if (!layout_->latexargs().empty()) {
1395 OutputParams rp = features.runparams();
1396 rp.local_font = &owner_->getFirstFontSettings(bp);
1397 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1399 os << from_ascii(layout_->latexparam());
1401 docstring::size_type const length = ods.str().length();
1402 // this will output "{" at the beginning, but not at the end
1403 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1404 if (ods.str().length() > length) {
1407 if (!layout_->postcommandargs().empty()) {
1408 OutputParams rp = features.runparams();
1409 rp.local_font = &owner_->getFirstFontSettings(bp);
1410 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1413 string const snippet = to_utf8(ods.str());
1414 features.addPreambleSnippet(snippet, true);
1418 if (features.runparams().flavor == OutputParams::HTML
1419 && layout_->htmltitle()) {
1420 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1423 // check the params.
1424 if (!params_.spacing().isDefault())
1425 features.require("setspace");
1428 features.useLayout(layout_->name());
1431 fontlist_.validate(features);
1433 // then the indentation
1434 if (!params_.leftIndent().zero())
1435 features.require("ParagraphLeftIndent");
1438 InsetList::const_iterator icit = insetlist_.begin();
1439 InsetList::const_iterator iend = insetlist_.end();
1440 for (; icit != iend; ++icit) {
1442 features.inDeletedInset(owner_->isDeleted(icit->pos));
1443 icit->inset->validate(features);
1444 features.inDeletedInset(false);
1445 if (layout_->needprotect &&
1446 icit->inset->lyxCode() == FOOT_CODE)
1447 features.require("NeedLyXFootnoteCode");
1451 // then the contents
1452 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1453 BufferEncodings::validate(text_[i], features);
1457 /////////////////////////////////////////////////////////////////////
1461 /////////////////////////////////////////////////////////////////////
1464 Layout const emptyParagraphLayout;
1467 Paragraph::Paragraph()
1468 : d(new Paragraph::Private(this, emptyParagraphLayout))
1475 Paragraph::Paragraph(Paragraph const & par)
1476 : itemdepth(par.itemdepth),
1477 d(new Paragraph::Private(*par.d, this))
1483 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1484 : itemdepth(par.itemdepth),
1485 d(new Paragraph::Private(*par.d, this, beg, end))
1491 Paragraph & Paragraph::operator=(Paragraph const & par)
1493 // needed as we will destroy the private part before copying it
1495 itemdepth = par.itemdepth;
1499 d = new Private(*par.d, this);
1506 Paragraph::~Paragraph()
1515 // this shall be called just before every "os << ..." action.
1516 void flushString(ostream & os, docstring & s)
1525 void Paragraph::write(ostream & os, BufferParams const & bparams,
1526 depth_type & dth) const
1528 // The beginning or end of a deeper (i.e. nested) area?
1529 if (dth != d->params_.depth()) {
1530 if (d->params_.depth() > dth) {
1531 while (d->params_.depth() > dth) {
1532 os << "\n\\begin_deeper";
1536 while (d->params_.depth() < dth) {
1537 os << "\n\\end_deeper";
1543 // First write the layout
1544 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1546 d->params_.write(os);
1548 Font font1(inherit_font, bparams.language);
1550 Change running_change = Change(Change::UNCHANGED);
1552 // this string is used as a buffer to avoid repetitive calls
1553 // to to_utf8(), which turn out to be expensive (JMarc)
1554 docstring write_buffer;
1557 for (pos_type i = 0; i <= size(); ++i) {
1559 Change const & change = lookupChange(i);
1560 if (change != running_change)
1561 flushString(os, write_buffer);
1562 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1563 running_change = change;
1568 // Write font changes
1569 Font font2 = getFontSettings(bparams, i);
1570 if (font2 != font1) {
1571 flushString(os, write_buffer);
1572 font2.lyxWriteChanges(font1, os);
1577 char_type const c = d->text_[i];
1580 if (Inset const * inset = getInset(i)) {
1581 flushString(os, write_buffer);
1582 if (inset->directWrite()) {
1583 // international char, let it write
1584 // code directly so it's shorter in
1590 os << "\\begin_inset ";
1592 os << "\n\\end_inset\n\n";
1595 // FIXME This can be removed again once the mystery
1596 // crash has been resolved.
1601 flushString(os, write_buffer);
1602 os << "\n\\backslash\n";
1606 flushString(os, write_buffer);
1607 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1614 if ((column > 70 && c == ' ')
1616 flushString(os, write_buffer);
1620 // this check is to amend a bug. LyX sometimes
1621 // inserts '\0' this could cause problems.
1623 write_buffer.push_back(c);
1625 LYXERR0("NUL char in structure.");
1631 flushString(os, write_buffer);
1632 os << "\n\\end_layout\n";
1633 // FIXME This can be removed again once the mystery
1634 // crash has been resolved.
1639 void Paragraph::validate(LaTeXFeatures & features) const
1641 d->validate(features);
1645 void Paragraph::insert(pos_type start, docstring const & str,
1646 Font const & font, Change const & change)
1648 for (size_t i = 0, n = str.size(); i != n ; ++i)
1649 insertChar(start + i, str[i], font, change);
1653 void Paragraph::appendChar(char_type c, Font const & font,
1654 Change const & change)
1657 d->changes_.insert(change, d->text_.size());
1658 // when appending characters, no need to update tables
1659 d->text_.push_back(c);
1660 setFont(d->text_.size() - 1, font);
1661 d->requestSpellCheck(d->text_.size() - 1);
1665 void Paragraph::appendString(docstring const & s, Font const & font,
1666 Change const & change)
1668 pos_type end = s.size();
1669 size_t oldsize = d->text_.size();
1670 size_t newsize = oldsize + end;
1671 size_t capacity = d->text_.capacity();
1672 if (newsize >= capacity)
1673 d->text_.reserve(max(capacity + 100, newsize));
1675 // when appending characters, no need to update tables
1678 // FIXME: Optimize this!
1679 for (size_t i = oldsize; i != newsize; ++i) {
1681 d->changes_.insert(change, i);
1682 d->requestSpellCheck(i);
1684 d->fontlist_.set(oldsize, font);
1685 d->fontlist_.set(newsize - 1, font);
1689 void Paragraph::insertChar(pos_type pos, char_type c,
1692 d->insertChar(pos, c, Change(trackChanges ?
1693 Change::INSERTED : Change::UNCHANGED));
1697 void Paragraph::insertChar(pos_type pos, char_type c,
1698 Font const & font, bool trackChanges)
1700 d->insertChar(pos, c, Change(trackChanges ?
1701 Change::INSERTED : Change::UNCHANGED));
1706 void Paragraph::insertChar(pos_type pos, char_type c,
1707 Font const & font, Change const & change)
1709 d->insertChar(pos, c, change);
1714 void Paragraph::resetFonts(Font const & font)
1716 d->fontlist_.clear();
1717 d->fontlist_.set(0, font);
1718 d->fontlist_.set(d->text_.size() - 1, font);
1721 // Gets uninstantiated font setting at position.
1722 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1726 LYXERR0("pos: " << pos << " size: " << size());
1730 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1731 if (cit != d->fontlist_.end())
1734 if (pos == size() && !empty())
1735 return getFontSettings(bparams, pos - 1);
1737 // Optimisation: avoid a full font instantiation if there is no
1738 // language change from previous call.
1739 static Font previous_font;
1740 static Language const * previous_lang = 0;
1741 Language const * lang = getParLanguage(bparams);
1742 if (lang != previous_lang) {
1743 previous_lang = lang;
1744 previous_font = Font(inherit_font, lang);
1746 return previous_font;
1750 FontSpan Paragraph::fontSpan(pos_type pos) const
1752 LBUFERR(pos <= size());
1755 return FontSpan(pos, pos);
1758 FontList::const_iterator cit = d->fontlist_.begin();
1759 FontList::const_iterator end = d->fontlist_.end();
1760 for (; cit != end; ++cit) {
1761 if (cit->pos() >= pos) {
1762 if (pos >= beginOfBody())
1763 return FontSpan(max(start, beginOfBody()),
1766 return FontSpan(start,
1767 min(beginOfBody() - 1,
1770 start = cit->pos() + 1;
1773 // This should not happen, but if so, we take no chances.
1774 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1775 LASSERT(false, return FontSpan(pos, pos));
1779 // Gets uninstantiated font setting at position 0
1780 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1782 if (!empty() && !d->fontlist_.empty())
1783 return d->fontlist_.begin()->font();
1785 // Optimisation: avoid a full font instantiation if there is no
1786 // language change from previous call.
1787 static Font previous_font;
1788 static Language const * previous_lang = 0;
1789 if (bparams.language != previous_lang) {
1790 previous_lang = bparams.language;
1791 previous_font = Font(inherit_font, bparams.language);
1794 return previous_font;
1798 // Gets the fully instantiated font at a given position in a paragraph
1799 // This is basically the same function as Text::GetFont() in text2.cpp.
1800 // The difference is that this one is used for generating the LaTeX file,
1801 // and thus cosmetic "improvements" are disallowed: This has to deliver
1802 // the true picture of the buffer. (Asger)
1803 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1804 Font const & outerfont) const
1808 Font font = getFontSettings(bparams, pos);
1810 pos_type const body_pos = beginOfBody();
1811 FontInfo & fi = font.fontInfo();
1813 fi.realize(d->layout_->labelfont);
1815 fi.realize(d->layout_->font);
1817 fi.realize(outerfont.fontInfo());
1818 fi.realize(bparams.getFont().fontInfo());
1824 Font const Paragraph::getLabelFont
1825 (BufferParams const & bparams, Font const & outerfont) const
1827 FontInfo tmpfont = d->layout_->labelfont;
1828 tmpfont.realize(outerfont.fontInfo());
1829 tmpfont.realize(bparams.getFont().fontInfo());
1830 return Font(tmpfont, getParLanguage(bparams));
1834 Font const Paragraph::getLayoutFont
1835 (BufferParams const & bparams, Font const & outerfont) const
1837 FontInfo tmpfont = d->layout_->font;
1838 tmpfont.realize(outerfont.fontInfo());
1839 tmpfont.realize(bparams.getFont().fontInfo());
1840 return Font(tmpfont, getParLanguage(bparams));
1844 /// Returns the height of the highest font in range
1845 FontSize Paragraph::highestFontInRange
1846 (pos_type startpos, pos_type endpos, FontSize def_size) const
1848 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1852 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1854 char_type c = d->text_[pos];
1855 if (!getFontSettings(bparams, pos).isRightToLeft())
1858 // FIXME: The arabic special casing is due to the difference of arabic
1859 // round brackets input introduced in r18599. Check if this should be
1860 // unified with Hebrew or at least if all bracket types should be
1861 // handled the same (file format change in either case).
1862 string const & lang = getFontSettings(bparams, pos).language()->lang();
1863 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1868 uc = arabic ? c : ')';
1871 uc = arabic ? c : '(';
1897 void Paragraph::setFont(pos_type pos, Font const & font)
1899 LASSERT(pos <= size(), return);
1901 // First, reduce font against layout/label font
1902 // Update: The setCharFont() routine in text2.cpp already
1903 // reduces font, so we don't need to do that here. (Asger)
1905 d->fontlist_.set(pos, font);
1909 void Paragraph::makeSameLayout(Paragraph const & par)
1911 d->layout_ = par.d->layout_;
1912 d->params_ = par.d->params_;
1916 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1918 if (isFreeSpacing())
1924 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1925 if (eraseChar(pos, trackChanges))
1931 return count > 0 || pos > 0;
1935 bool Paragraph::hasSameLayout(Paragraph const & par) const
1937 return par.d->layout_ == d->layout_
1938 && d->params_.sameLayout(par.d->params_);
1942 depth_type Paragraph::getDepth() const
1944 return d->params_.depth();
1948 depth_type Paragraph::getMaxDepthAfter() const
1950 if (d->layout_->isEnvironment())
1951 return d->params_.depth() + 1;
1953 return d->params_.depth();
1957 char Paragraph::getAlign() const
1959 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1960 return d->layout_->align;
1962 return d->params_.align();
1966 docstring const & Paragraph::labelString() const
1968 return d->params_.labelString();
1972 // the next two functions are for the manual labels
1973 docstring const Paragraph::getLabelWidthString() const
1975 if (d->layout_->margintype == MARGIN_MANUAL
1976 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1977 return d->params_.labelWidthString();
1979 return _("Senseless with this layout!");
1983 void Paragraph::setLabelWidthString(docstring const & s)
1985 d->params_.labelWidthString(s);
1989 docstring Paragraph::expandLabel(Layout const & layout,
1990 BufferParams const & bparams) const
1992 return expandParagraphLabel(layout, bparams, true);
1996 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1997 BufferParams const & bparams) const
1999 return expandParagraphLabel(layout, bparams, false);
2003 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2004 BufferParams const & bparams, bool process_appendix) const
2006 DocumentClass const & tclass = bparams.documentClass();
2007 string const & lang = getParLanguage(bparams)->code();
2008 bool const in_appendix = process_appendix && d->params_.appendix();
2009 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2011 if (fmt.empty() && !layout.counter.empty())
2012 return tclass.counters().theCounter(layout.counter, lang);
2014 // handle 'inherited level parts' in 'fmt',
2015 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2016 size_t const i = fmt.find('@', 0);
2017 if (i != docstring::npos) {
2018 size_t const j = fmt.find('@', i + 1);
2019 if (j != docstring::npos) {
2020 docstring parent(fmt, i + 1, j - i - 1);
2021 docstring label = from_ascii("??");
2022 if (tclass.hasLayout(parent))
2023 label = expandParagraphLabel(tclass[parent], bparams,
2025 fmt = docstring(fmt, 0, i) + label
2026 + docstring(fmt, j + 1, docstring::npos);
2030 return tclass.counters().counterLabel(fmt, lang);
2034 void Paragraph::applyLayout(Layout const & new_layout)
2036 d->layout_ = &new_layout;
2037 LyXAlignment const oldAlign = d->params_.align();
2039 if (!(oldAlign & d->layout_->alignpossible)) {
2040 frontend::Alert::warning(_("Alignment not permitted"),
2041 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2042 d->params_.align(LYX_ALIGN_LAYOUT);
2047 pos_type Paragraph::beginOfBody() const
2049 return d->begin_of_body_;
2053 void Paragraph::setBeginOfBody()
2055 if (d->layout_->labeltype != LABEL_MANUAL) {
2056 d->begin_of_body_ = 0;
2060 // Unroll the first two cycles of the loop
2061 // and remember the previous character to
2062 // remove unnecessary getChar() calls
2064 pos_type end = size();
2065 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2068 char_type previous_char = d->text_[i];
2069 if (!(isNewline(i) || isEnvSeparator(i))) {
2071 while (i < end && previous_char != ' ') {
2072 char_type temp = d->text_[i];
2073 if (isNewline(i) || isEnvSeparator(i))
2076 previous_char = temp;
2082 d->begin_of_body_ = i;
2086 bool Paragraph::allowParagraphCustomization() const
2088 return inInset().allowParagraphCustomization();
2092 bool Paragraph::usePlainLayout() const
2094 return inInset().usePlainLayout();
2098 bool Paragraph::isPassThru() const
2100 return inInset().isPassThru() || d->layout_->pass_thru;
2105 // paragraphs inside floats need different alignment tags to avoid
2108 bool noTrivlistCentering(InsetCode code)
2110 return code == FLOAT_CODE
2111 || code == WRAP_CODE
2112 || code == CELL_CODE;
2116 string correction(string const & orig)
2118 if (orig == "flushleft")
2119 return "raggedright";
2120 if (orig == "flushright")
2121 return "raggedleft";
2122 if (orig == "center")
2128 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2129 InsetCode code, bool const lastpar, int & col)
2131 string macro = suffix + "{";
2132 if (noTrivlistCentering(code)) {
2134 // the last paragraph in non-trivlist-aligned
2135 // context is special (to avoid unwanted whitespace)
2136 if (suffix == "\\begin") {
2137 macro = "\\" + correction(env) + "{}";
2138 os << from_ascii(macro);
2139 col += macro.size();
2144 macro += correction(env);
2148 if (suffix == "\\par\\end") {
2152 os << from_ascii(macro);
2153 col += macro.size();
2154 if (suffix == "\\begin") {
2164 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2165 otexstream & os, OutputParams const & runparams) const
2170 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2171 (layout_->toggle_indent != ITOGGLE_NEVER) :
2172 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2174 if (canindent && params_.noindent() && !layout_->pass_thru) {
2175 os << "\\noindent ";
2179 LyXAlignment const curAlign = params_.align();
2181 if (curAlign == layout_->align)
2185 case LYX_ALIGN_NONE:
2186 case LYX_ALIGN_BLOCK:
2187 case LYX_ALIGN_LAYOUT:
2188 case LYX_ALIGN_SPECIAL:
2189 case LYX_ALIGN_DECIMAL:
2191 case LYX_ALIGN_LEFT:
2192 case LYX_ALIGN_RIGHT:
2193 case LYX_ALIGN_CENTER:
2194 if (runparams.moving_arg) {
2201 string const begin_tag = "\\begin";
2202 InsetCode code = ownerCode();
2203 bool const lastpar = runparams.isLastPar;
2206 case LYX_ALIGN_NONE:
2207 case LYX_ALIGN_BLOCK:
2208 case LYX_ALIGN_LAYOUT:
2209 case LYX_ALIGN_SPECIAL:
2210 case LYX_ALIGN_DECIMAL:
2212 case LYX_ALIGN_LEFT: {
2213 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2214 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2216 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2218 } case LYX_ALIGN_RIGHT: {
2219 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2220 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2222 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2224 } case LYX_ALIGN_CENTER: {
2225 corrected_env(os, begin_tag, "center", code, lastpar, column);
2234 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2235 otexstream & os, OutputParams const & runparams) const
2237 LyXAlignment const curAlign = params_.align();
2239 if (curAlign == layout_->align)
2243 case LYX_ALIGN_NONE:
2244 case LYX_ALIGN_BLOCK:
2245 case LYX_ALIGN_LAYOUT:
2246 case LYX_ALIGN_SPECIAL:
2247 case LYX_ALIGN_DECIMAL:
2249 case LYX_ALIGN_LEFT:
2250 case LYX_ALIGN_RIGHT:
2251 case LYX_ALIGN_CENTER:
2252 if (runparams.moving_arg)
2257 bool output = false;
2259 string const end_tag = "\\par\\end";
2260 InsetCode code = ownerCode();
2261 bool const lastpar = runparams.isLastPar;
2264 case LYX_ALIGN_NONE:
2265 case LYX_ALIGN_BLOCK:
2266 case LYX_ALIGN_LAYOUT:
2267 case LYX_ALIGN_SPECIAL:
2268 case LYX_ALIGN_DECIMAL:
2270 case LYX_ALIGN_LEFT: {
2271 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2272 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2274 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2276 } case LYX_ALIGN_RIGHT: {
2277 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2278 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2280 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2282 } case LYX_ALIGN_CENTER: {
2283 corrected_env(os, end_tag, "center", code, lastpar, col);
2288 return output || lastpar;
2292 // This one spits out the text of the paragraph
2293 void Paragraph::latex(BufferParams const & bparams,
2294 Font const & outerfont,
2296 OutputParams const & runparams,
2297 int start_pos, int end_pos, bool force) const
2299 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2301 // FIXME This check should not be needed. Perhaps issue an
2302 // error if it triggers.
2303 Layout const & style = inInset().forcePlainLayout() ?
2304 bparams.documentClass().plainLayout() : *d->layout_;
2306 if (!force && style.inpreamble)
2309 bool const allowcust = allowParagraphCustomization();
2311 // Current base font for all inherited font changes, without any
2312 // change caused by an individual character, except for the language:
2313 // It is set to the language of the first character.
2314 // As long as we are in the label, this font is the base font of the
2315 // label. Before the first body character it is set to the base font
2319 // Maybe we have to create a optional argument.
2320 pos_type body_pos = beginOfBody();
2321 unsigned int column = 0;
2324 // the optional argument is kept in curly brackets in
2325 // case it contains a ']'
2326 // This is not strictly needed, but if this is changed it
2327 // would be a file format change, and tex2lyx would need
2328 // to be adjusted, since it unconditionally removes the
2329 // braces when it parses \item.
2332 basefont = getLabelFont(bparams, outerfont);
2334 basefont = getLayoutFont(bparams, outerfont);
2337 // Which font is currently active?
2338 Font running_font(basefont);
2339 // Do we have an open font change?
2340 bool open_font = false;
2342 Change runningChange = Change(Change::UNCHANGED);
2344 Encoding const * const prev_encoding = runparams.encoding;
2346 os.texrow().start(id(), 0);
2348 // if the paragraph is empty, the loop will not be entered at all
2350 if (style.isCommand()) {
2354 if (!style.leftdelim().empty()) {
2355 os << style.leftdelim();
2356 column += style.leftdelim().size();
2359 column += d->startTeXParParams(bparams, os, runparams);
2362 for (pos_type i = 0; i < size(); ++i) {
2363 // First char in paragraph or after label?
2364 if (i == body_pos) {
2367 column += running_font.latexWriteEndChanges(
2368 os, bparams, runparams,
2369 basefont, basefont);
2372 basefont = getLayoutFont(bparams, outerfont);
2373 running_font = basefont;
2375 column += Changes::latexMarkChange(os, bparams,
2376 runningChange, Change(Change::UNCHANGED),
2378 runningChange = Change(Change::UNCHANGED);
2383 if (style.isCommand()) {
2388 if (!style.leftdelim().empty()) {
2389 os << style.leftdelim();
2390 column += style.leftdelim().size();
2394 column += d->startTeXParParams(bparams, os,
2398 runparams.wasDisplayMath = runparams.inDisplayMath;
2399 runparams.inDisplayMath = false;
2400 bool deleted_display_math = false;
2402 // Check whether a display math inset follows
2403 if (d->text_[i] == META_INSET
2404 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2405 InsetMath const * im = getInset(i)->asInsetMath();
2406 if (im && im->asHullInset()
2407 && im->asHullInset()->outerDisplay()) {
2408 runparams.inDisplayMath = true;
2409 // runparams.inDeletedInset will be set by
2410 // latexInset later, but we need this info
2411 // before it is called. On the other hand, we
2412 // cannot set it here because it is a counter.
2413 deleted_display_math = isDeleted(i);
2417 Change const & change = runparams.inDeletedInset
2418 ? runparams.changeOfDeletedInset : lookupChange(i);
2420 if (bparams.output_changes && runningChange != change) {
2422 column += running_font.latexWriteEndChanges(
2423 os, bparams, runparams, basefont, basefont);
2426 basefont = getLayoutFont(bparams, outerfont);
2427 running_font = basefont;
2428 column += Changes::latexMarkChange(os, bparams, runningChange,
2430 runningChange = change;
2433 // do not output text which is marked deleted
2434 // if change tracking output is disabled
2435 if (!bparams.output_changes && change.deleted()) {
2441 // Fully instantiated font
2442 Font const font = getFont(bparams, i, outerfont);
2444 Font const last_font = running_font;
2446 // Do we need to close the previous font?
2448 (font != running_font ||
2449 font.language() != running_font.language()))
2451 column += running_font.latexWriteEndChanges(
2452 os, bparams, runparams, basefont,
2453 (i == body_pos-1) ? basefont : font);
2454 running_font = basefont;
2458 string const running_lang = runparams.use_polyglossia ?
2459 running_font.language()->polyglossia() : running_font.language()->babel();
2460 // close babel's font environment before opening CJK.
2461 string const lang_end_command = runparams.use_polyglossia ?
2462 "\\end{$$lang}" : lyxrc.language_command_end;
2463 if (!running_lang.empty() &&
2464 font.language()->encoding()->package() == Encoding::CJK) {
2465 string end_tag = subst(lang_end_command,
2468 os << from_ascii(end_tag);
2469 column += end_tag.length();
2470 if (runparams.use_polyglossia)
2471 popPolyglossiaLang();
2474 // Switch file encoding if necessary (and allowed)
2475 if (!runparams.pass_thru && !style.pass_thru &&
2476 runparams.encoding->package() != Encoding::none &&
2477 font.language()->encoding()->package() != Encoding::none) {
2478 pair<bool, int> const enc_switch =
2479 switchEncoding(os.os(), bparams, runparams,
2480 *(font.language()->encoding()));
2481 if (enc_switch.first) {
2482 column += enc_switch.second;
2483 runparams.encoding = font.language()->encoding();
2487 char_type const c = d->text_[i];
2489 // A display math inset inside an ulem command will be output
2490 // as a box of width \columnwidth, so we have to either disable
2491 // indentation if the inset starts a paragraph, or start a new
2492 // line to accommodate such box. This has to be done before
2493 // writing any font changing commands.
2494 if (runparams.inDisplayMath && !deleted_display_math
2495 && runparams.inulemcmd) {
2496 if (os.afterParbreak())
2502 // Do we need to change font?
2503 if ((font != running_font ||
2504 font.language() != running_font.language()) &&
2507 odocstringstream ods;
2508 column += font.latexWriteStartChanges(ods, bparams,
2509 runparams, basefont,
2511 // Check again for display math in ulem commands as a
2512 // font change may also occur just before a math inset.
2513 if (runparams.inDisplayMath && !deleted_display_math
2514 && runparams.inulemcmd) {
2515 if (os.afterParbreak())
2520 running_font = font;
2522 docstring fontchange = ods.str();
2523 // check whether the fontchange ends with a \\textcolor
2524 // modifier and the text starts with a space (bug 4473)
2525 docstring const last_modifier = rsplit(fontchange, '\\');
2526 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2527 os << fontchange << from_ascii("{}");
2528 // check if the fontchange ends with a trailing blank
2529 // (like "\small " (see bug 3382)
2530 else if (suffixIs(fontchange, ' ') && c == ' ')
2531 os << fontchange.substr(0, fontchange.size() - 1)
2532 << from_ascii("{}");
2537 // FIXME: think about end_pos implementation...
2538 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2539 // FIXME: integrate this case in latexSpecialChar
2540 // Do not print the separation of the optional argument
2541 // if style.pass_thru is false. This works because
2542 // latexSpecialChar ignores spaces if
2543 // style.pass_thru is false.
2544 if (i != body_pos - 1) {
2545 if (d->simpleTeXBlanks(runparams, os,
2546 i, column, font, style)) {
2547 // A surrogate pair was output. We
2548 // must not call latexSpecialChar
2549 // in this iteration, since it would output
2550 // the combining character again.
2557 OutputParams rp = runparams;
2558 rp.free_spacing = style.free_spacing;
2559 rp.local_font = &font;
2560 rp.intitle = style.intitle;
2562 // Two major modes: LaTeX or plain
2563 // Handle here those cases common to both modes
2564 // and then split to handle the two modes separately.
2565 if (c == META_INSET) {
2566 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2567 d->latexInset(bparams, os, rp, running_font,
2568 basefont, outerfont, open_font,
2569 runningChange, style, i, column);
2571 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2573 d->latexSpecialChar(os, bparams, rp,
2574 running_font, runningChange,
2575 style, i, end_pos, column);
2576 } catch (EncodingException & e) {
2577 if (runparams.dryrun) {
2578 os << "<" << _("LyX Warning: ")
2579 << _("uncodable character") << " '";
2583 // add location information and throw again.
2591 // Set the encoding to that returned from latexSpecialChar (see
2592 // comment for encoding member in OutputParams.h)
2593 runparams.encoding = rp.encoding;
2595 // Also carry on the info on a closed ulem command for insets
2596 // such as Note that do not produce any output, so that no
2597 // command is ever executed but its opening was recorded.
2598 runparams.inulemcmd = rp.inulemcmd;
2601 // If we have an open font definition, we have to close it
2603 #ifdef FIXED_LANGUAGE_END_DETECTION
2605 running_font.latexWriteEndChanges(os, bparams,
2606 runparams, basefont,
2607 next_->getFont(bparams, 0, outerfont));
2609 running_font.latexWriteEndChanges(os, bparams,
2610 runparams, basefont, basefont);
2613 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2614 //FIXME: there as we start another \selectlanguage with the next paragraph if
2615 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2616 running_font.latexWriteEndChanges(os, bparams, runparams,
2617 basefont, basefont);
2621 column += Changes::latexMarkChange(os, bparams, runningChange,
2622 Change(Change::UNCHANGED), runparams);
2624 // Needed if there is an optional argument but no contents.
2625 if (body_pos > 0 && body_pos == size()) {
2629 if (!style.rightdelim().empty()) {
2630 os << style.rightdelim();
2631 column += style.rightdelim().size();
2634 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2635 && runparams.encoding != prev_encoding) {
2636 runparams.encoding = prev_encoding;
2637 os << setEncoding(prev_encoding->iconvName());
2640 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2644 bool Paragraph::emptyTag() const
2646 for (pos_type i = 0; i < size(); ++i) {
2647 if (Inset const * inset = getInset(i)) {
2648 InsetCode lyx_code = inset->lyxCode();
2649 // FIXME testing like that is wrong. What is
2651 if (lyx_code != TOC_CODE &&
2652 lyx_code != INCLUDE_CODE &&
2653 lyx_code != GRAPHICS_CODE &&
2654 lyx_code != ERT_CODE &&
2655 lyx_code != LISTINGS_CODE &&
2656 lyx_code != FLOAT_CODE &&
2657 lyx_code != TABULAR_CODE) {
2661 char_type c = d->text_[i];
2662 if (c != ' ' && c != '\t')
2670 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2673 for (pos_type i = 0; i < size(); ++i) {
2674 if (Inset const * inset = getInset(i)) {
2675 InsetCode lyx_code = inset->lyxCode();
2676 if (lyx_code == LABEL_CODE) {
2677 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2678 docstring const & id = il->getParam("name");
2679 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2687 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2691 for (i = 0; i < size(); ++i) {
2692 if (Inset const * inset = getInset(i)) {
2693 inset->docbook(os, runparams);
2695 char_type c = d->text_[i];
2698 os << sgml::escapeChar(c);
2705 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2709 for (i = 0; i < size(); ++i) {
2710 if (Inset const * inset = getInset(i)) {
2711 inset->xhtml(xs, runparams);
2713 char_type c = d->text_[i];
2723 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2726 pos_type size = text_.size();
2727 for (pos_type i = initial; i < size; ++i) {
2728 Font font = owner_->getFont(buf.params(), i, outerfont);
2729 if (text_[i] == META_INSET)
2731 if (i != initial && font != font_old)
2740 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2742 OutputParams const & runparams,
2743 Font const & outerfont,
2744 pos_type initial) const
2746 bool emph_flag = false;
2748 Layout const & style = *d->layout_;
2750 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2752 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2755 // parsing main loop
2756 for (pos_type i = initial; i < size(); ++i) {
2757 Font font = getFont(buf.params(), i, outerfont);
2759 // handle <emphasis> tag
2760 if (font_old.emph() != font.fontInfo().emph()) {
2761 if (font.fontInfo().emph() == FONT_ON) {
2764 } else if (i != initial) {
2765 os << "</emphasis>";
2770 if (Inset const * inset = getInset(i)) {
2771 inset->docbook(os, runparams);
2773 char_type c = d->text_[i];
2775 if (style.pass_thru)
2778 os << sgml::escapeChar(c);
2780 font_old = font.fontInfo();
2784 os << "</emphasis>";
2787 if (style.free_spacing)
2789 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2795 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2796 vector<html::EndFontTag> & tagsToClose,
2797 bool & flag, FontState curstate, html::FontTypes type)
2799 if (curstate == FONT_ON) {
2800 tagsToOpen.push_back(html::FontTag(type));
2803 tagsToClose.push_back(html::EndFontTag(type));
2810 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2812 OutputParams const & runparams,
2813 Font const & outerfont,
2814 bool start_paragraph, bool close_paragraph,
2815 pos_type initial) const
2819 // track whether we have opened these tags
2820 bool emph_flag = false;
2821 bool bold_flag = false;
2822 bool noun_flag = false;
2823 bool ubar_flag = false;
2824 bool dbar_flag = false;
2825 bool sout_flag = false;
2826 bool wave_flag = false;
2828 bool shap_flag = false;
2830 bool faml_flag = false;
2832 bool size_flag = false;
2834 Layout const & style = *d->layout_;
2836 if (start_paragraph)
2837 xs.startParagraph(allowEmpty());
2840 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2842 FontShape curr_fs = INHERIT_SHAPE;
2843 FontFamily curr_fam = INHERIT_FAMILY;
2844 FontSize curr_size = FONT_SIZE_INHERIT;
2846 string const default_family =
2847 buf.masterBuffer()->params().fonts_default_family;
2849 vector<html::FontTag> tagsToOpen;
2850 vector<html::EndFontTag> tagsToClose;
2852 // parsing main loop
2853 for (pos_type i = initial; i < size(); ++i) {
2854 // let's not show deleted material in the output
2858 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2861 FontState curstate = font.fontInfo().emph();
2862 if (font_old.emph() != curstate)
2863 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2866 curstate = font.fontInfo().noun();
2867 if (font_old.noun() != curstate)
2868 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2871 curstate = font.fontInfo().underbar();
2872 if (font_old.underbar() != curstate)
2873 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2876 curstate = font.fontInfo().strikeout();
2877 if (font_old.strikeout() != curstate)
2878 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2881 curstate = font.fontInfo().uuline();
2882 if (font_old.uuline() != curstate)
2883 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2886 curstate = font.fontInfo().uwave();
2887 if (font_old.uwave() != curstate)
2888 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2891 // a little hackish, but allows us to reuse what we have.
2892 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2893 if (font_old.series() != font.fontInfo().series())
2894 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2897 curr_fs = font.fontInfo().shape();
2898 FontShape old_fs = font_old.shape();
2899 if (old_fs != curr_fs) {
2903 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2906 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2908 case SMALLCAPS_SHAPE:
2909 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2915 // the other tags are for internal use
2923 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2927 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2930 case SMALLCAPS_SHAPE:
2931 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2938 // the other tags are for internal use
2945 curr_fam = font.fontInfo().family();
2946 FontFamily old_fam = font_old.family();
2947 if (old_fam != curr_fam) {
2951 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2954 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2956 case TYPEWRITER_FAMILY:
2957 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2959 case INHERIT_FAMILY:
2962 // the other tags are for internal use
2970 // we will treat a "default" font family as roman, since we have
2971 // no other idea what to do.
2972 if (default_family != "rmdefault" && default_family != "default") {
2973 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
2978 if (default_family != "sfdefault") {
2979 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
2983 case TYPEWRITER_FAMILY:
2984 if (default_family != "ttdefault") {
2985 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
2989 case INHERIT_FAMILY:
2992 // the other tags are for internal use
2999 curr_size = font.fontInfo().size();
3000 FontSize old_size = font_old.size();
3001 if (old_size != curr_size) {
3004 case FONT_SIZE_TINY:
3005 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3007 case FONT_SIZE_SCRIPT:
3008 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3010 case FONT_SIZE_FOOTNOTE:
3011 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3013 case FONT_SIZE_SMALL:
3014 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3016 case FONT_SIZE_LARGE:
3017 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3019 case FONT_SIZE_LARGER:
3020 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3022 case FONT_SIZE_LARGEST:
3023 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3025 case FONT_SIZE_HUGE:
3026 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3028 case FONT_SIZE_HUGER:
3029 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3031 case FONT_SIZE_INCREASE:
3032 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3034 case FONT_SIZE_DECREASE:
3035 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3037 case FONT_SIZE_INHERIT:
3038 case FONT_SIZE_NORMAL:
3041 // the other tags are for internal use
3047 switch (curr_size) {
3048 case FONT_SIZE_TINY:
3049 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3052 case FONT_SIZE_SCRIPT:
3053 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3056 case FONT_SIZE_FOOTNOTE:
3057 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3060 case FONT_SIZE_SMALL:
3061 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3064 case FONT_SIZE_LARGE:
3065 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3068 case FONT_SIZE_LARGER:
3069 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3072 case FONT_SIZE_LARGEST:
3073 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3076 case FONT_SIZE_HUGE:
3077 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3080 case FONT_SIZE_HUGER:
3081 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3084 case FONT_SIZE_INCREASE:
3085 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3088 case FONT_SIZE_DECREASE:
3089 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3092 case FONT_SIZE_NORMAL:
3093 case FONT_SIZE_INHERIT:
3096 // the other tags are for internal use
3103 // Other such tags? What about the other text ranges?
3105 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3106 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3107 for (; cit != cen; ++cit)
3110 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3111 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3112 for (; sit != sen; ++sit)
3115 tagsToClose.clear();
3118 Inset const * inset = getInset(i);
3120 if (!runparams.for_toc || inset->isInToc()) {
3121 OutputParams np = runparams;
3122 np.local_font = &font;
3123 // If the paragraph has size 1, then we are in the "special
3124 // case" where we do not output the containing paragraph info
3125 if (!inset->getLayout().htmlisblock() && size() != 1)
3126 np.html_in_par = true;
3127 retval += inset->xhtml(xs, np);
3130 char_type c = getUChar(buf.masterBuffer()->params(), i);
3133 font_old = font.fontInfo();
3137 // I'm worried about what happens if a branch, say, is itself
3138 // wrapped in some font stuff. I think that will not work.
3140 if (close_paragraph)
3147 bool Paragraph::isHfill(pos_type pos) const
3149 Inset const * inset = getInset(pos);
3150 return inset && inset->isHfill();
3154 bool Paragraph::isNewline(pos_type pos) const
3156 Inset const * inset = getInset(pos);
3157 return inset && inset->lyxCode() == NEWLINE_CODE;
3161 bool Paragraph::isEnvSeparator(pos_type pos) const
3163 Inset const * inset = getInset(pos);
3164 return inset && inset->lyxCode() == SEPARATOR_CODE;
3168 bool Paragraph::isLineSeparator(pos_type pos) const
3170 char_type const c = d->text_[pos];
3171 if (isLineSeparatorChar(c))
3173 Inset const * inset = getInset(pos);
3174 return inset && inset->isLineSeparator();
3178 bool Paragraph::isWordSeparator(pos_type pos) const
3182 if (Inset const * inset = getInset(pos))
3183 return !inset->isLetter();
3184 // if we have a hard hyphen (no en- or emdash) or apostrophe
3185 // we pass this to the spell checker
3186 // FIXME: this method is subject to change, visit
3187 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3188 // to get an impression how complex this is.
3189 if (isHardHyphenOrApostrophe(pos))
3191 char_type const c = d->text_[pos];
3192 // We want to pass the escape chars to the spellchecker
3193 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3194 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3198 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3200 pos_type const psize = size();
3203 char_type const c = d->text_[pos];
3204 if (c != '-' && c != '\'')
3206 int nextpos = pos + 1;
3207 int prevpos = pos > 0 ? pos - 1 : 0;
3208 if ((nextpos == psize || isSpace(nextpos))
3209 && (pos == 0 || isSpace(prevpos)))
3215 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3217 return d->speller_state_.getRange(pos);
3221 bool Paragraph::isChar(pos_type pos) const
3223 if (Inset const * inset = getInset(pos))
3224 return inset->isChar();
3225 char_type const c = d->text_[pos];
3226 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3230 bool Paragraph::isSpace(pos_type pos) const
3232 if (Inset const * inset = getInset(pos))
3233 return inset->isSpace();
3234 char_type const c = d->text_[pos];
3235 return lyx::isSpace(c);
3240 Paragraph::getParLanguage(BufferParams const & bparams) const
3243 return getFirstFontSettings(bparams).language();
3244 // FIXME: we should check the prev par as well (Lgb)
3245 return bparams.language;
3249 bool Paragraph::isRTL(BufferParams const & bparams) const
3251 return getParLanguage(bparams)->rightToLeft()
3252 && !inInset().getLayout().forceLTR();
3256 void Paragraph::changeLanguage(BufferParams const & bparams,
3257 Language const * from, Language const * to)
3259 // change language including dummy font change at the end
3260 for (pos_type i = 0; i <= size(); ++i) {
3261 Font font = getFontSettings(bparams, i);
3262 if (font.language() == from) {
3263 font.setLanguage(to);
3265 d->requestSpellCheck(i);
3271 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3273 Language const * doc_language = bparams.language;
3274 FontList::const_iterator cit = d->fontlist_.begin();
3275 FontList::const_iterator end = d->fontlist_.end();
3277 for (; cit != end; ++cit)
3278 if (cit->font().language() != ignore_language &&
3279 cit->font().language() != latex_language &&
3280 cit->font().language() != doc_language)
3286 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3288 FontList::const_iterator cit = d->fontlist_.begin();
3289 FontList::const_iterator end = d->fontlist_.end();
3291 for (; cit != end; ++cit) {
3292 Language const * lang = cit->font().language();
3293 if (lang != ignore_language &&
3294 lang != latex_language)
3295 languages.insert(lang);
3300 docstring Paragraph::asString(int options) const
3302 return asString(0, size(), options);
3306 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3308 odocstringstream os;
3311 && options & AS_STR_LABEL
3312 && !d->params_.labelString().empty())
3313 os << d->params_.labelString() << ' ';
3315 for (pos_type i = beg; i < end; ++i) {
3316 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3318 char_type const c = d->text_[i];
3319 if (isPrintable(c) || c == '\t'
3320 || (c == '\n' && (options & AS_STR_NEWLINES)))
3322 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3323 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3324 LASSERT(runparams != 0, return docstring());
3325 getInset(i)->plaintext(os, *runparams);
3327 getInset(i)->toString(os);
3336 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3337 bool const shorten) const
3339 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3340 if (!d->params_.labelString().empty())
3341 os += d->params_.labelString() + ' ';
3342 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3345 char_type const c = d->text_[i];
3348 else if (c == META_INSET)
3349 getInset(i)->forOutliner(os, tmplen, false);
3352 Text::shortenForOutliner(os, maxlen);
3356 void Paragraph::setInsetOwner(Inset const * inset)
3358 d->inset_owner_ = inset;
3362 int Paragraph::id() const
3368 void Paragraph::setId(int id)
3374 Layout const & Paragraph::layout() const
3380 void Paragraph::setLayout(Layout const & layout)
3382 d->layout_ = &layout;
3386 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3388 setLayout(tc.defaultLayout());
3392 void Paragraph::setPlainLayout(DocumentClass const & tc)
3394 setLayout(tc.plainLayout());
3398 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3400 if (usePlainLayout())
3401 setPlainLayout(tclass);
3403 setDefaultLayout(tclass);
3407 Inset const & Paragraph::inInset() const
3409 LBUFERR(d->inset_owner_);
3410 return *d->inset_owner_;
3414 ParagraphParameters & Paragraph::params()
3420 ParagraphParameters const & Paragraph::params() const
3426 bool Paragraph::isFreeSpacing() const
3428 if (d->layout_->free_spacing)
3430 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3434 bool Paragraph::allowEmpty() const
3436 if (d->layout_->keepempty)
3438 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3442 bool Paragraph::brokenBiblio() const
3444 // there is a problem if there is no bibitem at position 0 or
3445 // if there is another bibitem in the paragraph.
3446 return d->layout_->labeltype == LABEL_BIBLIO
3447 && (d->insetlist_.find(BIBITEM_CODE) != 0
3448 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3452 int Paragraph::fixBiblio(Buffer const & buffer)
3454 // FIXME: What about the case where paragraph is not BIBLIO
3455 // but there is an InsetBibitem?
3456 // FIXME: when there was already an inset at 0, the return value is 1,
3457 // which does not tell whether another inset has been remove; the
3458 // cursor cannot be correctly updated.
3460 if (d->layout_->labeltype != LABEL_BIBLIO)
3463 bool const track_changes = buffer.params().track_changes;
3464 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3465 bool const hasbibitem0 = bibitem_pos == 0;
3468 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3469 // There was an InsetBibitem at pos 0, and no other one => OK
3470 if (bibitem_pos == -1)
3472 // there is a bibitem at the 0 position, but since
3473 // there is a second one, we copy the second on the
3474 // first. We're assuming there are at most two of
3475 // these, which there should be.
3476 // FIXME: why does it make sense to do that rather
3477 // than keep the first? (JMarc)
3478 Inset * inset = releaseInset(bibitem_pos);
3479 d->insetlist_.begin()->inset = inset;
3480 return -bibitem_pos;
3483 // We need to create an inset at the beginning
3485 if (bibitem_pos > 0) {
3486 // there was one somewhere in the paragraph, let's move it
3487 inset = d->insetlist_.release(bibitem_pos);
3488 eraseChar(bibitem_pos, track_changes);
3491 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3492 InsetCommandParams(BIBITEM_CODE));
3494 Font font(inherit_font, buffer.params().language);
3495 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3496 : Change::UNCHANGED));
3502 void Paragraph::checkAuthors(AuthorList const & authorList)
3504 d->changes_.checkAuthors(authorList);
3508 bool Paragraph::isChanged(pos_type pos) const
3510 return lookupChange(pos).changed();
3514 bool Paragraph::isInserted(pos_type pos) const
3516 return lookupChange(pos).inserted();
3520 bool Paragraph::isDeleted(pos_type pos) const
3522 return lookupChange(pos).deleted();
3526 InsetList const & Paragraph::insetList() const
3528 return d->insetlist_;
3532 void Paragraph::setBuffer(Buffer & b)
3534 d->insetlist_.setBuffer(b);
3538 Inset * Paragraph::releaseInset(pos_type pos)
3540 Inset * inset = d->insetlist_.release(pos);
3541 /// does not honour change tracking!
3542 eraseChar(pos, false);
3547 Inset * Paragraph::getInset(pos_type pos)
3549 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3550 ? d->insetlist_.get(pos) : 0;
3554 Inset const * Paragraph::getInset(pos_type pos) const
3556 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3557 ? d->insetlist_.get(pos) : 0;
3561 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3562 pos_type & right, TextCase action)
3564 // process sequences of modified characters; in change
3565 // tracking mode, this approach results in much better
3566 // usability than changing case on a char-by-char basis
3567 // We also need to track the current font, since font
3568 // changes within sequences can occur.
3569 vector<pair<char_type, Font> > changes;
3571 bool const trackChanges = bparams.track_changes;
3573 bool capitalize = true;
3575 for (; pos < right; ++pos) {
3576 char_type oldChar = d->text_[pos];
3577 char_type newChar = oldChar;
3579 // ignore insets and don't play with deleted text!
3580 if (oldChar != META_INSET && !isDeleted(pos)) {
3582 case text_lowercase:
3583 newChar = lowercase(oldChar);
3585 case text_capitalization:
3587 newChar = uppercase(oldChar);
3591 case text_uppercase:
3592 newChar = uppercase(oldChar);
3597 if (isWordSeparator(pos) || isDeleted(pos)) {
3598 // permit capitalization again
3602 if (oldChar != newChar) {
3603 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3604 if (pos != right - 1)
3606 // step behind the changing area
3610 int erasePos = pos - changes.size();
3611 for (size_t i = 0; i < changes.size(); i++) {
3612 insertChar(pos, changes[i].first,
3615 if (!eraseChar(erasePos, trackChanges)) {
3618 ++right; // expand selection
3626 int Paragraph::find(docstring const & str, bool cs, bool mw,
3627 pos_type start_pos, bool del) const
3629 pos_type pos = start_pos;
3630 int const strsize = str.length();
3632 pos_type const parsize = d->text_.size();
3633 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3634 // Ignore "invisible" letters such as ligature breaks
3635 // and hyphenation chars while searching
3636 while (pos < parsize - 1 && isInset(pos)) {
3637 odocstringstream os;
3638 getInset(pos)->toString(os);
3639 if (!getInset(pos)->isLetter() || !os.str().empty())
3643 if (cs && str[i] != d->text_[pos])
3645 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3647 if (!del && isDeleted(pos))
3654 // if necessary, check whether string matches word
3656 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3659 && !isWordSeparator(pos))
3663 return pos - start_pos;
3667 char_type Paragraph::getChar(pos_type pos) const
3669 return d->text_[pos];
3673 pos_type Paragraph::size() const
3675 return d->text_.size();
3679 bool Paragraph::empty() const
3681 return d->text_.empty();
3685 bool Paragraph::isInset(pos_type pos) const
3687 return d->text_[pos] == META_INSET;
3691 bool Paragraph::isSeparator(pos_type pos) const
3693 //FIXME: Are we sure this can be the only separator?
3694 return d->text_[pos] == ' ';
3698 void Paragraph::deregisterWords()
3700 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3701 Private::LangWordsMap::const_iterator ite = d->words_.end();
3702 for (; itl != ite; ++itl) {
3703 WordList * wl = theWordList(itl->first);
3704 Private::Words::const_iterator it = (itl->second).begin();
3705 Private::Words::const_iterator et = (itl->second).end();
3706 for (; it != et; ++it)
3713 void Paragraph::locateWord(pos_type & from, pos_type & to,
3714 word_location const loc) const
3717 case WHOLE_WORD_STRICT:
3718 if (from == 0 || from == size()
3719 || isWordSeparator(from)
3720 || isWordSeparator(from - 1)) {
3724 // no break here, we go to the next
3727 // If we are already at the beginning of a word, do nothing
3728 if (!from || isWordSeparator(from - 1))
3730 // no break here, we go to the next
3733 // always move the cursor to the beginning of previous word
3734 while (from && !isWordSeparator(from - 1))
3738 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3741 // no need to move the 'from' cursor
3745 while (to < size() && !isWordSeparator(to))
3750 void Paragraph::collectWords()
3752 for (pos_type pos = 0; pos < size(); ++pos) {
3753 if (isWordSeparator(pos))
3755 pos_type from = pos;
3756 locateWord(from, pos, WHOLE_WORD);
3757 // Work around MSVC warning: The statement
3758 // if (pos < from + lyxrc.completion_minlength)
3759 // triggers a signed vs. unsigned warning.
3760 // I don't know why this happens, it could be a MSVC bug, or
3761 // related to LLP64 (windows) vs. LP64 (unix) programming
3762 // model, or the C++ standard might be ambigous in the section
3763 // defining the "usual arithmetic conversions". However, using
3764 // a temporary variable is safe and works on all compilers.
3765 pos_type const endpos = from + lyxrc.completion_minlength;
3768 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3769 if (cit == d->fontlist_.end())
3771 Language const * lang = cit->font().language();
3772 docstring const word = asString(from, pos, AS_STR_NONE);
3773 d->words_[lang->lang()].insert(word);
3778 void Paragraph::registerWords()
3780 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3781 Private::LangWordsMap::const_iterator ite = d->words_.end();
3782 for (; itl != ite; ++itl) {
3783 WordList * wl = theWordList(itl->first);
3784 Private::Words::const_iterator it = (itl->second).begin();
3785 Private::Words::const_iterator et = (itl->second).end();
3786 for (; it != et; ++it)
3792 void Paragraph::updateWords()
3800 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3802 SkipPositionsIterator begin = skips.begin();
3803 SkipPositions::iterator end = skips.end();
3804 if (pos > 0 && begin < end) {
3806 if (end->last == pos - 1) {
3811 skips.insert(end, FontSpan(pos, pos));
3815 Language * Paragraph::Private::locateSpellRange(
3816 pos_type & from, pos_type & to,
3817 SkipPositions & skips) const
3819 // skip leading white space
3820 while (from < to && owner_->isWordSeparator(from))
3822 // don't check empty range
3825 // get current language
3826 Language * lang = getSpellLanguage(from);
3827 pos_type last = from;
3828 bool samelang = true;
3829 bool sameinset = true;
3830 while (last < to && samelang && sameinset) {
3831 // hop to end of word
3832 while (last < to && !owner_->isWordSeparator(last)) {
3833 if (owner_->getInset(last)) {
3834 appendSkipPosition(skips, last);
3835 } else if (owner_->isDeleted(last)) {
3836 appendSkipPosition(skips, last);
3840 // hop to next word while checking for insets
3841 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3842 if (Inset const * inset = owner_->getInset(last))
3843 sameinset = inset->isChar() && inset->isLetter();
3844 if (sameinset && owner_->isDeleted(last)) {
3845 appendSkipPosition(skips, last);
3850 if (sameinset && last < to) {
3851 // now check for language change
3852 samelang = lang == getSpellLanguage(last);
3855 // if language change detected backstep is needed
3863 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3866 const_cast<Language *>(owner_->getFontSettings(
3867 inset_owner_->buffer().params(), from).language());
3868 if (lang == inset_owner_->buffer().params().language
3869 && !lyxrc.spellchecker_alt_lang.empty()) {
3871 string const lang_variety =
3872 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3873 lang->setCode(lang_code);
3874 lang->setVariety(lang_variety);
3880 void Paragraph::requestSpellCheck(pos_type pos)
3882 d->requestSpellCheck(pos);
3886 bool Paragraph::needsSpellCheck() const
3888 SpellChecker::ChangeNumber speller_change_number = 0;
3889 if (theSpellChecker())
3890 speller_change_number = theSpellChecker()->changeNumber();
3891 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3892 d->speller_state_.needsCompleteRefresh(speller_change_number);
3894 return d->needsSpellCheck();
3898 bool Paragraph::Private::ignoreWord(docstring const & word) const
3900 // Ignore words with digits
3901 // FIXME: make this customizable
3902 // (note that some checkers ignore words with digits by default)
3903 docstring::const_iterator cit = word.begin();
3904 docstring::const_iterator const end = word.end();
3905 for (; cit != end; ++cit) {
3906 if (isNumber((*cit)))
3913 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3914 WordLangTuple & wl, docstring_list & suggestions,
3915 bool do_suggestion, bool check_learned) const
3917 SpellChecker::Result result = SpellChecker::WORD_OK;
3918 SpellChecker * speller = theSpellChecker();
3922 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3925 locateWord(from, to, WHOLE_WORD);
3926 if (from == to || from >= size())
3929 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3930 Language * lang = d->getSpellLanguage(from);
3932 wl = WordLangTuple(word, lang);
3937 if (needsSpellCheck() || check_learned) {
3939 if (!d->ignoreWord(word)) {
3940 bool const trailing_dot = to < size() && d->text_[to] == '.';
3941 result = speller->check(wl);
3942 if (SpellChecker::misspelled(result) && trailing_dot) {
3943 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3944 result = speller->check(wl);
3945 if (!SpellChecker::misspelled(result)) {
3946 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3948 from << ".." << to << "]");
3950 // spell check with dot appended failed too
3951 // restore original word/lang value
3952 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3953 wl = WordLangTuple(word, lang);
3957 if (!SpellChecker::misspelled(result)) {
3958 // area up to the begin of the next word is not misspelled
3959 while (end < size() && isWordSeparator(end))
3962 d->setMisspelled(from, end, result);
3964 result = d->speller_state_.getState(from);
3968 suggestions.clear();
3970 if (SpellChecker::misspelled(result)) {
3971 LYXERR(Debug::GUI, "misspelled word: \"" <<
3973 from << ".." << to << "]");
3975 speller->suggest(wl, suggestions);
3981 void Paragraph::Private::markMisspelledWords(
3982 pos_type const & first, pos_type const & last,
3983 SpellChecker::Result result,
3984 docstring const & word,
3985 SkipPositions const & skips)
3987 if (!SpellChecker::misspelled(result)) {
3988 setMisspelled(first, last, SpellChecker::WORD_OK);
3992 SpellChecker * speller = theSpellChecker();
3993 // locate and enumerate the error positions
3994 int nerrors = speller->numMisspelledWords();
3996 SkipPositionsIterator it = skips.begin();
3997 SkipPositionsIterator et = skips.end();
3998 for (int index = 0; index < nerrors; ++index) {
4001 speller->misspelledWord(index, wstart, wlen);
4002 /// should not happen if speller supports range checks
4003 if (!wlen) continue;
4004 docstring const misspelled = word.substr(wstart, wlen);
4005 wstart += first + numskipped;
4006 if (snext < wstart) {
4007 /// mark the range of correct spelling
4008 numskipped += countSkips(it, et, wstart);
4009 setMisspelled(snext,
4010 wstart - 1, SpellChecker::WORD_OK);
4012 snext = wstart + wlen;
4013 numskipped += countSkips(it, et, snext);
4014 /// mark the range of misspelling
4015 setMisspelled(wstart, snext, result);
4016 LYXERR(Debug::GUI, "misspelled word: \"" <<
4017 misspelled << "\" [" <<
4018 wstart << ".." << (snext-1) << "]");
4021 if (snext <= last) {
4022 /// mark the range of correct spelling at end
4023 setMisspelled(snext, last, SpellChecker::WORD_OK);
4028 void Paragraph::spellCheck() const
4030 SpellChecker * speller = theSpellChecker();
4031 if (!speller || empty() ||!needsSpellCheck())
4035 d->rangeOfSpellCheck(start, endpos);
4036 if (speller->canCheckParagraph()) {
4037 // loop until we leave the range
4038 for (pos_type first = start; first < endpos; ) {
4039 pos_type last = endpos;
4040 Private::SkipPositions skips;
4041 Language * lang = d->locateSpellRange(first, last, skips);
4042 if (first >= endpos)
4044 // start the spell checker on the unit of meaning
4045 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4046 WordLangTuple wl = WordLangTuple(word, lang);
4047 SpellChecker::Result result = word.size() ?
4048 speller->check(wl) : SpellChecker::WORD_OK;
4049 d->markMisspelledWords(first, last, result, word, skips);
4053 static docstring_list suggestions;
4054 pos_type to = endpos;
4055 while (start < endpos) {
4057 spellCheck(start, to, wl, suggestions, false);
4061 d->readySpellCheck();
4065 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4067 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4068 if (result || pos <= 0 || pos > size())
4070 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4071 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4076 string Paragraph::magicLabel() const
4079 ss << "magicparlabel-" << id();