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"
29 #include "InsetList.h"
31 #include "LaTeXFeatures.h"
37 #include "OutputParams.h"
38 #include "output_latex.h"
39 #include "output_xhtml.h"
40 #include "ParagraphParameters.h"
41 #include "SpellChecker.h"
43 #include "TextClass.h"
46 #include "WordLangTuple.h"
49 #include "frontends/alert.h"
51 #include "insets/InsetBibitem.h"
52 #include "insets/InsetLabel.h"
53 #include "insets/InsetSpecialChar.h"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 class SpellResultRange {
85 SpellResultRange(FontSpan range, SpellChecker::Result result)
86 : range_(range), result_(result)
89 FontSpan const & range() const { return range_; }
91 void range(FontSpan const & r) { range_ = r; }
93 SpellChecker::Result result() const { return result_; }
95 void result(SpellChecker::Result r) { result_ = r; }
97 bool inside(pos_type pos) const { return range_.inside(pos); }
99 bool covered(FontSpan const & r) const
101 // 1. first of new range inside current range or
102 // 2. last of new range inside current range or
103 // 3. first of current range inside new range or
104 // 4. last of current range inside new range
105 return range_.inside(r.first) || range_.inside(r.last) ||
106 r.inside(range_.first) || r.inside(range_.last);
109 void shift(pos_type pos, int offset)
111 if (range_.first > pos) {
112 range_.first += offset;
113 range_.last += offset;
114 } else if (range_.last >= pos) {
115 range_.last += offset;
120 SpellChecker::Result result_ ;
124 /////////////////////////////////////////////////////////////////////
128 /////////////////////////////////////////////////////////////////////
130 class SpellCheckerState {
132 SpellCheckerState() {
133 needs_refresh_ = true;
134 current_change_number_ = 0;
137 void setRange(FontSpan const & fp, SpellChecker::Result state)
140 RangesIterator et = ranges_.end();
141 RangesIterator it = ranges_.begin();
142 for (; it != et; ++it) {
143 if (!it->covered(fp))
144 result.push_back(SpellResultRange(it->range(), it->result()));
145 else if (state == SpellChecker::WORD_OK) {
146 // trim or split the current misspelled range
147 // store misspelled ranges only
148 FontSpan range = it->range();
149 if (fp.first > range.first) {
150 // misspelled area in front of WORD_OK
151 range.last = fp.first - 1;
152 result.push_back(SpellResultRange(range, it->result()));
155 if (fp.last < range.last) {
156 // misspelled area after WORD_OK range
157 range.first = fp.last + 1;
158 result.push_back(SpellResultRange(range, it->result()));
163 if (state != SpellChecker::WORD_OK)
164 ranges_.push_back(SpellResultRange(fp, state));
167 void increasePosAfterPos(pos_type pos)
169 correctRangesAfterPos(pos, 1);
173 void decreasePosAfterPos(pos_type pos)
175 correctRangesAfterPos(pos, -1);
179 void refreshLast(pos_type pos)
181 if (pos < refresh_.last)
185 SpellChecker::Result getState(pos_type pos) const
187 SpellChecker::Result result = SpellChecker::WORD_OK;
188 RangesIterator et = ranges_.end();
189 RangesIterator it = ranges_.begin();
190 for (; it != et; ++it) {
191 if(it->inside(pos)) {
198 FontSpan const & getRange(pos_type pos) const
200 /// empty span to indicate mismatch
201 static FontSpan empty_;
202 RangesIterator et = ranges_.end();
203 RangesIterator it = ranges_.begin();
204 for (; it != et; ++it) {
205 if(it->inside(pos)) {
212 bool needsRefresh() const {
213 return needs_refresh_;
216 SpellChecker::ChangeNumber currentChangeNumber() const {
217 return current_change_number_;
220 void refreshRange(pos_type & first, pos_type & last) const {
221 first = refresh_.first;
222 last = refresh_.last;
225 void needsRefresh(pos_type pos) {
226 if (needs_refresh_ && pos != -1) {
227 if (pos < refresh_.first)
228 refresh_.first = pos;
229 if (pos > refresh_.last)
231 } else if (pos != -1) {
232 // init request check for neighbour positions too
233 refresh_.first = pos > 0 ? pos - 1 : 0;
234 // no need for special end of paragraph check
235 refresh_.last = pos + 1;
237 needs_refresh_ = pos != -1;
240 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
241 needs_refresh_ = true;
244 current_change_number_ = change_number;
248 typedef vector<SpellResultRange> Ranges;
249 typedef Ranges::const_iterator RangesIterator;
251 /// the area of the paragraph with pending spell check
254 /// spell state cache version number
255 SpellChecker::ChangeNumber current_change_number_;
258 void correctRangesAfterPos(pos_type pos, int offset)
260 RangesIterator et = ranges_.end();
261 Ranges::iterator it = ranges_.begin();
262 for (; it != et; ++it) {
263 it->shift(pos, offset);
269 /////////////////////////////////////////////////////////////////////
271 // Paragraph::Private
273 /////////////////////////////////////////////////////////////////////
275 class Paragraph::Private
279 Private(Paragraph * owner, Layout const & layout);
280 /// "Copy constructor"
281 Private(Private const &, Paragraph * owner);
282 /// Copy constructor from \p beg to \p end
283 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
286 void insertChar(pos_type pos, char_type c, Change const & change);
288 /// Output the surrogate pair formed by \p c and \p next to \p os.
289 /// \return the number of characters written.
290 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
291 OutputParams const &);
293 /// Output a space in appropriate formatting (or a surrogate pair
294 /// if the next character is a combining character).
295 /// \return whether a surrogate pair was output.
296 bool simpleTeXBlanks(OutputParams const &,
299 unsigned int & column,
301 Layout const & style);
303 /// Output consecutive unicode chars, belonging to the same script as
304 /// specified by the latex macro \p ltx, to \p os starting from \p i.
305 /// \return the number of characters written.
306 int writeScriptChars(otexstream & os, docstring const & ltx,
307 Change const &, Encoding const &, pos_type & i);
309 /// This could go to ParagraphParameters if we want to.
310 int startTeXParParams(BufferParams const &, otexstream &,
311 OutputParams const &) const;
313 /// This could go to ParagraphParameters if we want to.
314 bool endTeXParParams(BufferParams const &, otexstream &,
315 OutputParams const &) const;
318 void latexInset(BufferParams const &,
323 Font const & outerfont,
325 Change & running_change,
326 Layout const & style,
328 unsigned int & column);
331 void latexSpecialChar(
333 BufferParams const & bparams,
334 OutputParams const & runparams,
335 Font const & running_font,
336 Change const & running_change,
337 Layout const & style,
340 unsigned int & column);
347 unsigned int & column);
353 unsigned int & column);
355 bool latexSpecialTypewriter(
359 unsigned int & column);
361 bool latexSpecialPhrase(
365 unsigned int & column,
366 OutputParams const & runparams);
369 void validate(LaTeXFeatures & features) const;
371 /// Checks if the paragraph contains only text and no inset or font change.
372 bool onlyText(Buffer const & buf, Font const & outerfont,
373 pos_type initial) const;
375 /// match a string against a particular point in the paragraph
376 bool isTextAt(string const & str, pos_type pos) const;
378 /// a vector of speller skip positions
379 typedef vector<FontSpan> SkipPositions;
380 typedef SkipPositions::const_iterator SkipPositionsIterator;
382 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
384 Language * getSpellLanguage(pos_type const from) const;
386 Language * locateSpellRange(pos_type & from, pos_type & to,
387 SkipPositions & skips) const;
389 bool hasSpellerChange() const {
390 SpellChecker::ChangeNumber speller_change_number = 0;
391 if (theSpellChecker())
392 speller_change_number = theSpellChecker()->changeNumber();
393 return speller_change_number > speller_state_.currentChangeNumber();
396 bool ignoreWord(docstring const & word) const ;
398 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
400 pos_type textsize = owner_->size();
401 // check for sane arguments
402 if (to <= from || from >= textsize)
404 FontSpan fp = FontSpan(from, to - 1);
405 speller_state_.setRange(fp, state);
408 void requestSpellCheck(pos_type pos) {
410 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
412 speller_state_.needsRefresh(pos);
415 void readySpellCheck() {
416 speller_state_.needsRefresh(-1);
419 bool needsSpellCheck() const
421 return speller_state_.needsRefresh();
424 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
426 speller_state_.refreshRange(first, last);
428 last = owner_->size();
431 pos_type endpos = last;
432 owner_->locateWord(first, endpos, WHOLE_WORD);
435 owner_->locateWord(last, endpos, WHOLE_WORD);
440 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
444 while (it != et && it->first < start) {
445 int skip = it->last - it->first + 1;
453 void markMisspelledWords(pos_type const & first, pos_type const & last,
454 SpellChecker::Result result,
455 docstring const & word,
456 SkipPositions const & skips);
458 InsetCode ownerCode() const
460 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
463 /// Which Paragraph owns us?
467 Inset const * inset_owner_;
476 ParagraphParameters params_;
478 /// for recording and looking up changes
482 InsetList insetlist_;
485 pos_type begin_of_body_;
487 typedef docstring TextContainer;
491 typedef set<docstring> Words;
492 typedef map<Language, Words> LangWordsMap;
496 Layout const * layout_;
498 SpellCheckerState speller_state_;
504 struct special_phrase {
510 special_phrase const special_phrases[] = {
511 { "LyX", from_ascii("\\LyX{}"), false },
512 { "TeX", from_ascii("\\TeX{}"), true },
513 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
514 { "LaTeX", from_ascii("\\LaTeX{}"), true },
517 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
522 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
523 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
529 // Initialization of the counter for the paragraph id's,
531 // FIXME: There should be a more intelligent way to generate and use the
532 // paragraph ids per buffer instead a global static counter for all InsetText
533 // in the running program.
534 static int paragraph_id = -1;
536 Paragraph::Private::Private(Private const & p, Paragraph * owner)
537 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
538 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
539 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
542 id_ = ++paragraph_id;
543 requestSpellCheck(p.text_.size());
547 Paragraph::Private::Private(Private const & p, Paragraph * owner,
548 pos_type beg, pos_type end)
549 : owner_(owner), inset_owner_(p.inset_owner_),
550 params_(p.params_), changes_(p.changes_),
551 insetlist_(p.insetlist_, beg, end),
552 begin_of_body_(p.begin_of_body_), words_(p.words_),
555 id_ = ++paragraph_id;
556 if (beg >= pos_type(p.text_.size()))
558 text_ = p.text_.substr(beg, end - beg);
560 FontList::const_iterator fcit = fontlist_.begin();
561 FontList::const_iterator fend = fontlist_.end();
562 for (; fcit != fend; ++fcit) {
563 if (fcit->pos() < beg)
565 if (fcit->pos() >= end) {
566 // Add last entry in the fontlist_.
567 fontlist_.set(text_.size() - 1, fcit->font());
570 // Add a new entry in the fontlist_.
571 fontlist_.set(fcit->pos() - beg, fcit->font());
573 requestSpellCheck(p.text_.size());
577 void Paragraph::addChangesToToc(DocIterator const & cdit,
578 Buffer const & buf) const
580 d->changes_.addToToc(cdit, buf);
584 bool Paragraph::isDeleted(pos_type start, pos_type end) const
586 LASSERT(start >= 0 && start <= size(), /**/);
587 LASSERT(end > start && end <= size() + 1, /**/);
589 return d->changes_.isDeleted(start, end);
593 bool Paragraph::isChanged(pos_type start, pos_type end) const
595 LASSERT(start >= 0 && start <= size(), /**/);
596 LASSERT(end > start && end <= size() + 1, /**/);
598 return d->changes_.isChanged(start, end);
602 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
604 // keep the logic here in sync with the logic of eraseChars()
608 Change const change = d->changes_.lookup(size());
609 return change.inserted() && change.currentAuthor();
613 void Paragraph::setChange(Change const & change)
615 // beware of the imaginary end-of-par character!
616 d->changes_.set(change, 0, size() + 1);
619 * Propagate the change recursively - but not in case of DELETED!
621 * Imagine that your co-author makes changes in an existing inset. He
622 * sends your document to you and you come to the conclusion that the
623 * inset should go completely. If you erase it, LyX must not delete all
624 * text within the inset. Otherwise, the change tracked insertions of
625 * your co-author get lost and there is no way to restore them later.
627 * Conclusion: An inset's content should remain untouched if you delete it
630 if (!change.deleted()) {
631 for (pos_type pos = 0; pos < size(); ++pos) {
632 if (Inset * inset = getInset(pos))
633 inset->setChange(change);
639 void Paragraph::setChange(pos_type pos, Change const & change)
641 LASSERT(pos >= 0 && pos <= size(), /**/);
642 d->changes_.set(change, pos);
644 // see comment in setChange(Change const &) above
645 if (!change.deleted() && pos < size())
646 if (Inset * inset = getInset(pos))
647 inset->setChange(change);
651 Change const & Paragraph::lookupChange(pos_type pos) const
653 LASSERT(pos >= 0 && pos <= size(), /**/);
654 return d->changes_.lookup(pos);
658 void Paragraph::acceptChanges(pos_type start, pos_type end)
660 LASSERT(start >= 0 && start <= size(), /**/);
661 LASSERT(end > start && end <= size() + 1, /**/);
663 for (pos_type pos = start; pos < end; ++pos) {
664 switch (lookupChange(pos).type) {
665 case Change::UNCHANGED:
666 // accept changes in nested inset
667 if (Inset * inset = getInset(pos))
668 inset->acceptChanges();
671 case Change::INSERTED:
672 d->changes_.set(Change(Change::UNCHANGED), pos);
673 // also accept changes in nested inset
674 if (Inset * inset = getInset(pos))
675 inset->acceptChanges();
678 case Change::DELETED:
679 // Suppress access to non-existent
680 // "end-of-paragraph char"
682 eraseChar(pos, false);
693 void Paragraph::rejectChanges(pos_type start, pos_type end)
695 LASSERT(start >= 0 && start <= size(), /**/);
696 LASSERT(end > start && end <= size() + 1, /**/);
698 for (pos_type pos = start; pos < end; ++pos) {
699 switch (lookupChange(pos).type) {
700 case Change::UNCHANGED:
701 // reject changes in nested inset
702 if (Inset * inset = getInset(pos))
703 inset->rejectChanges();
706 case Change::INSERTED:
707 // Suppress access to non-existent
708 // "end-of-paragraph char"
710 eraseChar(pos, false);
716 case Change::DELETED:
717 d->changes_.set(Change(Change::UNCHANGED), pos);
719 // Do NOT reject changes within a deleted inset!
720 // There may be insertions of a co-author inside of it!
728 void Paragraph::Private::insertChar(pos_type pos, char_type c,
729 Change const & change)
731 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
734 changes_.insert(change, pos);
736 // This is actually very common when parsing buffers (and
737 // maybe inserting ascii text)
738 if (pos == pos_type(text_.size())) {
739 // when appending characters, no need to update tables
741 // but we want spell checking
742 requestSpellCheck(pos);
746 text_.insert(text_.begin() + pos, c);
748 // Update the font table.
749 fontlist_.increasePosAfterPos(pos);
752 insetlist_.increasePosAfterPos(pos);
754 // Update list of misspelled positions
755 speller_state_.increasePosAfterPos(pos);
759 bool Paragraph::insertInset(pos_type pos, Inset * inset,
760 Change const & change)
762 LASSERT(inset, /**/);
763 LASSERT(pos >= 0 && pos <= size(), /**/);
765 // Paragraph::insertInset() can be used in cut/copy/paste operation where
766 // d->inset_owner_ is not set yet.
767 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
770 d->insertChar(pos, META_INSET, change);
771 LASSERT(d->text_[pos] == META_INSET, /**/);
773 // Add a new entry in the insetlist_.
774 d->insetlist_.insert(inset, pos);
776 // Some insets require run of spell checker
777 requestSpellCheck(pos);
782 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
784 LASSERT(pos >= 0 && pos <= size(), return false);
786 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
789 Change change = d->changes_.lookup(pos);
791 // set the character to DELETED if
792 // a) it was previously unchanged or
793 // b) it was inserted by a co-author
795 if (!change.changed() ||
796 (change.inserted() && !change.currentAuthor())) {
797 setChange(pos, Change(Change::DELETED));
798 // request run of spell checker
799 requestSpellCheck(pos);
803 if (change.deleted())
807 // Don't physically access the imaginary end-of-paragraph character.
808 // eraseChar() can only mark it as DELETED. A physical deletion of
809 // end-of-par must be handled externally.
815 d->changes_.erase(pos);
817 // if it is an inset, delete the inset entry
818 if (d->text_[pos] == META_INSET)
819 d->insetlist_.erase(pos);
821 d->text_.erase(d->text_.begin() + pos);
823 // Update the fontlist_
824 d->fontlist_.erase(pos);
826 // Update the insetlist_
827 d->insetlist_.decreasePosAfterPos(pos);
829 // Update list of misspelled positions
830 d->speller_state_.decreasePosAfterPos(pos);
831 d->speller_state_.refreshLast(size());
837 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
839 LASSERT(start >= 0 && start <= size(), /**/);
840 LASSERT(end >= start && end <= size() + 1, /**/);
843 for (pos_type count = end - start; count; --count) {
844 if (!eraseChar(i, trackChanges))
851 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
852 char_type next, OutputParams const & runparams)
854 // Writing next here may circumvent a possible font change between
855 // c and next. Since next is only output if it forms a surrogate pair
856 // with c we can ignore this:
857 // A font change inside a surrogate pair does not make sense and is
858 // hopefully impossible to input.
859 // FIXME: change tracking
860 // Is this correct WRT change tracking?
861 Encoding const & encoding = *(runparams.encoding);
862 docstring const latex1 = encoding.latexChar(next).first;
863 docstring const latex2 = encoding.latexChar(c).first;
864 if (docstring(1, next) == latex1) {
865 // the encoding supports the combination
866 os << latex2 << latex1;
867 return latex1.length() + latex2.length();
868 } else if (runparams.local_font &&
869 runparams.local_font->language()->lang() == "polutonikogreek") {
870 // polutonikogreek only works without the brackets
871 os << latex1 << latex2;
872 return latex1.length() + latex2.length();
874 os << latex1 << '{' << latex2 << '}';
875 return latex1.length() + latex2.length() + 2;
879 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
882 unsigned int & column,
884 Layout const & style)
886 if (style.pass_thru || runparams.pass_thru)
889 if (i + 1 < int(text_.size())) {
890 char_type next = text_[i + 1];
891 if (Encodings::isCombiningChar(next)) {
892 // This space has an accent, so we must always output it.
893 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
898 if (runparams.linelen > 0
899 && column > runparams.linelen
901 && text_[i - 1] != ' '
902 && (i + 1 < int(text_.size()))
903 // same in FreeSpacing mode
904 && !owner_->isFreeSpacing()
905 // In typewriter mode, we want to avoid
906 // ! . ? : at the end of a line
907 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
908 && (text_[i - 1] == '.'
909 || text_[i - 1] == '?'
910 || text_[i - 1] == ':'
911 || text_[i - 1] == '!'))) {
913 os.texrow().start(owner_->id(), i + 1);
915 } else if (style.free_spacing) {
924 int Paragraph::Private::writeScriptChars(otexstream & os,
925 docstring const & ltx,
926 Change const & runningChange,
927 Encoding const & encoding,
930 // FIXME: modifying i here is not very nice...
932 // We only arrive here when a proper language for character text_[i] has
933 // not been specified (i.e., it could not be translated in the current
934 // latex encoding) or its latex translation has been forced, and it
935 // belongs to a known script.
936 // Parameter ltx contains the latex translation of text_[i] as specified
937 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
938 // The latex macro name "textXXX" specifies the script to which text_[i]
939 // belongs and we use it in order to check whether characters from the
940 // same script immediately follow, such that we can collect them in a
941 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
942 // for the first char but only "<spec>" for all subsequent chars.
943 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
944 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
945 string script = to_ascii(ltx.substr(1, brace1 - 1));
948 bool closing_brace = true;
949 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
950 // Correct encoding is being used, so we can avoid \textgreek.
953 closing_brace = false;
955 os << ltx.substr(pos, length);
956 int size = text_.size();
957 while (i + 1 < size) {
958 char_type const next = text_[i + 1];
959 // Stop here if next character belongs to another script
960 // or there is a change in change tracking status.
961 if (!Encodings::isKnownScriptChar(next, script) ||
962 runningChange != owner_->lookupChange(i + 1))
966 FontList::const_iterator cit = fontlist_.begin();
967 FontList::const_iterator end = fontlist_.end();
968 for (; cit != end; ++cit) {
969 if (cit->pos() >= i && !found) {
970 prev_font = cit->font();
973 if (cit->pos() >= i + 1)
976 // Stop here if there is a font attribute or encoding change.
977 if (found && cit != end && prev_font != cit->font())
979 docstring const latex = encoding.latexChar(next).first;
980 docstring::size_type const b1 =
981 latex.find_first_of(from_ascii("{"));
982 docstring::size_type const b2 =
983 latex.find_last_of(from_ascii("}"));
984 int const len = b2 - b1 - 1;
985 os << latex.substr(b1 + 1, len);
997 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
999 pos_type const len = str.length();
1001 // is the paragraph large enough?
1002 if (pos + len > int(text_.size()))
1005 // does the wanted text start at point?
1006 for (string::size_type i = 0; i < str.length(); ++i) {
1007 // Caution: direct comparison of characters works only
1008 // because str is pure ASCII.
1009 if (str[i] != text_[pos + i])
1013 return fontlist_.hasChangeInRange(pos, len);
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);
1030 LASSERT(inset, /**/);
1032 if (style.pass_thru) {
1033 inset->plaintext(os.os(), runparams);
1037 // FIXME: move this to InsetNewline::latex
1038 if (inset->lyxCode() == NEWLINE_CODE) {
1039 // newlines are handled differently here than
1040 // the default in simpleTeXSpecialChars().
1041 if (!style.newline_allowed) {
1045 column += running_font.latexWriteEndChanges(
1046 os, bparams, runparams,
1047 basefont, basefont);
1051 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1054 basefont = owner_->getLayoutFont(bparams, outerfont);
1055 running_font = basefont;
1057 if (runparams.moving_arg)
1061 os.texrow().start(owner_->id(), i + 1);
1065 if (owner_->isDeleted(i)) {
1066 if( ++runparams.inDeletedInset == 1)
1067 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1070 if (inset->canTrackChanges()) {
1071 column += Changes::latexMarkChange(os, bparams, running_change,
1072 Change(Change::UNCHANGED), runparams);
1073 running_change = Change(Change::UNCHANGED);
1077 odocstream::pos_type const len = os.os().tellp();
1079 if (inset->forceLTR()
1080 && !runparams.use_polyglossia
1081 && running_font.isRightToLeft()
1082 // ERT is an exception, it should be output with no
1083 // decorations at all
1084 && inset->lyxCode() != ERT_CODE) {
1085 if (running_font.language()->lang() == "farsi")
1092 // FIXME: Bug: we can have an empty font change here!
1093 // if there has just been a font change, we are going to close it
1094 // right now, which means stupid latex code like \textsf{}. AFAIK,
1095 // this does not harm dvi output. A minor bug, thus (JMarc)
1097 // Some insets cannot be inside a font change command.
1098 // However, even such insets *can* be placed in \L or \R
1099 // or their equivalents (for RTL language switches), so we don't
1100 // close the language in those cases.
1101 // ArabTeX, though, cannot handle this special behavior, it seems.
1102 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1103 || running_font.language()->lang() == "arabic_arabtex";
1104 if (open_font && !inset->inheritFont()) {
1105 bool closeLanguage = arabtex
1106 || basefont.isRightToLeft() == running_font.isRightToLeft();
1107 unsigned int count = running_font.latexWriteEndChanges(os,
1108 bparams, runparams, basefont, basefont, closeLanguage);
1110 // if any font properties were closed, update the running_font,
1111 // making sure, however, to leave the language as it was
1113 // FIXME: probably a better way to keep track of the old
1114 // language, than copying the entire font?
1115 Font const copy_font(running_font);
1116 basefont = owner_->getLayoutFont(bparams, outerfont);
1117 running_font = basefont;
1119 running_font.setLanguage(copy_font.language());
1120 // leave font open if language is still open
1121 open_font = (running_font.language() == basefont.language());
1123 runparams.local_font = &basefont;
1127 int prev_rows = os.texrow().rows();
1130 runparams.lastid = id_;
1131 runparams.lastpos = i;
1132 inset->latex(os, runparams);
1133 } catch (EncodingException & e) {
1134 // add location information and throw again.
1141 if (running_font.language()->lang() == "farsi")
1147 if (os.texrow().rows() > prev_rows) {
1148 os.texrow().start(owner_->id(), i + 1);
1151 column += (unsigned int)(os.os().tellp() - len);
1154 if (owner_->isDeleted(i))
1155 --runparams.inDeletedInset;
1159 void Paragraph::Private::latexSpecialChar(otexstream & os,
1160 BufferParams const & bparams,
1161 OutputParams const & runparams,
1162 Font const & running_font,
1163 Change const & running_change,
1164 Layout const & style,
1167 unsigned int & column)
1169 // With polyglossia, brackets and stuff need not be reversed
1170 // in RTL scripts (see bug #8251)
1171 char_type const c = (runparams.use_polyglossia) ?
1172 owner_->getUChar(bparams, i) : text_[i];
1174 if (style.pass_thru || runparams.pass_thru) {
1176 Encoding const * const enc = runparams.encoding;
1177 if (enc && !enc->encodable(c))
1178 throw EncodingException(c);
1184 // TIPA uses its own T3 encoding
1185 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1187 // If T1 font encoding is used, use the special
1188 // characters it provides.
1189 // NOTE: some languages reset the font encoding
1191 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1192 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1195 // \tt font needs special treatment
1196 if (!runparams.inIPA
1197 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1198 && latexSpecialTypewriter(c, os, i, column))
1201 // Otherwise, we use what LaTeX provides us.
1204 os << "\\textbackslash{}";
1208 os << "\\textless{}";
1212 os << "\\textgreater{}";
1216 os << "\\textbar{}";
1223 os << "\\char`\\\"{}";
1228 case '%': case '#': case '{':
1236 os << "\\textasciitilde{}";
1241 os << "\\textasciicircum{}";
1248 // avoid being mistaken for optional arguments
1256 // Blanks are printed before font switching.
1257 // Sure? I am not! (try nice-latex)
1258 // I am sure it's correct. LyX might be smarter
1259 // in the future, but for now, nothing wrong is
1265 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1271 Encoding const & encoding = *(runparams.encoding);
1272 char_type next = '\0';
1273 if (i + 1 < int(text_.size())) {
1274 next = text_[i + 1];
1275 if (Encodings::isCombiningChar(next)) {
1276 column += latexSurrogatePair(os, c, next, runparams) - 1;
1282 pair<docstring, bool> latex = encoding.latexChar(c);
1283 docstring nextlatex;
1284 bool nexttipas = false;
1285 string nexttipashortcut;
1286 if (next != '\0' && next != META_INSET) {
1287 nextlatex = encoding.latexChar(next).first;
1288 if (runparams.inIPA) {
1289 nexttipashortcut = Encodings::TIPAShortcut(next);
1290 nexttipas = !nexttipashortcut.empty();
1294 if (runparams.inIPA) {
1295 string const tipashortcut = Encodings::TIPAShortcut(c);
1296 if (!tipashortcut.empty()) {
1297 latex.first = from_ascii(tipashortcut);
1298 latex.second = false;
1302 if (Encodings::isKnownScriptChar(c, script)
1303 && prefixIs(latex.first, from_ascii("\\" + script)))
1304 column += writeScriptChars(os, latex.first,
1305 running_change, encoding, i) - 1;
1306 else if (latex.second
1307 && ((!prefixIs(nextlatex, '\\')
1308 && !prefixIs(nextlatex, '{')
1309 && !prefixIs(nextlatex, '}'))
1311 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1313 // Prevent eating of a following
1314 // space or command corruption by
1315 // following characters
1316 if (next == ' ' || next == '\0') {
1317 column += latex.first.length() + 1;
1318 os << latex.first << "{}";
1320 column += latex.first.length();
1321 os << latex.first << " ";
1324 column += latex.first.length() - 1;
1332 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1333 pos_type i, unsigned int & column)
1339 // In T1 encoding, these characters exist
1340 // but we should avoid ligatures
1341 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1343 os << "\\textcompwordmark{}";
1350 // soul.sty breaks with \char`\"
1351 os << "\\textquotedbl{}";
1360 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1361 pos_type /*i*/, unsigned int & /*column*/)
1377 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1378 pos_type i, unsigned int & column)
1382 // within \ttfamily, "--" is merged to "-" (no endash)
1383 // so we avoid this rather irritating ligature
1384 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1391 // everything else has to be checked separately
1392 // (depending on the encoding)
1400 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1401 /// do not apply the macro transformation.
1402 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1403 unsigned int & column, OutputParams const & runparams)
1405 // FIXME: if we have "LaTeX" with a font
1406 // change in the middle (before the 'T', then
1407 // the "TeX" part is still special cased.
1408 // Really we should only operate this on
1409 // "words" for some definition of word
1411 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1412 if (!isTextAt(special_phrases[pnr].phrase, i)
1413 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1415 if (runparams.moving_arg)
1417 os << special_phrases[pnr].macro;
1418 i += special_phrases[pnr].phrase.length() - 1;
1419 column += special_phrases[pnr].macro.length() - 1;
1426 void Paragraph::Private::validate(LaTeXFeatures & features) const
1428 if (layout_->inpreamble && inset_owner_) {
1429 bool const is_command = layout_->latextype == LATEX_COMMAND;
1430 Buffer const & buf = inset_owner_->buffer();
1431 BufferParams const & bp = buf.params();
1434 // Using a string stream here circumvents the encoding
1435 // switching machinery of odocstream. Therefore the
1436 // output is wrong if this paragraph contains content
1437 // that needs to switch encoding.
1438 odocstringstream ods;
1439 otexstream os(ods, texrow);
1441 os << '\\' << from_ascii(layout_->latexname());
1442 // we have to provide all the optional arguments here, even though
1443 // the last one is the only one we care about.
1444 // Separate handling of optional argument inset.
1445 if (layout_->optargs != 0 || layout_->reqargs != 0)
1446 latexArgInsets(*owner_, os, features.runparams(),
1447 layout_->reqargs, layout_->optargs);
1449 os << from_ascii(layout_->latexparam());
1451 docstring::size_type const length = ods.str().length();
1452 // this will output "{" at the beginning, but not at the end
1453 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1454 if (ods.str().length() > length) {
1457 string const snippet = to_utf8(ods.str());
1458 features.addPreambleSnippet(snippet);
1462 if (features.runparams().flavor == OutputParams::HTML
1463 && layout_->htmltitle()) {
1464 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1467 // check the params.
1468 if (!params_.spacing().isDefault())
1469 features.require("setspace");
1472 features.useLayout(layout_->name());
1475 fontlist_.validate(features);
1477 // then the indentation
1478 if (!params_.leftIndent().zero())
1479 features.require("ParagraphLeftIndent");
1482 InsetList::const_iterator icit = insetlist_.begin();
1483 InsetList::const_iterator iend = insetlist_.end();
1484 for (; icit != iend; ++icit) {
1486 icit->inset->validate(features);
1487 if (layout_->needprotect &&
1488 icit->inset->lyxCode() == FOOT_CODE)
1489 features.require("NeedLyXFootnoteCode");
1493 // then the contents
1494 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1495 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1496 if (!special_phrases[pnr].builtin
1497 && isTextAt(special_phrases[pnr].phrase, i)) {
1498 features.require(special_phrases[pnr].phrase);
1502 Encodings::validate(text_[i], features);
1506 /////////////////////////////////////////////////////////////////////
1510 /////////////////////////////////////////////////////////////////////
1513 Layout const emptyParagraphLayout;
1516 Paragraph::Paragraph()
1517 : d(new Paragraph::Private(this, emptyParagraphLayout))
1524 Paragraph::Paragraph(Paragraph const & par)
1525 : itemdepth(par.itemdepth),
1526 d(new Paragraph::Private(*par.d, this))
1532 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1533 : itemdepth(par.itemdepth),
1534 d(new Paragraph::Private(*par.d, this, beg, end))
1540 Paragraph & Paragraph::operator=(Paragraph const & par)
1542 // needed as we will destroy the private part before copying it
1544 itemdepth = par.itemdepth;
1548 d = new Private(*par.d, this);
1555 Paragraph::~Paragraph()
1564 // this shall be called just before every "os << ..." action.
1565 void flushString(ostream & os, docstring & s)
1574 void Paragraph::write(ostream & os, BufferParams const & bparams,
1575 depth_type & dth) const
1577 // The beginning or end of a deeper (i.e. nested) area?
1578 if (dth != d->params_.depth()) {
1579 if (d->params_.depth() > dth) {
1580 while (d->params_.depth() > dth) {
1581 os << "\n\\begin_deeper";
1585 while (d->params_.depth() < dth) {
1586 os << "\n\\end_deeper";
1592 // First write the layout
1593 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1595 d->params_.write(os);
1597 Font font1(inherit_font, bparams.language);
1599 Change running_change = Change(Change::UNCHANGED);
1601 // this string is used as a buffer to avoid repetitive calls
1602 // to to_utf8(), which turn out to be expensive (JMarc)
1603 docstring write_buffer;
1606 for (pos_type i = 0; i <= size(); ++i) {
1608 Change const change = lookupChange(i);
1609 if (change != running_change)
1610 flushString(os, write_buffer);
1611 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1612 running_change = change;
1617 // Write font changes
1618 Font font2 = getFontSettings(bparams, i);
1619 if (font2 != font1) {
1620 flushString(os, write_buffer);
1621 font2.lyxWriteChanges(font1, os);
1626 char_type const c = d->text_[i];
1629 if (Inset const * inset = getInset(i)) {
1630 flushString(os, write_buffer);
1631 if (inset->directWrite()) {
1632 // international char, let it write
1633 // code directly so it's shorter in
1639 os << "\\begin_inset ";
1641 os << "\n\\end_inset\n\n";
1647 flushString(os, write_buffer);
1648 os << "\n\\backslash\n";
1652 flushString(os, write_buffer);
1653 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1660 if ((column > 70 && c == ' ')
1662 flushString(os, write_buffer);
1666 // this check is to amend a bug. LyX sometimes
1667 // inserts '\0' this could cause problems.
1669 write_buffer.push_back(c);
1671 LYXERR0("NUL char in structure.");
1677 flushString(os, write_buffer);
1678 os << "\n\\end_layout\n";
1682 void Paragraph::validate(LaTeXFeatures & features) const
1684 d->validate(features);
1688 void Paragraph::insert(pos_type start, docstring const & str,
1689 Font const & font, Change const & change)
1691 for (size_t i = 0, n = str.size(); i != n ; ++i)
1692 insertChar(start + i, str[i], font, change);
1696 void Paragraph::appendChar(char_type c, Font const & font,
1697 Change const & change)
1700 d->changes_.insert(change, d->text_.size());
1701 // when appending characters, no need to update tables
1702 d->text_.push_back(c);
1703 setFont(d->text_.size() - 1, font);
1704 d->requestSpellCheck(d->text_.size() - 1);
1708 void Paragraph::appendString(docstring const & s, Font const & font,
1709 Change const & change)
1711 pos_type end = s.size();
1712 size_t oldsize = d->text_.size();
1713 size_t newsize = oldsize + end;
1714 size_t capacity = d->text_.capacity();
1715 if (newsize >= capacity)
1716 d->text_.reserve(max(capacity + 100, newsize));
1718 // when appending characters, no need to update tables
1721 // FIXME: Optimize this!
1722 for (size_t i = oldsize; i != newsize; ++i) {
1724 d->changes_.insert(change, i);
1725 d->requestSpellCheck(i);
1727 d->fontlist_.set(oldsize, font);
1728 d->fontlist_.set(newsize - 1, font);
1732 void Paragraph::insertChar(pos_type pos, char_type c,
1735 d->insertChar(pos, c, Change(trackChanges ?
1736 Change::INSERTED : Change::UNCHANGED));
1740 void Paragraph::insertChar(pos_type pos, char_type c,
1741 Font const & font, bool trackChanges)
1743 d->insertChar(pos, c, Change(trackChanges ?
1744 Change::INSERTED : Change::UNCHANGED));
1749 void Paragraph::insertChar(pos_type pos, char_type c,
1750 Font const & font, Change const & change)
1752 d->insertChar(pos, c, change);
1757 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1758 Font const & font, Change const & change)
1760 bool const success = insertInset(pos, inset, change);
1761 // Set the font/language of the inset...
1767 void Paragraph::resetFonts(Font const & font)
1769 d->fontlist_.clear();
1770 d->fontlist_.set(0, font);
1771 d->fontlist_.set(d->text_.size() - 1, font);
1774 // Gets uninstantiated font setting at position.
1775 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1779 LYXERR0("pos: " << pos << " size: " << size());
1780 LASSERT(pos <= size(), /**/);
1783 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1784 if (cit != d->fontlist_.end())
1787 if (pos == size() && !empty())
1788 return getFontSettings(bparams, pos - 1);
1790 // Optimisation: avoid a full font instantiation if there is no
1791 // language change from previous call.
1792 static Font previous_font;
1793 static Language const * previous_lang = 0;
1794 Language const * lang = getParLanguage(bparams);
1795 if (lang != previous_lang) {
1796 previous_lang = lang;
1797 previous_font = Font(inherit_font, lang);
1799 return previous_font;
1803 FontSpan Paragraph::fontSpan(pos_type pos) const
1805 LASSERT(pos <= size(), /**/);
1808 FontList::const_iterator cit = d->fontlist_.begin();
1809 FontList::const_iterator end = d->fontlist_.end();
1810 for (; cit != end; ++cit) {
1811 if (cit->pos() >= pos) {
1812 if (pos >= beginOfBody())
1813 return FontSpan(max(start, beginOfBody()),
1816 return FontSpan(start,
1817 min(beginOfBody() - 1,
1820 start = cit->pos() + 1;
1823 // This should not happen, but if so, we take no chances.
1824 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1825 return FontSpan(pos, pos);
1829 // Gets uninstantiated font setting at position 0
1830 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1832 if (!empty() && !d->fontlist_.empty())
1833 return d->fontlist_.begin()->font();
1835 // Optimisation: avoid a full font instantiation if there is no
1836 // language change from previous call.
1837 static Font previous_font;
1838 static Language const * previous_lang = 0;
1839 if (bparams.language != previous_lang) {
1840 previous_lang = bparams.language;
1841 previous_font = Font(inherit_font, bparams.language);
1844 return previous_font;
1848 // Gets the fully instantiated font at a given position in a paragraph
1849 // This is basically the same function as Text::GetFont() in text2.cpp.
1850 // The difference is that this one is used for generating the LaTeX file,
1851 // and thus cosmetic "improvements" are disallowed: This has to deliver
1852 // the true picture of the buffer. (Asger)
1853 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1854 Font const & outerfont) const
1856 LASSERT(pos >= 0, /**/);
1858 Font font = getFontSettings(bparams, pos);
1860 pos_type const body_pos = beginOfBody();
1861 FontInfo & fi = font.fontInfo();
1863 fi.realize(d->layout_->labelfont);
1865 fi.realize(d->layout_->font);
1867 fi.realize(outerfont.fontInfo());
1868 fi.realize(bparams.getFont().fontInfo());
1874 Font const Paragraph::getLabelFont
1875 (BufferParams const & bparams, Font const & outerfont) const
1877 FontInfo tmpfont = d->layout_->labelfont;
1878 tmpfont.realize(outerfont.fontInfo());
1879 tmpfont.realize(bparams.getFont().fontInfo());
1880 return Font(tmpfont, getParLanguage(bparams));
1884 Font const Paragraph::getLayoutFont
1885 (BufferParams const & bparams, Font const & outerfont) const
1887 FontInfo tmpfont = d->layout_->font;
1888 tmpfont.realize(outerfont.fontInfo());
1889 tmpfont.realize(bparams.getFont().fontInfo());
1890 return Font(tmpfont, getParLanguage(bparams));
1894 /// Returns the height of the highest font in range
1895 FontSize Paragraph::highestFontInRange
1896 (pos_type startpos, pos_type endpos, FontSize def_size) const
1898 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1902 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1904 char_type c = d->text_[pos];
1905 if (!lyxrc.rtl_support || !getFontSettings(bparams, pos).isRightToLeft())
1908 // FIXME: The arabic special casing is due to the difference of arabic
1909 // round brackets input introduced in r18599. Check if this should be
1910 // unified with Hebrew or at least if all bracket types should be
1911 // handled the same (file format change in either case).
1912 string const & lang = getFontSettings(bparams, pos).language()->lang();
1913 bool const arabic = lang == "arabic_arabtex" || lang == "arabic_arabi"
1918 uc = arabic ? c : ')';
1921 uc = arabic ? c : '(';
1947 void Paragraph::setFont(pos_type pos, Font const & font)
1949 LASSERT(pos <= size(), /**/);
1951 // First, reduce font against layout/label font
1952 // Update: The setCharFont() routine in text2.cpp already
1953 // reduces font, so we don't need to do that here. (Asger)
1955 d->fontlist_.set(pos, font);
1959 void Paragraph::makeSameLayout(Paragraph const & par)
1961 d->layout_ = par.d->layout_;
1962 d->params_ = par.d->params_;
1966 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1968 if (isFreeSpacing())
1974 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1975 if (eraseChar(pos, trackChanges))
1981 return count > 0 || pos > 0;
1985 bool Paragraph::hasSameLayout(Paragraph const & par) const
1987 return par.d->layout_ == d->layout_
1988 && d->params_.sameLayout(par.d->params_);
1992 depth_type Paragraph::getDepth() const
1994 return d->params_.depth();
1998 depth_type Paragraph::getMaxDepthAfter() const
2000 if (d->layout_->isEnvironment())
2001 return d->params_.depth() + 1;
2003 return d->params_.depth();
2007 char Paragraph::getAlign() const
2009 if (d->params_.align() == LYX_ALIGN_LAYOUT)
2010 return d->layout_->align;
2012 return d->params_.align();
2016 docstring const & Paragraph::labelString() const
2018 return d->params_.labelString();
2022 // the next two functions are for the manual labels
2023 docstring const Paragraph::getLabelWidthString() const
2025 if (d->layout_->margintype == MARGIN_MANUAL
2026 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2027 return d->params_.labelWidthString();
2029 return _("Senseless with this layout!");
2033 void Paragraph::setLabelWidthString(docstring const & s)
2035 d->params_.labelWidthString(s);
2039 docstring Paragraph::expandLabel(Layout const & layout,
2040 BufferParams const & bparams) const
2042 return expandParagraphLabel(layout, bparams, true);
2046 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2047 BufferParams const & bparams) const
2049 return expandParagraphLabel(layout, bparams, false);
2053 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2054 BufferParams const & bparams, bool process_appendix) const
2056 DocumentClass const & tclass = bparams.documentClass();
2057 string const & lang = getParLanguage(bparams)->code();
2058 bool const in_appendix = process_appendix && d->params_.appendix();
2059 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2061 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
2062 && !layout.counter.empty())
2063 return tclass.counters().theCounter(layout.counter, lang);
2065 // handle 'inherited level parts' in 'fmt',
2066 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2067 size_t const i = fmt.find('@', 0);
2068 if (i != docstring::npos) {
2069 size_t const j = fmt.find('@', i + 1);
2070 if (j != docstring::npos) {
2071 docstring parent(fmt, i + 1, j - i - 1);
2072 docstring label = from_ascii("??");
2073 if (tclass.hasLayout(parent))
2074 docstring label = expandParagraphLabel(tclass[parent], bparams,
2076 fmt = docstring(fmt, 0, i) + label
2077 + docstring(fmt, j + 1, docstring::npos);
2081 return tclass.counters().counterLabel(fmt, lang);
2085 void Paragraph::applyLayout(Layout const & new_layout)
2087 d->layout_ = &new_layout;
2088 LyXAlignment const oldAlign = d->params_.align();
2090 if (!(oldAlign & d->layout_->alignpossible)) {
2091 frontend::Alert::warning(_("Alignment not permitted"),
2092 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2093 d->params_.align(LYX_ALIGN_LAYOUT);
2098 pos_type Paragraph::beginOfBody() const
2100 return d->begin_of_body_;
2104 void Paragraph::setBeginOfBody()
2106 if (d->layout_->labeltype != LABEL_MANUAL) {
2107 d->begin_of_body_ = 0;
2111 // Unroll the first two cycles of the loop
2112 // and remember the previous character to
2113 // remove unnecessary getChar() calls
2115 pos_type end = size();
2116 if (i < end && !isNewline(i)) {
2118 char_type previous_char = 0;
2121 previous_char = d->text_[i];
2122 if (!isNewline(i)) {
2124 while (i < end && previous_char != ' ') {
2129 previous_char = temp;
2135 d->begin_of_body_ = i;
2139 bool Paragraph::allowParagraphCustomization() const
2141 return inInset().allowParagraphCustomization();
2145 bool Paragraph::usePlainLayout() const
2147 return inInset().usePlainLayout();
2151 bool Paragraph::isPassThru() const
2153 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2158 // paragraphs inside floats need different alignment tags to avoid
2161 bool noTrivlistCentering(InsetCode code)
2163 return code == FLOAT_CODE
2164 || code == WRAP_CODE
2165 || code == CELL_CODE;
2169 string correction(string const & orig)
2171 if (orig == "flushleft")
2172 return "raggedright";
2173 if (orig == "flushright")
2174 return "raggedleft";
2175 if (orig == "center")
2181 string const corrected_env(string const & suffix, string const & env,
2182 InsetCode code, bool const lastpar)
2184 string output = suffix + "{";
2185 if (noTrivlistCentering(code)) {
2187 // the last paragraph in non-trivlist-aligned
2188 // context is special (to avoid unwanted whitespace)
2189 if (suffix == "\\begin")
2190 return "\\" + correction(env) + "{}";
2193 output += correction(env);
2197 if (suffix == "\\begin")
2203 void adjust_column(string const & str, int & column)
2205 if (!contains(str, "\n"))
2206 column += str.size();
2209 column = rsplit(str, tmp, '\n').size();
2216 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2217 otexstream & os, OutputParams const & runparams) const
2221 if (params_.noindent() && !layout_->pass_thru) {
2222 os << "\\noindent ";
2226 LyXAlignment const curAlign = params_.align();
2228 if (curAlign == layout_->align)
2232 case LYX_ALIGN_NONE:
2233 case LYX_ALIGN_BLOCK:
2234 case LYX_ALIGN_LAYOUT:
2235 case LYX_ALIGN_SPECIAL:
2236 case LYX_ALIGN_DECIMAL:
2238 case LYX_ALIGN_LEFT:
2239 case LYX_ALIGN_RIGHT:
2240 case LYX_ALIGN_CENTER:
2241 if (runparams.moving_arg) {
2248 string const begin_tag = "\\begin";
2249 InsetCode code = ownerCode();
2250 bool const lastpar = runparams.isLastPar;
2253 case LYX_ALIGN_NONE:
2254 case LYX_ALIGN_BLOCK:
2255 case LYX_ALIGN_LAYOUT:
2256 case LYX_ALIGN_SPECIAL:
2257 case LYX_ALIGN_DECIMAL:
2259 case LYX_ALIGN_LEFT: {
2261 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2262 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2264 output = corrected_env(begin_tag, "flushright", code, lastpar);
2265 os << from_ascii(output);
2266 adjust_column(output, column);
2268 } case LYX_ALIGN_RIGHT: {
2270 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2271 output = corrected_env(begin_tag, "flushright", code, lastpar);
2273 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2274 os << from_ascii(output);
2275 adjust_column(output, column);
2277 } case LYX_ALIGN_CENTER: {
2279 output = corrected_env(begin_tag, "center", code, lastpar);
2280 os << from_ascii(output);
2281 adjust_column(output, column);
2290 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2291 otexstream & os, OutputParams const & runparams) const
2293 LyXAlignment const curAlign = params_.align();
2295 if (curAlign == layout_->align)
2299 case LYX_ALIGN_NONE:
2300 case LYX_ALIGN_BLOCK:
2301 case LYX_ALIGN_LAYOUT:
2302 case LYX_ALIGN_SPECIAL:
2303 case LYX_ALIGN_DECIMAL:
2305 case LYX_ALIGN_LEFT:
2306 case LYX_ALIGN_RIGHT:
2307 case LYX_ALIGN_CENTER:
2308 if (runparams.moving_arg)
2314 string const end_tag = "\n\\par\\end";
2315 InsetCode code = ownerCode();
2316 bool const lastpar = runparams.isLastPar;
2319 case LYX_ALIGN_NONE:
2320 case LYX_ALIGN_BLOCK:
2321 case LYX_ALIGN_LAYOUT:
2322 case LYX_ALIGN_SPECIAL:
2323 case LYX_ALIGN_DECIMAL:
2325 case LYX_ALIGN_LEFT: {
2326 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2327 output = corrected_env(end_tag, "flushleft", code, lastpar);
2329 output = corrected_env(end_tag, "flushright", code, lastpar);
2330 os << from_ascii(output);
2332 } case LYX_ALIGN_RIGHT: {
2333 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2334 output = corrected_env(end_tag, "flushright", code, lastpar);
2336 output = corrected_env(end_tag, "flushleft", code, lastpar);
2337 os << from_ascii(output);
2339 } case LYX_ALIGN_CENTER: {
2340 output = corrected_env(end_tag, "center", code, lastpar);
2341 os << from_ascii(output);
2346 return !output.empty() || lastpar;
2350 // This one spits out the text of the paragraph
2351 void Paragraph::latex(BufferParams const & bparams,
2352 Font const & outerfont,
2354 OutputParams const & runparams,
2355 int start_pos, int end_pos, bool force) const
2357 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2359 // FIXME This check should not be needed. Perhaps issue an
2360 // error if it triggers.
2361 Layout const & style = inInset().forcePlainLayout() ?
2362 bparams.documentClass().plainLayout() : *d->layout_;
2364 if (!force && style.inpreamble)
2367 bool const allowcust = allowParagraphCustomization();
2369 // Current base font for all inherited font changes, without any
2370 // change caused by an individual character, except for the language:
2371 // It is set to the language of the first character.
2372 // As long as we are in the label, this font is the base font of the
2373 // label. Before the first body character it is set to the base font
2377 // Maybe we have to create a optional argument.
2378 pos_type body_pos = beginOfBody();
2379 unsigned int column = 0;
2382 // the optional argument is kept in curly brackets in
2383 // case it contains a ']'
2384 // This is not strictly needed, but if this is changed it
2385 // would be a file format change, and tex2lyx would need
2386 // to be adjusted, since it unconditionally removes the
2387 // braces when it parses \item.
2390 basefont = getLabelFont(bparams, outerfont);
2392 basefont = getLayoutFont(bparams, outerfont);
2395 // Which font is currently active?
2396 Font running_font(basefont);
2397 // Do we have an open font change?
2398 bool open_font = false;
2400 Change runningChange = Change(Change::UNCHANGED);
2402 Encoding const * const prev_encoding = runparams.encoding;
2404 os.texrow().start(id(), 0);
2406 // if the paragraph is empty, the loop will not be entered at all
2408 if (style.isCommand()) {
2413 column += d->startTeXParParams(bparams, os, runparams);
2416 for (pos_type i = 0; i < size(); ++i) {
2417 // First char in paragraph or after label?
2418 if (i == body_pos) {
2421 column += running_font.latexWriteEndChanges(
2422 os, bparams, runparams,
2423 basefont, basefont);
2426 basefont = getLayoutFont(bparams, outerfont);
2427 running_font = basefont;
2429 column += Changes::latexMarkChange(os, bparams,
2430 runningChange, Change(Change::UNCHANGED),
2432 runningChange = Change(Change::UNCHANGED);
2437 if (style.isCommand()) {
2443 column += d->startTeXParParams(bparams, os,
2447 Change const & change = runparams.inDeletedInset
2448 ? runparams.changeOfDeletedInset : lookupChange(i);
2450 if (bparams.outputChanges && runningChange != change) {
2452 column += running_font.latexWriteEndChanges(
2453 os, bparams, runparams, basefont, basefont);
2456 basefont = getLayoutFont(bparams, outerfont);
2457 running_font = basefont;
2459 column += Changes::latexMarkChange(os, bparams, runningChange,
2461 runningChange = change;
2464 // do not output text which is marked deleted
2465 // if change tracking output is disabled
2466 if (!bparams.outputChanges && change.deleted()) {
2472 // Fully instantiated font
2473 Font const font = getFont(bparams, i, outerfont);
2475 Font const last_font = running_font;
2477 // Do we need to close the previous font?
2479 (font != running_font ||
2480 font.language() != running_font.language()))
2482 column += running_font.latexWriteEndChanges(
2483 os, bparams, runparams, basefont,
2484 (i == body_pos-1) ? basefont : font);
2485 running_font = basefont;
2489 string const running_lang = runparams.use_polyglossia ?
2490 running_font.language()->polyglossia() : running_font.language()->babel();
2491 // close babel's font environment before opening CJK.
2492 string const lang_end_command = runparams.use_polyglossia ?
2493 "\\end{$$lang}" : lyxrc.language_command_end;
2494 if (!running_lang.empty() &&
2495 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();
2503 // Switch file encoding if necessary (and allowed)
2504 if (!runparams.pass_thru && !style.pass_thru &&
2505 runparams.encoding->package() != Encoding::none &&
2506 font.language()->encoding()->package() != Encoding::none) {
2507 pair<bool, int> const enc_switch =
2508 switchEncoding(os.os(), bparams, runparams,
2509 *(font.language()->encoding()));
2510 if (enc_switch.first) {
2511 column += enc_switch.second;
2512 runparams.encoding = font.language()->encoding();
2516 char_type const c = d->text_[i];
2518 // Do we need to change font?
2519 if ((font != running_font ||
2520 font.language() != running_font.language()) &&
2523 odocstringstream ods;
2524 column += font.latexWriteStartChanges(ods, bparams,
2525 runparams, basefont,
2527 running_font = font;
2529 docstring fontchange = ods.str();
2530 // check whether the fontchange ends with a \\textcolor
2531 // modifier and the text starts with a space (bug 4473)
2532 docstring const last_modifier = rsplit(fontchange, '\\');
2533 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2534 os << fontchange << from_ascii("{}");
2535 // check if the fontchange ends with a trailing blank
2536 // (like "\small " (see bug 3382)
2537 else if (suffixIs(fontchange, ' ') && c == ' ')
2538 os << fontchange.substr(0, fontchange.size() - 1)
2539 << from_ascii("{}");
2544 // FIXME: think about end_pos implementation...
2545 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2546 // FIXME: integrate this case in latexSpecialChar
2547 // Do not print the separation of the optional argument
2548 // if style.pass_thru is false. This works because
2549 // latexSpecialChar ignores spaces if
2550 // style.pass_thru is false.
2551 if (i != body_pos - 1) {
2552 if (d->simpleTeXBlanks(runparams, os,
2553 i, column, font, style)) {
2554 // A surrogate pair was output. We
2555 // must not call latexSpecialChar
2556 // in this iteration, since it would output
2557 // the combining character again.
2564 OutputParams rp = runparams;
2565 rp.free_spacing = style.free_spacing;
2566 rp.local_font = &font;
2567 rp.intitle = style.intitle;
2569 // Two major modes: LaTeX or plain
2570 // Handle here those cases common to both modes
2571 // and then split to handle the two modes separately.
2572 if (c == META_INSET) {
2573 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2574 d->latexInset(bparams, os, rp, running_font,
2575 basefont, outerfont, open_font,
2576 runningChange, style, i, column);
2579 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2581 d->latexSpecialChar(os, bparams, rp, running_font, runningChange,
2582 style, i, end_pos, column);
2583 } catch (EncodingException & e) {
2584 if (runparams.dryrun) {
2585 os << "<" << _("LyX Warning: ")
2586 << _("uncodable character") << " '";
2590 // add location information and throw again.
2599 // Set the encoding to that returned from latexSpecialChar (see
2600 // comment for encoding member in OutputParams.h)
2601 runparams.encoding = rp.encoding;
2604 // If we have an open font definition, we have to close it
2606 #ifdef FIXED_LANGUAGE_END_DETECTION
2608 running_font.latexWriteEndChanges(os, bparams,
2609 runparams, basefont,
2610 next_->getFont(bparams, 0, outerfont));
2612 running_font.latexWriteEndChanges(os, bparams,
2613 runparams, basefont, basefont);
2616 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2617 //FIXME: there as we start another \selectlanguage with the next paragraph if
2618 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2619 running_font.latexWriteEndChanges(os, bparams, runparams,
2620 basefont, basefont);
2624 column += Changes::latexMarkChange(os, bparams, runningChange,
2625 Change(Change::UNCHANGED), runparams);
2627 // Needed if there is an optional argument but no contents.
2628 if (body_pos > 0 && body_pos == size()) {
2632 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2633 && runparams.encoding != prev_encoding) {
2634 runparams.encoding = prev_encoding;
2635 if (!runparams.isFullUnicode())
2636 os << setEncoding(prev_encoding->iconvName());
2639 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2643 bool Paragraph::emptyTag() const
2645 for (pos_type i = 0; i < size(); ++i) {
2646 if (Inset const * inset = getInset(i)) {
2647 InsetCode lyx_code = inset->lyxCode();
2648 // FIXME testing like that is wrong. What is
2650 if (lyx_code != TOC_CODE &&
2651 lyx_code != INCLUDE_CODE &&
2652 lyx_code != GRAPHICS_CODE &&
2653 lyx_code != ERT_CODE &&
2654 lyx_code != LISTINGS_CODE &&
2655 lyx_code != FLOAT_CODE &&
2656 lyx_code != TABULAR_CODE) {
2660 char_type c = d->text_[i];
2661 if (c != ' ' && c != '\t')
2669 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2672 for (pos_type i = 0; i < size(); ++i) {
2673 if (Inset const * inset = getInset(i)) {
2674 InsetCode lyx_code = inset->lyxCode();
2675 if (lyx_code == LABEL_CODE) {
2676 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2677 docstring const & id = il->getParam("name");
2678 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2686 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2690 for (i = 0; i < size(); ++i) {
2691 if (Inset const * inset = getInset(i)) {
2692 inset->docbook(os, runparams);
2694 char_type c = d->text_[i];
2697 os << sgml::escapeChar(c);
2704 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2708 for (i = 0; i < size(); ++i) {
2709 if (Inset const * inset = getInset(i)) {
2710 inset->xhtml(xs, runparams);
2712 char_type c = d->text_[i];
2722 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2725 pos_type size = text_.size();
2726 for (pos_type i = initial; i < size; ++i) {
2727 Font font = owner_->getFont(buf.params(), i, outerfont);
2728 if (text_[i] == META_INSET)
2730 if (i != initial && font != font_old)
2739 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2741 OutputParams const & runparams,
2742 Font const & outerfont,
2743 pos_type initial) const
2745 bool emph_flag = false;
2747 Layout const & style = *d->layout_;
2749 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2751 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2754 // parsing main loop
2755 for (pos_type i = initial; i < size(); ++i) {
2756 Font font = getFont(buf.params(), i, outerfont);
2758 // handle <emphasis> tag
2759 if (font_old.emph() != font.fontInfo().emph()) {
2760 if (font.fontInfo().emph() == FONT_ON) {
2763 } else if (i != initial) {
2764 os << "</emphasis>";
2769 if (Inset const * inset = getInset(i)) {
2770 inset->docbook(os, runparams);
2772 char_type c = d->text_[i];
2774 if (style.pass_thru)
2777 os << sgml::escapeChar(c);
2779 font_old = font.fontInfo();
2783 os << "</emphasis>";
2786 if (style.free_spacing)
2788 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2793 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2795 OutputParams const & runparams,
2796 Font const & outerfont,
2797 pos_type initial) const
2801 bool emph_flag = false;
2802 bool bold_flag = false;
2804 Layout const & style = *d->layout_;
2806 xs.startParagraph(allowEmpty());
2808 if (!runparams.for_toc && runparams.html_make_pars) {
2809 // generate a magic label for this paragraph
2810 string const attr = "id='" + magicLabel() + "'";
2811 xs << html::CompTag("a", attr);
2815 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2817 // parsing main loop
2818 for (pos_type i = initial; i < size(); ++i) {
2819 // let's not show deleted material in the output
2823 Font font = getFont(buf.params(), i, outerfont);
2826 if (font_old.emph() != font.fontInfo().emph()) {
2827 if (font.fontInfo().emph() == FONT_ON) {
2828 xs << html::StartTag("em");
2830 } else if (emph_flag && i != initial) {
2831 xs << html::EndTag("em");
2836 if (font_old.series() != font.fontInfo().series()) {
2837 if (font.fontInfo().series() == BOLD_SERIES) {
2838 xs << html::StartTag("strong");
2840 } else if (bold_flag && i != initial) {
2841 xs << html::EndTag("strong");
2846 // Other such tags? What about the other text ranges?
2848 Inset const * inset = getInset(i);
2850 if (!runparams.for_toc || inset->isInToc()) {
2851 OutputParams np = runparams;
2852 if (!inset->getLayout().htmlisblock())
2853 np.html_in_par = true;
2854 retval += inset->xhtml(xs, np);
2857 char_type c = d->text_[getUChar(buf.params(), i)];
2859 if (style.pass_thru)
2861 else if (c == '-') {
2864 if (j < size() && d->text_[j] == '-') {
2866 if (j < size() && d->text_[j] == '-') {
2867 str += from_ascii("—");
2870 str += from_ascii("–");
2876 // We don't want to escape the entities. Note that
2877 // it is safe to do this, since str can otherwise
2878 // only be "-". E.g., it can't be "<".
2879 xs << XHTMLStream::ESCAPE_NONE << str;
2883 font_old = font.fontInfo();
2892 bool Paragraph::isHfill(pos_type pos) const
2894 Inset const * inset = getInset(pos);
2895 return inset && (inset->lyxCode() == SPACE_CODE &&
2896 inset->isStretchableSpace());
2900 bool Paragraph::isNewline(pos_type pos) const
2902 Inset const * inset = getInset(pos);
2903 return inset && inset->lyxCode() == NEWLINE_CODE;
2907 bool Paragraph::isLineSeparator(pos_type pos) const
2909 char_type const c = d->text_[pos];
2910 if (isLineSeparatorChar(c))
2912 Inset const * inset = getInset(pos);
2913 return inset && inset->isLineSeparator();
2917 bool Paragraph::isWordSeparator(pos_type pos) const
2921 if (Inset const * inset = getInset(pos))
2922 return !inset->isLetter();
2923 // if we have a hard hyphen (no en- or emdash) or apostrophe
2924 // we pass this to the spell checker
2925 // FIXME: this method is subject to change, visit
2926 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2927 // to get an impression how complex this is.
2928 if (isHardHyphenOrApostrophe(pos))
2930 char_type const c = d->text_[pos];
2931 // We want to pass the escape chars to the spellchecker
2932 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2933 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2937 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2939 pos_type const psize = size();
2942 char_type const c = d->text_[pos];
2943 if (c != '-' && c != '\'')
2945 int nextpos = pos + 1;
2946 int prevpos = pos > 0 ? pos - 1 : 0;
2947 if ((nextpos == psize || isSpace(nextpos))
2948 && (pos == 0 || isSpace(prevpos)))
2951 || ((nextpos == psize || d->text_[nextpos] != '-')
2952 && (pos == 0 || d->text_[prevpos] != '-'));
2956 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2959 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2963 bool Paragraph::isChar(pos_type pos) const
2965 if (Inset const * inset = getInset(pos))
2966 return inset->isChar();
2967 char_type const c = d->text_[pos];
2968 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2972 bool Paragraph::isSpace(pos_type pos) const
2974 if (Inset const * inset = getInset(pos))
2975 return inset->isSpace();
2976 char_type const c = d->text_[pos];
2977 return lyx::isSpace(c);
2982 Paragraph::getParLanguage(BufferParams const & bparams) const
2985 return getFirstFontSettings(bparams).language();
2986 // FIXME: we should check the prev par as well (Lgb)
2987 return bparams.language;
2991 bool Paragraph::isRTL(BufferParams const & bparams) const
2993 return lyxrc.rtl_support
2994 && getParLanguage(bparams)->rightToLeft()
2995 && !inInset().getLayout().forceLTR();
2999 void Paragraph::changeLanguage(BufferParams const & bparams,
3000 Language const * from, Language const * to)
3002 // change language including dummy font change at the end
3003 for (pos_type i = 0; i <= size(); ++i) {
3004 Font font = getFontSettings(bparams, i);
3005 if (font.language() == from) {
3006 font.setLanguage(to);
3008 d->requestSpellCheck(i);
3014 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3016 Language const * doc_language = bparams.language;
3017 FontList::const_iterator cit = d->fontlist_.begin();
3018 FontList::const_iterator end = d->fontlist_.end();
3020 for (; cit != end; ++cit)
3021 if (cit->font().language() != ignore_language &&
3022 cit->font().language() != latex_language &&
3023 cit->font().language() != doc_language)
3029 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3031 FontList::const_iterator cit = d->fontlist_.begin();
3032 FontList::const_iterator end = d->fontlist_.end();
3034 for (; cit != end; ++cit) {
3035 Language const * lang = cit->font().language();
3036 if (lang != ignore_language &&
3037 lang != latex_language)
3038 languages.insert(lang);
3043 docstring Paragraph::asString(int options) const
3045 return asString(0, size(), options);
3049 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
3051 odocstringstream os;
3054 && options & AS_STR_LABEL
3055 && !d->params_.labelString().empty())
3056 os << d->params_.labelString() << ' ';
3058 for (pos_type i = beg; i < end; ++i) {
3059 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3061 char_type const c = d->text_[i];
3062 if (isPrintable(c) || c == '\t'
3063 || (c == '\n' && (options & AS_STR_NEWLINES)))
3065 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3066 getInset(i)->toString(os);
3067 if (getInset(i)->asInsetMath())
3076 void Paragraph::forToc(docstring & os, size_t maxlen) const
3078 if (!d->params_.labelString().empty())
3079 os += d->params_.labelString() + ' ';
3080 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3083 char_type const c = d->text_[i];
3086 else if (c == '\t' || c == '\n')
3088 else if (c == META_INSET)
3089 getInset(i)->forToc(os, maxlen);
3094 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3096 odocstringstream os;
3099 && options & AS_STR_LABEL
3100 && !d->params_.labelString().empty())
3101 os << d->params_.labelString() << ' ';
3103 for (pos_type i = beg; i < end; ++i) {
3104 char_type const c = d->text_[i];
3105 if (isPrintable(c) || c == '\t'
3106 || (c == '\n' && (options & AS_STR_NEWLINES)))
3108 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3109 getInset(i)->plaintext(os, runparams);
3117 void Paragraph::setInsetOwner(Inset const * inset)
3119 d->inset_owner_ = inset;
3123 int Paragraph::id() const
3129 void Paragraph::setId(int id)
3135 Layout const & Paragraph::layout() const
3141 void Paragraph::setLayout(Layout const & layout)
3143 d->layout_ = &layout;
3147 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3149 setLayout(tc.defaultLayout());
3153 void Paragraph::setPlainLayout(DocumentClass const & tc)
3155 setLayout(tc.plainLayout());
3159 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3161 if (usePlainLayout())
3162 setPlainLayout(tclass);
3164 setDefaultLayout(tclass);
3168 Inset const & Paragraph::inInset() const
3170 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3171 _("Memory problem"), _("Paragraph not properly initialized")));
3172 return *d->inset_owner_;
3176 ParagraphParameters & Paragraph::params()
3182 ParagraphParameters const & Paragraph::params() const
3188 bool Paragraph::isFreeSpacing() const
3190 if (d->layout_->free_spacing)
3192 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3196 bool Paragraph::allowEmpty() const
3198 if (d->layout_->keepempty)
3200 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3204 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3206 if (!Encodings::isArabicChar(c))
3209 char_type prev_char = ' ';
3210 char_type next_char = ' ';
3212 for (pos_type i = pos - 1; i >= 0; --i) {
3213 char_type const par_char = d->text_[i];
3214 if (!Encodings::isArabicComposeChar(par_char)) {
3215 prev_char = par_char;
3220 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3221 char_type const par_char = d->text_[i];
3222 if (!Encodings::isArabicComposeChar(par_char)) {
3223 next_char = par_char;
3228 if (Encodings::isArabicChar(next_char)) {
3229 if (Encodings::isArabicChar(prev_char) &&
3230 !Encodings::isArabicSpecialChar(prev_char))
3231 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3233 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3235 if (Encodings::isArabicChar(prev_char) &&
3236 !Encodings::isArabicSpecialChar(prev_char))
3237 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3239 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3244 bool Paragraph::brokenBiblio() const
3246 // there is a problem if there is no bibitem at position 0 or
3247 // if there is another bibitem in the paragraph.
3248 return d->layout_->labeltype == LABEL_BIBLIO
3249 && (d->insetlist_.find(BIBITEM_CODE) != 0
3250 || d->insetlist_.find(BIBITEM_CODE, 1) > 0);
3254 int Paragraph::fixBiblio(Buffer const & buffer)
3256 // FIXME: What about the case where paragraph is not BIBLIO
3257 // but there is an InsetBibitem?
3258 // FIXME: when there was already an inset at 0, the return value is 1,
3259 // which does not tell whether another inset has been remove; the
3260 // cursor cannot be correctly updated.
3262 if (d->layout_->labeltype != LABEL_BIBLIO)
3265 bool const track_changes = buffer.params().trackChanges;
3266 int bibitem_pos = d->insetlist_.find(BIBITEM_CODE);
3267 bool const hasbibitem0 = bibitem_pos == 0;
3270 bibitem_pos = d->insetlist_.find(BIBITEM_CODE, 1);
3271 // There was an InsetBibitem at pos 0, and no other one => OK
3272 if (bibitem_pos == -1)
3274 // there is a bibitem at the 0 position, but since
3275 // there is a second one, we copy the second on the
3276 // first. We're assuming there are at most two of
3277 // these, which there should be.
3278 // FIXME: why does it make sense to do that rather
3279 // than keep the first? (JMarc)
3280 Inset * inset = d->insetlist_.release(bibitem_pos);
3281 eraseChar(bibitem_pos, track_changes);
3282 d->insetlist_.begin()->inset = inset;
3283 return -bibitem_pos;
3286 // We need to create an inset at the beginning
3288 if (bibitem_pos > 0) {
3289 // there was one somewhere in the paragraph, let's move it
3290 inset = d->insetlist_.release(bibitem_pos);
3291 eraseChar(bibitem_pos, track_changes);
3294 inset = new InsetBibitem(const_cast<Buffer *>(&buffer),
3295 InsetCommandParams(BIBITEM_CODE));
3297 insertInset(0, inset, Change(track_changes ? Change::INSERTED
3298 : Change::UNCHANGED));
3304 void Paragraph::checkAuthors(AuthorList const & authorList)
3306 d->changes_.checkAuthors(authorList);
3310 bool Paragraph::isChanged(pos_type pos) const
3312 return lookupChange(pos).changed();
3316 bool Paragraph::isInserted(pos_type pos) const
3318 return lookupChange(pos).inserted();
3322 bool Paragraph::isDeleted(pos_type pos) const
3324 return lookupChange(pos).deleted();
3328 InsetList const & Paragraph::insetList() const
3330 return d->insetlist_;
3334 void Paragraph::setBuffer(Buffer & b)
3336 d->insetlist_.setBuffer(b);
3340 Inset * Paragraph::releaseInset(pos_type pos)
3342 Inset * inset = d->insetlist_.release(pos);
3343 /// does not honour change tracking!
3344 eraseChar(pos, false);
3349 Inset * Paragraph::getInset(pos_type pos)
3351 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3352 ? d->insetlist_.get(pos) : 0;
3356 Inset const * Paragraph::getInset(pos_type pos) const
3358 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3359 ? d->insetlist_.get(pos) : 0;
3363 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3364 pos_type & right, TextCase action)
3366 // process sequences of modified characters; in change
3367 // tracking mode, this approach results in much better
3368 // usability than changing case on a char-by-char basis
3371 bool const trackChanges = bparams.trackChanges;
3373 bool capitalize = true;
3375 for (; pos < right; ++pos) {
3376 char_type oldChar = d->text_[pos];
3377 char_type newChar = oldChar;
3379 // ignore insets and don't play with deleted text!
3380 if (oldChar != META_INSET && !isDeleted(pos)) {
3382 case text_lowercase:
3383 newChar = lowercase(oldChar);
3385 case text_capitalization:
3387 newChar = uppercase(oldChar);
3391 case text_uppercase:
3392 newChar = uppercase(oldChar);
3397 if (isWordSeparator(pos) || isDeleted(pos)) {
3398 // permit capitalization again
3402 if (oldChar != newChar) {
3404 if (pos != right - 1)
3406 // step behind the changing area
3410 int erasePos = pos - changes.size();
3411 for (size_t i = 0; i < changes.size(); i++) {
3412 insertChar(pos, changes[i],
3413 getFontSettings(bparams,
3416 if (!eraseChar(erasePos, trackChanges)) {
3419 ++right; // expand selection
3427 int Paragraph::find(docstring const & str, bool cs, bool mw,
3428 pos_type start_pos, bool del) const
3430 pos_type pos = start_pos;
3431 int const strsize = str.length();
3433 pos_type const parsize = d->text_.size();
3434 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3435 // Ignore "invisible" letters such as ligature breaks
3436 // and hyphenation chars while searching
3437 while (pos < parsize - 1 && isInset(pos)) {
3438 odocstringstream os;
3439 getInset(pos)->toString(os);
3440 if (!getInset(pos)->isLetter() || !os.str().empty())
3444 if (cs && str[i] != d->text_[pos])
3446 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3448 if (!del && isDeleted(pos))
3455 // if necessary, check whether string matches word
3457 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3460 && !isWordSeparator(pos))
3464 return pos - start_pos;
3468 char_type Paragraph::getChar(pos_type pos) const
3470 return d->text_[pos];
3474 pos_type Paragraph::size() const
3476 return d->text_.size();
3480 bool Paragraph::empty() const
3482 return d->text_.empty();
3486 bool Paragraph::isInset(pos_type pos) const
3488 return d->text_[pos] == META_INSET;
3492 bool Paragraph::isSeparator(pos_type pos) const
3494 //FIXME: Are we sure this can be the only separator?
3495 return d->text_[pos] == ' ';
3499 void Paragraph::deregisterWords()
3501 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3502 Private::LangWordsMap::const_iterator ite = d->words_.end();
3503 for (; itl != ite; ++itl) {
3504 WordList * wl = theWordList(itl->first);
3505 Private::Words::const_iterator it = (itl->second).begin();
3506 Private::Words::const_iterator et = (itl->second).end();
3507 for (; it != et; ++it)
3514 void Paragraph::locateWord(pos_type & from, pos_type & to,
3515 word_location const loc) const
3518 case WHOLE_WORD_STRICT:
3519 if (from == 0 || from == size()
3520 || isWordSeparator(from)
3521 || isWordSeparator(from - 1)) {
3525 // no break here, we go to the next
3528 // If we are already at the beginning of a word, do nothing
3529 if (!from || isWordSeparator(from - 1))
3531 // no break here, we go to the next
3534 // always move the cursor to the beginning of previous word
3535 while (from && !isWordSeparator(from - 1))
3539 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3542 // no need to move the 'from' cursor
3546 while (to < size() && !isWordSeparator(to))
3551 void Paragraph::collectWords()
3553 pos_type n = size();
3554 for (pos_type pos = 0; pos < n; ++pos) {
3555 if (isWordSeparator(pos))
3557 pos_type from = pos;
3558 locateWord(from, pos, WHOLE_WORD);
3559 if ((pos - from) >= (int)lyxrc.completion_minlength) {
3560 docstring word = asString(from, pos, AS_STR_NONE);
3561 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3562 if (cit == d->fontlist_.end())
3564 Language const * lang = cit->font().language();
3565 d->words_[*lang].insert(word);
3571 void Paragraph::registerWords()
3573 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3574 Private::LangWordsMap::const_iterator ite = d->words_.end();
3575 for (; itl != ite; ++itl) {
3576 WordList * wl = theWordList(itl->first);
3577 Private::Words::const_iterator it = (itl->second).begin();
3578 Private::Words::const_iterator et = (itl->second).end();
3579 for (; it != et; ++it)
3585 void Paragraph::updateWords()
3593 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3595 SkipPositionsIterator begin = skips.begin();
3596 SkipPositions::iterator end = skips.end();
3597 if (pos > 0 && begin < end) {
3599 if (end->last == pos - 1) {
3604 skips.insert(end, FontSpan(pos, pos));
3608 Language * Paragraph::Private::locateSpellRange(
3609 pos_type & from, pos_type & to,
3610 SkipPositions & skips) const
3612 // skip leading white space
3613 while (from < to && owner_->isWordSeparator(from))
3615 // don't check empty range
3618 // get current language
3619 Language * lang = getSpellLanguage(from);
3620 pos_type last = from;
3621 bool samelang = true;
3622 bool sameinset = true;
3623 while (last < to && samelang && sameinset) {
3624 // hop to end of word
3625 while (last < to && !owner_->isWordSeparator(last)) {
3626 if (owner_->getInset(last)) {
3627 appendSkipPosition(skips, last);
3628 } else if (owner_->isDeleted(last)) {
3629 appendSkipPosition(skips, last);
3633 // hop to next word while checking for insets
3634 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3635 if (Inset const * inset = owner_->getInset(last))
3636 sameinset = inset->isChar() && inset->isLetter();
3637 if (sameinset && owner_->isDeleted(last)) {
3638 appendSkipPosition(skips, last);
3643 if (sameinset && last < to) {
3644 // now check for language change
3645 samelang = lang == getSpellLanguage(last);
3648 // if language change detected backstep is needed
3656 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3659 const_cast<Language *>(owner_->getFontSettings(
3660 inset_owner_->buffer().params(), from).language());
3661 if (lang == inset_owner_->buffer().params().language
3662 && !lyxrc.spellchecker_alt_lang.empty()) {
3664 string const lang_variety =
3665 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3666 lang->setCode(lang_code);
3667 lang->setVariety(lang_variety);
3673 void Paragraph::requestSpellCheck(pos_type pos)
3675 d->requestSpellCheck(pos);
3679 bool Paragraph::needsSpellCheck() const
3681 SpellChecker::ChangeNumber speller_change_number = 0;
3682 if (theSpellChecker())
3683 speller_change_number = theSpellChecker()->changeNumber();
3684 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3685 d->speller_state_.needsCompleteRefresh(speller_change_number);
3687 return d->needsSpellCheck();
3691 bool Paragraph::Private::ignoreWord(docstring const & word) const
3693 // Ignore words with digits
3694 // FIXME: make this customizable
3695 // (note that some checkers ignore words with digits by default)
3696 docstring::const_iterator cit = word.begin();
3697 docstring::const_iterator const end = word.end();
3698 for (; cit != end; ++cit) {
3699 if (isNumber((*cit)))
3706 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3707 WordLangTuple & wl, docstring_list & suggestions,
3708 bool do_suggestion, bool check_learned) const
3710 SpellChecker::Result result = SpellChecker::WORD_OK;
3711 SpellChecker * speller = theSpellChecker();
3715 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3718 locateWord(from, to, WHOLE_WORD);
3719 if (from == to || from >= size())
3722 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3723 Language * lang = d->getSpellLanguage(from);
3725 wl = WordLangTuple(word, lang);
3730 if (needsSpellCheck() || check_learned) {
3732 if (!d->ignoreWord(word)) {
3733 bool const trailing_dot = to < size() && d->text_[to] == '.';
3734 result = speller->check(wl);
3735 if (SpellChecker::misspelled(result) && trailing_dot) {
3736 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3737 result = speller->check(wl);
3738 if (!SpellChecker::misspelled(result)) {
3739 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3741 from << ".." << to << "]");
3743 // spell check with dot appended failed too
3744 // restore original word/lang value
3745 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3746 wl = WordLangTuple(word, lang);
3750 if (!SpellChecker::misspelled(result)) {
3751 // area up to the begin of the next word is not misspelled
3752 while (end < size() && isWordSeparator(end))
3755 d->setMisspelled(from, end, result);
3757 result = d->speller_state_.getState(from);
3761 suggestions.clear();
3763 if (SpellChecker::misspelled(result)) {
3764 LYXERR(Debug::GUI, "misspelled word: \"" <<
3766 from << ".." << to << "]");
3768 speller->suggest(wl, suggestions);
3774 void Paragraph::Private::markMisspelledWords(
3775 pos_type const & first, pos_type const & last,
3776 SpellChecker::Result result,
3777 docstring const & word,
3778 SkipPositions const & skips)
3780 if (!SpellChecker::misspelled(result)) {
3781 setMisspelled(first, last, SpellChecker::WORD_OK);
3785 SpellChecker * speller = theSpellChecker();
3786 // locate and enumerate the error positions
3787 int nerrors = speller->numMisspelledWords();
3789 SkipPositionsIterator it = skips.begin();
3790 SkipPositionsIterator et = skips.end();
3791 for (int index = 0; index < nerrors; ++index) {
3794 speller->misspelledWord(index, wstart, wlen);
3795 /// should not happen if speller supports range checks
3796 if (!wlen) continue;
3797 docstring const misspelled = word.substr(wstart, wlen);
3798 wstart += first + numskipped;
3799 if (snext < wstart) {
3800 /// mark the range of correct spelling
3801 numskipped += countSkips(it, et, wstart);
3802 setMisspelled(snext,
3803 wstart - 1, SpellChecker::WORD_OK);
3805 snext = wstart + wlen;
3806 numskipped += countSkips(it, et, snext);
3807 /// mark the range of misspelling
3808 setMisspelled(wstart, snext, result);
3809 LYXERR(Debug::GUI, "misspelled word: \"" <<
3810 misspelled << "\" [" <<
3811 wstart << ".." << (snext-1) << "]");
3814 if (snext <= last) {
3815 /// mark the range of correct spelling at end
3816 setMisspelled(snext, last, SpellChecker::WORD_OK);
3821 void Paragraph::spellCheck() const
3823 SpellChecker * speller = theSpellChecker();
3824 if (!speller || !size() ||!needsSpellCheck())
3828 d->rangeOfSpellCheck(start, endpos);
3829 if (speller->canCheckParagraph()) {
3830 // loop until we leave the range
3831 for (pos_type first = start; first < endpos; ) {
3832 pos_type last = endpos;
3833 Private::SkipPositions skips;
3834 Language * lang = d->locateSpellRange(first, last, skips);
3835 if (first >= endpos)
3837 // start the spell checker on the unit of meaning
3838 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3839 WordLangTuple wl = WordLangTuple(word, lang);
3840 SpellChecker::Result result = word.size() ?
3841 speller->check(wl) : SpellChecker::WORD_OK;
3842 d->markMisspelledWords(first, last, result, word, skips);
3846 static docstring_list suggestions;
3847 pos_type to = endpos;
3848 while (start < endpos) {
3850 spellCheck(start, to, wl, suggestions, false);
3854 d->readySpellCheck();
3858 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3860 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3861 if (result || pos <= 0 || pos > size())
3863 if (check_boundary && (pos == size() || isWordSeparator(pos)))
3864 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3869 string Paragraph::magicLabel() const
3872 ss << "magicparlabel-" << id();