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"
47 #include "WordLangTuple.h"
50 #include "frontends/alert.h"
52 #include "insets/InsetBibitem.h"
53 #include "insets/InsetLabel.h"
54 #include "insets/InsetSpecialChar.h"
56 #include "support/debug.h"
57 #include "support/docstring_list.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
68 using namespace lyx::support;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
78 /////////////////////////////////////////////////////////////////////
82 /////////////////////////////////////////////////////////////////////
84 class SpellResultRange {
86 SpellResultRange(FontSpan range, SpellChecker::Result result)
87 : range_(range), result_(result)
90 FontSpan const & range() const { return range_; }
92 void range(FontSpan const & r) { range_ = r; }
94 SpellChecker::Result result() const { return result_; }
96 void result(SpellChecker::Result r) { result_ = r; }
98 bool inside(pos_type pos) const { return range_.inside(pos); }
100 bool covered(FontSpan const & r) const
102 // 1. first of new range inside current range or
103 // 2. last of new range inside current range or
104 // 3. first of current range inside new range or
105 // 4. last of current range inside new range
106 return range_.inside(r.first) || range_.inside(r.last) ||
107 r.inside(range_.first) || r.inside(range_.last);
110 void shift(pos_type pos, int offset)
112 if (range_.first > pos) {
113 range_.first += offset;
114 range_.last += offset;
115 } else if (range_.last > pos) {
116 range_.last += offset;
121 SpellChecker::Result result_ ;
125 /////////////////////////////////////////////////////////////////////
129 /////////////////////////////////////////////////////////////////////
131 class SpellCheckerState {
133 SpellCheckerState() {
134 needs_refresh_ = true;
135 current_change_number_ = 0;
138 void setRange(FontSpan const fp, SpellChecker::Result state)
141 RangesIterator et = ranges_.end();
142 RangesIterator it = ranges_.begin();
143 for (; it != et; ++it) {
144 if (!it->covered(fp))
145 result.push_back(SpellResultRange(it->range(), it->result()));
146 else if (state == SpellChecker::WORD_OK) {
147 // trim or split the current misspelled range
148 // store misspelled ranges only
149 FontSpan range = it->range();
150 if (fp.first > range.first) {
151 // misspelled area in front of WORD_OK
152 range.last = fp.first - 1;
153 result.push_back(SpellResultRange(range, it->result()));
156 if (fp.last < range.last) {
157 // misspelled area after WORD_OK range
158 range.first = fp.last + 1;
159 result.push_back(SpellResultRange(range, it->result()));
164 if (state != SpellChecker::WORD_OK)
165 ranges_.push_back(SpellResultRange(fp, state));
168 void increasePosAfterPos(pos_type pos)
170 correctRangesAfterPos(pos, 1);
174 void decreasePosAfterPos(pos_type pos)
176 correctRangesAfterPos(pos, -1);
180 void refreshLast(pos_type pos)
182 if (pos < refresh_.last)
186 SpellChecker::Result getState(pos_type pos) const
188 SpellChecker::Result result = SpellChecker::WORD_OK;
189 RangesIterator et = ranges_.end();
190 RangesIterator it = ranges_.begin();
191 for (; it != et; ++it) {
192 if(it->inside(pos)) {
199 FontSpan const & getRange(pos_type pos) const
201 /// empty span to indicate mismatch
202 static FontSpan empty_;
203 RangesIterator et = ranges_.end();
204 RangesIterator it = ranges_.begin();
205 for (; it != et; ++it) {
206 if(it->inside(pos)) {
213 bool needsRefresh() const {
214 return needs_refresh_;
217 SpellChecker::ChangeNumber currentChangeNumber() const {
218 return current_change_number_;
221 void refreshRange(pos_type & first, pos_type & last) const {
222 first = refresh_.first;
223 last = refresh_.last;
226 void needsRefresh(pos_type pos) {
227 if (needs_refresh_ && pos != -1) {
228 if (pos < refresh_.first)
229 refresh_.first = pos;
230 if (pos > refresh_.last)
232 } else if (pos != -1) {
233 // init request check for neighbour positions too
234 refresh_.first = pos > 0 ? pos - 1 : 0;
235 // no need for special end of paragraph check
236 refresh_.last = pos + 1;
238 needs_refresh_ = pos != -1;
241 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
242 needs_refresh_ = true;
245 current_change_number_ = change_number;
249 typedef vector<SpellResultRange> Ranges;
250 typedef Ranges::const_iterator RangesIterator;
252 /// the area of the paragraph with pending spell check
255 /// spell state cache version number
256 SpellChecker::ChangeNumber current_change_number_;
259 void correctRangesAfterPos(pos_type pos, int offset)
261 RangesIterator et = ranges_.end();
262 Ranges::iterator it = ranges_.begin();
263 for (; it != et; ++it) {
264 it->shift(pos, offset);
270 /////////////////////////////////////////////////////////////////////
272 // Paragraph::Private
274 /////////////////////////////////////////////////////////////////////
276 class Paragraph::Private
280 Private(Paragraph * owner, Layout const & layout);
281 /// "Copy constructor"
282 Private(Private const &, Paragraph * owner);
283 /// Copy constructor from \p beg to \p end
284 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
287 void insertChar(pos_type pos, char_type c, Change const & change);
289 /// Output the surrogate pair formed by \p c and \p next to \p os.
290 /// \return the number of characters written.
291 int latexSurrogatePair(otexstream & os, char_type c, char_type next,
292 OutputParams const &);
294 /// Output a space in appropriate formatting (or a surrogate pair
295 /// if the next character is a combining character).
296 /// \return whether a surrogate pair was output.
297 bool simpleTeXBlanks(OutputParams const &,
300 unsigned int & column,
302 Layout const & style);
304 /// Output consecutive unicode chars, belonging to the same script as
305 /// specified by the latex macro \p ltx, to \p os starting from \p i.
306 /// \return the number of characters written.
307 int writeScriptChars(otexstream & os, docstring const & ltx,
308 Change const &, Encoding const &, pos_type & i);
310 /// This could go to ParagraphParameters if we want to.
311 int startTeXParParams(BufferParams const &, otexstream &,
312 OutputParams const &) const;
314 /// This could go to ParagraphParameters if we want to.
315 int endTeXParParams(BufferParams const &, otexstream &,
316 OutputParams const &) const;
319 void latexInset(BufferParams const &,
324 Font const & outerfont,
326 Change & running_change,
327 Layout const & style,
329 unsigned int & column);
332 void latexSpecialChar(
334 OutputParams const & runparams,
335 Font const & running_font,
336 Change const & running_change,
337 Layout const & style,
340 unsigned int & column);
347 unsigned int & column);
349 bool latexSpecialTypewriter(
353 unsigned int & column);
355 bool latexSpecialPhrase(
359 unsigned int & column,
360 OutputParams const & runparams);
363 void validate(LaTeXFeatures & features) const;
365 /// Checks if the paragraph contains only text and no inset or font change.
366 bool onlyText(Buffer const & buf, Font const & outerfont,
367 pos_type initial) const;
369 /// match a string against a particular point in the paragraph
370 bool isTextAt(string const & str, pos_type pos) const;
372 /// a vector of speller skip positions
373 typedef vector<FontSpan> SkipPositions;
374 typedef SkipPositions::const_iterator SkipPositionsIterator;
376 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
378 Language * getSpellLanguage(pos_type const from) const;
380 Language * locateSpellRange(pos_type & from, pos_type & to,
381 SkipPositions & skips) const;
383 bool hasSpellerChange() const {
384 SpellChecker::ChangeNumber speller_change_number = 0;
385 if (theSpellChecker())
386 speller_change_number = theSpellChecker()->changeNumber();
387 return speller_change_number > speller_state_.currentChangeNumber();
390 bool ignoreWord(docstring const & word) const ;
392 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
394 pos_type textsize = owner_->size();
395 // check for sane arguments
396 if (to <= from || from >= textsize)
398 FontSpan fp = FontSpan(from, to - 1);
399 speller_state_.setRange(fp, state);
402 void requestSpellCheck(pos_type pos) {
403 speller_state_.needsRefresh(pos);
406 void readySpellCheck() {
407 speller_state_.needsRefresh(-1);
410 bool needsSpellCheck() const
412 return speller_state_.needsRefresh();
415 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
417 speller_state_.refreshRange(first, last);
419 last = owner_->size();
422 pos_type endpos = last;
423 owner_->locateWord(first, endpos, WHOLE_WORD);
426 owner_->locateWord(last, endpos, WHOLE_WORD);
431 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
435 while (it != et && it->first < start) {
436 int skip = it->last - it->first + 1;
444 void markMisspelledWords(pos_type const & first, pos_type const & last,
445 SpellChecker::Result result,
446 docstring const & word,
447 SkipPositions const & skips);
449 InsetCode ownerCode() const
451 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
454 /// Which Paragraph owns us?
458 Inset const * inset_owner_;
467 ParagraphParameters params_;
469 /// for recording and looking up changes
473 InsetList insetlist_;
476 pos_type begin_of_body_;
478 typedef docstring TextContainer;
482 typedef set<docstring> Words;
483 typedef map<Language, Words> LangWordsMap;
487 Layout const * layout_;
489 SpellCheckerState speller_state_;
495 struct special_phrase {
501 special_phrase const special_phrases[] = {
502 { "LyX", from_ascii("\\LyX{}"), false },
503 { "TeX", from_ascii("\\TeX{}"), true },
504 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
505 { "LaTeX", from_ascii("\\LaTeX{}"), true },
508 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
513 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
514 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
520 // Initialization of the counter for the paragraph id's,
522 // FIXME: There should be a more intelligent way to generate and use the
523 // paragraph ids per buffer instead a global static counter for all InsetText
524 // in the running program.
525 static int paragraph_id = -1;
527 Paragraph::Private::Private(Private const & p, Paragraph * owner)
528 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
529 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
530 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
533 id_ = ++paragraph_id;
534 requestSpellCheck(p.text_.size());
538 Paragraph::Private::Private(Private const & p, Paragraph * owner,
539 pos_type beg, pos_type end)
540 : owner_(owner), inset_owner_(p.inset_owner_),
541 params_(p.params_), changes_(p.changes_),
542 insetlist_(p.insetlist_, beg, end),
543 begin_of_body_(p.begin_of_body_), words_(p.words_),
546 id_ = ++paragraph_id;
547 if (beg >= pos_type(p.text_.size()))
549 text_ = p.text_.substr(beg, end - beg);
551 FontList::const_iterator fcit = fontlist_.begin();
552 FontList::const_iterator fend = fontlist_.end();
553 for (; fcit != fend; ++fcit) {
554 if (fcit->pos() < beg)
556 if (fcit->pos() >= end) {
557 // Add last entry in the fontlist_.
558 fontlist_.set(text_.size() - 1, fcit->font());
561 // Add a new entry in the fontlist_.
562 fontlist_.set(fcit->pos() - beg, fcit->font());
564 requestSpellCheck(p.text_.size());
568 void Paragraph::addChangesToToc(DocIterator const & cdit,
569 Buffer const & buf) const
571 d->changes_.addToToc(cdit, buf);
575 bool Paragraph::isDeleted(pos_type start, pos_type end) const
577 LASSERT(start >= 0 && start <= size(), /**/);
578 LASSERT(end > start && end <= size() + 1, /**/);
580 return d->changes_.isDeleted(start, end);
584 bool Paragraph::isChanged(pos_type start, pos_type end) const
586 LASSERT(start >= 0 && start <= size(), /**/);
587 LASSERT(end > start && end <= size() + 1, /**/);
589 return d->changes_.isChanged(start, end);
593 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
595 // keep the logic here in sync with the logic of eraseChars()
599 Change const change = d->changes_.lookup(size());
600 return change.inserted() && change.currentAuthor();
604 void Paragraph::setChange(Change const & change)
606 // beware of the imaginary end-of-par character!
607 d->changes_.set(change, 0, size() + 1);
610 * Propagate the change recursively - but not in case of DELETED!
612 * Imagine that your co-author makes changes in an existing inset. He
613 * sends your document to you and you come to the conclusion that the
614 * inset should go completely. If you erase it, LyX must not delete all
615 * text within the inset. Otherwise, the change tracked insertions of
616 * your co-author get lost and there is no way to restore them later.
618 * Conclusion: An inset's content should remain untouched if you delete it
621 if (!change.deleted()) {
622 for (pos_type pos = 0; pos < size(); ++pos) {
623 if (Inset * inset = getInset(pos))
624 inset->setChange(change);
630 void Paragraph::setChange(pos_type pos, Change const & change)
632 LASSERT(pos >= 0 && pos <= size(), /**/);
633 d->changes_.set(change, pos);
635 // see comment in setChange(Change const &) above
636 if (!change.deleted() && pos < size())
637 if (Inset * inset = getInset(pos))
638 inset->setChange(change);
642 Change const & Paragraph::lookupChange(pos_type pos) const
644 LASSERT(pos >= 0 && pos <= size(), /**/);
645 return d->changes_.lookup(pos);
649 void Paragraph::acceptChanges(pos_type start, pos_type end)
651 LASSERT(start >= 0 && start <= size(), /**/);
652 LASSERT(end > start && end <= size() + 1, /**/);
654 for (pos_type pos = start; pos < end; ++pos) {
655 switch (lookupChange(pos).type) {
656 case Change::UNCHANGED:
657 // accept changes in nested inset
658 if (Inset * inset = getInset(pos))
659 inset->acceptChanges();
662 case Change::INSERTED:
663 d->changes_.set(Change(Change::UNCHANGED), pos);
664 // also accept changes in nested inset
665 if (Inset * inset = getInset(pos))
666 inset->acceptChanges();
669 case Change::DELETED:
670 // Suppress access to non-existent
671 // "end-of-paragraph char"
673 eraseChar(pos, false);
684 void Paragraph::rejectChanges(pos_type start, pos_type end)
686 LASSERT(start >= 0 && start <= size(), /**/);
687 LASSERT(end > start && end <= size() + 1, /**/);
689 for (pos_type pos = start; pos < end; ++pos) {
690 switch (lookupChange(pos).type) {
691 case Change::UNCHANGED:
692 // reject changes in nested inset
693 if (Inset * inset = getInset(pos))
694 inset->rejectChanges();
697 case Change::INSERTED:
698 // Suppress access to non-existent
699 // "end-of-paragraph char"
701 eraseChar(pos, false);
707 case Change::DELETED:
708 d->changes_.set(Change(Change::UNCHANGED), pos);
710 // Do NOT reject changes within a deleted inset!
711 // There may be insertions of a co-author inside of it!
719 void Paragraph::Private::insertChar(pos_type pos, char_type c,
720 Change const & change)
722 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
725 changes_.insert(change, pos);
727 // This is actually very common when parsing buffers (and
728 // maybe inserting ascii text)
729 if (pos == pos_type(text_.size())) {
730 // when appending characters, no need to update tables
732 // but we want spell checking
733 requestSpellCheck(pos);
737 text_.insert(text_.begin() + pos, c);
739 // Update the font table.
740 fontlist_.increasePosAfterPos(pos);
743 insetlist_.increasePosAfterPos(pos);
745 // Update list of misspelled positions
746 speller_state_.increasePosAfterPos(pos);
750 bool Paragraph::insertInset(pos_type pos, Inset * inset,
751 Change const & change)
753 LASSERT(inset, /**/);
754 LASSERT(pos >= 0 && pos <= size(), /**/);
756 // Paragraph::insertInset() can be used in cut/copy/paste operation where
757 // d->inset_owner_ is not set yet.
758 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
761 d->insertChar(pos, META_INSET, change);
762 LASSERT(d->text_[pos] == META_INSET, /**/);
764 // Add a new entry in the insetlist_.
765 d->insetlist_.insert(inset, pos);
767 // Some insets require run of spell checker
768 requestSpellCheck(pos);
773 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
775 LASSERT(pos >= 0 && pos <= size(), return false);
777 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
780 Change change = d->changes_.lookup(pos);
782 // set the character to DELETED if
783 // a) it was previously unchanged or
784 // b) it was inserted by a co-author
786 if (!change.changed() ||
787 (change.inserted() && !change.currentAuthor())) {
788 setChange(pos, Change(Change::DELETED));
789 // request run of spell checker
790 requestSpellCheck(pos);
794 if (change.deleted())
798 // Don't physically access the imaginary end-of-paragraph character.
799 // eraseChar() can only mark it as DELETED. A physical deletion of
800 // end-of-par must be handled externally.
806 d->changes_.erase(pos);
808 // if it is an inset, delete the inset entry
809 if (d->text_[pos] == META_INSET)
810 d->insetlist_.erase(pos);
812 d->text_.erase(d->text_.begin() + pos);
814 // Update the fontlist_
815 d->fontlist_.erase(pos);
817 // Update the insetlist_
818 d->insetlist_.decreasePosAfterPos(pos);
820 // Update list of misspelled positions
821 d->speller_state_.decreasePosAfterPos(pos);
822 d->speller_state_.refreshLast(size());
828 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
830 LASSERT(start >= 0 && start <= size(), /**/);
831 LASSERT(end >= start && end <= size() + 1, /**/);
834 for (pos_type count = end - start; count; --count) {
835 if (!eraseChar(i, trackChanges))
842 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
843 char_type next, OutputParams const & runparams)
845 // Writing next here may circumvent a possible font change between
846 // c and next. Since next is only output if it forms a surrogate pair
847 // with c we can ignore this:
848 // A font change inside a surrogate pair does not make sense and is
849 // hopefully impossible to input.
850 // FIXME: change tracking
851 // Is this correct WRT change tracking?
852 Encoding const & encoding = *(runparams.encoding);
853 docstring const latex1 = encoding.latexChar(next);
854 docstring const latex2 = encoding.latexChar(c);
855 if (docstring(1, next) == latex1) {
856 // the encoding supports the combination
857 os << latex2 << latex1;
858 return latex1.length() + latex2.length();
859 } else if (runparams.local_font &&
860 runparams.local_font->language()->lang() == "polutonikogreek") {
861 // polutonikogreek only works without the brackets
862 os << latex1 << latex2;
863 return latex1.length() + latex2.length();
865 os << latex1 << '{' << latex2 << '}';
866 return latex1.length() + latex2.length() + 2;
870 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
873 unsigned int & column,
875 Layout const & style)
877 if (style.pass_thru || runparams.pass_thru)
880 if (i + 1 < int(text_.size())) {
881 char_type next = text_[i + 1];
882 if (Encodings::isCombiningChar(next)) {
883 // This space has an accent, so we must always output it.
884 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
889 if (runparams.linelen > 0
890 && column > runparams.linelen
892 && text_[i - 1] != ' '
893 && (i + 1 < int(text_.size()))
894 // same in FreeSpacing mode
895 && !owner_->isFreeSpacing()
896 // In typewriter mode, we want to avoid
897 // ! . ? : at the end of a line
898 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
899 && (text_[i - 1] == '.'
900 || text_[i - 1] == '?'
901 || text_[i - 1] == ':'
902 || text_[i - 1] == '!'))) {
904 os.texrow().start(owner_->id(), i + 1);
906 } else if (style.free_spacing) {
915 int Paragraph::Private::writeScriptChars(otexstream & os,
916 docstring const & ltx,
917 Change const & runningChange,
918 Encoding const & encoding,
921 // FIXME: modifying i here is not very nice...
923 // We only arrive here when a proper language for character text_[i] has
924 // not been specified (i.e., it could not be translated in the current
925 // latex encoding) or its latex translation has been forced, and it
926 // belongs to a known script.
927 // Parameter ltx contains the latex translation of text_[i] as specified
928 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
929 // The latex macro name "textXXX" specifies the script to which text_[i]
930 // belongs and we use it in order to check whether characters from the
931 // same script immediately follow, such that we can collect them in a
932 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
933 // for the first char but only "<spec>" for all subsequent chars.
934 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
935 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
936 string script = to_ascii(ltx.substr(1, brace1 - 1));
939 bool closing_brace = true;
940 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
941 // Correct encoding is being used, so we can avoid \textgreek.
944 closing_brace = false;
946 os << ltx.substr(pos, length);
947 int size = text_.size();
948 while (i + 1 < size) {
949 char_type const next = text_[i + 1];
950 // Stop here if next character belongs to another script
951 // or there is a change in change tracking status.
952 if (!Encodings::isKnownScriptChar(next, script) ||
953 runningChange != owner_->lookupChange(i + 1))
957 FontList::const_iterator cit = fontlist_.begin();
958 FontList::const_iterator end = fontlist_.end();
959 for (; cit != end; ++cit) {
960 if (cit->pos() >= i && !found) {
961 prev_font = cit->font();
964 if (cit->pos() >= i + 1)
967 // Stop here if there is a font attribute or encoding change.
968 if (found && cit != end && prev_font != cit->font())
970 docstring const latex = encoding.latexChar(next);
971 docstring::size_type const b1 =
972 latex.find_first_of(from_ascii("{"));
973 docstring::size_type const b2 =
974 latex.find_last_of(from_ascii("}"));
975 int const len = b2 - b1 - 1;
976 os << latex.substr(b1 + 1, len);
988 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
990 pos_type const len = str.length();
992 // is the paragraph large enough?
993 if (pos + len > int(text_.size()))
996 // does the wanted text start at point?
997 for (string::size_type i = 0; i < str.length(); ++i) {
998 // Caution: direct comparison of characters works only
999 // because str is pure ASCII.
1000 if (str[i] != text_[pos + i])
1004 return fontlist_.hasChangeInRange(pos, len);
1008 void Paragraph::Private::latexInset(BufferParams const & bparams,
1010 OutputParams & runparams,
1011 Font & running_font,
1013 Font const & outerfont,
1015 Change & running_change,
1016 Layout const & style,
1018 unsigned int & column)
1020 Inset * inset = owner_->getInset(i);
1021 LASSERT(inset, /**/);
1023 if (style.pass_thru) {
1024 inset->plaintext(os.os(), runparams);
1028 // FIXME: move this to InsetNewline::latex
1029 if (inset->lyxCode() == NEWLINE_CODE) {
1030 // newlines are handled differently here than
1031 // the default in simpleTeXSpecialChars().
1032 if (!style.newline_allowed) {
1036 column += running_font.latexWriteEndChanges(
1037 os, bparams, runparams,
1038 basefont, basefont);
1042 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1045 basefont = owner_->getLayoutFont(bparams, outerfont);
1046 running_font = basefont;
1048 if (runparams.moving_arg)
1052 os.texrow().start(owner_->id(), i + 1);
1056 if (owner_->isDeleted(i)) {
1057 if( ++runparams.inDeletedInset == 1)
1058 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1061 if (inset->canTrackChanges()) {
1062 column += Changes::latexMarkChange(os, bparams, running_change,
1063 Change(Change::UNCHANGED), runparams);
1064 running_change = Change(Change::UNCHANGED);
1068 odocstream::pos_type const len = os.os().tellp();
1070 if (inset->forceLTR()
1071 && running_font.isRightToLeft()
1072 // ERT is an exception, it should be output with no
1073 // decorations at all
1074 && inset->lyxCode() != ERT_CODE) {
1075 if (running_font.language()->lang() == "farsi")
1082 // FIXME: Bug: we can have an empty font change here!
1083 // if there has just been a font change, we are going to close it
1084 // right now, which means stupid latex code like \textsf{}. AFAIK,
1085 // this does not harm dvi output. A minor bug, thus (JMarc)
1087 // Some insets cannot be inside a font change command.
1088 // However, even such insets *can* be placed in \L or \R
1089 // or their equivalents (for RTL language switches), so we don't
1090 // close the language in those cases.
1091 // ArabTeX, though, cannot handle this special behavior, it seems.
1092 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1093 || running_font.language()->lang() == "arabic_arabtex";
1094 if (open_font && inset->noFontChange()) {
1095 bool closeLanguage = arabtex
1096 || basefont.isRightToLeft() == running_font.isRightToLeft();
1097 unsigned int count = running_font.latexWriteEndChanges(os,
1098 bparams, runparams, basefont, basefont, closeLanguage);
1100 // if any font properties were closed, update the running_font,
1101 // making sure, however, to leave the language as it was
1103 // FIXME: probably a better way to keep track of the old
1104 // language, than copying the entire font?
1105 Font const copy_font(running_font);
1106 basefont = owner_->getLayoutFont(bparams, outerfont);
1107 running_font = basefont;
1109 running_font.setLanguage(copy_font.language());
1110 // leave font open if language is still open
1111 open_font = (running_font.language() == basefont.language());
1113 runparams.local_font = &basefont;
1117 int prev_rows = os.texrow().rows();
1120 inset->latex(os, runparams);
1121 } catch (EncodingException & e) {
1122 // add location information and throw again.
1129 if (running_font.language()->lang() == "farsi")
1135 if (os.texrow().rows() > prev_rows) {
1136 os.texrow().start(owner_->id(), i + 1);
1139 column += (unsigned int)(os.os().tellp() - len);
1142 if (owner_->isDeleted(i))
1143 --runparams.inDeletedInset;
1147 void Paragraph::Private::latexSpecialChar(otexstream & os,
1148 OutputParams const & runparams,
1149 Font const & running_font,
1150 Change const & running_change,
1151 Layout const & style,
1154 unsigned int & column)
1156 char_type const c = text_[i];
1158 if (style.pass_thru || runparams.pass_thru) {
1160 // FIXME UNICODE: This can fail if c cannot
1161 // be encoded in the current encoding.
1166 // If T1 font encoding is used, use the special
1167 // characters it provides.
1168 // NOTE: some languages reset the font encoding
1170 if (!running_font.language()->internalFontEncoding()
1171 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1174 // \tt font needs special treatment
1175 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1176 && latexSpecialTypewriter(c, os, i, column))
1179 // Otherwise, we use what LaTeX provides us.
1182 os << "\\textbackslash{}";
1186 os << "\\textless{}";
1190 os << "\\textgreater{}";
1194 os << "\\textbar{}";
1201 os << "\\char`\\\"{}";
1206 case '%': case '#': case '{':
1214 os << "\\textasciitilde{}";
1219 os << "\\textasciicircum{}";
1226 // avoid being mistaken for optional arguments
1234 // Blanks are printed before font switching.
1235 // Sure? I am not! (try nice-latex)
1236 // I am sure it's correct. LyX might be smarter
1237 // in the future, but for now, nothing wrong is
1243 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1249 Encoding const & encoding = *(runparams.encoding);
1250 if (i + 1 < int(text_.size())) {
1251 char_type next = text_[i + 1];
1252 if (Encodings::isCombiningChar(next)) {
1253 column += latexSurrogatePair(os, c, next, runparams) - 1;
1259 docstring const latex = encoding.latexChar(c);
1260 if (Encodings::isKnownScriptChar(c, script)
1261 && prefixIs(latex, from_ascii("\\" + script)))
1262 column += writeScriptChars(os, latex,
1263 running_change, encoding, i) - 1;
1264 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1265 // Prevent eating of a following
1266 // space or command corruption by
1267 // following characters
1268 column += latex.length() + 1;
1269 os << latex << "{}";
1271 column += latex.length() - 1;
1279 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1280 pos_type i, unsigned int & column)
1286 // In T1 encoding, these characters exist
1287 // but we should avoid ligatures
1288 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1290 os << "\\textcompwordmark{}";
1297 // soul.sty breaks with \char`\"
1298 os << "\\textquotedbl{}";
1307 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1308 pos_type i, unsigned int & column)
1312 // within \ttfamily, "--" is merged to "-" (no endash)
1313 // so we avoid this rather irritating ligature
1314 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1321 // everything else has to be checked separately
1322 // (depending on the encoding)
1330 /// If [start_pos, end_pos) does not include entirely the special phrase, then
1331 /// do not apply the macro transformation.
1332 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i, pos_type end_pos,
1333 unsigned int & column, OutputParams const & runparams)
1335 // FIXME: if we have "LaTeX" with a font
1336 // change in the middle (before the 'T', then
1337 // the "TeX" part is still special cased.
1338 // Really we should only operate this on
1339 // "words" for some definition of word
1341 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1342 if (!isTextAt(special_phrases[pnr].phrase, i)
1343 || (end_pos != -1 && i + int(special_phrases[pnr].phrase.size()) > end_pos))
1345 if (runparams.moving_arg)
1347 os << special_phrases[pnr].macro;
1348 i += special_phrases[pnr].phrase.length() - 1;
1349 column += special_phrases[pnr].macro.length() - 1;
1356 void Paragraph::Private::validate(LaTeXFeatures & features) const
1358 if (layout_->inpreamble && inset_owner_) {
1359 bool const is_command = layout_->latextype == LATEX_COMMAND;
1360 Buffer const & buf = inset_owner_->buffer();
1361 BufferParams const & bp = buf.params();
1364 // Using a string stream here circumvents the encoding
1365 // switching machinery of odocstream. Therefore the
1366 // output is wrong if this paragraph contains content
1367 // that needs to switch encoding.
1368 odocstringstream ods;
1369 otexstream os(ods, texrow);
1371 os << '\\' << from_ascii(layout_->latexname());
1372 // we have to provide all the optional arguments here, even though
1373 // the last one is the only one we care about.
1374 // Separate handling of optional argument inset.
1375 if (layout_->optargs != 0 || layout_->reqargs != 0)
1376 latexArgInsets(*owner_, os, features.runparams(),
1377 layout_->reqargs, layout_->optargs);
1379 os << from_ascii(layout_->latexparam());
1381 docstring::size_type const length = ods.str().length();
1382 // this will output "{" at the beginning, but not at the end
1383 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1384 if (ods.str().length() > length) {
1387 string const snippet = to_utf8(ods.str());
1388 features.addPreambleSnippet(snippet);
1392 if (features.runparams().flavor == OutputParams::HTML
1393 && layout_->htmltitle()) {
1394 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1397 // check the params.
1398 if (!params_.spacing().isDefault())
1399 features.require("setspace");
1402 features.useLayout(layout_->name());
1405 fontlist_.validate(features);
1407 // then the indentation
1408 if (!params_.leftIndent().zero())
1409 features.require("ParagraphLeftIndent");
1412 InsetList::const_iterator icit = insetlist_.begin();
1413 InsetList::const_iterator iend = insetlist_.end();
1414 for (; icit != iend; ++icit) {
1416 icit->inset->validate(features);
1417 if (layout_->needprotect &&
1418 icit->inset->lyxCode() == FOOT_CODE)
1419 features.require("NeedLyXFootnoteCode");
1423 // then the contents
1424 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1425 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1426 if (!special_phrases[pnr].builtin
1427 && isTextAt(special_phrases[pnr].phrase, i)) {
1428 features.require(special_phrases[pnr].phrase);
1432 Encodings::validate(text_[i], features);
1436 /////////////////////////////////////////////////////////////////////
1440 /////////////////////////////////////////////////////////////////////
1443 Layout const emptyParagraphLayout;
1446 Paragraph::Paragraph()
1447 : d(new Paragraph::Private(this, emptyParagraphLayout))
1454 Paragraph::Paragraph(Paragraph const & par)
1455 : itemdepth(par.itemdepth),
1456 d(new Paragraph::Private(*par.d, this))
1462 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1463 : itemdepth(par.itemdepth),
1464 d(new Paragraph::Private(*par.d, this, beg, end))
1470 Paragraph & Paragraph::operator=(Paragraph const & par)
1472 // needed as we will destroy the private part before copying it
1474 itemdepth = par.itemdepth;
1478 d = new Private(*par.d, this);
1485 Paragraph::~Paragraph()
1494 // this shall be called just before every "os << ..." action.
1495 void flushString(ostream & os, docstring & s)
1504 void Paragraph::write(ostream & os, BufferParams const & bparams,
1505 depth_type & dth) const
1507 // The beginning or end of a deeper (i.e. nested) area?
1508 if (dth != d->params_.depth()) {
1509 if (d->params_.depth() > dth) {
1510 while (d->params_.depth() > dth) {
1511 os << "\n\\begin_deeper";
1515 while (d->params_.depth() < dth) {
1516 os << "\n\\end_deeper";
1522 // First write the layout
1523 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1525 d->params_.write(os);
1527 Font font1(inherit_font, bparams.language);
1529 Change running_change = Change(Change::UNCHANGED);
1531 // this string is used as a buffer to avoid repetitive calls
1532 // to to_utf8(), which turn out to be expensive (JMarc)
1533 docstring write_buffer;
1536 for (pos_type i = 0; i <= size(); ++i) {
1538 Change const change = lookupChange(i);
1539 if (change != running_change)
1540 flushString(os, write_buffer);
1541 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1542 running_change = change;
1547 // Write font changes
1548 Font font2 = getFontSettings(bparams, i);
1549 if (font2 != font1) {
1550 flushString(os, write_buffer);
1551 font2.lyxWriteChanges(font1, os);
1556 char_type const c = d->text_[i];
1559 if (Inset const * inset = getInset(i)) {
1560 flushString(os, write_buffer);
1561 if (inset->directWrite()) {
1562 // international char, let it write
1563 // code directly so it's shorter in
1569 os << "\\begin_inset ";
1571 os << "\n\\end_inset\n\n";
1577 flushString(os, write_buffer);
1578 os << "\n\\backslash\n";
1582 flushString(os, write_buffer);
1583 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1590 if ((column > 70 && c == ' ')
1592 flushString(os, write_buffer);
1596 // this check is to amend a bug. LyX sometimes
1597 // inserts '\0' this could cause problems.
1599 write_buffer.push_back(c);
1601 LYXERR0("NUL char in structure.");
1607 flushString(os, write_buffer);
1608 os << "\n\\end_layout\n";
1612 void Paragraph::validate(LaTeXFeatures & features) const
1614 d->validate(features);
1618 void Paragraph::insert(pos_type start, docstring const & str,
1619 Font const & font, Change const & change)
1621 for (size_t i = 0, n = str.size(); i != n ; ++i)
1622 insertChar(start + i, str[i], font, change);
1626 void Paragraph::appendChar(char_type c, Font const & font,
1627 Change const & change)
1630 d->changes_.insert(change, d->text_.size());
1631 // when appending characters, no need to update tables
1632 d->text_.push_back(c);
1633 setFont(d->text_.size() - 1, font);
1637 void Paragraph::appendString(docstring const & s, Font const & font,
1638 Change const & change)
1640 pos_type end = s.size();
1641 size_t oldsize = d->text_.size();
1642 size_t newsize = oldsize + end;
1643 size_t capacity = d->text_.capacity();
1644 if (newsize >= capacity)
1645 d->text_.reserve(max(capacity + 100, newsize));
1647 // when appending characters, no need to update tables
1650 // FIXME: Optimize this!
1651 for (size_t i = oldsize; i != newsize; ++i) {
1653 d->changes_.insert(change, i);
1655 d->fontlist_.set(oldsize, font);
1656 d->fontlist_.set(newsize - 1, font);
1660 void Paragraph::insertChar(pos_type pos, char_type c,
1663 d->insertChar(pos, c, Change(trackChanges ?
1664 Change::INSERTED : Change::UNCHANGED));
1668 void Paragraph::insertChar(pos_type pos, char_type c,
1669 Font const & font, bool trackChanges)
1671 d->insertChar(pos, c, Change(trackChanges ?
1672 Change::INSERTED : Change::UNCHANGED));
1677 void Paragraph::insertChar(pos_type pos, char_type c,
1678 Font const & font, Change const & change)
1680 d->insertChar(pos, c, change);
1685 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1686 Font const & font, Change const & change)
1688 bool const success = insertInset(pos, inset, change);
1689 // Set the font/language of the inset...
1695 void Paragraph::resetFonts(Font const & font)
1697 d->fontlist_.clear();
1698 d->fontlist_.set(0, font);
1699 d->fontlist_.set(d->text_.size() - 1, font);
1702 // Gets uninstantiated font setting at position.
1703 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1707 LYXERR0("pos: " << pos << " size: " << size());
1708 LASSERT(pos <= size(), /**/);
1711 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1712 if (cit != d->fontlist_.end())
1715 if (pos == size() && !empty())
1716 return getFontSettings(bparams, pos - 1);
1718 // Optimisation: avoid a full font instantiation if there is no
1719 // language change from previous call.
1720 static Font previous_font;
1721 static Language const * previous_lang = 0;
1722 Language const * lang = getParLanguage(bparams);
1723 if (lang != previous_lang) {
1724 previous_lang = lang;
1725 previous_font = Font(inherit_font, lang);
1727 return previous_font;
1731 FontSpan Paragraph::fontSpan(pos_type pos) const
1733 LASSERT(pos <= size(), /**/);
1736 FontList::const_iterator cit = d->fontlist_.begin();
1737 FontList::const_iterator end = d->fontlist_.end();
1738 for (; cit != end; ++cit) {
1739 if (cit->pos() >= pos) {
1740 if (pos >= beginOfBody())
1741 return FontSpan(max(start, beginOfBody()),
1744 return FontSpan(start,
1745 min(beginOfBody() - 1,
1748 start = cit->pos() + 1;
1751 // This should not happen, but if so, we take no chances.
1752 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1753 return FontSpan(pos, pos);
1757 // Gets uninstantiated font setting at position 0
1758 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1760 if (!empty() && !d->fontlist_.empty())
1761 return d->fontlist_.begin()->font();
1763 // Optimisation: avoid a full font instantiation if there is no
1764 // language change from previous call.
1765 static Font previous_font;
1766 static Language const * previous_lang = 0;
1767 if (bparams.language != previous_lang) {
1768 previous_lang = bparams.language;
1769 previous_font = Font(inherit_font, bparams.language);
1772 return previous_font;
1776 // Gets the fully instantiated font at a given position in a paragraph
1777 // This is basically the same function as Text::GetFont() in text2.cpp.
1778 // The difference is that this one is used for generating the LaTeX file,
1779 // and thus cosmetic "improvements" are disallowed: This has to deliver
1780 // the true picture of the buffer. (Asger)
1781 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1782 Font const & outerfont) const
1784 LASSERT(pos >= 0, /**/);
1786 Font font = getFontSettings(bparams, pos);
1788 pos_type const body_pos = beginOfBody();
1789 FontInfo & fi = font.fontInfo();
1791 fi.realize(d->layout_->labelfont);
1793 fi.realize(d->layout_->font);
1795 fi.realize(outerfont.fontInfo());
1796 fi.realize(bparams.getFont().fontInfo());
1802 Font const Paragraph::getLabelFont
1803 (BufferParams const & bparams, Font const & outerfont) const
1805 FontInfo tmpfont = d->layout_->labelfont;
1806 tmpfont.realize(outerfont.fontInfo());
1807 tmpfont.realize(bparams.getFont().fontInfo());
1808 return Font(tmpfont, getParLanguage(bparams));
1812 Font const Paragraph::getLayoutFont
1813 (BufferParams const & bparams, Font const & outerfont) const
1815 FontInfo tmpfont = d->layout_->font;
1816 tmpfont.realize(outerfont.fontInfo());
1817 tmpfont.realize(bparams.getFont().fontInfo());
1818 return Font(tmpfont, getParLanguage(bparams));
1822 /// Returns the height of the highest font in range
1823 FontSize Paragraph::highestFontInRange
1824 (pos_type startpos, pos_type endpos, FontSize def_size) const
1826 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1830 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1832 char_type c = d->text_[pos];
1833 if (!lyxrc.rtl_support)
1863 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1869 void Paragraph::setFont(pos_type pos, Font const & font)
1871 LASSERT(pos <= size(), /**/);
1873 // First, reduce font against layout/label font
1874 // Update: The setCharFont() routine in text2.cpp already
1875 // reduces font, so we don't need to do that here. (Asger)
1877 d->fontlist_.set(pos, font);
1881 void Paragraph::makeSameLayout(Paragraph const & par)
1883 d->layout_ = par.d->layout_;
1884 d->params_ = par.d->params_;
1888 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1890 if (isFreeSpacing())
1896 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1897 if (eraseChar(pos, trackChanges))
1903 return count > 0 || pos > 0;
1907 bool Paragraph::hasSameLayout(Paragraph const & par) const
1909 return par.d->layout_ == d->layout_
1910 && d->params_.sameLayout(par.d->params_);
1914 depth_type Paragraph::getDepth() const
1916 return d->params_.depth();
1920 depth_type Paragraph::getMaxDepthAfter() const
1922 if (d->layout_->isEnvironment())
1923 return d->params_.depth() + 1;
1925 return d->params_.depth();
1929 char Paragraph::getAlign() const
1931 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1932 return d->layout_->align;
1934 return d->params_.align();
1938 docstring const & Paragraph::labelString() const
1940 return d->params_.labelString();
1944 // the next two functions are for the manual labels
1945 docstring const Paragraph::getLabelWidthString() const
1947 if (d->layout_->margintype == MARGIN_MANUAL
1948 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1949 return d->params_.labelWidthString();
1951 return _("Senseless with this layout!");
1955 void Paragraph::setLabelWidthString(docstring const & s)
1957 d->params_.labelWidthString(s);
1961 docstring Paragraph::expandLabel(Layout const & layout,
1962 BufferParams const & bparams) const
1964 return expandParagraphLabel(layout, bparams, true);
1968 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1969 BufferParams const & bparams) const
1971 return expandParagraphLabel(layout, bparams, false);
1975 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1976 BufferParams const & bparams, bool process_appendix) const
1978 DocumentClass const & tclass = bparams.documentClass();
1979 string const & lang = getParLanguage(bparams)->code();
1980 bool const in_appendix = process_appendix && d->params_.appendix();
1981 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1983 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1984 && !layout.counter.empty())
1985 return tclass.counters().theCounter(layout.counter, lang);
1987 // handle 'inherited level parts' in 'fmt',
1988 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1989 size_t const i = fmt.find('@', 0);
1990 if (i != docstring::npos) {
1991 size_t const j = fmt.find('@', i + 1);
1992 if (j != docstring::npos) {
1993 docstring parent(fmt, i + 1, j - i - 1);
1994 docstring label = from_ascii("??");
1995 if (tclass.hasLayout(parent))
1996 docstring label = expandParagraphLabel(tclass[parent], bparams,
1998 fmt = docstring(fmt, 0, i) + label
1999 + docstring(fmt, j + 1, docstring::npos);
2003 return tclass.counters().counterLabel(fmt, lang);
2007 void Paragraph::applyLayout(Layout const & new_layout)
2009 d->layout_ = &new_layout;
2010 LyXAlignment const oldAlign = d->params_.align();
2012 if (!(oldAlign & d->layout_->alignpossible)) {
2013 frontend::Alert::warning(_("Alignment not permitted"),
2014 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2015 d->params_.align(LYX_ALIGN_LAYOUT);
2020 pos_type Paragraph::beginOfBody() const
2022 return d->begin_of_body_;
2026 void Paragraph::setBeginOfBody()
2028 if (d->layout_->labeltype != LABEL_MANUAL) {
2029 d->begin_of_body_ = 0;
2033 // Unroll the first two cycles of the loop
2034 // and remember the previous character to
2035 // remove unnecessary getChar() calls
2037 pos_type end = size();
2038 if (i < end && !isNewline(i)) {
2040 char_type previous_char = 0;
2043 previous_char = d->text_[i];
2044 if (!isNewline(i)) {
2046 while (i < end && previous_char != ' ') {
2051 previous_char = temp;
2057 d->begin_of_body_ = i;
2061 bool Paragraph::allowParagraphCustomization() const
2063 return inInset().allowParagraphCustomization();
2067 bool Paragraph::usePlainLayout() const
2069 return inInset().usePlainLayout();
2073 bool Paragraph::isPassThru() const
2075 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2080 // paragraphs inside floats need different alignment tags to avoid
2083 bool noTrivlistCentering(InsetCode code)
2085 return code == FLOAT_CODE
2086 || code == WRAP_CODE
2087 || code == CELL_CODE;
2091 string correction(string const & orig)
2093 if (orig == "flushleft")
2094 return "raggedright";
2095 if (orig == "flushright")
2096 return "raggedleft";
2097 if (orig == "center")
2103 string const corrected_env(string const & suffix, string const & env,
2104 InsetCode code, bool const lastpar)
2106 string output = suffix + "{";
2107 if (noTrivlistCentering(code)) {
2109 // the last paragraph in non-trivlist-aligned
2110 // context is special (to avoid unwanted whitespace)
2111 if (suffix == "\\begin")
2112 return "\\" + correction(env) + "{}";
2115 output += correction(env);
2119 if (suffix == "\\begin")
2125 void adjust_column(string const & str, int & column)
2127 if (!contains(str, "\n"))
2128 column += str.size();
2131 column = rsplit(str, tmp, '\n').size();
2138 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2139 otexstream & os, OutputParams const & runparams) const
2143 if (params_.noindent() && !layout_->pass_thru) {
2144 os << "\\noindent ";
2148 LyXAlignment const curAlign = params_.align();
2150 if (curAlign == layout_->align)
2154 case LYX_ALIGN_NONE:
2155 case LYX_ALIGN_BLOCK:
2156 case LYX_ALIGN_LAYOUT:
2157 case LYX_ALIGN_SPECIAL:
2158 case LYX_ALIGN_DECIMAL:
2160 case LYX_ALIGN_LEFT:
2161 case LYX_ALIGN_RIGHT:
2162 case LYX_ALIGN_CENTER:
2163 if (runparams.moving_arg) {
2170 string const begin_tag = "\\begin";
2171 InsetCode code = ownerCode();
2172 bool const lastpar = runparams.isLastPar;
2175 case LYX_ALIGN_NONE:
2176 case LYX_ALIGN_BLOCK:
2177 case LYX_ALIGN_LAYOUT:
2178 case LYX_ALIGN_SPECIAL:
2179 case LYX_ALIGN_DECIMAL:
2181 case LYX_ALIGN_LEFT: {
2183 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2184 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2186 output = corrected_env(begin_tag, "flushright", code, lastpar);
2187 os << from_ascii(output);
2188 adjust_column(output, column);
2190 } case LYX_ALIGN_RIGHT: {
2192 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2193 output = corrected_env(begin_tag, "flushright", code, lastpar);
2195 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2196 os << from_ascii(output);
2197 adjust_column(output, column);
2199 } case LYX_ALIGN_CENTER: {
2201 output = corrected_env(begin_tag, "center", code, lastpar);
2202 os << from_ascii(output);
2203 adjust_column(output, column);
2212 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2213 otexstream & os, OutputParams const & runparams) const
2217 LyXAlignment const curAlign = params_.align();
2219 if (curAlign == layout_->align)
2223 case LYX_ALIGN_NONE:
2224 case LYX_ALIGN_BLOCK:
2225 case LYX_ALIGN_LAYOUT:
2226 case LYX_ALIGN_SPECIAL:
2227 case LYX_ALIGN_DECIMAL:
2229 case LYX_ALIGN_LEFT:
2230 case LYX_ALIGN_RIGHT:
2231 case LYX_ALIGN_CENTER:
2232 if (runparams.moving_arg) {
2239 string const end_tag = "\n\\par\\end";
2240 InsetCode code = ownerCode();
2241 bool const lastpar = runparams.isLastPar;
2244 case LYX_ALIGN_NONE:
2245 case LYX_ALIGN_BLOCK:
2246 case LYX_ALIGN_LAYOUT:
2247 case LYX_ALIGN_SPECIAL:
2248 case LYX_ALIGN_DECIMAL:
2250 case LYX_ALIGN_LEFT: {
2252 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2253 output = corrected_env(end_tag, "flushleft", code, lastpar);
2255 output = corrected_env(end_tag, "flushright", code, lastpar);
2256 os << from_ascii(output);
2257 adjust_column(output, column);
2259 } case LYX_ALIGN_RIGHT: {
2261 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2262 output = corrected_env(end_tag, "flushright", code, lastpar);
2264 output = corrected_env(end_tag, "flushleft", code, lastpar);
2265 os << from_ascii(output);
2266 adjust_column(output, column);
2268 } case LYX_ALIGN_CENTER: {
2270 output = corrected_env(end_tag, "center", code, lastpar);
2271 os << from_ascii(output);
2272 adjust_column(output, column);
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 ']'
2317 basefont = getLabelFont(bparams, outerfont);
2319 basefont = getLayoutFont(bparams, outerfont);
2322 // Which font is currently active?
2323 Font running_font(basefont);
2324 // Do we have an open font change?
2325 bool open_font = false;
2327 Change runningChange = Change(Change::UNCHANGED);
2329 Encoding const * const prev_encoding = runparams.encoding;
2331 os.texrow().start(id(), 0);
2333 // if the paragraph is empty, the loop will not be entered at all
2335 if (style.isCommand()) {
2340 column += d->startTeXParParams(bparams, os, runparams);
2343 for (pos_type i = 0; i < size(); ++i) {
2344 // First char in paragraph or after label?
2345 if (i == body_pos) {
2348 column += running_font.latexWriteEndChanges(
2349 os, bparams, runparams,
2350 basefont, basefont);
2353 basefont = getLayoutFont(bparams, outerfont);
2354 running_font = basefont;
2356 column += Changes::latexMarkChange(os, bparams,
2357 runningChange, Change(Change::UNCHANGED),
2359 runningChange = Change(Change::UNCHANGED);
2364 if (style.isCommand()) {
2370 column += d->startTeXParParams(bparams, os,
2374 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2377 if (bparams.outputChanges && runningChange != change) {
2379 column += running_font.latexWriteEndChanges(
2380 os, bparams, runparams, basefont, basefont);
2383 basefont = getLayoutFont(bparams, outerfont);
2384 running_font = basefont;
2386 column += Changes::latexMarkChange(os, bparams, runningChange,
2388 runningChange = change;
2391 // do not output text which is marked deleted
2392 // if change tracking output is disabled
2393 if (!bparams.outputChanges && change.deleted()) {
2399 // Fully instantiated font
2400 Font const font = getFont(bparams, i, outerfont);
2402 Font const last_font = running_font;
2404 // Do we need to close the previous font?
2406 (font != running_font ||
2407 font.language() != running_font.language()))
2409 column += running_font.latexWriteEndChanges(
2410 os, bparams, runparams, basefont,
2411 (i == body_pos-1) ? basefont : font);
2412 running_font = basefont;
2416 string const running_lang = runparams.use_polyglossia ?
2417 running_font.language()->polyglossia() : running_font.language()->babel();
2418 // close babel's font environment before opening CJK.
2419 string const lang_end_command = runparams.use_polyglossia ?
2420 "\\end{$$lang}" : lyxrc.language_command_end;
2421 if (!running_lang.empty() &&
2422 font.language()->encoding()->package() == Encoding::CJK) {
2423 string end_tag = subst(lang_end_command,
2426 os << from_ascii(end_tag);
2427 column += end_tag.length();
2430 // Switch file encoding if necessary (and allowed)
2431 if (!runparams.pass_thru && !style.pass_thru &&
2432 runparams.encoding->package() != Encoding::none &&
2433 font.language()->encoding()->package() != Encoding::none) {
2434 pair<bool, int> const enc_switch =
2435 switchEncoding(os.os(), bparams, runparams,
2436 *(font.language()->encoding()));
2437 if (enc_switch.first) {
2438 column += enc_switch.second;
2439 runparams.encoding = font.language()->encoding();
2443 char_type const c = d->text_[i];
2445 // Do we need to change font?
2446 if ((font != running_font ||
2447 font.language() != running_font.language()) &&
2450 odocstringstream ods;
2451 column += font.latexWriteStartChanges(ods, bparams,
2452 runparams, basefont,
2454 running_font = font;
2456 docstring fontchange = ods.str();
2457 // check whether the fontchange ends with a \\textcolor
2458 // modifier and the text starts with a space (bug 4473)
2459 docstring const last_modifier = rsplit(fontchange, '\\');
2460 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2461 os << fontchange << from_ascii("{}");
2462 // check if the fontchange ends with a trailing blank
2463 // (like "\small " (see bug 3382)
2464 else if (suffixIs(fontchange, ' ') && c == ' ')
2465 os << fontchange.substr(0, fontchange.size() - 1)
2466 << from_ascii("{}");
2471 // FIXME: think about end_pos implementation...
2472 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2473 // FIXME: integrate this case in latexSpecialChar
2474 // Do not print the separation of the optional argument
2475 // if style.pass_thru is false. This works because
2476 // latexSpecialChar ignores spaces if
2477 // style.pass_thru is false.
2478 if (i != body_pos - 1) {
2479 if (d->simpleTeXBlanks(runparams, os,
2480 i, column, font, style)) {
2481 // A surrogate pair was output. We
2482 // must not call latexSpecialChar
2483 // in this iteration, since it would output
2484 // the combining character again.
2491 OutputParams rp = runparams;
2492 rp.free_spacing = style.free_spacing;
2493 rp.local_font = &font;
2494 rp.intitle = style.intitle;
2496 // Two major modes: LaTeX or plain
2497 // Handle here those cases common to both modes
2498 // and then split to handle the two modes separately.
2499 if (c == META_INSET) {
2500 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2501 d->latexInset(bparams, os, rp, running_font,
2502 basefont, outerfont, open_font,
2503 runningChange, style, i, column);
2506 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2508 d->latexSpecialChar(os, rp, running_font, runningChange,
2509 style, i, end_pos, column);
2510 } catch (EncodingException & e) {
2511 if (runparams.dryrun) {
2512 os << "<" << _("LyX Warning: ")
2513 << _("uncodable character") << " '";
2517 // add location information and throw again.
2526 // Set the encoding to that returned from latexSpecialChar (see
2527 // comment for encoding member in OutputParams.h)
2528 runparams.encoding = rp.encoding;
2531 // If we have an open font definition, we have to close it
2533 #ifdef FIXED_LANGUAGE_END_DETECTION
2535 running_font.latexWriteEndChanges(os, bparams,
2536 runparams, basefont,
2537 next_->getFont(bparams, 0, outerfont));
2539 running_font.latexWriteEndChanges(os, bparams,
2540 runparams, basefont, basefont);
2543 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2544 //FIXME: there as we start another \selectlanguage with the next paragraph if
2545 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2546 running_font.latexWriteEndChanges(os, bparams, runparams,
2547 basefont, basefont);
2551 column += Changes::latexMarkChange(os, bparams, runningChange,
2552 Change(Change::UNCHANGED), runparams);
2554 // Needed if there is an optional argument but no contents.
2555 if (body_pos > 0 && body_pos == size()) {
2559 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2560 && runparams.encoding != prev_encoding) {
2561 runparams.encoding = prev_encoding;
2562 if (!runparams.isFullUnicode())
2563 os << setEncoding(prev_encoding->iconvName());
2566 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2570 bool Paragraph::emptyTag() const
2572 for (pos_type i = 0; i < size(); ++i) {
2573 if (Inset const * inset = getInset(i)) {
2574 InsetCode lyx_code = inset->lyxCode();
2575 // FIXME testing like that is wrong. What is
2577 if (lyx_code != TOC_CODE &&
2578 lyx_code != INCLUDE_CODE &&
2579 lyx_code != GRAPHICS_CODE &&
2580 lyx_code != ERT_CODE &&
2581 lyx_code != LISTINGS_CODE &&
2582 lyx_code != FLOAT_CODE &&
2583 lyx_code != TABULAR_CODE) {
2587 char_type c = d->text_[i];
2588 if (c != ' ' && c != '\t')
2596 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2599 for (pos_type i = 0; i < size(); ++i) {
2600 if (Inset const * inset = getInset(i)) {
2601 InsetCode lyx_code = inset->lyxCode();
2602 if (lyx_code == LABEL_CODE) {
2603 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2604 docstring const & id = il->getParam("name");
2605 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2613 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2617 for (i = 0; i < size(); ++i) {
2618 if (Inset const * inset = getInset(i)) {
2619 inset->docbook(os, runparams);
2621 char_type c = d->text_[i];
2624 os << sgml::escapeChar(c);
2631 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2635 for (i = 0; i < size(); ++i) {
2636 if (Inset const * inset = getInset(i)) {
2637 inset->xhtml(xs, runparams);
2639 char_type c = d->text_[i];
2649 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2652 pos_type size = text_.size();
2653 for (pos_type i = initial; i < size; ++i) {
2654 Font font = owner_->getFont(buf.params(), i, outerfont);
2655 if (text_[i] == META_INSET)
2657 if (i != initial && font != font_old)
2666 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2668 OutputParams const & runparams,
2669 Font const & outerfont,
2670 pos_type initial) const
2672 bool emph_flag = false;
2674 Layout const & style = *d->layout_;
2676 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2678 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2681 // parsing main loop
2682 for (pos_type i = initial; i < size(); ++i) {
2683 Font font = getFont(buf.params(), i, outerfont);
2685 // handle <emphasis> tag
2686 if (font_old.emph() != font.fontInfo().emph()) {
2687 if (font.fontInfo().emph() == FONT_ON) {
2690 } else if (i != initial) {
2691 os << "</emphasis>";
2696 if (Inset const * inset = getInset(i)) {
2697 inset->docbook(os, runparams);
2699 char_type c = d->text_[i];
2701 if (style.pass_thru)
2704 os << sgml::escapeChar(c);
2706 font_old = font.fontInfo();
2710 os << "</emphasis>";
2713 if (style.free_spacing)
2715 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2720 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2722 OutputParams const & runparams,
2723 Font const & outerfont,
2724 pos_type initial) const
2728 bool emph_flag = false;
2729 bool bold_flag = false;
2732 Layout const & style = *d->layout_;
2734 if (!runparams.for_toc && runparams.html_make_pars) {
2735 // generate a magic label for this paragraph
2736 string const attr = "id='" + magicLabel() + "'";
2737 xs << html::CompTag("a", attr);
2741 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2743 // parsing main loop
2744 for (pos_type i = initial; i < size(); ++i) {
2745 // let's not show deleted material in the output
2749 Font font = getFont(buf.params(), i, outerfont);
2752 if (font_old.emph() != font.fontInfo().emph()) {
2753 if (font.fontInfo().emph() == FONT_ON) {
2754 xs << html::StartTag("em");
2756 } else if (emph_flag && i != initial) {
2757 xs << html::EndTag("em");
2762 if (font_old.series() != font.fontInfo().series()) {
2763 if (font.fontInfo().series() == BOLD_SERIES) {
2764 xs << html::StartTag("strong");
2766 } else if (bold_flag && i != initial) {
2767 xs << html::EndTag("strong");
2772 // Other such tags? What about the other text ranges?
2774 Inset const * inset = getInset(i);
2776 if (!runparams.for_toc || inset->isInToc()) {
2777 OutputParams np = runparams;
2778 if (!inset->getLayout().htmlisblock())
2779 np.html_in_par = true;
2780 retval += inset->xhtml(xs, np);
2783 char_type c = d->text_[i];
2785 if (style.pass_thru)
2787 else if (c == '-') {
2790 if (j < size() && d->text_[j] == '-') {
2792 if (j < size() && d->text_[j] == '-') {
2793 str += from_ascii("—");
2796 str += from_ascii("–");
2802 // We don't want to escape the entities. Note that
2803 // it is safe to do this, since str can otherwise
2804 // only be "-". E.g., it can't be "<".
2805 xs << XHTMLStream::ESCAPE_NONE << str;
2809 font_old = font.fontInfo();
2817 bool Paragraph::isHfill(pos_type pos) const
2819 Inset const * inset = getInset(pos);
2820 return inset && (inset->lyxCode() == SPACE_CODE &&
2821 inset->isStretchableSpace());
2825 bool Paragraph::isNewline(pos_type pos) const
2827 Inset const * inset = getInset(pos);
2828 return inset && inset->lyxCode() == NEWLINE_CODE;
2832 bool Paragraph::isLineSeparator(pos_type pos) const
2834 char_type const c = d->text_[pos];
2835 if (isLineSeparatorChar(c))
2837 Inset const * inset = getInset(pos);
2838 return inset && inset->isLineSeparator();
2842 bool Paragraph::isWordSeparator(pos_type pos) const
2844 if (Inset const * inset = getInset(pos))
2845 return !inset->isLetter();
2848 char_type const c = d->text_[pos];
2849 // We want to pass the ' and escape chars to the spellchecker
2850 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2851 return (!isLetterChar(c) && !isDigitASCII(c) && !contains(quote, c));
2855 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2858 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2862 bool Paragraph::isChar(pos_type pos) const
2864 if (Inset const * inset = getInset(pos))
2865 return inset->isChar();
2866 char_type const c = d->text_[pos];
2867 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2871 bool Paragraph::isSpace(pos_type pos) const
2873 if (Inset const * inset = getInset(pos))
2874 return inset->isSpace();
2875 char_type const c = d->text_[pos];
2876 return lyx::isSpace(c);
2881 Paragraph::getParLanguage(BufferParams const & bparams) const
2884 return getFirstFontSettings(bparams).language();
2885 // FIXME: we should check the prev par as well (Lgb)
2886 return bparams.language;
2890 bool Paragraph::isRTL(BufferParams const & bparams) const
2892 return lyxrc.rtl_support
2893 && getParLanguage(bparams)->rightToLeft()
2894 && !inInset().getLayout().forceLTR();
2898 void Paragraph::changeLanguage(BufferParams const & bparams,
2899 Language const * from, Language const * to)
2901 // change language including dummy font change at the end
2902 for (pos_type i = 0; i <= size(); ++i) {
2903 Font font = getFontSettings(bparams, i);
2904 if (font.language() == from) {
2905 font.setLanguage(to);
2909 d->requestSpellCheck(size());
2913 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2915 Language const * doc_language = bparams.language;
2916 FontList::const_iterator cit = d->fontlist_.begin();
2917 FontList::const_iterator end = d->fontlist_.end();
2919 for (; cit != end; ++cit)
2920 if (cit->font().language() != ignore_language &&
2921 cit->font().language() != latex_language &&
2922 cit->font().language() != doc_language)
2928 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2930 FontList::const_iterator cit = d->fontlist_.begin();
2931 FontList::const_iterator end = d->fontlist_.end();
2933 for (; cit != end; ++cit) {
2934 Language const * lang = cit->font().language();
2935 if (lang != ignore_language &&
2936 lang != latex_language)
2937 languages.insert(lang);
2942 docstring Paragraph::asString(int options) const
2944 return asString(0, size(), options);
2948 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2950 odocstringstream os;
2953 && options & AS_STR_LABEL
2954 && !d->params_.labelString().empty())
2955 os << d->params_.labelString() << ' ';
2957 for (pos_type i = beg; i < end; ++i) {
2958 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2960 char_type const c = d->text_[i];
2961 if (isPrintable(c) || c == '\t'
2962 || (c == '\n' && (options & AS_STR_NEWLINES)))
2964 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2965 getInset(i)->toString(os);
2966 if (getInset(i)->asInsetMath())
2975 void Paragraph::forToc(docstring & os, size_t maxlen) const
2977 if (!d->params_.labelString().empty())
2978 os += d->params_.labelString() + ' ';
2979 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
2982 char_type const c = d->text_[i];
2985 else if (c == '\t' || c == '\n')
2987 else if (c == META_INSET)
2988 getInset(i)->forToc(os, maxlen);
2993 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2995 odocstringstream os;
2998 && options & AS_STR_LABEL
2999 && !d->params_.labelString().empty())
3000 os << d->params_.labelString() << ' ';
3002 for (pos_type i = beg; i < end; ++i) {
3003 char_type const c = d->text_[i];
3004 if (isPrintable(c) || c == '\t'
3005 || (c == '\n' && (options & AS_STR_NEWLINES)))
3007 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3008 getInset(i)->plaintext(os, runparams);
3016 void Paragraph::setInsetOwner(Inset const * inset)
3018 d->inset_owner_ = inset;
3022 int Paragraph::id() const
3028 void Paragraph::setId(int id)
3034 Layout const & Paragraph::layout() const
3040 void Paragraph::setLayout(Layout const & layout)
3042 d->layout_ = &layout;
3046 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3048 setLayout(tc.defaultLayout());
3052 void Paragraph::setPlainLayout(DocumentClass const & tc)
3054 setLayout(tc.plainLayout());
3058 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3060 if (usePlainLayout())
3061 setPlainLayout(tclass);
3063 setDefaultLayout(tclass);
3067 Inset const & Paragraph::inInset() const
3069 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3070 _("Memory problem"), _("Paragraph not properly initialized")));
3071 return *d->inset_owner_;
3075 ParagraphParameters & Paragraph::params()
3081 ParagraphParameters const & Paragraph::params() const
3087 bool Paragraph::isFreeSpacing() const
3089 if (d->layout_->free_spacing)
3091 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3095 bool Paragraph::allowEmpty() const
3097 if (d->layout_->keepempty)
3099 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3103 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3105 if (!Encodings::isArabicChar(c))
3108 char_type prev_char = ' ';
3109 char_type next_char = ' ';
3111 for (pos_type i = pos - 1; i >= 0; --i) {
3112 char_type const par_char = d->text_[i];
3113 if (!Encodings::isArabicComposeChar(par_char)) {
3114 prev_char = par_char;
3119 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3120 char_type const par_char = d->text_[i];
3121 if (!Encodings::isArabicComposeChar(par_char)) {
3122 next_char = par_char;
3127 if (Encodings::isArabicChar(next_char)) {
3128 if (Encodings::isArabicChar(prev_char) &&
3129 !Encodings::isArabicSpecialChar(prev_char))
3130 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3132 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3134 if (Encodings::isArabicChar(prev_char) &&
3135 !Encodings::isArabicSpecialChar(prev_char))
3136 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3138 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3143 int Paragraph::checkBiblio(Buffer const & buffer)
3146 // This is getting more and more a mess. ...We really should clean
3147 // up this bibitem issue for 1.6.
3149 // Add bibitem insets if necessary
3150 if (d->layout_->labeltype != LABEL_BIBLIO)
3153 bool hasbibitem = !d->insetlist_.empty()
3154 // Insist on it being in pos 0
3155 && d->text_[0] == META_INSET
3156 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3158 bool track_changes = buffer.params().trackChanges;
3163 // remove a bibitem in pos != 0
3164 // restore it later in pos 0 if necessary
3165 // (e.g. if a user inserts contents _before_ the item)
3166 // we're assuming there's only one of these, which there
3168 int erasedInsetPosition = -1;
3169 InsetList::iterator it = d->insetlist_.begin();
3170 InsetList::iterator end = d->insetlist_.end();
3171 for (; it != end; ++it)
3172 if (it->inset->lyxCode() == BIBITEM_CODE
3174 InsetCommand * olditem = it->inset->asInsetCommand();
3175 oldkey = olditem->getParam("key");
3176 oldlabel = olditem->getParam("label");
3177 erasedInsetPosition = it->pos;
3178 eraseChar(erasedInsetPosition, track_changes);
3182 // There was an InsetBibitem at the beginning, and we didn't
3183 // have to erase one.
3184 if (hasbibitem && erasedInsetPosition < 0)
3187 // There was an InsetBibitem at the beginning and we did have to
3188 // erase one. So we give its properties to the beginning inset.
3190 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3191 if (!oldkey.empty())
3192 inset->setParam("key", oldkey);
3193 inset->setParam("label", oldlabel);
3194 return -erasedInsetPosition;
3197 // There was no inset at the beginning, so we need to create one with
3198 // the key and label of the one we erased.
3199 InsetBibitem * inset =
3200 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3201 // restore values of previously deleted item in this par.
3202 if (!oldkey.empty())
3203 inset->setParam("key", oldkey);
3204 inset->setParam("label", oldlabel);
3205 insertInset(0, inset,
3206 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3212 void Paragraph::checkAuthors(AuthorList const & authorList)
3214 d->changes_.checkAuthors(authorList);
3218 bool Paragraph::isChanged(pos_type pos) const
3220 return lookupChange(pos).changed();
3224 bool Paragraph::isInserted(pos_type pos) const
3226 return lookupChange(pos).inserted();
3230 bool Paragraph::isDeleted(pos_type pos) const
3232 return lookupChange(pos).deleted();
3236 InsetList const & Paragraph::insetList() const
3238 return d->insetlist_;
3242 void Paragraph::setBuffer(Buffer & b)
3244 d->insetlist_.setBuffer(b);
3248 Inset * Paragraph::releaseInset(pos_type pos)
3250 Inset * inset = d->insetlist_.release(pos);
3251 /// does not honour change tracking!
3252 eraseChar(pos, false);
3257 Inset * Paragraph::getInset(pos_type pos)
3259 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3260 ? d->insetlist_.get(pos) : 0;
3264 Inset const * Paragraph::getInset(pos_type pos) const
3266 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3267 ? d->insetlist_.get(pos) : 0;
3271 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3272 pos_type & right, TextCase action)
3274 // process sequences of modified characters; in change
3275 // tracking mode, this approach results in much better
3276 // usability than changing case on a char-by-char basis
3279 bool const trackChanges = bparams.trackChanges;
3281 bool capitalize = true;
3283 for (; pos < right; ++pos) {
3284 char_type oldChar = d->text_[pos];
3285 char_type newChar = oldChar;
3287 // ignore insets and don't play with deleted text!
3288 if (oldChar != META_INSET && !isDeleted(pos)) {
3290 case text_lowercase:
3291 newChar = lowercase(oldChar);
3293 case text_capitalization:
3295 newChar = uppercase(oldChar);
3299 case text_uppercase:
3300 newChar = uppercase(oldChar);
3305 if (isWordSeparator(pos) || isDeleted(pos)) {
3306 // permit capitalization again
3310 if (oldChar != newChar) {
3312 if (pos != right - 1)
3314 // step behind the changing area
3318 int erasePos = pos - changes.size();
3319 for (size_t i = 0; i < changes.size(); i++) {
3320 insertChar(pos, changes[i],
3321 getFontSettings(bparams,
3324 if (!eraseChar(erasePos, trackChanges)) {
3327 ++right; // expand selection
3335 int Paragraph::find(docstring const & str, bool cs, bool mw,
3336 pos_type start_pos, bool del) const
3338 pos_type pos = start_pos;
3339 int const strsize = str.length();
3341 pos_type const parsize = d->text_.size();
3342 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3343 // Ignore ligature break and hyphenation chars while searching
3344 while (pos < parsize - 1 && isInset(pos)) {
3345 const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3347 || (isc->kind() != InsetSpecialChar::HYPHENATION
3348 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3352 if (cs && str[i] != d->text_[pos])
3354 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3356 if (!del && isDeleted(pos))
3363 // if necessary, check whether string matches word
3365 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3368 && !isWordSeparator(pos))
3372 return pos - start_pos;
3376 char_type Paragraph::getChar(pos_type pos) const
3378 return d->text_[pos];
3382 pos_type Paragraph::size() const
3384 return d->text_.size();
3388 bool Paragraph::empty() const
3390 return d->text_.empty();
3394 bool Paragraph::isInset(pos_type pos) const
3396 return d->text_[pos] == META_INSET;
3400 bool Paragraph::isSeparator(pos_type pos) const
3402 //FIXME: Are we sure this can be the only separator?
3403 return d->text_[pos] == ' ';
3407 void Paragraph::deregisterWords()
3409 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3410 Private::LangWordsMap::const_iterator ite = d->words_.end();
3411 for (; itl != ite; ++itl) {
3412 WordList * wl = theWordList(itl->first);
3413 Private::Words::const_iterator it = (itl->second).begin();
3414 Private::Words::const_iterator et = (itl->second).end();
3415 for (; it != et; ++it)
3422 void Paragraph::locateWord(pos_type & from, pos_type & to,
3423 word_location const loc) const
3426 case WHOLE_WORD_STRICT:
3427 if (from == 0 || from == size()
3428 || isWordSeparator(from)
3429 || isWordSeparator(from - 1)) {
3433 // no break here, we go to the next
3436 // If we are already at the beginning of a word, do nothing
3437 if (!from || isWordSeparator(from - 1))
3439 // no break here, we go to the next
3442 // always move the cursor to the beginning of previous word
3443 while (from && !isWordSeparator(from - 1))
3447 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3450 // no need to move the 'from' cursor
3454 while (to < size() && !isWordSeparator(to))
3459 void Paragraph::collectWords()
3461 // This is the value that needs to be exposed in the preferences
3462 // to resolve bug #6760.
3463 static int minlength = 6;
3464 pos_type n = size();
3465 for (pos_type pos = 0; pos < n; ++pos) {
3466 if (isWordSeparator(pos))
3468 pos_type from = pos;
3469 locateWord(from, pos, WHOLE_WORD);
3470 if (pos - from >= minlength) {
3471 docstring word = asString(from, pos, AS_STR_NONE);
3472 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3473 if (cit == d->fontlist_.end())
3475 Language const * lang = cit->font().language();
3476 d->words_[*lang].insert(word);
3482 void Paragraph::registerWords()
3484 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3485 Private::LangWordsMap::const_iterator ite = d->words_.end();
3486 for (; itl != ite; ++itl) {
3487 WordList * wl = theWordList(itl->first);
3488 Private::Words::const_iterator it = (itl->second).begin();
3489 Private::Words::const_iterator et = (itl->second).end();
3490 for (; it != et; ++it)
3496 void Paragraph::updateWords()
3504 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3506 SkipPositionsIterator begin = skips.begin();
3507 SkipPositions::iterator end = skips.end();
3508 if (pos > 0 && begin < end) {
3510 if (end->last == pos - 1) {
3515 skips.insert(end, FontSpan(pos, pos));
3519 Language * Paragraph::Private::locateSpellRange(
3520 pos_type & from, pos_type & to,
3521 SkipPositions & skips) const
3523 // skip leading white space
3524 while (from < to && owner_->isWordSeparator(from))
3526 // don't check empty range
3529 // get current language
3530 Language * lang = getSpellLanguage(from);
3531 pos_type last = from;
3532 bool samelang = true;
3533 bool sameinset = true;
3534 while (last < to && samelang && sameinset) {
3535 // hop to end of word
3536 while (last < to && !owner_->isWordSeparator(last)) {
3537 if (owner_->getInset(last)) {
3538 appendSkipPosition(skips, last);
3539 } else if (owner_->isDeleted(last)) {
3540 appendSkipPosition(skips, last);
3544 // hop to next word while checking for insets
3545 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3546 if (Inset const * inset = owner_->getInset(last))
3547 sameinset = inset->isChar() && inset->isLetter();
3548 if (sameinset && owner_->isDeleted(last)) {
3549 appendSkipPosition(skips, last);
3554 if (sameinset && last < to) {
3555 // now check for language change
3556 samelang = lang == getSpellLanguage(last);
3559 // if language change detected backstep is needed
3567 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3570 const_cast<Language *>(owner_->getFontSettings(
3571 inset_owner_->buffer().params(), from).language());
3572 if (lang == inset_owner_->buffer().params().language
3573 && !lyxrc.spellchecker_alt_lang.empty()) {
3575 string const lang_variety =
3576 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3577 lang->setCode(lang_code);
3578 lang->setVariety(lang_variety);
3584 void Paragraph::requestSpellCheck(pos_type pos)
3586 d->requestSpellCheck(pos == -1 ? size() : pos);
3590 bool Paragraph::needsSpellCheck() const
3592 SpellChecker::ChangeNumber speller_change_number = 0;
3593 if (theSpellChecker())
3594 speller_change_number = theSpellChecker()->changeNumber();
3595 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3596 d->speller_state_.needsCompleteRefresh(speller_change_number);
3598 return d->needsSpellCheck();
3602 bool Paragraph::Private::ignoreWord(docstring const & word) const
3604 // Ignore words with digits
3605 // FIXME: make this customizable
3606 // (note that some checkers ignore words with digits by default)
3607 docstring::const_iterator cit = word.begin();
3608 docstring::const_iterator const end = word.end();
3609 for (; cit != end; ++cit) {
3610 if (isNumber((*cit)))
3617 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3618 WordLangTuple & wl, docstring_list & suggestions,
3619 bool do_suggestion, bool check_learned) const
3621 SpellChecker::Result result = SpellChecker::WORD_OK;
3622 SpellChecker * speller = theSpellChecker();
3626 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3629 locateWord(from, to, WHOLE_WORD);
3630 if (from == to || from >= size())
3633 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3634 Language * lang = d->getSpellLanguage(from);
3636 wl = WordLangTuple(word, lang);
3641 if (needsSpellCheck() || check_learned) {
3642 if (!d->ignoreWord(word)) {
3643 bool const trailing_dot = to < size() && d->text_[to] == '.';
3644 result = speller->check(wl);
3645 if (SpellChecker::misspelled(result) && trailing_dot) {
3646 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3647 result = speller->check(wl);
3648 if (!SpellChecker::misspelled(result)) {
3649 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3651 from << ".." << to << "]");
3653 // spell check with dot appended failed
3654 // restore original word/lang value
3655 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3656 wl = WordLangTuple(word, lang);
3660 d->setMisspelled(from, to, result);
3662 result = d->speller_state_.getState(from);
3665 bool const misspelled_ = SpellChecker::misspelled(result) ;
3666 if (misspelled_ && do_suggestion)
3667 speller->suggest(wl, suggestions);
3668 else if (misspelled_)
3669 LYXERR(Debug::GUI, "misspelled word: \"" <<
3671 from << ".." << to << "]");
3673 suggestions.clear();
3679 void Paragraph::Private::markMisspelledWords(
3680 pos_type const & first, pos_type const & last,
3681 SpellChecker::Result result,
3682 docstring const & word,
3683 SkipPositions const & skips)
3685 if (!SpellChecker::misspelled(result)) {
3686 setMisspelled(first, last, SpellChecker::WORD_OK);
3690 SpellChecker * speller = theSpellChecker();
3691 // locate and enumerate the error positions
3692 int nerrors = speller->numMisspelledWords();
3694 SkipPositionsIterator it = skips.begin();
3695 SkipPositionsIterator et = skips.end();
3696 for (int index = 0; index < nerrors; ++index) {
3699 speller->misspelledWord(index, wstart, wlen);
3700 /// should not happen if speller supports range checks
3701 if (!wlen) continue;
3702 docstring const misspelled = word.substr(wstart, wlen);
3703 wstart += first + numskipped;
3704 if (snext < wstart) {
3705 /// mark the range of correct spelling
3706 numskipped += countSkips(it, et, wstart);
3707 setMisspelled(snext,
3708 wstart - 1, SpellChecker::WORD_OK);
3710 snext = wstart + wlen;
3711 numskipped += countSkips(it, et, snext);
3712 /// mark the range of misspelling
3713 setMisspelled(wstart, snext, result);
3714 LYXERR(Debug::GUI, "misspelled word: \"" <<
3715 misspelled << "\" [" <<
3716 wstart << ".." << (snext-1) << "]");
3719 if (snext <= last) {
3720 /// mark the range of correct spelling at end
3721 setMisspelled(snext, last, SpellChecker::WORD_OK);
3726 void Paragraph::spellCheck() const
3728 SpellChecker * speller = theSpellChecker();
3729 if (!speller || !size() ||!needsSpellCheck())
3733 d->rangeOfSpellCheck(start, endpos);
3734 if (speller->canCheckParagraph()) {
3735 // loop until we leave the range
3736 for (pos_type first = start; first < endpos; ) {
3737 pos_type last = endpos;
3738 Private::SkipPositions skips;
3739 Language * lang = d->locateSpellRange(first, last, skips);
3740 if (first >= endpos)
3742 // start the spell checker on the unit of meaning
3743 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3744 WordLangTuple wl = WordLangTuple(word, lang);
3745 SpellChecker::Result result = word.size() ?
3746 speller->check(wl) : SpellChecker::WORD_OK;
3747 d->markMisspelledWords(first, last, result, word, skips);
3751 static docstring_list suggestions;
3752 pos_type to = endpos;
3753 while (start < endpos) {
3755 spellCheck(start, to, wl, suggestions, false);
3759 d->readySpellCheck();
3763 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3765 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3766 if (result || pos <= 0 || pos >= size())
3768 if (check_boundary && isWordSeparator(pos))
3769 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3774 string Paragraph::magicLabel() const
3777 ss << "magicparlabel-" << id();