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"
55 #include "support/debug.h"
56 #include "support/docstring_list.h"
57 #include "support/ExceptionMessage.h"
58 #include "support/gettext.h"
59 #include "support/lassert.h"
60 #include "support/lstrings.h"
61 #include "support/textutils.h"
67 using namespace lyx::support;
72 /// Inset identifier (above 0x10ffff, for ucs-4)
73 char_type const META_INSET = 0x200001;
77 /////////////////////////////////////////////////////////////////////
81 /////////////////////////////////////////////////////////////////////
83 class SpellResultRange {
85 SpellResultRange(FontSpan range, SpellChecker::Result result)
86 : range_(range), result_(result)
89 FontSpan const & range() const { return range_; }
91 void range(FontSpan const & r) { range_ = r; }
93 SpellChecker::Result result() const { return result_; }
95 void result(SpellChecker::Result r) { result_ = r; }
97 bool inside(pos_type pos) const { return range_.inside(pos); }
99 bool covered(FontSpan const & r) const
101 // 1. first of new range inside current range or
102 // 2. last of new range inside current range or
103 // 3. first of current range inside new range or
104 // 4. last of current range inside new range
105 return range_.inside(r.first) || range_.inside(r.last) ||
106 r.inside(range_.first) || r.inside(range_.last);
109 void shift(pos_type pos, int offset)
111 if (range_.first > pos) {
112 range_.first += offset;
113 range_.last += offset;
114 } else if (range_.last > pos) {
115 range_.last += offset;
120 SpellChecker::Result result_ ;
124 /////////////////////////////////////////////////////////////////////
128 /////////////////////////////////////////////////////////////////////
130 class SpellCheckerState {
132 SpellCheckerState() {
133 needs_refresh_ = true;
134 current_change_number_ = 0;
137 void setRange(FontSpan const fp, SpellChecker::Result state)
139 eraseCoveredRanges(fp);
140 if (state != SpellChecker::WORD_OK)
141 ranges_.push_back(SpellResultRange(fp, state));
144 void increasePosAfterPos(pos_type pos)
146 correctRangesAfterPos(pos, 1);
150 void decreasePosAfterPos(pos_type pos)
152 correctRangesAfterPos(pos, -1);
156 SpellChecker::Result getState(pos_type pos) const
158 SpellChecker::Result result = SpellChecker::WORD_OK;
159 RangesIterator et = ranges_.end();
160 RangesIterator it = ranges_.begin();
161 for (; it != et; ++it) {
162 if(it->inside(pos)) {
169 bool needsRefresh() const {
170 return needs_refresh_;
173 SpellChecker::ChangeNumber currentChangeNumber() const {
174 return current_change_number_;
177 void refreshRange(pos_type & first, pos_type & last) const {
178 first = refresh_.first;
179 last = refresh_.last;
182 void needsRefresh(pos_type pos) {
183 if (needs_refresh_ && pos != -1) {
184 if (pos < refresh_.first)
185 refresh_.first = pos;
186 if (pos > refresh_.last)
188 } else if (pos != -1) {
189 refresh_.first = pos;
192 needs_refresh_ = pos != -1;
195 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
196 needs_refresh_ = true;
199 current_change_number_ = change_number;
203 typedef vector<SpellResultRange> Ranges;
204 typedef Ranges::const_iterator RangesIterator;
206 /// the area of the paragraph with pending spell check
209 /// spell state cache version number
210 SpellChecker::ChangeNumber current_change_number_;
213 void eraseCoveredRanges(FontSpan const fp)
216 RangesIterator et = ranges_.end();
217 RangesIterator it = ranges_.begin();
218 for (; it != et; ++it) {
219 if (!it->covered(fp))
220 result.push_back(SpellResultRange(it->range(), it->result()));
225 void correctRangesAfterPos(pos_type pos, int offset)
227 RangesIterator et = ranges_.end();
228 Ranges::iterator it = ranges_.begin();
229 for (; it != et; ++it) {
230 it->shift(pos, offset);
236 /////////////////////////////////////////////////////////////////////
238 // Paragraph::Private
240 /////////////////////////////////////////////////////////////////////
242 class Paragraph::Private
246 Private(Paragraph * owner, Layout const & layout);
247 /// "Copy constructor"
248 Private(Private const &, Paragraph * owner);
249 /// Copy constructor from \p beg to \p end
250 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
253 void insertChar(pos_type pos, char_type c, Change const & change);
255 /// Output the surrogate pair formed by \p c and \p next to \p os.
256 /// \return the number of characters written.
257 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
258 OutputParams const &);
260 /// Output a space in appropriate formatting (or a surrogate pair
261 /// if the next character is a combining character).
262 /// \return whether a surrogate pair was output.
263 bool simpleTeXBlanks(OutputParams const &,
264 odocstream &, TexRow & texrow,
266 unsigned int & column,
268 Layout const & style);
270 /// Output consecutive unicode chars, belonging to the same script as
271 /// specified by the latex macro \p ltx, to \p os starting from \p i.
272 /// \return the number of characters written.
273 int writeScriptChars(odocstream & os, docstring const & ltx,
274 Change const &, Encoding const &, pos_type & i);
276 /// This could go to ParagraphParameters if we want to.
277 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
278 OutputParams const &) const;
280 /// This could go to ParagraphParameters if we want to.
281 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
282 OutputParams const &) const;
285 void latexInset(BufferParams const &,
287 TexRow & texrow, OutputParams &,
290 Font const & outerfont,
292 Change & running_change,
293 Layout const & style,
295 unsigned int & column);
298 void latexSpecialChar(
300 OutputParams const & runparams,
301 Font const & running_font,
302 Change const & running_change,
303 Layout const & style,
305 unsigned int & column);
312 unsigned int & column);
314 bool latexSpecialTypewriter(
318 unsigned int & column);
320 bool latexSpecialPhrase(
323 unsigned int & column,
324 OutputParams const & runparams);
327 void validate(LaTeXFeatures & features) const;
329 /// Checks if the paragraph contains only text and no inset or font change.
330 bool onlyText(Buffer const & buf, Font const & outerfont,
331 pos_type initial) const;
333 /// match a string against a particular point in the paragraph
334 bool isTextAt(string const & str, pos_type pos) const;
336 /// a vector of speller skip positions
337 typedef vector<FontSpan> SkipPositions;
338 typedef SkipPositions::const_iterator SkipPositionsIterator;
340 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
342 Language * getSpellLanguage(pos_type const from) const;
344 Language * locateSpellRange(pos_type & from, pos_type & to,
345 SkipPositions & skips) const;
347 bool hasSpellerChange() const {
348 SpellChecker::ChangeNumber speller_change_number = 0;
349 if (theSpellChecker())
350 speller_change_number = theSpellChecker()->changeNumber();
351 return speller_change_number > speller_state_.currentChangeNumber();
354 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
356 pos_type textsize = owner_->size();
357 // check for sane arguments
358 if (to < from || from >= textsize)
360 FontSpan fp = FontSpan(from, to);
361 // don't mark end of paragraph
362 if (fp.last >= textsize)
363 fp.last = textsize - 1;
364 speller_state_.setRange(fp, state);
367 void requestSpellCheck(pos_type pos) {
368 speller_state_.needsRefresh(pos);
371 void readySpellCheck() {
372 speller_state_.needsRefresh(-1);
375 bool needsSpellCheck() const
377 return speller_state_.needsRefresh();
380 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
382 speller_state_.refreshRange(first, last);
384 last = owner_->size();
387 pos_type endpos = last;
388 owner_->locateWord(first, endpos, WHOLE_WORD);
391 owner_->locateWord(last, endpos, WHOLE_WORD);
396 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
400 while (it != et && it->first < start) {
401 int skip = it->last - it->first + 1;
409 void markMisspelledWords(pos_type const & first, pos_type const & last,
410 SpellChecker::Result result,
411 docstring const & word,
412 SkipPositions const & skips);
414 InsetCode ownerCode() const
416 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
419 /// Which Paragraph owns us?
423 Inset const * inset_owner_;
432 ParagraphParameters params_;
434 /// for recording and looking up changes
438 InsetList insetlist_;
441 pos_type begin_of_body_;
443 typedef docstring TextContainer;
447 typedef set<docstring> Words;
448 typedef map<Language, Words> LangWordsMap;
452 Layout const * layout_;
454 SpellCheckerState speller_state_;
460 struct special_phrase {
466 special_phrase const special_phrases[] = {
467 { "LyX", from_ascii("\\LyX{}"), false },
468 { "TeX", from_ascii("\\TeX{}"), true },
469 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
470 { "LaTeX", from_ascii("\\LaTeX{}"), true },
473 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
478 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
479 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
485 // Initialization of the counter for the paragraph id's,
487 // FIXME: There should be a more intelligent way to generate and use the
488 // paragraph ids per buffer instead a global static counter for all InsetText
489 // in the running program.
490 static int paragraph_id = -1;
492 Paragraph::Private::Private(Private const & p, Paragraph * owner)
493 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
494 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
495 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
498 id_ = ++paragraph_id;
499 requestSpellCheck(p.text_.size());
503 Paragraph::Private::Private(Private const & p, Paragraph * owner,
504 pos_type beg, pos_type end)
505 : owner_(owner), inset_owner_(p.inset_owner_),
506 params_(p.params_), changes_(p.changes_),
507 insetlist_(p.insetlist_, beg, end),
508 begin_of_body_(p.begin_of_body_), words_(p.words_),
511 id_ = ++paragraph_id;
512 if (beg >= pos_type(p.text_.size()))
514 text_ = p.text_.substr(beg, end - beg);
516 FontList::const_iterator fcit = fontlist_.begin();
517 FontList::const_iterator fend = fontlist_.end();
518 for (; fcit != fend; ++fcit) {
519 if (fcit->pos() < beg)
521 if (fcit->pos() >= end) {
522 // Add last entry in the fontlist_.
523 fontlist_.set(text_.size() - 1, fcit->font());
526 // Add a new entry in the fontlist_.
527 fontlist_.set(fcit->pos() - beg, fcit->font());
529 requestSpellCheck(p.text_.size());
533 void Paragraph::addChangesToToc(DocIterator const & cdit,
534 Buffer const & buf) const
536 d->changes_.addToToc(cdit, buf);
540 bool Paragraph::isDeleted(pos_type start, pos_type end) const
542 LASSERT(start >= 0 && start <= size(), /**/);
543 LASSERT(end > start && end <= size() + 1, /**/);
545 return d->changes_.isDeleted(start, end);
549 bool Paragraph::isChanged(pos_type start, pos_type end) const
551 LASSERT(start >= 0 && start <= size(), /**/);
552 LASSERT(end > start && end <= size() + 1, /**/);
554 return d->changes_.isChanged(start, end);
558 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
560 // keep the logic here in sync with the logic of eraseChars()
564 Change const change = d->changes_.lookup(size());
565 return change.inserted() && change.currentAuthor();
569 void Paragraph::setChange(Change const & change)
571 // beware of the imaginary end-of-par character!
572 d->changes_.set(change, 0, size() + 1);
575 * Propagate the change recursively - but not in case of DELETED!
577 * Imagine that your co-author makes changes in an existing inset. He
578 * sends your document to you and you come to the conclusion that the
579 * inset should go completely. If you erase it, LyX must not delete all
580 * text within the inset. Otherwise, the change tracked insertions of
581 * your co-author get lost and there is no way to restore them later.
583 * Conclusion: An inset's content should remain untouched if you delete it
586 if (!change.deleted()) {
587 for (pos_type pos = 0; pos < size(); ++pos) {
588 if (Inset * inset = getInset(pos))
589 inset->setChange(change);
595 void Paragraph::setChange(pos_type pos, Change const & change)
597 LASSERT(pos >= 0 && pos <= size(), /**/);
598 d->changes_.set(change, pos);
600 // see comment in setChange(Change const &) above
601 if (!change.deleted() && pos < size())
602 if (Inset * inset = getInset(pos))
603 inset->setChange(change);
607 Change const & Paragraph::lookupChange(pos_type pos) const
609 LASSERT(pos >= 0 && pos <= size(), /**/);
610 return d->changes_.lookup(pos);
614 void Paragraph::acceptChanges(pos_type start, pos_type end)
616 LASSERT(start >= 0 && start <= size(), /**/);
617 LASSERT(end > start && end <= size() + 1, /**/);
619 for (pos_type pos = start; pos < end; ++pos) {
620 switch (lookupChange(pos).type) {
621 case Change::UNCHANGED:
622 // accept changes in nested inset
623 if (Inset * inset = getInset(pos))
624 inset->acceptChanges();
627 case Change::INSERTED:
628 d->changes_.set(Change(Change::UNCHANGED), pos);
629 // also accept changes in nested inset
630 if (Inset * inset = getInset(pos))
631 inset->acceptChanges();
634 case Change::DELETED:
635 // Suppress access to non-existent
636 // "end-of-paragraph char"
638 eraseChar(pos, false);
649 void Paragraph::rejectChanges(pos_type start, pos_type end)
651 LASSERT(start >= 0 && start <= size(), /**/);
652 LASSERT(end > start && end <= size() + 1, /**/);
654 for (pos_type pos = start; pos < end; ++pos) {
655 switch (lookupChange(pos).type) {
656 case Change::UNCHANGED:
657 // reject changes in nested inset
658 if (Inset * inset = getInset(pos))
659 inset->rejectChanges();
662 case Change::INSERTED:
663 // Suppress access to non-existent
664 // "end-of-paragraph char"
666 eraseChar(pos, false);
672 case Change::DELETED:
673 d->changes_.set(Change(Change::UNCHANGED), pos);
675 // Do NOT reject changes within a deleted inset!
676 // There may be insertions of a co-author inside of it!
684 void Paragraph::Private::insertChar(pos_type pos, char_type c,
685 Change const & change)
687 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
690 changes_.insert(change, pos);
692 // This is actually very common when parsing buffers (and
693 // maybe inserting ascii text)
694 if (pos == pos_type(text_.size())) {
695 // when appending characters, no need to update tables
697 // but we want spell checking
698 requestSpellCheck(pos);
702 text_.insert(text_.begin() + pos, c);
704 // Update the font table.
705 fontlist_.increasePosAfterPos(pos);
708 insetlist_.increasePosAfterPos(pos);
710 // Update list of misspelled positions
711 speller_state_.increasePosAfterPos(pos);
715 bool Paragraph::insertInset(pos_type pos, Inset * inset,
716 Change const & change)
718 LASSERT(inset, /**/);
719 LASSERT(pos >= 0 && pos <= size(), /**/);
721 // Paragraph::insertInset() can be used in cut/copy/paste operation where
722 // d->inset_owner_ is not set yet.
723 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
726 d->insertChar(pos, META_INSET, change);
727 LASSERT(d->text_[pos] == META_INSET, /**/);
729 // Add a new entry in the insetlist_.
730 d->insetlist_.insert(inset, pos);
732 // Some insets require run of spell checker
733 requestSpellCheck(pos);
738 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
740 LASSERT(pos >= 0 && pos <= size(), return false);
742 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
745 Change change = d->changes_.lookup(pos);
747 // set the character to DELETED if
748 // a) it was previously unchanged or
749 // b) it was inserted by a co-author
751 if (!change.changed() ||
752 (change.inserted() && !change.currentAuthor())) {
753 setChange(pos, Change(Change::DELETED));
757 if (change.deleted())
761 // Don't physically access the imaginary end-of-paragraph character.
762 // eraseChar() can only mark it as DELETED. A physical deletion of
763 // end-of-par must be handled externally.
769 d->changes_.erase(pos);
771 // if it is an inset, delete the inset entry
772 if (d->text_[pos] == META_INSET)
773 d->insetlist_.erase(pos);
775 d->text_.erase(d->text_.begin() + pos);
777 // Update the fontlist_
778 d->fontlist_.erase(pos);
780 // Update the insetlist_
781 d->insetlist_.decreasePosAfterPos(pos);
783 // Update list of misspelled positions
784 d->speller_state_.decreasePosAfterPos(pos);
790 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
792 LASSERT(start >= 0 && start <= size(), /**/);
793 LASSERT(end >= start && end <= size() + 1, /**/);
796 for (pos_type count = end - start; count; --count) {
797 if (!eraseChar(i, trackChanges))
804 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
805 char_type next, OutputParams const & runparams)
807 // Writing next here may circumvent a possible font change between
808 // c and next. Since next is only output if it forms a surrogate pair
809 // with c we can ignore this:
810 // A font change inside a surrogate pair does not make sense and is
811 // hopefully impossible to input.
812 // FIXME: change tracking
813 // Is this correct WRT change tracking?
814 Encoding const & encoding = *(runparams.encoding);
815 docstring const latex1 = encoding.latexChar(next);
816 docstring const latex2 = encoding.latexChar(c);
817 if (docstring(1, next) == latex1) {
818 // the encoding supports the combination
819 os << latex2 << latex1;
820 return latex1.length() + latex2.length();
821 } else if (runparams.local_font &&
822 runparams.local_font->language()->lang() == "polutonikogreek") {
823 // polutonikogreek only works without the brackets
824 os << latex1 << latex2;
825 return latex1.length() + latex2.length();
827 os << latex1 << '{' << latex2 << '}';
828 return latex1.length() + latex2.length() + 2;
832 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
833 odocstream & os, TexRow & texrow,
835 unsigned int & column,
837 Layout const & style)
839 if (style.pass_thru || runparams.pass_thru)
842 if (i + 1 < int(text_.size())) {
843 char_type next = text_[i + 1];
844 if (Encodings::isCombiningChar(next)) {
845 // This space has an accent, so we must always output it.
846 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
851 if (runparams.linelen > 0
852 && column > runparams.linelen
854 && text_[i - 1] != ' '
855 && (i + 1 < int(text_.size()))
856 // same in FreeSpacing mode
857 && !owner_->isFreeSpacing()
858 // In typewriter mode, we want to avoid
859 // ! . ? : at the end of a line
860 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
861 && (text_[i - 1] == '.'
862 || text_[i - 1] == '?'
863 || text_[i - 1] == ':'
864 || text_[i - 1] == '!'))) {
867 texrow.start(owner_->id(), i + 1);
869 } else if (style.free_spacing) {
878 int Paragraph::Private::writeScriptChars(odocstream & os,
879 docstring const & ltx,
880 Change const & runningChange,
881 Encoding const & encoding,
884 // FIXME: modifying i here is not very nice...
886 // We only arrive here when a proper language for character text_[i] has
887 // not been specified (i.e., it could not be translated in the current
888 // latex encoding) or its latex translation has been forced, and it
889 // belongs to a known script.
890 // Parameter ltx contains the latex translation of text_[i] as specified
891 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
892 // The latex macro name "textXXX" specifies the script to which text_[i]
893 // belongs and we use it in order to check whether characters from the
894 // same script immediately follow, such that we can collect them in a
895 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
896 // for the first char but only "<spec>" for all subsequent chars.
897 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
898 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
899 string script = to_ascii(ltx.substr(1, brace1 - 1));
902 bool closing_brace = true;
903 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
904 // Correct encoding is being used, so we can avoid \textgreek.
907 closing_brace = false;
909 os << ltx.substr(pos, length);
910 int size = text_.size();
911 while (i + 1 < size) {
912 char_type const next = text_[i + 1];
913 // Stop here if next character belongs to another script
914 // or there is a change in change tracking status.
915 if (!Encodings::isKnownScriptChar(next, script) ||
916 runningChange != owner_->lookupChange(i + 1))
920 FontList::const_iterator cit = fontlist_.begin();
921 FontList::const_iterator end = fontlist_.end();
922 for (; cit != end; ++cit) {
923 if (cit->pos() >= i && !found) {
924 prev_font = cit->font();
927 if (cit->pos() >= i + 1)
930 // Stop here if there is a font attribute or encoding change.
931 if (found && cit != end && prev_font != cit->font())
933 docstring const latex = encoding.latexChar(next);
934 docstring::size_type const b1 =
935 latex.find_first_of(from_ascii("{"));
936 docstring::size_type const b2 =
937 latex.find_last_of(from_ascii("}"));
938 int const len = b2 - b1 - 1;
939 os << latex.substr(b1 + 1, len);
951 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
953 pos_type const len = str.length();
955 // is the paragraph large enough?
956 if (pos + len > int(text_.size()))
959 // does the wanted text start at point?
960 for (string::size_type i = 0; i < str.length(); ++i) {
961 // Caution: direct comparison of characters works only
962 // because str is pure ASCII.
963 if (str[i] != text_[pos + i])
967 return fontlist_.hasChangeInRange(pos, len);
971 void Paragraph::Private::latexInset(BufferParams const & bparams,
974 OutputParams & runparams,
977 Font const & outerfont,
979 Change & running_change,
980 Layout const & style,
982 unsigned int & column)
984 Inset * inset = owner_->getInset(i);
985 LASSERT(inset, /**/);
987 if (style.pass_thru) {
988 inset->plaintext(os, runparams);
992 // FIXME: move this to InsetNewline::latex
993 if (inset->lyxCode() == NEWLINE_CODE) {
994 // newlines are handled differently here than
995 // the default in simpleTeXSpecialChars().
996 if (!style.newline_allowed) {
1000 column += running_font.latexWriteEndChanges(
1001 os, bparams, runparams,
1002 basefont, basefont);
1006 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1009 basefont = owner_->getLayoutFont(bparams, outerfont);
1010 running_font = basefont;
1012 if (runparams.moving_arg)
1017 texrow.start(owner_->id(), i + 1);
1021 if (owner_->isDeleted(i)) {
1022 if( ++runparams.inDeletedInset == 1)
1023 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1026 if (inset->canTrackChanges()) {
1027 column += Changes::latexMarkChange(os, bparams, running_change,
1028 Change(Change::UNCHANGED), runparams);
1029 running_change = Change(Change::UNCHANGED);
1033 odocstream::pos_type const len = os.tellp();
1035 if (inset->forceLTR()
1036 && running_font.isRightToLeft()
1037 // ERT is an exception, it should be output with no
1038 // decorations at all
1039 && inset->lyxCode() != ERT_CODE) {
1040 if (running_font.language()->lang() == "farsi")
1047 // FIXME: Bug: we can have an empty font change here!
1048 // if there has just been a font change, we are going to close it
1049 // right now, which means stupid latex code like \textsf{}. AFAIK,
1050 // this does not harm dvi output. A minor bug, thus (JMarc)
1052 // Some insets cannot be inside a font change command.
1053 // However, even such insets *can* be placed in \L or \R
1054 // or their equivalents (for RTL language switches), so we don't
1055 // close the language in those cases.
1056 // ArabTeX, though, cannot handle this special behavior, it seems.
1057 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1058 || running_font.language()->lang() == "arabic_arabtex";
1059 if (open_font && inset->noFontChange()) {
1060 bool closeLanguage = arabtex
1061 || basefont.isRightToLeft() == running_font.isRightToLeft();
1062 unsigned int count = running_font.latexWriteEndChanges(os,
1063 bparams, runparams, basefont, basefont, closeLanguage);
1065 // if any font properties were closed, update the running_font,
1066 // making sure, however, to leave the language as it was
1068 // FIXME: probably a better way to keep track of the old
1069 // language, than copying the entire font?
1070 Font const copy_font(running_font);
1071 basefont = owner_->getLayoutFont(bparams, outerfont);
1072 running_font = basefont;
1074 running_font.setLanguage(copy_font.language());
1075 // leave font open if language is still open
1076 open_font = (running_font.language() == basefont.language());
1078 runparams.local_font = &basefont;
1085 tmp = inset->latex(os, runparams);
1086 } catch (EncodingException & e) {
1087 // add location information and throw again.
1094 if (running_font.language()->lang() == "farsi")
1101 texrow.newlines(tmp);
1102 texrow.start(owner_->id(), i + 1);
1105 column += os.tellp() - len;
1108 if (owner_->isDeleted(i))
1109 --runparams.inDeletedInset;
1113 void Paragraph::Private::latexSpecialChar(
1115 OutputParams const & runparams,
1116 Font const & running_font,
1117 Change const & running_change,
1118 Layout const & style,
1120 unsigned int & column)
1122 char_type const c = text_[i];
1124 if (style.pass_thru || runparams.pass_thru) {
1126 // FIXME UNICODE: This can fail if c cannot
1127 // be encoded in the current encoding.
1132 // If T1 font encoding is used, use the special
1133 // characters it provides.
1134 // NOTE: some languages reset the font encoding
1136 if (!running_font.language()->internalFontEncoding()
1137 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1140 // \tt font needs special treatment
1141 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1142 && latexSpecialTypewriter(c, os, i, column))
1145 // Otherwise, we use what LaTeX provides us.
1148 os << "\\textbackslash{}";
1152 os << "\\textless{}";
1156 os << "\\textgreater{}";
1160 os << "\\textbar{}";
1167 os << "\\char`\\\"{}";
1172 case '%': case '#': case '{':
1180 os << "\\textasciitilde{}";
1185 os << "\\textasciicircum{}";
1192 // avoid being mistaken for optional arguments
1200 // Blanks are printed before font switching.
1201 // Sure? I am not! (try nice-latex)
1202 // I am sure it's correct. LyX might be smarter
1203 // in the future, but for now, nothing wrong is
1209 if (latexSpecialPhrase(os, i, column, runparams))
1215 Encoding const & encoding = *(runparams.encoding);
1216 if (i + 1 < int(text_.size())) {
1217 char_type next = text_[i + 1];
1218 if (Encodings::isCombiningChar(next)) {
1219 column += latexSurrogatePair(os, c, next, runparams) - 1;
1225 docstring const latex = encoding.latexChar(c);
1226 if (Encodings::isKnownScriptChar(c, script)
1227 && prefixIs(latex, from_ascii("\\" + script)))
1228 column += writeScriptChars(os, latex,
1229 running_change, encoding, i) - 1;
1230 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1231 // Prevent eating of a following
1232 // space or command corruption by
1233 // following characters
1234 column += latex.length() + 1;
1235 os << latex << "{}";
1237 column += latex.length() - 1;
1245 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1246 pos_type i, unsigned int & column)
1252 // In T1 encoding, these characters exist
1253 // but we should avoid ligatures
1254 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1256 os << "\\textcompwordmark{}";
1263 // soul.sty breaks with \char`\"
1264 os << "\\textquotedbl{}";
1273 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1274 pos_type i, unsigned int & column)
1278 // within \ttfamily, "--" is merged to "-" (no endash)
1279 // so we avoid this rather irritating ligature
1280 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1287 // everything else has to be checked separately
1288 // (depending on the encoding)
1295 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1296 unsigned int & column, OutputParams const & runparams)
1298 // FIXME: if we have "LaTeX" with a font
1299 // change in the middle (before the 'T', then
1300 // the "TeX" part is still special cased.
1301 // Really we should only operate this on
1302 // "words" for some definition of word
1304 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1305 if (!isTextAt(special_phrases[pnr].phrase, i))
1307 if (runparams.moving_arg)
1309 os << special_phrases[pnr].macro;
1310 i += special_phrases[pnr].phrase.length() - 1;
1311 column += special_phrases[pnr].macro.length() - 1;
1318 void Paragraph::Private::validate(LaTeXFeatures & features) const
1320 if (layout_->inpreamble && inset_owner_) {
1321 Buffer const & buf = inset_owner_->buffer();
1322 BufferParams const & bp = buf.params();
1325 odocstringstream ods;
1326 // we have to provide all the optional arguments here, even though
1327 // the last one is the only one we care about.
1328 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1329 docstring const d = ods.str();
1331 // this will have "{" at the beginning, but not at the end
1332 string const content = to_utf8(d);
1333 string const cmd = layout_->latexname();
1334 features.addPreambleSnippet("\\" + cmd + content + "}");
1338 if (features.runparams().flavor == OutputParams::HTML
1339 && layout_->htmltitle()) {
1340 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1343 // check the params.
1344 if (!params_.spacing().isDefault())
1345 features.require("setspace");
1348 features.useLayout(layout_->name());
1351 fontlist_.validate(features);
1353 // then the indentation
1354 if (!params_.leftIndent().zero())
1355 features.require("ParagraphLeftIndent");
1358 InsetList::const_iterator icit = insetlist_.begin();
1359 InsetList::const_iterator iend = insetlist_.end();
1360 for (; icit != iend; ++icit) {
1362 icit->inset->validate(features);
1363 if (layout_->needprotect &&
1364 icit->inset->lyxCode() == FOOT_CODE)
1365 features.require("NeedLyXFootnoteCode");
1369 // then the contents
1370 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1371 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1372 if (!special_phrases[pnr].builtin
1373 && isTextAt(special_phrases[pnr].phrase, i)) {
1374 features.require(special_phrases[pnr].phrase);
1378 Encodings::validate(text_[i], features);
1382 /////////////////////////////////////////////////////////////////////
1386 /////////////////////////////////////////////////////////////////////
1389 Layout const emptyParagraphLayout;
1392 Paragraph::Paragraph()
1393 : d(new Paragraph::Private(this, emptyParagraphLayout))
1400 Paragraph::Paragraph(Paragraph const & par)
1401 : itemdepth(par.itemdepth),
1402 d(new Paragraph::Private(*par.d, this))
1408 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1409 : itemdepth(par.itemdepth),
1410 d(new Paragraph::Private(*par.d, this, beg, end))
1416 Paragraph & Paragraph::operator=(Paragraph const & par)
1418 // needed as we will destroy the private part before copying it
1420 itemdepth = par.itemdepth;
1424 d = new Private(*par.d, this);
1431 Paragraph::~Paragraph()
1440 // this shall be called just before every "os << ..." action.
1441 void flushString(ostream & os, docstring & s)
1450 void Paragraph::write(ostream & os, BufferParams const & bparams,
1451 depth_type & dth) const
1453 // The beginning or end of a deeper (i.e. nested) area?
1454 if (dth != d->params_.depth()) {
1455 if (d->params_.depth() > dth) {
1456 while (d->params_.depth() > dth) {
1457 os << "\n\\begin_deeper";
1461 while (d->params_.depth() < dth) {
1462 os << "\n\\end_deeper";
1468 // First write the layout
1469 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1471 d->params_.write(os);
1473 Font font1(inherit_font, bparams.language);
1475 Change running_change = Change(Change::UNCHANGED);
1477 // this string is used as a buffer to avoid repetitive calls
1478 // to to_utf8(), which turn out to be expensive (JMarc)
1479 docstring write_buffer;
1482 for (pos_type i = 0; i <= size(); ++i) {
1484 Change const change = lookupChange(i);
1485 if (change != running_change)
1486 flushString(os, write_buffer);
1487 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1488 running_change = change;
1493 // Write font changes
1494 Font font2 = getFontSettings(bparams, i);
1495 if (font2 != font1) {
1496 flushString(os, write_buffer);
1497 font2.lyxWriteChanges(font1, os);
1502 char_type const c = d->text_[i];
1505 if (Inset const * inset = getInset(i)) {
1506 flushString(os, write_buffer);
1507 if (inset->directWrite()) {
1508 // international char, let it write
1509 // code directly so it's shorter in
1515 os << "\\begin_inset ";
1517 os << "\n\\end_inset\n\n";
1523 flushString(os, write_buffer);
1524 os << "\n\\backslash\n";
1528 flushString(os, write_buffer);
1529 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1536 if ((column > 70 && c == ' ')
1538 flushString(os, write_buffer);
1542 // this check is to amend a bug. LyX sometimes
1543 // inserts '\0' this could cause problems.
1545 write_buffer.push_back(c);
1547 LYXERR0("NUL char in structure.");
1553 flushString(os, write_buffer);
1554 os << "\n\\end_layout\n";
1558 void Paragraph::validate(LaTeXFeatures & features) const
1560 d->validate(features);
1564 void Paragraph::insert(pos_type start, docstring const & str,
1565 Font const & font, Change const & change)
1567 for (size_t i = 0, n = str.size(); i != n ; ++i)
1568 insertChar(start + i, str[i], font, change);
1572 void Paragraph::appendChar(char_type c, Font const & font,
1573 Change const & change)
1576 d->changes_.insert(change, d->text_.size());
1577 // when appending characters, no need to update tables
1578 d->text_.push_back(c);
1579 setFont(d->text_.size() - 1, font);
1583 void Paragraph::appendString(docstring const & s, Font const & font,
1584 Change const & change)
1586 pos_type end = s.size();
1587 size_t oldsize = d->text_.size();
1588 size_t newsize = oldsize + end;
1589 size_t capacity = d->text_.capacity();
1590 if (newsize >= capacity)
1591 d->text_.reserve(max(capacity + 100, newsize));
1593 // when appending characters, no need to update tables
1596 // FIXME: Optimize this!
1597 for (size_t i = oldsize; i != newsize; ++i) {
1599 d->changes_.insert(change, i);
1601 d->fontlist_.set(oldsize, font);
1602 d->fontlist_.set(newsize - 1, font);
1606 void Paragraph::insertChar(pos_type pos, char_type c,
1609 d->insertChar(pos, c, Change(trackChanges ?
1610 Change::INSERTED : Change::UNCHANGED));
1614 void Paragraph::insertChar(pos_type pos, char_type c,
1615 Font const & font, bool trackChanges)
1617 d->insertChar(pos, c, Change(trackChanges ?
1618 Change::INSERTED : Change::UNCHANGED));
1623 void Paragraph::insertChar(pos_type pos, char_type c,
1624 Font const & font, Change const & change)
1626 d->insertChar(pos, c, change);
1631 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1632 Font const & font, Change const & change)
1634 bool const success = insertInset(pos, inset, change);
1635 // Set the font/language of the inset...
1641 void Paragraph::resetFonts(Font const & font)
1643 d->fontlist_.clear();
1644 d->fontlist_.set(0, font);
1645 d->fontlist_.set(d->text_.size() - 1, font);
1648 // Gets uninstantiated font setting at position.
1649 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1653 LYXERR0("pos: " << pos << " size: " << size());
1654 LASSERT(pos <= size(), /**/);
1657 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1658 if (cit != d->fontlist_.end())
1661 if (pos == size() && !empty())
1662 return getFontSettings(bparams, pos - 1);
1664 // Optimisation: avoid a full font instantiation if there is no
1665 // language change from previous call.
1666 static Font previous_font;
1667 static Language const * previous_lang = 0;
1668 Language const * lang = getParLanguage(bparams);
1669 if (lang != previous_lang) {
1670 previous_lang = lang;
1671 previous_font = Font(inherit_font, lang);
1673 return previous_font;
1677 FontSpan Paragraph::fontSpan(pos_type pos) const
1679 LASSERT(pos <= size(), /**/);
1682 FontList::const_iterator cit = d->fontlist_.begin();
1683 FontList::const_iterator end = d->fontlist_.end();
1684 for (; cit != end; ++cit) {
1685 if (cit->pos() >= pos) {
1686 if (pos >= beginOfBody())
1687 return FontSpan(max(start, beginOfBody()),
1690 return FontSpan(start,
1691 min(beginOfBody() - 1,
1694 start = cit->pos() + 1;
1697 // This should not happen, but if so, we take no chances.
1698 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1699 return FontSpan(pos, pos);
1703 // Gets uninstantiated font setting at position 0
1704 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1706 if (!empty() && !d->fontlist_.empty())
1707 return d->fontlist_.begin()->font();
1709 // Optimisation: avoid a full font instantiation if there is no
1710 // language change from previous call.
1711 static Font previous_font;
1712 static Language const * previous_lang = 0;
1713 if (bparams.language != previous_lang) {
1714 previous_lang = bparams.language;
1715 previous_font = Font(inherit_font, bparams.language);
1718 return previous_font;
1722 // Gets the fully instantiated font at a given position in a paragraph
1723 // This is basically the same function as Text::GetFont() in text2.cpp.
1724 // The difference is that this one is used for generating the LaTeX file,
1725 // and thus cosmetic "improvements" are disallowed: This has to deliver
1726 // the true picture of the buffer. (Asger)
1727 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1728 Font const & outerfont) const
1730 LASSERT(pos >= 0, /**/);
1732 Font font = getFontSettings(bparams, pos);
1734 pos_type const body_pos = beginOfBody();
1735 FontInfo & fi = font.fontInfo();
1737 fi.realize(d->layout_->labelfont);
1739 fi.realize(d->layout_->font);
1741 fi.realize(outerfont.fontInfo());
1742 fi.realize(bparams.getFont().fontInfo());
1748 Font const Paragraph::getLabelFont
1749 (BufferParams const & bparams, Font const & outerfont) const
1751 FontInfo tmpfont = d->layout_->labelfont;
1752 tmpfont.realize(outerfont.fontInfo());
1753 tmpfont.realize(bparams.getFont().fontInfo());
1754 return Font(tmpfont, getParLanguage(bparams));
1758 Font const Paragraph::getLayoutFont
1759 (BufferParams const & bparams, Font const & outerfont) const
1761 FontInfo tmpfont = d->layout_->font;
1762 tmpfont.realize(outerfont.fontInfo());
1763 tmpfont.realize(bparams.getFont().fontInfo());
1764 return Font(tmpfont, getParLanguage(bparams));
1768 /// Returns the height of the highest font in range
1769 FontSize Paragraph::highestFontInRange
1770 (pos_type startpos, pos_type endpos, FontSize def_size) const
1772 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1776 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1778 char_type c = d->text_[pos];
1779 if (!lyxrc.rtl_support)
1809 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1815 void Paragraph::setFont(pos_type pos, Font const & font)
1817 LASSERT(pos <= size(), /**/);
1819 // First, reduce font against layout/label font
1820 // Update: The setCharFont() routine in text2.cpp already
1821 // reduces font, so we don't need to do that here. (Asger)
1823 d->fontlist_.set(pos, font);
1827 void Paragraph::makeSameLayout(Paragraph const & par)
1829 d->layout_ = par.d->layout_;
1830 d->params_ = par.d->params_;
1834 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1836 if (isFreeSpacing())
1842 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1843 if (eraseChar(pos, trackChanges))
1849 return count > 0 || pos > 0;
1853 bool Paragraph::hasSameLayout(Paragraph const & par) const
1855 return par.d->layout_ == d->layout_
1856 && d->params_.sameLayout(par.d->params_);
1860 depth_type Paragraph::getDepth() const
1862 return d->params_.depth();
1866 depth_type Paragraph::getMaxDepthAfter() const
1868 if (d->layout_->isEnvironment())
1869 return d->params_.depth() + 1;
1871 return d->params_.depth();
1875 char Paragraph::getAlign() const
1877 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1878 return d->layout_->align;
1880 return d->params_.align();
1884 docstring const & Paragraph::labelString() const
1886 return d->params_.labelString();
1890 // the next two functions are for the manual labels
1891 docstring const Paragraph::getLabelWidthString() const
1893 if (d->layout_->margintype == MARGIN_MANUAL
1894 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1895 return d->params_.labelWidthString();
1897 return _("Senseless with this layout!");
1901 void Paragraph::setLabelWidthString(docstring const & s)
1903 d->params_.labelWidthString(s);
1907 docstring Paragraph::expandLabel(Layout const & layout,
1908 BufferParams const & bparams) const
1910 return expandParagraphLabel(layout, bparams, true);
1914 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1915 BufferParams const & bparams) const
1917 return expandParagraphLabel(layout, bparams, false);
1921 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1922 BufferParams const & bparams, bool process_appendix) const
1924 DocumentClass const & tclass = bparams.documentClass();
1925 string const & lang = getParLanguage(bparams)->code();
1926 bool const in_appendix = process_appendix && d->params_.appendix();
1927 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1929 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1930 && !layout.counter.empty())
1931 return tclass.counters().theCounter(layout.counter, lang);
1933 // handle 'inherited level parts' in 'fmt',
1934 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1935 size_t const i = fmt.find('@', 0);
1936 if (i != docstring::npos) {
1937 size_t const j = fmt.find('@', i + 1);
1938 if (j != docstring::npos) {
1939 docstring parent(fmt, i + 1, j - i - 1);
1940 docstring label = from_ascii("??");
1941 if (tclass.hasLayout(parent))
1942 docstring label = expandParagraphLabel(tclass[parent], bparams,
1944 fmt = docstring(fmt, 0, i) + label
1945 + docstring(fmt, j + 1, docstring::npos);
1949 return tclass.counters().counterLabel(fmt, lang);
1953 void Paragraph::applyLayout(Layout const & new_layout)
1955 d->layout_ = &new_layout;
1956 LyXAlignment const oldAlign = d->params_.align();
1958 if (!(oldAlign & d->layout_->alignpossible)) {
1959 frontend::Alert::warning(_("Alignment not permitted"),
1960 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1961 d->params_.align(LYX_ALIGN_LAYOUT);
1966 pos_type Paragraph::beginOfBody() const
1968 return d->begin_of_body_;
1972 void Paragraph::setBeginOfBody()
1974 if (d->layout_->labeltype != LABEL_MANUAL) {
1975 d->begin_of_body_ = 0;
1979 // Unroll the first two cycles of the loop
1980 // and remember the previous character to
1981 // remove unnecessary getChar() calls
1983 pos_type end = size();
1984 if (i < end && !isNewline(i)) {
1986 char_type previous_char = 0;
1989 previous_char = d->text_[i];
1990 if (!isNewline(i)) {
1992 while (i < end && previous_char != ' ') {
1997 previous_char = temp;
2003 d->begin_of_body_ = i;
2007 bool Paragraph::allowParagraphCustomization() const
2009 return inInset().allowParagraphCustomization();
2013 bool Paragraph::usePlainLayout() const
2015 return inInset().usePlainLayout();
2021 // paragraphs inside floats need different alignment tags to avoid
2024 bool noTrivlistCentering(InsetCode code)
2026 return code == FLOAT_CODE
2027 || code == WRAP_CODE
2028 || code == CELL_CODE;
2032 string correction(string const & orig)
2034 if (orig == "flushleft")
2035 return "raggedright";
2036 if (orig == "flushright")
2037 return "raggedleft";
2038 if (orig == "center")
2044 string const corrected_env(string const & suffix, string const & env,
2045 InsetCode code, bool const lastpar)
2047 string output = suffix + "{";
2048 if (noTrivlistCentering(code)) {
2050 // the last paragraph in non-trivlist-aligned
2051 // context is special (to avoid unwanted whitespace)
2052 if (suffix == "\\begin")
2053 return "\\" + correction(env) + "{}";
2056 output += correction(env);
2060 if (suffix == "\\begin")
2066 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2068 if (!contains(str, "\n"))
2069 column += str.size();
2073 column = rsplit(str, tmp, '\n').size();
2080 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2081 odocstream & os, TexRow & texrow,
2082 OutputParams const & runparams) const
2086 if (params_.noindent()) {
2087 os << "\\noindent ";
2091 LyXAlignment const curAlign = params_.align();
2093 if (curAlign == layout_->align)
2097 case LYX_ALIGN_NONE:
2098 case LYX_ALIGN_BLOCK:
2099 case LYX_ALIGN_LAYOUT:
2100 case LYX_ALIGN_SPECIAL:
2101 case LYX_ALIGN_DECIMAL:
2103 case LYX_ALIGN_LEFT:
2104 case LYX_ALIGN_RIGHT:
2105 case LYX_ALIGN_CENTER:
2106 if (runparams.moving_arg) {
2113 string const begin_tag = "\\begin";
2114 InsetCode code = ownerCode();
2115 bool const lastpar = runparams.isLastPar;
2118 case LYX_ALIGN_NONE:
2119 case LYX_ALIGN_BLOCK:
2120 case LYX_ALIGN_LAYOUT:
2121 case LYX_ALIGN_SPECIAL:
2122 case LYX_ALIGN_DECIMAL:
2124 case LYX_ALIGN_LEFT: {
2126 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2127 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2129 output = corrected_env(begin_tag, "flushright", code, lastpar);
2130 os << from_ascii(output);
2131 adjust_row_column(output, texrow, column);
2133 } case LYX_ALIGN_RIGHT: {
2135 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2136 output = corrected_env(begin_tag, "flushright", code, lastpar);
2138 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2139 os << from_ascii(output);
2140 adjust_row_column(output, texrow, column);
2142 } case LYX_ALIGN_CENTER: {
2144 output = corrected_env(begin_tag, "center", code, lastpar);
2145 os << from_ascii(output);
2146 adjust_row_column(output, texrow, column);
2155 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2156 odocstream & os, TexRow & texrow,
2157 OutputParams const & runparams) const
2161 LyXAlignment const curAlign = params_.align();
2163 if (curAlign == layout_->align)
2167 case LYX_ALIGN_NONE:
2168 case LYX_ALIGN_BLOCK:
2169 case LYX_ALIGN_LAYOUT:
2170 case LYX_ALIGN_SPECIAL:
2171 case LYX_ALIGN_DECIMAL:
2173 case LYX_ALIGN_LEFT:
2174 case LYX_ALIGN_RIGHT:
2175 case LYX_ALIGN_CENTER:
2176 if (runparams.moving_arg) {
2183 string const end_tag = "\n\\par\\end";
2184 InsetCode code = ownerCode();
2185 bool const lastpar = runparams.isLastPar;
2188 case LYX_ALIGN_NONE:
2189 case LYX_ALIGN_BLOCK:
2190 case LYX_ALIGN_LAYOUT:
2191 case LYX_ALIGN_SPECIAL:
2192 case LYX_ALIGN_DECIMAL:
2194 case LYX_ALIGN_LEFT: {
2196 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2197 output = corrected_env(end_tag, "flushleft", code, lastpar);
2199 output = corrected_env(end_tag, "flushright", code, lastpar);
2200 os << from_ascii(output);
2201 adjust_row_column(output, texrow, column);
2203 } case LYX_ALIGN_RIGHT: {
2205 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2206 output = corrected_env(end_tag, "flushright", code, lastpar);
2208 output = corrected_env(end_tag, "flushleft", code, lastpar);
2209 os << from_ascii(output);
2210 adjust_row_column(output, texrow, column);
2212 } case LYX_ALIGN_CENTER: {
2214 output = corrected_env(end_tag, "center", code, lastpar);
2215 os << from_ascii(output);
2216 adjust_row_column(output, texrow, column);
2225 // This one spits out the text of the paragraph
2226 void Paragraph::latex(BufferParams const & bparams,
2227 Font const & outerfont,
2228 odocstream & os, TexRow & texrow,
2229 OutputParams const & runparams,
2230 int start_pos, int end_pos, bool force) const
2232 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2234 // FIXME This check should not be needed. Perhaps issue an
2235 // error if it triggers.
2236 Layout const & style = inInset().forcePlainLayout() ?
2237 bparams.documentClass().plainLayout() : *d->layout_;
2239 if (!force && style.inpreamble)
2242 bool const allowcust = allowParagraphCustomization();
2244 // Current base font for all inherited font changes, without any
2245 // change caused by an individual character, except for the language:
2246 // It is set to the language of the first character.
2247 // As long as we are in the label, this font is the base font of the
2248 // label. Before the first body character it is set to the base font
2252 // Maybe we have to create a optional argument.
2253 pos_type body_pos = beginOfBody();
2254 unsigned int column = 0;
2257 // the optional argument is kept in curly brackets in
2258 // case it contains a ']'
2261 basefont = getLabelFont(bparams, outerfont);
2263 basefont = getLayoutFont(bparams, outerfont);
2266 // Which font is currently active?
2267 Font running_font(basefont);
2268 // Do we have an open font change?
2269 bool open_font = false;
2271 Change runningChange = Change(Change::UNCHANGED);
2273 Encoding const * const prev_encoding = runparams.encoding;
2275 texrow.start(id(), 0);
2277 // if the paragraph is empty, the loop will not be entered at all
2279 if (style.isCommand()) {
2284 column += d->startTeXParParams(bparams, os, texrow,
2288 for (pos_type i = 0; i < size(); ++i) {
2289 // First char in paragraph or after label?
2290 if (i == body_pos) {
2293 column += running_font.latexWriteEndChanges(
2294 os, bparams, runparams,
2295 basefont, basefont);
2298 basefont = getLayoutFont(bparams, outerfont);
2299 running_font = basefont;
2301 column += Changes::latexMarkChange(os, bparams,
2302 runningChange, Change(Change::UNCHANGED),
2304 runningChange = Change(Change::UNCHANGED);
2309 if (style.isCommand()) {
2315 column += d->startTeXParParams(bparams, os,
2320 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2323 if (bparams.outputChanges && runningChange != change) {
2325 column += running_font.latexWriteEndChanges(
2326 os, bparams, runparams, basefont, basefont);
2329 basefont = getLayoutFont(bparams, outerfont);
2330 running_font = basefont;
2332 column += Changes::latexMarkChange(os, bparams, runningChange,
2334 runningChange = change;
2337 // do not output text which is marked deleted
2338 // if change tracking output is disabled
2339 if (!bparams.outputChanges && change.deleted()) {
2345 // Fully instantiated font
2346 Font const font = getFont(bparams, i, outerfont);
2348 Font const last_font = running_font;
2350 // Do we need to close the previous font?
2352 (font != running_font ||
2353 font.language() != running_font.language()))
2355 column += running_font.latexWriteEndChanges(
2356 os, bparams, runparams, basefont,
2357 (i == body_pos-1) ? basefont : font);
2358 running_font = basefont;
2362 // close babel's font environment before opening CJK.
2363 if (!running_font.language()->babel().empty() &&
2364 font.language()->encoding()->package() == Encoding::CJK) {
2365 string end_tag = subst(lyxrc.language_command_end,
2367 running_font.language()->babel());
2368 os << from_ascii(end_tag);
2369 column += end_tag.length();
2372 // Switch file encoding if necessary (and allowed)
2373 if (!runparams.pass_thru && !style.pass_thru &&
2374 runparams.encoding->package() != Encoding::none &&
2375 font.language()->encoding()->package() != Encoding::none) {
2376 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2377 runparams, *(font.language()->encoding()));
2378 if (enc_switch.first) {
2379 column += enc_switch.second;
2380 runparams.encoding = font.language()->encoding();
2384 char_type const c = d->text_[i];
2386 // Do we need to change font?
2387 if ((font != running_font ||
2388 font.language() != running_font.language()) &&
2391 odocstringstream ods;
2392 column += font.latexWriteStartChanges(ods, bparams,
2393 runparams, basefont,
2395 running_font = font;
2397 docstring fontchange = ods.str();
2398 // check whether the fontchange ends with a \\textcolor
2399 // modifier and the text starts with a space (bug 4473)
2400 docstring const last_modifier = rsplit(fontchange, '\\');
2401 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2402 os << fontchange << from_ascii("{}");
2403 // check if the fontchange ends with a trailing blank
2404 // (like "\small " (see bug 3382)
2405 else if (suffixIs(fontchange, ' ') && c == ' ')
2406 os << fontchange.substr(0, fontchange.size() - 1)
2407 << from_ascii("{}");
2412 // FIXME: think about end_pos implementation...
2413 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2414 // FIXME: integrate this case in latexSpecialChar
2415 // Do not print the separation of the optional argument
2416 // if style.pass_thru is false. This works because
2417 // latexSpecialChar ignores spaces if
2418 // style.pass_thru is false.
2419 if (i != body_pos - 1) {
2420 if (d->simpleTeXBlanks(
2421 runparams, os, texrow,
2422 i, column, font, style)) {
2423 // A surrogate pair was output. We
2424 // must not call latexSpecialChar
2425 // in this iteration, since it would output
2426 // the combining character again.
2433 OutputParams rp = runparams;
2434 rp.free_spacing = style.free_spacing;
2435 rp.local_font = &font;
2436 rp.intitle = style.intitle;
2438 // Two major modes: LaTeX or plain
2439 // Handle here those cases common to both modes
2440 // and then split to handle the two modes separately.
2441 if (c == META_INSET) {
2442 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2443 d->latexInset(bparams, os,
2444 texrow, rp, running_font,
2445 basefont, outerfont, open_font,
2446 runningChange, style, i, column);
2449 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2451 d->latexSpecialChar(os, rp, running_font, runningChange,
2453 } catch (EncodingException & e) {
2454 if (runparams.dryrun) {
2455 os << "<" << _("LyX Warning: ")
2456 << _("uncodable character") << " '";
2460 // add location information and throw again.
2469 // Set the encoding to that returned from latexSpecialChar (see
2470 // comment for encoding member in OutputParams.h)
2471 runparams.encoding = rp.encoding;
2474 // If we have an open font definition, we have to close it
2476 #ifdef FIXED_LANGUAGE_END_DETECTION
2478 running_font.latexWriteEndChanges(os, bparams,
2479 runparams, basefont,
2480 next_->getFont(bparams, 0, outerfont));
2482 running_font.latexWriteEndChanges(os, bparams,
2483 runparams, basefont, basefont);
2486 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2487 //FIXME: there as we start another \selectlanguage with the next paragraph if
2488 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2489 running_font.latexWriteEndChanges(os, bparams, runparams,
2490 basefont, basefont);
2494 column += Changes::latexMarkChange(os, bparams, runningChange,
2495 Change(Change::UNCHANGED), runparams);
2497 // Needed if there is an optional argument but no contents.
2498 if (body_pos > 0 && body_pos == size()) {
2502 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2503 && runparams.encoding != prev_encoding) {
2504 runparams.encoding = prev_encoding;
2505 if (!bparams.useXetex)
2506 os << setEncoding(prev_encoding->iconvName());
2509 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2513 bool Paragraph::emptyTag() const
2515 for (pos_type i = 0; i < size(); ++i) {
2516 if (Inset const * inset = getInset(i)) {
2517 InsetCode lyx_code = inset->lyxCode();
2518 // FIXME testing like that is wrong. What is
2520 if (lyx_code != TOC_CODE &&
2521 lyx_code != INCLUDE_CODE &&
2522 lyx_code != GRAPHICS_CODE &&
2523 lyx_code != ERT_CODE &&
2524 lyx_code != LISTINGS_CODE &&
2525 lyx_code != FLOAT_CODE &&
2526 lyx_code != TABULAR_CODE) {
2530 char_type c = d->text_[i];
2531 if (c != ' ' && c != '\t')
2539 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2542 for (pos_type i = 0; i < size(); ++i) {
2543 if (Inset const * inset = getInset(i)) {
2544 InsetCode lyx_code = inset->lyxCode();
2545 if (lyx_code == LABEL_CODE) {
2546 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2547 docstring const & id = il->getParam("name");
2548 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2556 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2560 for (i = 0; i < size(); ++i) {
2561 if (Inset const * inset = getInset(i)) {
2562 inset->docbook(os, runparams);
2564 char_type c = d->text_[i];
2567 os << sgml::escapeChar(c);
2574 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2578 for (i = 0; i < size(); ++i) {
2579 if (Inset const * inset = getInset(i)) {
2580 inset->xhtml(xs, runparams);
2582 char_type c = d->text_[i];
2592 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2595 pos_type size = text_.size();
2596 for (pos_type i = initial; i < size; ++i) {
2597 Font font = owner_->getFont(buf.params(), i, outerfont);
2598 if (text_[i] == META_INSET)
2600 if (i != initial && font != font_old)
2609 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2611 OutputParams const & runparams,
2612 Font const & outerfont,
2613 pos_type initial) const
2615 bool emph_flag = false;
2617 Layout const & style = *d->layout_;
2619 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2621 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2624 // parsing main loop
2625 for (pos_type i = initial; i < size(); ++i) {
2626 Font font = getFont(buf.params(), i, outerfont);
2628 // handle <emphasis> tag
2629 if (font_old.emph() != font.fontInfo().emph()) {
2630 if (font.fontInfo().emph() == FONT_ON) {
2633 } else if (i != initial) {
2634 os << "</emphasis>";
2639 if (Inset const * inset = getInset(i)) {
2640 inset->docbook(os, runparams);
2642 char_type c = d->text_[i];
2644 if (style.pass_thru)
2647 os << sgml::escapeChar(c);
2649 font_old = font.fontInfo();
2653 os << "</emphasis>";
2656 if (style.free_spacing)
2658 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2663 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2665 OutputParams const & runparams,
2666 Font const & outerfont,
2667 pos_type initial) const
2671 bool emph_flag = false;
2672 bool bold_flag = false;
2675 Layout const & style = *d->layout_;
2677 if (!runparams.for_toc && runparams.html_make_pars) {
2678 // generate a magic label for this paragraph
2679 string const attr = "id='" + magicLabel() + "'";
2680 xs << html::CompTag("a", attr);
2684 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2686 // parsing main loop
2687 for (pos_type i = initial; i < size(); ++i) {
2688 // let's not show deleted material in the output
2692 Font font = getFont(buf.params(), i, outerfont);
2695 if (font_old.emph() != font.fontInfo().emph()) {
2696 if (font.fontInfo().emph() == FONT_ON) {
2697 xs << html::StartTag("em");
2699 } else if (emph_flag && i != initial) {
2700 xs << html::EndTag("em");
2705 if (font_old.series() != font.fontInfo().series()) {
2706 if (font.fontInfo().series() == BOLD_SERIES) {
2707 xs << html::StartTag("strong");
2709 } else if (bold_flag && i != initial) {
2710 xs << html::EndTag("strong");
2715 // Other such tags? What about the other text ranges?
2717 Inset const * inset = getInset(i);
2719 InsetCommand const * ic = inset->asInsetCommand();
2720 InsetLayout const & il = inset->getLayout();
2721 InsetMath const * im = inset->asInsetMath();
2722 if (!runparams.for_toc
2723 || im || il.isInToc() || (ic && ic->isInToc())) {
2724 OutputParams np = runparams;
2725 if (!il.htmlisblock())
2726 np.html_in_par = true;
2727 retval += inset->xhtml(xs, np);
2730 char_type c = d->text_[i];
2732 if (style.pass_thru)
2734 else if (c == '-') {
2737 if (j < size() && d->text_[j] == '-') {
2739 if (j < size() && d->text_[j] == '-') {
2740 str += from_ascii("—");
2743 str += from_ascii("–");
2749 // We don't want to escape the entities. Note that
2750 // it is safe to do this, since str can otherwise
2751 // only be "-". E.g., it can't be "<".
2752 xs << XHTMLStream::NextRaw() << str;
2756 font_old = font.fontInfo();
2764 bool Paragraph::isHfill(pos_type pos) const
2766 Inset const * inset = getInset(pos);
2767 return inset && (inset->lyxCode() == SPACE_CODE &&
2768 inset->isStretchableSpace());
2772 bool Paragraph::isNewline(pos_type pos) const
2774 Inset const * inset = getInset(pos);
2775 return inset && inset->lyxCode() == NEWLINE_CODE;
2779 bool Paragraph::isLineSeparator(pos_type pos) const
2781 char_type const c = d->text_[pos];
2782 if (isLineSeparatorChar(c))
2784 Inset const * inset = getInset(pos);
2785 return inset && inset->isLineSeparator();
2789 bool Paragraph::isWordSeparator(pos_type pos) const
2791 if (Inset const * inset = getInset(pos))
2792 return !inset->isLetter();
2793 char_type const c = d->text_[pos];
2794 // We want to pass the ' and escape chars to the spellchecker
2795 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2796 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2801 bool Paragraph::isChar(pos_type pos) const
2803 if (Inset const * inset = getInset(pos))
2804 return inset->isChar();
2805 char_type const c = d->text_[pos];
2806 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2810 bool Paragraph::isSpace(pos_type pos) const
2812 if (Inset const * inset = getInset(pos))
2813 return inset->isSpace();
2814 char_type const c = d->text_[pos];
2815 return lyx::isSpace(c);
2820 Paragraph::getParLanguage(BufferParams const & bparams) const
2823 return getFirstFontSettings(bparams).language();
2824 // FIXME: we should check the prev par as well (Lgb)
2825 return bparams.language;
2829 bool Paragraph::isRTL(BufferParams const & bparams) const
2831 return lyxrc.rtl_support
2832 && getParLanguage(bparams)->rightToLeft()
2833 && !inInset().getLayout().forceLTR();
2837 void Paragraph::changeLanguage(BufferParams const & bparams,
2838 Language const * from, Language const * to)
2840 // change language including dummy font change at the end
2841 for (pos_type i = 0; i <= size(); ++i) {
2842 Font font = getFontSettings(bparams, i);
2843 if (font.language() == from) {
2844 font.setLanguage(to);
2848 d->requestSpellCheck(size());
2852 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2854 Language const * doc_language = bparams.language;
2855 FontList::const_iterator cit = d->fontlist_.begin();
2856 FontList::const_iterator end = d->fontlist_.end();
2858 for (; cit != end; ++cit)
2859 if (cit->font().language() != ignore_language &&
2860 cit->font().language() != latex_language &&
2861 cit->font().language() != doc_language)
2867 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2869 FontList::const_iterator cit = d->fontlist_.begin();
2870 FontList::const_iterator end = d->fontlist_.end();
2872 for (; cit != end; ++cit) {
2873 Language const * lang = cit->font().language();
2874 if (lang != ignore_language &&
2875 lang != latex_language)
2876 languages.insert(lang);
2881 docstring Paragraph::asString(int options) const
2883 return asString(0, size(), options);
2887 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2889 odocstringstream os;
2892 && options & AS_STR_LABEL
2893 && !d->params_.labelString().empty())
2894 os << d->params_.labelString() << ' ';
2896 for (pos_type i = beg; i < end; ++i) {
2897 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2899 char_type const c = d->text_[i];
2900 if (isPrintable(c) || c == '\t'
2901 || (c == '\n' && (options & AS_STR_NEWLINES)))
2903 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2904 getInset(i)->tocString(os);
2905 if (getInset(i)->asInsetMath())
2914 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2916 odocstringstream os;
2919 && options & AS_STR_LABEL
2920 && !d->params_.labelString().empty())
2921 os << d->params_.labelString() << ' ';
2923 for (pos_type i = beg; i < end; ++i) {
2924 char_type const c = d->text_[i];
2925 if (isPrintable(c) || c == '\t'
2926 || (c == '\n' && (options & AS_STR_NEWLINES)))
2928 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2929 getInset(i)->plaintext(os, runparams);
2937 void Paragraph::setInsetOwner(Inset const * inset)
2939 d->inset_owner_ = inset;
2943 int Paragraph::id() const
2949 void Paragraph::setId(int id)
2955 Layout const & Paragraph::layout() const
2961 void Paragraph::setLayout(Layout const & layout)
2963 d->layout_ = &layout;
2967 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2969 setLayout(tc.defaultLayout());
2973 void Paragraph::setPlainLayout(DocumentClass const & tc)
2975 setLayout(tc.plainLayout());
2979 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2981 if (usePlainLayout())
2982 setPlainLayout(tclass);
2984 setDefaultLayout(tclass);
2988 Inset const & Paragraph::inInset() const
2990 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2991 _("Memory problem"), _("Paragraph not properly initialized")));
2992 return *d->inset_owner_;
2996 ParagraphParameters & Paragraph::params()
3002 ParagraphParameters const & Paragraph::params() const
3008 bool Paragraph::isFreeSpacing() const
3010 if (d->layout_->free_spacing)
3012 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3016 bool Paragraph::allowEmpty() const
3018 if (d->layout_->keepempty)
3020 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3024 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3026 if (!Encodings::isArabicChar(c))
3029 char_type prev_char = ' ';
3030 char_type next_char = ' ';
3032 for (pos_type i = pos - 1; i >= 0; --i) {
3033 char_type const par_char = d->text_[i];
3034 if (!Encodings::isArabicComposeChar(par_char)) {
3035 prev_char = par_char;
3040 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3041 char_type const par_char = d->text_[i];
3042 if (!Encodings::isArabicComposeChar(par_char)) {
3043 next_char = par_char;
3048 if (Encodings::isArabicChar(next_char)) {
3049 if (Encodings::isArabicChar(prev_char) &&
3050 !Encodings::isArabicSpecialChar(prev_char))
3051 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3053 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3055 if (Encodings::isArabicChar(prev_char) &&
3056 !Encodings::isArabicSpecialChar(prev_char))
3057 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3059 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3064 int Paragraph::checkBiblio(Buffer const & buffer)
3067 // This is getting more and more a mess. ...We really should clean
3068 // up this bibitem issue for 1.6. See also bug 2743.
3070 // Add bibitem insets if necessary
3071 if (d->layout_->labeltype != LABEL_BIBLIO)
3074 bool hasbibitem = !d->insetlist_.empty()
3075 // Insist on it being in pos 0
3076 && d->text_[0] == META_INSET
3077 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3079 bool track_changes = buffer.params().trackChanges;
3084 // remove a bibitem in pos != 0
3085 // restore it later in pos 0 if necessary
3086 // (e.g. if a user inserts contents _before_ the item)
3087 // we're assuming there's only one of these, which there
3089 int erasedInsetPosition = -1;
3090 InsetList::iterator it = d->insetlist_.begin();
3091 InsetList::iterator end = d->insetlist_.end();
3092 for (; it != end; ++it)
3093 if (it->inset->lyxCode() == BIBITEM_CODE
3095 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3096 oldkey = olditem->getParam("key");
3097 oldlabel = olditem->getParam("label");
3098 erasedInsetPosition = it->pos;
3099 eraseChar(erasedInsetPosition, track_changes);
3103 // There was an InsetBibitem at the beginning, and we didn't
3104 // have to erase one.
3105 if (hasbibitem && erasedInsetPosition < 0)
3108 // There was an InsetBibitem at the beginning and we did have to
3109 // erase one. So we give its properties to the beginning inset.
3111 InsetBibitem * inset =
3112 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3113 if (!oldkey.empty())
3114 inset->setParam("key", oldkey);
3115 inset->setParam("label", oldlabel);
3116 return -erasedInsetPosition;
3119 // There was no inset at the beginning, so we need to create one with
3120 // the key and label of the one we erased.
3121 InsetBibitem * inset =
3122 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3123 // restore values of previously deleted item in this par.
3124 if (!oldkey.empty())
3125 inset->setParam("key", oldkey);
3126 inset->setParam("label", oldlabel);
3127 insertInset(0, static_cast<Inset *>(inset),
3128 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3134 void Paragraph::checkAuthors(AuthorList const & authorList)
3136 d->changes_.checkAuthors(authorList);
3140 bool Paragraph::isChanged(pos_type pos) const
3142 return lookupChange(pos).changed();
3146 bool Paragraph::isInserted(pos_type pos) const
3148 return lookupChange(pos).inserted();
3152 bool Paragraph::isDeleted(pos_type pos) const
3154 return lookupChange(pos).deleted();
3158 InsetList const & Paragraph::insetList() const
3160 return d->insetlist_;
3164 void Paragraph::setBuffer(Buffer & b)
3166 d->insetlist_.setBuffer(b);
3170 Inset * Paragraph::releaseInset(pos_type pos)
3172 Inset * inset = d->insetlist_.release(pos);
3173 /// does not honour change tracking!
3174 eraseChar(pos, false);
3179 Inset * Paragraph::getInset(pos_type pos)
3181 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3182 ? d->insetlist_.get(pos) : 0;
3186 Inset const * Paragraph::getInset(pos_type pos) const
3188 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3189 ? d->insetlist_.get(pos) : 0;
3193 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3194 pos_type & right, TextCase action)
3196 // process sequences of modified characters; in change
3197 // tracking mode, this approach results in much better
3198 // usability than changing case on a char-by-char basis
3201 bool const trackChanges = bparams.trackChanges;
3203 bool capitalize = true;
3205 for (; pos < right; ++pos) {
3206 char_type oldChar = d->text_[pos];
3207 char_type newChar = oldChar;
3209 // ignore insets and don't play with deleted text!
3210 if (oldChar != META_INSET && !isDeleted(pos)) {
3212 case text_lowercase:
3213 newChar = lowercase(oldChar);
3215 case text_capitalization:
3217 newChar = uppercase(oldChar);
3221 case text_uppercase:
3222 newChar = uppercase(oldChar);
3227 if (isWordSeparator(pos) || isDeleted(pos)) {
3228 // permit capitalization again
3232 if (oldChar != newChar) {
3234 if (pos != right - 1)
3236 // step behind the changing area
3240 int erasePos = pos - changes.size();
3241 for (size_t i = 0; i < changes.size(); i++) {
3242 insertChar(pos, changes[i],
3243 getFontSettings(bparams,
3246 if (!eraseChar(erasePos, trackChanges)) {
3249 ++right; // expand selection
3257 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3258 pos_type pos, bool del) const
3260 int const strsize = str.length();
3262 pos_type const parsize = d->text_.size();
3263 for (i = 0; pos + i < parsize; ++i) {
3266 if (cs && str[i] != d->text_[pos + i])
3268 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3270 if (!del && isDeleted(pos + i))
3277 // if necessary, check whether string matches word
3279 if (pos > 0 && !isWordSeparator(pos - 1))
3281 if (pos + strsize < parsize
3282 && !isWordSeparator(pos + strsize))
3290 char_type Paragraph::getChar(pos_type pos) const
3292 return d->text_[pos];
3296 pos_type Paragraph::size() const
3298 return d->text_.size();
3302 bool Paragraph::empty() const
3304 return d->text_.empty();
3308 bool Paragraph::isInset(pos_type pos) const
3310 return d->text_[pos] == META_INSET;
3314 bool Paragraph::isSeparator(pos_type pos) const
3316 //FIXME: Are we sure this can be the only separator?
3317 return d->text_[pos] == ' ';
3321 void Paragraph::deregisterWords()
3323 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3324 Private::LangWordsMap::const_iterator ite = d->words_.end();
3325 for (; itl != ite; ++itl) {
3326 WordList * wl = theWordList(itl->first);
3327 Private::Words::const_iterator it = (itl->second).begin();
3328 Private::Words::const_iterator et = (itl->second).end();
3329 for (; it != et; ++it)
3336 void Paragraph::locateWord(pos_type & from, pos_type & to,
3337 word_location const loc) const
3340 case WHOLE_WORD_STRICT:
3341 if (from == 0 || from == size()
3342 || isWordSeparator(from)
3343 || isWordSeparator(from - 1)) {
3347 // no break here, we go to the next
3350 // If we are already at the beginning of a word, do nothing
3351 if (!from || isWordSeparator(from - 1))
3353 // no break here, we go to the next
3356 // always move the cursor to the beginning of previous word
3357 while (from && !isWordSeparator(from - 1))
3361 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3364 // no need to move the 'from' cursor
3368 while (to < size() && !isWordSeparator(to))
3373 void Paragraph::collectWords()
3375 // This is the value that needs to be exposed in the preferences
3376 // to resolve bug #6760.
3377 static int minlength = 6;
3378 pos_type n = size();
3379 for (pos_type pos = 0; pos < n; ++pos) {
3380 if (isWordSeparator(pos))
3382 pos_type from = pos;
3383 locateWord(from, pos, WHOLE_WORD);
3384 if (pos - from >= minlength) {
3385 docstring word = asString(from, pos, AS_STR_NONE);
3386 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3387 if (cit == d->fontlist_.end())
3389 Language const * lang = cit->font().language();
3390 d->words_[*lang].insert(word);
3396 void Paragraph::registerWords()
3398 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3399 Private::LangWordsMap::const_iterator ite = d->words_.end();
3400 for (; itl != ite; ++itl) {
3401 WordList * wl = theWordList(itl->first);
3402 Private::Words::const_iterator it = (itl->second).begin();
3403 Private::Words::const_iterator et = (itl->second).end();
3404 for (; it != et; ++it)
3410 void Paragraph::updateWords()
3418 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3420 SkipPositionsIterator begin = skips.begin();
3421 SkipPositions::iterator end = skips.end();
3422 if (pos > 0 && begin < end) {
3424 if (end->last == pos - 1) {
3429 skips.insert(end, FontSpan(pos, pos));
3433 Language * Paragraph::Private::locateSpellRange(
3434 pos_type & from, pos_type & to,
3435 SkipPositions & skips) const
3437 // skip leading white space
3438 while (from < to && owner_->isWordSeparator(from))
3440 // don't check empty range
3443 // get current language
3444 Language * lang = getSpellLanguage(from);
3445 pos_type last = from;
3446 bool samelang = true;
3447 bool sameinset = true;
3448 while (last < to && samelang && sameinset) {
3449 // hop to end of word
3450 while (last < to && !owner_->isWordSeparator(last)) {
3451 if (owner_->getInset(last)) {
3452 appendSkipPosition(skips, last);
3453 } else if (owner_->isDeleted(last)) {
3454 appendSkipPosition(skips, last);
3458 // hop to next word while checking for insets
3459 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3460 if (Inset const * inset = owner_->getInset(last))
3461 sameinset = inset->isChar() && inset->isLetter();
3462 if (sameinset && owner_->isDeleted(last)) {
3463 appendSkipPosition(skips, last);
3468 if (sameinset && last < to) {
3469 // now check for language change
3470 samelang = lang == getSpellLanguage(last);
3473 // if language change detected backstep is needed
3481 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3484 const_cast<Language *>(owner_->getFontSettings(
3485 inset_owner_->buffer().params(), from).language());
3486 if (lang == inset_owner_->buffer().params().language
3487 && !lyxrc.spellchecker_alt_lang.empty()) {
3489 string const lang_variety =
3490 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3491 lang->setCode(lang_code);
3492 lang->setVariety(lang_variety);
3498 void Paragraph::requestSpellCheck(pos_type pos)
3500 d->requestSpellCheck(pos == -1 ? size() : pos);
3504 bool Paragraph::needsSpellCheck() const
3506 SpellChecker::ChangeNumber speller_change_number = 0;
3507 if (theSpellChecker())
3508 speller_change_number = theSpellChecker()->changeNumber();
3509 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3510 d->speller_state_.needsCompleteRefresh(speller_change_number);
3512 return d->needsSpellCheck();
3516 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3517 WordLangTuple & wl, docstring_list & suggestions,
3518 bool do_suggestion, bool check_learned) const
3520 SpellChecker::Result result = SpellChecker::WORD_OK;
3521 SpellChecker * speller = theSpellChecker();
3525 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3528 locateWord(from, to, WHOLE_WORD);
3529 if (from == to || from >= size())
3532 docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3533 Language * lang = d->getSpellLanguage(from);
3535 wl = WordLangTuple(word, lang);
3540 if (needsSpellCheck() || check_learned) {
3541 // Ignore words with digits
3542 // FIXME: make this customizable
3543 // (note that some checkers ignore words with digits by default)
3544 if (!hasDigit(word)) {
3545 bool const trailing_dot = to < size() && d->text_[to] == '.';
3546 result = speller->check(wl);
3547 if (SpellChecker::misspelled(result) && trailing_dot) {
3548 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3549 result = speller->check(wl);
3550 if (!SpellChecker::misspelled(result)) {
3551 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3553 from << ".." << to << "]");
3557 d->setMisspelled(from, to, result);
3559 result = d->speller_state_.getState(from);
3562 bool const misspelled_ = SpellChecker::misspelled(result) ;
3563 if (misspelled_ && do_suggestion)
3564 speller->suggest(wl, suggestions);
3565 else if (misspelled_)
3566 LYXERR(Debug::GUI, "misspelled word: \"" <<
3568 from << ".." << to << "]");
3570 suggestions.clear();
3576 void Paragraph::Private::markMisspelledWords(
3577 pos_type const & first, pos_type const & last,
3578 SpellChecker::Result result,
3579 docstring const & word,
3580 SkipPositions const & skips)
3582 if (!SpellChecker::misspelled(result)) {
3583 setMisspelled(first, last, SpellChecker::WORD_OK);
3587 SpellChecker * speller = theSpellChecker();
3588 // locate and enumerate the error positions
3589 int nerrors = speller->numMisspelledWords();
3591 SkipPositionsIterator it = skips.begin();
3592 SkipPositionsIterator et = skips.end();
3593 for (int index = 0; index < nerrors; ++index) {
3596 speller->misspelledWord(index, wstart, wlen);
3597 /// should not happen if speller supports range checks
3598 if (!wlen) continue;
3599 docstring const misspelled = word.substr(wstart, wlen);
3600 wstart += first + numskipped;
3601 if (snext < wstart) {
3602 /// mark the range of correct spelling
3603 numskipped += countSkips(it, et, wstart);
3604 setMisspelled(snext,
3605 wstart - 1, SpellChecker::WORD_OK);
3607 snext = wstart + wlen;
3608 numskipped += countSkips(it, et, snext);
3609 /// mark the range of misspelling
3610 setMisspelled(wstart, snext, result);
3611 LYXERR(Debug::GUI, "misspelled word: \"" <<
3612 misspelled << "\" [" <<
3613 wstart << ".." << (snext-1) << "]");
3616 if (snext <= last) {
3617 /// mark the range of correct spelling at end
3618 setMisspelled(snext, last, SpellChecker::WORD_OK);
3623 void Paragraph::spellCheck() const
3625 SpellChecker * speller = theSpellChecker();
3626 if (!speller || !size() ||!needsSpellCheck())
3630 d->rangeOfSpellCheck(start, endpos);
3631 if (speller->canCheckParagraph()) {
3632 // loop until we leave the range
3633 for (pos_type first = start; first < endpos; ) {
3634 pos_type last = endpos;
3635 Private::SkipPositions skips;
3636 Language * lang = d->locateSpellRange(first, last, skips);
3637 if (first >= endpos)
3639 // start the spell checker on the unit of meaning
3640 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3641 WordLangTuple wl = WordLangTuple(word, lang);
3642 SpellChecker::Result result = word.size() ?
3643 speller->check(wl) : SpellChecker::WORD_OK;
3644 d->markMisspelledWords(first, last, result, word, skips);
3648 static docstring_list suggestions;
3649 pos_type to = endpos;
3650 while (start < endpos) {
3652 spellCheck(start, to, wl, suggestions, false);
3656 d->readySpellCheck();
3660 bool Paragraph::isMisspelled(pos_type pos) const
3662 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3666 string Paragraph::magicLabel() const
3669 ss << "magicparlabel-" << id();