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,
339 unsigned int & column);
346 unsigned int & column);
348 bool latexSpecialTypewriter(
352 unsigned int & column);
354 bool latexSpecialPhrase(
357 unsigned int & column,
358 OutputParams const & runparams);
361 void validate(LaTeXFeatures & features) const;
363 /// Checks if the paragraph contains only text and no inset or font change.
364 bool onlyText(Buffer const & buf, Font const & outerfont,
365 pos_type initial) const;
367 /// match a string against a particular point in the paragraph
368 bool isTextAt(string const & str, pos_type pos) const;
370 /// a vector of speller skip positions
371 typedef vector<FontSpan> SkipPositions;
372 typedef SkipPositions::const_iterator SkipPositionsIterator;
374 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
376 Language * getSpellLanguage(pos_type const from) const;
378 Language * locateSpellRange(pos_type & from, pos_type & to,
379 SkipPositions & skips) const;
381 bool hasSpellerChange() const {
382 SpellChecker::ChangeNumber speller_change_number = 0;
383 if (theSpellChecker())
384 speller_change_number = theSpellChecker()->changeNumber();
385 return speller_change_number > speller_state_.currentChangeNumber();
388 bool ignoreWord(docstring const & word) const ;
390 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
392 pos_type textsize = owner_->size();
393 // check for sane arguments
394 if (to <= from || from >= textsize)
396 FontSpan fp = FontSpan(from, to - 1);
397 speller_state_.setRange(fp, state);
400 void requestSpellCheck(pos_type pos) {
401 speller_state_.needsRefresh(pos);
404 void readySpellCheck() {
405 speller_state_.needsRefresh(-1);
408 bool needsSpellCheck() const
410 return speller_state_.needsRefresh();
413 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
415 speller_state_.refreshRange(first, last);
417 last = owner_->size();
420 pos_type endpos = last;
421 owner_->locateWord(first, endpos, WHOLE_WORD);
424 owner_->locateWord(last, endpos, WHOLE_WORD);
429 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
433 while (it != et && it->first < start) {
434 int skip = it->last - it->first + 1;
442 void markMisspelledWords(pos_type const & first, pos_type const & last,
443 SpellChecker::Result result,
444 docstring const & word,
445 SkipPositions const & skips);
447 InsetCode ownerCode() const
449 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
452 /// Which Paragraph owns us?
456 Inset const * inset_owner_;
465 ParagraphParameters params_;
467 /// for recording and looking up changes
471 InsetList insetlist_;
474 pos_type begin_of_body_;
476 typedef docstring TextContainer;
480 typedef set<docstring> Words;
481 typedef map<Language, Words> LangWordsMap;
485 Layout const * layout_;
487 SpellCheckerState speller_state_;
493 struct special_phrase {
499 special_phrase const special_phrases[] = {
500 { "LyX", from_ascii("\\LyX{}"), false },
501 { "TeX", from_ascii("\\TeX{}"), true },
502 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
503 { "LaTeX", from_ascii("\\LaTeX{}"), true },
506 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
511 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
512 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
518 // Initialization of the counter for the paragraph id's,
520 // FIXME: There should be a more intelligent way to generate and use the
521 // paragraph ids per buffer instead a global static counter for all InsetText
522 // in the running program.
523 static int paragraph_id = -1;
525 Paragraph::Private::Private(Private const & p, Paragraph * owner)
526 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
527 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
528 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
531 id_ = ++paragraph_id;
532 requestSpellCheck(p.text_.size());
536 Paragraph::Private::Private(Private const & p, Paragraph * owner,
537 pos_type beg, pos_type end)
538 : owner_(owner), inset_owner_(p.inset_owner_),
539 params_(p.params_), changes_(p.changes_),
540 insetlist_(p.insetlist_, beg, end),
541 begin_of_body_(p.begin_of_body_), words_(p.words_),
544 id_ = ++paragraph_id;
545 if (beg >= pos_type(p.text_.size()))
547 text_ = p.text_.substr(beg, end - beg);
549 FontList::const_iterator fcit = fontlist_.begin();
550 FontList::const_iterator fend = fontlist_.end();
551 for (; fcit != fend; ++fcit) {
552 if (fcit->pos() < beg)
554 if (fcit->pos() >= end) {
555 // Add last entry in the fontlist_.
556 fontlist_.set(text_.size() - 1, fcit->font());
559 // Add a new entry in the fontlist_.
560 fontlist_.set(fcit->pos() - beg, fcit->font());
562 requestSpellCheck(p.text_.size());
566 void Paragraph::addChangesToToc(DocIterator const & cdit,
567 Buffer const & buf) const
569 d->changes_.addToToc(cdit, buf);
573 bool Paragraph::isDeleted(pos_type start, pos_type end) const
575 LASSERT(start >= 0 && start <= size(), /**/);
576 LASSERT(end > start && end <= size() + 1, /**/);
578 return d->changes_.isDeleted(start, end);
582 bool Paragraph::isChanged(pos_type start, pos_type end) const
584 LASSERT(start >= 0 && start <= size(), /**/);
585 LASSERT(end > start && end <= size() + 1, /**/);
587 return d->changes_.isChanged(start, end);
591 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
593 // keep the logic here in sync with the logic of eraseChars()
597 Change const change = d->changes_.lookup(size());
598 return change.inserted() && change.currentAuthor();
602 void Paragraph::setChange(Change const & change)
604 // beware of the imaginary end-of-par character!
605 d->changes_.set(change, 0, size() + 1);
608 * Propagate the change recursively - but not in case of DELETED!
610 * Imagine that your co-author makes changes in an existing inset. He
611 * sends your document to you and you come to the conclusion that the
612 * inset should go completely. If you erase it, LyX must not delete all
613 * text within the inset. Otherwise, the change tracked insertions of
614 * your co-author get lost and there is no way to restore them later.
616 * Conclusion: An inset's content should remain untouched if you delete it
619 if (!change.deleted()) {
620 for (pos_type pos = 0; pos < size(); ++pos) {
621 if (Inset * inset = getInset(pos))
622 inset->setChange(change);
628 void Paragraph::setChange(pos_type pos, Change const & change)
630 LASSERT(pos >= 0 && pos <= size(), /**/);
631 d->changes_.set(change, pos);
633 // see comment in setChange(Change const &) above
634 if (!change.deleted() && pos < size())
635 if (Inset * inset = getInset(pos))
636 inset->setChange(change);
640 Change const & Paragraph::lookupChange(pos_type pos) const
642 LASSERT(pos >= 0 && pos <= size(), /**/);
643 return d->changes_.lookup(pos);
647 void Paragraph::acceptChanges(pos_type start, pos_type end)
649 LASSERT(start >= 0 && start <= size(), /**/);
650 LASSERT(end > start && end <= size() + 1, /**/);
652 for (pos_type pos = start; pos < end; ++pos) {
653 switch (lookupChange(pos).type) {
654 case Change::UNCHANGED:
655 // accept changes in nested inset
656 if (Inset * inset = getInset(pos))
657 inset->acceptChanges();
660 case Change::INSERTED:
661 d->changes_.set(Change(Change::UNCHANGED), pos);
662 // also accept changes in nested inset
663 if (Inset * inset = getInset(pos))
664 inset->acceptChanges();
667 case Change::DELETED:
668 // Suppress access to non-existent
669 // "end-of-paragraph char"
671 eraseChar(pos, false);
682 void Paragraph::rejectChanges(pos_type start, pos_type end)
684 LASSERT(start >= 0 && start <= size(), /**/);
685 LASSERT(end > start && end <= size() + 1, /**/);
687 for (pos_type pos = start; pos < end; ++pos) {
688 switch (lookupChange(pos).type) {
689 case Change::UNCHANGED:
690 // reject changes in nested inset
691 if (Inset * inset = getInset(pos))
692 inset->rejectChanges();
695 case Change::INSERTED:
696 // Suppress access to non-existent
697 // "end-of-paragraph char"
699 eraseChar(pos, false);
705 case Change::DELETED:
706 d->changes_.set(Change(Change::UNCHANGED), pos);
708 // Do NOT reject changes within a deleted inset!
709 // There may be insertions of a co-author inside of it!
717 void Paragraph::Private::insertChar(pos_type pos, char_type c,
718 Change const & change)
720 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
723 changes_.insert(change, pos);
725 // This is actually very common when parsing buffers (and
726 // maybe inserting ascii text)
727 if (pos == pos_type(text_.size())) {
728 // when appending characters, no need to update tables
730 // but we want spell checking
731 requestSpellCheck(pos);
735 text_.insert(text_.begin() + pos, c);
737 // Update the font table.
738 fontlist_.increasePosAfterPos(pos);
741 insetlist_.increasePosAfterPos(pos);
743 // Update list of misspelled positions
744 speller_state_.increasePosAfterPos(pos);
748 bool Paragraph::insertInset(pos_type pos, Inset * inset,
749 Change const & change)
751 LASSERT(inset, /**/);
752 LASSERT(pos >= 0 && pos <= size(), /**/);
754 // Paragraph::insertInset() can be used in cut/copy/paste operation where
755 // d->inset_owner_ is not set yet.
756 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
759 d->insertChar(pos, META_INSET, change);
760 LASSERT(d->text_[pos] == META_INSET, /**/);
762 // Add a new entry in the insetlist_.
763 d->insetlist_.insert(inset, pos);
765 // Some insets require run of spell checker
766 requestSpellCheck(pos);
771 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
773 LASSERT(pos >= 0 && pos <= size(), return false);
775 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
778 Change change = d->changes_.lookup(pos);
780 // set the character to DELETED if
781 // a) it was previously unchanged or
782 // b) it was inserted by a co-author
784 if (!change.changed() ||
785 (change.inserted() && !change.currentAuthor())) {
786 setChange(pos, Change(Change::DELETED));
787 // request run of spell checker
788 requestSpellCheck(pos);
792 if (change.deleted())
796 // Don't physically access the imaginary end-of-paragraph character.
797 // eraseChar() can only mark it as DELETED. A physical deletion of
798 // end-of-par must be handled externally.
804 d->changes_.erase(pos);
806 // if it is an inset, delete the inset entry
807 if (d->text_[pos] == META_INSET)
808 d->insetlist_.erase(pos);
810 d->text_.erase(d->text_.begin() + pos);
812 // Update the fontlist_
813 d->fontlist_.erase(pos);
815 // Update the insetlist_
816 d->insetlist_.decreasePosAfterPos(pos);
818 // Update list of misspelled positions
819 d->speller_state_.decreasePosAfterPos(pos);
820 d->speller_state_.refreshLast(size());
826 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
828 LASSERT(start >= 0 && start <= size(), /**/);
829 LASSERT(end >= start && end <= size() + 1, /**/);
832 for (pos_type count = end - start; count; --count) {
833 if (!eraseChar(i, trackChanges))
840 int Paragraph::Private::latexSurrogatePair(otexstream & os, char_type c,
841 char_type next, OutputParams const & runparams)
843 // Writing next here may circumvent a possible font change between
844 // c and next. Since next is only output if it forms a surrogate pair
845 // with c we can ignore this:
846 // A font change inside a surrogate pair does not make sense and is
847 // hopefully impossible to input.
848 // FIXME: change tracking
849 // Is this correct WRT change tracking?
850 Encoding const & encoding = *(runparams.encoding);
851 docstring const latex1 = encoding.latexChar(next);
852 docstring const latex2 = encoding.latexChar(c);
853 if (docstring(1, next) == latex1) {
854 // the encoding supports the combination
855 os << latex2 << latex1;
856 return latex1.length() + latex2.length();
857 } else if (runparams.local_font &&
858 runparams.local_font->language()->lang() == "polutonikogreek") {
859 // polutonikogreek only works without the brackets
860 os << latex1 << latex2;
861 return latex1.length() + latex2.length();
863 os << latex1 << '{' << latex2 << '}';
864 return latex1.length() + latex2.length() + 2;
868 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
871 unsigned int & column,
873 Layout const & style)
875 if (style.pass_thru || runparams.pass_thru)
878 if (i + 1 < int(text_.size())) {
879 char_type next = text_[i + 1];
880 if (Encodings::isCombiningChar(next)) {
881 // This space has an accent, so we must always output it.
882 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
887 if (runparams.linelen > 0
888 && column > runparams.linelen
890 && text_[i - 1] != ' '
891 && (i + 1 < int(text_.size()))
892 // same in FreeSpacing mode
893 && !owner_->isFreeSpacing()
894 // In typewriter mode, we want to avoid
895 // ! . ? : at the end of a line
896 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
897 && (text_[i - 1] == '.'
898 || text_[i - 1] == '?'
899 || text_[i - 1] == ':'
900 || text_[i - 1] == '!'))) {
902 os.texrow().start(owner_->id(), i + 1);
904 } else if (style.free_spacing) {
913 int Paragraph::Private::writeScriptChars(otexstream & os,
914 docstring const & ltx,
915 Change const & runningChange,
916 Encoding const & encoding,
919 // FIXME: modifying i here is not very nice...
921 // We only arrive here when a proper language for character text_[i] has
922 // not been specified (i.e., it could not be translated in the current
923 // latex encoding) or its latex translation has been forced, and it
924 // belongs to a known script.
925 // Parameter ltx contains the latex translation of text_[i] as specified
926 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
927 // The latex macro name "textXXX" specifies the script to which text_[i]
928 // belongs and we use it in order to check whether characters from the
929 // same script immediately follow, such that we can collect them in a
930 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
931 // for the first char but only "<spec>" for all subsequent chars.
932 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
933 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
934 string script = to_ascii(ltx.substr(1, brace1 - 1));
937 bool closing_brace = true;
938 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
939 // Correct encoding is being used, so we can avoid \textgreek.
942 closing_brace = false;
944 os << ltx.substr(pos, length);
945 int size = text_.size();
946 while (i + 1 < size) {
947 char_type const next = text_[i + 1];
948 // Stop here if next character belongs to another script
949 // or there is a change in change tracking status.
950 if (!Encodings::isKnownScriptChar(next, script) ||
951 runningChange != owner_->lookupChange(i + 1))
955 FontList::const_iterator cit = fontlist_.begin();
956 FontList::const_iterator end = fontlist_.end();
957 for (; cit != end; ++cit) {
958 if (cit->pos() >= i && !found) {
959 prev_font = cit->font();
962 if (cit->pos() >= i + 1)
965 // Stop here if there is a font attribute or encoding change.
966 if (found && cit != end && prev_font != cit->font())
968 docstring const latex = encoding.latexChar(next);
969 docstring::size_type const b1 =
970 latex.find_first_of(from_ascii("{"));
971 docstring::size_type const b2 =
972 latex.find_last_of(from_ascii("}"));
973 int const len = b2 - b1 - 1;
974 os << latex.substr(b1 + 1, len);
986 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
988 pos_type const len = str.length();
990 // is the paragraph large enough?
991 if (pos + len > int(text_.size()))
994 // does the wanted text start at point?
995 for (string::size_type i = 0; i < str.length(); ++i) {
996 // Caution: direct comparison of characters works only
997 // because str is pure ASCII.
998 if (str[i] != text_[pos + i])
1002 return fontlist_.hasChangeInRange(pos, len);
1006 void Paragraph::Private::latexInset(BufferParams const & bparams,
1008 OutputParams & runparams,
1009 Font & running_font,
1011 Font const & outerfont,
1013 Change & running_change,
1014 Layout const & style,
1016 unsigned int & column)
1018 Inset * inset = owner_->getInset(i);
1019 LASSERT(inset, /**/);
1021 if (style.pass_thru) {
1022 inset->plaintext(os.os(), runparams);
1026 // FIXME: move this to InsetNewline::latex
1027 if (inset->lyxCode() == NEWLINE_CODE) {
1028 // newlines are handled differently here than
1029 // the default in simpleTeXSpecialChars().
1030 if (!style.newline_allowed) {
1034 column += running_font.latexWriteEndChanges(
1035 os, bparams, runparams,
1036 basefont, basefont);
1040 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1043 basefont = owner_->getLayoutFont(bparams, outerfont);
1044 running_font = basefont;
1046 if (runparams.moving_arg)
1050 os.texrow().start(owner_->id(), i + 1);
1054 if (owner_->isDeleted(i)) {
1055 if( ++runparams.inDeletedInset == 1)
1056 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1059 if (inset->canTrackChanges()) {
1060 column += Changes::latexMarkChange(os, bparams, running_change,
1061 Change(Change::UNCHANGED), runparams);
1062 running_change = Change(Change::UNCHANGED);
1066 odocstream::pos_type const len = os.os().tellp();
1068 if (inset->forceLTR()
1069 && running_font.isRightToLeft()
1070 // ERT is an exception, it should be output with no
1071 // decorations at all
1072 && inset->lyxCode() != ERT_CODE) {
1073 if (running_font.language()->lang() == "farsi")
1080 // FIXME: Bug: we can have an empty font change here!
1081 // if there has just been a font change, we are going to close it
1082 // right now, which means stupid latex code like \textsf{}. AFAIK,
1083 // this does not harm dvi output. A minor bug, thus (JMarc)
1085 // Some insets cannot be inside a font change command.
1086 // However, even such insets *can* be placed in \L or \R
1087 // or their equivalents (for RTL language switches), so we don't
1088 // close the language in those cases.
1089 // ArabTeX, though, cannot handle this special behavior, it seems.
1090 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1091 || running_font.language()->lang() == "arabic_arabtex";
1092 if (open_font && inset->noFontChange()) {
1093 bool closeLanguage = arabtex
1094 || basefont.isRightToLeft() == running_font.isRightToLeft();
1095 unsigned int count = running_font.latexWriteEndChanges(os,
1096 bparams, runparams, basefont, basefont, closeLanguage);
1098 // if any font properties were closed, update the running_font,
1099 // making sure, however, to leave the language as it was
1101 // FIXME: probably a better way to keep track of the old
1102 // language, than copying the entire font?
1103 Font const copy_font(running_font);
1104 basefont = owner_->getLayoutFont(bparams, outerfont);
1105 running_font = basefont;
1107 running_font.setLanguage(copy_font.language());
1108 // leave font open if language is still open
1109 open_font = (running_font.language() == basefont.language());
1111 runparams.local_font = &basefont;
1115 int prev_rows = os.texrow().rows();
1118 inset->latex(os, runparams);
1119 } catch (EncodingException & e) {
1120 // add location information and throw again.
1127 if (running_font.language()->lang() == "farsi")
1133 if (os.texrow().rows() > prev_rows) {
1134 os.texrow().start(owner_->id(), i + 1);
1137 column += (unsigned int)(os.os().tellp() - len);
1140 if (owner_->isDeleted(i))
1141 --runparams.inDeletedInset;
1145 void Paragraph::Private::latexSpecialChar(otexstream & os,
1146 OutputParams const & runparams,
1147 Font const & running_font,
1148 Change const & running_change,
1149 Layout const & style,
1151 unsigned int & column)
1153 char_type const c = text_[i];
1155 if (style.pass_thru || runparams.pass_thru) {
1157 // FIXME UNICODE: This can fail if c cannot
1158 // be encoded in the current encoding.
1163 // If T1 font encoding is used, use the special
1164 // characters it provides.
1165 // NOTE: some languages reset the font encoding
1167 if (!running_font.language()->internalFontEncoding()
1168 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1171 // \tt font needs special treatment
1172 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1173 && latexSpecialTypewriter(c, os, i, column))
1176 // Otherwise, we use what LaTeX provides us.
1179 os << "\\textbackslash{}";
1183 os << "\\textless{}";
1187 os << "\\textgreater{}";
1191 os << "\\textbar{}";
1198 os << "\\char`\\\"{}";
1203 case '%': case '#': case '{':
1211 os << "\\textasciitilde{}";
1216 os << "\\textasciicircum{}";
1223 // avoid being mistaken for optional arguments
1231 // Blanks are printed before font switching.
1232 // Sure? I am not! (try nice-latex)
1233 // I am sure it's correct. LyX might be smarter
1234 // in the future, but for now, nothing wrong is
1240 if (latexSpecialPhrase(os, i, column, runparams))
1246 Encoding const & encoding = *(runparams.encoding);
1247 if (i + 1 < int(text_.size())) {
1248 char_type next = text_[i + 1];
1249 if (Encodings::isCombiningChar(next)) {
1250 column += latexSurrogatePair(os, c, next, runparams) - 1;
1256 docstring const latex = encoding.latexChar(c);
1257 if (Encodings::isKnownScriptChar(c, script)
1258 && prefixIs(latex, from_ascii("\\" + script)))
1259 column += writeScriptChars(os, latex,
1260 running_change, encoding, i) - 1;
1261 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1262 // Prevent eating of a following
1263 // space or command corruption by
1264 // following characters
1265 column += latex.length() + 1;
1266 os << latex << "{}";
1268 column += latex.length() - 1;
1276 bool Paragraph::Private::latexSpecialT1(char_type const c, otexstream & os,
1277 pos_type i, unsigned int & column)
1283 // In T1 encoding, these characters exist
1284 // but we should avoid ligatures
1285 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1287 os << "\\textcompwordmark{}";
1294 // soul.sty breaks with \char`\"
1295 os << "\\textquotedbl{}";
1304 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, otexstream & os,
1305 pos_type i, unsigned int & column)
1309 // within \ttfamily, "--" is merged to "-" (no endash)
1310 // so we avoid this rather irritating ligature
1311 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1318 // everything else has to be checked separately
1319 // (depending on the encoding)
1326 bool Paragraph::Private::latexSpecialPhrase(otexstream & os, pos_type & i,
1327 unsigned int & column, OutputParams const & runparams)
1329 // FIXME: if we have "LaTeX" with a font
1330 // change in the middle (before the 'T', then
1331 // the "TeX" part is still special cased.
1332 // Really we should only operate this on
1333 // "words" for some definition of word
1335 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1336 if (!isTextAt(special_phrases[pnr].phrase, i))
1338 if (runparams.moving_arg)
1340 os << special_phrases[pnr].macro;
1341 i += special_phrases[pnr].phrase.length() - 1;
1342 column += special_phrases[pnr].macro.length() - 1;
1349 void Paragraph::Private::validate(LaTeXFeatures & features) const
1351 if (layout_->inpreamble && inset_owner_) {
1352 bool const is_command = layout_->latextype == LATEX_COMMAND;
1353 Buffer const & buf = inset_owner_->buffer();
1354 BufferParams const & bp = buf.params();
1357 // Using a string stream here circumvents the encoding
1358 // switching machinery of odocstream. Therefore the
1359 // output is wrong if this paragraph contains content
1360 // that needs to switch encoding.
1361 odocstringstream ods;
1362 otexstream os(ods, texrow);
1364 os << '\\' << from_ascii(layout_->latexname());
1365 // we have to provide all the optional arguments here, even though
1366 // the last one is the only one we care about.
1367 // Separate handling of optional argument inset.
1368 if (layout_->optargs != 0 || layout_->reqargs != 0)
1369 latexArgInsets(*owner_, os, features.runparams(),
1370 layout_->reqargs, layout_->optargs);
1372 os << from_ascii(layout_->latexparam());
1374 docstring::size_type const length = ods.str().length();
1375 // this will output "{" at the beginning, but not at the end
1376 owner_->latex(bp, f, os, features.runparams(), 0, -1, true);
1377 if (ods.str().length() > length) {
1380 string const snippet = to_utf8(ods.str());
1381 features.addPreambleSnippet(snippet);
1385 if (features.runparams().flavor == OutputParams::HTML
1386 && layout_->htmltitle()) {
1387 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1390 // check the params.
1391 if (!params_.spacing().isDefault())
1392 features.require("setspace");
1395 features.useLayout(layout_->name());
1398 fontlist_.validate(features);
1400 // then the indentation
1401 if (!params_.leftIndent().zero())
1402 features.require("ParagraphLeftIndent");
1405 InsetList::const_iterator icit = insetlist_.begin();
1406 InsetList::const_iterator iend = insetlist_.end();
1407 for (; icit != iend; ++icit) {
1409 icit->inset->validate(features);
1410 if (layout_->needprotect &&
1411 icit->inset->lyxCode() == FOOT_CODE)
1412 features.require("NeedLyXFootnoteCode");
1416 // then the contents
1417 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1418 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1419 if (!special_phrases[pnr].builtin
1420 && isTextAt(special_phrases[pnr].phrase, i)) {
1421 features.require(special_phrases[pnr].phrase);
1425 Encodings::validate(text_[i], features);
1429 /////////////////////////////////////////////////////////////////////
1433 /////////////////////////////////////////////////////////////////////
1436 Layout const emptyParagraphLayout;
1439 Paragraph::Paragraph()
1440 : d(new Paragraph::Private(this, emptyParagraphLayout))
1447 Paragraph::Paragraph(Paragraph const & par)
1448 : itemdepth(par.itemdepth),
1449 d(new Paragraph::Private(*par.d, this))
1455 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1456 : itemdepth(par.itemdepth),
1457 d(new Paragraph::Private(*par.d, this, beg, end))
1463 Paragraph & Paragraph::operator=(Paragraph const & par)
1465 // needed as we will destroy the private part before copying it
1467 itemdepth = par.itemdepth;
1471 d = new Private(*par.d, this);
1478 Paragraph::~Paragraph()
1487 // this shall be called just before every "os << ..." action.
1488 void flushString(ostream & os, docstring & s)
1497 void Paragraph::write(ostream & os, BufferParams const & bparams,
1498 depth_type & dth) const
1500 // The beginning or end of a deeper (i.e. nested) area?
1501 if (dth != d->params_.depth()) {
1502 if (d->params_.depth() > dth) {
1503 while (d->params_.depth() > dth) {
1504 os << "\n\\begin_deeper";
1508 while (d->params_.depth() < dth) {
1509 os << "\n\\end_deeper";
1515 // First write the layout
1516 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1518 d->params_.write(os);
1520 Font font1(inherit_font, bparams.language);
1522 Change running_change = Change(Change::UNCHANGED);
1524 // this string is used as a buffer to avoid repetitive calls
1525 // to to_utf8(), which turn out to be expensive (JMarc)
1526 docstring write_buffer;
1529 for (pos_type i = 0; i <= size(); ++i) {
1531 Change const change = lookupChange(i);
1532 if (change != running_change)
1533 flushString(os, write_buffer);
1534 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1535 running_change = change;
1540 // Write font changes
1541 Font font2 = getFontSettings(bparams, i);
1542 if (font2 != font1) {
1543 flushString(os, write_buffer);
1544 font2.lyxWriteChanges(font1, os);
1549 char_type const c = d->text_[i];
1552 if (Inset const * inset = getInset(i)) {
1553 flushString(os, write_buffer);
1554 if (inset->directWrite()) {
1555 // international char, let it write
1556 // code directly so it's shorter in
1562 os << "\\begin_inset ";
1564 os << "\n\\end_inset\n\n";
1570 flushString(os, write_buffer);
1571 os << "\n\\backslash\n";
1575 flushString(os, write_buffer);
1576 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1583 if ((column > 70 && c == ' ')
1585 flushString(os, write_buffer);
1589 // this check is to amend a bug. LyX sometimes
1590 // inserts '\0' this could cause problems.
1592 write_buffer.push_back(c);
1594 LYXERR0("NUL char in structure.");
1600 flushString(os, write_buffer);
1601 os << "\n\\end_layout\n";
1605 void Paragraph::validate(LaTeXFeatures & features) const
1607 d->validate(features);
1611 void Paragraph::insert(pos_type start, docstring const & str,
1612 Font const & font, Change const & change)
1614 for (size_t i = 0, n = str.size(); i != n ; ++i)
1615 insertChar(start + i, str[i], font, change);
1619 void Paragraph::appendChar(char_type c, Font const & font,
1620 Change const & change)
1623 d->changes_.insert(change, d->text_.size());
1624 // when appending characters, no need to update tables
1625 d->text_.push_back(c);
1626 setFont(d->text_.size() - 1, font);
1630 void Paragraph::appendString(docstring const & s, Font const & font,
1631 Change const & change)
1633 pos_type end = s.size();
1634 size_t oldsize = d->text_.size();
1635 size_t newsize = oldsize + end;
1636 size_t capacity = d->text_.capacity();
1637 if (newsize >= capacity)
1638 d->text_.reserve(max(capacity + 100, newsize));
1640 // when appending characters, no need to update tables
1643 // FIXME: Optimize this!
1644 for (size_t i = oldsize; i != newsize; ++i) {
1646 d->changes_.insert(change, i);
1648 d->fontlist_.set(oldsize, font);
1649 d->fontlist_.set(newsize - 1, font);
1653 void Paragraph::insertChar(pos_type pos, char_type c,
1656 d->insertChar(pos, c, Change(trackChanges ?
1657 Change::INSERTED : Change::UNCHANGED));
1661 void Paragraph::insertChar(pos_type pos, char_type c,
1662 Font const & font, bool trackChanges)
1664 d->insertChar(pos, c, Change(trackChanges ?
1665 Change::INSERTED : Change::UNCHANGED));
1670 void Paragraph::insertChar(pos_type pos, char_type c,
1671 Font const & font, Change const & change)
1673 d->insertChar(pos, c, change);
1678 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1679 Font const & font, Change const & change)
1681 bool const success = insertInset(pos, inset, change);
1682 // Set the font/language of the inset...
1688 void Paragraph::resetFonts(Font const & font)
1690 d->fontlist_.clear();
1691 d->fontlist_.set(0, font);
1692 d->fontlist_.set(d->text_.size() - 1, font);
1695 // Gets uninstantiated font setting at position.
1696 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1700 LYXERR0("pos: " << pos << " size: " << size());
1701 LASSERT(pos <= size(), /**/);
1704 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1705 if (cit != d->fontlist_.end())
1708 if (pos == size() && !empty())
1709 return getFontSettings(bparams, pos - 1);
1711 // Optimisation: avoid a full font instantiation if there is no
1712 // language change from previous call.
1713 static Font previous_font;
1714 static Language const * previous_lang = 0;
1715 Language const * lang = getParLanguage(bparams);
1716 if (lang != previous_lang) {
1717 previous_lang = lang;
1718 previous_font = Font(inherit_font, lang);
1720 return previous_font;
1724 FontSpan Paragraph::fontSpan(pos_type pos) const
1726 LASSERT(pos <= size(), /**/);
1729 FontList::const_iterator cit = d->fontlist_.begin();
1730 FontList::const_iterator end = d->fontlist_.end();
1731 for (; cit != end; ++cit) {
1732 if (cit->pos() >= pos) {
1733 if (pos >= beginOfBody())
1734 return FontSpan(max(start, beginOfBody()),
1737 return FontSpan(start,
1738 min(beginOfBody() - 1,
1741 start = cit->pos() + 1;
1744 // This should not happen, but if so, we take no chances.
1745 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1746 return FontSpan(pos, pos);
1750 // Gets uninstantiated font setting at position 0
1751 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1753 if (!empty() && !d->fontlist_.empty())
1754 return d->fontlist_.begin()->font();
1756 // Optimisation: avoid a full font instantiation if there is no
1757 // language change from previous call.
1758 static Font previous_font;
1759 static Language const * previous_lang = 0;
1760 if (bparams.language != previous_lang) {
1761 previous_lang = bparams.language;
1762 previous_font = Font(inherit_font, bparams.language);
1765 return previous_font;
1769 // Gets the fully instantiated font at a given position in a paragraph
1770 // This is basically the same function as Text::GetFont() in text2.cpp.
1771 // The difference is that this one is used for generating the LaTeX file,
1772 // and thus cosmetic "improvements" are disallowed: This has to deliver
1773 // the true picture of the buffer. (Asger)
1774 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1775 Font const & outerfont) const
1777 LASSERT(pos >= 0, /**/);
1779 Font font = getFontSettings(bparams, pos);
1781 pos_type const body_pos = beginOfBody();
1782 FontInfo & fi = font.fontInfo();
1784 fi.realize(d->layout_->labelfont);
1786 fi.realize(d->layout_->font);
1788 fi.realize(outerfont.fontInfo());
1789 fi.realize(bparams.getFont().fontInfo());
1795 Font const Paragraph::getLabelFont
1796 (BufferParams const & bparams, Font const & outerfont) const
1798 FontInfo tmpfont = d->layout_->labelfont;
1799 tmpfont.realize(outerfont.fontInfo());
1800 tmpfont.realize(bparams.getFont().fontInfo());
1801 return Font(tmpfont, getParLanguage(bparams));
1805 Font const Paragraph::getLayoutFont
1806 (BufferParams const & bparams, Font const & outerfont) const
1808 FontInfo tmpfont = d->layout_->font;
1809 tmpfont.realize(outerfont.fontInfo());
1810 tmpfont.realize(bparams.getFont().fontInfo());
1811 return Font(tmpfont, getParLanguage(bparams));
1815 /// Returns the height of the highest font in range
1816 FontSize Paragraph::highestFontInRange
1817 (pos_type startpos, pos_type endpos, FontSize def_size) const
1819 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1823 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1825 char_type c = d->text_[pos];
1826 if (!lyxrc.rtl_support)
1856 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1862 void Paragraph::setFont(pos_type pos, Font const & font)
1864 LASSERT(pos <= size(), /**/);
1866 // First, reduce font against layout/label font
1867 // Update: The setCharFont() routine in text2.cpp already
1868 // reduces font, so we don't need to do that here. (Asger)
1870 d->fontlist_.set(pos, font);
1874 void Paragraph::makeSameLayout(Paragraph const & par)
1876 d->layout_ = par.d->layout_;
1877 d->params_ = par.d->params_;
1881 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1883 if (isFreeSpacing())
1889 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1890 if (eraseChar(pos, trackChanges))
1896 return count > 0 || pos > 0;
1900 bool Paragraph::hasSameLayout(Paragraph const & par) const
1902 return par.d->layout_ == d->layout_
1903 && d->params_.sameLayout(par.d->params_);
1907 depth_type Paragraph::getDepth() const
1909 return d->params_.depth();
1913 depth_type Paragraph::getMaxDepthAfter() const
1915 if (d->layout_->isEnvironment())
1916 return d->params_.depth() + 1;
1918 return d->params_.depth();
1922 char Paragraph::getAlign() const
1924 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1925 return d->layout_->align;
1927 return d->params_.align();
1931 docstring const & Paragraph::labelString() const
1933 return d->params_.labelString();
1937 // the next two functions are for the manual labels
1938 docstring const Paragraph::getLabelWidthString() const
1940 if (d->layout_->margintype == MARGIN_MANUAL
1941 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1942 return d->params_.labelWidthString();
1944 return _("Senseless with this layout!");
1948 void Paragraph::setLabelWidthString(docstring const & s)
1950 d->params_.labelWidthString(s);
1954 docstring Paragraph::expandLabel(Layout const & layout,
1955 BufferParams const & bparams) const
1957 return expandParagraphLabel(layout, bparams, true);
1961 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1962 BufferParams const & bparams) const
1964 return expandParagraphLabel(layout, bparams, false);
1968 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1969 BufferParams const & bparams, bool process_appendix) const
1971 DocumentClass const & tclass = bparams.documentClass();
1972 string const & lang = getParLanguage(bparams)->code();
1973 bool const in_appendix = process_appendix && d->params_.appendix();
1974 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1976 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1977 && !layout.counter.empty())
1978 return tclass.counters().theCounter(layout.counter, lang);
1980 // handle 'inherited level parts' in 'fmt',
1981 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1982 size_t const i = fmt.find('@', 0);
1983 if (i != docstring::npos) {
1984 size_t const j = fmt.find('@', i + 1);
1985 if (j != docstring::npos) {
1986 docstring parent(fmt, i + 1, j - i - 1);
1987 docstring label = from_ascii("??");
1988 if (tclass.hasLayout(parent))
1989 docstring label = expandParagraphLabel(tclass[parent], bparams,
1991 fmt = docstring(fmt, 0, i) + label
1992 + docstring(fmt, j + 1, docstring::npos);
1996 return tclass.counters().counterLabel(fmt, lang);
2000 void Paragraph::applyLayout(Layout const & new_layout)
2002 d->layout_ = &new_layout;
2003 LyXAlignment const oldAlign = d->params_.align();
2005 if (!(oldAlign & d->layout_->alignpossible)) {
2006 frontend::Alert::warning(_("Alignment not permitted"),
2007 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2008 d->params_.align(LYX_ALIGN_LAYOUT);
2013 pos_type Paragraph::beginOfBody() const
2015 return d->begin_of_body_;
2019 void Paragraph::setBeginOfBody()
2021 if (d->layout_->labeltype != LABEL_MANUAL) {
2022 d->begin_of_body_ = 0;
2026 // Unroll the first two cycles of the loop
2027 // and remember the previous character to
2028 // remove unnecessary getChar() calls
2030 pos_type end = size();
2031 if (i < end && !isNewline(i)) {
2033 char_type previous_char = 0;
2036 previous_char = d->text_[i];
2037 if (!isNewline(i)) {
2039 while (i < end && previous_char != ' ') {
2044 previous_char = temp;
2050 d->begin_of_body_ = i;
2054 bool Paragraph::allowParagraphCustomization() const
2056 return inInset().allowParagraphCustomization();
2060 bool Paragraph::usePlainLayout() const
2062 return inInset().usePlainLayout();
2066 bool Paragraph::isPassThru() const
2068 return inInset().getLayout().isPassThru() || d->layout_->pass_thru;
2073 // paragraphs inside floats need different alignment tags to avoid
2076 bool noTrivlistCentering(InsetCode code)
2078 return code == FLOAT_CODE
2079 || code == WRAP_CODE
2080 || code == CELL_CODE;
2084 string correction(string const & orig)
2086 if (orig == "flushleft")
2087 return "raggedright";
2088 if (orig == "flushright")
2089 return "raggedleft";
2090 if (orig == "center")
2096 string const corrected_env(string const & suffix, string const & env,
2097 InsetCode code, bool const lastpar)
2099 string output = suffix + "{";
2100 if (noTrivlistCentering(code)) {
2102 // the last paragraph in non-trivlist-aligned
2103 // context is special (to avoid unwanted whitespace)
2104 if (suffix == "\\begin")
2105 return "\\" + correction(env) + "{}";
2108 output += correction(env);
2112 if (suffix == "\\begin")
2118 void adjust_column(string const & str, int & column)
2120 if (!contains(str, "\n"))
2121 column += str.size();
2124 column = rsplit(str, tmp, '\n').size();
2131 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2132 otexstream & os, OutputParams const & runparams) const
2136 if (params_.noindent() && !layout_->pass_thru) {
2137 os << "\\noindent ";
2141 LyXAlignment const curAlign = params_.align();
2143 if (curAlign == layout_->align)
2147 case LYX_ALIGN_NONE:
2148 case LYX_ALIGN_BLOCK:
2149 case LYX_ALIGN_LAYOUT:
2150 case LYX_ALIGN_SPECIAL:
2151 case LYX_ALIGN_DECIMAL:
2153 case LYX_ALIGN_LEFT:
2154 case LYX_ALIGN_RIGHT:
2155 case LYX_ALIGN_CENTER:
2156 if (runparams.moving_arg) {
2163 string const begin_tag = "\\begin";
2164 InsetCode code = ownerCode();
2165 bool const lastpar = runparams.isLastPar;
2168 case LYX_ALIGN_NONE:
2169 case LYX_ALIGN_BLOCK:
2170 case LYX_ALIGN_LAYOUT:
2171 case LYX_ALIGN_SPECIAL:
2172 case LYX_ALIGN_DECIMAL:
2174 case LYX_ALIGN_LEFT: {
2176 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2177 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2179 output = corrected_env(begin_tag, "flushright", code, lastpar);
2180 os << from_ascii(output);
2181 adjust_column(output, column);
2183 } case LYX_ALIGN_RIGHT: {
2185 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2186 output = corrected_env(begin_tag, "flushright", code, lastpar);
2188 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2189 os << from_ascii(output);
2190 adjust_column(output, column);
2192 } case LYX_ALIGN_CENTER: {
2194 output = corrected_env(begin_tag, "center", code, lastpar);
2195 os << from_ascii(output);
2196 adjust_column(output, column);
2205 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2206 otexstream & os, OutputParams const & runparams) const
2210 LyXAlignment const curAlign = params_.align();
2212 if (curAlign == layout_->align)
2216 case LYX_ALIGN_NONE:
2217 case LYX_ALIGN_BLOCK:
2218 case LYX_ALIGN_LAYOUT:
2219 case LYX_ALIGN_SPECIAL:
2220 case LYX_ALIGN_DECIMAL:
2222 case LYX_ALIGN_LEFT:
2223 case LYX_ALIGN_RIGHT:
2224 case LYX_ALIGN_CENTER:
2225 if (runparams.moving_arg) {
2232 string const end_tag = "\n\\par\\end";
2233 InsetCode code = ownerCode();
2234 bool const lastpar = runparams.isLastPar;
2237 case LYX_ALIGN_NONE:
2238 case LYX_ALIGN_BLOCK:
2239 case LYX_ALIGN_LAYOUT:
2240 case LYX_ALIGN_SPECIAL:
2241 case LYX_ALIGN_DECIMAL:
2243 case LYX_ALIGN_LEFT: {
2245 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2246 output = corrected_env(end_tag, "flushleft", code, lastpar);
2248 output = corrected_env(end_tag, "flushright", code, lastpar);
2249 os << from_ascii(output);
2250 adjust_column(output, column);
2252 } case LYX_ALIGN_RIGHT: {
2254 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2255 output = corrected_env(end_tag, "flushright", code, lastpar);
2257 output = corrected_env(end_tag, "flushleft", code, lastpar);
2258 os << from_ascii(output);
2259 adjust_column(output, column);
2261 } case LYX_ALIGN_CENTER: {
2263 output = corrected_env(end_tag, "center", code, lastpar);
2264 os << from_ascii(output);
2265 adjust_column(output, column);
2274 // This one spits out the text of the paragraph
2275 void Paragraph::latex(BufferParams const & bparams,
2276 Font const & outerfont,
2278 OutputParams const & runparams,
2279 int start_pos, int end_pos, bool force) const
2281 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2283 // FIXME This check should not be needed. Perhaps issue an
2284 // error if it triggers.
2285 Layout const & style = inInset().forcePlainLayout() ?
2286 bparams.documentClass().plainLayout() : *d->layout_;
2288 if (!force && style.inpreamble)
2291 bool const allowcust = allowParagraphCustomization();
2293 // Current base font for all inherited font changes, without any
2294 // change caused by an individual character, except for the language:
2295 // It is set to the language of the first character.
2296 // As long as we are in the label, this font is the base font of the
2297 // label. Before the first body character it is set to the base font
2301 // Maybe we have to create a optional argument.
2302 pos_type body_pos = beginOfBody();
2303 unsigned int column = 0;
2306 // the optional argument is kept in curly brackets in
2307 // case it contains a ']'
2310 basefont = getLabelFont(bparams, outerfont);
2312 basefont = getLayoutFont(bparams, outerfont);
2315 // Which font is currently active?
2316 Font running_font(basefont);
2317 // Do we have an open font change?
2318 bool open_font = false;
2320 Change runningChange = Change(Change::UNCHANGED);
2322 Encoding const * const prev_encoding = runparams.encoding;
2324 os.texrow().start(id(), 0);
2326 // if the paragraph is empty, the loop will not be entered at all
2328 if (style.isCommand()) {
2333 column += d->startTeXParParams(bparams, os, runparams);
2336 for (pos_type i = 0; i < size(); ++i) {
2337 // First char in paragraph or after label?
2338 if (i == body_pos) {
2341 column += running_font.latexWriteEndChanges(
2342 os, bparams, runparams,
2343 basefont, basefont);
2346 basefont = getLayoutFont(bparams, outerfont);
2347 running_font = basefont;
2349 column += Changes::latexMarkChange(os, bparams,
2350 runningChange, Change(Change::UNCHANGED),
2352 runningChange = Change(Change::UNCHANGED);
2357 if (style.isCommand()) {
2363 column += d->startTeXParParams(bparams, os,
2367 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2370 if (bparams.outputChanges && runningChange != change) {
2372 column += running_font.latexWriteEndChanges(
2373 os, bparams, runparams, basefont, basefont);
2376 basefont = getLayoutFont(bparams, outerfont);
2377 running_font = basefont;
2379 column += Changes::latexMarkChange(os, bparams, runningChange,
2381 runningChange = change;
2384 // do not output text which is marked deleted
2385 // if change tracking output is disabled
2386 if (!bparams.outputChanges && change.deleted()) {
2392 // Fully instantiated font
2393 Font const font = getFont(bparams, i, outerfont);
2395 Font const last_font = running_font;
2397 // Do we need to close the previous font?
2399 (font != running_font ||
2400 font.language() != running_font.language()))
2402 column += running_font.latexWriteEndChanges(
2403 os, bparams, runparams, basefont,
2404 (i == body_pos-1) ? basefont : font);
2405 running_font = basefont;
2409 string const running_lang = runparams.use_polyglossia ?
2410 running_font.language()->polyglossia() : running_font.language()->babel();
2411 // close babel's font environment before opening CJK.
2412 string const lang_end_command = runparams.use_polyglossia ?
2413 "\\end{$$lang}" : lyxrc.language_command_end;
2414 if (!running_lang.empty() &&
2415 font.language()->encoding()->package() == Encoding::CJK) {
2416 string end_tag = subst(lang_end_command,
2419 os << from_ascii(end_tag);
2420 column += end_tag.length();
2423 // Switch file encoding if necessary (and allowed)
2424 if (!runparams.pass_thru && !style.pass_thru &&
2425 runparams.encoding->package() != Encoding::none &&
2426 font.language()->encoding()->package() != Encoding::none) {
2427 pair<bool, int> const enc_switch =
2428 switchEncoding(os.os(), bparams, runparams,
2429 *(font.language()->encoding()));
2430 if (enc_switch.first) {
2431 column += enc_switch.second;
2432 runparams.encoding = font.language()->encoding();
2436 char_type const c = d->text_[i];
2438 // Do we need to change font?
2439 if ((font != running_font ||
2440 font.language() != running_font.language()) &&
2443 odocstringstream ods;
2444 column += font.latexWriteStartChanges(ods, bparams,
2445 runparams, basefont,
2447 running_font = font;
2449 docstring fontchange = ods.str();
2450 // check whether the fontchange ends with a \\textcolor
2451 // modifier and the text starts with a space (bug 4473)
2452 docstring const last_modifier = rsplit(fontchange, '\\');
2453 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2454 os << fontchange << from_ascii("{}");
2455 // check if the fontchange ends with a trailing blank
2456 // (like "\small " (see bug 3382)
2457 else if (suffixIs(fontchange, ' ') && c == ' ')
2458 os << fontchange.substr(0, fontchange.size() - 1)
2459 << from_ascii("{}");
2464 // FIXME: think about end_pos implementation...
2465 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2466 // FIXME: integrate this case in latexSpecialChar
2467 // Do not print the separation of the optional argument
2468 // if style.pass_thru is false. This works because
2469 // latexSpecialChar ignores spaces if
2470 // style.pass_thru is false.
2471 if (i != body_pos - 1) {
2472 if (d->simpleTeXBlanks(runparams, os,
2473 i, column, font, style)) {
2474 // A surrogate pair was output. We
2475 // must not call latexSpecialChar
2476 // in this iteration, since it would output
2477 // the combining character again.
2484 OutputParams rp = runparams;
2485 rp.free_spacing = style.free_spacing;
2486 rp.local_font = &font;
2487 rp.intitle = style.intitle;
2489 // Two major modes: LaTeX or plain
2490 // Handle here those cases common to both modes
2491 // and then split to handle the two modes separately.
2492 if (c == META_INSET) {
2493 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2494 d->latexInset(bparams, os, rp, running_font,
2495 basefont, outerfont, open_font,
2496 runningChange, style, i, column);
2499 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2501 d->latexSpecialChar(os, rp, running_font, runningChange,
2503 } catch (EncodingException & e) {
2504 if (runparams.dryrun) {
2505 os << "<" << _("LyX Warning: ")
2506 << _("uncodable character") << " '";
2510 // add location information and throw again.
2519 // Set the encoding to that returned from latexSpecialChar (see
2520 // comment for encoding member in OutputParams.h)
2521 runparams.encoding = rp.encoding;
2524 // If we have an open font definition, we have to close it
2526 #ifdef FIXED_LANGUAGE_END_DETECTION
2528 running_font.latexWriteEndChanges(os, bparams,
2529 runparams, basefont,
2530 next_->getFont(bparams, 0, outerfont));
2532 running_font.latexWriteEndChanges(os, bparams,
2533 runparams, basefont, basefont);
2536 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2537 //FIXME: there as we start another \selectlanguage with the next paragraph if
2538 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2539 running_font.latexWriteEndChanges(os, bparams, runparams,
2540 basefont, basefont);
2544 column += Changes::latexMarkChange(os, bparams, runningChange,
2545 Change(Change::UNCHANGED), runparams);
2547 // Needed if there is an optional argument but no contents.
2548 if (body_pos > 0 && body_pos == size()) {
2552 if (allowcust && d->endTeXParParams(bparams, os, runparams)
2553 && runparams.encoding != prev_encoding) {
2554 runparams.encoding = prev_encoding;
2555 if (!runparams.isFullUnicode())
2556 os << setEncoding(prev_encoding->iconvName());
2559 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2563 bool Paragraph::emptyTag() const
2565 for (pos_type i = 0; i < size(); ++i) {
2566 if (Inset const * inset = getInset(i)) {
2567 InsetCode lyx_code = inset->lyxCode();
2568 // FIXME testing like that is wrong. What is
2570 if (lyx_code != TOC_CODE &&
2571 lyx_code != INCLUDE_CODE &&
2572 lyx_code != GRAPHICS_CODE &&
2573 lyx_code != ERT_CODE &&
2574 lyx_code != LISTINGS_CODE &&
2575 lyx_code != FLOAT_CODE &&
2576 lyx_code != TABULAR_CODE) {
2580 char_type c = d->text_[i];
2581 if (c != ' ' && c != '\t')
2589 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2592 for (pos_type i = 0; i < size(); ++i) {
2593 if (Inset const * inset = getInset(i)) {
2594 InsetCode lyx_code = inset->lyxCode();
2595 if (lyx_code == LABEL_CODE) {
2596 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2597 docstring const & id = il->getParam("name");
2598 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2606 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2610 for (i = 0; i < size(); ++i) {
2611 if (Inset const * inset = getInset(i)) {
2612 inset->docbook(os, runparams);
2614 char_type c = d->text_[i];
2617 os << sgml::escapeChar(c);
2624 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2628 for (i = 0; i < size(); ++i) {
2629 if (Inset const * inset = getInset(i)) {
2630 inset->xhtml(xs, runparams);
2632 char_type c = d->text_[i];
2642 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2645 pos_type size = text_.size();
2646 for (pos_type i = initial; i < size; ++i) {
2647 Font font = owner_->getFont(buf.params(), i, outerfont);
2648 if (text_[i] == META_INSET)
2650 if (i != initial && font != font_old)
2659 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2661 OutputParams const & runparams,
2662 Font const & outerfont,
2663 pos_type initial) const
2665 bool emph_flag = false;
2667 Layout const & style = *d->layout_;
2669 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2671 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2674 // parsing main loop
2675 for (pos_type i = initial; i < size(); ++i) {
2676 Font font = getFont(buf.params(), i, outerfont);
2678 // handle <emphasis> tag
2679 if (font_old.emph() != font.fontInfo().emph()) {
2680 if (font.fontInfo().emph() == FONT_ON) {
2683 } else if (i != initial) {
2684 os << "</emphasis>";
2689 if (Inset const * inset = getInset(i)) {
2690 inset->docbook(os, runparams);
2692 char_type c = d->text_[i];
2694 if (style.pass_thru)
2697 os << sgml::escapeChar(c);
2699 font_old = font.fontInfo();
2703 os << "</emphasis>";
2706 if (style.free_spacing)
2708 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2713 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2715 OutputParams const & runparams,
2716 Font const & outerfont,
2717 pos_type initial) const
2721 bool emph_flag = false;
2722 bool bold_flag = false;
2725 Layout const & style = *d->layout_;
2727 if (!runparams.for_toc && runparams.html_make_pars) {
2728 // generate a magic label for this paragraph
2729 string const attr = "id='" + magicLabel() + "'";
2730 xs << html::CompTag("a", attr);
2734 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2736 // parsing main loop
2737 for (pos_type i = initial; i < size(); ++i) {
2738 // let's not show deleted material in the output
2742 Font font = getFont(buf.params(), i, outerfont);
2745 if (font_old.emph() != font.fontInfo().emph()) {
2746 if (font.fontInfo().emph() == FONT_ON) {
2747 xs << html::StartTag("em");
2749 } else if (emph_flag && i != initial) {
2750 xs << html::EndTag("em");
2755 if (font_old.series() != font.fontInfo().series()) {
2756 if (font.fontInfo().series() == BOLD_SERIES) {
2757 xs << html::StartTag("strong");
2759 } else if (bold_flag && i != initial) {
2760 xs << html::EndTag("strong");
2765 // Other such tags? What about the other text ranges?
2767 Inset const * inset = getInset(i);
2769 if (!runparams.for_toc || inset->isInToc()) {
2770 OutputParams np = runparams;
2771 if (!inset->getLayout().htmlisblock())
2772 np.html_in_par = true;
2773 retval += inset->xhtml(xs, np);
2776 char_type c = d->text_[i];
2778 if (style.pass_thru)
2780 else if (c == '-') {
2783 if (j < size() && d->text_[j] == '-') {
2785 if (j < size() && d->text_[j] == '-') {
2786 str += from_ascii("—");
2789 str += from_ascii("–");
2795 // We don't want to escape the entities. Note that
2796 // it is safe to do this, since str can otherwise
2797 // only be "-". E.g., it can't be "<".
2798 xs << XHTMLStream::ESCAPE_NONE << str;
2802 font_old = font.fontInfo();
2810 bool Paragraph::isHfill(pos_type pos) const
2812 Inset const * inset = getInset(pos);
2813 return inset && (inset->lyxCode() == SPACE_CODE &&
2814 inset->isStretchableSpace());
2818 bool Paragraph::isNewline(pos_type pos) const
2820 Inset const * inset = getInset(pos);
2821 return inset && inset->lyxCode() == NEWLINE_CODE;
2825 bool Paragraph::isLineSeparator(pos_type pos) const
2827 char_type const c = d->text_[pos];
2828 if (isLineSeparatorChar(c))
2830 Inset const * inset = getInset(pos);
2831 return inset && inset->isLineSeparator();
2835 bool Paragraph::isWordSeparator(pos_type pos) const
2837 if (Inset const * inset = getInset(pos))
2838 return !inset->isLetter();
2841 char_type const c = d->text_[pos];
2842 // We want to pass the ' and escape chars to the spellchecker
2843 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2844 return (!isLetterChar(c) && !isDigitASCII(c) && !contains(quote, c));
2848 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2851 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2855 bool Paragraph::isChar(pos_type pos) const
2857 if (Inset const * inset = getInset(pos))
2858 return inset->isChar();
2859 char_type const c = d->text_[pos];
2860 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2864 bool Paragraph::isSpace(pos_type pos) const
2866 if (Inset const * inset = getInset(pos))
2867 return inset->isSpace();
2868 char_type const c = d->text_[pos];
2869 return lyx::isSpace(c);
2874 Paragraph::getParLanguage(BufferParams const & bparams) const
2877 return getFirstFontSettings(bparams).language();
2878 // FIXME: we should check the prev par as well (Lgb)
2879 return bparams.language;
2883 bool Paragraph::isRTL(BufferParams const & bparams) const
2885 return lyxrc.rtl_support
2886 && getParLanguage(bparams)->rightToLeft()
2887 && !inInset().getLayout().forceLTR();
2891 void Paragraph::changeLanguage(BufferParams const & bparams,
2892 Language const * from, Language const * to)
2894 // change language including dummy font change at the end
2895 for (pos_type i = 0; i <= size(); ++i) {
2896 Font font = getFontSettings(bparams, i);
2897 if (font.language() == from) {
2898 font.setLanguage(to);
2902 d->requestSpellCheck(size());
2906 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2908 Language const * doc_language = bparams.language;
2909 FontList::const_iterator cit = d->fontlist_.begin();
2910 FontList::const_iterator end = d->fontlist_.end();
2912 for (; cit != end; ++cit)
2913 if (cit->font().language() != ignore_language &&
2914 cit->font().language() != latex_language &&
2915 cit->font().language() != doc_language)
2921 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2923 FontList::const_iterator cit = d->fontlist_.begin();
2924 FontList::const_iterator end = d->fontlist_.end();
2926 for (; cit != end; ++cit) {
2927 Language const * lang = cit->font().language();
2928 if (lang != ignore_language &&
2929 lang != latex_language)
2930 languages.insert(lang);
2935 docstring Paragraph::asString(int options) const
2937 return asString(0, size(), options);
2941 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2943 odocstringstream os;
2946 && options & AS_STR_LABEL
2947 && !d->params_.labelString().empty())
2948 os << d->params_.labelString() << ' ';
2950 for (pos_type i = beg; i < end; ++i) {
2951 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2953 char_type const c = d->text_[i];
2954 if (isPrintable(c) || c == '\t'
2955 || (c == '\n' && (options & AS_STR_NEWLINES)))
2957 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2958 getInset(i)->toString(os);
2959 if (getInset(i)->asInsetMath())
2968 void Paragraph::forToc(docstring & os, size_t maxlen) const
2970 if (!d->params_.labelString().empty())
2971 os += d->params_.labelString() + ' ';
2972 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
2975 char_type const c = d->text_[i];
2978 else if (c == '\t' || c == '\n')
2980 else if (c == META_INSET)
2981 getInset(i)->forToc(os, maxlen);
2986 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2988 odocstringstream os;
2991 && options & AS_STR_LABEL
2992 && !d->params_.labelString().empty())
2993 os << d->params_.labelString() << ' ';
2995 for (pos_type i = beg; i < end; ++i) {
2996 char_type const c = d->text_[i];
2997 if (isPrintable(c) || c == '\t'
2998 || (c == '\n' && (options & AS_STR_NEWLINES)))
3000 else if (c == META_INSET && (options & AS_STR_INSETS)) {
3001 getInset(i)->plaintext(os, runparams);
3009 void Paragraph::setInsetOwner(Inset const * inset)
3011 d->inset_owner_ = inset;
3015 int Paragraph::id() const
3021 void Paragraph::setId(int id)
3027 Layout const & Paragraph::layout() const
3033 void Paragraph::setLayout(Layout const & layout)
3035 d->layout_ = &layout;
3039 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3041 setLayout(tc.defaultLayout());
3045 void Paragraph::setPlainLayout(DocumentClass const & tc)
3047 setLayout(tc.plainLayout());
3051 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3053 if (usePlainLayout())
3054 setPlainLayout(tclass);
3056 setDefaultLayout(tclass);
3060 Inset const & Paragraph::inInset() const
3062 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3063 _("Memory problem"), _("Paragraph not properly initialized")));
3064 return *d->inset_owner_;
3068 ParagraphParameters & Paragraph::params()
3074 ParagraphParameters const & Paragraph::params() const
3080 bool Paragraph::isFreeSpacing() const
3082 if (d->layout_->free_spacing)
3084 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3088 bool Paragraph::allowEmpty() const
3090 if (d->layout_->keepempty)
3092 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3096 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3098 if (!Encodings::isArabicChar(c))
3101 char_type prev_char = ' ';
3102 char_type next_char = ' ';
3104 for (pos_type i = pos - 1; i >= 0; --i) {
3105 char_type const par_char = d->text_[i];
3106 if (!Encodings::isArabicComposeChar(par_char)) {
3107 prev_char = par_char;
3112 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3113 char_type const par_char = d->text_[i];
3114 if (!Encodings::isArabicComposeChar(par_char)) {
3115 next_char = par_char;
3120 if (Encodings::isArabicChar(next_char)) {
3121 if (Encodings::isArabicChar(prev_char) &&
3122 !Encodings::isArabicSpecialChar(prev_char))
3123 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3125 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3127 if (Encodings::isArabicChar(prev_char) &&
3128 !Encodings::isArabicSpecialChar(prev_char))
3129 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3131 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3136 int Paragraph::checkBiblio(Buffer const & buffer)
3139 // This is getting more and more a mess. ...We really should clean
3140 // up this bibitem issue for 1.6.
3142 // Add bibitem insets if necessary
3143 if (d->layout_->labeltype != LABEL_BIBLIO)
3146 bool hasbibitem = !d->insetlist_.empty()
3147 // Insist on it being in pos 0
3148 && d->text_[0] == META_INSET
3149 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3151 bool track_changes = buffer.params().trackChanges;
3156 // remove a bibitem in pos != 0
3157 // restore it later in pos 0 if necessary
3158 // (e.g. if a user inserts contents _before_ the item)
3159 // we're assuming there's only one of these, which there
3161 int erasedInsetPosition = -1;
3162 InsetList::iterator it = d->insetlist_.begin();
3163 InsetList::iterator end = d->insetlist_.end();
3164 for (; it != end; ++it)
3165 if (it->inset->lyxCode() == BIBITEM_CODE
3167 InsetCommand * olditem = it->inset->asInsetCommand();
3168 oldkey = olditem->getParam("key");
3169 oldlabel = olditem->getParam("label");
3170 erasedInsetPosition = it->pos;
3171 eraseChar(erasedInsetPosition, track_changes);
3175 // There was an InsetBibitem at the beginning, and we didn't
3176 // have to erase one.
3177 if (hasbibitem && erasedInsetPosition < 0)
3180 // There was an InsetBibitem at the beginning and we did have to
3181 // erase one. So we give its properties to the beginning inset.
3183 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3184 if (!oldkey.empty())
3185 inset->setParam("key", oldkey);
3186 inset->setParam("label", oldlabel);
3187 return -erasedInsetPosition;
3190 // There was no inset at the beginning, so we need to create one with
3191 // the key and label of the one we erased.
3192 InsetBibitem * inset =
3193 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3194 // restore values of previously deleted item in this par.
3195 if (!oldkey.empty())
3196 inset->setParam("key", oldkey);
3197 inset->setParam("label", oldlabel);
3198 insertInset(0, inset,
3199 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3205 void Paragraph::checkAuthors(AuthorList const & authorList)
3207 d->changes_.checkAuthors(authorList);
3211 bool Paragraph::isChanged(pos_type pos) const
3213 return lookupChange(pos).changed();
3217 bool Paragraph::isInserted(pos_type pos) const
3219 return lookupChange(pos).inserted();
3223 bool Paragraph::isDeleted(pos_type pos) const
3225 return lookupChange(pos).deleted();
3229 InsetList const & Paragraph::insetList() const
3231 return d->insetlist_;
3235 void Paragraph::setBuffer(Buffer & b)
3237 d->insetlist_.setBuffer(b);
3241 Inset * Paragraph::releaseInset(pos_type pos)
3243 Inset * inset = d->insetlist_.release(pos);
3244 /// does not honour change tracking!
3245 eraseChar(pos, false);
3250 Inset * Paragraph::getInset(pos_type pos)
3252 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3253 ? d->insetlist_.get(pos) : 0;
3257 Inset const * Paragraph::getInset(pos_type pos) const
3259 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3260 ? d->insetlist_.get(pos) : 0;
3264 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3265 pos_type & right, TextCase action)
3267 // process sequences of modified characters; in change
3268 // tracking mode, this approach results in much better
3269 // usability than changing case on a char-by-char basis
3272 bool const trackChanges = bparams.trackChanges;
3274 bool capitalize = true;
3276 for (; pos < right; ++pos) {
3277 char_type oldChar = d->text_[pos];
3278 char_type newChar = oldChar;
3280 // ignore insets and don't play with deleted text!
3281 if (oldChar != META_INSET && !isDeleted(pos)) {
3283 case text_lowercase:
3284 newChar = lowercase(oldChar);
3286 case text_capitalization:
3288 newChar = uppercase(oldChar);
3292 case text_uppercase:
3293 newChar = uppercase(oldChar);
3298 if (isWordSeparator(pos) || isDeleted(pos)) {
3299 // permit capitalization again
3303 if (oldChar != newChar) {
3305 if (pos != right - 1)
3307 // step behind the changing area
3311 int erasePos = pos - changes.size();
3312 for (size_t i = 0; i < changes.size(); i++) {
3313 insertChar(pos, changes[i],
3314 getFontSettings(bparams,
3317 if (!eraseChar(erasePos, trackChanges)) {
3320 ++right; // expand selection
3328 int Paragraph::find(docstring const & str, bool cs, bool mw,
3329 pos_type start_pos, bool del) const
3331 pos_type pos = start_pos;
3332 int const strsize = str.length();
3334 pos_type const parsize = d->text_.size();
3335 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3336 // Ignore ligature break and hyphenation chars while searching
3337 while (pos < parsize - 1 && isInset(pos)) {
3338 const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3340 || (isc->kind() != InsetSpecialChar::HYPHENATION
3341 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3345 if (cs && str[i] != d->text_[pos])
3347 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3349 if (!del && isDeleted(pos))
3356 // if necessary, check whether string matches word
3358 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3361 && !isWordSeparator(pos))
3365 return pos - start_pos;
3369 char_type Paragraph::getChar(pos_type pos) const
3371 return d->text_[pos];
3375 pos_type Paragraph::size() const
3377 return d->text_.size();
3381 bool Paragraph::empty() const
3383 return d->text_.empty();
3387 bool Paragraph::isInset(pos_type pos) const
3389 return d->text_[pos] == META_INSET;
3393 bool Paragraph::isSeparator(pos_type pos) const
3395 //FIXME: Are we sure this can be the only separator?
3396 return d->text_[pos] == ' ';
3400 void Paragraph::deregisterWords()
3402 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3403 Private::LangWordsMap::const_iterator ite = d->words_.end();
3404 for (; itl != ite; ++itl) {
3405 WordList * wl = theWordList(itl->first);
3406 Private::Words::const_iterator it = (itl->second).begin();
3407 Private::Words::const_iterator et = (itl->second).end();
3408 for (; it != et; ++it)
3415 void Paragraph::locateWord(pos_type & from, pos_type & to,
3416 word_location const loc) const
3419 case WHOLE_WORD_STRICT:
3420 if (from == 0 || from == size()
3421 || isWordSeparator(from)
3422 || isWordSeparator(from - 1)) {
3426 // no break here, we go to the next
3429 // If we are already at the beginning of a word, do nothing
3430 if (!from || isWordSeparator(from - 1))
3432 // no break here, we go to the next
3435 // always move the cursor to the beginning of previous word
3436 while (from && !isWordSeparator(from - 1))
3440 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3443 // no need to move the 'from' cursor
3447 while (to < size() && !isWordSeparator(to))
3452 void Paragraph::collectWords()
3454 // This is the value that needs to be exposed in the preferences
3455 // to resolve bug #6760.
3456 static int minlength = 6;
3457 pos_type n = size();
3458 for (pos_type pos = 0; pos < n; ++pos) {
3459 if (isWordSeparator(pos))
3461 pos_type from = pos;
3462 locateWord(from, pos, WHOLE_WORD);
3463 if (pos - from >= minlength) {
3464 docstring word = asString(from, pos, AS_STR_NONE);
3465 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3466 if (cit == d->fontlist_.end())
3468 Language const * lang = cit->font().language();
3469 d->words_[*lang].insert(word);
3475 void Paragraph::registerWords()
3477 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3478 Private::LangWordsMap::const_iterator ite = d->words_.end();
3479 for (; itl != ite; ++itl) {
3480 WordList * wl = theWordList(itl->first);
3481 Private::Words::const_iterator it = (itl->second).begin();
3482 Private::Words::const_iterator et = (itl->second).end();
3483 for (; it != et; ++it)
3489 void Paragraph::updateWords()
3497 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3499 SkipPositionsIterator begin = skips.begin();
3500 SkipPositions::iterator end = skips.end();
3501 if (pos > 0 && begin < end) {
3503 if (end->last == pos - 1) {
3508 skips.insert(end, FontSpan(pos, pos));
3512 Language * Paragraph::Private::locateSpellRange(
3513 pos_type & from, pos_type & to,
3514 SkipPositions & skips) const
3516 // skip leading white space
3517 while (from < to && owner_->isWordSeparator(from))
3519 // don't check empty range
3522 // get current language
3523 Language * lang = getSpellLanguage(from);
3524 pos_type last = from;
3525 bool samelang = true;
3526 bool sameinset = true;
3527 while (last < to && samelang && sameinset) {
3528 // hop to end of word
3529 while (last < to && !owner_->isWordSeparator(last)) {
3530 if (owner_->getInset(last)) {
3531 appendSkipPosition(skips, last);
3532 } else if (owner_->isDeleted(last)) {
3533 appendSkipPosition(skips, last);
3537 // hop to next word while checking for insets
3538 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3539 if (Inset const * inset = owner_->getInset(last))
3540 sameinset = inset->isChar() && inset->isLetter();
3541 if (sameinset && owner_->isDeleted(last)) {
3542 appendSkipPosition(skips, last);
3547 if (sameinset && last < to) {
3548 // now check for language change
3549 samelang = lang == getSpellLanguage(last);
3552 // if language change detected backstep is needed
3560 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3563 const_cast<Language *>(owner_->getFontSettings(
3564 inset_owner_->buffer().params(), from).language());
3565 if (lang == inset_owner_->buffer().params().language
3566 && !lyxrc.spellchecker_alt_lang.empty()) {
3568 string const lang_variety =
3569 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3570 lang->setCode(lang_code);
3571 lang->setVariety(lang_variety);
3577 void Paragraph::requestSpellCheck(pos_type pos)
3579 d->requestSpellCheck(pos == -1 ? size() : pos);
3583 bool Paragraph::needsSpellCheck() const
3585 SpellChecker::ChangeNumber speller_change_number = 0;
3586 if (theSpellChecker())
3587 speller_change_number = theSpellChecker()->changeNumber();
3588 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3589 d->speller_state_.needsCompleteRefresh(speller_change_number);
3591 return d->needsSpellCheck();
3595 bool Paragraph::Private::ignoreWord(docstring const & word) const
3597 // Ignore words with digits
3598 // FIXME: make this customizable
3599 // (note that some checkers ignore words with digits by default)
3600 docstring::const_iterator cit = word.begin();
3601 docstring::const_iterator const end = word.end();
3602 for (; cit != end; ++cit) {
3603 if (isNumber((*cit)))
3610 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3611 WordLangTuple & wl, docstring_list & suggestions,
3612 bool do_suggestion, bool check_learned) const
3614 SpellChecker::Result result = SpellChecker::WORD_OK;
3615 SpellChecker * speller = theSpellChecker();
3619 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3622 locateWord(from, to, WHOLE_WORD);
3623 if (from == to || from >= size())
3626 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3627 Language * lang = d->getSpellLanguage(from);
3629 wl = WordLangTuple(word, lang);
3634 if (needsSpellCheck() || check_learned) {
3635 if (!d->ignoreWord(word)) {
3636 bool const trailing_dot = to < size() && d->text_[to] == '.';
3637 result = speller->check(wl);
3638 if (SpellChecker::misspelled(result) && trailing_dot) {
3639 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3640 result = speller->check(wl);
3641 if (!SpellChecker::misspelled(result)) {
3642 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3644 from << ".." << to << "]");
3646 // spell check with dot appended failed
3647 // restore original word/lang value
3648 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3649 wl = WordLangTuple(word, lang);
3653 d->setMisspelled(from, to, result);
3655 result = d->speller_state_.getState(from);
3658 bool const misspelled_ = SpellChecker::misspelled(result) ;
3659 if (misspelled_ && do_suggestion)
3660 speller->suggest(wl, suggestions);
3661 else if (misspelled_)
3662 LYXERR(Debug::GUI, "misspelled word: \"" <<
3664 from << ".." << to << "]");
3666 suggestions.clear();
3672 void Paragraph::Private::markMisspelledWords(
3673 pos_type const & first, pos_type const & last,
3674 SpellChecker::Result result,
3675 docstring const & word,
3676 SkipPositions const & skips)
3678 if (!SpellChecker::misspelled(result)) {
3679 setMisspelled(first, last, SpellChecker::WORD_OK);
3683 SpellChecker * speller = theSpellChecker();
3684 // locate and enumerate the error positions
3685 int nerrors = speller->numMisspelledWords();
3687 SkipPositionsIterator it = skips.begin();
3688 SkipPositionsIterator et = skips.end();
3689 for (int index = 0; index < nerrors; ++index) {
3692 speller->misspelledWord(index, wstart, wlen);
3693 /// should not happen if speller supports range checks
3694 if (!wlen) continue;
3695 docstring const misspelled = word.substr(wstart, wlen);
3696 wstart += first + numskipped;
3697 if (snext < wstart) {
3698 /// mark the range of correct spelling
3699 numskipped += countSkips(it, et, wstart);
3700 setMisspelled(snext,
3701 wstart - 1, SpellChecker::WORD_OK);
3703 snext = wstart + wlen;
3704 numskipped += countSkips(it, et, snext);
3705 /// mark the range of misspelling
3706 setMisspelled(wstart, snext, result);
3707 LYXERR(Debug::GUI, "misspelled word: \"" <<
3708 misspelled << "\" [" <<
3709 wstart << ".." << (snext-1) << "]");
3712 if (snext <= last) {
3713 /// mark the range of correct spelling at end
3714 setMisspelled(snext, last, SpellChecker::WORD_OK);
3719 void Paragraph::spellCheck() const
3721 SpellChecker * speller = theSpellChecker();
3722 if (!speller || !size() ||!needsSpellCheck())
3726 d->rangeOfSpellCheck(start, endpos);
3727 if (speller->canCheckParagraph()) {
3728 // loop until we leave the range
3729 for (pos_type first = start; first < endpos; ) {
3730 pos_type last = endpos;
3731 Private::SkipPositions skips;
3732 Language * lang = d->locateSpellRange(first, last, skips);
3733 if (first >= endpos)
3735 // start the spell checker on the unit of meaning
3736 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3737 WordLangTuple wl = WordLangTuple(word, lang);
3738 SpellChecker::Result result = word.size() ?
3739 speller->check(wl) : SpellChecker::WORD_OK;
3740 d->markMisspelledWords(first, last, result, word, skips);
3744 static docstring_list suggestions;
3745 pos_type to = endpos;
3746 while (start < endpos) {
3748 spellCheck(start, to, wl, suggestions, false);
3752 d->readySpellCheck();
3756 bool Paragraph::isMisspelled(pos_type pos, bool check_boundary) const
3758 bool result = SpellChecker::misspelled(d->speller_state_.getState(pos));
3759 if (result || pos <= 0 || pos >= size())
3761 if (check_boundary && isWordSeparator(pos))
3762 result = SpellChecker::misspelled(d->speller_state_.getState(pos - 1));
3767 string Paragraph::magicLabel() const
3770 ss << "magicparlabel-" << id();