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)
140 eraseCoveredRanges(fp);
141 if (state != SpellChecker::WORD_OK)
142 ranges_.push_back(SpellResultRange(fp, state));
145 void increasePosAfterPos(pos_type pos)
147 correctRangesAfterPos(pos, 1);
151 void decreasePosAfterPos(pos_type pos)
153 correctRangesAfterPos(pos, -1);
157 void refreshLast(pos_type pos)
159 if (pos < refresh_.last)
163 SpellChecker::Result getState(pos_type pos) const
165 SpellChecker::Result result = SpellChecker::WORD_OK;
166 RangesIterator et = ranges_.end();
167 RangesIterator it = ranges_.begin();
168 for (; it != et; ++it) {
169 if(it->inside(pos)) {
176 FontSpan const & getRange(pos_type pos) const
178 /// empty span to indicate mismatch
179 static FontSpan empty_;
180 RangesIterator et = ranges_.end();
181 RangesIterator it = ranges_.begin();
182 for (; it != et; ++it) {
183 if(it->inside(pos)) {
190 bool needsRefresh() const {
191 return needs_refresh_;
194 SpellChecker::ChangeNumber currentChangeNumber() const {
195 return current_change_number_;
198 void refreshRange(pos_type & first, pos_type & last) const {
199 first = refresh_.first;
200 last = refresh_.last;
203 void needsRefresh(pos_type pos) {
204 if (needs_refresh_ && pos != -1) {
205 if (pos < refresh_.first)
206 refresh_.first = pos;
207 if (pos > refresh_.last)
209 } else if (pos != -1) {
210 refresh_.first = pos;
213 needs_refresh_ = pos != -1;
216 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
217 needs_refresh_ = true;
220 current_change_number_ = change_number;
224 typedef vector<SpellResultRange> Ranges;
225 typedef Ranges::const_iterator RangesIterator;
227 /// the area of the paragraph with pending spell check
230 /// spell state cache version number
231 SpellChecker::ChangeNumber current_change_number_;
234 void eraseCoveredRanges(FontSpan const fp)
237 RangesIterator et = ranges_.end();
238 RangesIterator it = ranges_.begin();
239 for (; it != et; ++it) {
240 if (!it->covered(fp))
241 result.push_back(SpellResultRange(it->range(), it->result()));
246 void correctRangesAfterPos(pos_type pos, int offset)
248 RangesIterator et = ranges_.end();
249 Ranges::iterator it = ranges_.begin();
250 for (; it != et; ++it) {
251 it->shift(pos, offset);
257 /////////////////////////////////////////////////////////////////////
259 // Paragraph::Private
261 /////////////////////////////////////////////////////////////////////
263 class Paragraph::Private
267 Private(Paragraph * owner, Layout const & layout);
268 /// "Copy constructor"
269 Private(Private const &, Paragraph * owner);
270 /// Copy constructor from \p beg to \p end
271 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
274 void insertChar(pos_type pos, char_type c, Change const & change);
276 /// Output the surrogate pair formed by \p c and \p next to \p os.
277 /// \return the number of characters written.
278 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
279 OutputParams const &);
281 /// Output a space in appropriate formatting (or a surrogate pair
282 /// if the next character is a combining character).
283 /// \return whether a surrogate pair was output.
284 bool simpleTeXBlanks(OutputParams const &,
285 odocstream &, TexRow & texrow,
287 unsigned int & column,
289 Layout const & style);
291 /// Output consecutive unicode chars, belonging to the same script as
292 /// specified by the latex macro \p ltx, to \p os starting from \p i.
293 /// \return the number of characters written.
294 int writeScriptChars(odocstream & os, docstring const & ltx,
295 Change const &, Encoding const &, pos_type & i);
297 /// This could go to ParagraphParameters if we want to.
298 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
299 OutputParams const &) const;
301 /// This could go to ParagraphParameters if we want to.
302 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
303 OutputParams const &) const;
306 void latexInset(BufferParams const &,
308 TexRow & texrow, OutputParams &,
311 Font const & outerfont,
313 Change & running_change,
314 Layout const & style,
316 unsigned int & column);
319 void latexSpecialChar(
321 OutputParams const & runparams,
322 Font const & running_font,
323 Change const & running_change,
324 Layout const & style,
326 unsigned int & column);
333 unsigned int & column);
335 bool latexSpecialTypewriter(
339 unsigned int & column);
341 bool latexSpecialPhrase(
344 unsigned int & column,
345 OutputParams const & runparams);
348 void validate(LaTeXFeatures & features) const;
350 /// Checks if the paragraph contains only text and no inset or font change.
351 bool onlyText(Buffer const & buf, Font const & outerfont,
352 pos_type initial) const;
354 /// match a string against a particular point in the paragraph
355 bool isTextAt(string const & str, pos_type pos) const;
357 /// a vector of speller skip positions
358 typedef vector<FontSpan> SkipPositions;
359 typedef SkipPositions::const_iterator SkipPositionsIterator;
361 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
363 Language * getSpellLanguage(pos_type const from) const;
365 Language * locateSpellRange(pos_type & from, pos_type & to,
366 SkipPositions & skips) const;
368 bool hasSpellerChange() const {
369 SpellChecker::ChangeNumber speller_change_number = 0;
370 if (theSpellChecker())
371 speller_change_number = theSpellChecker()->changeNumber();
372 return speller_change_number > speller_state_.currentChangeNumber();
375 bool ignoreWord(docstring const & word) const ;
377 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
379 pos_type textsize = owner_->size();
380 // check for sane arguments
381 if (to < from || from >= textsize)
383 FontSpan fp = FontSpan(from, to);
384 // don't mark end of paragraph
385 if (fp.last >= textsize)
386 fp.last = textsize - 1;
387 speller_state_.setRange(fp, state);
390 void requestSpellCheck(pos_type pos) {
391 speller_state_.needsRefresh(pos);
394 void readySpellCheck() {
395 speller_state_.needsRefresh(-1);
398 bool needsSpellCheck() const
400 return speller_state_.needsRefresh();
403 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
405 speller_state_.refreshRange(first, last);
407 last = owner_->size();
410 pos_type endpos = last;
411 owner_->locateWord(first, endpos, WHOLE_WORD);
414 owner_->locateWord(last, endpos, WHOLE_WORD);
419 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
423 while (it != et && it->first < start) {
424 int skip = it->last - it->first + 1;
432 void markMisspelledWords(pos_type const & first, pos_type const & last,
433 SpellChecker::Result result,
434 docstring const & word,
435 SkipPositions const & skips);
437 InsetCode ownerCode() const
439 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
442 /// Which Paragraph owns us?
446 Inset const * inset_owner_;
455 ParagraphParameters params_;
457 /// for recording and looking up changes
461 InsetList insetlist_;
464 pos_type begin_of_body_;
466 typedef docstring TextContainer;
470 typedef set<docstring> Words;
471 typedef map<Language, Words> LangWordsMap;
475 Layout const * layout_;
477 SpellCheckerState speller_state_;
483 struct special_phrase {
489 special_phrase const special_phrases[] = {
490 { "LyX", from_ascii("\\LyX{}"), false },
491 { "TeX", from_ascii("\\TeX{}"), true },
492 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
493 { "LaTeX", from_ascii("\\LaTeX{}"), true },
496 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
501 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
502 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
508 // Initialization of the counter for the paragraph id's,
510 // FIXME: There should be a more intelligent way to generate and use the
511 // paragraph ids per buffer instead a global static counter for all InsetText
512 // in the running program.
513 static int paragraph_id = -1;
515 Paragraph::Private::Private(Private const & p, Paragraph * owner)
516 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
517 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
518 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
521 id_ = ++paragraph_id;
522 requestSpellCheck(p.text_.size());
526 Paragraph::Private::Private(Private const & p, Paragraph * owner,
527 pos_type beg, pos_type end)
528 : owner_(owner), inset_owner_(p.inset_owner_),
529 params_(p.params_), changes_(p.changes_),
530 insetlist_(p.insetlist_, beg, end),
531 begin_of_body_(p.begin_of_body_), words_(p.words_),
534 id_ = ++paragraph_id;
535 if (beg >= pos_type(p.text_.size()))
537 text_ = p.text_.substr(beg, end - beg);
539 FontList::const_iterator fcit = fontlist_.begin();
540 FontList::const_iterator fend = fontlist_.end();
541 for (; fcit != fend; ++fcit) {
542 if (fcit->pos() < beg)
544 if (fcit->pos() >= end) {
545 // Add last entry in the fontlist_.
546 fontlist_.set(text_.size() - 1, fcit->font());
549 // Add a new entry in the fontlist_.
550 fontlist_.set(fcit->pos() - beg, fcit->font());
552 requestSpellCheck(p.text_.size());
556 void Paragraph::addChangesToToc(DocIterator const & cdit,
557 Buffer const & buf) const
559 d->changes_.addToToc(cdit, buf);
563 bool Paragraph::isDeleted(pos_type start, pos_type end) const
565 LASSERT(start >= 0 && start <= size(), /**/);
566 LASSERT(end > start && end <= size() + 1, /**/);
568 return d->changes_.isDeleted(start, end);
572 bool Paragraph::isChanged(pos_type start, pos_type end) const
574 LASSERT(start >= 0 && start <= size(), /**/);
575 LASSERT(end > start && end <= size() + 1, /**/);
577 return d->changes_.isChanged(start, end);
581 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
583 // keep the logic here in sync with the logic of eraseChars()
587 Change const change = d->changes_.lookup(size());
588 return change.inserted() && change.currentAuthor();
592 void Paragraph::setChange(Change const & change)
594 // beware of the imaginary end-of-par character!
595 d->changes_.set(change, 0, size() + 1);
598 * Propagate the change recursively - but not in case of DELETED!
600 * Imagine that your co-author makes changes in an existing inset. He
601 * sends your document to you and you come to the conclusion that the
602 * inset should go completely. If you erase it, LyX must not delete all
603 * text within the inset. Otherwise, the change tracked insertions of
604 * your co-author get lost and there is no way to restore them later.
606 * Conclusion: An inset's content should remain untouched if you delete it
609 if (!change.deleted()) {
610 for (pos_type pos = 0; pos < size(); ++pos) {
611 if (Inset * inset = getInset(pos))
612 inset->setChange(change);
618 void Paragraph::setChange(pos_type pos, Change const & change)
620 LASSERT(pos >= 0 && pos <= size(), /**/);
621 d->changes_.set(change, pos);
623 // see comment in setChange(Change const &) above
624 if (!change.deleted() && pos < size())
625 if (Inset * inset = getInset(pos))
626 inset->setChange(change);
630 Change const & Paragraph::lookupChange(pos_type pos) const
632 LASSERT(pos >= 0 && pos <= size(), /**/);
633 return d->changes_.lookup(pos);
637 void Paragraph::acceptChanges(pos_type start, pos_type end)
639 LASSERT(start >= 0 && start <= size(), /**/);
640 LASSERT(end > start && end <= size() + 1, /**/);
642 for (pos_type pos = start; pos < end; ++pos) {
643 switch (lookupChange(pos).type) {
644 case Change::UNCHANGED:
645 // accept changes in nested inset
646 if (Inset * inset = getInset(pos))
647 inset->acceptChanges();
650 case Change::INSERTED:
651 d->changes_.set(Change(Change::UNCHANGED), pos);
652 // also accept changes in nested inset
653 if (Inset * inset = getInset(pos))
654 inset->acceptChanges();
657 case Change::DELETED:
658 // Suppress access to non-existent
659 // "end-of-paragraph char"
661 eraseChar(pos, false);
672 void Paragraph::rejectChanges(pos_type start, pos_type end)
674 LASSERT(start >= 0 && start <= size(), /**/);
675 LASSERT(end > start && end <= size() + 1, /**/);
677 for (pos_type pos = start; pos < end; ++pos) {
678 switch (lookupChange(pos).type) {
679 case Change::UNCHANGED:
680 // reject changes in nested inset
681 if (Inset * inset = getInset(pos))
682 inset->rejectChanges();
685 case Change::INSERTED:
686 // Suppress access to non-existent
687 // "end-of-paragraph char"
689 eraseChar(pos, false);
695 case Change::DELETED:
696 d->changes_.set(Change(Change::UNCHANGED), pos);
698 // Do NOT reject changes within a deleted inset!
699 // There may be insertions of a co-author inside of it!
707 void Paragraph::Private::insertChar(pos_type pos, char_type c,
708 Change const & change)
710 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
713 changes_.insert(change, pos);
715 // This is actually very common when parsing buffers (and
716 // maybe inserting ascii text)
717 if (pos == pos_type(text_.size())) {
718 // when appending characters, no need to update tables
720 // but we want spell checking
721 requestSpellCheck(pos);
725 text_.insert(text_.begin() + pos, c);
727 // Update the font table.
728 fontlist_.increasePosAfterPos(pos);
731 insetlist_.increasePosAfterPos(pos);
733 // Update list of misspelled positions
734 speller_state_.increasePosAfterPos(pos);
738 bool Paragraph::insertInset(pos_type pos, Inset * inset,
739 Change const & change)
741 LASSERT(inset, /**/);
742 LASSERT(pos >= 0 && pos <= size(), /**/);
744 // Paragraph::insertInset() can be used in cut/copy/paste operation where
745 // d->inset_owner_ is not set yet.
746 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
749 d->insertChar(pos, META_INSET, change);
750 LASSERT(d->text_[pos] == META_INSET, /**/);
752 // Add a new entry in the insetlist_.
753 d->insetlist_.insert(inset, pos);
755 // Some insets require run of spell checker
756 requestSpellCheck(pos);
761 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
763 LASSERT(pos >= 0 && pos <= size(), return false);
765 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
768 Change change = d->changes_.lookup(pos);
770 // set the character to DELETED if
771 // a) it was previously unchanged or
772 // b) it was inserted by a co-author
774 if (!change.changed() ||
775 (change.inserted() && !change.currentAuthor())) {
776 setChange(pos, Change(Change::DELETED));
777 // request run of spell checker
778 requestSpellCheck(pos);
782 if (change.deleted())
786 // Don't physically access the imaginary end-of-paragraph character.
787 // eraseChar() can only mark it as DELETED. A physical deletion of
788 // end-of-par must be handled externally.
794 d->changes_.erase(pos);
796 // if it is an inset, delete the inset entry
797 if (d->text_[pos] == META_INSET)
798 d->insetlist_.erase(pos);
800 d->text_.erase(d->text_.begin() + pos);
802 // Update the fontlist_
803 d->fontlist_.erase(pos);
805 // Update the insetlist_
806 d->insetlist_.decreasePosAfterPos(pos);
808 // Update list of misspelled positions
809 d->speller_state_.decreasePosAfterPos(pos);
810 d->speller_state_.refreshLast(size());
816 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
818 LASSERT(start >= 0 && start <= size(), /**/);
819 LASSERT(end >= start && end <= size() + 1, /**/);
822 for (pos_type count = end - start; count; --count) {
823 if (!eraseChar(i, trackChanges))
830 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
831 char_type next, OutputParams const & runparams)
833 // Writing next here may circumvent a possible font change between
834 // c and next. Since next is only output if it forms a surrogate pair
835 // with c we can ignore this:
836 // A font change inside a surrogate pair does not make sense and is
837 // hopefully impossible to input.
838 // FIXME: change tracking
839 // Is this correct WRT change tracking?
840 Encoding const & encoding = *(runparams.encoding);
841 docstring const latex1 = encoding.latexChar(next);
842 docstring const latex2 = encoding.latexChar(c);
843 if (docstring(1, next) == latex1) {
844 // the encoding supports the combination
845 os << latex2 << latex1;
846 return latex1.length() + latex2.length();
847 } else if (runparams.local_font &&
848 runparams.local_font->language()->lang() == "polutonikogreek") {
849 // polutonikogreek only works without the brackets
850 os << latex1 << latex2;
851 return latex1.length() + latex2.length();
853 os << latex1 << '{' << latex2 << '}';
854 return latex1.length() + latex2.length() + 2;
858 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
859 odocstream & os, TexRow & texrow,
861 unsigned int & column,
863 Layout const & style)
865 if (style.pass_thru || runparams.pass_thru)
868 if (i + 1 < int(text_.size())) {
869 char_type next = text_[i + 1];
870 if (Encodings::isCombiningChar(next)) {
871 // This space has an accent, so we must always output it.
872 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
877 if (runparams.linelen > 0
878 && column > runparams.linelen
880 && text_[i - 1] != ' '
881 && (i + 1 < int(text_.size()))
882 // same in FreeSpacing mode
883 && !owner_->isFreeSpacing()
884 // In typewriter mode, we want to avoid
885 // ! . ? : at the end of a line
886 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
887 && (text_[i - 1] == '.'
888 || text_[i - 1] == '?'
889 || text_[i - 1] == ':'
890 || text_[i - 1] == '!'))) {
893 texrow.start(owner_->id(), i + 1);
895 } else if (style.free_spacing) {
904 int Paragraph::Private::writeScriptChars(odocstream & os,
905 docstring const & ltx,
906 Change const & runningChange,
907 Encoding const & encoding,
910 // FIXME: modifying i here is not very nice...
912 // We only arrive here when a proper language for character text_[i] has
913 // not been specified (i.e., it could not be translated in the current
914 // latex encoding) or its latex translation has been forced, and it
915 // belongs to a known script.
916 // Parameter ltx contains the latex translation of text_[i] as specified
917 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
918 // The latex macro name "textXXX" specifies the script to which text_[i]
919 // belongs and we use it in order to check whether characters from the
920 // same script immediately follow, such that we can collect them in a
921 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
922 // for the first char but only "<spec>" for all subsequent chars.
923 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
924 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
925 string script = to_ascii(ltx.substr(1, brace1 - 1));
928 bool closing_brace = true;
929 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
930 // Correct encoding is being used, so we can avoid \textgreek.
933 closing_brace = false;
935 os << ltx.substr(pos, length);
936 int size = text_.size();
937 while (i + 1 < size) {
938 char_type const next = text_[i + 1];
939 // Stop here if next character belongs to another script
940 // or there is a change in change tracking status.
941 if (!Encodings::isKnownScriptChar(next, script) ||
942 runningChange != owner_->lookupChange(i + 1))
946 FontList::const_iterator cit = fontlist_.begin();
947 FontList::const_iterator end = fontlist_.end();
948 for (; cit != end; ++cit) {
949 if (cit->pos() >= i && !found) {
950 prev_font = cit->font();
953 if (cit->pos() >= i + 1)
956 // Stop here if there is a font attribute or encoding change.
957 if (found && cit != end && prev_font != cit->font())
959 docstring const latex = encoding.latexChar(next);
960 docstring::size_type const b1 =
961 latex.find_first_of(from_ascii("{"));
962 docstring::size_type const b2 =
963 latex.find_last_of(from_ascii("}"));
964 int const len = b2 - b1 - 1;
965 os << latex.substr(b1 + 1, len);
977 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
979 pos_type const len = str.length();
981 // is the paragraph large enough?
982 if (pos + len > int(text_.size()))
985 // does the wanted text start at point?
986 for (string::size_type i = 0; i < str.length(); ++i) {
987 // Caution: direct comparison of characters works only
988 // because str is pure ASCII.
989 if (str[i] != text_[pos + i])
993 return fontlist_.hasChangeInRange(pos, len);
997 void Paragraph::Private::latexInset(BufferParams const & bparams,
1000 OutputParams & runparams,
1001 Font & running_font,
1003 Font const & outerfont,
1005 Change & running_change,
1006 Layout const & style,
1008 unsigned int & column)
1010 Inset * inset = owner_->getInset(i);
1011 LASSERT(inset, /**/);
1013 if (style.pass_thru) {
1014 inset->plaintext(os, runparams);
1018 // FIXME: move this to InsetNewline::latex
1019 if (inset->lyxCode() == NEWLINE_CODE) {
1020 // newlines are handled differently here than
1021 // the default in simpleTeXSpecialChars().
1022 if (!style.newline_allowed) {
1026 column += running_font.latexWriteEndChanges(
1027 os, bparams, runparams,
1028 basefont, basefont);
1032 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1035 basefont = owner_->getLayoutFont(bparams, outerfont);
1036 running_font = basefont;
1038 if (runparams.moving_arg)
1043 texrow.start(owner_->id(), i + 1);
1047 if (owner_->isDeleted(i)) {
1048 if( ++runparams.inDeletedInset == 1)
1049 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1052 if (inset->canTrackChanges()) {
1053 column += Changes::latexMarkChange(os, bparams, running_change,
1054 Change(Change::UNCHANGED), runparams);
1055 running_change = Change(Change::UNCHANGED);
1059 odocstream::pos_type const len = os.tellp();
1061 if (inset->forceLTR()
1062 && running_font.isRightToLeft()
1063 // ERT is an exception, it should be output with no
1064 // decorations at all
1065 && inset->lyxCode() != ERT_CODE) {
1066 if (running_font.language()->lang() == "farsi")
1073 // FIXME: Bug: we can have an empty font change here!
1074 // if there has just been a font change, we are going to close it
1075 // right now, which means stupid latex code like \textsf{}. AFAIK,
1076 // this does not harm dvi output. A minor bug, thus (JMarc)
1078 // Some insets cannot be inside a font change command.
1079 // However, even such insets *can* be placed in \L or \R
1080 // or their equivalents (for RTL language switches), so we don't
1081 // close the language in those cases.
1082 // ArabTeX, though, cannot handle this special behavior, it seems.
1083 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1084 || running_font.language()->lang() == "arabic_arabtex";
1085 if (open_font && inset->noFontChange()) {
1086 bool closeLanguage = arabtex
1087 || basefont.isRightToLeft() == running_font.isRightToLeft();
1088 unsigned int count = running_font.latexWriteEndChanges(os,
1089 bparams, runparams, basefont, basefont, closeLanguage);
1091 // if any font properties were closed, update the running_font,
1092 // making sure, however, to leave the language as it was
1094 // FIXME: probably a better way to keep track of the old
1095 // language, than copying the entire font?
1096 Font const copy_font(running_font);
1097 basefont = owner_->getLayoutFont(bparams, outerfont);
1098 running_font = basefont;
1100 running_font.setLanguage(copy_font.language());
1101 // leave font open if language is still open
1102 open_font = (running_font.language() == basefont.language());
1104 runparams.local_font = &basefont;
1111 tmp = inset->latex(os, runparams);
1112 } catch (EncodingException & e) {
1113 // add location information and throw again.
1120 if (running_font.language()->lang() == "farsi")
1127 texrow.newlines(tmp);
1128 texrow.start(owner_->id(), i + 1);
1131 column += (unsigned int)(os.tellp() - len);
1134 if (owner_->isDeleted(i))
1135 --runparams.inDeletedInset;
1139 void Paragraph::Private::latexSpecialChar(
1141 OutputParams const & runparams,
1142 Font const & running_font,
1143 Change const & running_change,
1144 Layout const & style,
1146 unsigned int & column)
1148 char_type const c = text_[i];
1150 if (style.pass_thru || runparams.pass_thru) {
1152 // FIXME UNICODE: This can fail if c cannot
1153 // be encoded in the current encoding.
1158 // If T1 font encoding is used, use the special
1159 // characters it provides.
1160 // NOTE: some languages reset the font encoding
1162 if (!running_font.language()->internalFontEncoding()
1163 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1166 // \tt font needs special treatment
1167 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1168 && latexSpecialTypewriter(c, os, i, column))
1171 // Otherwise, we use what LaTeX provides us.
1174 os << "\\textbackslash{}";
1178 os << "\\textless{}";
1182 os << "\\textgreater{}";
1186 os << "\\textbar{}";
1193 os << "\\char`\\\"{}";
1198 case '%': case '#': case '{':
1206 os << "\\textasciitilde{}";
1211 os << "\\textasciicircum{}";
1218 // avoid being mistaken for optional arguments
1226 // Blanks are printed before font switching.
1227 // Sure? I am not! (try nice-latex)
1228 // I am sure it's correct. LyX might be smarter
1229 // in the future, but for now, nothing wrong is
1235 if (latexSpecialPhrase(os, i, column, runparams))
1241 Encoding const & encoding = *(runparams.encoding);
1242 if (i + 1 < int(text_.size())) {
1243 char_type next = text_[i + 1];
1244 if (Encodings::isCombiningChar(next)) {
1245 column += latexSurrogatePair(os, c, next, runparams) - 1;
1251 docstring const latex = encoding.latexChar(c);
1252 if (Encodings::isKnownScriptChar(c, script)
1253 && prefixIs(latex, from_ascii("\\" + script)))
1254 column += writeScriptChars(os, latex,
1255 running_change, encoding, i) - 1;
1256 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1257 // Prevent eating of a following
1258 // space or command corruption by
1259 // following characters
1260 column += latex.length() + 1;
1261 os << latex << "{}";
1263 column += latex.length() - 1;
1271 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1272 pos_type i, unsigned int & column)
1278 // In T1 encoding, these characters exist
1279 // but we should avoid ligatures
1280 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1282 os << "\\textcompwordmark{}";
1289 // soul.sty breaks with \char`\"
1290 os << "\\textquotedbl{}";
1299 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1300 pos_type i, unsigned int & column)
1304 // within \ttfamily, "--" is merged to "-" (no endash)
1305 // so we avoid this rather irritating ligature
1306 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1313 // everything else has to be checked separately
1314 // (depending on the encoding)
1321 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1322 unsigned int & column, OutputParams const & runparams)
1324 // FIXME: if we have "LaTeX" with a font
1325 // change in the middle (before the 'T', then
1326 // the "TeX" part is still special cased.
1327 // Really we should only operate this on
1328 // "words" for some definition of word
1330 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1331 if (!isTextAt(special_phrases[pnr].phrase, i))
1333 if (runparams.moving_arg)
1335 os << special_phrases[pnr].macro;
1336 i += special_phrases[pnr].phrase.length() - 1;
1337 column += special_phrases[pnr].macro.length() - 1;
1344 void Paragraph::Private::validate(LaTeXFeatures & features) const
1346 if (layout_->inpreamble && inset_owner_) {
1347 bool const is_command = layout_->latextype == LATEX_COMMAND;
1348 Buffer const & buf = inset_owner_->buffer();
1349 BufferParams const & bp = buf.params();
1352 // Using a string stream here circumvents the encoding
1353 // switching machinery of odocstream. Therefore the
1354 // output is wrong if this paragraph contains content
1355 // that needs to switch encoding.
1356 odocstringstream ods;
1358 ods << '\\' << from_ascii(layout_->latexname());
1359 // we have to provide all the optional arguments here, even though
1360 // the last one is the only one we care about.
1361 // Separate handling of optional argument inset.
1362 if (layout_->optargs != 0 || layout_->reqargs != 0)
1363 latexArgInsets(*owner_, ods, features.runparams(),
1364 layout_->reqargs, layout_->optargs);
1366 ods << from_ascii(layout_->latexparam());
1368 docstring::size_type const length = ods.str().length();
1369 // this will output "{" at the beginning, but not at the end
1370 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1371 if (ods.str().length() > length) {
1374 string const snippet = to_utf8(ods.str());
1375 features.addPreambleSnippet(snippet);
1379 if (features.runparams().flavor == OutputParams::HTML
1380 && layout_->htmltitle()) {
1381 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1384 // check the params.
1385 if (!params_.spacing().isDefault())
1386 features.require("setspace");
1389 features.useLayout(layout_->name());
1392 fontlist_.validate(features);
1394 // then the indentation
1395 if (!params_.leftIndent().zero())
1396 features.require("ParagraphLeftIndent");
1399 InsetList::const_iterator icit = insetlist_.begin();
1400 InsetList::const_iterator iend = insetlist_.end();
1401 for (; icit != iend; ++icit) {
1403 icit->inset->validate(features);
1404 if (layout_->needprotect &&
1405 icit->inset->lyxCode() == FOOT_CODE)
1406 features.require("NeedLyXFootnoteCode");
1410 // then the contents
1411 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1412 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1413 if (!special_phrases[pnr].builtin
1414 && isTextAt(special_phrases[pnr].phrase, i)) {
1415 features.require(special_phrases[pnr].phrase);
1419 Encodings::validate(text_[i], features);
1423 /////////////////////////////////////////////////////////////////////
1427 /////////////////////////////////////////////////////////////////////
1430 Layout const emptyParagraphLayout;
1433 Paragraph::Paragraph()
1434 : d(new Paragraph::Private(this, emptyParagraphLayout))
1441 Paragraph::Paragraph(Paragraph const & par)
1442 : itemdepth(par.itemdepth),
1443 d(new Paragraph::Private(*par.d, this))
1449 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1450 : itemdepth(par.itemdepth),
1451 d(new Paragraph::Private(*par.d, this, beg, end))
1457 Paragraph & Paragraph::operator=(Paragraph const & par)
1459 // needed as we will destroy the private part before copying it
1461 itemdepth = par.itemdepth;
1465 d = new Private(*par.d, this);
1472 Paragraph::~Paragraph()
1481 // this shall be called just before every "os << ..." action.
1482 void flushString(ostream & os, docstring & s)
1491 void Paragraph::write(ostream & os, BufferParams const & bparams,
1492 depth_type & dth) const
1494 // The beginning or end of a deeper (i.e. nested) area?
1495 if (dth != d->params_.depth()) {
1496 if (d->params_.depth() > dth) {
1497 while (d->params_.depth() > dth) {
1498 os << "\n\\begin_deeper";
1502 while (d->params_.depth() < dth) {
1503 os << "\n\\end_deeper";
1509 // First write the layout
1510 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1512 d->params_.write(os);
1514 Font font1(inherit_font, bparams.language);
1516 Change running_change = Change(Change::UNCHANGED);
1518 // this string is used as a buffer to avoid repetitive calls
1519 // to to_utf8(), which turn out to be expensive (JMarc)
1520 docstring write_buffer;
1523 for (pos_type i = 0; i <= size(); ++i) {
1525 Change const change = lookupChange(i);
1526 if (change != running_change)
1527 flushString(os, write_buffer);
1528 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1529 running_change = change;
1534 // Write font changes
1535 Font font2 = getFontSettings(bparams, i);
1536 if (font2 != font1) {
1537 flushString(os, write_buffer);
1538 font2.lyxWriteChanges(font1, os);
1543 char_type const c = d->text_[i];
1546 if (Inset const * inset = getInset(i)) {
1547 flushString(os, write_buffer);
1548 if (inset->directWrite()) {
1549 // international char, let it write
1550 // code directly so it's shorter in
1556 os << "\\begin_inset ";
1558 os << "\n\\end_inset\n\n";
1564 flushString(os, write_buffer);
1565 os << "\n\\backslash\n";
1569 flushString(os, write_buffer);
1570 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1577 if ((column > 70 && c == ' ')
1579 flushString(os, write_buffer);
1583 // this check is to amend a bug. LyX sometimes
1584 // inserts '\0' this could cause problems.
1586 write_buffer.push_back(c);
1588 LYXERR0("NUL char in structure.");
1594 flushString(os, write_buffer);
1595 os << "\n\\end_layout\n";
1599 void Paragraph::validate(LaTeXFeatures & features) const
1601 d->validate(features);
1605 void Paragraph::insert(pos_type start, docstring const & str,
1606 Font const & font, Change const & change)
1608 for (size_t i = 0, n = str.size(); i != n ; ++i)
1609 insertChar(start + i, str[i], font, change);
1613 void Paragraph::appendChar(char_type c, Font const & font,
1614 Change const & change)
1617 d->changes_.insert(change, d->text_.size());
1618 // when appending characters, no need to update tables
1619 d->text_.push_back(c);
1620 setFont(d->text_.size() - 1, font);
1624 void Paragraph::appendString(docstring const & s, Font const & font,
1625 Change const & change)
1627 pos_type end = s.size();
1628 size_t oldsize = d->text_.size();
1629 size_t newsize = oldsize + end;
1630 size_t capacity = d->text_.capacity();
1631 if (newsize >= capacity)
1632 d->text_.reserve(max(capacity + 100, newsize));
1634 // when appending characters, no need to update tables
1637 // FIXME: Optimize this!
1638 for (size_t i = oldsize; i != newsize; ++i) {
1640 d->changes_.insert(change, i);
1642 d->fontlist_.set(oldsize, font);
1643 d->fontlist_.set(newsize - 1, font);
1647 void Paragraph::insertChar(pos_type pos, char_type c,
1650 d->insertChar(pos, c, Change(trackChanges ?
1651 Change::INSERTED : Change::UNCHANGED));
1655 void Paragraph::insertChar(pos_type pos, char_type c,
1656 Font const & font, bool trackChanges)
1658 d->insertChar(pos, c, Change(trackChanges ?
1659 Change::INSERTED : Change::UNCHANGED));
1664 void Paragraph::insertChar(pos_type pos, char_type c,
1665 Font const & font, Change const & change)
1667 d->insertChar(pos, c, change);
1672 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1673 Font const & font, Change const & change)
1675 bool const success = insertInset(pos, inset, change);
1676 // Set the font/language of the inset...
1682 void Paragraph::resetFonts(Font const & font)
1684 d->fontlist_.clear();
1685 d->fontlist_.set(0, font);
1686 d->fontlist_.set(d->text_.size() - 1, font);
1689 // Gets uninstantiated font setting at position.
1690 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1694 LYXERR0("pos: " << pos << " size: " << size());
1695 LASSERT(pos <= size(), /**/);
1698 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1699 if (cit != d->fontlist_.end())
1702 if (pos == size() && !empty())
1703 return getFontSettings(bparams, pos - 1);
1705 // Optimisation: avoid a full font instantiation if there is no
1706 // language change from previous call.
1707 static Font previous_font;
1708 static Language const * previous_lang = 0;
1709 Language const * lang = getParLanguage(bparams);
1710 if (lang != previous_lang) {
1711 previous_lang = lang;
1712 previous_font = Font(inherit_font, lang);
1714 return previous_font;
1718 FontSpan Paragraph::fontSpan(pos_type pos) const
1720 LASSERT(pos <= size(), /**/);
1723 FontList::const_iterator cit = d->fontlist_.begin();
1724 FontList::const_iterator end = d->fontlist_.end();
1725 for (; cit != end; ++cit) {
1726 if (cit->pos() >= pos) {
1727 if (pos >= beginOfBody())
1728 return FontSpan(max(start, beginOfBody()),
1731 return FontSpan(start,
1732 min(beginOfBody() - 1,
1735 start = cit->pos() + 1;
1738 // This should not happen, but if so, we take no chances.
1739 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1740 return FontSpan(pos, pos);
1744 // Gets uninstantiated font setting at position 0
1745 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1747 if (!empty() && !d->fontlist_.empty())
1748 return d->fontlist_.begin()->font();
1750 // Optimisation: avoid a full font instantiation if there is no
1751 // language change from previous call.
1752 static Font previous_font;
1753 static Language const * previous_lang = 0;
1754 if (bparams.language != previous_lang) {
1755 previous_lang = bparams.language;
1756 previous_font = Font(inherit_font, bparams.language);
1759 return previous_font;
1763 // Gets the fully instantiated font at a given position in a paragraph
1764 // This is basically the same function as Text::GetFont() in text2.cpp.
1765 // The difference is that this one is used for generating the LaTeX file,
1766 // and thus cosmetic "improvements" are disallowed: This has to deliver
1767 // the true picture of the buffer. (Asger)
1768 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1769 Font const & outerfont) const
1771 LASSERT(pos >= 0, /**/);
1773 Font font = getFontSettings(bparams, pos);
1775 pos_type const body_pos = beginOfBody();
1776 FontInfo & fi = font.fontInfo();
1778 fi.realize(d->layout_->labelfont);
1780 fi.realize(d->layout_->font);
1782 fi.realize(outerfont.fontInfo());
1783 fi.realize(bparams.getFont().fontInfo());
1789 Font const Paragraph::getLabelFont
1790 (BufferParams const & bparams, Font const & outerfont) const
1792 FontInfo tmpfont = d->layout_->labelfont;
1793 tmpfont.realize(outerfont.fontInfo());
1794 tmpfont.realize(bparams.getFont().fontInfo());
1795 return Font(tmpfont, getParLanguage(bparams));
1799 Font const Paragraph::getLayoutFont
1800 (BufferParams const & bparams, Font const & outerfont) const
1802 FontInfo tmpfont = d->layout_->font;
1803 tmpfont.realize(outerfont.fontInfo());
1804 tmpfont.realize(bparams.getFont().fontInfo());
1805 return Font(tmpfont, getParLanguage(bparams));
1809 /// Returns the height of the highest font in range
1810 FontSize Paragraph::highestFontInRange
1811 (pos_type startpos, pos_type endpos, FontSize def_size) const
1813 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1817 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1819 char_type c = d->text_[pos];
1820 if (!lyxrc.rtl_support)
1850 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1856 void Paragraph::setFont(pos_type pos, Font const & font)
1858 LASSERT(pos <= size(), /**/);
1860 // First, reduce font against layout/label font
1861 // Update: The setCharFont() routine in text2.cpp already
1862 // reduces font, so we don't need to do that here. (Asger)
1864 d->fontlist_.set(pos, font);
1868 void Paragraph::makeSameLayout(Paragraph const & par)
1870 d->layout_ = par.d->layout_;
1871 d->params_ = par.d->params_;
1875 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1877 if (isFreeSpacing())
1883 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1884 if (eraseChar(pos, trackChanges))
1890 return count > 0 || pos > 0;
1894 bool Paragraph::hasSameLayout(Paragraph const & par) const
1896 return par.d->layout_ == d->layout_
1897 && d->params_.sameLayout(par.d->params_);
1901 depth_type Paragraph::getDepth() const
1903 return d->params_.depth();
1907 depth_type Paragraph::getMaxDepthAfter() const
1909 if (d->layout_->isEnvironment())
1910 return d->params_.depth() + 1;
1912 return d->params_.depth();
1916 char Paragraph::getAlign() const
1918 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1919 return d->layout_->align;
1921 return d->params_.align();
1925 docstring const & Paragraph::labelString() const
1927 return d->params_.labelString();
1931 // the next two functions are for the manual labels
1932 docstring const Paragraph::getLabelWidthString() const
1934 if (d->layout_->margintype == MARGIN_MANUAL
1935 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1936 return d->params_.labelWidthString();
1938 return _("Senseless with this layout!");
1942 void Paragraph::setLabelWidthString(docstring const & s)
1944 d->params_.labelWidthString(s);
1948 docstring Paragraph::expandLabel(Layout const & layout,
1949 BufferParams const & bparams) const
1951 return expandParagraphLabel(layout, bparams, true);
1955 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1956 BufferParams const & bparams) const
1958 return expandParagraphLabel(layout, bparams, false);
1962 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1963 BufferParams const & bparams, bool process_appendix) const
1965 DocumentClass const & tclass = bparams.documentClass();
1966 string const & lang = getParLanguage(bparams)->code();
1967 bool const in_appendix = process_appendix && d->params_.appendix();
1968 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1970 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1971 && !layout.counter.empty())
1972 return tclass.counters().theCounter(layout.counter, lang);
1974 // handle 'inherited level parts' in 'fmt',
1975 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1976 size_t const i = fmt.find('@', 0);
1977 if (i != docstring::npos) {
1978 size_t const j = fmt.find('@', i + 1);
1979 if (j != docstring::npos) {
1980 docstring parent(fmt, i + 1, j - i - 1);
1981 docstring label = from_ascii("??");
1982 if (tclass.hasLayout(parent))
1983 docstring label = expandParagraphLabel(tclass[parent], bparams,
1985 fmt = docstring(fmt, 0, i) + label
1986 + docstring(fmt, j + 1, docstring::npos);
1990 return tclass.counters().counterLabel(fmt, lang);
1994 void Paragraph::applyLayout(Layout const & new_layout)
1996 d->layout_ = &new_layout;
1997 LyXAlignment const oldAlign = d->params_.align();
1999 if (!(oldAlign & d->layout_->alignpossible)) {
2000 frontend::Alert::warning(_("Alignment not permitted"),
2001 _("The new layout does not permit the alignment previously used.\nSetting to default."));
2002 d->params_.align(LYX_ALIGN_LAYOUT);
2007 pos_type Paragraph::beginOfBody() const
2009 return d->begin_of_body_;
2013 void Paragraph::setBeginOfBody()
2015 if (d->layout_->labeltype != LABEL_MANUAL) {
2016 d->begin_of_body_ = 0;
2020 // Unroll the first two cycles of the loop
2021 // and remember the previous character to
2022 // remove unnecessary getChar() calls
2024 pos_type end = size();
2025 if (i < end && !isNewline(i)) {
2027 char_type previous_char = 0;
2030 previous_char = d->text_[i];
2031 if (!isNewline(i)) {
2033 while (i < end && previous_char != ' ') {
2038 previous_char = temp;
2044 d->begin_of_body_ = i;
2048 bool Paragraph::allowParagraphCustomization() const
2050 return inInset().allowParagraphCustomization();
2054 bool Paragraph::usePlainLayout() const
2056 return inInset().usePlainLayout();
2062 // paragraphs inside floats need different alignment tags to avoid
2065 bool noTrivlistCentering(InsetCode code)
2067 return code == FLOAT_CODE
2068 || code == WRAP_CODE
2069 || code == CELL_CODE;
2073 string correction(string const & orig)
2075 if (orig == "flushleft")
2076 return "raggedright";
2077 if (orig == "flushright")
2078 return "raggedleft";
2079 if (orig == "center")
2085 string const corrected_env(string const & suffix, string const & env,
2086 InsetCode code, bool const lastpar)
2088 string output = suffix + "{";
2089 if (noTrivlistCentering(code)) {
2091 // the last paragraph in non-trivlist-aligned
2092 // context is special (to avoid unwanted whitespace)
2093 if (suffix == "\\begin")
2094 return "\\" + correction(env) + "{}";
2097 output += correction(env);
2101 if (suffix == "\\begin")
2107 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2109 if (!contains(str, "\n"))
2110 column += str.size();
2114 column = rsplit(str, tmp, '\n').size();
2121 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2122 odocstream & os, TexRow & texrow,
2123 OutputParams const & runparams) const
2127 if (params_.noindent()) {
2128 os << "\\noindent ";
2132 LyXAlignment const curAlign = params_.align();
2134 if (curAlign == layout_->align)
2138 case LYX_ALIGN_NONE:
2139 case LYX_ALIGN_BLOCK:
2140 case LYX_ALIGN_LAYOUT:
2141 case LYX_ALIGN_SPECIAL:
2142 case LYX_ALIGN_DECIMAL:
2144 case LYX_ALIGN_LEFT:
2145 case LYX_ALIGN_RIGHT:
2146 case LYX_ALIGN_CENTER:
2147 if (runparams.moving_arg) {
2154 string const begin_tag = "\\begin";
2155 InsetCode code = ownerCode();
2156 bool const lastpar = runparams.isLastPar;
2159 case LYX_ALIGN_NONE:
2160 case LYX_ALIGN_BLOCK:
2161 case LYX_ALIGN_LAYOUT:
2162 case LYX_ALIGN_SPECIAL:
2163 case LYX_ALIGN_DECIMAL:
2165 case LYX_ALIGN_LEFT: {
2167 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2168 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2170 output = corrected_env(begin_tag, "flushright", code, lastpar);
2171 os << from_ascii(output);
2172 adjust_row_column(output, texrow, column);
2174 } case LYX_ALIGN_RIGHT: {
2176 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2177 output = corrected_env(begin_tag, "flushright", code, lastpar);
2179 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2180 os << from_ascii(output);
2181 adjust_row_column(output, texrow, column);
2183 } case LYX_ALIGN_CENTER: {
2185 output = corrected_env(begin_tag, "center", code, lastpar);
2186 os << from_ascii(output);
2187 adjust_row_column(output, texrow, column);
2196 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2197 odocstream & os, TexRow & texrow,
2198 OutputParams const & runparams) const
2202 LyXAlignment const curAlign = params_.align();
2204 if (curAlign == layout_->align)
2208 case LYX_ALIGN_NONE:
2209 case LYX_ALIGN_BLOCK:
2210 case LYX_ALIGN_LAYOUT:
2211 case LYX_ALIGN_SPECIAL:
2212 case LYX_ALIGN_DECIMAL:
2214 case LYX_ALIGN_LEFT:
2215 case LYX_ALIGN_RIGHT:
2216 case LYX_ALIGN_CENTER:
2217 if (runparams.moving_arg) {
2224 string const end_tag = "\n\\par\\end";
2225 InsetCode code = ownerCode();
2226 bool const lastpar = runparams.isLastPar;
2229 case LYX_ALIGN_NONE:
2230 case LYX_ALIGN_BLOCK:
2231 case LYX_ALIGN_LAYOUT:
2232 case LYX_ALIGN_SPECIAL:
2233 case LYX_ALIGN_DECIMAL:
2235 case LYX_ALIGN_LEFT: {
2237 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2238 output = corrected_env(end_tag, "flushleft", code, lastpar);
2240 output = corrected_env(end_tag, "flushright", code, lastpar);
2241 os << from_ascii(output);
2242 adjust_row_column(output, texrow, column);
2244 } case LYX_ALIGN_RIGHT: {
2246 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2247 output = corrected_env(end_tag, "flushright", code, lastpar);
2249 output = corrected_env(end_tag, "flushleft", code, lastpar);
2250 os << from_ascii(output);
2251 adjust_row_column(output, texrow, column);
2253 } case LYX_ALIGN_CENTER: {
2255 output = corrected_env(end_tag, "center", code, lastpar);
2256 os << from_ascii(output);
2257 adjust_row_column(output, texrow, column);
2266 // This one spits out the text of the paragraph
2267 void Paragraph::latex(BufferParams const & bparams,
2268 Font const & outerfont,
2269 odocstream & os, TexRow & texrow,
2270 OutputParams const & runparams,
2271 int start_pos, int end_pos, bool force) const
2273 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2275 // FIXME This check should not be needed. Perhaps issue an
2276 // error if it triggers.
2277 Layout const & style = inInset().forcePlainLayout() ?
2278 bparams.documentClass().plainLayout() : *d->layout_;
2280 if (!force && style.inpreamble)
2283 bool const allowcust = allowParagraphCustomization();
2285 // Current base font for all inherited font changes, without any
2286 // change caused by an individual character, except for the language:
2287 // It is set to the language of the first character.
2288 // As long as we are in the label, this font is the base font of the
2289 // label. Before the first body character it is set to the base font
2293 // Maybe we have to create a optional argument.
2294 pos_type body_pos = beginOfBody();
2295 unsigned int column = 0;
2298 // the optional argument is kept in curly brackets in
2299 // case it contains a ']'
2302 basefont = getLabelFont(bparams, outerfont);
2304 basefont = getLayoutFont(bparams, outerfont);
2307 // Which font is currently active?
2308 Font running_font(basefont);
2309 // Do we have an open font change?
2310 bool open_font = false;
2312 Change runningChange = Change(Change::UNCHANGED);
2314 Encoding const * const prev_encoding = runparams.encoding;
2316 texrow.start(id(), 0);
2318 // if the paragraph is empty, the loop will not be entered at all
2320 if (style.isCommand()) {
2325 column += d->startTeXParParams(bparams, os, texrow,
2329 for (pos_type i = 0; i < size(); ++i) {
2330 // First char in paragraph or after label?
2331 if (i == body_pos) {
2334 column += running_font.latexWriteEndChanges(
2335 os, bparams, runparams,
2336 basefont, basefont);
2339 basefont = getLayoutFont(bparams, outerfont);
2340 running_font = basefont;
2342 column += Changes::latexMarkChange(os, bparams,
2343 runningChange, Change(Change::UNCHANGED),
2345 runningChange = Change(Change::UNCHANGED);
2350 if (style.isCommand()) {
2356 column += d->startTeXParParams(bparams, os,
2361 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2364 if (bparams.outputChanges && runningChange != change) {
2366 column += running_font.latexWriteEndChanges(
2367 os, bparams, runparams, basefont, basefont);
2370 basefont = getLayoutFont(bparams, outerfont);
2371 running_font = basefont;
2373 column += Changes::latexMarkChange(os, bparams, runningChange,
2375 runningChange = change;
2378 // do not output text which is marked deleted
2379 // if change tracking output is disabled
2380 if (!bparams.outputChanges && change.deleted()) {
2386 // Fully instantiated font
2387 Font const font = getFont(bparams, i, outerfont);
2389 Font const last_font = running_font;
2391 // Do we need to close the previous font?
2393 (font != running_font ||
2394 font.language() != running_font.language()))
2396 column += running_font.latexWriteEndChanges(
2397 os, bparams, runparams, basefont,
2398 (i == body_pos-1) ? basefont : font);
2399 running_font = basefont;
2403 string const running_lang = runparams.use_polyglossia ?
2404 running_font.language()->polyglossia() : running_font.language()->babel();
2405 // close babel's font environment before opening CJK.
2406 string const lang_end_command = runparams.use_polyglossia ?
2407 "\\end{$$lang}" : lyxrc.language_command_end;
2408 if (!running_lang.empty() &&
2409 font.language()->encoding()->package() == Encoding::CJK) {
2410 string end_tag = subst(lang_end_command,
2413 os << from_ascii(end_tag);
2414 column += end_tag.length();
2417 // Switch file encoding if necessary (and allowed)
2418 if (!runparams.pass_thru && !style.pass_thru &&
2419 runparams.encoding->package() != Encoding::none &&
2420 font.language()->encoding()->package() != Encoding::none) {
2421 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2422 runparams, *(font.language()->encoding()));
2423 if (enc_switch.first) {
2424 column += enc_switch.second;
2425 runparams.encoding = font.language()->encoding();
2429 char_type const c = d->text_[i];
2431 // Do we need to change font?
2432 if ((font != running_font ||
2433 font.language() != running_font.language()) &&
2436 odocstringstream ods;
2437 column += font.latexWriteStartChanges(ods, bparams,
2438 runparams, basefont,
2440 running_font = font;
2442 docstring fontchange = ods.str();
2443 // check whether the fontchange ends with a \\textcolor
2444 // modifier and the text starts with a space (bug 4473)
2445 docstring const last_modifier = rsplit(fontchange, '\\');
2446 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2447 os << fontchange << from_ascii("{}");
2448 // check if the fontchange ends with a trailing blank
2449 // (like "\small " (see bug 3382)
2450 else if (suffixIs(fontchange, ' ') && c == ' ')
2451 os << fontchange.substr(0, fontchange.size() - 1)
2452 << from_ascii("{}");
2457 // FIXME: think about end_pos implementation...
2458 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2459 // FIXME: integrate this case in latexSpecialChar
2460 // Do not print the separation of the optional argument
2461 // if style.pass_thru is false. This works because
2462 // latexSpecialChar ignores spaces if
2463 // style.pass_thru is false.
2464 if (i != body_pos - 1) {
2465 if (d->simpleTeXBlanks(
2466 runparams, os, texrow,
2467 i, column, font, style)) {
2468 // A surrogate pair was output. We
2469 // must not call latexSpecialChar
2470 // in this iteration, since it would output
2471 // the combining character again.
2478 OutputParams rp = runparams;
2479 rp.free_spacing = style.free_spacing;
2480 rp.local_font = &font;
2481 rp.intitle = style.intitle;
2483 // Two major modes: LaTeX or plain
2484 // Handle here those cases common to both modes
2485 // and then split to handle the two modes separately.
2486 if (c == META_INSET) {
2487 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2488 d->latexInset(bparams, os,
2489 texrow, rp, running_font,
2490 basefont, outerfont, open_font,
2491 runningChange, style, i, column);
2494 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2496 d->latexSpecialChar(os, rp, running_font, runningChange,
2498 } catch (EncodingException & e) {
2499 if (runparams.dryrun) {
2500 os << "<" << _("LyX Warning: ")
2501 << _("uncodable character") << " '";
2505 // add location information and throw again.
2514 // Set the encoding to that returned from latexSpecialChar (see
2515 // comment for encoding member in OutputParams.h)
2516 runparams.encoding = rp.encoding;
2519 // If we have an open font definition, we have to close it
2521 #ifdef FIXED_LANGUAGE_END_DETECTION
2523 running_font.latexWriteEndChanges(os, bparams,
2524 runparams, basefont,
2525 next_->getFont(bparams, 0, outerfont));
2527 running_font.latexWriteEndChanges(os, bparams,
2528 runparams, basefont, basefont);
2531 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2532 //FIXME: there as we start another \selectlanguage with the next paragraph if
2533 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2534 running_font.latexWriteEndChanges(os, bparams, runparams,
2535 basefont, basefont);
2539 column += Changes::latexMarkChange(os, bparams, runningChange,
2540 Change(Change::UNCHANGED), runparams);
2542 // Needed if there is an optional argument but no contents.
2543 if (body_pos > 0 && body_pos == size()) {
2547 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2548 && runparams.encoding != prev_encoding) {
2549 runparams.encoding = prev_encoding;
2550 if (!runparams.isFullUnicode())
2551 os << setEncoding(prev_encoding->iconvName());
2554 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2558 bool Paragraph::emptyTag() const
2560 for (pos_type i = 0; i < size(); ++i) {
2561 if (Inset const * inset = getInset(i)) {
2562 InsetCode lyx_code = inset->lyxCode();
2563 // FIXME testing like that is wrong. What is
2565 if (lyx_code != TOC_CODE &&
2566 lyx_code != INCLUDE_CODE &&
2567 lyx_code != GRAPHICS_CODE &&
2568 lyx_code != ERT_CODE &&
2569 lyx_code != LISTINGS_CODE &&
2570 lyx_code != FLOAT_CODE &&
2571 lyx_code != TABULAR_CODE) {
2575 char_type c = d->text_[i];
2576 if (c != ' ' && c != '\t')
2584 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2587 for (pos_type i = 0; i < size(); ++i) {
2588 if (Inset const * inset = getInset(i)) {
2589 InsetCode lyx_code = inset->lyxCode();
2590 if (lyx_code == LABEL_CODE) {
2591 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2592 docstring const & id = il->getParam("name");
2593 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2601 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2605 for (i = 0; i < size(); ++i) {
2606 if (Inset const * inset = getInset(i)) {
2607 inset->docbook(os, runparams);
2609 char_type c = d->text_[i];
2612 os << sgml::escapeChar(c);
2619 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2623 for (i = 0; i < size(); ++i) {
2624 if (Inset const * inset = getInset(i)) {
2625 inset->xhtml(xs, runparams);
2627 char_type c = d->text_[i];
2637 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2640 pos_type size = text_.size();
2641 for (pos_type i = initial; i < size; ++i) {
2642 Font font = owner_->getFont(buf.params(), i, outerfont);
2643 if (text_[i] == META_INSET)
2645 if (i != initial && font != font_old)
2654 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2656 OutputParams const & runparams,
2657 Font const & outerfont,
2658 pos_type initial) const
2660 bool emph_flag = false;
2662 Layout const & style = *d->layout_;
2664 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2666 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2669 // parsing main loop
2670 for (pos_type i = initial; i < size(); ++i) {
2671 Font font = getFont(buf.params(), i, outerfont);
2673 // handle <emphasis> tag
2674 if (font_old.emph() != font.fontInfo().emph()) {
2675 if (font.fontInfo().emph() == FONT_ON) {
2678 } else if (i != initial) {
2679 os << "</emphasis>";
2684 if (Inset const * inset = getInset(i)) {
2685 inset->docbook(os, runparams);
2687 char_type c = d->text_[i];
2689 if (style.pass_thru)
2692 os << sgml::escapeChar(c);
2694 font_old = font.fontInfo();
2698 os << "</emphasis>";
2701 if (style.free_spacing)
2703 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2708 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2710 OutputParams const & runparams,
2711 Font const & outerfont,
2712 pos_type initial) const
2716 bool emph_flag = false;
2717 bool bold_flag = false;
2720 Layout const & style = *d->layout_;
2722 if (!runparams.for_toc && runparams.html_make_pars) {
2723 // generate a magic label for this paragraph
2724 string const attr = "id='" + magicLabel() + "'";
2725 xs << html::CompTag("a", attr);
2729 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2731 // parsing main loop
2732 for (pos_type i = initial; i < size(); ++i) {
2733 // let's not show deleted material in the output
2737 Font font = getFont(buf.params(), i, outerfont);
2740 if (font_old.emph() != font.fontInfo().emph()) {
2741 if (font.fontInfo().emph() == FONT_ON) {
2742 xs << html::StartTag("em");
2744 } else if (emph_flag && i != initial) {
2745 xs << html::EndTag("em");
2750 if (font_old.series() != font.fontInfo().series()) {
2751 if (font.fontInfo().series() == BOLD_SERIES) {
2752 xs << html::StartTag("strong");
2754 } else if (bold_flag && i != initial) {
2755 xs << html::EndTag("strong");
2760 // Other such tags? What about the other text ranges?
2762 Inset const * inset = getInset(i);
2764 if (!runparams.for_toc || inset->isInToc()) {
2765 OutputParams np = runparams;
2766 if (!inset->getLayout().htmlisblock())
2767 np.html_in_par = true;
2768 retval += inset->xhtml(xs, np);
2771 char_type c = d->text_[i];
2773 if (style.pass_thru)
2775 else if (c == '-') {
2778 if (j < size() && d->text_[j] == '-') {
2780 if (j < size() && d->text_[j] == '-') {
2781 str += from_ascii("—");
2784 str += from_ascii("–");
2790 // We don't want to escape the entities. Note that
2791 // it is safe to do this, since str can otherwise
2792 // only be "-". E.g., it can't be "<".
2793 xs << XHTMLStream::ESCAPE_NONE << str;
2797 font_old = font.fontInfo();
2805 bool Paragraph::isHfill(pos_type pos) const
2807 Inset const * inset = getInset(pos);
2808 return inset && (inset->lyxCode() == SPACE_CODE &&
2809 inset->isStretchableSpace());
2813 bool Paragraph::isNewline(pos_type pos) const
2815 Inset const * inset = getInset(pos);
2816 return inset && inset->lyxCode() == NEWLINE_CODE;
2820 bool Paragraph::isLineSeparator(pos_type pos) const
2822 char_type const c = d->text_[pos];
2823 if (isLineSeparatorChar(c))
2825 Inset const * inset = getInset(pos);
2826 return inset && inset->isLineSeparator();
2830 bool Paragraph::isWordSeparator(pos_type pos) const
2832 if (Inset const * inset = getInset(pos))
2833 return !inset->isLetter();
2834 char_type const c = d->text_[pos];
2835 // We want to pass the ' and escape chars to the spellchecker
2836 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2837 return (!isLetterChar(c) && !isDigitASCII(c) && !contains(quote, c))
2842 bool Paragraph::isSameSpellRange(pos_type pos1, pos_type pos2) const
2845 || d->speller_state_.getRange(pos1) == d->speller_state_.getRange(pos2);
2849 bool Paragraph::isChar(pos_type pos) const
2851 if (Inset const * inset = getInset(pos))
2852 return inset->isChar();
2853 char_type const c = d->text_[pos];
2854 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2858 bool Paragraph::isSpace(pos_type pos) const
2860 if (Inset const * inset = getInset(pos))
2861 return inset->isSpace();
2862 char_type const c = d->text_[pos];
2863 return lyx::isSpace(c);
2868 Paragraph::getParLanguage(BufferParams const & bparams) const
2871 return getFirstFontSettings(bparams).language();
2872 // FIXME: we should check the prev par as well (Lgb)
2873 return bparams.language;
2877 bool Paragraph::isRTL(BufferParams const & bparams) const
2879 return lyxrc.rtl_support
2880 && getParLanguage(bparams)->rightToLeft()
2881 && !inInset().getLayout().forceLTR();
2885 void Paragraph::changeLanguage(BufferParams const & bparams,
2886 Language const * from, Language const * to)
2888 // change language including dummy font change at the end
2889 for (pos_type i = 0; i <= size(); ++i) {
2890 Font font = getFontSettings(bparams, i);
2891 if (font.language() == from) {
2892 font.setLanguage(to);
2896 d->requestSpellCheck(size());
2900 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2902 Language const * doc_language = bparams.language;
2903 FontList::const_iterator cit = d->fontlist_.begin();
2904 FontList::const_iterator end = d->fontlist_.end();
2906 for (; cit != end; ++cit)
2907 if (cit->font().language() != ignore_language &&
2908 cit->font().language() != latex_language &&
2909 cit->font().language() != doc_language)
2915 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2917 FontList::const_iterator cit = d->fontlist_.begin();
2918 FontList::const_iterator end = d->fontlist_.end();
2920 for (; cit != end; ++cit) {
2921 Language const * lang = cit->font().language();
2922 if (lang != ignore_language &&
2923 lang != latex_language)
2924 languages.insert(lang);
2929 docstring Paragraph::asString(int options) const
2931 return asString(0, size(), options);
2935 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2937 odocstringstream os;
2940 && options & AS_STR_LABEL
2941 && !d->params_.labelString().empty())
2942 os << d->params_.labelString() << ' ';
2944 for (pos_type i = beg; i < end; ++i) {
2945 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2947 char_type const c = d->text_[i];
2948 if (isPrintable(c) || c == '\t'
2949 || (c == '\n' && (options & AS_STR_NEWLINES)))
2951 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2952 getInset(i)->toString(os);
2953 if (getInset(i)->asInsetMath())
2962 void Paragraph::forToc(docstring & os, size_t maxlen) const
2964 for (pos_type i = 0; i < size() && os.length() < maxlen; ++i) {
2967 char_type const c = d->text_[i];
2970 else if (c == '\t' || c == '\n')
2972 else if (c == META_INSET)
2973 getInset(i)->forToc(os, maxlen);
2978 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2980 odocstringstream os;
2983 && options & AS_STR_LABEL
2984 && !d->params_.labelString().empty())
2985 os << d->params_.labelString() << ' ';
2987 for (pos_type i = beg; i < end; ++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)->plaintext(os, runparams);
3001 void Paragraph::setInsetOwner(Inset const * inset)
3003 d->inset_owner_ = inset;
3007 int Paragraph::id() const
3013 void Paragraph::setId(int id)
3019 Layout const & Paragraph::layout() const
3025 void Paragraph::setLayout(Layout const & layout)
3027 d->layout_ = &layout;
3031 void Paragraph::setDefaultLayout(DocumentClass const & tc)
3033 setLayout(tc.defaultLayout());
3037 void Paragraph::setPlainLayout(DocumentClass const & tc)
3039 setLayout(tc.plainLayout());
3043 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3045 if (usePlainLayout())
3046 setPlainLayout(tclass);
3048 setDefaultLayout(tclass);
3052 Inset const & Paragraph::inInset() const
3054 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3055 _("Memory problem"), _("Paragraph not properly initialized")));
3056 return *d->inset_owner_;
3060 ParagraphParameters & Paragraph::params()
3066 ParagraphParameters const & Paragraph::params() const
3072 bool Paragraph::isFreeSpacing() const
3074 if (d->layout_->free_spacing)
3076 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3080 bool Paragraph::allowEmpty() const
3082 if (d->layout_->keepempty)
3084 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3088 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3090 if (!Encodings::isArabicChar(c))
3093 char_type prev_char = ' ';
3094 char_type next_char = ' ';
3096 for (pos_type i = pos - 1; i >= 0; --i) {
3097 char_type const par_char = d->text_[i];
3098 if (!Encodings::isArabicComposeChar(par_char)) {
3099 prev_char = par_char;
3104 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3105 char_type const par_char = d->text_[i];
3106 if (!Encodings::isArabicComposeChar(par_char)) {
3107 next_char = par_char;
3112 if (Encodings::isArabicChar(next_char)) {
3113 if (Encodings::isArabicChar(prev_char) &&
3114 !Encodings::isArabicSpecialChar(prev_char))
3115 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3117 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3119 if (Encodings::isArabicChar(prev_char) &&
3120 !Encodings::isArabicSpecialChar(prev_char))
3121 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3123 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3128 int Paragraph::checkBiblio(Buffer const & buffer)
3131 // This is getting more and more a mess. ...We really should clean
3132 // up this bibitem issue for 1.6.
3134 // Add bibitem insets if necessary
3135 if (d->layout_->labeltype != LABEL_BIBLIO)
3138 bool hasbibitem = !d->insetlist_.empty()
3139 // Insist on it being in pos 0
3140 && d->text_[0] == META_INSET
3141 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3143 bool track_changes = buffer.params().trackChanges;
3148 // remove a bibitem in pos != 0
3149 // restore it later in pos 0 if necessary
3150 // (e.g. if a user inserts contents _before_ the item)
3151 // we're assuming there's only one of these, which there
3153 int erasedInsetPosition = -1;
3154 InsetList::iterator it = d->insetlist_.begin();
3155 InsetList::iterator end = d->insetlist_.end();
3156 for (; it != end; ++it)
3157 if (it->inset->lyxCode() == BIBITEM_CODE
3159 InsetCommand * olditem = it->inset->asInsetCommand();
3160 oldkey = olditem->getParam("key");
3161 oldlabel = olditem->getParam("label");
3162 erasedInsetPosition = it->pos;
3163 eraseChar(erasedInsetPosition, track_changes);
3167 // There was an InsetBibitem at the beginning, and we didn't
3168 // have to erase one.
3169 if (hasbibitem && erasedInsetPosition < 0)
3172 // There was an InsetBibitem at the beginning and we did have to
3173 // erase one. So we give its properties to the beginning inset.
3175 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3176 if (!oldkey.empty())
3177 inset->setParam("key", oldkey);
3178 inset->setParam("label", oldlabel);
3179 return -erasedInsetPosition;
3182 // There was no inset at the beginning, so we need to create one with
3183 // the key and label of the one we erased.
3184 InsetBibitem * inset =
3185 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3186 // restore values of previously deleted item in this par.
3187 if (!oldkey.empty())
3188 inset->setParam("key", oldkey);
3189 inset->setParam("label", oldlabel);
3190 insertInset(0, inset,
3191 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3197 void Paragraph::checkAuthors(AuthorList const & authorList)
3199 d->changes_.checkAuthors(authorList);
3203 bool Paragraph::isChanged(pos_type pos) const
3205 return lookupChange(pos).changed();
3209 bool Paragraph::isInserted(pos_type pos) const
3211 return lookupChange(pos).inserted();
3215 bool Paragraph::isDeleted(pos_type pos) const
3217 return lookupChange(pos).deleted();
3221 InsetList const & Paragraph::insetList() const
3223 return d->insetlist_;
3227 void Paragraph::setBuffer(Buffer & b)
3229 d->insetlist_.setBuffer(b);
3233 Inset * Paragraph::releaseInset(pos_type pos)
3235 Inset * inset = d->insetlist_.release(pos);
3236 /// does not honour change tracking!
3237 eraseChar(pos, false);
3242 Inset * Paragraph::getInset(pos_type pos)
3244 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3245 ? d->insetlist_.get(pos) : 0;
3249 Inset const * Paragraph::getInset(pos_type pos) const
3251 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3252 ? d->insetlist_.get(pos) : 0;
3256 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3257 pos_type & right, TextCase action)
3259 // process sequences of modified characters; in change
3260 // tracking mode, this approach results in much better
3261 // usability than changing case on a char-by-char basis
3264 bool const trackChanges = bparams.trackChanges;
3266 bool capitalize = true;
3268 for (; pos < right; ++pos) {
3269 char_type oldChar = d->text_[pos];
3270 char_type newChar = oldChar;
3272 // ignore insets and don't play with deleted text!
3273 if (oldChar != META_INSET && !isDeleted(pos)) {
3275 case text_lowercase:
3276 newChar = lowercase(oldChar);
3278 case text_capitalization:
3280 newChar = uppercase(oldChar);
3284 case text_uppercase:
3285 newChar = uppercase(oldChar);
3290 if (isWordSeparator(pos) || isDeleted(pos)) {
3291 // permit capitalization again
3295 if (oldChar != newChar) {
3297 if (pos != right - 1)
3299 // step behind the changing area
3303 int erasePos = pos - changes.size();
3304 for (size_t i = 0; i < changes.size(); i++) {
3305 insertChar(pos, changes[i],
3306 getFontSettings(bparams,
3309 if (!eraseChar(erasePos, trackChanges)) {
3312 ++right; // expand selection
3320 int Paragraph::find(docstring const & str, bool cs, bool mw,
3321 pos_type start_pos, bool del) const
3323 pos_type pos = start_pos;
3324 int const strsize = str.length();
3326 pos_type const parsize = d->text_.size();
3327 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3328 // Ignore ligature break and hyphenation chars while searching
3329 while (pos < parsize - 1 && isInset(pos)) {
3330 const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3332 || (isc->kind() != InsetSpecialChar::HYPHENATION
3333 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3337 if (cs && str[i] != d->text_[pos])
3339 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3341 if (!del && isDeleted(pos))
3348 // if necessary, check whether string matches word
3350 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3353 && !isWordSeparator(pos))
3357 return pos - start_pos;
3361 char_type Paragraph::getChar(pos_type pos) const
3363 return d->text_[pos];
3367 pos_type Paragraph::size() const
3369 return d->text_.size();
3373 bool Paragraph::empty() const
3375 return d->text_.empty();
3379 bool Paragraph::isInset(pos_type pos) const
3381 return d->text_[pos] == META_INSET;
3385 bool Paragraph::isSeparator(pos_type pos) const
3387 //FIXME: Are we sure this can be the only separator?
3388 return d->text_[pos] == ' ';
3392 void Paragraph::deregisterWords()
3394 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3395 Private::LangWordsMap::const_iterator ite = d->words_.end();
3396 for (; itl != ite; ++itl) {
3397 WordList * wl = theWordList(itl->first);
3398 Private::Words::const_iterator it = (itl->second).begin();
3399 Private::Words::const_iterator et = (itl->second).end();
3400 for (; it != et; ++it)
3407 void Paragraph::locateWord(pos_type & from, pos_type & to,
3408 word_location const loc) const
3411 case WHOLE_WORD_STRICT:
3412 if (from == 0 || from == size()
3413 || isWordSeparator(from)
3414 || isWordSeparator(from - 1)) {
3418 // no break here, we go to the next
3421 // If we are already at the beginning of a word, do nothing
3422 if (!from || isWordSeparator(from - 1))
3424 // no break here, we go to the next
3427 // always move the cursor to the beginning of previous word
3428 while (from && !isWordSeparator(from - 1))
3432 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3435 // no need to move the 'from' cursor
3439 while (to < size() && !isWordSeparator(to))
3444 void Paragraph::collectWords()
3446 // This is the value that needs to be exposed in the preferences
3447 // to resolve bug #6760.
3448 static int minlength = 6;
3449 pos_type n = size();
3450 for (pos_type pos = 0; pos < n; ++pos) {
3451 if (isWordSeparator(pos))
3453 pos_type from = pos;
3454 locateWord(from, pos, WHOLE_WORD);
3455 if (pos - from >= minlength) {
3456 docstring word = asString(from, pos, AS_STR_NONE);
3457 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3458 if (cit == d->fontlist_.end())
3460 Language const * lang = cit->font().language();
3461 d->words_[*lang].insert(word);
3467 void Paragraph::registerWords()
3469 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3470 Private::LangWordsMap::const_iterator ite = d->words_.end();
3471 for (; itl != ite; ++itl) {
3472 WordList * wl = theWordList(itl->first);
3473 Private::Words::const_iterator it = (itl->second).begin();
3474 Private::Words::const_iterator et = (itl->second).end();
3475 for (; it != et; ++it)
3481 void Paragraph::updateWords()
3489 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3491 SkipPositionsIterator begin = skips.begin();
3492 SkipPositions::iterator end = skips.end();
3493 if (pos > 0 && begin < end) {
3495 if (end->last == pos - 1) {
3500 skips.insert(end, FontSpan(pos, pos));
3504 Language * Paragraph::Private::locateSpellRange(
3505 pos_type & from, pos_type & to,
3506 SkipPositions & skips) const
3508 // skip leading white space
3509 while (from < to && owner_->isWordSeparator(from))
3511 // don't check empty range
3514 // get current language
3515 Language * lang = getSpellLanguage(from);
3516 pos_type last = from;
3517 bool samelang = true;
3518 bool sameinset = true;
3519 while (last < to && samelang && sameinset) {
3520 // hop to end of word
3521 while (last < to && !owner_->isWordSeparator(last)) {
3522 if (owner_->getInset(last)) {
3523 appendSkipPosition(skips, last);
3524 } else if (owner_->isDeleted(last)) {
3525 appendSkipPosition(skips, last);
3529 // hop to next word while checking for insets
3530 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3531 if (Inset const * inset = owner_->getInset(last))
3532 sameinset = inset->isChar() && inset->isLetter();
3533 if (sameinset && owner_->isDeleted(last)) {
3534 appendSkipPosition(skips, last);
3539 if (sameinset && last < to) {
3540 // now check for language change
3541 samelang = lang == getSpellLanguage(last);
3544 // if language change detected backstep is needed
3552 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3555 const_cast<Language *>(owner_->getFontSettings(
3556 inset_owner_->buffer().params(), from).language());
3557 if (lang == inset_owner_->buffer().params().language
3558 && !lyxrc.spellchecker_alt_lang.empty()) {
3560 string const lang_variety =
3561 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3562 lang->setCode(lang_code);
3563 lang->setVariety(lang_variety);
3569 void Paragraph::requestSpellCheck(pos_type pos)
3571 d->requestSpellCheck(pos == -1 ? size() : pos);
3575 bool Paragraph::needsSpellCheck() const
3577 SpellChecker::ChangeNumber speller_change_number = 0;
3578 if (theSpellChecker())
3579 speller_change_number = theSpellChecker()->changeNumber();
3580 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3581 d->speller_state_.needsCompleteRefresh(speller_change_number);
3583 return d->needsSpellCheck();
3587 bool Paragraph::Private::ignoreWord(docstring const & word) const
3589 // Ignore words with digits
3590 // FIXME: make this customizable
3591 // (note that some checkers ignore words with digits by default)
3592 docstring::const_iterator cit = word.begin();
3593 docstring::const_iterator const end = word.end();
3594 for (; cit != end; ++cit) {
3595 if (isNumber((*cit)))
3602 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3603 WordLangTuple & wl, docstring_list & suggestions,
3604 bool do_suggestion, bool check_learned) const
3606 SpellChecker::Result result = SpellChecker::WORD_OK;
3607 SpellChecker * speller = theSpellChecker();
3611 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3614 locateWord(from, to, WHOLE_WORD);
3615 if (from == to || from >= size())
3618 docstring word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3619 Language * lang = d->getSpellLanguage(from);
3621 wl = WordLangTuple(word, lang);
3626 if (needsSpellCheck() || check_learned) {
3627 if (!d->ignoreWord(word)) {
3628 bool const trailing_dot = to < size() && d->text_[to] == '.';
3629 result = speller->check(wl);
3630 if (SpellChecker::misspelled(result) && trailing_dot) {
3631 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3632 result = speller->check(wl);
3633 if (!SpellChecker::misspelled(result)) {
3634 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3636 from << ".." << to << "]");
3638 // spell check with dot appended failed
3639 // restore original word/lang value
3640 word = asString(from, to, AS_STR_INSETS | AS_STR_SKIPDELETE);
3641 wl = WordLangTuple(word, lang);
3645 d->setMisspelled(from, to, result);
3647 result = d->speller_state_.getState(from);
3650 bool const misspelled_ = SpellChecker::misspelled(result) ;
3651 if (misspelled_ && do_suggestion)
3652 speller->suggest(wl, suggestions);
3653 else if (misspelled_)
3654 LYXERR(Debug::GUI, "misspelled word: \"" <<
3656 from << ".." << to << "]");
3658 suggestions.clear();
3664 void Paragraph::Private::markMisspelledWords(
3665 pos_type const & first, pos_type const & last,
3666 SpellChecker::Result result,
3667 docstring const & word,
3668 SkipPositions const & skips)
3670 if (!SpellChecker::misspelled(result)) {
3671 setMisspelled(first, last, SpellChecker::WORD_OK);
3675 SpellChecker * speller = theSpellChecker();
3676 // locate and enumerate the error positions
3677 int nerrors = speller->numMisspelledWords();
3679 SkipPositionsIterator it = skips.begin();
3680 SkipPositionsIterator et = skips.end();
3681 for (int index = 0; index < nerrors; ++index) {
3684 speller->misspelledWord(index, wstart, wlen);
3685 /// should not happen if speller supports range checks
3686 if (!wlen) continue;
3687 docstring const misspelled = word.substr(wstart, wlen);
3688 wstart += first + numskipped;
3689 if (snext < wstart) {
3690 /// mark the range of correct spelling
3691 numskipped += countSkips(it, et, wstart);
3692 setMisspelled(snext,
3693 wstart - 1, SpellChecker::WORD_OK);
3695 snext = wstart + wlen;
3696 numskipped += countSkips(it, et, snext);
3697 /// mark the range of misspelling
3698 setMisspelled(wstart, snext, result);
3699 LYXERR(Debug::GUI, "misspelled word: \"" <<
3700 misspelled << "\" [" <<
3701 wstart << ".." << (snext-1) << "]");
3704 if (snext <= last) {
3705 /// mark the range of correct spelling at end
3706 setMisspelled(snext, last, SpellChecker::WORD_OK);
3711 void Paragraph::spellCheck() const
3713 SpellChecker * speller = theSpellChecker();
3714 if (!speller || !size() ||!needsSpellCheck())
3718 d->rangeOfSpellCheck(start, endpos);
3719 if (speller->canCheckParagraph()) {
3720 // loop until we leave the range
3721 for (pos_type first = start; first < endpos; ) {
3722 pos_type last = endpos;
3723 Private::SkipPositions skips;
3724 Language * lang = d->locateSpellRange(first, last, skips);
3725 if (first >= endpos)
3727 // start the spell checker on the unit of meaning
3728 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3729 WordLangTuple wl = WordLangTuple(word, lang);
3730 SpellChecker::Result result = word.size() ?
3731 speller->check(wl) : SpellChecker::WORD_OK;
3732 d->markMisspelledWords(first, last, result, word, skips);
3736 static docstring_list suggestions;
3737 pos_type to = endpos;
3738 while (start < endpos) {
3740 spellCheck(start, to, wl, suggestions, false);
3744 d->readySpellCheck();
3748 bool Paragraph::isMisspelled(pos_type pos) const
3750 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3754 string Paragraph::magicLabel() const
3757 ss << "magicparlabel-" << id();