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 bool 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) {
404 speller_state_.needsCompleteRefresh(speller_state_.currentChangeNumber());
406 speller_state_.needsRefresh(pos);
409 void readySpellCheck() {
410 speller_state_.needsRefresh(-1);
413 bool needsSpellCheck() const
415 return speller_state_.needsRefresh();
418 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
420 speller_state_.refreshRange(first, last);
422 last = owner_->size();
425 pos_type endpos = last;
426 owner_->locateWord(first, endpos, WHOLE_WORD);
429 owner_->locateWord(last, endpos, WHOLE_WORD);
434 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
438 while (it != et && it->first < start) {
439 int skip = it->last - it->first + 1;
447 void markMisspelledWords(pos_type const & first, pos_type const & last,
448 SpellChecker::Result result,
449 docstring const & word,
450 SkipPositions const & skips);
452 InsetCode ownerCode() const
454 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
457 /// Which Paragraph owns us?
461 Inset const * inset_owner_;
470 ParagraphParameters params_;
472 /// for recording and looking up changes
476 InsetList insetlist_;
479 pos_type begin_of_body_;
481 typedef docstring TextContainer;
485 typedef set<docstring> Words;
486 typedef map<Language, Words> LangWordsMap;
490 Layout const * layout_;
492 SpellCheckerState speller_state_;
498 struct special_phrase {
504 special_phrase const special_phrases[] = {
505 { "LyX", from_ascii("\\LyX{}"), false },
506 { "TeX", from_ascii("\\TeX{}"), true },
507 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
508 { "LaTeX", from_ascii("\\LaTeX{}"), true },
511 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
516 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
517 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
523 // Initialization of the counter for the paragraph id's,
525 // FIXME: There should be a more intelligent way to generate and use the
526 // paragraph ids per buffer instead a global static counter for all InsetText
527 // in the running program.
528 static int paragraph_id = -1;
530 Paragraph::Private::Private(Private const & p, Paragraph * owner)
531 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
532 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
533 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
536 id_ = ++paragraph_id;
537 requestSpellCheck(p.text_.size());
541 Paragraph::Private::Private(Private const & p, Paragraph * owner,
542 pos_type beg, pos_type end)
543 : owner_(owner), inset_owner_(p.inset_owner_),
544 params_(p.params_), changes_(p.changes_),
545 insetlist_(p.insetlist_, beg, end),
546 begin_of_body_(p.begin_of_body_), words_(p.words_),
549 id_ = ++paragraph_id;
550 if (beg >= pos_type(p.text_.size()))
552 text_ = p.text_.substr(beg, end - beg);
554 FontList::const_iterator fcit = fontlist_.begin();
555 FontList::const_iterator fend = fontlist_.end();
556 for (; fcit != fend; ++fcit) {
557 if (fcit->pos() < beg)
559 if (fcit->pos() >= end) {
560 // Add last entry in the fontlist_.
561 fontlist_.set(text_.size() - 1, fcit->font());
564 // Add a new entry in the fontlist_.
565 fontlist_.set(fcit->pos() - beg, fcit->font());
567 requestSpellCheck(p.text_.size());
571 void Paragraph::addChangesToToc(DocIterator const & cdit,
572 Buffer const & buf) const
574 d->changes_.addToToc(cdit, buf);
578 bool Paragraph::isDeleted(pos_type start, pos_type end) const
580 LASSERT(start >= 0 && start <= size(), /**/);
581 LASSERT(end > start && end <= size() + 1, /**/);
583 return d->changes_.isDeleted(start, end);
587 bool Paragraph::isChanged(pos_type start, pos_type end) const
589 LASSERT(start >= 0 && start <= size(), /**/);
590 LASSERT(end > start && end <= size() + 1, /**/);
592 return d->changes_.isChanged(start, end);
596 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
598 // keep the logic here in sync with the logic of eraseChars()
602 Change const change = d->changes_.lookup(size());
603 return change.inserted() && change.currentAuthor();
607 void Paragraph::setChange(Change const & change)
609 // beware of the imaginary end-of-par character!
610 d->changes_.set(change, 0, size() + 1);
613 * Propagate the change recursively - but not in case of DELETED!
615 * Imagine that your co-author makes changes in an existing inset. He
616 * sends your document to you and you come to the conclusion that the
617 * inset should go completely. If you erase it, LyX must not delete all
618 * text within the inset. Otherwise, the change tracked insertions of
619 * your co-author get lost and there is no way to restore them later.
621 * Conclusion: An inset's content should remain untouched if you delete it
624 if (!change.deleted()) {
625 for (pos_type pos = 0; pos < size(); ++pos) {
626 if (Inset * inset = getInset(pos))
627 inset->setChange(change);
633 void Paragraph::setChange(pos_type pos, Change const & change)
635 LASSERT(pos >= 0 && pos <= size(), /**/);
636 d->changes_.set(change, pos);
638 // see comment in setChange(Change const &) above
639 if (!change.deleted() && pos < size())
640 if (Inset * inset = getInset(pos))
641 inset->setChange(change);
645 Change const & Paragraph::lookupChange(pos_type pos) const
647 LASSERT(pos >= 0 && pos <= size(), /**/);
648 return d->changes_.lookup(pos);
652 void Paragraph::acceptChanges(pos_type start, pos_type end)
654 LASSERT(start >= 0 && start <= size(), /**/);
655 LASSERT(end > start && end <= size() + 1, /**/);
657 for (pos_type pos = start; pos < end; ++pos) {
658 switch (lookupChange(pos).type) {
659 case Change::UNCHANGED:
660 // accept changes in nested inset
661 if (Inset * inset = getInset(pos))
662 inset->acceptChanges();
665 case Change::INSERTED:
666 d->changes_.set(Change(Change::UNCHANGED), pos);
667 // also accept changes in nested inset
668 if (Inset * inset = getInset(pos))
669 inset->acceptChanges();
672 case Change::DELETED:
673 // Suppress access to non-existent
674 // "end-of-paragraph char"
676 eraseChar(pos, false);
687 void Paragraph::rejectChanges(pos_type start, pos_type end)
689 LASSERT(start >= 0 && start <= size(), /**/);
690 LASSERT(end > start && end <= size() + 1, /**/);
692 for (pos_type pos = start; pos < end; ++pos) {
693 switch (lookupChange(pos).type) {
694 case Change::UNCHANGED:
695 // reject changes in nested inset
696 if (Inset * inset = getInset(pos))
697 inset->rejectChanges();
700 case Change::INSERTED:
701 // Suppress access to non-existent
702 // "end-of-paragraph char"
704 eraseChar(pos, false);
710 case Change::DELETED:
711 d->changes_.set(Change(Change::UNCHANGED), pos);
713 // Do NOT reject changes within a deleted inset!
714 // There may be insertions of a co-author inside of it!
722 void Paragraph::Private::insertChar(pos_type pos, char_type c,
723 Change const & change)
725 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
728 changes_.insert(change, pos);
730 // This is actually very common when parsing buffers (and
731 // maybe inserting ascii text)
732 if (pos == pos_type(text_.size())) {
733 // when appending characters, no need to update tables
735 // but we want spell checking
736 requestSpellCheck(pos);
740 text_.insert(text_.begin() + pos, c);
742 // Update the font table.
743 fontlist_.increasePosAfterPos(pos);
746 insetlist_.increasePosAfterPos(pos);
748 // Update list of misspelled positions
749 speller_state_.increasePosAfterPos(pos);
753 bool Paragraph::insertInset(pos_type pos, Inset * inset,
754 Change const & change)
756 LASSERT(inset, /**/);
757 LASSERT(pos >= 0 && pos <= size(), /**/);
759 // Paragraph::insertInset() can be used in cut/copy/paste operation where
760 // d->inset_owner_ is not set yet.
761 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
764 d->insertChar(pos, META_INSET, change);
765 LASSERT(d->text_[pos] == META_INSET, /**/);
767 // Add a new entry in the insetlist_.
768 d->insetlist_.insert(inset, pos);
770 // Some insets require run of spell checker
771 requestSpellCheck(pos);
776 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
778 LASSERT(pos >= 0 && pos <= size(), return false);
780 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
783 Change change = d->changes_.lookup(pos);
785 // set the character to DELETED if
786 // a) it was previously unchanged or
787 // b) it was inserted by a co-author
789 if (!change.changed() ||
790 (change.inserted() && !change.currentAuthor())) {
791 setChange(pos, Change(Change::DELETED));
792 // request run of spell checker
793 requestSpellCheck(pos);
797 if (change.deleted())
801 // Don't physically access the imaginary end-of-paragraph character.
802 // eraseChar() can only mark it as DELETED. A physical deletion of
803 // end-of-par must be handled externally.
809 d->changes_.erase(pos);
811 // if it is an inset, delete the inset entry
812 if (d->text_[pos] == META_INSET)
813 d->insetlist_.erase(pos);
815 d->text_.erase(d->text_.begin() + pos);
817 // Update the fontlist_
818 d->fontlist_.erase(pos);
820 // Update the insetlist_
821 d->insetlist_.decreasePosAfterPos(pos);
823 // Update list of misspelled positions
824 d->speller_state_.decreasePosAfterPos(pos);
825 d->speller_state_.refreshLast(size());
831 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
833 LASSERT(start >= 0 && start <= size(), /**/);
834 LASSERT(end >= start && end <= size() + 1, /**/);
837 for (pos_type count = end - start; count; --count) {
838 if (!eraseChar(i, trackChanges))
845 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
846 char_type next, OutputParams const & runparams)
848 // Writing next here may circumvent a possible font change between
849 // c and next. Since next is only output if it forms a surrogate pair
850 // with c we can ignore this:
851 // A font change inside a surrogate pair does not make sense and is
852 // hopefully impossible to input.
853 // FIXME: change tracking
854 // Is this correct WRT change tracking?
855 Encoding const & encoding = *(runparams.encoding);
856 docstring const latex1 = encoding.latexChar(next);
857 docstring const latex2 = encoding.latexChar(c);
858 if (docstring(1, next) == latex1) {
859 // the encoding supports the combination
860 os << latex2 << latex1;
861 return latex1.length() + latex2.length();
862 } else if (runparams.local_font &&
863 runparams.local_font->language()->lang() == "polutonikogreek") {
864 // polutonikogreek only works without the brackets
865 os << latex1 << latex2;
866 return latex1.length() + latex2.length();
868 os << latex1 << '{' << latex2 << '}';
869 return latex1.length() + latex2.length() + 2;
873 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
876 unsigned int & column,
878 Layout const & style)
880 if (style.pass_thru || runparams.pass_thru)
883 if (i + 1 < int(text_.size())) {
884 char_type next = text_[i + 1];
885 if (Encodings::isCombiningChar(next)) {
886 // This space has an accent, so we must always output it.
887 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
892 if (runparams.linelen > 0
893 && column > runparams.linelen
895 && text_[i - 1] != ' '
896 && (i + 1 < int(text_.size()))
897 // same in FreeSpacing mode
898 && !owner_->isFreeSpacing()
899 // In typewriter mode, we want to avoid
900 // ! . ? : at the end of a line
901 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
902 && (text_[i - 1] == '.'
903 || text_[i - 1] == '?'
904 || text_[i - 1] == ':'
905 || text_[i - 1] == '!'))) {
907 os.texrow().start(owner_->id(), i + 1);
909 } else if (style.free_spacing) {
918 int Paragraph::Private::writeScriptChars(otexstream & os,
919 docstring const & ltx,
920 Change const & runningChange,
921 Encoding const & encoding,
924 // FIXME: modifying i here is not very nice...
926 // We only arrive here when a proper language for character text_[i] has
927 // not been specified (i.e., it could not be translated in the current
928 // latex encoding) or its latex translation has been forced, and it
929 // belongs to a known script.
930 // Parameter ltx contains the latex translation of text_[i] as specified
931 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
932 // The latex macro name "textXXX" specifies the script to which text_[i]
933 // belongs and we use it in order to check whether characters from the
934 // same script immediately follow, such that we can collect them in a
935 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
936 // for the first char but only "<spec>" for all subsequent chars.
937 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
938 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
939 string script = to_ascii(ltx.substr(1, brace1 - 1));
942 bool closing_brace = true;
943 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
944 // Correct encoding is being used, so we can avoid \textgreek.
947 closing_brace = false;
949 os << ltx.substr(pos, length);
950 int size = text_.size();
951 while (i + 1 < size) {
952 char_type const next = text_[i + 1];
953 // Stop here if next character belongs to another script
954 // or there is a change in change tracking status.
955 if (!Encodings::isKnownScriptChar(next, script) ||
956 runningChange != owner_->lookupChange(i + 1))
960 FontList::const_iterator cit = fontlist_.begin();
961 FontList::const_iterator end = fontlist_.end();
962 for (; cit != end; ++cit) {
963 if (cit->pos() >= i && !found) {
964 prev_font = cit->font();
967 if (cit->pos() >= i + 1)
970 // Stop here if there is a font attribute or encoding change.
971 if (found && cit != end && prev_font != cit->font())
973 docstring const latex = encoding.latexChar(next);
974 docstring::size_type const b1 =
975 latex.find_first_of(from_ascii("{"));
976 docstring::size_type const b2 =
977 latex.find_last_of(from_ascii("}"));
978 int const len = b2 - b1 - 1;
979 os << latex.substr(b1 + 1, len);
991 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
993 pos_type const len = str.length();
995 // is the paragraph large enough?
996 if (pos + len > int(text_.size()))
999 // does the wanted text start at point?
1000 for (string::size_type i = 0; i < str.length(); ++i) {
1001 // Caution: direct comparison of characters works only
1002 // because str is pure ASCII.
1003 if (str[i] != text_[pos + i])
1007 return fontlist_.hasChangeInRange(pos, len);
1011 void Paragraph::Private::latexInset(BufferParams const & bparams,
1013 OutputParams & runparams,
1014 Font & running_font,
1016 Font const & outerfont,
1018 Change & running_change,
1019 Layout const & style,
1021 unsigned int & column)
1023 Inset * inset = owner_->getInset(i);
1024 LASSERT(inset, /**/);
1026 if (style.pass_thru) {
1027 inset->plaintext(os.os(), runparams);
1031 // FIXME: move this to InsetNewline::latex
1032 if (inset->lyxCode() == NEWLINE_CODE) {
1033 // newlines are handled differently here than
1034 // the default in simpleTeXSpecialChars().
1035 if (!style.newline_allowed) {
1039 column += running_font.latexWriteEndChanges(
1040 os, bparams, runparams,
1041 basefont, basefont);
1045 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1048 basefont = owner_->getLayoutFont(bparams, outerfont);
1049 running_font = basefont;
1051 if (runparams.moving_arg)
1055 os.texrow().start(owner_->id(), i + 1);
1059 if (owner_->isDeleted(i)) {
1060 if( ++runparams.inDeletedInset == 1)
1061 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1064 if (inset->canTrackChanges()) {
1065 column += Changes::latexMarkChange(os, bparams, running_change,
1066 Change(Change::UNCHANGED), runparams);
1067 running_change = Change(Change::UNCHANGED);
1071 odocstream::pos_type const len = os.os().tellp();
1073 if (inset->forceLTR()
1074 && running_font.isRightToLeft()
1075 // ERT is an exception, it should be output with no
1076 // decorations at all
1077 && inset->lyxCode() != ERT_CODE) {
1078 if (running_font.language()->lang() == "farsi")
1085 // FIXME: Bug: we can have an empty font change here!
1086 // if there has just been a font change, we are going to close it
1087 // right now, which means stupid latex code like \textsf{}. AFAIK,
1088 // this does not harm dvi output. A minor bug, thus (JMarc)
1090 // Some insets cannot be inside a font change command.
1091 // However, even such insets *can* be placed in \L or \R
1092 // or their equivalents (for RTL language switches), so we don't
1093 // close the language in those cases.
1094 // ArabTeX, though, cannot handle this special behavior, it seems.
1095 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1096 || running_font.language()->lang() == "arabic_arabtex";
1097 if (open_font && !inset->inheritFont()) {
1098 bool closeLanguage = arabtex
1099 || basefont.isRightToLeft() == running_font.isRightToLeft();
1100 unsigned int count = running_font.latexWriteEndChanges(os,
1101 bparams, runparams, basefont, basefont, closeLanguage);
1103 // if any font properties were closed, update the running_font,
1104 // making sure, however, to leave the language as it was
1106 // FIXME: probably a better way to keep track of the old
1107 // language, than copying the entire font?
1108 Font const copy_font(running_font);
1109 basefont = owner_->getLayoutFont(bparams, outerfont);
1110 running_font = basefont;
1112 running_font.setLanguage(copy_font.language());
1113 // leave font open if language is still open
1114 open_font = (running_font.language() == basefont.language());
1116 runparams.local_font = &basefont;
1120 int prev_rows = os.texrow().rows();
1123 runparams.lastid = id_;
1124 runparams.lastpos = i;
1125 inset->latex(os, runparams);
1126 } catch (EncodingException & e) {
1127 // add location information and throw again.
1134 if (running_font.language()->lang() == "farsi")
1140 if (os.texrow().rows() > prev_rows) {
1141 os.texrow().start(owner_->id(), i + 1);
1144 column += (unsigned int)(os.os().tellp() - len);
1147 if (owner_->isDeleted(i))
1148 --runparams.inDeletedInset;
1152 void Paragraph::Private::latexSpecialChar(otexstream & os,
1153 OutputParams const & runparams,
1154 Font const & running_font,
1155 Change const & running_change,
1156 Layout const & style,
1159 unsigned int & column)
1161 char_type const c = text_[i];
1163 if (style.pass_thru || runparams.pass_thru) {
1165 Encoding const * const enc = runparams.encoding;
1166 if (enc && enc->latexChar(c, true).empty())
1167 throw EncodingException(c);
1173 // If T1 font encoding is used, use the special
1174 // characters it provides.
1175 // NOTE: some languages reset the font encoding
1177 if (!running_font.language()->internalFontEncoding()
1178 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1181 // \tt font needs special treatment
1182 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1183 && latexSpecialTypewriter(c, os, i, column))
1186 // Otherwise, we use what LaTeX provides us.
1189 os << "\\textbackslash{}";
1193 os << "\\textless{}";
1197 os << "\\textgreater{}";
1201 os << "\\textbar{}";
1208 os << "\\char`\\\"{}";
1213 case '%': case '#': case '{':
1221 os << "\\textasciitilde{}";
1226 os << "\\textasciicircum{}";
1233 // avoid being mistaken for optional arguments
1241 // Blanks are printed before font switching.
1242 // Sure? I am not! (try nice-latex)
1243 // I am sure it's correct. LyX might be smarter
1244 // in the future, but for now, nothing wrong is
1250 if (latexSpecialPhrase(os, i, end_pos, column, runparams))
1256 Encoding const & encoding = *(runparams.encoding);
1257 if (i + 1 < int(text_.size())) {
1258 char_type next = text_[i + 1];
1259 if (Encodings::isCombiningChar(next)) {
1260 column += latexSurrogatePair(os, c, next, runparams) - 1;
1266 docstring const latex = encoding.latexChar(c);
1267 if (Encodings::isKnownScriptChar(c, script)
1268 && prefixIs(latex, from_ascii("\\" + script)))
1269 column += writeScriptChars(os, latex,
1270 running_change, encoding, i) - 1;
1271 else if (latex.length() > 1 && 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 ']'
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
2375 ? runparams.changeOfDeletedInset : lookupChange(i);
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;
2731 Layout const & style = *d->layout_;
2733 xs.startParagraph(allowEmpty());
2735 if (!runparams.for_toc && runparams.html_make_pars) {
2736 // generate a magic label for this paragraph
2737 string const attr = "id='" + magicLabel() + "'";
2738 xs << html::CompTag("a", attr);
2742 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2744 // parsing main loop
2745 for (pos_type i = initial; i < size(); ++i) {
2746 // let's not show deleted material in the output
2750 Font font = getFont(buf.params(), i, outerfont);
2753 if (font_old.emph() != font.fontInfo().emph()) {
2754 if (font.fontInfo().emph() == FONT_ON) {
2755 xs << html::StartTag("em");
2757 } else if (emph_flag && i != initial) {
2758 xs << html::EndTag("em");
2763 if (font_old.series() != font.fontInfo().series()) {
2764 if (font.fontInfo().series() == BOLD_SERIES) {
2765 xs << html::StartTag("strong");
2767 } else if (bold_flag && i != initial) {
2768 xs << html::EndTag("strong");
2773 // Other such tags? What about the other text ranges?
2775 Inset const * inset = getInset(i);
2777 if (!runparams.for_toc || inset->isInToc()) {
2778 OutputParams np = runparams;
2779 if (!inset->getLayout().htmlisblock())
2780 np.html_in_par = true;
2781 retval += inset->xhtml(xs, np);
2784 char_type c = d->text_[i];
2786 if (style.pass_thru)
2788 else if (c == '-') {
2791 if (j < size() && d->text_[j] == '-') {
2793 if (j < size() && d->text_[j] == '-') {
2794 str += from_ascii("—");
2797 str += from_ascii("–");
2803 // We don't want to escape the entities. Note that
2804 // it is safe to do this, since str can otherwise
2805 // only be "-". E.g., it can't be "<".
2806 xs << XHTMLStream::ESCAPE_NONE << str;
2810 font_old = font.fontInfo();
2819 bool Paragraph::isHfill(pos_type pos) const
2821 Inset const * inset = getInset(pos);
2822 return inset && (inset->lyxCode() == SPACE_CODE &&
2823 inset->isStretchableSpace());
2827 bool Paragraph::isNewline(pos_type pos) const
2829 Inset const * inset = getInset(pos);
2830 return inset && inset->lyxCode() == NEWLINE_CODE;
2834 bool Paragraph::isLineSeparator(pos_type pos) const
2836 char_type const c = d->text_[pos];
2837 if (isLineSeparatorChar(c))
2839 Inset const * inset = getInset(pos);
2840 return inset && inset->isLineSeparator();
2844 bool Paragraph::isWordSeparator(pos_type pos) const
2848 if (Inset const * inset = getInset(pos))
2849 return !inset->isLetter();
2850 // if we have a hard hyphen (no en- or emdash) or apostrophe
2851 // we pass this to the spell checker
2852 // FIXME: this method is subject to change, visit
2853 // https://bugzilla.mozilla.org/show_bug.cgi?id=355178
2854 // to get an impression how complex this is.
2855 if (isHardHyphenOrApostrophe(pos))
2857 char_type const c = d->text_[pos];
2858 // We want to pass the escape chars to the spellchecker
2859 docstring const escape_chars = from_utf8(lyxrc.spellchecker_esc_chars);
2860 return !isLetterChar(c) && !isDigitASCII(c) && !contains(escape_chars, c);
2864 bool Paragraph::isHardHyphenOrApostrophe(pos_type pos) const
2866 pos_type const psize = size();
2869 char_type const c = d->text_[pos];
2870 if (c != '-' && c != '\'')
2872 int nextpos = pos + 1;
2873 int prevpos = pos > 0 ? pos - 1 : 0;
2874 if ((nextpos == psize || isSpace(nextpos))
2875 && (pos == 0 || isSpace(prevpos)))
2878 || ((nextpos == psize || d->text_[nextpos] != '-')
2879 && (pos == 0 || d->text_[prevpos] != '-'));
2883 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2886 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2890 bool Paragraph::isChar(pos_type pos) const
2892 if (Inset const * inset = getInset(pos))
2893 return inset->isChar();
2894 char_type const c = d->text_[pos];
2895 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2899 bool Paragraph::isSpace(pos_type pos) const
2901 if (Inset const * inset = getInset(pos))
2902 return inset->isSpace();
2903 char_type const c = d->text_[pos];
2904 return lyx::isSpace(c);
2909 Paragraph::getParLanguage(BufferParams const & bparams) const
2912 return getFirstFontSettings(bparams).language();
2913 // FIXME: we should check the prev par as well (Lgb)
2914 return bparams.language;
2918 bool Paragraph::isRTL(BufferParams const & bparams) const
2920 return lyxrc.rtl_support
2921 && getParLanguage(bparams)->rightToLeft()
2922 && !inInset().getLayout().forceLTR();
2926 void Paragraph::changeLanguage(BufferParams const & bparams,
2927 Language const * from, Language const * to)
2929 // change language including dummy font change at the end
2930 for (pos_type i = 0; i <= size(); ++i) {
2931 Font font = getFontSettings(bparams, i);
2932 if (font.language() == from) {
2933 font.setLanguage(to);
2937 d->requestSpellCheck(size());
2941 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2943 Language const * doc_language = bparams.language;
2944 FontList::const_iterator cit = d->fontlist_.begin();
2945 FontList::const_iterator end = d->fontlist_.end();
2947 for (; cit != end; ++cit)
2948 if (cit->font().language() != ignore_language &&
2949 cit->font().language() != latex_language &&
2950 cit->font().language() != doc_language)
2956 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2958 FontList::const_iterator cit = d->fontlist_.begin();
2959 FontList::const_iterator end = d->fontlist_.end();
2961 for (; cit != end; ++cit) {
2962 Language const * lang = cit->font().language();
2963 if (lang != ignore_language &&
2964 lang != latex_language)
2965 languages.insert(lang);
2970 docstring Paragraph::asString(int options) const
2972 return asString(0, size(), options);
2976 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2978 odocstringstream os;
2981 && options & AS_STR_LABEL
2982 && !d->params_.labelString().empty())
2983 os << d->params_.labelString() << ' ';
2985 for (pos_type i = beg; i < end; ++i) {
2986 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2988 char_type const c = d->text_[i];
2989 if (isPrintable(c) || c == '\t'
2990 || (c == '\n' && (options & AS_STR_NEWLINES)))
2992 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2993 getInset(i)->toString(os);
2994 if (getInset(i)->asInsetMath())
3003 void Paragraph::forToc(docstring & os, size_t maxlen) const
3005 if (!d->params_.labelString().empty())
3006 os += d->params_.labelString() + ' ';
3007 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
3010 char_type const c = d->text_[i];
3013 else if (c == '\t' || c == '\n')
3015 else if (c == META_INSET)
3016 getInset(i)->forToc(os, maxlen);
3021 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
3023 odocstringstream os;
3026 && options & AS_STR_LABEL
3027 && !d->params_.labelString().empty())
3028 os << d->params_.labelString() << ' ';
3030 for (pos_type i = beg; i < end; ++i) {
3031 char_type const c = d->text_[i];
3032 if (isPrintable(c) || c == '\t'
3033 || (c == '\n' && (options & AS_STR_NEWLINES)))
3035 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3036 getInset(i)->plaintext(os, runparams);
3044 void Paragraph::setInsetOwner(Inset const * inset)
3046 d->inset_owner_ = inset;
3050 int Paragraph::id() const
3056 void Paragraph::setId(int id)
3062 Layout const & Paragraph::layout() const
3068 void Paragraph::setLayout(Layout const & layout)
3070 d->layout_ = &layout;
3074 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3076 setLayout(tc.defaultLayout());
3080 void Paragraph::setPlainLayout(DocumentClass const & tc)
3082 setLayout(tc.plainLayout());
3086 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3088 if (usePlainLayout())
3089 setPlainLayout(tclass);
3091 setDefaultLayout(tclass);
3095 Inset const & Paragraph::inInset() const
3097 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3098 _("Memory problem"), _("Paragraph not properly initialized")));
3099 return *d->inset_owner_;
3103 ParagraphParameters & Paragraph::params()
3109 ParagraphParameters const & Paragraph::params() const
3115 bool Paragraph::isFreeSpacing() const
3117 if (d->layout_->free_spacing)
3119 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3123 bool Paragraph::allowEmpty() const
3125 if (d->layout_->keepempty)
3127 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3131 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3133 if (!Encodings::isArabicChar(c))
3136 char_type prev_char = ' ';
3137 char_type next_char = ' ';
3139 for (pos_type i = pos - 1; i >= 0; --i) {
3140 char_type const par_char = d->text_[i];
3141 if (!Encodings::isArabicComposeChar(par_char)) {
3142 prev_char = par_char;
3147 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3148 char_type const par_char = d->text_[i];
3149 if (!Encodings::isArabicComposeChar(par_char)) {
3150 next_char = par_char;
3155 if (Encodings::isArabicChar(next_char)) {
3156 if (Encodings::isArabicChar(prev_char) &&
3157 !Encodings::isArabicSpecialChar(prev_char))
3158 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3160 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3162 if (Encodings::isArabicChar(prev_char) &&
3163 !Encodings::isArabicSpecialChar(prev_char))
3164 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3166 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3171 int Paragraph::checkBiblio(Buffer const & buffer)
3174 // This is getting more and more a mess. ...We really should clean
3175 // up this bibitem issue for 1.6.
3177 // Add bibitem insets if necessary
3178 if (d->layout_->labeltype != LABEL_BIBLIO)
3181 bool hasbibitem = !d->insetlist_.empty()
3182 // Insist on it being in pos 0
3183 && d->text_[0] == META_INSET
3184 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3186 bool track_changes = buffer.params().trackChanges;
3191 // remove a bibitem in pos != 0
3192 // restore it later in pos 0 if necessary
3193 // (e.g. if a user inserts contents _before_ the item)
3194 // we're assuming there's only one of these, which there
3196 int erasedInsetPosition = -1;
3197 InsetList::iterator it = d->insetlist_.begin();
3198 InsetList::iterator end = d->insetlist_.end();
3199 for (; it != end; ++it)
3200 if (it->inset->lyxCode() == BIBITEM_CODE
3202 InsetCommand * olditem = it->inset->asInsetCommand();
3203 oldkey = olditem->getParam("key");
3204 oldlabel = olditem->getParam("label");
3205 erasedInsetPosition = it->pos;
3206 eraseChar(erasedInsetPosition, track_changes);
3210 // There was an InsetBibitem at the beginning, and we didn't
3211 // have to erase one.
3212 if (hasbibitem && erasedInsetPosition < 0)
3215 // There was an InsetBibitem at the beginning and we did have to
3216 // erase one. So we give its properties to the beginning inset.
3218 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3219 if (!oldkey.empty())
3220 inset->setParam("key", oldkey);
3221 inset->setParam("label", oldlabel);
3222 return -erasedInsetPosition;
3225 // There was no inset at the beginning, so we need to create one with
3226 // the key and label of the one we erased.
3227 InsetBibitem * inset =
3228 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3229 // restore values of previously deleted item in this par.
3230 if (!oldkey.empty())
3231 inset->setParam("key", oldkey);
3232 inset->setParam("label", oldlabel);
3233 insertInset(0, inset,
3234 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3240 void Paragraph::checkAuthors(AuthorList const & authorList)
3242 d->changes_.checkAuthors(authorList);
3246 bool Paragraph::isChanged(pos_type pos) const
3248 return lookupChange(pos).changed();
3252 bool Paragraph::isInserted(pos_type pos) const
3254 return lookupChange(pos).inserted();
3258 bool Paragraph::isDeleted(pos_type pos) const
3260 return lookupChange(pos).deleted();
3264 InsetList const & Paragraph::insetList() const
3266 return d->insetlist_;
3270 void Paragraph::setBuffer(Buffer & b)
3272 d->insetlist_.setBuffer(b);
3276 Inset * Paragraph::releaseInset(pos_type pos)
3278 Inset * inset = d->insetlist_.release(pos);
3279 /// does not honour change tracking!
3280 eraseChar(pos, false);
3285 Inset * Paragraph::getInset(pos_type pos)
3287 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3288 ? d->insetlist_.get(pos) : 0;
3292 Inset const * Paragraph::getInset(pos_type pos) const
3294 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3295 ? d->insetlist_.get(pos) : 0;
3299 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3300 pos_type & right, TextCase action)
3302 // process sequences of modified characters; in change
3303 // tracking mode, this approach results in much better
3304 // usability than changing case on a char-by-char basis
3307 bool const trackChanges = bparams.trackChanges;
3309 bool capitalize = true;
3311 for (; pos < right; ++pos) {
3312 char_type oldChar = d->text_[pos];
3313 char_type newChar = oldChar;
3315 // ignore insets and don't play with deleted text!
3316 if (oldChar != META_INSET && !isDeleted(pos)) {
3318 case text_lowercase:
3319 newChar = lowercase(oldChar);
3321 case text_capitalization:
3323 newChar = uppercase(oldChar);
3327 case text_uppercase:
3328 newChar = uppercase(oldChar);
3333 if (isWordSeparator(pos) || isDeleted(pos)) {
3334 // permit capitalization again
3338 if (oldChar != newChar) {
3340 if (pos != right - 1)
3342 // step behind the changing area
3346 int erasePos = pos - changes.size();
3347 for (size_t i = 0; i < changes.size(); i++) {
3348 insertChar(pos, changes[i],
3349 getFontSettings(bparams,
3352 if (!eraseChar(erasePos, trackChanges)) {
3355 ++right; // expand selection
3363 int Paragraph::find(docstring const & str, bool cs, bool mw,
3364 pos_type start_pos, bool del) const
3366 pos_type pos = start_pos;
3367 int const strsize = str.length();
3369 pos_type const parsize = d->text_.size();
3370 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3371 // Ignore "invisible" letters such as ligature breaks
3372 // and hyphenation chars while searching
3373 while (pos < parsize - 1 && isInset(pos)) {
3374 odocstringstream os;
3375 getInset(pos)->toString(os);
3376 if (!getInset(pos)->isLetter() || !os.str().empty())
3380 if (cs && str[i] != d->text_[pos])
3382 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3384 if (!del && isDeleted(pos))
3391 // if necessary, check whether string matches word
3393 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3396 && !isWordSeparator(pos))
3400 return pos - start_pos;
3404 char_type Paragraph::getChar(pos_type pos) const
3406 return d->text_[pos];
3410 pos_type Paragraph::size() const
3412 return d->text_.size();
3416 bool Paragraph::empty() const
3418 return d->text_.empty();
3422 bool Paragraph::isInset(pos_type pos) const
3424 return d->text_[pos] == META_INSET;
3428 bool Paragraph::isSeparator(pos_type pos) const
3430 //FIXME: Are we sure this can be the only separator?
3431 return d->text_[pos] == ' ';
3435 void Paragraph::deregisterWords()
3437 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3438 Private::LangWordsMap::const_iterator ite = d->words_.end();
3439 for (; itl != ite; ++itl) {
3440 WordList * wl = theWordList(itl->first);
3441 Private::Words::const_iterator it = (itl->second).begin();
3442 Private::Words::const_iterator et = (itl->second).end();
3443 for (; it != et; ++it)
3450 void Paragraph::locateWord(pos_type & from, pos_type & to,
3451 word_location const loc) const
3454 case WHOLE_WORD_STRICT:
3455 if (from == 0 || from == size()
3456 || isWordSeparator(from)
3457 || isWordSeparator(from - 1)) {
3461 // no break here, we go to the next
3464 // If we are already at the beginning of a word, do nothing
3465 if (!from || isWordSeparator(from - 1))
3467 // no break here, we go to the next
3470 // always move the cursor to the beginning of previous word
3471 while (from && !isWordSeparator(from - 1))
3475 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3478 // no need to move the 'from' cursor
3482 while (to < size() && !isWordSeparator(to))
3487 void Paragraph::collectWords()
3489 // This is the value that needs to be exposed in the preferences
3490 // to resolve bug #6760.
3491 static int minlength = 6;
3492 pos_type n = size();
3493 for (pos_type pos = 0; pos < n; ++pos) {
3494 if (isWordSeparator(pos))
3496 pos_type from = pos;
3497 locateWord(from, pos, WHOLE_WORD);
3498 if (pos - from >= minlength) {
3499 docstring word = asString(from, pos, AS_STR_NONE);
3500 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3501 if (cit == d->fontlist_.end())
3503 Language const * lang = cit->font().language();
3504 d->words_[*lang].insert(word);
3510 void Paragraph::registerWords()
3512 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3513 Private::LangWordsMap::const_iterator ite = d->words_.end();
3514 for (; itl != ite; ++itl) {
3515 WordList * wl = theWordList(itl->first);
3516 Private::Words::const_iterator it = (itl->second).begin();
3517 Private::Words::const_iterator et = (itl->second).end();
3518 for (; it != et; ++it)
3524 void Paragraph::updateWords()
3532 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3534 SkipPositionsIterator begin = skips.begin();
3535 SkipPositions::iterator end = skips.end();
3536 if (pos > 0 && begin < end) {
3538 if (end->last == pos - 1) {
3543 skips.insert(end, FontSpan(pos, pos));
3547 Language * Paragraph::Private::locateSpellRange(
3548 pos_type & from, pos_type & to,
3549 SkipPositions & skips) const
3551 // skip leading white space
3552 while (from < to && owner_->isWordSeparator(from))
3554 // don't check empty range
3557 // get current language
3558 Language * lang = getSpellLanguage(from);
3559 pos_type last = from;
3560 bool samelang = true;
3561 bool sameinset = true;
3562 while (last < to && samelang && sameinset) {
3563 // hop to end of word
3564 while (last < to && !owner_->isWordSeparator(last)) {
3565 if (owner_->getInset(last)) {
3566 appendSkipPosition(skips, last);
3567 } else if (owner_->isDeleted(last)) {
3568 appendSkipPosition(skips, last);
3572 // hop to next word while checking for insets
3573 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3574 if (Inset const * inset = owner_->getInset(last))
3575 sameinset = inset->isChar() && inset->isLetter();
3576 if (sameinset && owner_->isDeleted(last)) {
3577 appendSkipPosition(skips, last);
3582 if (sameinset && last < to) {
3583 // now check for language change
3584 samelang = lang == getSpellLanguage(last);
3587 // if language change detected backstep is needed
3595 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3598 const_cast<Language *>(owner_->getFontSettings(
3599 inset_owner_->buffer().params(), from).language());
3600 if (lang == inset_owner_->buffer().params().language
3601 && !lyxrc.spellchecker_alt_lang.empty()) {
3603 string const lang_variety =
3604 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3605 lang->setCode(lang_code);
3606 lang->setVariety(lang_variety);
3612 void Paragraph::requestSpellCheck(pos_type pos)
3614 d->requestSpellCheck(pos);
3618 bool Paragraph::needsSpellCheck() const
3620 SpellChecker::ChangeNumber speller_change_number = 0;
3621 if (theSpellChecker())
3622 speller_change_number = theSpellChecker()->changeNumber();
3623 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3624 d->speller_state_.needsCompleteRefresh(speller_change_number);
3626 return d->needsSpellCheck();
3630 bool Paragraph::Private::ignoreWord(docstring const & word) const
3632 // Ignore words with digits
3633 // FIXME: make this customizable
3634 // (note that some checkers ignore words with digits by default)
3635 docstring::const_iterator cit = word.begin();
3636 docstring::const_iterator const end = word.end();
3637 for (; cit != end; ++cit) {
3638 if (isNumber((*cit)))
3645 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3646 WordLangTuple & wl, docstring_list & suggestions,
3647 bool do_suggestion, bool check_learned) const
3649 SpellChecker::Result result = SpellChecker::WORD_OK;
3650 SpellChecker * speller = theSpellChecker();
3654 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3657 locateWord(from, to, WHOLE_WORD);
3658 if (from == to || from >= size())
3661 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3662 Language * lang = d->getSpellLanguage(from);
3664 wl = WordLangTuple(word, lang);
3669 if (needsSpellCheck() || check_learned) {
3671 if (!d->ignoreWord(word)) {
3672 bool const trailing_dot = to < size() && d->text_[to] == '.';
3673 result = speller->check(wl);
3674 if (SpellChecker::misspelled(result) && trailing_dot) {
3675 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3676 result = speller->check(wl);
3677 if (!SpellChecker::misspelled(result)) {
3678 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3680 from << ".." << to << "]");
3682 // spell check with dot appended failed too
3683 // restore original word/lang value
3684 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3685 wl = WordLangTuple(word, lang);
3689 if (!SpellChecker::misspelled(result)) {
3690 // area up to the begin of the next word is not misspelled
3691 while (end < size() && isWordSeparator(end))
3694 d->setMisspelled(from, end, result);
3696 result = d->speller_state_.getState(from);
3700 suggestions.clear();
3702 if (SpellChecker::misspelled(result)) {
3703 LYXERR(Debug::GUI, "misspelled word: \"" <<
3705 from << ".." << to << "]");
3707 speller->suggest(wl, suggestions);
3713 void Paragraph::Private::markMisspelledWords(
3714 pos_type const & first, pos_type const & last,
3715 SpellChecker::Result result,
3716 docstring const & word,
3717 SkipPositions const & skips)
3719 if (!SpellChecker::misspelled(result)) {
3720 setMisspelled(first, last, SpellChecker::WORD_OK);
3724 SpellChecker * speller = theSpellChecker();
3725 // locate and enumerate the error positions
3726 int nerrors = speller->numMisspelledWords();
3728 SkipPositionsIterator it = skips.begin();
3729 SkipPositionsIterator et = skips.end();
3730 for (int index = 0; index < nerrors; ++index) {
3733 speller->misspelledWord(index, wstart, wlen);
3734 /// should not happen if speller supports range checks
3735 if (!wlen) continue;
3736 docstring const misspelled = word.substr(wstart, wlen);
3737 wstart += first + numskipped;
3738 if (snext < wstart) {
3739 /// mark the range of correct spelling
3740 numskipped += countSkips(it, et, wstart);
3741 setMisspelled(snext,
3742 wstart - 1, SpellChecker::WORD_OK);
3744 snext = wstart + wlen;
3745 numskipped += countSkips(it, et, snext);
3746 /// mark the range of misspelling
3747 setMisspelled(wstart, snext, result);
3748 LYXERR(Debug::GUI, "misspelled word: \"" <<
3749 misspelled << "\" [" <<
3750 wstart << ".." << (snext-1) << "]");
3753 if (snext <= last) {
3754 /// mark the range of correct spelling at end
3755 setMisspelled(snext, last, SpellChecker::WORD_OK);
3760 void Paragraph::spellCheck() const
3762 SpellChecker * speller = theSpellChecker();
3763 if (!speller || !size() ||!needsSpellCheck())
3767 d->rangeOfSpellCheck(start, endpos);
3768 if (speller->canCheckParagraph()) {
3769 // loop until we leave the range
3770 for (pos_type first = start; first < endpos; ) {
3771 pos_type last = endpos;
3772 Private::SkipPositions skips;
3773 Language * lang = d->locateSpellRange(first, last, skips);
3774 if (first >= endpos)
3776 // start the spell checker on the unit of meaning
3777 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3778 WordLangTuple wl = WordLangTuple(word, lang);
3779 SpellChecker::Result result = word.size() ?
3780 speller->check(wl) : SpellChecker::WORD_OK;
3781 d->markMisspelledWords(first, last, result, word, skips);
3785 static docstring_list suggestions;
3786 pos_type to = endpos;
3787 while (start < endpos) {
3789 spellCheck(start, to, wl, suggestions, false);
3793 d->readySpellCheck();
3797 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3799 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3800 if (result || pos <= 0 || pos > size())
3802 if (check_boundary && (pos == size() || isWordSeparator(pos)))
3803 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3808 string Paragraph::magicLabel() const
3811 ss << "magicparlabel-" << id();