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);
348 bool latexSpecialTypewriter(
352 unsigned int & column);
354 bool latexSpecialPhrase(
358 unsigned int & column,
359 OutputParams const & runparams);
362 void validate(LaTeXFeatures & features) const;
364 /// Checks if the paragraph contains only text and no inset or font change.
365 bool onlyText(Buffer const & buf, Font const & outerfont,
366 pos_type initial) const;
368 /// match a string against a particular point in the paragraph
369 bool isTextAt(string const & str, pos_type pos) const;
371 /// a vector of speller skip positions
372 typedef vector<FontSpan> SkipPositions;
373 typedef SkipPositions::const_iterator SkipPositionsIterator;
375 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
377 Language * getSpellLanguage(pos_type const from) const;
379 Language * locateSpellRange(pos_type & from, pos_type & to,
380 SkipPositions & skips) const;
382 bool hasSpellerChange() const {
383 SpellChecker::ChangeNumber speller_change_number = 0;
384 if (theSpellChecker())
385 speller_change_number = theSpellChecker()->changeNumber();
386 return speller_change_number > speller_state_.currentChangeNumber();
389 bool ignoreWord(docstring const & word) const ;
391 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
393 pos_type textsize = owner_->size();
394 // check for sane arguments
395 if (to <= from || from >= textsize)
397 FontSpan fp = FontSpan(from, to - 1);
398 speller_state_.setRange(fp, state);
401 void requestSpellCheck(pos_type pos) {
403 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
405 speller_state_.needsRefresh(pos);
408 void readySpellCheck() {
409 speller_state_.needsRefresh(-1);
412 bool needsSpellCheck() const
414 return speller_state_.needsRefresh();
417 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
419 speller_state_.refreshRange(first, last);
421 last = owner_->size();
424 pos_type endpos = last;
425 owner_->locateWord(first, endpos, WHOLE_WORD);
428 owner_->locateWord(last, endpos, WHOLE_WORD);
433 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
437 while (it != et && it->first < start) {
438 int skip = it->last - it->first + 1;
446 void markMisspelledWords(pos_type const & first, pos_type const & last,
447 SpellChecker::Result result,
448 docstring const & word,
449 SkipPositions const & skips);
451 InsetCode ownerCode() const
453 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
456 /// Which Paragraph owns us?
460 Inset const * inset_owner_;
469 ParagraphParameters params_;
471 /// for recording and looking up changes
475 InsetList insetlist_;
478 pos_type begin_of_body_;
480 typedef docstring TextContainer;
484 typedef set<docstring> Words;
485 typedef map<Language, Words> LangWordsMap;
489 Layout const * layout_;
491 SpellCheckerState speller_state_;
497 struct special_phrase {
503 special_phrase const special_phrases[] = {
504 { "LyX", from_ascii("\\LyX{}"), false },
505 { "TeX", from_ascii("\\TeX{}"), true },
506 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
507 { "LaTeX", from_ascii("\\LaTeX{}"), true },
510 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
515 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
516 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
522 // Initialization of the counter for the paragraph id's,
524 // FIXME: There should be a more intelligent way to generate and use the
525 // paragraph ids per buffer instead a global static counter for all InsetText
526 // in the running program.
527 static int paragraph_id = -1;
529 Paragraph::Private::Private(Private const & p, Paragraph * owner)
530 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
531 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
532 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
535 id_ = ++paragraph_id;
536 requestSpellCheck(p.text_.size());
540 Paragraph::Private::Private(Private const & p, Paragraph * owner,
541 pos_type beg, pos_type end)
542 : owner_(owner), inset_owner_(p.inset_owner_),
543 params_(p.params_), changes_(p.changes_),
544 insetlist_(p.insetlist_, beg, end),
545 begin_of_body_(p.begin_of_body_), words_(p.words_),
548 id_ = ++paragraph_id;
549 if (beg >= pos_type(p.text_.size()))
551 text_ = p.text_.substr(beg, end - beg);
553 FontList::const_iterator fcit = fontlist_.begin();
554 FontList::const_iterator fend = fontlist_.end();
555 for (; fcit != fend; ++fcit) {
556 if (fcit->pos() < beg)
558 if (fcit->pos() >= end) {
559 // Add last entry in the fontlist_.
560 fontlist_.set(text_.size() - 1, fcit->font());
563 // Add a new entry in the fontlist_.
564 fontlist_.set(fcit->pos() - beg, fcit->font());
566 requestSpellCheck(p.text_.size());
570 void Paragraph::addChangesToToc(DocIterator const & cdit,
571 Buffer const & buf) const
573 d->changes_.addToToc(cdit, buf);
577 bool Paragraph::isDeleted(pos_type start, pos_type end) const
579 LASSERT(start >= 0 && start <= size(), /**/);
580 LASSERT(end > start && end <= size() + 1, /**/);
582 return d->changes_.isDeleted(start, end);
586 bool Paragraph::isChanged(pos_type start, pos_type end) const
588 LASSERT(start >= 0 && start <= size(), /**/);
589 LASSERT(end > start && end <= size() + 1, /**/);
591 return d->changes_.isChanged(start, end);
595 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
597 // keep the logic here in sync with the logic of eraseChars()
601 Change const change = d->changes_.lookup(size());
602 return change.inserted() && change.currentAuthor();
606 void Paragraph::setChange(Change const & change)
608 // beware of the imaginary end-of-par character!
609 d->changes_.set(change, 0, size() + 1);
612 * Propagate the change recursively - but not in case of DELETED!
614 * Imagine that your co-author makes changes in an existing inset. He
615 * sends your document to you and you come to the conclusion that the
616 * inset should go completely. If you erase it, LyX must not delete all
617 * text within the inset. Otherwise, the change tracked insertions of
618 * your co-author get lost and there is no way to restore them later.
620 * Conclusion: An inset's content should remain untouched if you delete it
623 if (!change.deleted()) {
624 for (pos_type pos = 0; pos < size(); ++pos) {
625 if (Inset * inset = getInset(pos))
626 inset->setChange(change);
632 void Paragraph::setChange(pos_type pos, Change const & change)
634 LASSERT(pos >= 0 && pos <= size(), /**/);
635 d->changes_.set(change, pos);
637 // see comment in setChange(Change const &) above
638 if (!change.deleted() && pos < size())
639 if (Inset * inset = getInset(pos))
640 inset->setChange(change);
644 Change const & Paragraph::lookupChange(pos_type pos) const
646 LASSERT(pos >= 0 && pos <= size(), /**/);
647 return d->changes_.lookup(pos);
651 void Paragraph::acceptChanges(pos_type start, pos_type end)
653 LASSERT(start >= 0 && start <= size(), /**/);
654 LASSERT(end > start && end <= size() + 1, /**/);
656 for (pos_type pos = start; pos < end; ++pos) {
657 switch (lookupChange(pos).type) {
658 case Change::UNCHANGED:
659 // accept changes in nested inset
660 if (Inset * inset = getInset(pos))
661 inset->acceptChanges();
664 case Change::INSERTED:
665 d->changes_.set(Change(Change::UNCHANGED), pos);
666 // also accept changes in nested inset
667 if (Inset * inset = getInset(pos))
668 inset->acceptChanges();
671 case Change::DELETED:
672 // Suppress access to non-existent
673 // "end-of-paragraph char"
675 eraseChar(pos, false);
686 void Paragraph::rejectChanges(pos_type start, pos_type end)
688 LASSERT(start >= 0 && start <= size(), /**/);
689 LASSERT(end > start && end <= size() + 1, /**/);
691 for (pos_type pos = start; pos < end; ++pos) {
692 switch (lookupChange(pos).type) {
693 case Change::UNCHANGED:
694 // reject changes in nested inset
695 if (Inset * inset = getInset(pos))
696 inset->rejectChanges();
699 case Change::INSERTED:
700 // Suppress access to non-existent
701 // "end-of-paragraph char"
703 eraseChar(pos, false);
709 case Change::DELETED:
710 d->changes_.set(Change(Change::UNCHANGED), pos);
712 // Do NOT reject changes within a deleted inset!
713 // There may be insertions of a co-author inside of it!
721 void Paragraph::Private::insertChar(pos_type pos, char_type c,
722 Change const & change)
724 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
727 changes_.insert(change, pos);
729 // This is actually very common when parsing buffers (and
730 // maybe inserting ascii text)
731 if (pos == pos_type(text_.size())) {
732 // when appending characters, no need to update tables
734 // but we want spell checking
735 requestSpellCheck(pos);
739 text_.insert(text_.begin() + pos, c);
741 // Update the font table.
742 fontlist_.increasePosAfterPos(pos);
745 insetlist_.increasePosAfterPos(pos);
747 // Update list of misspelled positions
748 speller_state_.increasePosAfterPos(pos);
752 bool Paragraph::insertInset(pos_type pos, Inset * inset,
753 Change const & change)
755 LASSERT(inset, /**/);
756 LASSERT(pos >= 0 && pos <= size(), /**/);
758 // Paragraph::insertInset() can be used in cut/copy/paste operation where
759 // d->inset_owner_ is not set yet.
760 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
763 d->insertChar(pos, META_INSET, change);
764 LASSERT(d->text_[pos] == META_INSET, /**/);
766 // Add a new entry in the insetlist_.
767 d->insetlist_.insert(inset, pos);
769 // Some insets require run of spell checker
770 requestSpellCheck(pos);
775 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
777 LASSERT(pos >= 0 && pos <= size(), return false);
779 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
782 Change change = d->changes_.lookup(pos);
784 // set the character to DELETED if
785 // a) it was previously unchanged or
786 // b) it was inserted by a co-author
788 if (!change.changed() ||
789 (change.inserted() && !change.currentAuthor())) {
790 setChange(pos, Change(Change::DELETED));
791 // request run of spell checker
792 requestSpellCheck(pos);
796 if (change.deleted())
800 // Don't physically access the imaginary end-of-paragraph character.
801 // eraseChar() can only mark it as DELETED. A physical deletion of
802 // end-of-par must be handled externally.
808 d->changes_.erase(pos);
810 // if it is an inset, delete the inset entry
811 if (d->text_[pos] == META_INSET)
812 d->insetlist_.erase(pos);
814 d->text_.erase(d->text_.begin() + pos);
816 // Update the fontlist_
817 d->fontlist_.erase(pos);
819 // Update the insetlist_
820 d->insetlist_.decreasePosAfterPos(pos);
822 // Update list of misspelled positions
823 d->speller_state_.decreasePosAfterPos(pos);
824 d->speller_state_.refreshLast(size());
830 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
832 LASSERT(start >= 0 && start <= size(), /**/);
833 LASSERT(end >= start && end <= size() + 1, /**/);
836 for (pos_type count = end - start; count; --count) {
837 if (!eraseChar(i, trackChanges))
844 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
845 char_type next, OutputParams const & runparams)
847 // Writing next here may circumvent a possible font change between
848 // c and next. Since next is only output if it forms a surrogate pair
849 // with c we can ignore this:
850 // A font change inside a surrogate pair does not make sense and is
851 // hopefully impossible to input.
852 // FIXME: change tracking
853 // Is this correct WRT change tracking?
854 Encoding const & encoding = *(runparams.encoding);
855 docstring const latex1 = encoding.latexChar(next);
856 docstring const latex2 = encoding.latexChar(c);
857 if (docstring(1, next) == latex1) {
858 // the encoding supports the combination
859 os << latex2 << latex1;
860 return latex1.length() + latex2.length();
861 } else if (runparams.local_font &&
862 runparams.local_font->language()->lang() == "polutonikogreek") {
863 // polutonikogreek only works without the brackets
864 os << latex1 << latex2;
865 return latex1.length() + latex2.length();
867 os << latex1 << '{' << latex2 << '}';
868 return latex1.length() + latex2.length() + 2;
872 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
875 unsigned int & column,
877 Layout const & style)
879 if (style.pass_thru || runparams.pass_thru)
882 if (i + 1 < int(text_.size())) {
883 char_type next = text_[i + 1];
884 if (Encodings::isCombiningChar(next)) {
885 // This space has an accent, so we must always output it.
886 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
891 if (runparams.linelen > 0
892 && column > runparams.linelen
894 && text_[i - 1] != ' '
895 && (i + 1 < int(text_.size()))
896 // same in FreeSpacing mode
897 && !owner_->isFreeSpacing()
898 // In typewriter mode, we want to avoid
899 // ! . ? : at the end of a line
900 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
901 && (text_[i - 1] == '.'
902 || text_[i - 1] == '?'
903 || text_[i - 1] == ':'
904 || text_[i - 1] == '!'))) {
906 os.texrow().start(owner_->id(), i + 1);
908 } else if (style.free_spacing) {
917 int Paragraph::Private::writeScriptChars(otexstream & os,
918 docstring const & ltx,
919 Change const & runningChange,
920 Encoding const & encoding,
923 // FIXME: modifying i here is not very nice...
925 // We only arrive here when a proper language for character text_[i] has
926 // not been specified (i.e., it could not be translated in the current
927 // latex encoding) or its latex translation has been forced, and it
928 // belongs to a known script.
929 // Parameter ltx contains the latex translation of text_[i] as specified
930 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
931 // The latex macro name "textXXX" specifies the script to which text_[i]
932 // belongs and we use it in order to check whether characters from the
933 // same script immediately follow, such that we can collect them in a
934 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
935 // for the first char but only "<spec>" for all subsequent chars.
936 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
937 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
938 string script = to_ascii(ltx.substr(1, brace1 - 1));
941 bool closing_brace = true;
942 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
943 // Correct encoding is being used, so we can avoid \textgreek.
946 closing_brace = false;
948 os << ltx.substr(pos, length);
949 int size = text_.size();
950 while (i + 1 < size) {
951 char_type const next = text_[i + 1];
952 // Stop here if next character belongs to another script
953 // or there is a change in change tracking status.
954 if (!Encodings::isKnownScriptChar(next, script) ||
955 runningChange != owner_->lookupChange(i + 1))
959 FontList::const_iterator cit = fontlist_.begin();
960 FontList::const_iterator end = fontlist_.end();
961 for (; cit != end; ++cit) {
962 if (cit->pos() >= i && !found) {
963 prev_font = cit->font();
966 if (cit->pos() >= i + 1)
969 // Stop here if there is a font attribute or encoding change.
970 if (found && cit != end && prev_font != cit->font())
972 docstring const latex = encoding.latexChar(next);
973 docstring::size_type const b1 =
974 latex.find_first_of(from_ascii("{"));
975 docstring::size_type const b2 =
976 latex.find_last_of(from_ascii("}"));
977 int const len = b2 - b1 - 1;
978 os << latex.substr(b1 + 1, len);
990 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
992 pos_type const len = str.length();
994 // is the paragraph large enough?
995 if (pos + len > int(text_.size()))
998 // does the wanted text start at point?
999 for (string::size_type i = 0; i < str.length(); ++i) {
1000 // Caution: direct comparison of characters works only
1001 // because str is pure ASCII.
1002 if (str[i] != text_[pos + i])
1006 return fontlist_.hasChangeInRange(pos, len);
1010 void Paragraph::Private::latexInset(BufferParams const & bparams,
1012 OutputParams & runparams,
1013 Font & running_font,
1015 Font const & outerfont,
1017 Change & running_change,
1018 Layout const & style,
1020 unsigned int & column)
1022 Inset * inset = owner_->getInset(i);
1023 LASSERT(inset, /**/);
1025 if (style.pass_thru) {
1026 inset->plaintext(os.os(), runparams);
1030 // FIXME: move this to InsetNewline::latex
1031 if (inset->lyxCode() == NEWLINE_CODE) {
1032 // newlines are handled differently here than
1033 // the default in simpleTeXSpecialChars().
1034 if (!style.newline_allowed) {
1038 column += running_font.latexWriteEndChanges(
1039 os, bparams, runparams,
1040 basefont, basefont);
1044 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1047 basefont = owner_->getLayoutFont(bparams, outerfont);
1048 running_font = basefont;
1050 if (runparams.moving_arg)
1054 os.texrow().start(owner_->id(), i + 1);
1058 if (owner_->isDeleted(i)) {
1059 if( ++runparams.inDeletedInset == 1)
1060 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1063 if (inset->canTrackChanges()) {
1064 column += Changes::latexMarkChange(os, bparams, running_change,
1065 Change(Change::UNCHANGED), runparams);
1066 running_change = Change(Change::UNCHANGED);
1070 odocstream::pos_type const len = os.os().tellp();
1072 if (inset->forceLTR()
1073 && running_font.isRightToLeft()
1074 // ERT is an exception, it should be output with no
1075 // decorations at all
1076 && inset->lyxCode() != ERT_CODE) {
1077 if (running_font.language()->lang() == "farsi")
1084 // FIXME: Bug: we can have an empty font change here!
1085 // if there has just been a font change, we are going to close it
1086 // right now, which means stupid latex code like \textsf{}. AFAIK,
1087 // this does not harm dvi output. A minor bug, thus (JMarc)
1089 // Some insets cannot be inside a font change command.
1090 // However, even such insets *can* be placed in \L or \R
1091 // or their equivalents (for RTL language switches), so we don't
1092 // close the language in those cases.
1093 // ArabTeX, though, cannot handle this special behavior, it seems.
1094 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1095 || running_font.language()->lang() == "arabic_arabtex";
1096 if (open_font && !inset->inheritFont()) {
1097 bool closeLanguage = arabtex
1098 || basefont.isRightToLeft() == running_font.isRightToLeft();
1099 unsigned int count = running_font.latexWriteEndChanges(os,
1100 bparams, runparams, basefont, basefont, closeLanguage);
1102 // if any font properties were closed, update the running_font,
1103 // making sure, however, to leave the language as it was
1105 // FIXME: probably a better way to keep track of the old
1106 // language, than copying the entire font?
1107 Font const copy_font(running_font);
1108 basefont = owner_->getLayoutFont(bparams, outerfont);
1109 running_font = basefont;
1111 running_font.setLanguage(copy_font.language());
1112 // leave font open if language is still open
1113 open_font = (running_font.language() == basefont.language());
1115 runparams.local_font = &basefont;
1119 int prev_rows = os.texrow().rows();
1122 runparams.lastid = id_;
1123 runparams.lastpos = i;
1124 inset->latex(os, runparams);
1125 } catch (EncodingException & e) {
1126 // add location information and throw again.
1133 if (running_font.language()->lang() == "farsi")
1139 if (os.texrow().rows() > prev_rows) {
1140 os.texrow().start(owner_->id(), i + 1);
1143 column += (unsigned int)(os.os().tellp() - len);
1146 if (owner_->isDeleted(i))
1147 --runparams.inDeletedInset;
1151 void Paragraph::Private::latexSpecialChar(otexstream & os,
1152 OutputParams const & runparams,
1153 Font const & running_font,
1154 Change const & running_change,
1155 Layout const & style,
1158 unsigned int & column)
1160 char_type const c = text_[i];
1162 if (style.pass_thru || runparams.pass_thru) {
1164 Encoding const * const enc = runparams.encoding;
1165 if (enc && enc->latexChar(c, true).empty())
1166 throw EncodingException(c);
1172 // If T1 font encoding is used, use the special
1173 // characters it provides.
1174 // NOTE: some languages reset the font encoding
1176 if (!running_font.language()->internalFontEncoding()
1177 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1180 // \tt font needs special treatment
1181 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1182 && latexSpecialTypewriter(c, os, i, column))
1185 // Otherwise, we use what LaTeX provides us.
1188 os << "\\textbackslash{}";
1192 os << "\\textless{}";
1196 os << "\\textgreater{}";
1200 os << "\\textbar{}";
1207 os << "\\char`\\\"{}";
1212 case '%': case '#': case '{':
1220 os << "\\textasciitilde{}";
1225 os << "\\textasciicircum{}";
1232 // avoid being mistaken for optional arguments
1240 // Blanks are printed before font switching.
1241 // Sure? I am not! (try nice-latex)
1242 // I am sure it's correct. LyX might be smarter
1243 // in the future, but for now, nothing wrong is
1249 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1255 Encoding const & encoding = *(runparams.encoding);
1256 if (i + 1 < int(text_.size())) {
1257 char_type next = text_[i + 1];
1258 if (Encodings::isCombiningChar(next)) {
1259 column += latexSurrogatePair(os, c, next, runparams) - 1;
1265 docstring const latex = encoding.latexChar(c);
1266 if (Encodings::isKnownScriptChar(c, script)
1267 && prefixIs(latex, from_ascii("\\" + script)))
1268 column += writeScriptChars(os, latex,
1269 running_change, encoding, i) - 1;
1270 else if (latex.length() > 1 && latex[latex.length() - 1] != '}' &&
1271 latex[latex.length() - 1] != '-') {
1272 // Prevent eating of a following
1273 // space or command corruption by
1274 // following characters
1275 column += latex.length() + 1;
1276 os << latex << "{}";
1278 column += latex.length() - 1;
1286 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1287 pos_type i, unsigned int & column)
1293 // In T1 encoding, these characters exist
1294 // but we should avoid ligatures
1295 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1297 os << "\\textcompwordmark{}";
1304 // soul.sty breaks with \char`\"
1305 os << "\\textquotedbl{}";
1314 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1315 pos_type i, unsigned int & column)
1319 // within \ttfamily, "--" is merged to "-" (no endash)
1320 // so we avoid this rather irritating ligature
1321 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1328 // everything else has to be checked separately
1329 // (depending on the encoding)
1337 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1338 /// do not apply the macro transformation.
1339 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1340 unsigned int & column, OutputParams const & runparams)
1342 // FIXME: if we have "LaTeX" with a font
1343 // change in the middle (before the 'T', then
1344 // the "TeX" part is still special cased.
1345 // Really we should only operate this on
1346 // "words" for some definition of word
1348 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1349 if (!isTextAt(special_phrases[pnr].phrase, i)
1350 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1352 if (runparams.moving_arg)
1354 os << special_phrases[pnr].macro;
1355 i += special_phrases[pnr].phrase.length() - 1;
1356 column += special_phrases[pnr].macro.length() - 1;
1363 void Paragraph::Private::validate(LaTeXFeatures & features) const
1365 if (layout_->inpreamble && inset_owner_) {
1366 bool const is_command = layout_->latextype == LATEX_COMMAND;
1367 Buffer const & buf = inset_owner_->buffer();
1368 BufferParams const & bp = buf.params();
1371 // Using a string stream here circumvents the encoding
1372 // switching machinery of odocstream. Therefore the
1373 // output is wrong if this paragraph contains content
1374 // that needs to switch encoding.
1375 odocstringstream ods;
1376 otexstream os(ods, texrow);
1378 os << '\\' << from_ascii(layout_->latexname());
1379 // we have to provide all the optional arguments here, even though
1380 // the last one is the only one we care about.
1381 // Separate handling of optional argument inset.
1382 if (layout_->optargs != 0 || layout_->reqargs != 0)
1383 latexArgInsets(*owner_, os, features.runparams(),
1384 layout_->reqargs, layout_->optargs);
1386 os << from_ascii(layout_->latexparam());
1388 docstring::size_type const length = ods.str().length();
1389 // this will output "{" at the beginning, but not at the end
1390 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1391 if (ods.str().length() > length) {
1394 string const snippet = to_utf8(ods.str());
1395 features.addPreambleSnippet(snippet);
1399 if (features.runparams().flavor == OutputParams::HTML
1400 && layout_->htmltitle()) {
1401 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1404 // check the params.
1405 if (!params_.spacing().isDefault())
1406 features.require("setspace");
1409 features.useLayout(layout_->name());
1412 fontlist_.validate(features);
1414 // then the indentation
1415 if (!params_.leftIndent().zero())
1416 features.require("ParagraphLeftIndent");
1419 InsetList::const_iterator icit = insetlist_.begin();
1420 InsetList::const_iterator iend = insetlist_.end();
1421 for (; icit != iend; ++icit) {
1423 icit->inset->validate(features);
1424 if (layout_->needprotect &&
1425 icit->inset->lyxCode() == FOOT_CODE)
1426 features.require("NeedLyXFootnoteCode");
1430 // then the contents
1431 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1432 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1433 if (!special_phrases[pnr].builtin
1434 && isTextAt(special_phrases[pnr].phrase, i)) {
1435 features.require(special_phrases[pnr].phrase);
1439 Encodings::validate(text_[i], features);
1443 /////////////////////////////////////////////////////////////////////
1447 /////////////////////////////////////////////////////////////////////
1450 Layout const emptyParagraphLayout;
1453 Paragraph::Paragraph()
1454 : d(new Paragraph::Private(this, emptyParagraphLayout))
1461 Paragraph::Paragraph(Paragraph const & par)
1462 : itemdepth(par.itemdepth),
1463 d(new Paragraph::Private(*par.d, this))
1469 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1470 : itemdepth(par.itemdepth),
1471 d(new Paragraph::Private(*par.d, this, beg, end))
1477 Paragraph & Paragraph::operator=(Paragraph const & par)
1479 // needed as we will destroy the private part before copying it
1481 itemdepth = par.itemdepth;
1485 d = new Private(*par.d, this);
1492 Paragraph::~Paragraph()
1501 // this shall be called just before every "os << ..." action.
1502 void flushString(ostream & os, docstring & s)
1511 void Paragraph::write(ostream & os, BufferParams const & bparams,
1512 depth_type & dth) const
1514 // The beginning or end of a deeper (i.e. nested) area?
1515 if (dth != d->params_.depth()) {
1516 if (d->params_.depth() > dth) {
1517 while (d->params_.depth() > dth) {
1518 os << "\n\\begin_deeper";
1522 while (d->params_.depth() < dth) {
1523 os << "\n\\end_deeper";
1529 // First write the layout
1530 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1532 d->params_.write(os);
1534 Font font1(inherit_font, bparams.language);
1536 Change running_change = Change(Change::UNCHANGED);
1538 // this string is used as a buffer to avoid repetitive calls
1539 // to to_utf8(), which turn out to be expensive (JMarc)
1540 docstring write_buffer;
1543 for (pos_type i = 0; i <= size(); ++i) {
1545 Change const change = lookupChange(i);
1546 if (change != running_change)
1547 flushString(os, write_buffer);
1548 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1549 running_change = change;
1554 // Write font changes
1555 Font font2 = getFontSettings(bparams, i);
1556 if (font2 != font1) {
1557 flushString(os, write_buffer);
1558 font2.lyxWriteChanges(font1, os);
1563 char_type const c = d->text_[i];
1566 if (Inset const * inset = getInset(i)) {
1567 flushString(os, write_buffer);
1568 if (inset->directWrite()) {
1569 // international char, let it write
1570 // code directly so it's shorter in
1576 os << "\\begin_inset ";
1578 os << "\n\\end_inset\n\n";
1584 flushString(os, write_buffer);
1585 os << "\n\\backslash\n";
1589 flushString(os, write_buffer);
1590 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1597 if ((column > 70 && c == ' ')
1599 flushString(os, write_buffer);
1603 // this check is to amend a bug. LyX sometimes
1604 // inserts '\0' this could cause problems.
1606 write_buffer.push_back(c);
1608 LYXERR0("NUL char in structure.");
1614 flushString(os, write_buffer);
1615 os << "\n\\end_layout\n";
1619 void Paragraph::validate(LaTeXFeatures & features) const
1621 d->validate(features);
1625 void Paragraph::insert(pos_type start, docstring const & str,
1626 Font const & font, Change const & change)
1628 for (size_t i = 0, n = str.size(); i != n ; ++i)
1629 insertChar(start + i, str[i], font, change);
1633 void Paragraph::appendChar(char_type c, Font const & font,
1634 Change const & change)
1637 d->changes_.insert(change, d->text_.size());
1638 // when appending characters, no need to update tables
1639 d->text_.push_back(c);
1640 setFont(d->text_.size() - 1, font);
1641 d->requestSpellCheck(d->text_.size() - 1);
1645 void Paragraph::appendString(docstring const & s, Font const & font,
1646 Change const & change)
1648 pos_type end = s.size();
1649 size_t oldsize = d->text_.size();
1650 size_t newsize = oldsize + end;
1651 size_t capacity = d->text_.capacity();
1652 if (newsize >= capacity)
1653 d->text_.reserve(max(capacity + 100, newsize));
1655 // when appending characters, no need to update tables
1658 // FIXME: Optimize this!
1659 for (size_t i = oldsize; i != newsize; ++i) {
1661 d->changes_.insert(change, i);
1662 d->requestSpellCheck(i);
1664 d->fontlist_.set(oldsize, font);
1665 d->fontlist_.set(newsize - 1, font);
1669 void Paragraph::insertChar(pos_type pos, char_type c,
1672 d->insertChar(pos, c, Change(trackChanges ?
1673 Change::INSERTED : Change::UNCHANGED));
1677 void Paragraph::insertChar(pos_type pos, char_type c,
1678 Font const & font, bool trackChanges)
1680 d->insertChar(pos, c, Change(trackChanges ?
1681 Change::INSERTED : Change::UNCHANGED));
1686 void Paragraph::insertChar(pos_type pos, char_type c,
1687 Font const & font, Change const & change)
1689 d->insertChar(pos, c, change);
1694 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1695 Font const & font, Change const & change)
1697 bool const success = insertInset(pos, inset, change);
1698 // Set the font/language of the inset...
1704 void Paragraph::resetFonts(Font const & font)
1706 d->fontlist_.clear();
1707 d->fontlist_.set(0, font);
1708 d->fontlist_.set(d->text_.size() - 1, font);
1711 // Gets uninstantiated font setting at position.
1712 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1716 LYXERR0("pos: " << pos << " size: " << size());
1717 LASSERT(pos <= size(), /**/);
1720 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1721 if (cit != d->fontlist_.end())
1724 if (pos == size() && !empty())
1725 return getFontSettings(bparams, pos - 1);
1727 // Optimisation: avoid a full font instantiation if there is no
1728 // language change from previous call.
1729 static Font previous_font;
1730 static Language const * previous_lang = 0;
1731 Language const * lang = getParLanguage(bparams);
1732 if (lang != previous_lang) {
1733 previous_lang = lang;
1734 previous_font = Font(inherit_font, lang);
1736 return previous_font;
1740 FontSpan Paragraph::fontSpan(pos_type pos) const
1742 LASSERT(pos <= size(), /**/);
1745 FontList::const_iterator cit = d->fontlist_.begin();
1746 FontList::const_iterator end = d->fontlist_.end();
1747 for (; cit != end; ++cit) {
1748 if (cit->pos() >= pos) {
1749 if (pos >= beginOfBody())
1750 return FontSpan(max(start, beginOfBody()),
1753 return FontSpan(start,
1754 min(beginOfBody() - 1,
1757 start = cit->pos() + 1;
1760 // This should not happen, but if so, we take no chances.
1761 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1762 return FontSpan(pos, pos);
1766 // Gets uninstantiated font setting at position 0
1767 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1769 if (!empty() && !d->fontlist_.empty())
1770 return d->fontlist_.begin()->font();
1772 // Optimisation: avoid a full font instantiation if there is no
1773 // language change from previous call.
1774 static Font previous_font;
1775 static Language const * previous_lang = 0;
1776 if (bparams.language != previous_lang) {
1777 previous_lang = bparams.language;
1778 previous_font = Font(inherit_font, bparams.language);
1781 return previous_font;
1785 // Gets the fully instantiated font at a given position in a paragraph
1786 // This is basically the same function as Text::GetFont() in text2.cpp.
1787 // The difference is that this one is used for generating the LaTeX file,
1788 // and thus cosmetic "improvements" are disallowed: This has to deliver
1789 // the true picture of the buffer. (Asger)
1790 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1791 Font const & outerfont) const
1793 LASSERT(pos >= 0, /**/);
1795 Font font = getFontSettings(bparams, pos);
1797 pos_type const body_pos = beginOfBody();
1798 FontInfo & fi = font.fontInfo();
1800 fi.realize(d->layout_->labelfont);
1802 fi.realize(d->layout_->font);
1804 fi.realize(outerfont.fontInfo());
1805 fi.realize(bparams.getFont().fontInfo());
1811 Font const Paragraph::getLabelFont
1812 (BufferParams const & bparams, Font const & outerfont) const
1814 FontInfo tmpfont = d->layout_->labelfont;
1815 tmpfont.realize(outerfont.fontInfo());
1816 tmpfont.realize(bparams.getFont().fontInfo());
1817 return Font(tmpfont, getParLanguage(bparams));
1821 Font const Paragraph::getLayoutFont
1822 (BufferParams const & bparams, Font const & outerfont) const
1824 FontInfo tmpfont = d->layout_->font;
1825 tmpfont.realize(outerfont.fontInfo());
1826 tmpfont.realize(bparams.getFont().fontInfo());
1827 return Font(tmpfont, getParLanguage(bparams));
1831 /// Returns the height of the highest font in range
1832 FontSize Paragraph::highestFontInRange
1833 (pos_type startpos, pos_type endpos, FontSize def_size) const
1835 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1839 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1841 char_type c = d->text_[pos];
1842 if (!lyxrc.rtl_support)
1872 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1878 void Paragraph::setFont(pos_type pos, Font const & font)
1880 LASSERT(pos <= size(), /**/);
1882 // First, reduce font against layout/label font
1883 // Update: The setCharFont() routine in text2.cpp already
1884 // reduces font, so we don't need to do that here. (Asger)
1886 d->fontlist_.set(pos, font);
1890 void Paragraph::makeSameLayout(Paragraph const & par)
1892 d->layout_ = par.d->layout_;
1893 d->params_ = par.d->params_;
1897 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1899 if (isFreeSpacing())
1905 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1906 if (eraseChar(pos, trackChanges))
1912 return count > 0 || pos > 0;
1916 bool Paragraph::hasSameLayout(Paragraph const & par) const
1918 return par.d->layout_ == d->layout_
1919 && d->params_.sameLayout(par.d->params_);
1923 depth_type Paragraph::getDepth() const
1925 return d->params_.depth();
1929 depth_type Paragraph::getMaxDepthAfter() const
1931 if (d->layout_->isEnvironment())
1932 return d->params_.depth() + 1;
1934 return d->params_.depth();
1938 char Paragraph::getAlign() const
1940 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1941 return d->layout_->align;
1943 return d->params_.align();
1947 docstring const & Paragraph::labelString() const
1949 return d->params_.labelString();
1953 // the next two functions are for the manual labels
1954 docstring const Paragraph::getLabelWidthString() const
1956 if (d->layout_->margintype == MARGIN_MANUAL
1957 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1958 return d->params_.labelWidthString();
1960 return _("Senseless with this layout!");
1964 void Paragraph::setLabelWidthString(docstring const & s)
1966 d->params_.labelWidthString(s);
1970 docstring Paragraph::expandLabel(Layout const & layout,
1971 BufferParams const & bparams) const
1973 return expandParagraphLabel(layout, bparams, true);
1977 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1978 BufferParams const & bparams) const
1980 return expandParagraphLabel(layout, bparams, false);
1984 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1985 BufferParams const & bparams, bool process_appendix) const
1987 DocumentClass const & tclass = bparams.documentClass();
1988 string const & lang = getParLanguage(bparams)->code();
1989 bool const in_appendix = process_appendix && d->params_.appendix();
1990 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1992 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1993 && !layout.counter.empty())
1994 return tclass.counters().theCounter(layout.counter, lang);
1996 // handle 'inherited level parts' in 'fmt',
1997 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1998 size_t const i = fmt.find('@', 0);
1999 if (i != docstring::npos) {
2000 size_t const j = fmt.find('@', i + 1);
2001 if (j != docstring::npos) {
2002 docstring parent(fmt, i + 1, j - i - 1);
2003 docstring label = from_ascii("??");
2004 if (tclass.hasLayout(parent))
2005 docstring label = expandParagraphLabel(tclass[parent], bparams,
2007 fmt = docstring(fmt, 0, i) + label
2008 + docstring(fmt, j + 1, docstring::npos);
2012 return tclass.counters().counterLabel(fmt, lang);
2016 void Paragraph::applyLayout(Layout const & new_layout)
2018 d->layout_ = &new_layout;
2019 LyXAlignment const oldAlign = d->params_.align();
2021 if (!(oldAlign & d->layout_->alignpossible)) {
2022 frontend::Alert::warning(_("Alignment not permitted"),
2023 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2024 d->params_.align(LYX_ALIGN_LAYOUT);
2029 pos_type Paragraph::beginOfBody() const
2031 return d->begin_of_body_;
2035 void Paragraph::setBeginOfBody()
2037 if (d->layout_->labeltype != LABEL_MANUAL) {
2038 d->begin_of_body_ = 0;
2042 // Unroll the first two cycles of the loop
2043 // and remember the previous character to
2044 // remove unnecessary getChar() calls
2046 pos_type end = size();
2047 if (i < end && !isNewline(i)) {
2049 char_type previous_char = 0;
2052 previous_char = d->text_[i];
2053 if (!isNewline(i)) {
2055 while (i < end && previous_char != ' ') {
2060 previous_char = temp;
2066 d->begin_of_body_ = i;
2070 bool Paragraph::allowParagraphCustomization() const
2072 return inInset().allowParagraphCustomization();
2076 bool Paragraph::usePlainLayout() const
2078 return inInset().usePlainLayout();
2082 bool Paragraph::isPassThru() const
2084 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2089 // paragraphs inside floats need different alignment tags to avoid
2092 bool noTrivlistCentering(InsetCode code)
2094 return code == FLOAT_CODE
2095 || code == WRAP_CODE
2096 || code == CELL_CODE;
2100 string correction(string const & orig)
2102 if (orig == "flushleft")
2103 return "raggedright";
2104 if (orig == "flushright")
2105 return "raggedleft";
2106 if (orig == "center")
2112 string const corrected_env(string const & suffix, string const & env,
2113 InsetCode code, bool const lastpar)
2115 string output = suffix + "{";
2116 if (noTrivlistCentering(code)) {
2118 // the last paragraph in non-trivlist-aligned
2119 // context is special (to avoid unwanted whitespace)
2120 if (suffix == "\\begin")
2121 return "\\" + correction(env) + "{}";
2124 output += correction(env);
2128 if (suffix == "\\begin")
2134 void adjust_column(string const & str, int & column)
2136 if (!contains(str, "\n"))
2137 column += str.size();
2140 column = rsplit(str, tmp, '\n').size();
2147 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2148 otexstream & os, OutputParams const & runparams) const
2152 if (params_.noindent() && !layout_->pass_thru) {
2153 os << "\\noindent ";
2157 LyXAlignment const curAlign = params_.align();
2159 if (curAlign == layout_->align)
2163 case LYX_ALIGN_NONE:
2164 case LYX_ALIGN_BLOCK:
2165 case LYX_ALIGN_LAYOUT:
2166 case LYX_ALIGN_SPECIAL:
2167 case LYX_ALIGN_DECIMAL:
2169 case LYX_ALIGN_LEFT:
2170 case LYX_ALIGN_RIGHT:
2171 case LYX_ALIGN_CENTER:
2172 if (runparams.moving_arg) {
2179 string const begin_tag = "\\begin";
2180 InsetCode code = ownerCode();
2181 bool const lastpar = runparams.isLastPar;
2184 case LYX_ALIGN_NONE:
2185 case LYX_ALIGN_BLOCK:
2186 case LYX_ALIGN_LAYOUT:
2187 case LYX_ALIGN_SPECIAL:
2188 case LYX_ALIGN_DECIMAL:
2190 case LYX_ALIGN_LEFT: {
2192 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2193 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2195 output = corrected_env(begin_tag, "flushright", code, lastpar);
2196 os << from_ascii(output);
2197 adjust_column(output, column);
2199 } case LYX_ALIGN_RIGHT: {
2201 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2202 output = corrected_env(begin_tag, "flushright", code, lastpar);
2204 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2205 os << from_ascii(output);
2206 adjust_column(output, column);
2208 } case LYX_ALIGN_CENTER: {
2210 output = corrected_env(begin_tag, "center", code, lastpar);
2211 os << from_ascii(output);
2212 adjust_column(output, column);
2221 bool Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2222 otexstream & os, OutputParams const & runparams) const
2224 LyXAlignment const curAlign = params_.align();
2226 if (curAlign == layout_->align)
2230 case LYX_ALIGN_NONE:
2231 case LYX_ALIGN_BLOCK:
2232 case LYX_ALIGN_LAYOUT:
2233 case LYX_ALIGN_SPECIAL:
2234 case LYX_ALIGN_DECIMAL:
2236 case LYX_ALIGN_LEFT:
2237 case LYX_ALIGN_RIGHT:
2238 case LYX_ALIGN_CENTER:
2239 if (runparams.moving_arg)
2245 string const end_tag = "\n\\par\\end";
2246 InsetCode code = ownerCode();
2247 bool const lastpar = runparams.isLastPar;
2250 case LYX_ALIGN_NONE:
2251 case LYX_ALIGN_BLOCK:
2252 case LYX_ALIGN_LAYOUT:
2253 case LYX_ALIGN_SPECIAL:
2254 case LYX_ALIGN_DECIMAL:
2256 case LYX_ALIGN_LEFT: {
2257 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2258 output = corrected_env(end_tag, "flushleft", code, lastpar);
2260 output = corrected_env(end_tag, "flushright", code, lastpar);
2261 os << from_ascii(output);
2263 } case LYX_ALIGN_RIGHT: {
2264 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2265 output = corrected_env(end_tag, "flushright", code, lastpar);
2267 output = corrected_env(end_tag, "flushleft", code, lastpar);
2268 os << from_ascii(output);
2270 } case LYX_ALIGN_CENTER: {
2271 output = corrected_env(end_tag, "center", code, lastpar);
2272 os << from_ascii(output);
2277 return !output.empty() || lastpar;
2281 // This one spits out the text of the paragraph
2282 void Paragraph::latex(BufferParams const & bparams,
2283 Font const & outerfont,
2285 OutputParams const & runparams,
2286 int start_pos, int end_pos, bool force) const
2288 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2290 // FIXME This check should not be needed. Perhaps issue an
2291 // error if it triggers.
2292 Layout const & style = inInset().forcePlainLayout() ?
2293 bparams.documentClass().plainLayout() : *d->layout_;
2295 if (!force && style.inpreamble)
2298 bool const allowcust = allowParagraphCustomization();
2300 // Current base font for all inherited font changes, without any
2301 // change caused by an individual character, except for the language:
2302 // It is set to the language of the first character.
2303 // As long as we are in the label, this font is the base font of the
2304 // label. Before the first body character it is set to the base font
2308 // Maybe we have to create a optional argument.
2309 pos_type body_pos = beginOfBody();
2310 unsigned int column = 0;
2313 // the optional argument is kept in curly brackets in
2314 // case it contains a ']'
2315 // This is not strictly needed, but if this is changed it
2316 // would be a file format change, and tex2lyx would need
2317 // to be adjusted, since it unconditionally removes the
2318 // braces when it parses \item.
2321 basefont = getLabelFont(bparams, outerfont);
2323 basefont = getLayoutFont(bparams, outerfont);
2326 // Which font is currently active?
2327 Font running_font(basefont);
2328 // Do we have an open font change?
2329 bool open_font = false;
2331 Change runningChange = Change(Change::UNCHANGED);
2333 Encoding const * const prev_encoding = runparams.encoding;
2335 os.texrow().start(id(), 0);
2337 // if the paragraph is empty, the loop will not be entered at all
2339 if (style.isCommand()) {
2344 column += d->startTeXParParams(bparams, os, runparams);
2347 for (pos_type i = 0; i < size(); ++i) {
2348 // First char in paragraph or after label?
2349 if (i == body_pos) {
2352 column += running_font.latexWriteEndChanges(
2353 os, bparams, runparams,
2354 basefont, basefont);
2357 basefont = getLayoutFont(bparams, outerfont);
2358 running_font = basefont;
2360 column += Changes::latexMarkChange(os, bparams,
2361 runningChange, Change(Change::UNCHANGED),
2363 runningChange = Change(Change::UNCHANGED);
2368 if (style.isCommand()) {
2374 column += d->startTeXParParams(bparams, os,
2378 Change const & change = runparams.inDeletedInset
2379 ? runparams.changeOfDeletedInset : lookupChange(i);
2381 if (bparams.outputChanges && runningChange != change) {
2383 column += running_font.latexWriteEndChanges(
2384 os, bparams, runparams, basefont, basefont);
2387 basefont = getLayoutFont(bparams, outerfont);
2388 running_font = basefont;
2390 column += Changes::latexMarkChange(os, bparams, runningChange,
2392 runningChange = change;
2395 // do not output text which is marked deleted
2396 // if change tracking output is disabled
2397 if (!bparams.outputChanges && change.deleted()) {
2403 // Fully instantiated font
2404 Font const font = getFont(bparams, i, outerfont);
2406 Font const last_font = running_font;
2408 // Do we need to close the previous font?
2410 (font != running_font ||
2411 font.language() != running_font.language()))
2413 column += running_font.latexWriteEndChanges(
2414 os, bparams, runparams, basefont,
2415 (i == body_pos-1) ? basefont : font);
2416 running_font = basefont;
2420 string const running_lang = runparams.use_polyglossia ?
2421 running_font.language()->polyglossia() : running_font.language()->babel();
2422 // close babel's font environment before opening CJK.
2423 string const lang_end_command = runparams.use_polyglossia ?
2424 "\\end{$$lang}" : lyxrc.language_command_end;
2425 if (!running_lang.empty() &&
2426 font.language()->encoding()->package() == Encoding::CJK) {
2427 string end_tag = subst(lang_end_command,
2430 os << from_ascii(end_tag);
2431 column += end_tag.length();
2434 // Switch file encoding if necessary (and allowed)
2435 if (!runparams.pass_thru && !style.pass_thru &&
2436 runparams.encoding->package() != Encoding::none &&
2437 font.language()->encoding()->package() != Encoding::none) {
2438 pair<bool, int> const enc_switch =
2439 switchEncoding(os.os(), bparams, runparams,
2440 *(font.language()->encoding()));
2441 if (enc_switch.first) {
2442 column += enc_switch.second;
2443 runparams.encoding = font.language()->encoding();
2447 char_type const c = d->text_[i];
2449 // Do we need to change font?
2450 if ((font != running_font ||
2451 font.language() != running_font.language()) &&
2454 odocstringstream ods;
2455 column += font.latexWriteStartChanges(ods, bparams,
2456 runparams, basefont,
2458 running_font = font;
2460 docstring fontchange = ods.str();
2461 // check whether the fontchange ends with a \\textcolor
2462 // modifier and the text starts with a space (bug 4473)
2463 docstring const last_modifier = rsplit(fontchange, '\\');
2464 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2465 os << fontchange << from_ascii("{}");
2466 // check if the fontchange ends with a trailing blank
2467 // (like "\small " (see bug 3382)
2468 else if (suffixIs(fontchange, ' ') && c == ' ')
2469 os << fontchange.substr(0, fontchange.size() - 1)
2470 << from_ascii("{}");
2475 // FIXME: think about end_pos implementation...
2476 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2477 // FIXME: integrate this case in latexSpecialChar
2478 // Do not print the separation of the optional argument
2479 // if style.pass_thru is false. This works because
2480 // latexSpecialChar ignores spaces if
2481 // style.pass_thru is false.
2482 if (i != body_pos - 1) {
2483 if (d->simpleTeXBlanks(runparams, os,
2484 i, column, font, style)) {
2485 // A surrogate pair was output. We
2486 // must not call latexSpecialChar
2487 // in this iteration, since it would output
2488 // the combining character again.
2495 OutputParams rp = runparams;
2496 rp.free_spacing = style.free_spacing;
2497 rp.local_font = &font;
2498 rp.intitle = style.intitle;
2500 // Two major modes: LaTeX or plain
2501 // Handle here those cases common to both modes
2502 // and then split to handle the two modes separately.
2503 if (c == META_INSET) {
2504 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2505 d->latexInset(bparams, os, rp, running_font,
2506 basefont, outerfont, open_font,
2507 runningChange, style, i, column);
2510 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2512 d->latexSpecialChar(os, rp, running_font, runningChange,
2513 style, i, end_pos, column);
2514 } catch (EncodingException & e) {
2515 if (runparams.dryrun) {
2516 os << "<" << _("LyX Warning: ")
2517 << _("uncodable character") << " '";
2521 // add location information and throw again.
2530 // Set the encoding to that returned from latexSpecialChar (see
2531 // comment for encoding member in OutputParams.h)
2532 runparams.encoding = rp.encoding;
2535 // If we have an open font definition, we have to close it
2537 #ifdef FIXED_LANGUAGE_END_DETECTION
2539 running_font.latexWriteEndChanges(os, bparams,
2540 runparams, basefont,
2541 next_->getFont(bparams, 0, outerfont));
2543 running_font.latexWriteEndChanges(os, bparams,
2544 runparams, basefont, basefont);
2547 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2548 //FIXME: there as we start another \selectlanguage with the next paragraph if
2549 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2550 running_font.latexWriteEndChanges(os, bparams, runparams,
2551 basefont, basefont);
2555 column += Changes::latexMarkChange(os, bparams, runningChange,
2556 Change(Change::UNCHANGED), runparams);
2558 // Needed if there is an optional argument but no contents.
2559 if (body_pos > 0 && body_pos == size()) {
2563 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2564 && runparams.encoding != prev_encoding) {
2565 runparams.encoding = prev_encoding;
2566 if (!runparams.isFullUnicode())
2567 os << setEncoding(prev_encoding->iconvName());
2570 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2574 bool Paragraph::emptyTag() const
2576 for (pos_type i = 0; i < size(); ++i) {
2577 if (Inset const * inset = getInset(i)) {
2578 InsetCode lyx_code = inset->lyxCode();
2579 // FIXME testing like that is wrong. What is
2581 if (lyx_code != TOC_CODE &&
2582 lyx_code != INCLUDE_CODE &&
2583 lyx_code != GRAPHICS_CODE &&
2584 lyx_code != ERT_CODE &&
2585 lyx_code != LISTINGS_CODE &&
2586 lyx_code != FLOAT_CODE &&
2587 lyx_code != TABULAR_CODE) {
2591 char_type c = d->text_[i];
2592 if (c != ' ' && c != '\t')
2600 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2603 for (pos_type i = 0; i < size(); ++i) {
2604 if (Inset const * inset = getInset(i)) {
2605 InsetCode lyx_code = inset->lyxCode();
2606 if (lyx_code == LABEL_CODE) {
2607 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2608 docstring const & id = il->getParam("name");
2609 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2617 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2621 for (i = 0; i < size(); ++i) {
2622 if (Inset const * inset = getInset(i)) {
2623 inset->docbook(os, runparams);
2625 char_type c = d->text_[i];
2628 os << sgml::escapeChar(c);
2635 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2639 for (i = 0; i < size(); ++i) {
2640 if (Inset const * inset = getInset(i)) {
2641 inset->xhtml(xs, runparams);
2643 char_type c = d->text_[i];
2653 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2656 pos_type size = text_.size();
2657 for (pos_type i = initial; i < size; ++i) {
2658 Font font = owner_->getFont(buf.params(), i, outerfont);
2659 if (text_[i] == META_INSET)
2661 if (i != initial && font != font_old)
2670 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2672 OutputParams const & runparams,
2673 Font const & outerfont,
2674 pos_type initial) const
2676 bool emph_flag = false;
2678 Layout const & style = *d->layout_;
2680 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2682 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2685 // parsing main loop
2686 for (pos_type i = initial; i < size(); ++i) {
2687 Font font = getFont(buf.params(), i, outerfont);
2689 // handle <emphasis> tag
2690 if (font_old.emph() != font.fontInfo().emph()) {
2691 if (font.fontInfo().emph() == FONT_ON) {
2694 } else if (i != initial) {
2695 os << "</emphasis>";
2700 if (Inset const * inset = getInset(i)) {
2701 inset->docbook(os, runparams);
2703 char_type c = d->text_[i];
2705 if (style.pass_thru)
2708 os << sgml::escapeChar(c);
2710 font_old = font.fontInfo();
2714 os << "</emphasis>";
2717 if (style.free_spacing)
2719 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2724 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2726 OutputParams const & runparams,
2727 Font const & outerfont,
2728 pos_type initial) const
2732 bool emph_flag = false;
2733 bool bold_flag = false;
2735 Layout const & style = *d->layout_;
2737 xs.startParagraph(allowEmpty());
2739 if (!runparams.for_toc && runparams.html_make_pars) {
2740 // generate a magic label for this paragraph
2741 string const attr = "id='" + magicLabel() + "'";
2742 xs << html::CompTag("a", attr);
2746 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2748 // parsing main loop
2749 for (pos_type i = initial; i < size(); ++i) {
2750 // let's not show deleted material in the output
2754 Font font = getFont(buf.params(), i, outerfont);
2757 if (font_old.emph() != font.fontInfo().emph()) {
2758 if (font.fontInfo().emph() == FONT_ON) {
2759 xs << html::StartTag("em");
2761 } else if (emph_flag && i != initial) {
2762 xs << html::EndTag("em");
2767 if (font_old.series() != font.fontInfo().series()) {
2768 if (font.fontInfo().series() == BOLD_SERIES) {
2769 xs << html::StartTag("strong");
2771 } else if (bold_flag && i != initial) {
2772 xs << html::EndTag("strong");
2777 // Other such tags? What about the other text ranges?
2779 Inset const * inset = getInset(i);
2781 if (!runparams.for_toc || inset->isInToc()) {
2782 OutputParams np = runparams;
2783 if (!inset->getLayout().htmlisblock())
2784 np.html_in_par = true;
2785 retval += inset->xhtml(xs, np);
2788 char_type c = d->text_[i];
2790 if (style.pass_thru)
2792 else if (c == '-') {
2795 if (j < size() && d->text_[j] == '-') {
2797 if (j < size() && d->text_[j] == '-') {
2798 str += from_ascii("—");
2801 str += from_ascii("–");
2807 // We don't want to escape the entities. Note that
2808 // it is safe to do this, since str can otherwise
2809 // only be "-". E.g., it can't be "<".
2810 xs << XHTMLStream::ESCAPE_NONE << str;
2814 font_old = font.fontInfo();
2823 bool Paragraph::isHfill(pos_type pos) const
2825 Inset const * inset = getInset(pos);
2826 return inset && (inset->lyxCode() == SPACE_CODE &&
2827 inset->isStretchableSpace());
2831 bool Paragraph::isNewline(pos_type pos) const
2833 Inset const * inset = getInset(pos);
2834 return inset && inset->lyxCode() == NEWLINE_CODE;
2838 bool Paragraph::isLineSeparator(pos_type pos) const
2840 char_type const c = d->text_[pos];
2841 if (isLineSeparatorChar(c))
2843 Inset const * inset = getInset(pos);
2844 return inset && inset->isLineSeparator();
2848 bool Paragraph::isWordSeparator(pos_type pos) const
2852 if (Inset const * inset = getInset(pos))
2853 return !inset->isLetter();
2854 // if we have a hard hyphen (no en- or emdash) or apostrophe
2855 // we pass this to the spell checker
2856 // FIXME: this method is subject to change, visit
2857 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2858 // to get an impression how complex this is.
2859 if (isHardHyphenOrApostrophe(pos))
2861 char_type const c = d->text_[pos];
2862 // We want to pass the escape chars to the spellchecker
2863 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2864 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2868 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2870 pos_type const psize = size();
2873 char_type const c = d->text_[pos];
2874 if (c != '-' && c != '\'')
2876 int nextpos = pos + 1;
2877 int prevpos = pos > 0 ? pos - 1 : 0;
2878 if ((nextpos == psize || isSpace(nextpos))
2879 && (pos == 0 || isSpace(prevpos)))
2882 || ((nextpos == psize || d->text_[nextpos] != '-')
2883 && (pos == 0 || d->text_[prevpos] != '-'));
2887 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2890 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2894 bool Paragraph::isChar(pos_type pos) const
2896 if (Inset const * inset = getInset(pos))
2897 return inset->isChar();
2898 char_type const c = d->text_[pos];
2899 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2903 bool Paragraph::isSpace(pos_type pos) const
2905 if (Inset const * inset = getInset(pos))
2906 return inset->isSpace();
2907 char_type const c = d->text_[pos];
2908 return lyx::isSpace(c);
2913 Paragraph::getParLanguage(BufferParams const & bparams) const
2916 return getFirstFontSettings(bparams).language();
2917 // FIXME: we should check the prev par as well (Lgb)
2918 return bparams.language;
2922 bool Paragraph::isRTL(BufferParams const & bparams) const
2924 return lyxrc.rtl_support
2925 && getParLanguage(bparams)->rightToLeft()
2926 && !inInset().getLayout().forceLTR();
2930 void Paragraph::changeLanguage(BufferParams const & bparams,
2931 Language const * from, Language const * to)
2933 // change language including dummy font change at the end
2934 for (pos_type i = 0; i <= size(); ++i) {
2935 Font font = getFontSettings(bparams, i);
2936 if (font.language() == from) {
2937 font.setLanguage(to);
2939 d->requestSpellCheck(i);
2945 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2947 Language const * doc_language = bparams.language;
2948 FontList::const_iterator cit = d->fontlist_.begin();
2949 FontList::const_iterator end = d->fontlist_.end();
2951 for (; cit != end; ++cit)
2952 if (cit->font().language() != ignore_language &&
2953 cit->font().language() != latex_language &&
2954 cit->font().language() != doc_language)
2960 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2962 FontList::const_iterator cit = d->fontlist_.begin();
2963 FontList::const_iterator end = d->fontlist_.end();
2965 for (; cit != end; ++cit) {
2966 Language const * lang = cit->font().language();
2967 if (lang != ignore_language &&
2968 lang != latex_language)
2969 languages.insert(lang);
2974 docstring Paragraph::asString(int options) const
2976 return asString(0, size(), options);
2980 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2982 odocstringstream os;
2985 && options & AS_STR_LABEL
2986 && !d->params_.labelString().empty())
2987 os << d->params_.labelString() << ' ';
2989 for (pos_type i = beg; i < end; ++i) {
2990 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2992 char_type const c = d->text_[i];
2993 if (isPrintable(c) || c == '\t'
2994 || (c == '\n' && (options & AS_STR_NEWLINES)))
2996 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2997 getInset(i)->toString(os);
2998 if (getInset(i)->asInsetMath())
3007 void Paragraph::forToc(docstring & os, size_t maxlen) const
3009 if (!d->params_.labelString().empty())
3010 os += d->params_.labelString() + ' ';
3011 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3014 char_type const c = d->text_[i];
3017 else if (c == '\t' || c == '\n')
3019 else if (c == META_INSET)
3020 getInset(i)->forToc(os, maxlen);
3025 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3027 odocstringstream os;
3030 && options & AS_STR_LABEL
3031 && !d->params_.labelString().empty())
3032 os << d->params_.labelString() << ' ';
3034 for (pos_type i = beg; i < end; ++i) {
3035 char_type const c = d->text_[i];
3036 if (isPrintable(c) || c == '\t'
3037 || (c == '\n' && (options & AS_STR_NEWLINES)))
3039 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3040 getInset(i)->plaintext(os, runparams);
3048 void Paragraph::setInsetOwner(Inset const * inset)
3050 d->inset_owner_ = inset;
3054 int Paragraph::id() const
3060 void Paragraph::setId(int id)
3066 Layout const & Paragraph::layout() const
3072 void Paragraph::setLayout(Layout const & layout)
3074 d->layout_ = &layout;
3078 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3080 setLayout(tc.defaultLayout());
3084 void Paragraph::setPlainLayout(DocumentClass const & tc)
3086 setLayout(tc.plainLayout());
3090 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3092 if (usePlainLayout())
3093 setPlainLayout(tclass);
3095 setDefaultLayout(tclass);
3099 Inset const & Paragraph::inInset() const
3101 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3102 _("Memory problem"), _("Paragraph not properly initialized")));
3103 return *d->inset_owner_;
3107 ParagraphParameters & Paragraph::params()
3113 ParagraphParameters const & Paragraph::params() const
3119 bool Paragraph::isFreeSpacing() const
3121 if (d->layout_->free_spacing)
3123 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3127 bool Paragraph::allowEmpty() const
3129 if (d->layout_->keepempty)
3131 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3135 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3137 if (!Encodings::isArabicChar(c))
3140 char_type prev_char = ' ';
3141 char_type next_char = ' ';
3143 for (pos_type i = pos - 1; i >= 0; --i) {
3144 char_type const par_char = d->text_[i];
3145 if (!Encodings::isArabicComposeChar(par_char)) {
3146 prev_char = par_char;
3151 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3152 char_type const par_char = d->text_[i];
3153 if (!Encodings::isArabicComposeChar(par_char)) {
3154 next_char = par_char;
3159 if (Encodings::isArabicChar(next_char)) {
3160 if (Encodings::isArabicChar(prev_char) &&
3161 !Encodings::isArabicSpecialChar(prev_char))
3162 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3164 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3166 if (Encodings::isArabicChar(prev_char) &&
3167 !Encodings::isArabicSpecialChar(prev_char))
3168 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3170 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3175 int Paragraph::checkBiblio(Buffer const & buffer)
3178 // This is getting more and more a mess. ...We really should clean
3179 // up this bibitem issue for 1.6.
3181 // Add bibitem insets if necessary
3182 if (d->layout_->labeltype != LABEL_BIBLIO)
3185 bool hasbibitem = !d->insetlist_.empty()
3186 // Insist on it being in pos 0
3187 && d->text_[0] == META_INSET
3188 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3190 bool track_changes = buffer.params().trackChanges;
3195 // remove a bibitem in pos != 0
3196 // restore it later in pos 0 if necessary
3197 // (e.g. if a user inserts contents _before_ the item)
3198 // we're assuming there's only one of these, which there
3200 int erasedInsetPosition = -1;
3201 InsetList::iterator it = d->insetlist_.begin();
3202 InsetList::iterator end = d->insetlist_.end();
3203 for (; it != end; ++it)
3204 if (it->inset->lyxCode() == BIBITEM_CODE
3206 InsetCommand * olditem = it->inset->asInsetCommand();
3207 oldkey = olditem->getParam("key");
3208 oldlabel = olditem->getParam("label");
3209 erasedInsetPosition = it->pos;
3210 eraseChar(erasedInsetPosition, track_changes);
3214 // There was an InsetBibitem at the beginning, and we didn't
3215 // have to erase one.
3216 if (hasbibitem && erasedInsetPosition < 0)
3219 // There was an InsetBibitem at the beginning and we did have to
3220 // erase one. So we give its properties to the beginning inset.
3222 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3223 if (!oldkey.empty())
3224 inset->setParam("key", oldkey);
3225 inset->setParam("label", oldlabel);
3226 return -erasedInsetPosition;
3229 // There was no inset at the beginning, so we need to create one with
3230 // the key and label of the one we erased.
3231 InsetBibitem * inset =
3232 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3233 // restore values of previously deleted item in this par.
3234 if (!oldkey.empty())
3235 inset->setParam("key", oldkey);
3236 inset->setParam("label", oldlabel);
3237 insertInset(0, inset,
3238 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3244 void Paragraph::checkAuthors(AuthorList const & authorList)
3246 d->changes_.checkAuthors(authorList);
3250 bool Paragraph::isChanged(pos_type pos) const
3252 return lookupChange(pos).changed();
3256 bool Paragraph::isInserted(pos_type pos) const
3258 return lookupChange(pos).inserted();
3262 bool Paragraph::isDeleted(pos_type pos) const
3264 return lookupChange(pos).deleted();
3268 InsetList const & Paragraph::insetList() const
3270 return d->insetlist_;
3274 void Paragraph::setBuffer(Buffer & b)
3276 d->insetlist_.setBuffer(b);
3280 Inset * Paragraph::releaseInset(pos_type pos)
3282 Inset * inset = d->insetlist_.release(pos);
3283 /// does not honour change tracking!
3284 eraseChar(pos, false);
3289 Inset * Paragraph::getInset(pos_type pos)
3291 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3292 ? d->insetlist_.get(pos) : 0;
3296 Inset const * Paragraph::getInset(pos_type pos) const
3298 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3299 ? d->insetlist_.get(pos) : 0;
3303 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3304 pos_type & right, TextCase action)
3306 // process sequences of modified characters; in change
3307 // tracking mode, this approach results in much better
3308 // usability than changing case on a char-by-char basis
3311 bool const trackChanges = bparams.trackChanges;
3313 bool capitalize = true;
3315 for (; pos < right; ++pos) {
3316 char_type oldChar = d->text_[pos];
3317 char_type newChar = oldChar;
3319 // ignore insets and don't play with deleted text!
3320 if (oldChar != META_INSET && !isDeleted(pos)) {
3322 case text_lowercase:
3323 newChar = lowercase(oldChar);
3325 case text_capitalization:
3327 newChar = uppercase(oldChar);
3331 case text_uppercase:
3332 newChar = uppercase(oldChar);
3337 if (isWordSeparator(pos) || isDeleted(pos)) {
3338 // permit capitalization again
3342 if (oldChar != newChar) {
3344 if (pos != right - 1)
3346 // step behind the changing area
3350 int erasePos = pos - changes.size();
3351 for (size_t i = 0; i < changes.size(); i++) {
3352 insertChar(pos, changes[i],
3353 getFontSettings(bparams,
3356 if (!eraseChar(erasePos, trackChanges)) {
3359 ++right; // expand selection
3367 int Paragraph::find(docstring const & str, bool cs, bool mw,
3368 pos_type start_pos, bool del) const
3370 pos_type pos = start_pos;
3371 int const strsize = str.length();
3373 pos_type const parsize = d->text_.size();
3374 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3375 // Ignore "invisible" letters such as ligature breaks
3376 // and hyphenation chars while searching
3377 while (pos < parsize - 1 && isInset(pos)) {
3378 odocstringstream os;
3379 getInset(pos)->toString(os);
3380 if (!getInset(pos)->isLetter() || !os.str().empty())
3384 if (cs && str[i] != d->text_[pos])
3386 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3388 if (!del && isDeleted(pos))
3395 // if necessary, check whether string matches word
3397 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3400 && !isWordSeparator(pos))
3404 return pos - start_pos;
3408 char_type Paragraph::getChar(pos_type pos) const
3410 return d->text_[pos];
3414 pos_type Paragraph::size() const
3416 return d->text_.size();
3420 bool Paragraph::empty() const
3422 return d->text_.empty();
3426 bool Paragraph::isInset(pos_type pos) const
3428 return d->text_[pos] == META_INSET;
3432 bool Paragraph::isSeparator(pos_type pos) const
3434 //FIXME: Are we sure this can be the only separator?
3435 return d->text_[pos] == ' ';
3439 void Paragraph::deregisterWords()
3441 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3442 Private::LangWordsMap::const_iterator ite = d->words_.end();
3443 for (; itl != ite; ++itl) {
3444 WordList * wl = theWordList(itl->first);
3445 Private::Words::const_iterator it = (itl->second).begin();
3446 Private::Words::const_iterator et = (itl->second).end();
3447 for (; it != et; ++it)
3454 void Paragraph::locateWord(pos_type & from, pos_type & to,
3455 word_location const loc) const
3458 case WHOLE_WORD_STRICT:
3459 if (from == 0 || from == size()
3460 || isWordSeparator(from)
3461 || isWordSeparator(from - 1)) {
3465 // no break here, we go to the next
3468 // If we are already at the beginning of a word, do nothing
3469 if (!from || isWordSeparator(from - 1))
3471 // no break here, we go to the next
3474 // always move the cursor to the beginning of previous word
3475 while (from && !isWordSeparator(from - 1))
3479 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3482 // no need to move the 'from' cursor
3486 while (to < size() && !isWordSeparator(to))
3491 void Paragraph::collectWords()
3493 pos_type n = size();
3494 for (pos_type pos = 0; pos < n; ++pos) {
3495 if (isWordSeparator(pos))
3497 pos_type from = pos;
3498 locateWord(from, pos, WHOLE_WORD);
3499 if ((pos - from) >= (int)lyxrc.completion_minlength) {
3500 docstring word = asString(from, pos, AS_STR_NONE);
3501 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3502 if (cit == d->fontlist_.end())
3504 Language const * lang = cit->font().language();
3505 d->words_[*lang].insert(word);
3511 void Paragraph::registerWords()
3513 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3514 Private::LangWordsMap::const_iterator ite = d->words_.end();
3515 for (; itl != ite; ++itl) {
3516 WordList * wl = theWordList(itl->first);
3517 Private::Words::const_iterator it = (itl->second).begin();
3518 Private::Words::const_iterator et = (itl->second).end();
3519 for (; it != et; ++it)
3525 void Paragraph::updateWords()
3533 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3535 SkipPositionsIterator begin = skips.begin();
3536 SkipPositions::iterator end = skips.end();
3537 if (pos > 0 && begin < end) {
3539 if (end->last == pos - 1) {
3544 skips.insert(end, FontSpan(pos, pos));
3548 Language * Paragraph::Private::locateSpellRange(
3549 pos_type & from, pos_type & to,
3550 SkipPositions & skips) const
3552 // skip leading white space
3553 while (from < to && owner_->isWordSeparator(from))
3555 // don't check empty range
3558 // get current language
3559 Language * lang = getSpellLanguage(from);
3560 pos_type last = from;
3561 bool samelang = true;
3562 bool sameinset = true;
3563 while (last < to && samelang && sameinset) {
3564 // hop to end of word
3565 while (last < to && !owner_->isWordSeparator(last)) {
3566 if (owner_->getInset(last)) {
3567 appendSkipPosition(skips, last);
3568 } else if (owner_->isDeleted(last)) {
3569 appendSkipPosition(skips, last);
3573 // hop to next word while checking for insets
3574 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3575 if (Inset const * inset = owner_->getInset(last))
3576 sameinset = inset->isChar() && inset->isLetter();
3577 if (sameinset && owner_->isDeleted(last)) {
3578 appendSkipPosition(skips, last);
3583 if (sameinset && last < to) {
3584 // now check for language change
3585 samelang = lang == getSpellLanguage(last);
3588 // if language change detected backstep is needed
3596 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3599 const_cast<Language *>(owner_->getFontSettings(
3600 inset_owner_->buffer().params(), from).language());
3601 if (lang == inset_owner_->buffer().params().language
3602 && !lyxrc.spellchecker_alt_lang.empty()) {
3604 string const lang_variety =
3605 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3606 lang->setCode(lang_code);
3607 lang->setVariety(lang_variety);
3613 void Paragraph::requestSpellCheck(pos_type pos)
3615 d->requestSpellCheck(pos);
3619 bool Paragraph::needsSpellCheck() const
3621 SpellChecker::ChangeNumber speller_change_number = 0;
3622 if (theSpellChecker())
3623 speller_change_number = theSpellChecker()->changeNumber();
3624 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3625 d->speller_state_.needsCompleteRefresh(speller_change_number);
3627 return d->needsSpellCheck();
3631 bool Paragraph::Private::ignoreWord(docstring const & word) const
3633 // Ignore words with digits
3634 // FIXME: make this customizable
3635 // (note that some checkers ignore words with digits by default)
3636 docstring::const_iterator cit = word.begin();
3637 docstring::const_iterator const end = word.end();
3638 for (; cit != end; ++cit) {
3639 if (isNumber((*cit)))
3646 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3647 WordLangTuple & wl, docstring_list & suggestions,
3648 bool do_suggestion, bool check_learned) const
3650 SpellChecker::Result result = SpellChecker::WORD_OK;
3651 SpellChecker * speller = theSpellChecker();
3655 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3658 locateWord(from, to, WHOLE_WORD);
3659 if (from == to || from >= size())
3662 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3663 Language * lang = d->getSpellLanguage(from);
3665 wl = WordLangTuple(word, lang);
3670 if (needsSpellCheck() || check_learned) {
3672 if (!d->ignoreWord(word)) {
3673 bool const trailing_dot = to < size() && d->text_[to] == '.';
3674 result = speller->check(wl);
3675 if (SpellChecker::misspelled(result) && trailing_dot) {
3676 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3677 result = speller->check(wl);
3678 if (!SpellChecker::misspelled(result)) {
3679 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3681 from << ".." << to << "]");
3683 // spell check with dot appended failed too
3684 // restore original word/lang value
3685 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3686 wl = WordLangTuple(word, lang);
3690 if (!SpellChecker::misspelled(result)) {
3691 // area up to the begin of the next word is not misspelled
3692 while (end < size() && isWordSeparator(end))
3695 d->setMisspelled(from, end, result);
3697 result = d->speller_state_.getState(from);
3701 suggestions.clear();
3703 if (SpellChecker::misspelled(result)) {
3704 LYXERR(Debug::GUI, "misspelled word: \"" <<
3706 from << ".." << to << "]");
3708 speller->suggest(wl, suggestions);
3714 void Paragraph::Private::markMisspelledWords(
3715 pos_type const & first, pos_type const & last,
3716 SpellChecker::Result result,
3717 docstring const & word,
3718 SkipPositions const & skips)
3720 if (!SpellChecker::misspelled(result)) {
3721 setMisspelled(first, last, SpellChecker::WORD_OK);
3725 SpellChecker * speller = theSpellChecker();
3726 // locate and enumerate the error positions
3727 int nerrors = speller->numMisspelledWords();
3729 SkipPositionsIterator it = skips.begin();
3730 SkipPositionsIterator et = skips.end();
3731 for (int index = 0; index < nerrors; ++index) {
3734 speller->misspelledWord(index, wstart, wlen);
3735 /// should not happen if speller supports range checks
3736 if (!wlen) continue;
3737 docstring const misspelled = word.substr(wstart, wlen);
3738 wstart += first + numskipped;
3739 if (snext < wstart) {
3740 /// mark the range of correct spelling
3741 numskipped += countSkips(it, et, wstart);
3742 setMisspelled(snext,
3743 wstart - 1, SpellChecker::WORD_OK);
3745 snext = wstart + wlen;
3746 numskipped += countSkips(it, et, snext);
3747 /// mark the range of misspelling
3748 setMisspelled(wstart, snext, result);
3749 LYXERR(Debug::GUI, "misspelled word: \"" <<
3750 misspelled << "\" [" <<
3751 wstart << ".." << (snext-1) << "]");
3754 if (snext <= last) {
3755 /// mark the range of correct spelling at end
3756 setMisspelled(snext, last, SpellChecker::WORD_OK);
3761 void Paragraph::spellCheck() const
3763 SpellChecker * speller = theSpellChecker();
3764 if (!speller || !size() ||!needsSpellCheck())
3768 d->rangeOfSpellCheck(start, endpos);
3769 if (speller->canCheckParagraph()) {
3770 // loop until we leave the range
3771 for (pos_type first = start; first < endpos; ) {
3772 pos_type last = endpos;
3773 Private::SkipPositions skips;
3774 Language * lang = d->locateSpellRange(first, last, skips);
3775 if (first >= endpos)
3777 // start the spell checker on the unit of meaning
3778 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3779 WordLangTuple wl = WordLangTuple(word, lang);
3780 SpellChecker::Result result = word.size() ?
3781 speller->check(wl) : SpellChecker::WORD_OK;
3782 d->markMisspelledWords(first, last, result, word, skips);
3786 static docstring_list suggestions;
3787 pos_type to = endpos;
3788 while (start < endpos) {
3790 spellCheck(start, to, wl, suggestions, false);
3794 d->readySpellCheck();
3798 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3800 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3801 if (result || pos <= 0 || pos > size())
3803 if (check_boundary && (pos == size() || isWordSeparator(pos)))
3804 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3809 string Paragraph::magicLabel() const
3812 ss << "magicparlabel-" << id();