3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Asger Alstrup
7 * \author Lars Gullik Bjønnes
8 * \author Richard Heck (XHTML output)
9 * \author Jean-Marc Lasgouttes
10 * \author Angus Leeming
12 * \author André Pönitz
14 * \author Jürgen Vigna
16 * Full author contact details are available in file CREDITS.
21 #include "Paragraph.h"
23 #include "LayoutFile.h"
25 #include "BufferParams.h"
28 #include "BufferEncodings.h"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "texstream.h"
44 #include "TextClass.h"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
56 #include "mathed/InsetMathHull.h"
58 #include "support/debug.h"
59 #include "support/docstring_list.h"
60 #include "support/ExceptionMessage.h"
61 #include "support/gettext.h"
62 #include "support/lassert.h"
63 #include "support/lstrings.h"
64 #include "support/textutils.h"
71 using namespace lyx::support;
77 /// Inset identifier (above 0x10ffff, for ucs-4)
78 char_type const META_INSET = 0x200001;
83 /////////////////////////////////////////////////////////////////////
87 /////////////////////////////////////////////////////////////////////
89 class SpellResultRange {
91 SpellResultRange(FontSpan range, SpellChecker::Result result)
92 : range_(range), result_(result)
95 FontSpan const & range() const { return range_; }
97 void range(FontSpan const & r) { range_ = r; }
99 SpellChecker::Result result() const { return result_; }
101 void result(SpellChecker::Result r) { result_ = r; }
103 bool contains(pos_type pos) const { return range_.contains(pos); }
105 bool covered(FontSpan const & r) const
107 // 1. first of new range inside current range or
108 // 2. last of new range inside current range or
109 // 3. first of current range inside new range or
110 // 4. last of current range inside new range
111 //FIXME: is this the same as !range_.intersect(r).empty() ?
112 return range_.contains(r.first) || range_.contains(r.last) ||
113 r.contains(range_.first) || r.contains(range_.last);
116 void shift(pos_type pos, int offset)
118 if (range_.first > pos) {
119 range_.first += offset;
120 range_.last += offset;
121 } else if (range_.last >= pos) {
122 range_.last += offset;
127 SpellChecker::Result result_ ;
131 /////////////////////////////////////////////////////////////////////
135 /////////////////////////////////////////////////////////////////////
137 class SpellCheckerState {
141 needs_refresh_ = true;
142 current_change_number_ = 0;
145 void setRange(FontSpan const & fp, SpellChecker::Result state)
148 RangesIterator et = ranges_.end();
149 RangesIterator it = ranges_.begin();
150 for (; it != et; ++it) {
151 if (!it->covered(fp))
152 result.push_back(SpellResultRange(it->range(), it->result()));
153 else if (state == SpellChecker::WORD_OK) {
154 // trim or split the current misspelled range
155 // store misspelled ranges only
156 FontSpan range = it->range();
157 if (fp.first > range.first) {
158 // misspelled area in front of WORD_OK
159 range.last = fp.first - 1;
160 result.push_back(SpellResultRange(range, it->result()));
163 if (fp.last < range.last) {
164 // misspelled area after WORD_OK range
165 range.first = fp.last + 1;
166 result.push_back(SpellResultRange(range, it->result()));
171 if (state != SpellChecker::WORD_OK)
172 ranges_.push_back(SpellResultRange(fp, state));
175 void increasePosAfterPos(pos_type pos)
177 correctRangesAfterPos(pos, 1);
181 void decreasePosAfterPos(pos_type pos)
183 correctRangesAfterPos(pos, -1);
187 void refreshLast(pos_type pos)
189 if (pos < refresh_.last)
193 SpellChecker::Result getState(pos_type pos) const
195 SpellChecker::Result result = SpellChecker::WORD_OK;
196 RangesIterator et = ranges_.end();
197 RangesIterator it = ranges_.begin();
198 for (; it != et; ++it) {
199 if(it->contains(pos)) {
206 FontSpan const & getRange(pos_type pos) const
208 /// empty span to indicate mismatch
209 static FontSpan empty_;
210 RangesIterator et = ranges_.end();
211 RangesIterator it = ranges_.begin();
212 for (; it != et; ++it) {
213 if(it->contains(pos)) {
220 bool needsRefresh() const
222 return needs_refresh_;
225 SpellChecker::ChangeNumber currentChangeNumber() const
227 return current_change_number_;
230 void refreshRange(pos_type & first, pos_type & last) const
232 first = refresh_.first;
233 last = refresh_.last;
236 void needsRefresh(pos_type pos)
238 if (needs_refresh_ && pos != -1) {
239 if (pos < refresh_.first)
240 refresh_.first = pos;
241 if (pos > refresh_.last)
243 } else if (pos != -1) {
244 // init request check for neighbour positions too
245 refresh_.first = pos > 0 ? pos - 1 : 0;
246 // no need for special end of paragraph check
247 refresh_.last = pos + 1;
249 needs_refresh_ = pos != -1;
252 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number)
254 needs_refresh_ = true;
257 current_change_number_ = change_number;
260 typedef vector<SpellResultRange> Ranges;
261 typedef Ranges::const_iterator RangesIterator;
263 /// the area of the paragraph with pending spell check
266 /// spell state cache version number
267 SpellChecker::ChangeNumber current_change_number_;
270 void correctRangesAfterPos(pos_type pos, int offset)
272 RangesIterator et = ranges_.end();
273 Ranges::iterator it = ranges_.begin();
274 for (; it != et; ++it) {
275 it->shift(pos, offset);
281 /////////////////////////////////////////////////////////////////////
283 // Paragraph::Private
285 /////////////////////////////////////////////////////////////////////
287 class Paragraph::Private
289 // Enforce our own "copy" constructor
290 Private(Private const &) = delete;
291 Private & operator=(Private const &) = delete;
292 // Unique ID generator
293 static int make_id();
296 Private(Paragraph * owner, Layout const & layout);
297 /// "Copy constructor"
298 Private(Private const &, Paragraph * owner);
299 /// Copy constructor from \p beg to \p end
300 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
303 void insertChar(pos_type pos, char_type c, Change const & change);
305 /// Output the surrogate pair formed by \p c and \p next to \p os.
306 /// \return the number of characters written.
307 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
308 OutputParams const &);
310 /// Output a space in appropriate formatting (or a surrogate pair
311 /// if the next character is a combining character).
312 /// \return whether a surrogate pair was output.
313 bool simpleTeXBlanks(OutputParams const &,
316 unsigned int & column,
318 Layout const & style);
320 /// Output consecutive unicode chars, belonging to the same script as
321 /// specified by the latex macro \p ltx, to \p os starting from \p i.
322 /// \return the number of characters written.
323 int writeScriptChars(otexstream & os, docstring const & ltx,
324 Change const &, Encoding const &, pos_type & i);
326 /// This could go to ParagraphParameters if we want to.
327 int startTeXParParams(BufferParams const &, otexstream &,
328 OutputParams const &) const;
330 /// This could go to ParagraphParameters if we want to.
331 bool endTeXParParams(BufferParams const &, otexstream &,
332 OutputParams const &) const;
335 void latexInset(BufferParams const &,
340 Font const & outerfont,
342 Change & running_change,
343 Layout const & style,
345 unsigned int & column);
348 void latexSpecialChar(
350 BufferParams const & bparams,
351 OutputParams const & runparams,
352 Font const & running_font,
353 Change const & running_change,
354 Layout const & style,
357 unsigned int & column);
364 unsigned int & column);
370 unsigned int & column);
376 unsigned int & column);
379 void validate(LaTeXFeatures & features) const;
381 /// Checks if the paragraph contains only text and no inset or font change.
382 bool onlyText(Buffer const & buf, Font const & outerfont,
383 pos_type initial) const;
385 /// a vector of speller skip positions
386 typedef vector<FontSpan> SkipPositions;
387 typedef SkipPositions::const_iterator SkipPositionsIterator;
389 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
391 Language * getSpellLanguage(pos_type const from) const;
393 Language * locateSpellRange(pos_type & from, pos_type & to,
394 SkipPositions & skips) const;
396 bool hasSpellerChange() const
398 SpellChecker::ChangeNumber speller_change_number = 0;
399 if (theSpellChecker())
400 speller_change_number = theSpellChecker()->changeNumber();
401 return speller_change_number > speller_state_.currentChangeNumber();
404 bool ignoreWord(docstring const & word) const ;
406 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
408 pos_type textsize = owner_->size();
409 // check for sane arguments
410 if (to <= from || from >= textsize)
412 FontSpan fp = FontSpan(from, to - 1);
413 speller_state_.setRange(fp, state);
416 void requestSpellCheck(pos_type pos)
419 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
421 speller_state_.needsRefresh(pos);
424 void readySpellCheck()
426 speller_state_.needsRefresh(-1);
429 bool needsSpellCheck() const
431 return speller_state_.needsRefresh();
434 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
436 speller_state_.refreshRange(first, last);
438 last = owner_->size();
441 pos_type endpos = last;
442 owner_->locateWord(first, endpos, WHOLE_WORD);
445 owner_->locateWord(last, endpos, WHOLE_WORD);
450 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
454 while (it != et && it->first < start) {
455 int skip = it->last - it->first + 1;
463 void markMisspelledWords(pos_type const & first, pos_type const & last,
464 SpellChecker::Result result,
465 docstring const & word,
466 SkipPositions const & skips);
468 InsetCode ownerCode() const
470 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
473 /// Which Paragraph owns us?
477 Inset const * inset_owner_;
486 ParagraphParameters params_;
488 /// for recording and looking up changes
492 InsetList insetlist_;
495 pos_type begin_of_body_;
497 typedef docstring TextContainer;
501 typedef set<docstring> Words;
502 typedef map<string, Words> LangWordsMap;
506 Layout const * layout_;
508 SpellCheckerState speller_state_;
512 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
513 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
520 int Paragraph::Private::make_id()
522 // The id is unique per session across buffers because it is used in
523 // LFUN_PARAGRAPH_GOTO to switch to a different buffer, for instance in the
526 static atomic_uint next_id(0);
531 Paragraph::Private::Private(Private const & p, Paragraph * owner)
532 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
534 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
535 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
538 requestSpellCheck(p.text_.size());
542 Paragraph::Private::Private(Private const & p, Paragraph * owner,
543 pos_type beg, pos_type end)
544 : owner_(owner), inset_owner_(p.inset_owner_), id_(make_id()),
545 params_(p.params_), changes_(p.changes_),
546 insetlist_(p.insetlist_, beg, end),
547 begin_of_body_(p.begin_of_body_), words_(p.words_),
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 void Paragraph::addChangesToToc(DocIterator const & cdit, Buffer const & buf,
572 bool output_active, TocBackend & backend) const
574 d->changes_.addToToc(cdit, buf, output_active, backend);
578 void Paragraph::addChangesToBuffer(Buffer const & buf) const
580 d->changes_.updateBuffer(buf);
584 bool Paragraph::isChangeUpdateRequired() const
586 return d->changes_.isUpdateRequired();
590 bool Paragraph::isDeleted(pos_type start, pos_type end) const
592 LASSERT(start >= 0 && start <= size(), return false);
593 LASSERT(end > start && end <= size() + 1, return false);
595 return d->changes_.isDeleted(start, end);
599 bool Paragraph::isChanged(pos_type start, pos_type end) const
601 LASSERT(start >= 0 && start <= size(), return false);
602 LASSERT(end > start && end <= size() + 1, return false);
604 return d->changes_.isChanged(start, end);
608 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
610 // keep the logic here in sync with the logic of eraseChars()
614 Change const & change = d->changes_.lookup(size());
615 return change.inserted() && change.currentAuthor();
619 void Paragraph::setChange(Change const & change)
621 // beware of the imaginary end-of-par character!
622 d->changes_.set(change, 0, size() + 1);
625 * Propagate the change recursively - but not in case of DELETED!
627 * Imagine that your co-author makes changes in an existing inset. He
628 * sends your document to you and you come to the conclusion that the
629 * inset should go completely. If you erase it, LyX must not delete all
630 * text within the inset. Otherwise, the change tracked insertions of
631 * your co-author get lost and there is no way to restore them later.
633 * Conclusion: An inset's content should remain untouched if you delete it
636 if (!change.deleted()) {
637 for (pos_type pos = 0; pos < size(); ++pos) {
638 if (Inset * inset = getInset(pos))
639 inset->setChange(change);
645 void Paragraph::setChange(pos_type pos, Change const & change)
647 LASSERT(pos >= 0 && pos <= size(), return);
648 d->changes_.set(change, pos);
650 // see comment in setChange(Change const &) above
651 if (!change.deleted() && pos < size())
652 if (Inset * inset = getInset(pos))
653 inset->setChange(change);
657 Change const & Paragraph::lookupChange(pos_type pos) const
659 LBUFERR(pos >= 0 && pos <= size());
660 return d->changes_.lookup(pos);
664 void Paragraph::acceptChanges(pos_type start, pos_type end)
666 LASSERT(start >= 0 && start <= size(), return);
667 LASSERT(end > start && end <= size() + 1, return);
669 for (pos_type pos = start; pos < end; ++pos) {
670 switch (lookupChange(pos).type) {
671 case Change::UNCHANGED:
672 // accept changes in nested inset
673 if (Inset * inset = getInset(pos))
674 inset->acceptChanges();
677 case Change::INSERTED:
678 d->changes_.set(Change(Change::UNCHANGED), pos);
679 // also accept changes in nested inset
680 if (Inset * inset = getInset(pos))
681 inset->acceptChanges();
684 case Change::DELETED:
685 // Suppress access to non-existent
686 // "end-of-paragraph char"
688 eraseChar(pos, false);
699 void Paragraph::rejectChanges(pos_type start, pos_type end)
701 LASSERT(start >= 0 && start <= size(), return);
702 LASSERT(end > start && end <= size() + 1, return);
704 for (pos_type pos = start; pos < end; ++pos) {
705 switch (lookupChange(pos).type) {
706 case Change::UNCHANGED:
707 // reject changes in nested inset
708 if (Inset * inset = getInset(pos))
709 inset->rejectChanges();
712 case Change::INSERTED:
713 // Suppress access to non-existent
714 // "end-of-paragraph char"
716 eraseChar(pos, false);
722 case Change::DELETED:
723 d->changes_.set(Change(Change::UNCHANGED), pos);
725 // Do NOT reject changes within a deleted inset!
726 // There may be insertions of a co-author inside of it!
734 void Paragraph::Private::insertChar(pos_type pos, char_type c,
735 Change const & change)
737 LASSERT(pos >= 0 && pos <= int(text_.size()), return);
740 changes_.insert(change, pos);
742 // This is actually very common when parsing buffers (and
743 // maybe inserting ascii text)
744 if (pos == pos_type(text_.size())) {
745 // when appending characters, no need to update tables
747 // but we want spell checking
748 requestSpellCheck(pos);
752 text_.insert(text_.begin() + pos, c);
754 // Update the font table.
755 fontlist_.increasePosAfterPos(pos);
758 insetlist_.increasePosAfterPos(pos);
760 // Update list of misspelled positions
761 speller_state_.increasePosAfterPos(pos);
765 bool Paragraph::insertInset(pos_type pos, Inset * inset,
766 Font const & font, Change const & change)
768 LASSERT(inset, return false);
769 LASSERT(pos >= 0 && pos <= size(), return false);
771 // Paragraph::insertInset() can be used in cut/copy/paste operation where
772 // d->inset_owner_ is not set yet.
773 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
776 d->insertChar(pos, META_INSET, change);
777 LASSERT(d->text_[pos] == META_INSET, return false);
779 // Add a new entry in the insetlist_.
780 d->insetlist_.insert(inset, pos);
782 // Some insets require run of spell checker
783 requestSpellCheck(pos);
789 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
791 LASSERT(pos >= 0 && pos <= size(), return false);
793 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
796 Change change = d->changes_.lookup(pos);
798 // set the character to DELETED if
799 // a) it was previously unchanged or
800 // b) it was inserted by a co-author
802 if (!change.changed() ||
803 (change.inserted() && !change.currentAuthor())) {
804 setChange(pos, Change(Change::DELETED));
805 // request run of spell checker
806 requestSpellCheck(pos);
810 if (change.deleted())
814 // Don't physically access the imaginary end-of-paragraph character.
815 // eraseChar() can only mark it as DELETED. A physical deletion of
816 // end-of-par must be handled externally.
822 d->changes_.erase(pos);
824 // if it is an inset, delete the inset entry
825 if (d->text_[pos] == META_INSET)
826 d->insetlist_.erase(pos);
828 d->text_.erase(d->text_.begin() + pos);
830 // Update the fontlist_
831 d->fontlist_.erase(pos);
833 // Update the insetlist_
834 d->insetlist_.decreasePosAfterPos(pos);
836 // Update list of misspelled positions
837 d->speller_state_.decreasePosAfterPos(pos);
838 d->speller_state_.refreshLast(size());
844 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
846 LASSERT(start >= 0 && start <= size(), return 0);
847 LASSERT(end >= start && end <= size() + 1, return 0);
850 for (pos_type count = end - start; count; --count) {
851 if (!eraseChar(i, trackChanges))
858 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
859 char_type next, OutputParams const & runparams)
861 // Writing next here may circumvent a possible font change between
862 // c and next. Since next is only output if it forms a surrogate pair
863 // with c we can ignore this:
864 // A font change inside a surrogate pair does not make sense and is
865 // hopefully impossible to input.
866 // FIXME: change tracking
867 // Is this correct WRT change tracking?
868 Encoding const & encoding = *(runparams.encoding);
869 docstring latex1 = encoding.latexChar(next).first;
870 if (runparams.inIPA) {
871 string const tipashortcut = Encodings::TIPAShortcut(next);
872 if (!tipashortcut.empty()) {
873 latex1 = from_ascii(tipashortcut);
876 docstring const latex2 = encoding.latexChar(c).first;
877 if (docstring(1, next) == latex1) {
878 // the encoding supports the combination
879 os << latex2 << latex1;
880 return latex1.length() + latex2.length();
881 } else if (runparams.local_font &&
882 runparams.local_font->language()->lang() == "polutonikogreek") {
883 // polutonikogreek only works without the brackets
884 os << latex1 << latex2;
885 return latex1.length() + latex2.length();
887 os << latex1 << '{' << latex2 << '}';
888 return latex1.length() + latex2.length() + 2;
892 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
895 unsigned int & column,
897 Layout const & style)
899 if (style.pass_thru || runparams.pass_thru)
902 if (i + 1 < int(text_.size())) {
903 char_type next = text_[i + 1];
904 if (Encodings::isCombiningChar(next)) {
905 // This space has an accent, so we must always output it.
906 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
911 if (runparams.linelen > 0
912 && column > runparams.linelen
914 && text_[i - 1] != ' '
915 && (i + 1 < int(text_.size()))
916 // same in FreeSpacing mode
917 && !owner_->isFreeSpacing()
918 // In typewriter mode, we want to avoid
919 // ! . ? : at the end of a line
920 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
921 && (text_[i - 1] == '.'
922 || text_[i - 1] == '?'
923 || text_[i - 1] == ':'
924 || text_[i - 1] == '!'))) {
926 os.texrow().start(owner_->id(), i + 1);
928 } else if (style.free_spacing) {
937 int Paragraph::Private::writeScriptChars(otexstream & os,
938 docstring const & ltx,
939 Change const & runningChange,
940 Encoding const & encoding,
943 // FIXME: modifying i here is not very nice...
945 // We only arrive here when character text_[i] could not be translated
946 // into the current latex encoding (or its latex translation has been forced,)
947 // and it belongs to a known script.
948 // TODO: We need \textcyr and \textgreek wrappers also for characters
949 // that can be encoded in the "LaTeX encoding" but not in the
950 // current *font encoding*.
951 // (See #9681 for details and test)
952 // Parameter ltx contains the latex translation of text_[i] as specified
953 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
954 // The latex macro name "textXXX" specifies the script to which text_[i]
955 // belongs and we use it in order to check whether characters from the
956 // same script immediately follow, such that we can collect them in a
957 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
958 // for the first char but only "<spec>" for all subsequent chars.
959 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
960 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
961 string script = to_ascii(ltx.substr(1, brace1 - 1));
964 bool closing_brace = true;
965 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
966 // Correct encoding is being used, so we can avoid \textgreek.
967 // TODO: wrong test: we need to check the *font encoding*
968 // (i.e. the active language and its FontEncoding tag)
969 // instead of the LaTeX *input encoding*!
970 // See #9637 for details and test-cases.
973 closing_brace = false;
975 os << ltx.substr(pos, length);
976 int size = text_.size();
977 while (i + 1 < size) {
978 char_type const next = text_[i + 1];
979 // Stop here if next character belongs to another script
980 // or there is a change in change tracking status.
981 if (!Encodings::isKnownScriptChar(next, script) ||
982 runningChange != owner_->lookupChange(i + 1))
986 FontList::const_iterator cit = fontlist_.begin();
987 FontList::const_iterator end = fontlist_.end();
988 for (; cit != end; ++cit) {
989 if (cit->pos() >= i && !found) {
990 prev_font = cit->font();
993 if (cit->pos() >= i + 1)
996 // Stop here if there is a font attribute or encoding change.
997 if (found && cit != end && prev_font != cit->font())
999 docstring const latex = encoding.latexChar(next).first;
1000 docstring::size_type const b1 =
1001 latex.find_first_of(from_ascii("{"));
1002 docstring::size_type const b2 =
1003 latex.find_last_of(from_ascii("}"));
1004 int const len = b2 - b1 - 1;
1005 os << latex.substr(b1 + 1, len);
1009 if (closing_brace) {
1017 void Paragraph::Private::latexInset(BufferParams const & bparams,
1019 OutputParams & runparams,
1020 Font & running_font,
1022 Font const & outerfont,
1024 Change & running_change,
1025 Layout const & style,
1027 unsigned int & column)
1029 Inset * inset = owner_->getInset(i);
1032 if (style.pass_thru) {
1033 odocstringstream ods;
1034 inset->plaintext(ods, runparams);
1039 // FIXME: move this to InsetNewline::latex
1040 if (inset->lyxCode() == NEWLINE_CODE || inset->lyxCode() == SEPARATOR_CODE) {
1041 // newlines are handled differently here than
1042 // the default in simpleTeXSpecialChars().
1043 if (!style.newline_allowed) {
1047 column += running_font.latexWriteEndChanges(
1048 os, bparams, runparams,
1049 basefont, basefont);
1053 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1056 basefont = owner_->getLayoutFont(bparams, outerfont);
1057 running_font = basefont;
1059 if (runparams.moving_arg)
1063 os.texrow().start(owner_->id(), i + 1);
1067 if (owner_->isDeleted(i)) {
1068 if( ++runparams.inDeletedInset == 1)
1069 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1072 if (inset->canTrackChanges()) {
1073 column += Changes::latexMarkChange(os, bparams, running_change,
1074 Change(Change::UNCHANGED), runparams);
1075 running_change = Change(Change::UNCHANGED);
1079 odocstream::pos_type const len = os.os().tellp();
1081 if (inset->forceLTR()
1082 && !runparams.use_polyglossia
1083 && running_font.isRightToLeft()
1084 // ERT is an exception, it should be output with no
1085 // decorations at all
1086 && inset->lyxCode() != ERT_CODE) {
1087 if (running_font.language()->lang() == "farsi")
1088 os << "\\beginL" << termcmd;
1094 // FIXME: Bug: we can have an empty font change here!
1095 // if there has just been a font change, we are going to close it
1096 // right now, which means stupid latex code like \textsf{}. AFAIK,
1097 // this does not harm dvi output. A minor bug, thus (JMarc)
1099 // Some insets cannot be inside a font change command.
1100 // However, even such insets *can* be placed in \L or \R
1101 // or their equivalents (for RTL language switches), so we don't
1102 // close the language in those cases.
1103 // ArabTeX, though, cannot handle this special behavior, it seems.
1104 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1105 || running_font.language()->lang() == "arabic_arabtex";
1106 if (open_font && !inset->inheritFont()) {
1107 bool closeLanguage = arabtex
1108 || basefont.isRightToLeft() == running_font.isRightToLeft();
1109 unsigned int count = running_font.latexWriteEndChanges(os,
1110 bparams, runparams, basefont, basefont, closeLanguage);
1112 // if any font properties were closed, update the running_font,
1113 // making sure, however, to leave the language as it was
1115 // FIXME: probably a better way to keep track of the old
1116 // language, than copying the entire font?
1117 Font const copy_font(running_font);
1118 basefont = owner_->getLayoutFont(bparams, outerfont);
1119 running_font = basefont;
1121 running_font.setLanguage(copy_font.language());
1122 // leave font open if language is still open
1123 open_font = (running_font.language() == basefont.language());
1125 runparams.local_font = &basefont;
1129 size_t const previous_row_count = os.texrow().rows();
1132 runparams.lastid = id_;
1133 runparams.lastpos = i;
1134 inset->latex(os, runparams);
1135 } catch (EncodingException & e) {
1136 // add location information and throw again.
1143 if (running_font.language()->lang() == "farsi")
1144 os << "\\endL" << termcmd;
1149 if (os.texrow().rows() > previous_row_count) {
1150 os.texrow().start(owner_->id(), i + 1);
1153 column += (unsigned int)(os.os().tellp() - len);
1156 if (owner_->isDeleted(i))
1157 --runparams.inDeletedInset;
1161 void Paragraph::Private::latexSpecialChar(otexstream & os,
1162 BufferParams const & bparams,
1163 OutputParams const & runparams,
1164 Font const & running_font,
1165 Change const & running_change,
1166 Layout const & style,
1169 unsigned int & column)
1171 // With polyglossia, brackets and stuff need not be reversed
1172 // in RTL scripts (see bug #8251)
1173 char_type const c = (runparams.use_polyglossia) ?
1174 owner_->getUChar(bparams, i) : text_[i];
1176 if (style.pass_thru || runparams.pass_thru
1177 || contains(style.pass_thru_chars, c)
1178 || contains(runparams.pass_thru_chars, c)) {
1180 Encoding const * const enc = runparams.encoding;
1181 if (enc && !enc->encodable(c))
1182 throw EncodingException(c);
1188 // TIPA uses its own T3 encoding
1189 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1191 // If T1 font encoding is used, use the special
1192 // characters it provides.
1193 // NOTE: Some languages reset the font encoding internally to a
1194 // non-standard font encoding. If we are using such a language,
1195 // we do not output special T1 chars.
1196 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1197 && !runparams.isFullUnicode() && bparams.main_font_encoding() == "T1"
1198 && latexSpecialT1(c, os, i, column))
1200 // NOTE: XeTeX and LuaTeX use EU1/2 (pre 2017) or TU (as of 2017) encoding
1201 else if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1202 && runparams.isFullUnicode() && latexSpecialTU(c, os, i, column))
1205 // Otherwise, we use what LaTeX provides us.
1208 os << "\\textbackslash" << termcmd;
1212 os << "\\textless" << termcmd;
1216 os << "\\textgreater" << termcmd;
1220 os << "\\textbar" << termcmd;
1225 if (i + 1 < static_cast<pos_type>(text_.size()) &&
1226 (end_pos == -1 || i + 1 < end_pos) &&
1227 text_[i+1] == '-') {
1228 // Prevent "--" becoming an endash and "---" becoming
1230 // Within \ttfamily, "--" is merged to "-" (no endash)
1231 // so we avoid this rather irritating ligature as well
1237 os << "\\char34" << termcmd;
1242 case '%': case '#': case '{':
1250 os << "\\textasciitilde" << termcmd;
1255 os << "\\textasciicircum" << termcmd;
1262 // avoid being mistaken for optional arguments
1270 // Blanks are printed before font switching.
1271 // Sure? I am not! (try nice-latex)
1272 // I am sure it's correct. LyX might be smarter
1273 // in the future, but for now, nothing wrong is
1279 if (bparams.use_dash_ligatures && !bparams.useNonTeXFonts) {
1296 Encoding const & encoding = *(runparams.encoding);
1297 char_type next = '\0';
1298 if (i + 1 < int(text_.size())) {
1299 next = text_[i + 1];
1300 if (Encodings::isCombiningChar(next)) {
1301 column += latexSurrogatePair(os, c, next, runparams) - 1;
1307 pair<docstring, bool> latex = encoding.latexChar(c);
1308 docstring nextlatex;
1309 bool nexttipas = false;
1310 string nexttipashortcut;
1311 if (next != '\0' && next != META_INSET && encoding.encodable(next)) {
1312 nextlatex = encoding.latexChar(next).first;
1313 if (runparams.inIPA) {
1314 nexttipashortcut = Encodings::TIPAShortcut(next);
1315 nexttipas = !nexttipashortcut.empty();
1319 if (runparams.inIPA) {
1320 string const tipashortcut = Encodings::TIPAShortcut(c);
1321 if (!tipashortcut.empty()) {
1322 latex.first = from_ascii(tipashortcut);
1323 latex.second = false;
1327 if (Encodings::isKnownScriptChar(c, script)
1328 && prefixIs(latex.first, from_ascii("\\" + script)))
1329 column += writeScriptChars(os, latex.first,
1330 running_change, encoding, i) - 1;
1331 else if (latex.second
1332 && ((!prefixIs(nextlatex, '\\')
1333 && !prefixIs(nextlatex, '{')
1334 && !prefixIs(nextlatex, '}'))
1336 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1338 // Prevent eating of a following
1339 // space or command corruption by
1340 // following characters
1341 if (next == ' ' || next == '\0') {
1342 column += latex.first.length() + 1;
1343 os << latex.first << "{}";
1345 column += latex.first.length();
1346 os << latex.first << " ";
1349 column += latex.first.length() - 1;
1357 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1358 pos_type i, unsigned int & column)
1364 // In T1 encoding, these characters exist
1365 // but we should avoid ligatures
1366 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1368 os << "\\textcompwordmark" << termcmd;
1375 // soul.sty breaks with \char`\"
1376 os << "\\textquotedbl" << termcmd;
1385 bool Paragraph::Private::latexSpecialTU(char_type const c, otexstream & os,
1386 pos_type i, unsigned int & column)
1388 // TU encoding is currently on par with T1.
1389 return latexSpecialT1(c, os, i, column);
1393 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1394 pos_type /*i*/, unsigned int & column)
1404 os << "\\textvertline" << termcmd;
1413 void Paragraph::Private::validate(LaTeXFeatures & features) const
1415 if (layout_->inpreamble && inset_owner_) {
1416 bool const is_command = layout_->latextype == LATEX_COMMAND;
1417 Buffer const & buf = inset_owner_->buffer();
1418 BufferParams const & bp = features.runparams().is_child
1419 ? buf.masterParams() : buf.params();
1421 // Using a string stream here circumvents the encoding
1422 // switching machinery of odocstream. Therefore the
1423 // output is wrong if this paragraph contains content
1424 // that needs to switch encoding.
1425 otexstringstream os;
1426 os << layout_->preamble();
1428 os << '\\' << from_ascii(layout_->latexname());
1429 // we have to provide all the optional arguments here, even though
1430 // the last one is the only one we care about.
1431 // Separate handling of optional argument inset.
1432 if (!layout_->latexargs().empty()) {
1433 OutputParams rp = features.runparams();
1434 rp.local_font = &owner_->getFirstFontSettings(bp);
1435 latexArgInsets(*owner_, os, rp, layout_->latexargs());
1437 os << from_ascii(layout_->latexparam());
1439 size_t const length = os.length();
1440 // this will output "{" at the beginning, but not at the end
1441 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1442 if (os.length() > length) {
1445 if (!layout_->postcommandargs().empty()) {
1446 OutputParams rp = features.runparams();
1447 rp.local_font = &owner_->getFirstFontSettings(bp);
1448 latexArgInsets(*owner_, os, rp, layout_->postcommandargs(), "post:");
1451 features.addPreambleSnippet(os.release(), true);
1455 if (features.runparams().flavor == OutputParams::HTML
1456 && layout_->htmltitle()) {
1457 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1460 // check the params.
1461 if (!params_.spacing().isDefault())
1462 features.require("setspace");
1465 features.useLayout(layout_->name());
1468 fontlist_.validate(features);
1470 // then the indentation
1471 if (!params_.leftIndent().zero())
1472 features.require("ParagraphLeftIndent");
1475 InsetList::const_iterator icit = insetlist_.begin();
1476 InsetList::const_iterator iend = insetlist_.end();
1477 for (; icit != iend; ++icit) {
1479 features.inDeletedInset(owner_->isDeleted(icit->pos));
1480 icit->inset->validate(features);
1481 features.inDeletedInset(false);
1482 if (layout_->needprotect &&
1483 icit->inset->lyxCode() == FOOT_CODE)
1484 features.require("NeedLyXFootnoteCode");
1488 // then the contents
1489 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1490 BufferEncodings::validate(text_[i], features);
1494 /////////////////////////////////////////////////////////////////////
1498 /////////////////////////////////////////////////////////////////////
1501 Layout const emptyParagraphLayout;
1504 Paragraph::Paragraph()
1505 : d(new Paragraph::Private(this, emptyParagraphLayout))
1512 Paragraph::Paragraph(Paragraph const & par)
1513 : itemdepth(par.itemdepth),
1514 d(new Paragraph::Private(*par.d, this))
1520 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1521 : itemdepth(par.itemdepth),
1522 d(new Paragraph::Private(*par.d, this, beg, end))
1528 Paragraph & Paragraph::operator=(Paragraph const & par)
1530 // needed as we will destroy the private part before copying it
1532 itemdepth = par.itemdepth;
1536 d = new Private(*par.d, this);
1543 Paragraph::~Paragraph()
1552 // this shall be called just before every "os << ..." action.
1553 void flushString(ostream & os, docstring & s)
1562 void Paragraph::write(ostream & os, BufferParams const & bparams,
1563 depth_type & dth) const
1565 // The beginning or end of a deeper (i.e. nested) area?
1566 if (dth != d->params_.depth()) {
1567 if (d->params_.depth() > dth) {
1568 while (d->params_.depth() > dth) {
1569 os << "\n\\begin_deeper";
1573 while (d->params_.depth() < dth) {
1574 os << "\n\\end_deeper";
1580 // First write the layout
1581 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1583 d->params_.write(os);
1585 Font font1(inherit_font, bparams.language);
1587 Change running_change = Change(Change::UNCHANGED);
1589 // this string is used as a buffer to avoid repetitive calls
1590 // to to_utf8(), which turn out to be expensive (JMarc)
1591 docstring write_buffer;
1594 for (pos_type i = 0; i <= size(); ++i) {
1596 Change const & change = lookupChange(i);
1597 if (change != running_change)
1598 flushString(os, write_buffer);
1599 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1600 running_change = change;
1605 // Write font changes
1606 Font font2 = getFontSettings(bparams, i);
1607 if (font2 != font1) {
1608 flushString(os, write_buffer);
1609 font2.lyxWriteChanges(font1, os);
1614 char_type const c = d->text_[i];
1617 if (Inset const * inset = getInset(i)) {
1618 flushString(os, write_buffer);
1619 if (inset->directWrite()) {
1620 // international char, let it write
1621 // code directly so it's shorter in
1627 os << "\\begin_inset ";
1629 os << "\n\\end_inset\n\n";
1632 // FIXME This can be removed again once the mystery
1633 // crash has been resolved.
1638 flushString(os, write_buffer);
1639 os << "\n\\backslash\n";
1643 flushString(os, write_buffer);
1644 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1651 if ((column > 70 && c == ' ')
1653 flushString(os, write_buffer);
1657 // this check is to amend a bug. LyX sometimes
1658 // inserts '\0' this could cause problems.
1660 write_buffer.push_back(c);
1662 LYXERR0("NUL char in structure.");
1668 flushString(os, write_buffer);
1669 os << "\n\\end_layout\n";
1670 // FIXME This can be removed again once the mystery
1671 // crash has been resolved.
1676 void Paragraph::validate(LaTeXFeatures & features) const
1678 d->validate(features);
1682 void Paragraph::insert(pos_type start, docstring const & str,
1683 Font const & font, Change const & change)
1685 for (size_t i = 0, n = str.size(); i != n ; ++i)
1686 insertChar(start + i, str[i], font, change);
1690 void Paragraph::appendChar(char_type c, Font const & font,
1691 Change const & change)
1694 d->changes_.insert(change, d->text_.size());
1695 // when appending characters, no need to update tables
1696 d->text_.push_back(c);
1697 setFont(d->text_.size() - 1, font);
1698 d->requestSpellCheck(d->text_.size() - 1);
1702 void Paragraph::appendString(docstring const & s, Font const & font,
1703 Change const & change)
1705 pos_type end = s.size();
1706 size_t oldsize = d->text_.size();
1707 size_t newsize = oldsize + end;
1708 size_t capacity = d->text_.capacity();
1709 if (newsize >= capacity)
1710 d->text_.reserve(max(capacity + 100, newsize));
1712 // when appending characters, no need to update tables
1715 // FIXME: Optimize this!
1716 for (size_t i = oldsize; i != newsize; ++i) {
1718 d->changes_.insert(change, i);
1719 d->requestSpellCheck(i);
1721 d->fontlist_.set(oldsize, font);
1722 d->fontlist_.set(newsize - 1, font);
1726 void Paragraph::insertChar(pos_type pos, char_type c,
1729 d->insertChar(pos, c, Change(trackChanges ?
1730 Change::INSERTED : Change::UNCHANGED));
1734 void Paragraph::insertChar(pos_type pos, char_type c,
1735 Font const & font, bool trackChanges)
1737 d->insertChar(pos, c, Change(trackChanges ?
1738 Change::INSERTED : Change::UNCHANGED));
1743 void Paragraph::insertChar(pos_type pos, char_type c,
1744 Font const & font, Change const & change)
1746 d->insertChar(pos, c, change);
1751 void Paragraph::resetFonts(Font const & font)
1753 d->fontlist_.clear();
1754 d->fontlist_.set(0, font);
1755 d->fontlist_.set(d->text_.size() - 1, font);
1758 // Gets uninstantiated font setting at position.
1759 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1763 LYXERR0("pos: " << pos << " size: " << size());
1767 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1768 if (cit != d->fontlist_.end())
1771 if (pos == size() && !empty())
1772 return getFontSettings(bparams, pos - 1);
1774 // Optimisation: avoid a full font instantiation if there is no
1775 // language change from previous call.
1776 static Font previous_font;
1777 static Language const * previous_lang = 0;
1778 Language const * lang = getParLanguage(bparams);
1779 if (lang != previous_lang) {
1780 previous_lang = lang;
1781 previous_font = Font(inherit_font, lang);
1783 return previous_font;
1787 FontSpan Paragraph::fontSpan(pos_type pos) const
1789 LBUFERR(pos <= size());
1792 return FontSpan(pos, pos);
1795 FontList::const_iterator cit = d->fontlist_.begin();
1796 FontList::const_iterator end = d->fontlist_.end();
1797 for (; cit != end; ++cit) {
1798 if (cit->pos() >= pos) {
1799 if (pos >= beginOfBody())
1800 return FontSpan(max(start, beginOfBody()),
1803 return FontSpan(start,
1804 min(beginOfBody() - 1,
1807 start = cit->pos() + 1;
1810 // This should not happen, but if so, we take no chances.
1811 LYXERR0("Paragraph::fontSpan: position not found in fontinfo table!");
1812 LASSERT(false, return FontSpan(pos, pos));
1816 // Gets uninstantiated font setting at position 0
1817 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1819 if (!empty() && !d->fontlist_.empty())
1820 return d->fontlist_.begin()->font();
1822 // Optimisation: avoid a full font instantiation if there is no
1823 // language change from previous call.
1824 static Font previous_font;
1825 static Language const * previous_lang = 0;
1826 if (bparams.language != previous_lang) {
1827 previous_lang = bparams.language;
1828 previous_font = Font(inherit_font, bparams.language);
1831 return previous_font;
1835 // Gets the fully instantiated font at a given position in a paragraph
1836 // This is basically the same function as Text::GetFont() in text2.cpp.
1837 // The difference is that this one is used for generating the LaTeX file,
1838 // and thus cosmetic "improvements" are disallowed: This has to deliver
1839 // the true picture of the buffer. (Asger)
1840 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1841 Font const & outerfont) const
1845 Font font = getFontSettings(bparams, pos);
1847 pos_type const body_pos = beginOfBody();
1848 FontInfo & fi = font.fontInfo();
1850 fi.realize(d->layout_->labelfont);
1852 fi.realize(d->layout_->font);
1854 fi.realize(outerfont.fontInfo());
1855 fi.realize(bparams.getFont().fontInfo());
1861 Font const Paragraph::getLabelFont
1862 (BufferParams const & bparams, Font const & outerfont) const
1864 FontInfo tmpfont = d->layout_->labelfont;
1865 tmpfont.realize(outerfont.fontInfo());
1866 tmpfont.realize(bparams.getFont().fontInfo());
1867 return Font(tmpfont, getParLanguage(bparams));
1871 Font const Paragraph::getLayoutFont
1872 (BufferParams const & bparams, Font const & outerfont) const
1874 FontInfo tmpfont = d->layout_->font;
1875 tmpfont.realize(outerfont.fontInfo());
1876 tmpfont.realize(bparams.getFont().fontInfo());
1877 return Font(tmpfont, getParLanguage(bparams));
1881 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1883 char_type c = d->text_[pos];
1884 if (!getFontSettings(bparams, pos).isRightToLeft())
1887 // FIXME: The arabic special casing is due to the difference of arabic
1888 // round brackets input introduced in r18599. Check if this should be
1889 // unified with Hebrew or at least if all bracket types should be
1890 // handled the same (file format change in either case).
1891 string const & lang = getFontSettings(bparams, pos).language()->lang();
1892 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1897 uc = arabic ? c : ')';
1900 uc = arabic ? c : '(';
1926 void Paragraph::setFont(pos_type pos, Font const & font)
1928 LASSERT(pos <= size(), return);
1930 // First, reduce font against layout/label font
1931 // Update: The setCharFont() routine in text2.cpp already
1932 // reduces font, so we don't need to do that here. (Asger)
1934 d->fontlist_.set(pos, font);
1938 void Paragraph::makeSameLayout(Paragraph const & par)
1940 d->layout_ = par.d->layout_;
1941 d->params_ = par.d->params_;
1945 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1947 if (isFreeSpacing())
1953 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1954 if (eraseChar(pos, trackChanges))
1960 return count > 0 || pos > 0;
1964 bool Paragraph::hasSameLayout(Paragraph const & par) const
1966 return par.d->layout_ == d->layout_
1967 && d->params_.sameLayout(par.d->params_);
1971 depth_type Paragraph::getDepth() const
1973 return d->params_.depth();
1977 depth_type Paragraph::getMaxDepthAfter() const
1979 if (d->layout_->isEnvironment())
1980 return d->params_.depth() + 1;
1982 return d->params_.depth();
1986 LyXAlignment Paragraph::getAlign() const
1988 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1989 return d->layout_->align;
1991 return d->params_.align();
1995 docstring const & Paragraph::labelString() const
1997 return d->params_.labelString();
2001 // the next two functions are for the manual labels
2002 docstring const Paragraph::getLabelWidthString() const
2004 if (d->layout_->margintype == MARGIN_MANUAL
2005 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2006 return d->params_.labelWidthString();
2008 return _("Senseless with this layout!");
2012 void Paragraph::setLabelWidthString(docstring const & s)
2014 d->params_.labelWidthString(s);
2018 docstring Paragraph::expandLabel(Layout const & layout,
2019 BufferParams const & bparams) const
2021 return expandParagraphLabel(layout, bparams, true);
2025 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2026 BufferParams const & bparams) const
2028 return expandParagraphLabel(layout, bparams, false);
2032 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2033 BufferParams const & bparams, bool process_appendix) const
2035 DocumentClass const & tclass = bparams.documentClass();
2036 string const & lang = getParLanguage(bparams)->code();
2037 bool const in_appendix = process_appendix && d->params_.appendix();
2038 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2040 if (fmt.empty() && !layout.counter.empty())
2041 return tclass.counters().theCounter(layout.counter, lang);
2043 // handle 'inherited level parts' in 'fmt',
2044 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2045 size_t const i = fmt.find('@', 0);
2046 if (i != docstring::npos) {
2047 size_t const j = fmt.find('@', i + 1);
2048 if (j != docstring::npos) {
2049 docstring parent(fmt, i + 1, j - i - 1);
2050 docstring label = from_ascii("??");
2051 if (tclass.hasLayout(parent))
2052 label = expandParagraphLabel(tclass[parent], bparams,
2054 fmt = docstring(fmt, 0, i) + label
2055 + docstring(fmt, j + 1, docstring::npos);
2059 return tclass.counters().counterLabel(fmt, lang);
2063 void Paragraph::applyLayout(Layout const & new_layout)
2065 d->layout_ = &new_layout;
2066 LyXAlignment const oldAlign = d->params_.align();
2068 if (!(oldAlign & d->layout_->alignpossible)) {
2069 frontend::Alert::warning(_("Alignment not permitted"),
2070 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2071 d->params_.align(LYX_ALIGN_LAYOUT);
2076 pos_type Paragraph::beginOfBody() const
2078 return d->begin_of_body_;
2082 void Paragraph::setBeginOfBody()
2084 if (d->layout_->labeltype != LABEL_MANUAL) {
2085 d->begin_of_body_ = 0;
2089 // Unroll the first two cycles of the loop
2090 // and remember the previous character to
2091 // remove unnecessary getChar() calls
2093 pos_type end = size();
2094 if (i < end && !(isNewline(i) || isEnvSeparator(i))) {
2097 char_type previous_char = d->text_[i];
2098 if (!(isNewline(i) || isEnvSeparator(i))) {
2100 while (i < end && previous_char != ' ') {
2101 char_type temp = d->text_[i];
2102 if (isNewline(i) || isEnvSeparator(i))
2105 previous_char = temp;
2111 d->begin_of_body_ = i;
2115 bool Paragraph::allowParagraphCustomization() const
2117 return inInset().allowParagraphCustomization();
2121 bool Paragraph::usePlainLayout() const
2123 return inInset().usePlainLayout();
2127 bool Paragraph::isPassThru() const
2129 return inInset().isPassThru() || d->layout_->pass_thru;
2134 // paragraphs inside floats need different alignment tags to avoid
2137 bool noTrivlistCentering(InsetCode code)
2139 return code == FLOAT_CODE
2140 || code == WRAP_CODE
2141 || code == CELL_CODE;
2145 string correction(string const & orig)
2147 if (orig == "flushleft")
2148 return "raggedright";
2149 if (orig == "flushright")
2150 return "raggedleft";
2151 if (orig == "center")
2157 bool corrected_env(otexstream & os, string const & suffix, string const & env,
2158 InsetCode code, bool const lastpar, int & col)
2160 string macro = suffix + "{";
2161 if (noTrivlistCentering(code)) {
2163 // the last paragraph in non-trivlist-aligned
2164 // context is special (to avoid unwanted whitespace)
2165 if (suffix == "\\begin") {
2166 macro = "\\" + correction(env) + "{}";
2167 os << from_ascii(macro);
2168 col += macro.size();
2173 macro += correction(env);
2177 if (suffix == "\\par\\end") {
2181 os << from_ascii(macro);
2182 col += macro.size();
2183 if (suffix == "\\begin") {
2193 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2194 otexstream & os, OutputParams const & runparams) const
2199 (bparams.paragraph_separation == BufferParams::ParagraphIndentSeparation) ?
2200 (layout_->toggle_indent != ITOGGLE_NEVER) :
2201 (layout_->toggle_indent == ITOGGLE_ALWAYS);
2203 if (canindent && params_.noindent() && !layout_->pass_thru) {
2204 os << "\\noindent ";
2208 LyXAlignment const curAlign = params_.align();
2210 if (curAlign == layout_->align)
2214 case LYX_ALIGN_NONE:
2215 case LYX_ALIGN_BLOCK:
2216 case LYX_ALIGN_LAYOUT:
2217 case LYX_ALIGN_SPECIAL:
2218 case LYX_ALIGN_DECIMAL:
2220 case LYX_ALIGN_LEFT:
2221 case LYX_ALIGN_RIGHT:
2222 case LYX_ALIGN_CENTER:
2223 if (runparams.moving_arg) {
2230 string const begin_tag = "\\begin";
2231 InsetCode code = ownerCode();
2232 bool const lastpar = runparams.isLastPar;
2235 case LYX_ALIGN_NONE:
2236 case LYX_ALIGN_BLOCK:
2237 case LYX_ALIGN_LAYOUT:
2238 case LYX_ALIGN_SPECIAL:
2239 case LYX_ALIGN_DECIMAL:
2241 case LYX_ALIGN_LEFT: {
2242 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2243 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2245 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2247 } case LYX_ALIGN_RIGHT: {
2248 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2249 corrected_env(os, begin_tag, "flushright", code, lastpar, column);
2251 corrected_env(os, begin_tag, "flushleft", code, lastpar, column);
2253 } case LYX_ALIGN_CENTER: {
2254 corrected_env(os, begin_tag, "center", code, lastpar, column);
2263 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2264 otexstream & os, OutputParams const & runparams) const
2266 LyXAlignment const curAlign = params_.align();
2268 if (curAlign == layout_->align)
2272 case LYX_ALIGN_NONE:
2273 case LYX_ALIGN_BLOCK:
2274 case LYX_ALIGN_LAYOUT:
2275 case LYX_ALIGN_SPECIAL:
2276 case LYX_ALIGN_DECIMAL:
2278 case LYX_ALIGN_LEFT:
2279 case LYX_ALIGN_RIGHT:
2280 case LYX_ALIGN_CENTER:
2281 if (runparams.moving_arg)
2286 bool output = false;
2288 string const end_tag = "\\par\\end";
2289 InsetCode code = ownerCode();
2290 bool const lastpar = runparams.isLastPar;
2293 case LYX_ALIGN_NONE:
2294 case LYX_ALIGN_BLOCK:
2295 case LYX_ALIGN_LAYOUT:
2296 case LYX_ALIGN_SPECIAL:
2297 case LYX_ALIGN_DECIMAL:
2299 case LYX_ALIGN_LEFT: {
2300 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2301 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2303 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2305 } case LYX_ALIGN_RIGHT: {
2306 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2307 output = corrected_env(os, end_tag, "flushright", code, lastpar, col);
2309 output = corrected_env(os, end_tag, "flushleft", code, lastpar, col);
2311 } case LYX_ALIGN_CENTER: {
2312 corrected_env(os, end_tag, "center", code, lastpar, col);
2317 return output || lastpar;
2321 // This one spits out the text of the paragraph
2322 void Paragraph::latex(BufferParams const & bparams,
2323 Font const & outerfont,
2325 OutputParams const & runparams,
2326 int start_pos, int end_pos, bool force) const
2328 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2330 // FIXME This check should not be needed. Perhaps issue an
2331 // error if it triggers.
2332 Layout const & style = inInset().forcePlainLayout() ?
2333 bparams.documentClass().plainLayout() : *d->layout_;
2335 if (!force && style.inpreamble)
2338 bool const allowcust = allowParagraphCustomization();
2340 // Current base font for all inherited font changes, without any
2341 // change caused by an individual character, except for the language:
2342 // It is set to the language of the first character.
2343 // As long as we are in the label, this font is the base font of the
2344 // label. Before the first body character it is set to the base font
2348 // Maybe we have to create a optional argument.
2349 pos_type body_pos = beginOfBody();
2350 unsigned int column = 0;
2353 // the optional argument is kept in curly brackets in
2354 // case it contains a ']'
2355 // This is not strictly needed, but if this is changed it
2356 // would be a file format change, and tex2lyx would need
2357 // to be adjusted, since it unconditionally removes the
2358 // braces when it parses \item.
2361 basefont = getLabelFont(bparams, outerfont);
2363 basefont = getLayoutFont(bparams, outerfont);
2366 // Which font is currently active?
2367 Font running_font(basefont);
2368 // Do we have an open font change?
2369 bool open_font = false;
2371 Change runningChange = Change(Change::UNCHANGED);
2373 Encoding const * const prev_encoding = runparams.encoding;
2375 os.texrow().start(id(), 0);
2377 // if the paragraph is empty, the loop will not be entered at all
2379 if (style.isCommand()) {
2383 if (!style.leftdelim().empty()) {
2384 os << style.leftdelim();
2385 column += style.leftdelim().size();
2388 column += d->startTeXParParams(bparams, os, runparams);
2391 for (pos_type i = 0; i < size(); ++i) {
2392 // First char in paragraph or after label?
2393 if (i == body_pos) {
2396 column += running_font.latexWriteEndChanges(
2397 os, bparams, runparams,
2398 basefont, basefont);
2401 basefont = getLayoutFont(bparams, outerfont);
2402 running_font = basefont;
2404 column += Changes::latexMarkChange(os, bparams,
2405 runningChange, Change(Change::UNCHANGED),
2407 runningChange = Change(Change::UNCHANGED);
2412 if (style.isCommand()) {
2417 if (!style.leftdelim().empty()) {
2418 os << style.leftdelim();
2419 column += style.leftdelim().size();
2423 column += d->startTeXParParams(bparams, os,
2427 runparams.wasDisplayMath = runparams.inDisplayMath;
2428 runparams.inDisplayMath = false;
2429 bool deleted_display_math = false;
2431 // Check whether a display math inset follows
2432 if (d->text_[i] == META_INSET
2433 && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2434 InsetMath const * im = getInset(i)->asInsetMath();
2435 if (im && im->asHullInset()
2436 && im->asHullInset()->outerDisplay()) {
2437 runparams.inDisplayMath = true;
2438 // runparams.inDeletedInset will be set by
2439 // latexInset later, but we need this info
2440 // before it is called. On the other hand, we
2441 // cannot set it here because it is a counter.
2442 deleted_display_math = isDeleted(i);
2446 Change const & change = runparams.inDeletedInset
2447 ? runparams.changeOfDeletedInset : lookupChange(i);
2449 if (bparams.output_changes && runningChange != change) {
2451 column += running_font.latexWriteEndChanges(
2452 os, bparams, runparams, basefont, basefont);
2455 basefont = getLayoutFont(bparams, outerfont);
2456 running_font = basefont;
2457 column += Changes::latexMarkChange(os, bparams, runningChange,
2459 runningChange = change;
2462 // do not output text which is marked deleted
2463 // if change tracking output is disabled
2464 if (!bparams.output_changes && change.deleted()) {
2470 // Fully instantiated font
2471 Font const current_font = getFont(bparams, i, outerfont);
2473 Font const last_font = running_font;
2475 // Do we need to close the previous font?
2477 (current_font != running_font ||
2478 current_font.language() != running_font.language()))
2480 column += running_font.latexWriteEndChanges(
2481 os, bparams, runparams, basefont,
2482 (i == body_pos-1) ? basefont : current_font);
2483 running_font = basefont;
2487 string const running_lang = runparams.use_polyglossia ?
2488 running_font.language()->polyglossia() : running_font.language()->babel();
2489 // close babel's font environment before opening CJK.
2490 string const lang_end_command = runparams.use_polyglossia ?
2491 "\\end{$$lang}" : lyxrc.language_command_end;
2492 bool const using_begin_end = runparams.use_polyglossia ||
2493 !lang_end_command.empty();
2494 if (!running_lang.empty() &&
2495 current_font.language()->encoding()->package() == Encoding::CJK) {
2496 string end_tag = subst(lang_end_command,
2499 os << from_ascii(end_tag);
2500 column += end_tag.length();
2501 if (using_begin_end)
2505 // Switch file encoding if necessary (and allowed)
2506 if (!runparams.pass_thru && !style.pass_thru &&
2507 runparams.encoding->package() != Encoding::none &&
2508 current_font.language()->encoding()->package() != Encoding::none) {
2509 pair<bool, int> const enc_switch =
2510 switchEncoding(os.os(), bparams, runparams,
2511 *(current_font.language()->encoding()));
2512 if (enc_switch.first) {
2513 column += enc_switch.second;
2514 runparams.encoding = current_font.language()->encoding();
2518 char_type const c = d->text_[i];
2520 // A display math inset inside an ulem command will be output
2521 // as a box of width \columnwidth, so we have to either disable
2522 // indentation if the inset starts a paragraph, or start a new
2523 // line to accommodate such box. This has to be done before
2524 // writing any font changing commands.
2525 if (runparams.inDisplayMath && !deleted_display_math
2526 && runparams.inulemcmd) {
2527 if (os.afterParbreak())
2533 // Do we need to change font?
2534 if ((current_font != running_font ||
2535 current_font.language() != running_font.language()) &&
2538 odocstringstream ods;
2539 column += current_font.latexWriteStartChanges(ods, bparams,
2540 runparams, basefont,
2542 // Check again for display math in ulem commands as a
2543 // font change may also occur just before a math inset.
2544 if (runparams.inDisplayMath && !deleted_display_math
2545 && runparams.inulemcmd) {
2546 if (os.afterParbreak())
2551 running_font = current_font;
2553 docstring fontchange = ods.str();
2554 // check whether the fontchange ends with a \\textcolor
2555 // modifier and the text starts with a space (bug 4473)
2556 docstring const last_modifier = rsplit(fontchange, '\\');
2557 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2558 os << fontchange << from_ascii("{}");
2559 // check if the fontchange ends with a trailing blank
2560 // (like "\small " (see bug 3382)
2561 else if (suffixIs(fontchange, ' ') && c == ' ')
2562 os << fontchange.substr(0, fontchange.size() - 1)
2563 << from_ascii("{}");
2568 // FIXME: think about end_pos implementation...
2569 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2570 // FIXME: integrate this case in latexSpecialChar
2571 // Do not print the separation of the optional argument
2572 // if style.pass_thru is false. This works because
2573 // latexSpecialChar ignores spaces if
2574 // style.pass_thru is false.
2575 if (i != body_pos - 1) {
2576 if (d->simpleTeXBlanks(runparams, os,
2577 i, column, current_font, style)) {
2578 // A surrogate pair was output. We
2579 // must not call latexSpecialChar
2580 // in this iteration, since it would output
2581 // the combining character again.
2588 OutputParams rp = runparams;
2589 rp.free_spacing = style.free_spacing;
2590 rp.local_font = ¤t_font;
2591 rp.intitle = style.intitle;
2593 // Two major modes: LaTeX or plain
2594 // Handle here those cases common to both modes
2595 // and then split to handle the two modes separately.
2596 if (c == META_INSET) {
2597 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2598 d->latexInset(bparams, os, rp, running_font,
2599 basefont, outerfont, open_font,
2600 runningChange, style, i, column);
2602 } else if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2604 d->latexSpecialChar(os, bparams, rp,
2605 running_font, runningChange,
2606 style, i, end_pos, column);
2607 } catch (EncodingException & e) {
2608 if (runparams.dryrun) {
2609 os << "<" << _("LyX Warning: ")
2610 << _("uncodable character") << " '";
2614 // add location information and throw again.
2622 // Set the encoding to that returned from latexSpecialChar (see
2623 // comment for encoding member in OutputParams.h)
2624 runparams.encoding = rp.encoding;
2626 // Also carry on the info on a closed ulem command for insets
2627 // such as Note that do not produce any output, so that no
2628 // command is ever executed but its opening was recorded.
2629 runparams.inulemcmd = rp.inulemcmd;
2632 // If we have an open font definition, we have to close it
2634 #ifdef FIXED_LANGUAGE_END_DETECTION
2636 running_font.latexWriteEndChanges(os, bparams,
2637 runparams, basefont,
2638 next_->getFont(bparams, 0, outerfont));
2640 running_font.latexWriteEndChanges(os, bparams,
2641 runparams, basefont, basefont);
2644 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2645 //FIXME: there as we start another \selectlanguage with the next paragraph if
2646 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2647 running_font.latexWriteEndChanges(os, bparams, runparams,
2648 basefont, basefont);
2652 column += Changes::latexMarkChange(os, bparams, runningChange,
2653 Change(Change::UNCHANGED), runparams);
2655 // Needed if there is an optional argument but no contents.
2656 if (body_pos > 0 && body_pos == size()) {
2660 if (!style.rightdelim().empty()) {
2661 os << style.rightdelim();
2662 column += style.rightdelim().size();
2665 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2666 && runparams.encoding != prev_encoding) {
2667 runparams.encoding = prev_encoding;
2668 os << setEncoding(prev_encoding->iconvName());
2671 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2675 bool Paragraph::emptyTag() const
2677 for (pos_type i = 0; i < size(); ++i) {
2678 if (Inset const * inset = getInset(i)) {
2679 InsetCode lyx_code = inset->lyxCode();
2680 // FIXME testing like that is wrong. What is
2682 if (lyx_code != TOC_CODE &&
2683 lyx_code != INCLUDE_CODE &&
2684 lyx_code != GRAPHICS_CODE &&
2685 lyx_code != ERT_CODE &&
2686 lyx_code != LISTINGS_CODE &&
2687 lyx_code != FLOAT_CODE &&
2688 lyx_code != TABULAR_CODE) {
2692 char_type c = d->text_[i];
2693 if (c != ' ' && c != '\t')
2701 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2704 for (pos_type i = 0; i < size(); ++i) {
2705 if (Inset const * inset = getInset(i)) {
2706 InsetCode lyx_code = inset->lyxCode();
2707 if (lyx_code == LABEL_CODE) {
2708 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2709 docstring const & id = il->getParam("name");
2710 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2718 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2722 for (i = 0; i < size(); ++i) {
2723 if (Inset const * inset = getInset(i)) {
2724 inset->docbook(os, runparams);
2726 char_type c = d->text_[i];
2729 os << sgml::escapeChar(c);
2736 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2740 for (i = 0; i < size(); ++i) {
2741 if (Inset const * inset = getInset(i)) {
2742 inset->xhtml(xs, runparams);
2744 char_type c = d->text_[i];
2754 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2757 pos_type size = text_.size();
2758 for (pos_type i = initial; i < size; ++i) {
2759 Font font = owner_->getFont(buf.params(), i, outerfont);
2760 if (text_[i] == META_INSET)
2762 if (i != initial && font != font_old)
2771 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2773 OutputParams const & runparams,
2774 Font const & outerfont,
2775 pos_type initial) const
2777 bool emph_flag = false;
2779 Layout const & style = *d->layout_;
2781 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2783 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2786 // parsing main loop
2787 for (pos_type i = initial; i < size(); ++i) {
2788 Font font = getFont(buf.params(), i, outerfont);
2790 // handle <emphasis> tag
2791 if (font_old.emph() != font.fontInfo().emph()) {
2792 if (font.fontInfo().emph() == FONT_ON) {
2795 } else if (i != initial) {
2796 os << "</emphasis>";
2801 if (Inset const * inset = getInset(i)) {
2802 inset->docbook(os, runparams);
2804 char_type c = d->text_[i];
2806 if (style.pass_thru)
2809 os << sgml::escapeChar(c);
2811 font_old = font.fontInfo();
2815 os << "</emphasis>";
2818 if (style.free_spacing)
2820 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2826 void doFontSwitch(vector<html::FontTag> & tagsToOpen,
2827 vector<html::EndFontTag> & tagsToClose,
2828 bool & flag, FontState curstate, html::FontTypes type)
2830 if (curstate == FONT_ON) {
2831 tagsToOpen.push_back(html::FontTag(type));
2834 tagsToClose.push_back(html::EndFontTag(type));
2841 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2843 OutputParams const & runparams,
2844 Font const & outerfont,
2845 bool start_paragraph, bool close_paragraph,
2846 pos_type initial) const
2850 // track whether we have opened these tags
2851 bool emph_flag = false;
2852 bool bold_flag = false;
2853 bool noun_flag = false;
2854 bool ubar_flag = false;
2855 bool dbar_flag = false;
2856 bool sout_flag = false;
2857 bool xout_flag = false;
2858 bool wave_flag = false;
2860 bool shap_flag = false;
2862 bool faml_flag = false;
2864 bool size_flag = false;
2866 Layout const & style = *d->layout_;
2868 if (start_paragraph)
2869 xs.startDivision(allowEmpty());
2872 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2874 FontShape curr_fs = INHERIT_SHAPE;
2875 FontFamily curr_fam = INHERIT_FAMILY;
2876 FontSize curr_size = FONT_SIZE_INHERIT;
2878 string const default_family =
2879 buf.masterBuffer()->params().fonts_default_family;
2881 vector<html::FontTag> tagsToOpen;
2882 vector<html::EndFontTag> tagsToClose;
2884 // parsing main loop
2885 for (pos_type i = initial; i < size(); ++i) {
2886 // let's not show deleted material in the output
2890 Font const font = getFont(buf.masterBuffer()->params(), i, outerfont);
2893 FontState curstate = font.fontInfo().emph();
2894 if (font_old.emph() != curstate)
2895 doFontSwitch(tagsToOpen, tagsToClose, emph_flag, curstate, html::FT_EMPH);
2898 curstate = font.fontInfo().noun();
2899 if (font_old.noun() != curstate)
2900 doFontSwitch(tagsToOpen, tagsToClose, noun_flag, curstate, html::FT_NOUN);
2903 curstate = font.fontInfo().underbar();
2904 if (font_old.underbar() != curstate)
2905 doFontSwitch(tagsToOpen, tagsToClose, ubar_flag, curstate, html::FT_UBAR);
2908 curstate = font.fontInfo().strikeout();
2909 if (font_old.strikeout() != curstate)
2910 doFontSwitch(tagsToOpen, tagsToClose, sout_flag, curstate, html::FT_SOUT);
2913 curstate = font.fontInfo().xout();
2914 if (font_old.xout() != curstate)
2915 doFontSwitch(tagsToOpen, tagsToClose, xout_flag, curstate, html::FT_XOUT);
2918 curstate = font.fontInfo().uuline();
2919 if (font_old.uuline() != curstate)
2920 doFontSwitch(tagsToOpen, tagsToClose, dbar_flag, curstate, html::FT_DBAR);
2923 curstate = font.fontInfo().uwave();
2924 if (font_old.uwave() != curstate)
2925 doFontSwitch(tagsToOpen, tagsToClose, wave_flag, curstate, html::FT_WAVE);
2928 // a little hackish, but allows us to reuse what we have.
2929 curstate = (font.fontInfo().series() == BOLD_SERIES ? FONT_ON : FONT_OFF);
2930 if (font_old.series() != font.fontInfo().series())
2931 doFontSwitch(tagsToOpen, tagsToClose, bold_flag, curstate, html::FT_BOLD);
2934 curr_fs = font.fontInfo().shape();
2935 FontShape old_fs = font_old.shape();
2936 if (old_fs != curr_fs) {
2940 tagsToClose.push_back(html::EndFontTag(html::FT_ITALIC));
2943 tagsToClose.push_back(html::EndFontTag(html::FT_SLANTED));
2945 case SMALLCAPS_SHAPE:
2946 tagsToClose.push_back(html::EndFontTag(html::FT_SMALLCAPS));
2952 // the other tags are for internal use
2960 tagsToOpen.push_back(html::FontTag(html::FT_ITALIC));
2964 tagsToOpen.push_back(html::FontTag(html::FT_SLANTED));
2967 case SMALLCAPS_SHAPE:
2968 tagsToOpen.push_back(html::FontTag(html::FT_SMALLCAPS));
2975 // the other tags are for internal use
2982 curr_fam = font.fontInfo().family();
2983 FontFamily old_fam = font_old.family();
2984 if (old_fam != curr_fam) {
2988 tagsToClose.push_back(html::EndFontTag(html::FT_ROMAN));
2991 tagsToClose.push_back(html::EndFontTag(html::FT_SANS));
2993 case TYPEWRITER_FAMILY:
2994 tagsToClose.push_back(html::EndFontTag(html::FT_TYPE));
2996 case INHERIT_FAMILY:
2999 // the other tags are for internal use
3007 // we will treat a "default" font family as roman, since we have
3008 // no other idea what to do.
3009 if (default_family != "rmdefault" && default_family != "default") {
3010 tagsToOpen.push_back(html::FontTag(html::FT_ROMAN));
3015 if (default_family != "sfdefault") {
3016 tagsToOpen.push_back(html::FontTag(html::FT_SANS));
3020 case TYPEWRITER_FAMILY:
3021 if (default_family != "ttdefault") {
3022 tagsToOpen.push_back(html::FontTag(html::FT_TYPE));
3026 case INHERIT_FAMILY:
3029 // the other tags are for internal use
3036 curr_size = font.fontInfo().size();
3037 FontSize old_size = font_old.size();
3038 if (old_size != curr_size) {
3041 case FONT_SIZE_TINY:
3042 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_TINY));
3044 case FONT_SIZE_SCRIPT:
3045 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SCRIPT));
3047 case FONT_SIZE_FOOTNOTE:
3048 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_FOOTNOTE));
3050 case FONT_SIZE_SMALL:
3051 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_SMALL));
3053 case FONT_SIZE_LARGE:
3054 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGE));
3056 case FONT_SIZE_LARGER:
3057 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGER));
3059 case FONT_SIZE_LARGEST:
3060 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_LARGEST));
3062 case FONT_SIZE_HUGE:
3063 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGE));
3065 case FONT_SIZE_HUGER:
3066 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_HUGER));
3068 case FONT_SIZE_INCREASE:
3069 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_INCREASE));
3071 case FONT_SIZE_DECREASE:
3072 tagsToClose.push_back(html::EndFontTag(html::FT_SIZE_DECREASE));
3074 case FONT_SIZE_INHERIT:
3075 case FONT_SIZE_NORMAL:
3078 // the other tags are for internal use
3084 switch (curr_size) {
3085 case FONT_SIZE_TINY:
3086 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_TINY));
3089 case FONT_SIZE_SCRIPT:
3090 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SCRIPT));
3093 case FONT_SIZE_FOOTNOTE:
3094 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_FOOTNOTE));
3097 case FONT_SIZE_SMALL:
3098 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_SMALL));
3101 case FONT_SIZE_LARGE:
3102 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGE));
3105 case FONT_SIZE_LARGER:
3106 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGER));
3109 case FONT_SIZE_LARGEST:
3110 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_LARGEST));
3113 case FONT_SIZE_HUGE:
3114 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGE));
3117 case FONT_SIZE_HUGER:
3118 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_HUGER));
3121 case FONT_SIZE_INCREASE:
3122 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_INCREASE));
3125 case FONT_SIZE_DECREASE:
3126 tagsToOpen.push_back(html::FontTag(html::FT_SIZE_DECREASE));
3129 case FONT_SIZE_NORMAL:
3130 case FONT_SIZE_INHERIT:
3133 // the other tags are for internal use
3140 // Other such tags? What about the other text ranges?
3142 vector<html::EndFontTag>::const_iterator cit = tagsToClose.begin();
3143 vector<html::EndFontTag>::const_iterator cen = tagsToClose.end();
3144 for (; cit != cen; ++cit)
3147 vector<html::FontTag>::const_iterator sit = tagsToOpen.begin();
3148 vector<html::FontTag>::const_iterator sen = tagsToOpen.end();
3149 for (; sit != sen; ++sit)
3152 tagsToClose.clear();
3155 Inset const * inset = getInset(i);
3157 if (!runparams.for_toc || inset->isInToc()) {
3158 OutputParams np = runparams;
3159 np.local_font = &font;
3160 // If the paragraph has size 1, then we are in the "special
3161 // case" where we do not output the containing paragraph info
3162 if (!inset->getLayout().htmlisblock() && size() != 1)
3163 np.html_in_par = true;
3164 retval += inset->xhtml(xs, np);
3167 char_type c = getUChar(buf.masterBuffer()->params(), i);
3170 font_old = font.fontInfo();
3174 // I'm worried about what happens if a branch, say, is itself
3175 // wrapped in some font stuff. I think that will not work.
3177 if (close_paragraph)
3184 bool Paragraph::isHfill(pos_type pos) const
3186 Inset const * inset = getInset(pos);
3187 return inset && inset->isHfill();
3191 bool Paragraph::isNewline(pos_type pos) const
3193 // U+2028 LINE SEPARATOR
3194 // U+2029 PARAGRAPH SEPARATOR
3195 char_type const c = d->text_[pos];
3196 if (c == 0x2028 || c == 0x2029)
3198 Inset const * inset = getInset(pos);
3199 return inset && inset->lyxCode() == NEWLINE_CODE;
3203 bool Paragraph::isEnvSeparator(pos_type pos) const
3205 Inset const * inset = getInset(pos);
3206 return inset && inset->lyxCode() == SEPARATOR_CODE;
3210 bool Paragraph::isLineSeparator(pos_type pos) const
3212 char_type const c = d->text_[pos];
3213 if (isLineSeparatorChar(c))
3215 Inset const * inset = getInset(pos);
3216 return inset && inset->isLineSeparator();
3220 bool Paragraph::isWordSeparator(pos_type pos) const
3224 if (Inset const * inset = getInset(pos))
3225 return !inset->isLetter();
3226 // if we have a hard hyphen (no en- or emdash) or apostrophe
3227 // we pass this to the spell checker
3228 // FIXME: this method is subject to change, visit
3229 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
3230 // to get an impression how complex this is.
3231 if (isHardHyphenOrApostrophe(pos))
3233 char_type const c = d->text_[pos];
3234 // We want to pass the escape chars to the spellchecker
3235 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
3236 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
3240 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
3242 pos_type const psize = size();
3245 char_type const c = d->text_[pos];
3246 if (c != '-' && c != '\'')
3248 int nextpos = pos + 1;
3249 int prevpos = pos > 0 ? pos - 1 : 0;
3250 if ((nextpos == psize || isSpace(nextpos))
3251 && (pos == 0 || isSpace(prevpos)))
3257 FontSpan const & Paragraph::getSpellRange(pos_type pos) const
3259 return d->speller_state_.getRange(pos);
3263 bool Paragraph::isChar(pos_type pos) const
3265 if (Inset const * inset = getInset(pos))
3266 return inset->isChar();
3267 char_type const c = d->text_[pos];
3268 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
3272 bool Paragraph::isSpace(pos_type pos) const
3274 if (Inset const * inset = getInset(pos))
3275 return inset->isSpace();
3276 char_type const c = d->text_[pos];
3277 return lyx::isSpace(c);
3282 Paragraph::getParLanguage(BufferParams const & bparams) const
3285 return getFirstFontSettings(bparams).language();
3286 // FIXME: we should check the prev par as well (Lgb)
3287 return bparams.language;
3291 bool Paragraph::isRTL(BufferParams const & bparams) const
3293 return getParLanguage(bparams)->rightToLeft()
3294 && !inInset().getLayout().forceLTR();
3298 void Paragraph::changeLanguage(BufferParams const & bparams,
3299 Language const * from, Language const * to)
3301 // change language including dummy font change at the end
3302 for (pos_type i = 0; i <= size(); ++i) {
3303 Font font = getFontSettings(bparams, i);
3304 if (font.language() == from) {
3305 font.setLanguage(to);
3307 d->requestSpellCheck(i);
3313 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3315 Language const * doc_language = bparams.language;
3316 FontList::const_iterator cit = d->fontlist_.begin();
3317 FontList::const_iterator end = d->fontlist_.end();
3319 for (; cit != end; ++cit)
3320 if (cit->font().language() != ignore_language &&
3321 cit->font().language() != latex_language &&
3322 cit->font().language() != doc_language)
3328 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3330 FontList::const_iterator cit = d->fontlist_.begin();
3331 FontList::const_iterator end = d->fontlist_.end();
3333 for (; cit != end; ++cit) {
3334 Language const * lang = cit->font().language();
3335 if (lang != ignore_language &&
3336 lang != latex_language)
3337 languages.insert(lang);
3342 docstring Paragraph::asString(int options) const
3344 return asString(0, size(), options);
3348 docstring Paragraph::asString(pos_type beg, pos_type end, int options, const OutputParams *runparams) const
3350 odocstringstream os;
3353 && options & AS_STR_LABEL
3354 && !d->params_.labelString().empty())
3355 os << d->params_.labelString() << ' ';
3357 for (pos_type i = beg; i < end; ++i) {
3358 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3360 char_type const c = d->text_[i];
3361 if (isPrintable(c) || c == '\t'
3362 || (c == '\n' && (options & AS_STR_NEWLINES)))
3364 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3365 if (c == META_INSET && (options & AS_STR_PLAINTEXT)) {
3366 LASSERT(runparams != 0, return docstring());
3367 getInset(i)->plaintext(os, *runparams);
3369 getInset(i)->toString(os);
3378 void Paragraph::forOutliner(docstring & os, size_t const maxlen,
3379 bool const shorten, bool const label) const
3381 size_t tmplen = shorten ? maxlen + 1 : maxlen;
3382 if (label && !labelString().empty())
3383 os += labelString() + ' ';
3384 for (pos_type i = 0; i < size() && os.length() < tmplen; ++i) {
3387 char_type const c = d->text_[i];
3390 else if (c == META_INSET)
3391 getInset(i)->forOutliner(os, tmplen, false);
3394 Text::shortenForOutliner(os, maxlen);
3398 void Paragraph::setInsetOwner(Inset const * inset)
3400 d->inset_owner_ = inset;
3404 int Paragraph::id() const
3410 void Paragraph::setId(int id)
3416 Layout const & Paragraph::layout() const
3422 void Paragraph::setLayout(Layout const & layout)
3424 d->layout_ = &layout;
3428 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3430 setLayout(tc.defaultLayout());
3434 void Paragraph::setPlainLayout(DocumentClass const & tc)
3436 setLayout(tc.plainLayout());
3440 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3442 if (usePlainLayout())
3443 setPlainLayout(tclass);
3445 setDefaultLayout(tclass);
3449 Inset const & Paragraph::inInset() const
3451 LBUFERR(d->inset_owner_);
3452 return *d->inset_owner_;
3456 ParagraphParameters & Paragraph::params()
3462 ParagraphParameters const & Paragraph::params() const
3468 bool Paragraph::isFreeSpacing() const
3470 if (d->layout_->free_spacing)
3472 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3476 bool Paragraph::allowEmpty() const
3478 if (d->layout_->keepempty)
3480 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3484 bool Paragraph::brokenBiblio() const
3486 // there is a problem if there is no bibitem at position 0 or
3487 // if there is another bibitem in the paragraph.
3488 return d->layout_->labeltype == LABEL_BIBLIO
3489 && (d->insetlist_.find(BIBITEM_CODE) != 0
3490 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3494 int Paragraph::fixBiblio(Buffer const & buffer)
3496 // FIXME: What about the case where paragraph is not BIBLIO
3497 // but there is an InsetBibitem?
3498 // FIXME: when there was already an inset at 0, the return value is 1,
3499 // which does not tell whether another inset has been remove; the
3500 // cursor cannot be correctly updated.
3502 if (d->layout_->labeltype != LABEL_BIBLIO)
3505 bool const track_changes = buffer.params().track_changes;
3506 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3507 bool const hasbibitem0 = bibitem_pos == 0;
3510 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3511 // There was an InsetBibitem at pos 0, and no other one => OK
3512 if (bibitem_pos == -1)
3514 // there is a bibitem at the 0 position, but since
3515 // there is a second one, we copy the second on the
3516 // first. We're assuming there are at most two of
3517 // these, which there should be.
3518 // FIXME: why does it make sense to do that rather
3519 // than keep the first? (JMarc)
3520 Inset * inset = releaseInset(bibitem_pos);
3521 d->insetlist_.begin()->inset = inset;
3522 return -bibitem_pos;
3525 // We need to create an inset at the beginning
3527 if (bibitem_pos > 0) {
3528 // there was one somewhere in the paragraph, let's move it
3529 inset = d->insetlist_.release(bibitem_pos);
3530 eraseChar(bibitem_pos, track_changes);
3533 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3534 InsetCommandParams(BIBITEM_CODE));
3536 Font font(inherit_font, buffer.params().language);
3537 insertInset(0, inset, font, Change(track_changes ? Change::INSERTED
3538 : Change::UNCHANGED));
3544 void Paragraph::checkAuthors(AuthorList const & authorList)
3546 d->changes_.checkAuthors(authorList);
3550 bool Paragraph::isChanged(pos_type pos) const
3552 return lookupChange(pos).changed();
3556 bool Paragraph::isInserted(pos_type pos) const
3558 return lookupChange(pos).inserted();
3562 bool Paragraph::isDeleted(pos_type pos) const
3564 return lookupChange(pos).deleted();
3568 InsetList const & Paragraph::insetList() const
3570 return d->insetlist_;
3574 void Paragraph::setBuffer(Buffer & b)
3576 d->insetlist_.setBuffer(b);
3580 void Paragraph::resetBuffer()
3582 d->insetlist_.resetBuffer();
3586 Inset * Paragraph::releaseInset(pos_type pos)
3588 Inset * inset = d->insetlist_.release(pos);
3589 /// does not honour change tracking!
3590 eraseChar(pos, false);
3595 Inset * Paragraph::getInset(pos_type pos)
3597 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3598 ? d->insetlist_.get(pos) : 0;
3602 Inset const * Paragraph::getInset(pos_type pos) const
3604 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3605 ? d->insetlist_.get(pos) : 0;
3609 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3610 pos_type & right, TextCase action)
3612 // process sequences of modified characters; in change
3613 // tracking mode, this approach results in much better
3614 // usability than changing case on a char-by-char basis
3615 // We also need to track the current font, since font
3616 // changes within sequences can occur.
3617 vector<pair<char_type, Font> > changes;
3619 bool const trackChanges = bparams.track_changes;
3621 bool capitalize = true;
3623 for (; pos < right; ++pos) {
3624 char_type oldChar = d->text_[pos];
3625 char_type newChar = oldChar;
3627 // ignore insets and don't play with deleted text!
3628 if (oldChar != META_INSET && !isDeleted(pos)) {
3630 case text_lowercase:
3631 newChar = lowercase(oldChar);
3633 case text_capitalization:
3635 newChar = uppercase(oldChar);
3639 case text_uppercase:
3640 newChar = uppercase(oldChar);
3645 if (isWordSeparator(pos) || isDeleted(pos)) {
3646 // permit capitalization again
3650 if (oldChar != newChar) {
3651 changes.push_back(make_pair(newChar, getFontSettings(bparams, pos)));
3652 if (pos != right - 1)
3654 // step behind the changing area
3658 int erasePos = pos - changes.size();
3659 for (size_t i = 0; i < changes.size(); i++) {
3660 insertChar(pos, changes[i].first,
3663 if (!eraseChar(erasePos, trackChanges)) {
3666 ++right; // expand selection
3674 int Paragraph::find(docstring const & str, bool cs, bool mw,
3675 pos_type start_pos, bool del) const
3677 pos_type pos = start_pos;
3678 int const strsize = str.length();
3680 pos_type const parsize = d->text_.size();
3681 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3682 // Ignore "invisible" letters such as ligature breaks
3683 // and hyphenation chars while searching
3684 while (pos < parsize - 1 && isInset(pos)) {
3685 odocstringstream os;
3686 getInset(pos)->toString(os);
3687 if (!getInset(pos)->isLetter() || !os.str().empty())
3691 if (cs && str[i] != d->text_[pos])
3693 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3695 if (!del && isDeleted(pos))
3702 // if necessary, check whether string matches word
3704 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3707 && !isWordSeparator(pos))
3711 return pos - start_pos;
3715 char_type Paragraph::getChar(pos_type pos) const
3717 return d->text_[pos];
3721 pos_type Paragraph::size() const
3723 return d->text_.size();
3727 bool Paragraph::empty() const
3729 return d->text_.empty();
3733 bool Paragraph::isInset(pos_type pos) const
3735 return d->text_[pos] == META_INSET;
3739 bool Paragraph::isSeparator(pos_type pos) const
3741 //FIXME: Are we sure this can be the only separator?
3742 return d->text_[pos] == ' ';
3746 void Paragraph::deregisterWords()
3748 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3749 Private::LangWordsMap::const_iterator ite = d->words_.end();
3750 for (; itl != ite; ++itl) {
3751 WordList & wl = theWordList(itl->first);
3752 Private::Words::const_iterator it = (itl->second).begin();
3753 Private::Words::const_iterator et = (itl->second).end();
3754 for (; it != et; ++it)
3761 void Paragraph::locateWord(pos_type & from, pos_type & to,
3762 word_location const loc) const
3765 case WHOLE_WORD_STRICT:
3766 if (from == 0 || from == size()
3767 || isWordSeparator(from)
3768 || isWordSeparator(from - 1)) {
3772 // no break here, we go to the next
3775 // If we are already at the beginning of a word, do nothing
3776 if (!from || isWordSeparator(from - 1))
3778 // no break here, we go to the next
3781 // always move the cursor to the beginning of previous word
3782 while (from && !isWordSeparator(from - 1))
3786 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3789 // no need to move the 'from' cursor
3793 while (to < size() && !isWordSeparator(to))
3798 void Paragraph::collectWords()
3800 for (pos_type pos = 0; pos < size(); ++pos) {
3801 if (isWordSeparator(pos))
3803 pos_type from = pos;
3804 locateWord(from, pos, WHOLE_WORD);
3805 // Work around MSVC warning: The statement
3806 // if (pos < from + lyxrc.completion_minlength)
3807 // triggers a signed vs. unsigned warning.
3808 // I don't know why this happens, it could be a MSVC bug, or
3809 // related to LLP64 (windows) vs. LP64 (unix) programming
3810 // model, or the C++ standard might be ambigous in the section
3811 // defining the "usual arithmetic conversions". However, using
3812 // a temporary variable is safe and works on all compilers.
3813 pos_type const endpos = from + lyxrc.completion_minlength;
3816 FontList::const_iterator cit = d->fontlist_.fontIterator(from);
3817 if (cit == d->fontlist_.end())
3819 Language const * lang = cit->font().language();
3820 docstring const word = asString(from, pos, AS_STR_NONE);
3821 d->words_[lang->lang()].insert(word);
3826 void Paragraph::registerWords()
3828 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3829 Private::LangWordsMap::const_iterator ite = d->words_.end();
3830 for (; itl != ite; ++itl) {
3831 WordList & wl = theWordList(itl->first);
3832 Private::Words::const_iterator it = (itl->second).begin();
3833 Private::Words::const_iterator et = (itl->second).end();
3834 for (; it != et; ++it)
3840 void Paragraph::updateWords()
3848 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3850 SkipPositionsIterator begin = skips.begin();
3851 SkipPositions::iterator end = skips.end();
3852 if (pos > 0 && begin < end) {
3854 if (end->last == pos - 1) {
3859 skips.insert(end, FontSpan(pos, pos));
3863 Language * Paragraph::Private::locateSpellRange(
3864 pos_type & from, pos_type & to,
3865 SkipPositions & skips) const
3867 // skip leading white space
3868 while (from < to && owner_->isWordSeparator(from))
3870 // don't check empty range
3873 // get current language
3874 Language * lang = getSpellLanguage(from);
3875 pos_type last = from;
3876 bool samelang = true;
3877 bool sameinset = true;
3878 while (last < to && samelang && sameinset) {
3879 // hop to end of word
3880 while (last < to && !owner_->isWordSeparator(last)) {
3881 if (owner_->getInset(last)) {
3882 appendSkipPosition(skips, last);
3883 } else if (owner_->isDeleted(last)) {
3884 appendSkipPosition(skips, last);
3888 // hop to next word while checking for insets
3889 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3890 if (Inset const * inset = owner_->getInset(last))
3891 sameinset = inset->isChar() && inset->isLetter();
3892 if (sameinset && owner_->isDeleted(last)) {
3893 appendSkipPosition(skips, last);
3898 if (sameinset && last < to) {
3899 // now check for language change
3900 samelang = lang == getSpellLanguage(last);
3903 // if language change detected backstep is needed
3911 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3914 const_cast<Language *>(owner_->getFontSettings(
3915 inset_owner_->buffer().params(), from).language());
3916 if (lang == inset_owner_->buffer().params().language
3917 && !lyxrc.spellchecker_alt_lang.empty()) {
3919 string const lang_variety =
3920 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3921 lang->setCode(lang_code);
3922 lang->setVariety(lang_variety);
3928 void Paragraph::requestSpellCheck(pos_type pos)
3930 d->requestSpellCheck(pos);
3934 bool Paragraph::needsSpellCheck() const
3936 SpellChecker::ChangeNumber speller_change_number = 0;
3937 if (theSpellChecker())
3938 speller_change_number = theSpellChecker()->changeNumber();
3939 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3940 d->speller_state_.needsCompleteRefresh(speller_change_number);
3942 return d->needsSpellCheck();
3946 bool Paragraph::Private::ignoreWord(docstring const & word) const
3948 // Ignore words with digits
3949 // FIXME: make this customizable
3950 // (note that some checkers ignore words with digits by default)
3951 docstring::const_iterator cit = word.begin();
3952 docstring::const_iterator const end = word.end();
3953 for (; cit != end; ++cit) {
3954 if (isNumber((*cit)))
3961 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3962 WordLangTuple & wl, docstring_list & suggestions,
3963 bool do_suggestion, bool check_learned) const
3965 SpellChecker::Result result = SpellChecker::WORD_OK;
3966 SpellChecker * speller = theSpellChecker();
3970 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3973 locateWord(from, to, WHOLE_WORD);
3974 if (from == to || from >= size())
3977 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3978 Language * lang = d->getSpellLanguage(from);
3980 wl = WordLangTuple(word, lang);
3985 if (needsSpellCheck() || check_learned) {
3987 if (!d->ignoreWord(word)) {
3988 bool const trailing_dot = to < size() && d->text_[to] == '.';
3989 result = speller->check(wl);
3990 if (SpellChecker::misspelled(result) && trailing_dot) {
3991 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3992 result = speller->check(wl);
3993 if (!SpellChecker::misspelled(result)) {
3994 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3996 from << ".." << to << "]");
3998 // spell check with dot appended failed too
3999 // restore original word/lang value
4000 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
4001 wl = WordLangTuple(word, lang);
4005 if (!SpellChecker::misspelled(result)) {
4006 // area up to the begin of the next word is not misspelled
4007 while (end < size() && isWordSeparator(end))
4010 d->setMisspelled(from, end, result);
4012 result = d->speller_state_.getState(from);
4016 suggestions.clear();
4018 if (SpellChecker::misspelled(result)) {
4019 LYXERR(Debug::GUI, "misspelled word: \"" <<
4021 from << ".." << to << "]");
4023 speller->suggest(wl, suggestions);
4029 void Paragraph::Private::markMisspelledWords(
4030 pos_type const & first, pos_type const & last,
4031 SpellChecker::Result result,
4032 docstring const & word,
4033 SkipPositions const & skips)
4035 if (!SpellChecker::misspelled(result)) {
4036 setMisspelled(first, last, SpellChecker::WORD_OK);
4040 SpellChecker * speller = theSpellChecker();
4041 // locate and enumerate the error positions
4042 int nerrors = speller->numMisspelledWords();
4044 SkipPositionsIterator it = skips.begin();
4045 SkipPositionsIterator et = skips.end();
4046 for (int index = 0; index < nerrors; ++index) {
4049 speller->misspelledWord(index, wstart, wlen);
4050 /// should not happen if speller supports range checks
4051 if (!wlen) continue;
4052 docstring const misspelled = word.substr(wstart, wlen);
4053 wstart += first + numskipped;
4054 if (snext < wstart) {
4055 /// mark the range of correct spelling
4056 numskipped += countSkips(it, et, wstart);
4057 setMisspelled(snext,
4058 wstart - 1, SpellChecker::WORD_OK);
4060 snext = wstart + wlen;
4061 numskipped += countSkips(it, et, snext);
4062 /// mark the range of misspelling
4063 setMisspelled(wstart, snext, result);
4064 LYXERR(Debug::GUI, "misspelled word: \"" <<
4065 misspelled << "\" [" <<
4066 wstart << ".." << (snext-1) << "]");
4069 if (snext <= last) {
4070 /// mark the range of correct spelling at end
4071 setMisspelled(snext, last, SpellChecker::WORD_OK);
4076 void Paragraph::spellCheck() const
4078 SpellChecker * speller = theSpellChecker();
4079 if (!speller || empty() ||!needsSpellCheck())
4083 d->rangeOfSpellCheck(start, endpos);
4084 if (speller->canCheckParagraph()) {
4085 // loop until we leave the range
4086 for (pos_type first = start; first < endpos; ) {
4087 pos_type last = endpos;
4088 Private::SkipPositions skips;
4089 Language * lang = d->locateSpellRange(first, last, skips);
4090 if (first >= endpos)
4092 // start the spell checker on the unit of meaning
4093 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
4094 WordLangTuple wl = WordLangTuple(word, lang);
4095 SpellChecker::Result result = word.size() ?
4096 speller->check(wl) : SpellChecker::WORD_OK;
4097 d->markMisspelledWords(first, last, result, word, skips);
4101 static docstring_list suggestions;
4102 pos_type to = endpos;
4103 while (start < endpos) {
4105 spellCheck(start, to, wl, suggestions, false);
4109 d->readySpellCheck();
4113 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
4115 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
4116 if (result || pos <= 0 || pos > size())
4118 if (check_boundary && (pos == size() || isWordSeparator(pos)))
4119 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
4124 string Paragraph::magicLabel() const
4127 ss << "magicparlabel-" << id();