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 OutputParams const & runparams,
334 Font const & running_font,
335 Change const & running_change,
336 Layout const & style,
339 unsigned int & column);
346 unsigned int & column);
352 unsigned int & column);
354 bool latexSpecialTypewriter(
358 unsigned int & column);
360 bool latexSpecialPhrase(
364 unsigned int & column,
365 OutputParams const & runparams);
368 void validate(LaTeXFeatures & features) const;
370 /// Checks if the paragraph contains only text and no inset or font change.
371 bool onlyText(Buffer const & buf, Font const & outerfont,
372 pos_type initial) const;
374 /// match a string against a particular point in the paragraph
375 bool isTextAt(string const & str, pos_type pos) const;
377 /// a vector of speller skip positions
378 typedef vector<FontSpan> SkipPositions;
379 typedef SkipPositions::const_iterator SkipPositionsIterator;
381 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
383 Language * getSpellLanguage(pos_type const from) const;
385 Language * locateSpellRange(pos_type & from, pos_type & to,
386 SkipPositions & skips) const;
388 bool hasSpellerChange() const {
389 SpellChecker::ChangeNumber speller_change_number = 0;
390 if (theSpellChecker())
391 speller_change_number = theSpellChecker()->changeNumber();
392 return speller_change_number > speller_state_.currentChangeNumber();
395 bool ignoreWord(docstring const & word) const ;
397 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
399 pos_type textsize = owner_->size();
400 // check for sane arguments
401 if (to <= from || from >= textsize)
403 FontSpan fp = FontSpan(from, to - 1);
404 speller_state_.setRange(fp, state);
407 void requestSpellCheck(pos_type pos) {
409 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
411 speller_state_.needsRefresh(pos);
414 void readySpellCheck() {
415 speller_state_.needsRefresh(-1);
418 bool needsSpellCheck() const
420 return speller_state_.needsRefresh();
423 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
425 speller_state_.refreshRange(first, last);
427 last = owner_->size();
430 pos_type endpos = last;
431 owner_->locateWord(first, endpos, WHOLE_WORD);
434 owner_->locateWord(last, endpos, WHOLE_WORD);
439 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
443 while (it != et && it->first < start) {
444 int skip = it->last - it->first + 1;
452 void markMisspelledWords(pos_type const & first, pos_type const & last,
453 SpellChecker::Result result,
454 docstring const & word,
455 SkipPositions const & skips);
457 InsetCode ownerCode() const
459 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
462 /// Which Paragraph owns us?
466 Inset const * inset_owner_;
475 ParagraphParameters params_;
477 /// for recording and looking up changes
481 InsetList insetlist_;
484 pos_type begin_of_body_;
486 typedef docstring TextContainer;
490 typedef set<docstring> Words;
491 typedef map<Language, Words> LangWordsMap;
495 Layout const * layout_;
497 SpellCheckerState speller_state_;
503 struct special_phrase {
509 special_phrase const special_phrases[] = {
510 { "LyX", from_ascii("\\LyX{}"), false },
511 { "TeX", from_ascii("\\TeX{}"), true },
512 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
513 { "LaTeX", from_ascii("\\LaTeX{}"), true },
516 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
521 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
522 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
528 // Initialization of the counter for the paragraph id's,
530 // FIXME: There should be a more intelligent way to generate and use the
531 // paragraph ids per buffer instead a global static counter for all InsetText
532 // in the running program.
533 static int paragraph_id = -1;
535 Paragraph::Private::Private(Private const & p, Paragraph * owner)
536 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
537 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
538 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
541 id_ = ++paragraph_id;
542 requestSpellCheck(p.text_.size());
546 Paragraph::Private::Private(Private const & p, Paragraph * owner,
547 pos_type beg, pos_type end)
548 : owner_(owner), inset_owner_(p.inset_owner_),
549 params_(p.params_), changes_(p.changes_),
550 insetlist_(p.insetlist_, beg, end),
551 begin_of_body_(p.begin_of_body_), words_(p.words_),
554 id_ = ++paragraph_id;
555 if (beg >= pos_type(p.text_.size()))
557 text_ = p.text_.substr(beg, end - beg);
559 FontList::const_iterator fcit = fontlist_.begin();
560 FontList::const_iterator fend = fontlist_.end();
561 for (; fcit != fend; ++fcit) {
562 if (fcit->pos() < beg)
564 if (fcit->pos() >= end) {
565 // Add last entry in the fontlist_.
566 fontlist_.set(text_.size() - 1, fcit->font());
569 // Add a new entry in the fontlist_.
570 fontlist_.set(fcit->pos() - beg, fcit->font());
572 requestSpellCheck(p.text_.size());
576 void Paragraph::addChangesToToc(DocIterator const & cdit,
577 Buffer const & buf) const
579 d->changes_.addToToc(cdit, buf);
583 bool Paragraph::isDeleted(pos_type start, pos_type end) const
585 LASSERT(start >= 0 && start <= size(), /**/);
586 LASSERT(end > start && end <= size() + 1, /**/);
588 return d->changes_.isDeleted(start, end);
592 bool Paragraph::isChanged(pos_type start, pos_type end) const
594 LASSERT(start >= 0 && start <= size(), /**/);
595 LASSERT(end > start && end <= size() + 1, /**/);
597 return d->changes_.isChanged(start, end);
601 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
603 // keep the logic here in sync with the logic of eraseChars()
607 Change const change = d->changes_.lookup(size());
608 return change.inserted() && change.currentAuthor();
612 void Paragraph::setChange(Change const & change)
614 // beware of the imaginary end-of-par character!
615 d->changes_.set(change, 0, size() + 1);
618 * Propagate the change recursively - but not in case of DELETED!
620 * Imagine that your co-author makes changes in an existing inset. He
621 * sends your document to you and you come to the conclusion that the
622 * inset should go completely. If you erase it, LyX must not delete all
623 * text within the inset. Otherwise, the change tracked insertions of
624 * your co-author get lost and there is no way to restore them later.
626 * Conclusion: An inset's content should remain untouched if you delete it
629 if (!change.deleted()) {
630 for (pos_type pos = 0; pos < size(); ++pos) {
631 if (Inset * inset = getInset(pos))
632 inset->setChange(change);
638 void Paragraph::setChange(pos_type pos, Change const & change)
640 LASSERT(pos >= 0 && pos <= size(), /**/);
641 d->changes_.set(change, pos);
643 // see comment in setChange(Change const &) above
644 if (!change.deleted() && pos < size())
645 if (Inset * inset = getInset(pos))
646 inset->setChange(change);
650 Change const & Paragraph::lookupChange(pos_type pos) const
652 LASSERT(pos >= 0 && pos <= size(), /**/);
653 return d->changes_.lookup(pos);
657 void Paragraph::acceptChanges(pos_type start, pos_type end)
659 LASSERT(start >= 0 && start <= size(), /**/);
660 LASSERT(end > start && end <= size() + 1, /**/);
662 for (pos_type pos = start; pos < end; ++pos) {
663 switch (lookupChange(pos).type) {
664 case Change::UNCHANGED:
665 // accept changes in nested inset
666 if (Inset * inset = getInset(pos))
667 inset->acceptChanges();
670 case Change::INSERTED:
671 d->changes_.set(Change(Change::UNCHANGED), pos);
672 // also accept changes in nested inset
673 if (Inset * inset = getInset(pos))
674 inset->acceptChanges();
677 case Change::DELETED:
678 // Suppress access to non-existent
679 // "end-of-paragraph char"
681 eraseChar(pos, false);
692 void Paragraph::rejectChanges(pos_type start, pos_type end)
694 LASSERT(start >= 0 && start <= size(), /**/);
695 LASSERT(end > start && end <= size() + 1, /**/);
697 for (pos_type pos = start; pos < end; ++pos) {
698 switch (lookupChange(pos).type) {
699 case Change::UNCHANGED:
700 // reject changes in nested inset
701 if (Inset * inset = getInset(pos))
702 inset->rejectChanges();
705 case Change::INSERTED:
706 // Suppress access to non-existent
707 // "end-of-paragraph char"
709 eraseChar(pos, false);
715 case Change::DELETED:
716 d->changes_.set(Change(Change::UNCHANGED), pos);
718 // Do NOT reject changes within a deleted inset!
719 // There may be insertions of a co-author inside of it!
727 void Paragraph::Private::insertChar(pos_type pos, char_type c,
728 Change const & change)
730 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
733 changes_.insert(change, pos);
735 // This is actually very common when parsing buffers (and
736 // maybe inserting ascii text)
737 if (pos == pos_type(text_.size())) {
738 // when appending characters, no need to update tables
740 // but we want spell checking
741 requestSpellCheck(pos);
745 text_.insert(text_.begin() + pos, c);
747 // Update the font table.
748 fontlist_.increasePosAfterPos(pos);
751 insetlist_.increasePosAfterPos(pos);
753 // Update list of misspelled positions
754 speller_state_.increasePosAfterPos(pos);
758 bool Paragraph::insertInset(pos_type pos, Inset * inset,
759 Change const & change)
761 LASSERT(inset, /**/);
762 LASSERT(pos >= 0 && pos <= size(), /**/);
764 // Paragraph::insertInset() can be used in cut/copy/paste operation where
765 // d->inset_owner_ is not set yet.
766 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
769 d->insertChar(pos, META_INSET, change);
770 LASSERT(d->text_[pos] == META_INSET, /**/);
772 // Add a new entry in the insetlist_.
773 d->insetlist_.insert(inset, pos);
775 // Some insets require run of spell checker
776 requestSpellCheck(pos);
781 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
783 LASSERT(pos >= 0 && pos <= size(), return false);
785 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
788 Change change = d->changes_.lookup(pos);
790 // set the character to DELETED if
791 // a) it was previously unchanged or
792 // b) it was inserted by a co-author
794 if (!change.changed() ||
795 (change.inserted() && !change.currentAuthor())) {
796 setChange(pos, Change(Change::DELETED));
797 // request run of spell checker
798 requestSpellCheck(pos);
802 if (change.deleted())
806 // Don't physically access the imaginary end-of-paragraph character.
807 // eraseChar() can only mark it as DELETED. A physical deletion of
808 // end-of-par must be handled externally.
814 d->changes_.erase(pos);
816 // if it is an inset, delete the inset entry
817 if (d->text_[pos] == META_INSET)
818 d->insetlist_.erase(pos);
820 d->text_.erase(d->text_.begin() + pos);
822 // Update the fontlist_
823 d->fontlist_.erase(pos);
825 // Update the insetlist_
826 d->insetlist_.decreasePosAfterPos(pos);
828 // Update list of misspelled positions
829 d->speller_state_.decreasePosAfterPos(pos);
830 d->speller_state_.refreshLast(size());
836 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
838 LASSERT(start >= 0 && start <= size(), /**/);
839 LASSERT(end >= start && end <= size() + 1, /**/);
842 for (pos_type count = end - start; count; --count) {
843 if (!eraseChar(i, trackChanges))
850 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
851 char_type next, OutputParams const & runparams)
853 // Writing next here may circumvent a possible font change between
854 // c and next. Since next is only output if it forms a surrogate pair
855 // with c we can ignore this:
856 // A font change inside a surrogate pair does not make sense and is
857 // hopefully impossible to input.
858 // FIXME: change tracking
859 // Is this correct WRT change tracking?
860 Encoding const & encoding = *(runparams.encoding);
861 docstring const latex1 = encoding.latexChar(next).first;
862 docstring const latex2 = encoding.latexChar(c).first;
863 if (docstring(1, next) == latex1) {
864 // the encoding supports the combination
865 os << latex2 << latex1;
866 return latex1.length() + latex2.length();
867 } else if (runparams.local_font &&
868 runparams.local_font->language()->lang() == "polutonikogreek") {
869 // polutonikogreek only works without the brackets
870 os << latex1 << latex2;
871 return latex1.length() + latex2.length();
873 os << latex1 << '{' << latex2 << '}';
874 return latex1.length() + latex2.length() + 2;
878 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
881 unsigned int & column,
883 Layout const & style)
885 if (style.pass_thru || runparams.pass_thru)
888 if (i + 1 < int(text_.size())) {
889 char_type next = text_[i + 1];
890 if (Encodings::isCombiningChar(next)) {
891 // This space has an accent, so we must always output it.
892 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
897 if (runparams.linelen > 0
898 && column > runparams.linelen
900 && text_[i - 1] != ' '
901 && (i + 1 < int(text_.size()))
902 // same in FreeSpacing mode
903 && !owner_->isFreeSpacing()
904 // In typewriter mode, we want to avoid
905 // ! . ? : at the end of a line
906 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
907 && (text_[i - 1] == '.'
908 || text_[i - 1] == '?'
909 || text_[i - 1] == ':'
910 || text_[i - 1] == '!'))) {
912 os.texrow().start(owner_->id(), i + 1);
914 } else if (style.free_spacing) {
923 int Paragraph::Private::writeScriptChars(otexstream & os,
924 docstring const & ltx,
925 Change const & runningChange,
926 Encoding const & encoding,
929 // FIXME: modifying i here is not very nice...
931 // We only arrive here when a proper language for character text_[i] has
932 // not been specified (i.e., it could not be translated in the current
933 // latex encoding) or its latex translation has been forced, and it
934 // belongs to a known script.
935 // Parameter ltx contains the latex translation of text_[i] as specified
936 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
937 // The latex macro name "textXXX" specifies the script to which text_[i]
938 // belongs and we use it in order to check whether characters from the
939 // same script immediately follow, such that we can collect them in a
940 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
941 // for the first char but only "<spec>" for all subsequent chars.
942 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
943 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
944 string script = to_ascii(ltx.substr(1, brace1 - 1));
947 bool closing_brace = true;
948 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
949 // Correct encoding is being used, so we can avoid \textgreek.
952 closing_brace = false;
954 os << ltx.substr(pos, length);
955 int size = text_.size();
956 while (i + 1 < size) {
957 char_type const next = text_[i + 1];
958 // Stop here if next character belongs to another script
959 // or there is a change in change tracking status.
960 if (!Encodings::isKnownScriptChar(next, script) ||
961 runningChange != owner_->lookupChange(i + 1))
965 FontList::const_iterator cit = fontlist_.begin();
966 FontList::const_iterator end = fontlist_.end();
967 for (; cit != end; ++cit) {
968 if (cit->pos() >= i && !found) {
969 prev_font = cit->font();
972 if (cit->pos() >= i + 1)
975 // Stop here if there is a font attribute or encoding change.
976 if (found && cit != end && prev_font != cit->font())
978 docstring const latex = encoding.latexChar(next).first;
979 docstring::size_type const b1 =
980 latex.find_first_of(from_ascii("{"));
981 docstring::size_type const b2 =
982 latex.find_last_of(from_ascii("}"));
983 int const len = b2 - b1 - 1;
984 os << latex.substr(b1 + 1, len);
996 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
998 pos_type const len = str.length();
1000 // is the paragraph large enough?
1001 if (pos + len > int(text_.size()))
1004 // does the wanted text start at point?
1005 for (string::size_type i = 0; i < str.length(); ++i) {
1006 // Caution: direct comparison of characters works only
1007 // because str is pure ASCII.
1008 if (str[i] != text_[pos + i])
1012 return fontlist_.hasChangeInRange(pos, len);
1016 void Paragraph::Private::latexInset(BufferParams const & bparams,
1018 OutputParams & runparams,
1019 Font & running_font,
1021 Font const & outerfont,
1023 Change & running_change,
1024 Layout const & style,
1026 unsigned int & column)
1028 Inset * inset = owner_->getInset(i);
1029 LASSERT(inset, /**/);
1031 if (style.pass_thru) {
1032 inset->plaintext(os.os(), runparams);
1036 // FIXME: move this to InsetNewline::latex
1037 if (inset->lyxCode() == NEWLINE_CODE) {
1038 // newlines are handled differently here than
1039 // the default in simpleTeXSpecialChars().
1040 if (!style.newline_allowed) {
1044 column += running_font.latexWriteEndChanges(
1045 os, bparams, runparams,
1046 basefont, basefont);
1050 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1053 basefont = owner_->getLayoutFont(bparams, outerfont);
1054 running_font = basefont;
1056 if (runparams.moving_arg)
1060 os.texrow().start(owner_->id(), i + 1);
1064 if (owner_->isDeleted(i)) {
1065 if( ++runparams.inDeletedInset == 1)
1066 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1069 if (inset->canTrackChanges()) {
1070 column += Changes::latexMarkChange(os, bparams, running_change,
1071 Change(Change::UNCHANGED), runparams);
1072 running_change = Change(Change::UNCHANGED);
1076 odocstream::pos_type const len = os.os().tellp();
1078 if (inset->forceLTR()
1079 && running_font.isRightToLeft()
1080 // ERT is an exception, it should be output with no
1081 // decorations at all
1082 && inset->lyxCode() != ERT_CODE) {
1083 if (running_font.language()->lang() == "farsi")
1090 // FIXME: Bug: we can have an empty font change here!
1091 // if there has just been a font change, we are going to close it
1092 // right now, which means stupid latex code like \textsf{}. AFAIK,
1093 // this does not harm dvi output. A minor bug, thus (JMarc)
1095 // Some insets cannot be inside a font change command.
1096 // However, even such insets *can* be placed in \L or \R
1097 // or their equivalents (for RTL language switches), so we don't
1098 // close the language in those cases.
1099 // ArabTeX, though, cannot handle this special behavior, it seems.
1100 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1101 || running_font.language()->lang() == "arabic_arabtex";
1102 if (open_font && !inset->inheritFont()) {
1103 bool closeLanguage = arabtex
1104 || basefont.isRightToLeft() == running_font.isRightToLeft();
1105 unsigned int count = running_font.latexWriteEndChanges(os,
1106 bparams, runparams, basefont, basefont, closeLanguage);
1108 // if any font properties were closed, update the running_font,
1109 // making sure, however, to leave the language as it was
1111 // FIXME: probably a better way to keep track of the old
1112 // language, than copying the entire font?
1113 Font const copy_font(running_font);
1114 basefont = owner_->getLayoutFont(bparams, outerfont);
1115 running_font = basefont;
1117 running_font.setLanguage(copy_font.language());
1118 // leave font open if language is still open
1119 open_font = (running_font.language() == basefont.language());
1121 runparams.local_font = &basefont;
1125 int prev_rows = os.texrow().rows();
1128 runparams.lastid = id_;
1129 runparams.lastpos = i;
1130 inset->latex(os, runparams);
1131 } catch (EncodingException & e) {
1132 // add location information and throw again.
1139 if (running_font.language()->lang() == "farsi")
1145 if (os.texrow().rows() > prev_rows) {
1146 os.texrow().start(owner_->id(), i + 1);
1149 column += (unsigned int)(os.os().tellp() - len);
1152 if (owner_->isDeleted(i))
1153 --runparams.inDeletedInset;
1157 void Paragraph::Private::latexSpecialChar(otexstream & os,
1158 OutputParams const & runparams,
1159 Font const & running_font,
1160 Change const & running_change,
1161 Layout const & style,
1164 unsigned int & column)
1166 char_type const c = text_[i];
1168 if (style.pass_thru || runparams.pass_thru) {
1170 Encoding const * const enc = runparams.encoding;
1171 if (enc && !enc->encodable(c))
1172 throw EncodingException(c);
1178 // TIPA uses its own T3 encoding
1179 if (runparams.inIPA && latexSpecialT3(c, os, i, column))
1181 // If T1 font encoding is used, use the special
1182 // characters it provides.
1183 // NOTE: some languages reset the font encoding
1185 if (!runparams.inIPA && !running_font.language()->internalFontEncoding()
1186 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1189 // \tt font needs special treatment
1190 if (!runparams.inIPA
1191 && running_font.fontInfo().family() == TYPEWRITER_FAMILY
1192 && latexSpecialTypewriter(c, os, i, column))
1195 // Otherwise, we use what LaTeX provides us.
1198 os << "\\textbackslash{}";
1202 os << "\\textless{}";
1206 os << "\\textgreater{}";
1210 os << "\\textbar{}";
1217 os << "\\char`\\\"{}";
1222 case '%': case '#': case '{':
1230 os << "\\textasciitilde{}";
1235 os << "\\textasciicircum{}";
1242 // avoid being mistaken for optional arguments
1250 // Blanks are printed before font switching.
1251 // Sure? I am not! (try nice-latex)
1252 // I am sure it's correct. LyX might be smarter
1253 // in the future, but for now, nothing wrong is
1259 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1265 Encoding const & encoding = *(runparams.encoding);
1266 char_type next = '\0';
1267 if (i + 1 < int(text_.size())) {
1268 next = text_[i + 1];
1269 if (Encodings::isCombiningChar(next)) {
1270 column += latexSurrogatePair(os, c, next, runparams) - 1;
1276 pair<docstring, bool> latex = encoding.latexChar(c);
1277 docstring nextlatex;
1278 bool nexttipas = false;
1279 string nexttipashortcut;
1280 if (next != '\0' && next != META_INSET) {
1281 nextlatex = encoding.latexChar(next).first;
1282 if (runparams.inIPA) {
1283 nexttipashortcut = Encodings::TIPAShortcut(next);
1284 nexttipas = !nexttipashortcut.empty();
1288 if (runparams.inIPA) {
1289 string const tipashortcut = Encodings::TIPAShortcut(c);
1290 if (!tipashortcut.empty()) {
1291 latex.first = from_ascii(tipashortcut);
1292 latex.second = false;
1296 if (Encodings::isKnownScriptChar(c, script)
1297 && prefixIs(latex.first, from_ascii("\\" + script)))
1298 column += writeScriptChars(os, latex.first,
1299 running_change, encoding, i) - 1;
1300 else if (latex.second
1301 && ((!prefixIs(nextlatex, '\\')
1302 && !prefixIs(nextlatex, '{')
1303 && !prefixIs(nextlatex, '}'))
1305 && !prefixIs(from_ascii(nexttipashortcut), '\\')))
1307 // Prevent eating of a following
1308 // space or command corruption by
1309 // following characters
1310 if (next == ' ' || next == '\0') {
1311 column += latex.first.length() + 1;
1312 os << latex.first << "{}";
1314 column += latex.first.length();
1315 os << latex.first << " ";
1318 column += latex.first.length() - 1;
1326 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1327 pos_type i, unsigned int & column)
1333 // In T1 encoding, these characters exist
1334 // but we should avoid ligatures
1335 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1337 os << "\\textcompwordmark{}";
1344 // soul.sty breaks with \char`\"
1345 os << "\\textquotedbl{}";
1354 bool Paragraph::Private::latexSpecialT3(char_type const c, otexstream & os,
1355 pos_type /*i*/, unsigned int & /*column*/)
1371 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1372 pos_type i, unsigned int & column)
1376 // within \ttfamily, "--" is merged to "-" (no endash)
1377 // so we avoid this rather irritating ligature
1378 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1385 // everything else has to be checked separately
1386 // (depending on the encoding)
1394 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1395 /// do not apply the macro transformation.
1396 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1397 unsigned int & column, OutputParams const & runparams)
1399 // FIXME: if we have "LaTeX" with a font
1400 // change in the middle (before the 'T', then
1401 // the "TeX" part is still special cased.
1402 // Really we should only operate this on
1403 // "words" for some definition of word
1405 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1406 if (!isTextAt(special_phrases[pnr].phrase, i)
1407 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1409 if (runparams.moving_arg)
1411 os << special_phrases[pnr].macro;
1412 i += special_phrases[pnr].phrase.length() - 1;
1413 column += special_phrases[pnr].macro.length() - 1;
1420 void Paragraph::Private::validate(LaTeXFeatures & features) const
1422 if (layout_->inpreamble && inset_owner_) {
1423 bool const is_command = layout_->latextype == LATEX_COMMAND;
1424 Buffer const & buf = inset_owner_->buffer();
1425 BufferParams const & bp = buf.params();
1428 // Using a string stream here circumvents the encoding
1429 // switching machinery of odocstream. Therefore the
1430 // output is wrong if this paragraph contains content
1431 // that needs to switch encoding.
1432 odocstringstream ods;
1433 otexstream os(ods, texrow);
1435 os << '\\' << from_ascii(layout_->latexname());
1436 // we have to provide all the optional arguments here, even though
1437 // the last one is the only one we care about.
1438 // Separate handling of optional argument inset.
1439 if (layout_->optargs != 0 || layout_->reqargs != 0)
1440 latexArgInsets(*owner_, os, features.runparams(),
1441 layout_->reqargs, layout_->optargs);
1443 os << from_ascii(layout_->latexparam());
1445 docstring::size_type const length = ods.str().length();
1446 // this will output "{" at the beginning, but not at the end
1447 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1448 if (ods.str().length() > length) {
1451 string const snippet = to_utf8(ods.str());
1452 features.addPreambleSnippet(snippet);
1456 if (features.runparams().flavor == OutputParams::HTML
1457 && layout_->htmltitle()) {
1458 features.setHTMLTitle(owner_->asString(AS_STR_INSETS | AS_STR_SKIPDELETE));
1461 // check the params.
1462 if (!params_.spacing().isDefault())
1463 features.require("setspace");
1466 features.useLayout(layout_->name());
1469 fontlist_.validate(features);
1471 // then the indentation
1472 if (!params_.leftIndent().zero())
1473 features.require("ParagraphLeftIndent");
1476 InsetList::const_iterator icit = insetlist_.begin();
1477 InsetList::const_iterator iend = insetlist_.end();
1478 for (; icit != iend; ++icit) {
1480 icit->inset->validate(features);
1481 if (layout_->needprotect &&
1482 icit->inset->lyxCode() == FOOT_CODE)
1483 features.require("NeedLyXFootnoteCode");
1487 // then the contents
1488 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1489 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1490 if (!special_phrases[pnr].builtin
1491 && isTextAt(special_phrases[pnr].phrase, i)) {
1492 features.require(special_phrases[pnr].phrase);
1496 Encodings::validate(text_[i], features);
1500 /////////////////////////////////////////////////////////////////////
1504 /////////////////////////////////////////////////////////////////////
1507 Layout const emptyParagraphLayout;
1510 Paragraph::Paragraph()
1511 : d(new Paragraph::Private(this, emptyParagraphLayout))
1518 Paragraph::Paragraph(Paragraph const & par)
1519 : itemdepth(par.itemdepth),
1520 d(new Paragraph::Private(*par.d, this))
1526 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1527 : itemdepth(par.itemdepth),
1528 d(new Paragraph::Private(*par.d, this, beg, end))
1534 Paragraph & Paragraph::operator=(Paragraph const & par)
1536 // needed as we will destroy the private part before copying it
1538 itemdepth = par.itemdepth;
1542 d = new Private(*par.d, this);
1549 Paragraph::~Paragraph()
1558 // this shall be called just before every "os << ..." action.
1559 void flushString(ostream & os, docstring & s)
1568 void Paragraph::write(ostream & os, BufferParams const & bparams,
1569 depth_type & dth) const
1571 // The beginning or end of a deeper (i.e. nested) area?
1572 if (dth != d->params_.depth()) {
1573 if (d->params_.depth() > dth) {
1574 while (d->params_.depth() > dth) {
1575 os << "\n\\begin_deeper";
1579 while (d->params_.depth() < dth) {
1580 os << "\n\\end_deeper";
1586 // First write the layout
1587 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1589 d->params_.write(os);
1591 Font font1(inherit_font, bparams.language);
1593 Change running_change = Change(Change::UNCHANGED);
1595 // this string is used as a buffer to avoid repetitive calls
1596 // to to_utf8(), which turn out to be expensive (JMarc)
1597 docstring write_buffer;
1600 for (pos_type i = 0; i <= size(); ++i) {
1602 Change const change = lookupChange(i);
1603 if (change != running_change)
1604 flushString(os, write_buffer);
1605 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1606 running_change = change;
1611 // Write font changes
1612 Font font2 = getFontSettings(bparams, i);
1613 if (font2 != font1) {
1614 flushString(os, write_buffer);
1615 font2.lyxWriteChanges(font1, os);
1620 char_type const c = d->text_[i];
1623 if (Inset const * inset = getInset(i)) {
1624 flushString(os, write_buffer);
1625 if (inset->directWrite()) {
1626 // international char, let it write
1627 // code directly so it's shorter in
1633 os << "\\begin_inset ";
1635 os << "\n\\end_inset\n\n";
1641 flushString(os, write_buffer);
1642 os << "\n\\backslash\n";
1646 flushString(os, write_buffer);
1647 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1654 if ((column > 70 && c == ' ')
1656 flushString(os, write_buffer);
1660 // this check is to amend a bug. LyX sometimes
1661 // inserts '\0' this could cause problems.
1663 write_buffer.push_back(c);
1665 LYXERR0("NUL char in structure.");
1671 flushString(os, write_buffer);
1672 os << "\n\\end_layout\n";
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 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1752 Font const & font, Change const & change)
1754 bool const success = insertInset(pos, inset, change);
1755 // Set the font/language of the inset...
1761 void Paragraph::resetFonts(Font const & font)
1763 d->fontlist_.clear();
1764 d->fontlist_.set(0, font);
1765 d->fontlist_.set(d->text_.size() - 1, font);
1768 // Gets uninstantiated font setting at position.
1769 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1773 LYXERR0("pos: " << pos << " size: " << size());
1774 LASSERT(pos <= size(), /**/);
1777 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1778 if (cit != d->fontlist_.end())
1781 if (pos == size() && !empty())
1782 return getFontSettings(bparams, pos - 1);
1784 // Optimisation: avoid a full font instantiation if there is no
1785 // language change from previous call.
1786 static Font previous_font;
1787 static Language const * previous_lang = 0;
1788 Language const * lang = getParLanguage(bparams);
1789 if (lang != previous_lang) {
1790 previous_lang = lang;
1791 previous_font = Font(inherit_font, lang);
1793 return previous_font;
1797 FontSpan Paragraph::fontSpan(pos_type pos) const
1799 LASSERT(pos <= size(), /**/);
1802 FontList::const_iterator cit = d->fontlist_.begin();
1803 FontList::const_iterator end = d->fontlist_.end();
1804 for (; cit != end; ++cit) {
1805 if (cit->pos() >= pos) {
1806 if (pos >= beginOfBody())
1807 return FontSpan(max(start, beginOfBody()),
1810 return FontSpan(start,
1811 min(beginOfBody() - 1,
1814 start = cit->pos() + 1;
1817 // This should not happen, but if so, we take no chances.
1818 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1819 return FontSpan(pos, pos);
1823 // Gets uninstantiated font setting at position 0
1824 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1826 if (!empty() && !d->fontlist_.empty())
1827 return d->fontlist_.begin()->font();
1829 // Optimisation: avoid a full font instantiation if there is no
1830 // language change from previous call.
1831 static Font previous_font;
1832 static Language const * previous_lang = 0;
1833 if (bparams.language != previous_lang) {
1834 previous_lang = bparams.language;
1835 previous_font = Font(inherit_font, bparams.language);
1838 return previous_font;
1842 // Gets the fully instantiated font at a given position in a paragraph
1843 // This is basically the same function as Text::GetFont() in text2.cpp.
1844 // The difference is that this one is used for generating the LaTeX file,
1845 // and thus cosmetic "improvements" are disallowed: This has to deliver
1846 // the true picture of the buffer. (Asger)
1847 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1848 Font const & outerfont) const
1850 LASSERT(pos >= 0, /**/);
1852 Font font = getFontSettings(bparams, pos);
1854 pos_type const body_pos = beginOfBody();
1855 FontInfo & fi = font.fontInfo();
1857 fi.realize(d->layout_->labelfont);
1859 fi.realize(d->layout_->font);
1861 fi.realize(outerfont.fontInfo());
1862 fi.realize(bparams.getFont().fontInfo());
1868 Font const Paragraph::getLabelFont
1869 (BufferParams const & bparams, Font const & outerfont) const
1871 FontInfo tmpfont = d->layout_->labelfont;
1872 tmpfont.realize(outerfont.fontInfo());
1873 tmpfont.realize(bparams.getFont().fontInfo());
1874 return Font(tmpfont, getParLanguage(bparams));
1878 Font const Paragraph::getLayoutFont
1879 (BufferParams const & bparams, Font const & outerfont) const
1881 FontInfo tmpfont = d->layout_->font;
1882 tmpfont.realize(outerfont.fontInfo());
1883 tmpfont.realize(bparams.getFont().fontInfo());
1884 return Font(tmpfont, getParLanguage(bparams));
1888 /// Returns the height of the highest font in range
1889 FontSize Paragraph::highestFontInRange
1890 (pos_type startpos, pos_type endpos, FontSize def_size) const
1892 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1896 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1898 char_type c = d->text_[pos];
1899 if (!lyxrc.rtl_support)
1929 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1935 void Paragraph::setFont(pos_type pos, Font const & font)
1937 LASSERT(pos <= size(), /**/);
1939 // First, reduce font against layout/label font
1940 // Update: The setCharFont() routine in text2.cpp already
1941 // reduces font, so we don't need to do that here. (Asger)
1943 d->fontlist_.set(pos, font);
1947 void Paragraph::makeSameLayout(Paragraph const & par)
1949 d->layout_ = par.d->layout_;
1950 d->params_ = par.d->params_;
1954 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1956 if (isFreeSpacing())
1962 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1963 if (eraseChar(pos, trackChanges))
1969 return count > 0 || pos > 0;
1973 bool Paragraph::hasSameLayout(Paragraph const & par) const
1975 return par.d->layout_ == d->layout_
1976 && d->params_.sameLayout(par.d->params_);
1980 depth_type Paragraph::getDepth() const
1982 return d->params_.depth();
1986 depth_type Paragraph::getMaxDepthAfter() const
1988 if (d->layout_->isEnvironment())
1989 return d->params_.depth() + 1;
1991 return d->params_.depth();
1995 char Paragraph::getAlign() const
1997 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1998 return d->layout_->align;
2000 return d->params_.align();
2004 docstring const & Paragraph::labelString() const
2006 return d->params_.labelString();
2010 // the next two functions are for the manual labels
2011 docstring const Paragraph::getLabelWidthString() const
2013 if (d->layout_->margintype == MARGIN_MANUAL
2014 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
2015 return d->params_.labelWidthString();
2017 return _("Senseless with this layout!");
2021 void Paragraph::setLabelWidthString(docstring const & s)
2023 d->params_.labelWidthString(s);
2027 docstring Paragraph::expandLabel(Layout const & layout,
2028 BufferParams const & bparams) const
2030 return expandParagraphLabel(layout, bparams, true);
2034 docstring Paragraph::expandDocBookLabel(Layout const & layout,
2035 BufferParams const & bparams) const
2037 return expandParagraphLabel(layout, bparams, false);
2041 docstring Paragraph::expandParagraphLabel(Layout const & layout,
2042 BufferParams const & bparams, bool process_appendix) const
2044 DocumentClass const & tclass = bparams.documentClass();
2045 string const & lang = getParLanguage(bparams)->code();
2046 bool const in_appendix = process_appendix && d->params_.appendix();
2047 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
2049 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
2050 && !layout.counter.empty())
2051 return tclass.counters().theCounter(layout.counter, lang);
2053 // handle 'inherited level parts' in 'fmt',
2054 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
2055 size_t const i = fmt.find('@', 0);
2056 if (i != docstring::npos) {
2057 size_t const j = fmt.find('@', i + 1);
2058 if (j != docstring::npos) {
2059 docstring parent(fmt, i + 1, j - i - 1);
2060 docstring label = from_ascii("??");
2061 if (tclass.hasLayout(parent))
2062 docstring label = expandParagraphLabel(tclass[parent], bparams,
2064 fmt = docstring(fmt, 0, i) + label
2065 + docstring(fmt, j + 1, docstring::npos);
2069 return tclass.counters().counterLabel(fmt, lang);
2073 void Paragraph::applyLayout(Layout const & new_layout)
2075 d->layout_ = &new_layout;
2076 LyXAlignment const oldAlign = d->params_.align();
2078 if (!(oldAlign & d->layout_->alignpossible)) {
2079 frontend::Alert::warning(_("Alignment not permitted"),
2080 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2081 d->params_.align(LYX_ALIGN_LAYOUT);
2086 pos_type Paragraph::beginOfBody() const
2088 return d->begin_of_body_;
2092 void Paragraph::setBeginOfBody()
2094 if (d->layout_->labeltype != LABEL_MANUAL) {
2095 d->begin_of_body_ = 0;
2099 // Unroll the first two cycles of the loop
2100 // and remember the previous character to
2101 // remove unnecessary getChar() calls
2103 pos_type end = size();
2104 if (i < end && !isNewline(i)) {
2106 char_type previous_char = 0;
2109 previous_char = d->text_[i];
2110 if (!isNewline(i)) {
2112 while (i < end && previous_char != ' ') {
2117 previous_char = temp;
2123 d->begin_of_body_ = i;
2127 bool Paragraph::allowParagraphCustomization() const
2129 return inInset().allowParagraphCustomization();
2133 bool Paragraph::usePlainLayout() const
2135 return inInset().usePlainLayout();
2139 bool Paragraph::isPassThru() const
2141 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2146 // paragraphs inside floats need different alignment tags to avoid
2149 bool noTrivlistCentering(InsetCode code)
2151 return code == FLOAT_CODE
2152 || code == WRAP_CODE
2153 || code == CELL_CODE;
2157 string correction(string const & orig)
2159 if (orig == "flushleft")
2160 return "raggedright";
2161 if (orig == "flushright")
2162 return "raggedleft";
2163 if (orig == "center")
2169 string const corrected_env(string const & suffix, string const & env,
2170 InsetCode code, bool const lastpar)
2172 string output = suffix + "{";
2173 if (noTrivlistCentering(code)) {
2175 // the last paragraph in non-trivlist-aligned
2176 // context is special (to avoid unwanted whitespace)
2177 if (suffix == "\\begin")
2178 return "\\" + correction(env) + "{}";
2181 output += correction(env);
2185 if (suffix == "\\begin")
2191 void adjust_column(string const & str, int & column)
2193 if (!contains(str, "\n"))
2194 column += str.size();
2197 column = rsplit(str, tmp, '\n').size();
2204 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2205 otexstream & os, OutputParams const & runparams) const
2209 if (params_.noindent() && !layout_->pass_thru) {
2210 os << "\\noindent ";
2214 LyXAlignment const curAlign = params_.align();
2216 if (curAlign == layout_->align)
2220 case LYX_ALIGN_NONE:
2221 case LYX_ALIGN_BLOCK:
2222 case LYX_ALIGN_LAYOUT:
2223 case LYX_ALIGN_SPECIAL:
2224 case LYX_ALIGN_DECIMAL:
2226 case LYX_ALIGN_LEFT:
2227 case LYX_ALIGN_RIGHT:
2228 case LYX_ALIGN_CENTER:
2229 if (runparams.moving_arg) {
2236 string const begin_tag = "\\begin";
2237 InsetCode code = ownerCode();
2238 bool const lastpar = runparams.isLastPar;
2241 case LYX_ALIGN_NONE:
2242 case LYX_ALIGN_BLOCK:
2243 case LYX_ALIGN_LAYOUT:
2244 case LYX_ALIGN_SPECIAL:
2245 case LYX_ALIGN_DECIMAL:
2247 case LYX_ALIGN_LEFT: {
2249 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2250 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2252 output = corrected_env(begin_tag, "flushright", code, lastpar);
2253 os << from_ascii(output);
2254 adjust_column(output, column);
2256 } case LYX_ALIGN_RIGHT: {
2258 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2259 output = corrected_env(begin_tag, "flushright", code, lastpar);
2261 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2262 os << from_ascii(output);
2263 adjust_column(output, column);
2265 } case LYX_ALIGN_CENTER: {
2267 output = corrected_env(begin_tag, "center", code, lastpar);
2268 os << from_ascii(output);
2269 adjust_column(output, column);
2278 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2279 otexstream & os, OutputParams const & runparams) const
2281 LyXAlignment const curAlign = params_.align();
2283 if (curAlign == layout_->align)
2287 case LYX_ALIGN_NONE:
2288 case LYX_ALIGN_BLOCK:
2289 case LYX_ALIGN_LAYOUT:
2290 case LYX_ALIGN_SPECIAL:
2291 case LYX_ALIGN_DECIMAL:
2293 case LYX_ALIGN_LEFT:
2294 case LYX_ALIGN_RIGHT:
2295 case LYX_ALIGN_CENTER:
2296 if (runparams.moving_arg)
2302 string const end_tag = "\n\\par\\end";
2303 InsetCode code = ownerCode();
2304 bool const lastpar = runparams.isLastPar;
2307 case LYX_ALIGN_NONE:
2308 case LYX_ALIGN_BLOCK:
2309 case LYX_ALIGN_LAYOUT:
2310 case LYX_ALIGN_SPECIAL:
2311 case LYX_ALIGN_DECIMAL:
2313 case LYX_ALIGN_LEFT: {
2314 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2315 output = corrected_env(end_tag, "flushleft", code, lastpar);
2317 output = corrected_env(end_tag, "flushright", code, lastpar);
2318 os << from_ascii(output);
2320 } case LYX_ALIGN_RIGHT: {
2321 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2322 output = corrected_env(end_tag, "flushright", code, lastpar);
2324 output = corrected_env(end_tag, "flushleft", code, lastpar);
2325 os << from_ascii(output);
2327 } case LYX_ALIGN_CENTER: {
2328 output = corrected_env(end_tag, "center", code, lastpar);
2329 os << from_ascii(output);
2334 return !output.empty() || lastpar;
2338 // This one spits out the text of the paragraph
2339 void Paragraph::latex(BufferParams const & bparams,
2340 Font const & outerfont,
2342 OutputParams const & runparams,
2343 int start_pos, int end_pos, bool force) const
2345 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2347 // FIXME This check should not be needed. Perhaps issue an
2348 // error if it triggers.
2349 Layout const & style = inInset().forcePlainLayout() ?
2350 bparams.documentClass().plainLayout() : *d->layout_;
2352 if (!force && style.inpreamble)
2355 bool const allowcust = allowParagraphCustomization();
2357 // Current base font for all inherited font changes, without any
2358 // change caused by an individual character, except for the language:
2359 // It is set to the language of the first character.
2360 // As long as we are in the label, this font is the base font of the
2361 // label. Before the first body character it is set to the base font
2365 // Maybe we have to create a optional argument.
2366 pos_type body_pos = beginOfBody();
2367 unsigned int column = 0;
2370 // the optional argument is kept in curly brackets in
2371 // case it contains a ']'
2372 // This is not strictly needed, but if this is changed it
2373 // would be a file format change, and tex2lyx would need
2374 // to be adjusted, since it unconditionally removes the
2375 // braces when it parses \item.
2378 basefont = getLabelFont(bparams, outerfont);
2380 basefont = getLayoutFont(bparams, outerfont);
2383 // Which font is currently active?
2384 Font running_font(basefont);
2385 // Do we have an open font change?
2386 bool open_font = false;
2388 Change runningChange = Change(Change::UNCHANGED);
2390 Encoding const * const prev_encoding = runparams.encoding;
2392 os.texrow().start(id(), 0);
2394 // if the paragraph is empty, the loop will not be entered at all
2396 if (style.isCommand()) {
2401 column += d->startTeXParParams(bparams, os, runparams);
2404 for (pos_type i = 0; i < size(); ++i) {
2405 // First char in paragraph or after label?
2406 if (i == body_pos) {
2409 column += running_font.latexWriteEndChanges(
2410 os, bparams, runparams,
2411 basefont, basefont);
2414 basefont = getLayoutFont(bparams, outerfont);
2415 running_font = basefont;
2417 column += Changes::latexMarkChange(os, bparams,
2418 runningChange, Change(Change::UNCHANGED),
2420 runningChange = Change(Change::UNCHANGED);
2425 if (style.isCommand()) {
2431 column += d->startTeXParParams(bparams, os,
2435 Change const & change = runparams.inDeletedInset
2436 ? runparams.changeOfDeletedInset : lookupChange(i);
2438 if (bparams.outputChanges && runningChange != change) {
2440 column += running_font.latexWriteEndChanges(
2441 os, bparams, runparams, basefont, basefont);
2444 basefont = getLayoutFont(bparams, outerfont);
2445 running_font = basefont;
2447 column += Changes::latexMarkChange(os, bparams, runningChange,
2449 runningChange = change;
2452 // do not output text which is marked deleted
2453 // if change tracking output is disabled
2454 if (!bparams.outputChanges && change.deleted()) {
2460 // Fully instantiated font
2461 Font const font = getFont(bparams, i, outerfont);
2463 Font const last_font = running_font;
2465 // Do we need to close the previous font?
2467 (font != running_font ||
2468 font.language() != running_font.language()))
2470 column += running_font.latexWriteEndChanges(
2471 os, bparams, runparams, basefont,
2472 (i == body_pos-1) ? basefont : font);
2473 running_font = basefont;
2477 string const running_lang = runparams.use_polyglossia ?
2478 running_font.language()->polyglossia() : running_font.language()->babel();
2479 // close babel's font environment before opening CJK.
2480 string const lang_end_command = runparams.use_polyglossia ?
2481 "\\end{$$lang}" : lyxrc.language_command_end;
2482 if (!running_lang.empty() &&
2483 font.language()->encoding()->package() == Encoding::CJK) {
2484 string end_tag = subst(lang_end_command,
2487 os << from_ascii(end_tag);
2488 column += end_tag.length();
2491 // Switch file encoding if necessary (and allowed)
2492 if (!runparams.pass_thru && !style.pass_thru &&
2493 runparams.encoding->package() != Encoding::none &&
2494 font.language()->encoding()->package() != Encoding::none) {
2495 pair<bool, int> const enc_switch =
2496 switchEncoding(os.os(), bparams, runparams,
2497 *(font.language()->encoding()));
2498 if (enc_switch.first) {
2499 column += enc_switch.second;
2500 runparams.encoding = font.language()->encoding();
2504 char_type const c = d->text_[i];
2506 // Do we need to change font?
2507 if ((font != running_font ||
2508 font.language() != running_font.language()) &&
2511 odocstringstream ods;
2512 column += font.latexWriteStartChanges(ods, bparams,
2513 runparams, basefont,
2515 running_font = font;
2517 docstring fontchange = ods.str();
2518 // check whether the fontchange ends with a \\textcolor
2519 // modifier and the text starts with a space (bug 4473)
2520 docstring const last_modifier = rsplit(fontchange, '\\');
2521 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2522 os << fontchange << from_ascii("{}");
2523 // check if the fontchange ends with a trailing blank
2524 // (like "\small " (see bug 3382)
2525 else if (suffixIs(fontchange, ' ') && c == ' ')
2526 os << fontchange.substr(0, fontchange.size() - 1)
2527 << from_ascii("{}");
2532 // FIXME: think about end_pos implementation...
2533 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2534 // FIXME: integrate this case in latexSpecialChar
2535 // Do not print the separation of the optional argument
2536 // if style.pass_thru is false. This works because
2537 // latexSpecialChar ignores spaces if
2538 // style.pass_thru is false.
2539 if (i != body_pos - 1) {
2540 if (d->simpleTeXBlanks(runparams, os,
2541 i, column, font, style)) {
2542 // A surrogate pair was output. We
2543 // must not call latexSpecialChar
2544 // in this iteration, since it would output
2545 // the combining character again.
2552 OutputParams rp = runparams;
2553 rp.free_spacing = style.free_spacing;
2554 rp.local_font = &font;
2555 rp.intitle = style.intitle;
2557 // Two major modes: LaTeX or plain
2558 // Handle here those cases common to both modes
2559 // and then split to handle the two modes separately.
2560 if (c == META_INSET) {
2561 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2562 d->latexInset(bparams, os, rp, running_font,
2563 basefont, outerfont, open_font,
2564 runningChange, style, i, column);
2567 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2569 d->latexSpecialChar(os, rp, running_font, runningChange,
2570 style, i, end_pos, column);
2571 } catch (EncodingException & e) {
2572 if (runparams.dryrun) {
2573 os << "<" << _("LyX Warning: ")
2574 << _("uncodable character") << " '";
2578 // add location information and throw again.
2587 // Set the encoding to that returned from latexSpecialChar (see
2588 // comment for encoding member in OutputParams.h)
2589 runparams.encoding = rp.encoding;
2592 // If we have an open font definition, we have to close it
2594 #ifdef FIXED_LANGUAGE_END_DETECTION
2596 running_font.latexWriteEndChanges(os, bparams,
2597 runparams, basefont,
2598 next_->getFont(bparams, 0, outerfont));
2600 running_font.latexWriteEndChanges(os, bparams,
2601 runparams, basefont, basefont);
2604 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2605 //FIXME: there as we start another \selectlanguage with the next paragraph if
2606 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2607 running_font.latexWriteEndChanges(os, bparams, runparams,
2608 basefont, basefont);
2612 column += Changes::latexMarkChange(os, bparams, runningChange,
2613 Change(Change::UNCHANGED), runparams);
2615 // Needed if there is an optional argument but no contents.
2616 if (body_pos > 0 && body_pos == size()) {
2620 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2621 && runparams.encoding != prev_encoding) {
2622 runparams.encoding = prev_encoding;
2623 if (!runparams.isFullUnicode())
2624 os << setEncoding(prev_encoding->iconvName());
2627 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2631 bool Paragraph::emptyTag() const
2633 for (pos_type i = 0; i < size(); ++i) {
2634 if (Inset const * inset = getInset(i)) {
2635 InsetCode lyx_code = inset->lyxCode();
2636 // FIXME testing like that is wrong. What is
2638 if (lyx_code != TOC_CODE &&
2639 lyx_code != INCLUDE_CODE &&
2640 lyx_code != GRAPHICS_CODE &&
2641 lyx_code != ERT_CODE &&
2642 lyx_code != LISTINGS_CODE &&
2643 lyx_code != FLOAT_CODE &&
2644 lyx_code != TABULAR_CODE) {
2648 char_type c = d->text_[i];
2649 if (c != ' ' && c != '\t')
2657 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2660 for (pos_type i = 0; i < size(); ++i) {
2661 if (Inset const * inset = getInset(i)) {
2662 InsetCode lyx_code = inset->lyxCode();
2663 if (lyx_code == LABEL_CODE) {
2664 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2665 docstring const & id = il->getParam("name");
2666 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2674 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2678 for (i = 0; i < size(); ++i) {
2679 if (Inset const * inset = getInset(i)) {
2680 inset->docbook(os, runparams);
2682 char_type c = d->text_[i];
2685 os << sgml::escapeChar(c);
2692 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2696 for (i = 0; i < size(); ++i) {
2697 if (Inset const * inset = getInset(i)) {
2698 inset->xhtml(xs, runparams);
2700 char_type c = d->text_[i];
2710 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2713 pos_type size = text_.size();
2714 for (pos_type i = initial; i < size; ++i) {
2715 Font font = owner_->getFont(buf.params(), i, outerfont);
2716 if (text_[i] == META_INSET)
2718 if (i != initial && font != font_old)
2727 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2729 OutputParams const & runparams,
2730 Font const & outerfont,
2731 pos_type initial) const
2733 bool emph_flag = false;
2735 Layout const & style = *d->layout_;
2737 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2739 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2742 // parsing main loop
2743 for (pos_type i = initial; i < size(); ++i) {
2744 Font font = getFont(buf.params(), i, outerfont);
2746 // handle <emphasis> tag
2747 if (font_old.emph() != font.fontInfo().emph()) {
2748 if (font.fontInfo().emph() == FONT_ON) {
2751 } else if (i != initial) {
2752 os << "</emphasis>";
2757 if (Inset const * inset = getInset(i)) {
2758 inset->docbook(os, runparams);
2760 char_type c = d->text_[i];
2762 if (style.pass_thru)
2765 os << sgml::escapeChar(c);
2767 font_old = font.fontInfo();
2771 os << "</emphasis>";
2774 if (style.free_spacing)
2776 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2781 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2783 OutputParams const & runparams,
2784 Font const & outerfont,
2785 pos_type initial) const
2789 bool emph_flag = false;
2790 bool bold_flag = false;
2792 Layout const & style = *d->layout_;
2794 xs.startParagraph(allowEmpty());
2796 if (!runparams.for_toc && runparams.html_make_pars) {
2797 // generate a magic label for this paragraph
2798 string const attr = "id='" + magicLabel() + "'";
2799 xs << html::CompTag("a", attr);
2803 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2805 // parsing main loop
2806 for (pos_type i = initial; i < size(); ++i) {
2807 // let's not show deleted material in the output
2811 Font font = getFont(buf.params(), i, outerfont);
2814 if (font_old.emph() != font.fontInfo().emph()) {
2815 if (font.fontInfo().emph() == FONT_ON) {
2816 xs << html::StartTag("em");
2818 } else if (emph_flag && i != initial) {
2819 xs << html::EndTag("em");
2824 if (font_old.series() != font.fontInfo().series()) {
2825 if (font.fontInfo().series() == BOLD_SERIES) {
2826 xs << html::StartTag("strong");
2828 } else if (bold_flag && i != initial) {
2829 xs << html::EndTag("strong");
2834 // Other such tags? What about the other text ranges?
2836 Inset const * inset = getInset(i);
2838 if (!runparams.for_toc || inset->isInToc()) {
2839 OutputParams np = runparams;
2840 if (!inset->getLayout().htmlisblock())
2841 np.html_in_par = true;
2842 retval += inset->xhtml(xs, np);
2845 char_type c = d->text_[i];
2847 if (style.pass_thru)
2849 else if (c == '-') {
2852 if (j < size() && d->text_[j] == '-') {
2854 if (j < size() && d->text_[j] == '-') {
2855 str += from_ascii("—");
2858 str += from_ascii("–");
2864 // We don't want to escape the entities. Note that
2865 // it is safe to do this, since str can otherwise
2866 // only be "-". E.g., it can't be "<".
2867 xs << XHTMLStream::ESCAPE_NONE << str;
2871 font_old = font.fontInfo();
2880 bool Paragraph::isHfill(pos_type pos) const
2882 Inset const * inset = getInset(pos);
2883 return inset && (inset->lyxCode() == SPACE_CODE &&
2884 inset->isStretchableSpace());
2888 bool Paragraph::isNewline(pos_type pos) const
2890 Inset const * inset = getInset(pos);
2891 return inset && inset->lyxCode() == NEWLINE_CODE;
2895 bool Paragraph::isLineSeparator(pos_type pos) const
2897 char_type const c = d->text_[pos];
2898 if (isLineSeparatorChar(c))
2900 Inset const * inset = getInset(pos);
2901 return inset && inset->isLineSeparator();
2905 bool Paragraph::isWordSeparator(pos_type pos) const
2909 if (Inset const * inset = getInset(pos))
2910 return !inset->isLetter();
2911 // if we have a hard hyphen (no en- or emdash) or apostrophe
2912 // we pass this to the spell checker
2913 // FIXME: this method is subject to change, visit
2914 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2915 // to get an impression how complex this is.
2916 if (isHardHyphenOrApostrophe(pos))
2918 char_type const c = d->text_[pos];
2919 // We want to pass the escape chars to the spellchecker
2920 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2921 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2925 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2927 pos_type const psize = size();
2930 char_type const c = d->text_[pos];
2931 if (c != '-' && c != '\'')
2933 int nextpos = pos + 1;
2934 int prevpos = pos > 0 ? pos - 1 : 0;
2935 if ((nextpos == psize || isSpace(nextpos))
2936 && (pos == 0 || isSpace(prevpos)))
2939 || ((nextpos == psize || d->text_[nextpos] != '-')
2940 && (pos == 0 || d->text_[prevpos] != '-'));
2944 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2947 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2951 bool Paragraph::isChar(pos_type pos) const
2953 if (Inset const * inset = getInset(pos))
2954 return inset->isChar();
2955 char_type const c = d->text_[pos];
2956 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2960 bool Paragraph::isSpace(pos_type pos) const
2962 if (Inset const * inset = getInset(pos))
2963 return inset->isSpace();
2964 char_type const c = d->text_[pos];
2965 return lyx::isSpace(c);
2970 Paragraph::getParLanguage(BufferParams const & bparams) const
2973 return getFirstFontSettings(bparams).language();
2974 // FIXME: we should check the prev par as well (Lgb)
2975 return bparams.language;
2979 bool Paragraph::isRTL(BufferParams const & bparams) const
2981 return lyxrc.rtl_support
2982 && getParLanguage(bparams)->rightToLeft()
2983 && !inInset().getLayout().forceLTR();
2987 void Paragraph::changeLanguage(BufferParams const & bparams,
2988 Language const * from, Language const * to)
2990 // change language including dummy font change at the end
2991 for (pos_type i = 0; i <= size(); ++i) {
2992 Font font = getFontSettings(bparams, i);
2993 if (font.language() == from) {
2994 font.setLanguage(to);
2996 d->requestSpellCheck(i);
3002 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
3004 Language const * doc_language = bparams.language;
3005 FontList::const_iterator cit = d->fontlist_.begin();
3006 FontList::const_iterator end = d->fontlist_.end();
3008 for (; cit != end; ++cit)
3009 if (cit->font().language() != ignore_language &&
3010 cit->font().language() != latex_language &&
3011 cit->font().language() != doc_language)
3017 void Paragraph::getLanguages(std::set<Language const *> & languages) const
3019 FontList::const_iterator cit = d->fontlist_.begin();
3020 FontList::const_iterator end = d->fontlist_.end();
3022 for (; cit != end; ++cit) {
3023 Language const * lang = cit->font().language();
3024 if (lang != ignore_language &&
3025 lang != latex_language)
3026 languages.insert(lang);
3031 docstring Paragraph::asString(int options) const
3033 return asString(0, size(), options);
3037 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
3039 odocstringstream os;
3042 && options & AS_STR_LABEL
3043 && !d->params_.labelString().empty())
3044 os << d->params_.labelString() << ' ';
3046 for (pos_type i = beg; i < end; ++i) {
3047 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
3049 char_type const c = d->text_[i];
3050 if (isPrintable(c) || c == '\t'
3051 || (c == '\n' && (options & AS_STR_NEWLINES)))
3053 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3054 getInset(i)->toString(os);
3055 if (getInset(i)->asInsetMath())
3064 void Paragraph::forToc(docstring & os, size_t maxlen) const
3066 if (!d->params_.labelString().empty())
3067 os += d->params_.labelString() + ' ';
3068 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3071 char_type const c = d->text_[i];
3074 else if (c == '\t' || c == '\n')
3076 else if (c == META_INSET)
3077 getInset(i)->forToc(os, maxlen);
3082 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3084 odocstringstream os;
3087 && options & AS_STR_LABEL
3088 && !d->params_.labelString().empty())
3089 os << d->params_.labelString() << ' ';
3091 for (pos_type i = beg; i < end; ++i) {
3092 char_type const c = d->text_[i];
3093 if (isPrintable(c) || c == '\t'
3094 || (c == '\n' && (options & AS_STR_NEWLINES)))
3096 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3097 getInset(i)->plaintext(os, runparams);
3105 void Paragraph::setInsetOwner(Inset const * inset)
3107 d->inset_owner_ = inset;
3111 int Paragraph::id() const
3117 void Paragraph::setId(int id)
3123 Layout const & Paragraph::layout() const
3129 void Paragraph::setLayout(Layout const & layout)
3131 d->layout_ = &layout;
3135 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3137 setLayout(tc.defaultLayout());
3141 void Paragraph::setPlainLayout(DocumentClass const & tc)
3143 setLayout(tc.plainLayout());
3147 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3149 if (usePlainLayout())
3150 setPlainLayout(tclass);
3152 setDefaultLayout(tclass);
3156 Inset const & Paragraph::inInset() const
3158 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3159 _("Memory problem"), _("Paragraph not properly initialized")));
3160 return *d->inset_owner_;
3164 ParagraphParameters & Paragraph::params()
3170 ParagraphParameters const & Paragraph::params() const
3176 bool Paragraph::isFreeSpacing() const
3178 if (d->layout_->free_spacing)
3180 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3184 bool Paragraph::allowEmpty() const
3186 if (d->layout_->keepempty)
3188 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3192 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3194 if (!Encodings::isArabicChar(c))
3197 char_type prev_char = ' ';
3198 char_type next_char = ' ';
3200 for (pos_type i = pos - 1; i >= 0; --i) {
3201 char_type const par_char = d->text_[i];
3202 if (!Encodings::isArabicComposeChar(par_char)) {
3203 prev_char = par_char;
3208 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3209 char_type const par_char = d->text_[i];
3210 if (!Encodings::isArabicComposeChar(par_char)) {
3211 next_char = par_char;
3216 if (Encodings::isArabicChar(next_char)) {
3217 if (Encodings::isArabicChar(prev_char) &&
3218 !Encodings::isArabicSpecialChar(prev_char))
3219 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3221 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3223 if (Encodings::isArabicChar(prev_char) &&
3224 !Encodings::isArabicSpecialChar(prev_char))
3225 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3227 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3232 int Paragraph::checkBiblio(Buffer const & buffer)
3235 // This is getting more and more a mess. ...We really should clean
3236 // up this bibitem issue for 1.6.
3238 // Add bibitem insets if necessary
3239 if (d->layout_->labeltype != LABEL_BIBLIO)
3242 bool hasbibitem = !d->insetlist_.empty()
3243 // Insist on it being in pos 0
3244 && d->text_[0] == META_INSET
3245 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3247 bool track_changes = buffer.params().trackChanges;
3252 // remove a bibitem in pos != 0
3253 // restore it later in pos 0 if necessary
3254 // (e.g. if a user inserts contents _before_ the item)
3255 // we're assuming there's only one of these, which there
3257 int erasedInsetPosition = -1;
3258 InsetList::iterator it = d->insetlist_.begin();
3259 InsetList::iterator end = d->insetlist_.end();
3260 for (; it != end; ++it)
3261 if (it->inset->lyxCode() == BIBITEM_CODE
3263 InsetCommand * olditem = it->inset->asInsetCommand();
3264 oldkey = olditem->getParam("key");
3265 oldlabel = olditem->getParam("label");
3266 erasedInsetPosition = it->pos;
3267 eraseChar(erasedInsetPosition, track_changes);
3271 // There was an InsetBibitem at the beginning, and we didn't
3272 // have to erase one.
3273 if (hasbibitem && erasedInsetPosition < 0)
3276 // There was an InsetBibitem at the beginning and we did have to
3277 // erase one. So we give its properties to the beginning inset.
3279 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3280 if (!oldkey.empty())
3281 inset->setParam("key", oldkey);
3282 inset->setParam("label", oldlabel);
3283 return -erasedInsetPosition;
3286 // There was no inset at the beginning, so we need to create one with
3287 // the key and label of the one we erased.
3288 InsetBibitem * inset =
3289 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3290 // restore values of previously deleted item in this par.
3291 if (!oldkey.empty())
3292 inset->setParam("key", oldkey);
3293 inset->setParam("label", oldlabel);
3294 insertInset(0, inset,
3295 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3301 void Paragraph::checkAuthors(AuthorList const & authorList)
3303 d->changes_.checkAuthors(authorList);
3307 bool Paragraph::isChanged(pos_type pos) const
3309 return lookupChange(pos).changed();
3313 bool Paragraph::isInserted(pos_type pos) const
3315 return lookupChange(pos).inserted();
3319 bool Paragraph::isDeleted(pos_type pos) const
3321 return lookupChange(pos).deleted();
3325 InsetList const & Paragraph::insetList() const
3327 return d->insetlist_;
3331 void Paragraph::setBuffer(Buffer & b)
3333 d->insetlist_.setBuffer(b);
3337 Inset * Paragraph::releaseInset(pos_type pos)
3339 Inset * inset = d->insetlist_.release(pos);
3340 /// does not honour change tracking!
3341 eraseChar(pos, false);
3346 Inset * Paragraph::getInset(pos_type pos)
3348 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3349 ? d->insetlist_.get(pos) : 0;
3353 Inset const * Paragraph::getInset(pos_type pos) const
3355 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3356 ? d->insetlist_.get(pos) : 0;
3360 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3361 pos_type & right, TextCase action)
3363 // process sequences of modified characters; in change
3364 // tracking mode, this approach results in much better
3365 // usability than changing case on a char-by-char basis
3368 bool const trackChanges = bparams.trackChanges;
3370 bool capitalize = true;
3372 for (; pos < right; ++pos) {
3373 char_type oldChar = d->text_[pos];
3374 char_type newChar = oldChar;
3376 // ignore insets and don't play with deleted text!
3377 if (oldChar != META_INSET && !isDeleted(pos)) {
3379 case text_lowercase:
3380 newChar = lowercase(oldChar);
3382 case text_capitalization:
3384 newChar = uppercase(oldChar);
3388 case text_uppercase:
3389 newChar = uppercase(oldChar);
3394 if (isWordSeparator(pos) || isDeleted(pos)) {
3395 // permit capitalization again
3399 if (oldChar != newChar) {
3401 if (pos != right - 1)
3403 // step behind the changing area
3407 int erasePos = pos - changes.size();
3408 for (size_t i = 0; i < changes.size(); i++) {
3409 insertChar(pos, changes[i],
3410 getFontSettings(bparams,
3413 if (!eraseChar(erasePos, trackChanges)) {
3416 ++right; // expand selection
3424 int Paragraph::find(docstring const & str, bool cs, bool mw,
3425 pos_type start_pos, bool del) const
3427 pos_type pos = start_pos;
3428 int const strsize = str.length();
3430 pos_type const parsize = d->text_.size();
3431 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3432 // Ignore "invisible" letters such as ligature breaks
3433 // and hyphenation chars while searching
3434 while (pos < parsize - 1 && isInset(pos)) {
3435 odocstringstream os;
3436 getInset(pos)->toString(os);
3437 if (!getInset(pos)->isLetter() || !os.str().empty())
3441 if (cs && str[i] != d->text_[pos])
3443 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3445 if (!del && isDeleted(pos))
3452 // if necessary, check whether string matches word
3454 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3457 && !isWordSeparator(pos))
3461 return pos - start_pos;
3465 char_type Paragraph::getChar(pos_type pos) const
3467 return d->text_[pos];
3471 pos_type Paragraph::size() const
3473 return d->text_.size();
3477 bool Paragraph::empty() const
3479 return d->text_.empty();
3483 bool Paragraph::isInset(pos_type pos) const
3485 return d->text_[pos] == META_INSET;
3489 bool Paragraph::isSeparator(pos_type pos) const
3491 //FIXME: Are we sure this can be the only separator?
3492 return d->text_[pos] == ' ';
3496 void Paragraph::deregisterWords()
3498 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3499 Private::LangWordsMap::const_iterator ite = d->words_.end();
3500 for (; itl != ite; ++itl) {
3501 WordList * wl = theWordList(itl->first);
3502 Private::Words::const_iterator it = (itl->second).begin();
3503 Private::Words::const_iterator et = (itl->second).end();
3504 for (; it != et; ++it)
3511 void Paragraph::locateWord(pos_type & from, pos_type & to,
3512 word_location const loc) const
3515 case WHOLE_WORD_STRICT:
3516 if (from == 0 || from == size()
3517 || isWordSeparator(from)
3518 || isWordSeparator(from - 1)) {
3522 // no break here, we go to the next
3525 // If we are already at the beginning of a word, do nothing
3526 if (!from || isWordSeparator(from - 1))
3528 // no break here, we go to the next
3531 // always move the cursor to the beginning of previous word
3532 while (from && !isWordSeparator(from - 1))
3536 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3539 // no need to move the 'from' cursor
3543 while (to < size() && !isWordSeparator(to))
3548 void Paragraph::collectWords()
3550 pos_type n = size();
3551 for (pos_type pos = 0; pos < n; ++pos) {
3552 if (isWordSeparator(pos))
3554 pos_type from = pos;
3555 locateWord(from, pos, WHOLE_WORD);
3556 if ((pos - from) >= (int)lyxrc.completion_minlength) {
3557 docstring word = asString(from, pos, AS_STR_NONE);
3558 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3559 if (cit == d->fontlist_.end())
3561 Language const * lang = cit->font().language();
3562 d->words_[*lang].insert(word);
3568 void Paragraph::registerWords()
3570 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3571 Private::LangWordsMap::const_iterator ite = d->words_.end();
3572 for (; itl != ite; ++itl) {
3573 WordList * wl = theWordList(itl->first);
3574 Private::Words::const_iterator it = (itl->second).begin();
3575 Private::Words::const_iterator et = (itl->second).end();
3576 for (; it != et; ++it)
3582 void Paragraph::updateWords()
3590 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3592 SkipPositionsIterator begin = skips.begin();
3593 SkipPositions::iterator end = skips.end();
3594 if (pos > 0 && begin < end) {
3596 if (end->last == pos - 1) {
3601 skips.insert(end, FontSpan(pos, pos));
3605 Language * Paragraph::Private::locateSpellRange(
3606 pos_type & from, pos_type & to,
3607 SkipPositions & skips) const
3609 // skip leading white space
3610 while (from < to && owner_->isWordSeparator(from))
3612 // don't check empty range
3615 // get current language
3616 Language * lang = getSpellLanguage(from);
3617 pos_type last = from;
3618 bool samelang = true;
3619 bool sameinset = true;
3620 while (last < to && samelang && sameinset) {
3621 // hop to end of word
3622 while (last < to && !owner_->isWordSeparator(last)) {
3623 if (owner_->getInset(last)) {
3624 appendSkipPosition(skips, last);
3625 } else if (owner_->isDeleted(last)) {
3626 appendSkipPosition(skips, last);
3630 // hop to next word while checking for insets
3631 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3632 if (Inset const * inset = owner_->getInset(last))
3633 sameinset = inset->isChar() && inset->isLetter();
3634 if (sameinset && owner_->isDeleted(last)) {
3635 appendSkipPosition(skips, last);
3640 if (sameinset && last < to) {
3641 // now check for language change
3642 samelang = lang == getSpellLanguage(last);
3645 // if language change detected backstep is needed
3653 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3656 const_cast<Language *>(owner_->getFontSettings(
3657 inset_owner_->buffer().params(), from).language());
3658 if (lang == inset_owner_->buffer().params().language
3659 && !lyxrc.spellchecker_alt_lang.empty()) {
3661 string const lang_variety =
3662 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3663 lang->setCode(lang_code);
3664 lang->setVariety(lang_variety);
3670 void Paragraph::requestSpellCheck(pos_type pos)
3672 d->requestSpellCheck(pos);
3676 bool Paragraph::needsSpellCheck() const
3678 SpellChecker::ChangeNumber speller_change_number = 0;
3679 if (theSpellChecker())
3680 speller_change_number = theSpellChecker()->changeNumber();
3681 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3682 d->speller_state_.needsCompleteRefresh(speller_change_number);
3684 return d->needsSpellCheck();
3688 bool Paragraph::Private::ignoreWord(docstring const & word) const
3690 // Ignore words with digits
3691 // FIXME: make this customizable
3692 // (note that some checkers ignore words with digits by default)
3693 docstring::const_iterator cit = word.begin();
3694 docstring::const_iterator const end = word.end();
3695 for (; cit != end; ++cit) {
3696 if (isNumber((*cit)))
3703 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3704 WordLangTuple & wl, docstring_list & suggestions,
3705 bool do_suggestion, bool check_learned) const
3707 SpellChecker::Result result = SpellChecker::WORD_OK;
3708 SpellChecker * speller = theSpellChecker();
3712 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3715 locateWord(from, to, WHOLE_WORD);
3716 if (from == to || from >= size())
3719 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3720 Language * lang = d->getSpellLanguage(from);
3722 wl = WordLangTuple(word, lang);
3727 if (needsSpellCheck() || check_learned) {
3729 if (!d->ignoreWord(word)) {
3730 bool const trailing_dot = to < size() && d->text_[to] == '.';
3731 result = speller->check(wl);
3732 if (SpellChecker::misspelled(result) && trailing_dot) {
3733 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3734 result = speller->check(wl);
3735 if (!SpellChecker::misspelled(result)) {
3736 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3738 from << ".." << to << "]");
3740 // spell check with dot appended failed too
3741 // restore original word/lang value
3742 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3743 wl = WordLangTuple(word, lang);
3747 if (!SpellChecker::misspelled(result)) {
3748 // area up to the begin of the next word is not misspelled
3749 while (end < size() && isWordSeparator(end))
3752 d->setMisspelled(from, end, result);
3754 result = d->speller_state_.getState(from);
3758 suggestions.clear();
3760 if (SpellChecker::misspelled(result)) {
3761 LYXERR(Debug::GUI, "misspelled word: \"" <<
3763 from << ".." << to << "]");
3765 speller->suggest(wl, suggestions);
3771 void Paragraph::Private::markMisspelledWords(
3772 pos_type const & first, pos_type const & last,
3773 SpellChecker::Result result,
3774 docstring const & word,
3775 SkipPositions const & skips)
3777 if (!SpellChecker::misspelled(result)) {
3778 setMisspelled(first, last, SpellChecker::WORD_OK);
3782 SpellChecker * speller = theSpellChecker();
3783 // locate and enumerate the error positions
3784 int nerrors = speller->numMisspelledWords();
3786 SkipPositionsIterator it = skips.begin();
3787 SkipPositionsIterator et = skips.end();
3788 for (int index = 0; index < nerrors; ++index) {
3791 speller->misspelledWord(index, wstart, wlen);
3792 /// should not happen if speller supports range checks
3793 if (!wlen) continue;
3794 docstring const misspelled = word.substr(wstart, wlen);
3795 wstart += first + numskipped;
3796 if (snext < wstart) {
3797 /// mark the range of correct spelling
3798 numskipped += countSkips(it, et, wstart);
3799 setMisspelled(snext,
3800 wstart - 1, SpellChecker::WORD_OK);
3802 snext = wstart + wlen;
3803 numskipped += countSkips(it, et, snext);
3804 /// mark the range of misspelling
3805 setMisspelled(wstart, snext, result);
3806 LYXERR(Debug::GUI, "misspelled word: \"" <<
3807 misspelled << "\" [" <<
3808 wstart << ".." << (snext-1) << "]");
3811 if (snext <= last) {
3812 /// mark the range of correct spelling at end
3813 setMisspelled(snext, last, SpellChecker::WORD_OK);
3818 void Paragraph::spellCheck() const
3820 SpellChecker * speller = theSpellChecker();
3821 if (!speller || !size() ||!needsSpellCheck())
3825 d->rangeOfSpellCheck(start, endpos);
3826 if (speller->canCheckParagraph()) {
3827 // loop until we leave the range
3828 for (pos_type first = start; first < endpos; ) {
3829 pos_type last = endpos;
3830 Private::SkipPositions skips;
3831 Language * lang = d->locateSpellRange(first, last, skips);
3832 if (first >= endpos)
3834 // start the spell checker on the unit of meaning
3835 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3836 WordLangTuple wl = WordLangTuple(word, lang);
3837 SpellChecker::Result result = word.size() ?
3838 speller->check(wl) : SpellChecker::WORD_OK;
3839 d->markMisspelledWords(first, last, result, word, skips);
3843 static docstring_list suggestions;
3844 pos_type to = endpos;
3845 while (start < endpos) {
3847 spellCheck(start, to, wl, suggestions, false);
3851 d->readySpellCheck();
3855 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3857 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3858 if (result || pos <= 0 || pos > size())
3860 if (check_boundary && (pos == size() || isWordSeparator(pos)))
3861 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3866 string Paragraph::magicLabel() const
3869 ss << "magicparlabel-" << id();