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));
754 // request run of spell checker
755 requestSpellCheck(pos);
759 if (change.deleted())
763 // Don't physically access the imaginary end-of-paragraph character.
764 // eraseChar() can only mark it as DELETED. A physical deletion of
765 // end-of-par must be handled externally.
771 d->changes_.erase(pos);
773 // if it is an inset, delete the inset entry
774 if (d->text_[pos] == META_INSET)
775 d->insetlist_.erase(pos);
777 d->text_.erase(d->text_.begin() + pos);
779 // Update the fontlist_
780 d->fontlist_.erase(pos);
782 // Update the insetlist_
783 d->insetlist_.decreasePosAfterPos(pos);
785 // Update list of misspelled positions
786 d->speller_state_.decreasePosAfterPos(pos);
792 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
794 LASSERT(start >= 0 && start <= size(), /**/);
795 LASSERT(end >= start && end <= size() + 1, /**/);
798 for (pos_type count = end - start; count; --count) {
799 if (!eraseChar(i, trackChanges))
806 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
807 char_type next, OutputParams const & runparams)
809 // Writing next here may circumvent a possible font change between
810 // c and next. Since next is only output if it forms a surrogate pair
811 // with c we can ignore this:
812 // A font change inside a surrogate pair does not make sense and is
813 // hopefully impossible to input.
814 // FIXME: change tracking
815 // Is this correct WRT change tracking?
816 Encoding const & encoding = *(runparams.encoding);
817 docstring const latex1 = encoding.latexChar(next);
818 docstring const latex2 = encoding.latexChar(c);
819 if (docstring(1, next) == latex1) {
820 // the encoding supports the combination
821 os << latex2 << latex1;
822 return latex1.length() + latex2.length();
823 } else if (runparams.local_font &&
824 runparams.local_font->language()->lang() == "polutonikogreek") {
825 // polutonikogreek only works without the brackets
826 os << latex1 << latex2;
827 return latex1.length() + latex2.length();
829 os << latex1 << '{' << latex2 << '}';
830 return latex1.length() + latex2.length() + 2;
834 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
835 odocstream & os, TexRow & texrow,
837 unsigned int & column,
839 Layout const & style)
841 if (style.pass_thru || runparams.pass_thru)
844 if (i + 1 < int(text_.size())) {
845 char_type next = text_[i + 1];
846 if (Encodings::isCombiningChar(next)) {
847 // This space has an accent, so we must always output it.
848 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
853 if (runparams.linelen > 0
854 && column > runparams.linelen
856 && text_[i - 1] != ' '
857 && (i + 1 < int(text_.size()))
858 // same in FreeSpacing mode
859 && !owner_->isFreeSpacing()
860 // In typewriter mode, we want to avoid
861 // ! . ? : at the end of a line
862 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
863 && (text_[i - 1] == '.'
864 || text_[i - 1] == '?'
865 || text_[i - 1] == ':'
866 || text_[i - 1] == '!'))) {
869 texrow.start(owner_->id(), i + 1);
871 } else if (style.free_spacing) {
880 int Paragraph::Private::writeScriptChars(odocstream & os,
881 docstring const & ltx,
882 Change const & runningChange,
883 Encoding const & encoding,
886 // FIXME: modifying i here is not very nice...
888 // We only arrive here when a proper language for character text_[i] has
889 // not been specified (i.e., it could not be translated in the current
890 // latex encoding) or its latex translation has been forced, and it
891 // belongs to a known script.
892 // Parameter ltx contains the latex translation of text_[i] as specified
893 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
894 // The latex macro name "textXXX" specifies the script to which text_[i]
895 // belongs and we use it in order to check whether characters from the
896 // same script immediately follow, such that we can collect them in a
897 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
898 // for the first char but only "<spec>" for all subsequent chars.
899 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
900 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
901 string script = to_ascii(ltx.substr(1, brace1 - 1));
904 bool closing_brace = true;
905 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
906 // Correct encoding is being used, so we can avoid \textgreek.
909 closing_brace = false;
911 os << ltx.substr(pos, length);
912 int size = text_.size();
913 while (i + 1 < size) {
914 char_type const next = text_[i + 1];
915 // Stop here if next character belongs to another script
916 // or there is a change in change tracking status.
917 if (!Encodings::isKnownScriptChar(next, script) ||
918 runningChange != owner_->lookupChange(i + 1))
922 FontList::const_iterator cit = fontlist_.begin();
923 FontList::const_iterator end = fontlist_.end();
924 for (; cit != end; ++cit) {
925 if (cit->pos() >= i && !found) {
926 prev_font = cit->font();
929 if (cit->pos() >= i + 1)
932 // Stop here if there is a font attribute or encoding change.
933 if (found && cit != end && prev_font != cit->font())
935 docstring const latex = encoding.latexChar(next);
936 docstring::size_type const b1 =
937 latex.find_first_of(from_ascii("{"));
938 docstring::size_type const b2 =
939 latex.find_last_of(from_ascii("}"));
940 int const len = b2 - b1 - 1;
941 os << latex.substr(b1 + 1, len);
953 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
955 pos_type const len = str.length();
957 // is the paragraph large enough?
958 if (pos + len > int(text_.size()))
961 // does the wanted text start at point?
962 for (string::size_type i = 0; i < str.length(); ++i) {
963 // Caution: direct comparison of characters works only
964 // because str is pure ASCII.
965 if (str[i] != text_[pos + i])
969 return fontlist_.hasChangeInRange(pos, len);
973 void Paragraph::Private::latexInset(BufferParams const & bparams,
976 OutputParams & runparams,
979 Font const & outerfont,
981 Change & running_change,
982 Layout const & style,
984 unsigned int & column)
986 Inset * inset = owner_->getInset(i);
987 LASSERT(inset, /**/);
989 if (style.pass_thru) {
990 inset->plaintext(os, runparams);
994 // FIXME: move this to InsetNewline::latex
995 if (inset->lyxCode() == NEWLINE_CODE) {
996 // newlines are handled differently here than
997 // the default in simpleTeXSpecialChars().
998 if (!style.newline_allowed) {
1002 column += running_font.latexWriteEndChanges(
1003 os, bparams, runparams,
1004 basefont, basefont);
1008 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1011 basefont = owner_->getLayoutFont(bparams, outerfont);
1012 running_font = basefont;
1014 if (runparams.moving_arg)
1019 texrow.start(owner_->id(), i + 1);
1023 if (owner_->isDeleted(i)) {
1024 if( ++runparams.inDeletedInset == 1)
1025 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1028 if (inset->canTrackChanges()) {
1029 column += Changes::latexMarkChange(os, bparams, running_change,
1030 Change(Change::UNCHANGED), runparams);
1031 running_change = Change(Change::UNCHANGED);
1035 odocstream::pos_type const len = os.tellp();
1037 if (inset->forceLTR()
1038 && running_font.isRightToLeft()
1039 // ERT is an exception, it should be output with no
1040 // decorations at all
1041 && inset->lyxCode() != ERT_CODE) {
1042 if (running_font.language()->lang() == "farsi")
1049 // FIXME: Bug: we can have an empty font change here!
1050 // if there has just been a font change, we are going to close it
1051 // right now, which means stupid latex code like \textsf{}. AFAIK,
1052 // this does not harm dvi output. A minor bug, thus (JMarc)
1054 // Some insets cannot be inside a font change command.
1055 // However, even such insets *can* be placed in \L or \R
1056 // or their equivalents (for RTL language switches), so we don't
1057 // close the language in those cases.
1058 // ArabTeX, though, cannot handle this special behavior, it seems.
1059 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1060 || running_font.language()->lang() == "arabic_arabtex";
1061 if (open_font && inset->noFontChange()) {
1062 bool closeLanguage = arabtex
1063 || basefont.isRightToLeft() == running_font.isRightToLeft();
1064 unsigned int count = running_font.latexWriteEndChanges(os,
1065 bparams, runparams, basefont, basefont, closeLanguage);
1067 // if any font properties were closed, update the running_font,
1068 // making sure, however, to leave the language as it was
1070 // FIXME: probably a better way to keep track of the old
1071 // language, than copying the entire font?
1072 Font const copy_font(running_font);
1073 basefont = owner_->getLayoutFont(bparams, outerfont);
1074 running_font = basefont;
1076 running_font.setLanguage(copy_font.language());
1077 // leave font open if language is still open
1078 open_font = (running_font.language() == basefont.language());
1080 runparams.local_font = &basefont;
1087 tmp = inset->latex(os, runparams);
1088 } catch (EncodingException & e) {
1089 // add location information and throw again.
1096 if (running_font.language()->lang() == "farsi")
1103 texrow.newlines(tmp);
1104 texrow.start(owner_->id(), i + 1);
1107 column += os.tellp() - len;
1110 if (owner_->isDeleted(i))
1111 --runparams.inDeletedInset;
1115 void Paragraph::Private::latexSpecialChar(
1117 OutputParams const & runparams,
1118 Font const & running_font,
1119 Change const & running_change,
1120 Layout const & style,
1122 unsigned int & column)
1124 char_type const c = text_[i];
1126 if (style.pass_thru || runparams.pass_thru) {
1128 // FIXME UNICODE: This can fail if c cannot
1129 // be encoded in the current encoding.
1134 // If T1 font encoding is used, use the special
1135 // characters it provides.
1136 // NOTE: some languages reset the font encoding
1138 if (!running_font.language()->internalFontEncoding()
1139 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1142 // \tt font needs special treatment
1143 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1144 && latexSpecialTypewriter(c, os, i, column))
1147 // Otherwise, we use what LaTeX provides us.
1150 os << "\\textbackslash{}";
1154 os << "\\textless{}";
1158 os << "\\textgreater{}";
1162 os << "\\textbar{}";
1169 os << "\\char`\\\"{}";
1174 case '%': case '#': case '{':
1182 os << "\\textasciitilde{}";
1187 os << "\\textasciicircum{}";
1194 // avoid being mistaken for optional arguments
1202 // Blanks are printed before font switching.
1203 // Sure? I am not! (try nice-latex)
1204 // I am sure it's correct. LyX might be smarter
1205 // in the future, but for now, nothing wrong is
1211 if (latexSpecialPhrase(os, i, column, runparams))
1217 Encoding const & encoding = *(runparams.encoding);
1218 if (i + 1 < int(text_.size())) {
1219 char_type next = text_[i + 1];
1220 if (Encodings::isCombiningChar(next)) {
1221 column += latexSurrogatePair(os, c, next, runparams) - 1;
1227 docstring const latex = encoding.latexChar(c);
1228 if (Encodings::isKnownScriptChar(c, script)
1229 && prefixIs(latex, from_ascii("\\" + script)))
1230 column += writeScriptChars(os, latex,
1231 running_change, encoding, i) - 1;
1232 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1233 // Prevent eating of a following
1234 // space or command corruption by
1235 // following characters
1236 column += latex.length() + 1;
1237 os << latex << "{}";
1239 column += latex.length() - 1;
1247 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1248 pos_type i, unsigned int & column)
1254 // In T1 encoding, these characters exist
1255 // but we should avoid ligatures
1256 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1258 os << "\\textcompwordmark{}";
1265 // soul.sty breaks with \char`\"
1266 os << "\\textquotedbl{}";
1275 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1276 pos_type i, unsigned int & column)
1280 // within \ttfamily, "--" is merged to "-" (no endash)
1281 // so we avoid this rather irritating ligature
1282 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1289 // everything else has to be checked separately
1290 // (depending on the encoding)
1297 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1298 unsigned int & column, OutputParams const & runparams)
1300 // FIXME: if we have "LaTeX" with a font
1301 // change in the middle (before the 'T', then
1302 // the "TeX" part is still special cased.
1303 // Really we should only operate this on
1304 // "words" for some definition of word
1306 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1307 if (!isTextAt(special_phrases[pnr].phrase, i))
1309 if (runparams.moving_arg)
1311 os << special_phrases[pnr].macro;
1312 i += special_phrases[pnr].phrase.length() - 1;
1313 column += special_phrases[pnr].macro.length() - 1;
1320 void Paragraph::Private::validate(LaTeXFeatures & features) const
1322 if (layout_->inpreamble && inset_owner_) {
1323 Buffer const & buf = inset_owner_->buffer();
1324 BufferParams const & bp = buf.params();
1327 odocstringstream ods;
1328 // we have to provide all the optional arguments here, even though
1329 // the last one is the only one we care about.
1330 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1331 docstring const d = ods.str();
1333 // this will have "{" at the beginning, but not at the end
1334 string const content = to_utf8(d);
1335 string const cmd = layout_->latexname();
1336 features.addPreambleSnippet("\\" + cmd + content + "}");
1340 if (features.runparams().flavor == OutputParams::HTML
1341 && layout_->htmltitle()) {
1342 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1345 // check the params.
1346 if (!params_.spacing().isDefault())
1347 features.require("setspace");
1350 features.useLayout(layout_->name());
1353 fontlist_.validate(features);
1355 // then the indentation
1356 if (!params_.leftIndent().zero())
1357 features.require("ParagraphLeftIndent");
1360 InsetList::const_iterator icit = insetlist_.begin();
1361 InsetList::const_iterator iend = insetlist_.end();
1362 for (; icit != iend; ++icit) {
1364 icit->inset->validate(features);
1365 if (layout_->needprotect &&
1366 icit->inset->lyxCode() == FOOT_CODE)
1367 features.require("NeedLyXFootnoteCode");
1371 // then the contents
1372 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1373 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1374 if (!special_phrases[pnr].builtin
1375 && isTextAt(special_phrases[pnr].phrase, i)) {
1376 features.require(special_phrases[pnr].phrase);
1380 Encodings::validate(text_[i], features);
1384 /////////////////////////////////////////////////////////////////////
1388 /////////////////////////////////////////////////////////////////////
1391 Layout const emptyParagraphLayout;
1394 Paragraph::Paragraph()
1395 : d(new Paragraph::Private(this, emptyParagraphLayout))
1402 Paragraph::Paragraph(Paragraph const & par)
1403 : itemdepth(par.itemdepth),
1404 d(new Paragraph::Private(*par.d, this))
1410 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1411 : itemdepth(par.itemdepth),
1412 d(new Paragraph::Private(*par.d, this, beg, end))
1418 Paragraph & Paragraph::operator=(Paragraph const & par)
1420 // needed as we will destroy the private part before copying it
1422 itemdepth = par.itemdepth;
1426 d = new Private(*par.d, this);
1433 Paragraph::~Paragraph()
1442 // this shall be called just before every "os << ..." action.
1443 void flushString(ostream & os, docstring & s)
1452 void Paragraph::write(ostream & os, BufferParams const & bparams,
1453 depth_type & dth) const
1455 // The beginning or end of a deeper (i.e. nested) area?
1456 if (dth != d->params_.depth()) {
1457 if (d->params_.depth() > dth) {
1458 while (d->params_.depth() > dth) {
1459 os << "\n\\begin_deeper";
1463 while (d->params_.depth() < dth) {
1464 os << "\n\\end_deeper";
1470 // First write the layout
1471 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1473 d->params_.write(os);
1475 Font font1(inherit_font, bparams.language);
1477 Change running_change = Change(Change::UNCHANGED);
1479 // this string is used as a buffer to avoid repetitive calls
1480 // to to_utf8(), which turn out to be expensive (JMarc)
1481 docstring write_buffer;
1484 for (pos_type i = 0; i <= size(); ++i) {
1486 Change const change = lookupChange(i);
1487 if (change != running_change)
1488 flushString(os, write_buffer);
1489 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1490 running_change = change;
1495 // Write font changes
1496 Font font2 = getFontSettings(bparams, i);
1497 if (font2 != font1) {
1498 flushString(os, write_buffer);
1499 font2.lyxWriteChanges(font1, os);
1504 char_type const c = d->text_[i];
1507 if (Inset const * inset = getInset(i)) {
1508 flushString(os, write_buffer);
1509 if (inset->directWrite()) {
1510 // international char, let it write
1511 // code directly so it's shorter in
1517 os << "\\begin_inset ";
1519 os << "\n\\end_inset\n\n";
1525 flushString(os, write_buffer);
1526 os << "\n\\backslash\n";
1530 flushString(os, write_buffer);
1531 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1538 if ((column > 70 && c == ' ')
1540 flushString(os, write_buffer);
1544 // this check is to amend a bug. LyX sometimes
1545 // inserts '\0' this could cause problems.
1547 write_buffer.push_back(c);
1549 LYXERR0("NUL char in structure.");
1555 flushString(os, write_buffer);
1556 os << "\n\\end_layout\n";
1560 void Paragraph::validate(LaTeXFeatures & features) const
1562 d->validate(features);
1566 void Paragraph::insert(pos_type start, docstring const & str,
1567 Font const & font, Change const & change)
1569 for (size_t i = 0, n = str.size(); i != n ; ++i)
1570 insertChar(start + i, str[i], font, change);
1574 void Paragraph::appendChar(char_type c, Font const & font,
1575 Change const & change)
1578 d->changes_.insert(change, d->text_.size());
1579 // when appending characters, no need to update tables
1580 d->text_.push_back(c);
1581 setFont(d->text_.size() - 1, font);
1585 void Paragraph::appendString(docstring const & s, Font const & font,
1586 Change const & change)
1588 pos_type end = s.size();
1589 size_t oldsize = d->text_.size();
1590 size_t newsize = oldsize + end;
1591 size_t capacity = d->text_.capacity();
1592 if (newsize >= capacity)
1593 d->text_.reserve(max(capacity + 100, newsize));
1595 // when appending characters, no need to update tables
1598 // FIXME: Optimize this!
1599 for (size_t i = oldsize; i != newsize; ++i) {
1601 d->changes_.insert(change, i);
1603 d->fontlist_.set(oldsize, font);
1604 d->fontlist_.set(newsize - 1, font);
1608 void Paragraph::insertChar(pos_type pos, char_type c,
1611 d->insertChar(pos, c, Change(trackChanges ?
1612 Change::INSERTED : Change::UNCHANGED));
1616 void Paragraph::insertChar(pos_type pos, char_type c,
1617 Font const & font, bool trackChanges)
1619 d->insertChar(pos, c, Change(trackChanges ?
1620 Change::INSERTED : Change::UNCHANGED));
1625 void Paragraph::insertChar(pos_type pos, char_type c,
1626 Font const & font, Change const & change)
1628 d->insertChar(pos, c, change);
1633 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1634 Font const & font, Change const & change)
1636 bool const success = insertInset(pos, inset, change);
1637 // Set the font/language of the inset...
1643 void Paragraph::resetFonts(Font const & font)
1645 d->fontlist_.clear();
1646 d->fontlist_.set(0, font);
1647 d->fontlist_.set(d->text_.size() - 1, font);
1650 // Gets uninstantiated font setting at position.
1651 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1655 LYXERR0("pos: " << pos << " size: " << size());
1656 LASSERT(pos <= size(), /**/);
1659 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1660 if (cit != d->fontlist_.end())
1663 if (pos == size() && !empty())
1664 return getFontSettings(bparams, pos - 1);
1666 // Optimisation: avoid a full font instantiation if there is no
1667 // language change from previous call.
1668 static Font previous_font;
1669 static Language const * previous_lang = 0;
1670 Language const * lang = getParLanguage(bparams);
1671 if (lang != previous_lang) {
1672 previous_lang = lang;
1673 previous_font = Font(inherit_font, lang);
1675 return previous_font;
1679 FontSpan Paragraph::fontSpan(pos_type pos) const
1681 LASSERT(pos <= size(), /**/);
1684 FontList::const_iterator cit = d->fontlist_.begin();
1685 FontList::const_iterator end = d->fontlist_.end();
1686 for (; cit != end; ++cit) {
1687 if (cit->pos() >= pos) {
1688 if (pos >= beginOfBody())
1689 return FontSpan(max(start, beginOfBody()),
1692 return FontSpan(start,
1693 min(beginOfBody() - 1,
1696 start = cit->pos() + 1;
1699 // This should not happen, but if so, we take no chances.
1700 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1701 return FontSpan(pos, pos);
1705 // Gets uninstantiated font setting at position 0
1706 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1708 if (!empty() && !d->fontlist_.empty())
1709 return d->fontlist_.begin()->font();
1711 // Optimisation: avoid a full font instantiation if there is no
1712 // language change from previous call.
1713 static Font previous_font;
1714 static Language const * previous_lang = 0;
1715 if (bparams.language != previous_lang) {
1716 previous_lang = bparams.language;
1717 previous_font = Font(inherit_font, bparams.language);
1720 return previous_font;
1724 // Gets the fully instantiated font at a given position in a paragraph
1725 // This is basically the same function as Text::GetFont() in text2.cpp.
1726 // The difference is that this one is used for generating the LaTeX file,
1727 // and thus cosmetic "improvements" are disallowed: This has to deliver
1728 // the true picture of the buffer. (Asger)
1729 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1730 Font const & outerfont) const
1732 LASSERT(pos >= 0, /**/);
1734 Font font = getFontSettings(bparams, pos);
1736 pos_type const body_pos = beginOfBody();
1737 FontInfo & fi = font.fontInfo();
1739 fi.realize(d->layout_->labelfont);
1741 fi.realize(d->layout_->font);
1743 fi.realize(outerfont.fontInfo());
1744 fi.realize(bparams.getFont().fontInfo());
1750 Font const Paragraph::getLabelFont
1751 (BufferParams const & bparams, Font const & outerfont) const
1753 FontInfo tmpfont = d->layout_->labelfont;
1754 tmpfont.realize(outerfont.fontInfo());
1755 tmpfont.realize(bparams.getFont().fontInfo());
1756 return Font(tmpfont, getParLanguage(bparams));
1760 Font const Paragraph::getLayoutFont
1761 (BufferParams const & bparams, Font const & outerfont) const
1763 FontInfo tmpfont = d->layout_->font;
1764 tmpfont.realize(outerfont.fontInfo());
1765 tmpfont.realize(bparams.getFont().fontInfo());
1766 return Font(tmpfont, getParLanguage(bparams));
1770 /// Returns the height of the highest font in range
1771 FontSize Paragraph::highestFontInRange
1772 (pos_type startpos, pos_type endpos, FontSize def_size) const
1774 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1778 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1780 char_type c = d->text_[pos];
1781 if (!lyxrc.rtl_support)
1811 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1817 void Paragraph::setFont(pos_type pos, Font const & font)
1819 LASSERT(pos <= size(), /**/);
1821 // First, reduce font against layout/label font
1822 // Update: The setCharFont() routine in text2.cpp already
1823 // reduces font, so we don't need to do that here. (Asger)
1825 d->fontlist_.set(pos, font);
1829 void Paragraph::makeSameLayout(Paragraph const & par)
1831 d->layout_ = par.d->layout_;
1832 d->params_ = par.d->params_;
1836 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1838 if (isFreeSpacing())
1844 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1845 if (eraseChar(pos, trackChanges))
1851 return count > 0 || pos > 0;
1855 bool Paragraph::hasSameLayout(Paragraph const & par) const
1857 return par.d->layout_ == d->layout_
1858 && d->params_.sameLayout(par.d->params_);
1862 depth_type Paragraph::getDepth() const
1864 return d->params_.depth();
1868 depth_type Paragraph::getMaxDepthAfter() const
1870 if (d->layout_->isEnvironment())
1871 return d->params_.depth() + 1;
1873 return d->params_.depth();
1877 char Paragraph::getAlign() const
1879 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1880 return d->layout_->align;
1882 return d->params_.align();
1886 docstring const & Paragraph::labelString() const
1888 return d->params_.labelString();
1892 // the next two functions are for the manual labels
1893 docstring const Paragraph::getLabelWidthString() const
1895 if (d->layout_->margintype == MARGIN_MANUAL
1896 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1897 return d->params_.labelWidthString();
1899 return _("Senseless with this layout!");
1903 void Paragraph::setLabelWidthString(docstring const & s)
1905 d->params_.labelWidthString(s);
1909 docstring Paragraph::expandLabel(Layout const & layout,
1910 BufferParams const & bparams) const
1912 return expandParagraphLabel(layout, bparams, true);
1916 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1917 BufferParams const & bparams) const
1919 return expandParagraphLabel(layout, bparams, false);
1923 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1924 BufferParams const & bparams, bool process_appendix) const
1926 DocumentClass const & tclass = bparams.documentClass();
1927 string const & lang = getParLanguage(bparams)->code();
1928 bool const in_appendix = process_appendix && d->params_.appendix();
1929 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1931 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1932 && !layout.counter.empty())
1933 return tclass.counters().theCounter(layout.counter, lang);
1935 // handle 'inherited level parts' in 'fmt',
1936 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1937 size_t const i = fmt.find('@', 0);
1938 if (i != docstring::npos) {
1939 size_t const j = fmt.find('@', i + 1);
1940 if (j != docstring::npos) {
1941 docstring parent(fmt, i + 1, j - i - 1);
1942 docstring label = from_ascii("??");
1943 if (tclass.hasLayout(parent))
1944 docstring label = expandParagraphLabel(tclass[parent], bparams,
1946 fmt = docstring(fmt, 0, i) + label
1947 + docstring(fmt, j + 1, docstring::npos);
1951 return tclass.counters().counterLabel(fmt, lang);
1955 void Paragraph::applyLayout(Layout const & new_layout)
1957 d->layout_ = &new_layout;
1958 LyXAlignment const oldAlign = d->params_.align();
1960 if (!(oldAlign & d->layout_->alignpossible)) {
1961 frontend::Alert::warning(_("Alignment not permitted"),
1962 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1963 d->params_.align(LYX_ALIGN_LAYOUT);
1968 pos_type Paragraph::beginOfBody() const
1970 return d->begin_of_body_;
1974 void Paragraph::setBeginOfBody()
1976 if (d->layout_->labeltype != LABEL_MANUAL) {
1977 d->begin_of_body_ = 0;
1981 // Unroll the first two cycles of the loop
1982 // and remember the previous character to
1983 // remove unnecessary getChar() calls
1985 pos_type end = size();
1986 if (i < end && !isNewline(i)) {
1988 char_type previous_char = 0;
1991 previous_char = d->text_[i];
1992 if (!isNewline(i)) {
1994 while (i < end && previous_char != ' ') {
1999 previous_char = temp;
2005 d->begin_of_body_ = i;
2009 bool Paragraph::allowParagraphCustomization() const
2011 return inInset().allowParagraphCustomization();
2015 bool Paragraph::usePlainLayout() const
2017 return inInset().usePlainLayout();
2023 // paragraphs inside floats need different alignment tags to avoid
2026 bool noTrivlistCentering(InsetCode code)
2028 return code == FLOAT_CODE
2029 || code == WRAP_CODE
2030 || code == CELL_CODE;
2034 string correction(string const & orig)
2036 if (orig == "flushleft")
2037 return "raggedright";
2038 if (orig == "flushright")
2039 return "raggedleft";
2040 if (orig == "center")
2046 string const corrected_env(string const & suffix, string const & env,
2047 InsetCode code, bool const lastpar)
2049 string output = suffix + "{";
2050 if (noTrivlistCentering(code)) {
2052 // the last paragraph in non-trivlist-aligned
2053 // context is special (to avoid unwanted whitespace)
2054 if (suffix == "\\begin")
2055 return "\\" + correction(env) + "{}";
2058 output += correction(env);
2062 if (suffix == "\\begin")
2068 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2070 if (!contains(str, "\n"))
2071 column += str.size();
2075 column = rsplit(str, tmp, '\n').size();
2082 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2083 odocstream & os, TexRow & texrow,
2084 OutputParams const & runparams) const
2088 if (params_.noindent()) {
2089 os << "\\noindent ";
2093 LyXAlignment const curAlign = params_.align();
2095 if (curAlign == layout_->align)
2099 case LYX_ALIGN_NONE:
2100 case LYX_ALIGN_BLOCK:
2101 case LYX_ALIGN_LAYOUT:
2102 case LYX_ALIGN_SPECIAL:
2103 case LYX_ALIGN_DECIMAL:
2105 case LYX_ALIGN_LEFT:
2106 case LYX_ALIGN_RIGHT:
2107 case LYX_ALIGN_CENTER:
2108 if (runparams.moving_arg) {
2115 string const begin_tag = "\\begin";
2116 InsetCode code = ownerCode();
2117 bool const lastpar = runparams.isLastPar;
2120 case LYX_ALIGN_NONE:
2121 case LYX_ALIGN_BLOCK:
2122 case LYX_ALIGN_LAYOUT:
2123 case LYX_ALIGN_SPECIAL:
2124 case LYX_ALIGN_DECIMAL:
2126 case LYX_ALIGN_LEFT: {
2128 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2129 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2131 output = corrected_env(begin_tag, "flushright", code, lastpar);
2132 os << from_ascii(output);
2133 adjust_row_column(output, texrow, column);
2135 } case LYX_ALIGN_RIGHT: {
2137 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2138 output = corrected_env(begin_tag, "flushright", code, lastpar);
2140 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2141 os << from_ascii(output);
2142 adjust_row_column(output, texrow, column);
2144 } case LYX_ALIGN_CENTER: {
2146 output = corrected_env(begin_tag, "center", code, lastpar);
2147 os << from_ascii(output);
2148 adjust_row_column(output, texrow, column);
2157 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2158 odocstream & os, TexRow & texrow,
2159 OutputParams const & runparams) const
2163 LyXAlignment const curAlign = params_.align();
2165 if (curAlign == layout_->align)
2169 case LYX_ALIGN_NONE:
2170 case LYX_ALIGN_BLOCK:
2171 case LYX_ALIGN_LAYOUT:
2172 case LYX_ALIGN_SPECIAL:
2173 case LYX_ALIGN_DECIMAL:
2175 case LYX_ALIGN_LEFT:
2176 case LYX_ALIGN_RIGHT:
2177 case LYX_ALIGN_CENTER:
2178 if (runparams.moving_arg) {
2185 string const end_tag = "\n\\par\\end";
2186 InsetCode code = ownerCode();
2187 bool const lastpar = runparams.isLastPar;
2190 case LYX_ALIGN_NONE:
2191 case LYX_ALIGN_BLOCK:
2192 case LYX_ALIGN_LAYOUT:
2193 case LYX_ALIGN_SPECIAL:
2194 case LYX_ALIGN_DECIMAL:
2196 case LYX_ALIGN_LEFT: {
2198 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2199 output = corrected_env(end_tag, "flushleft", code, lastpar);
2201 output = corrected_env(end_tag, "flushright", code, lastpar);
2202 os << from_ascii(output);
2203 adjust_row_column(output, texrow, column);
2205 } case LYX_ALIGN_RIGHT: {
2207 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2208 output = corrected_env(end_tag, "flushright", code, lastpar);
2210 output = corrected_env(end_tag, "flushleft", code, lastpar);
2211 os << from_ascii(output);
2212 adjust_row_column(output, texrow, column);
2214 } case LYX_ALIGN_CENTER: {
2216 output = corrected_env(end_tag, "center", code, lastpar);
2217 os << from_ascii(output);
2218 adjust_row_column(output, texrow, column);
2227 // This one spits out the text of the paragraph
2228 void Paragraph::latex(BufferParams const & bparams,
2229 Font const & outerfont,
2230 odocstream & os, TexRow & texrow,
2231 OutputParams const & runparams,
2232 int start_pos, int end_pos, bool force) const
2234 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2236 // FIXME This check should not be needed. Perhaps issue an
2237 // error if it triggers.
2238 Layout const & style = inInset().forcePlainLayout() ?
2239 bparams.documentClass().plainLayout() : *d->layout_;
2241 if (!force && style.inpreamble)
2244 bool const allowcust = allowParagraphCustomization();
2246 // Current base font for all inherited font changes, without any
2247 // change caused by an individual character, except for the language:
2248 // It is set to the language of the first character.
2249 // As long as we are in the label, this font is the base font of the
2250 // label. Before the first body character it is set to the base font
2254 // Maybe we have to create a optional argument.
2255 pos_type body_pos = beginOfBody();
2256 unsigned int column = 0;
2259 // the optional argument is kept in curly brackets in
2260 // case it contains a ']'
2263 basefont = getLabelFont(bparams, outerfont);
2265 basefont = getLayoutFont(bparams, outerfont);
2268 // Which font is currently active?
2269 Font running_font(basefont);
2270 // Do we have an open font change?
2271 bool open_font = false;
2273 Change runningChange = Change(Change::UNCHANGED);
2275 Encoding const * const prev_encoding = runparams.encoding;
2277 texrow.start(id(), 0);
2279 // if the paragraph is empty, the loop will not be entered at all
2281 if (style.isCommand()) {
2286 column += d->startTeXParParams(bparams, os, texrow,
2290 for (pos_type i = 0; i < size(); ++i) {
2291 // First char in paragraph or after label?
2292 if (i == body_pos) {
2295 column += running_font.latexWriteEndChanges(
2296 os, bparams, runparams,
2297 basefont, basefont);
2300 basefont = getLayoutFont(bparams, outerfont);
2301 running_font = basefont;
2303 column += Changes::latexMarkChange(os, bparams,
2304 runningChange, Change(Change::UNCHANGED),
2306 runningChange = Change(Change::UNCHANGED);
2311 if (style.isCommand()) {
2317 column += d->startTeXParParams(bparams, os,
2322 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2325 if (bparams.outputChanges && runningChange != change) {
2327 column += running_font.latexWriteEndChanges(
2328 os, bparams, runparams, basefont, basefont);
2331 basefont = getLayoutFont(bparams, outerfont);
2332 running_font = basefont;
2334 column += Changes::latexMarkChange(os, bparams, runningChange,
2336 runningChange = change;
2339 // do not output text which is marked deleted
2340 // if change tracking output is disabled
2341 if (!bparams.outputChanges && change.deleted()) {
2347 // Fully instantiated font
2348 Font const font = getFont(bparams, i, outerfont);
2350 Font const last_font = running_font;
2352 // Do we need to close the previous font?
2354 (font != running_font ||
2355 font.language() != running_font.language()))
2357 column += running_font.latexWriteEndChanges(
2358 os, bparams, runparams, basefont,
2359 (i == body_pos-1) ? basefont : font);
2360 running_font = basefont;
2364 // close babel's font environment before opening CJK.
2365 if (!running_font.language()->babel().empty() &&
2366 font.language()->encoding()->package() == Encoding::CJK) {
2367 string end_tag = subst(lyxrc.language_command_end,
2369 running_font.language()->babel());
2370 os << from_ascii(end_tag);
2371 column += end_tag.length();
2374 // Switch file encoding if necessary (and allowed)
2375 if (!runparams.pass_thru && !style.pass_thru &&
2376 runparams.encoding->package() != Encoding::none &&
2377 font.language()->encoding()->package() != Encoding::none) {
2378 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2379 runparams, *(font.language()->encoding()));
2380 if (enc_switch.first) {
2381 column += enc_switch.second;
2382 runparams.encoding = font.language()->encoding();
2386 char_type const c = d->text_[i];
2388 // Do we need to change font?
2389 if ((font != running_font ||
2390 font.language() != running_font.language()) &&
2393 odocstringstream ods;
2394 column += font.latexWriteStartChanges(ods, bparams,
2395 runparams, basefont,
2397 running_font = font;
2399 docstring fontchange = ods.str();
2400 // check whether the fontchange ends with a \\textcolor
2401 // modifier and the text starts with a space (bug 4473)
2402 docstring const last_modifier = rsplit(fontchange, '\\');
2403 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2404 os << fontchange << from_ascii("{}");
2405 // check if the fontchange ends with a trailing blank
2406 // (like "\small " (see bug 3382)
2407 else if (suffixIs(fontchange, ' ') && c == ' ')
2408 os << fontchange.substr(0, fontchange.size() - 1)
2409 << from_ascii("{}");
2414 // FIXME: think about end_pos implementation...
2415 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2416 // FIXME: integrate this case in latexSpecialChar
2417 // Do not print the separation of the optional argument
2418 // if style.pass_thru is false. This works because
2419 // latexSpecialChar ignores spaces if
2420 // style.pass_thru is false.
2421 if (i != body_pos - 1) {
2422 if (d->simpleTeXBlanks(
2423 runparams, os, texrow,
2424 i, column, font, style)) {
2425 // A surrogate pair was output. We
2426 // must not call latexSpecialChar
2427 // in this iteration, since it would output
2428 // the combining character again.
2435 OutputParams rp = runparams;
2436 rp.free_spacing = style.free_spacing;
2437 rp.local_font = &font;
2438 rp.intitle = style.intitle;
2440 // Two major modes: LaTeX or plain
2441 // Handle here those cases common to both modes
2442 // and then split to handle the two modes separately.
2443 if (c == META_INSET) {
2444 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2445 d->latexInset(bparams, os,
2446 texrow, rp, running_font,
2447 basefont, outerfont, open_font,
2448 runningChange, style, i, column);
2451 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2453 d->latexSpecialChar(os, rp, running_font, runningChange,
2455 } catch (EncodingException & e) {
2456 if (runparams.dryrun) {
2457 os << "<" << _("LyX Warning: ")
2458 << _("uncodable character") << " '";
2462 // add location information and throw again.
2471 // Set the encoding to that returned from latexSpecialChar (see
2472 // comment for encoding member in OutputParams.h)
2473 runparams.encoding = rp.encoding;
2476 // If we have an open font definition, we have to close it
2478 #ifdef FIXED_LANGUAGE_END_DETECTION
2480 running_font.latexWriteEndChanges(os, bparams,
2481 runparams, basefont,
2482 next_->getFont(bparams, 0, outerfont));
2484 running_font.latexWriteEndChanges(os, bparams,
2485 runparams, basefont, basefont);
2488 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2489 //FIXME: there as we start another \selectlanguage with the next paragraph if
2490 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2491 running_font.latexWriteEndChanges(os, bparams, runparams,
2492 basefont, basefont);
2496 column += Changes::latexMarkChange(os, bparams, runningChange,
2497 Change(Change::UNCHANGED), runparams);
2499 // Needed if there is an optional argument but no contents.
2500 if (body_pos > 0 && body_pos == size()) {
2504 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2505 && runparams.encoding != prev_encoding) {
2506 runparams.encoding = prev_encoding;
2507 if (!bparams.useXetex)
2508 os << setEncoding(prev_encoding->iconvName());
2511 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2515 bool Paragraph::emptyTag() const
2517 for (pos_type i = 0; i < size(); ++i) {
2518 if (Inset const * inset = getInset(i)) {
2519 InsetCode lyx_code = inset->lyxCode();
2520 // FIXME testing like that is wrong. What is
2522 if (lyx_code != TOC_CODE &&
2523 lyx_code != INCLUDE_CODE &&
2524 lyx_code != GRAPHICS_CODE &&
2525 lyx_code != ERT_CODE &&
2526 lyx_code != LISTINGS_CODE &&
2527 lyx_code != FLOAT_CODE &&
2528 lyx_code != TABULAR_CODE) {
2532 char_type c = d->text_[i];
2533 if (c != ' ' && c != '\t')
2541 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2544 for (pos_type i = 0; i < size(); ++i) {
2545 if (Inset const * inset = getInset(i)) {
2546 InsetCode lyx_code = inset->lyxCode();
2547 if (lyx_code == LABEL_CODE) {
2548 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2549 docstring const & id = il->getParam("name");
2550 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2558 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2562 for (i = 0; i < size(); ++i) {
2563 if (Inset const * inset = getInset(i)) {
2564 inset->docbook(os, runparams);
2566 char_type c = d->text_[i];
2569 os << sgml::escapeChar(c);
2576 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2580 for (i = 0; i < size(); ++i) {
2581 if (Inset const * inset = getInset(i)) {
2582 inset->xhtml(xs, runparams);
2584 char_type c = d->text_[i];
2594 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2597 pos_type size = text_.size();
2598 for (pos_type i = initial; i < size; ++i) {
2599 Font font = owner_->getFont(buf.params(), i, outerfont);
2600 if (text_[i] == META_INSET)
2602 if (i != initial && font != font_old)
2611 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2613 OutputParams const & runparams,
2614 Font const & outerfont,
2615 pos_type initial) const
2617 bool emph_flag = false;
2619 Layout const & style = *d->layout_;
2621 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2623 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2626 // parsing main loop
2627 for (pos_type i = initial; i < size(); ++i) {
2628 Font font = getFont(buf.params(), i, outerfont);
2630 // handle <emphasis> tag
2631 if (font_old.emph() != font.fontInfo().emph()) {
2632 if (font.fontInfo().emph() == FONT_ON) {
2635 } else if (i != initial) {
2636 os << "</emphasis>";
2641 if (Inset const * inset = getInset(i)) {
2642 inset->docbook(os, runparams);
2644 char_type c = d->text_[i];
2646 if (style.pass_thru)
2649 os << sgml::escapeChar(c);
2651 font_old = font.fontInfo();
2655 os << "</emphasis>";
2658 if (style.free_spacing)
2660 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2665 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2667 OutputParams const & runparams,
2668 Font const & outerfont,
2669 pos_type initial) const
2673 bool emph_flag = false;
2674 bool bold_flag = false;
2677 Layout const & style = *d->layout_;
2679 if (!runparams.for_toc && runparams.html_make_pars) {
2680 // generate a magic label for this paragraph
2681 string const attr = "id='" + magicLabel() + "'";
2682 xs << html::CompTag("a", attr);
2686 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2688 // parsing main loop
2689 for (pos_type i = initial; i < size(); ++i) {
2690 // let's not show deleted material in the output
2694 Font font = getFont(buf.params(), i, outerfont);
2697 if (font_old.emph() != font.fontInfo().emph()) {
2698 if (font.fontInfo().emph() == FONT_ON) {
2699 xs << html::StartTag("em");
2701 } else if (emph_flag && i != initial) {
2702 xs << html::EndTag("em");
2707 if (font_old.series() != font.fontInfo().series()) {
2708 if (font.fontInfo().series() == BOLD_SERIES) {
2709 xs << html::StartTag("strong");
2711 } else if (bold_flag && i != initial) {
2712 xs << html::EndTag("strong");
2717 // Other such tags? What about the other text ranges?
2719 Inset const * inset = getInset(i);
2721 InsetCommand const * ic = inset->asInsetCommand();
2722 InsetLayout const & il = inset->getLayout();
2723 InsetMath const * im = inset->asInsetMath();
2724 if (!runparams.for_toc
2725 || im || il.isInToc() || (ic && ic->isInToc())) {
2726 OutputParams np = runparams;
2727 if (!il.htmlisblock())
2728 np.html_in_par = true;
2729 retval += inset->xhtml(xs, np);
2732 char_type c = d->text_[i];
2734 if (style.pass_thru)
2736 else if (c == '-') {
2739 if (j < size() && d->text_[j] == '-') {
2741 if (j < size() && d->text_[j] == '-') {
2742 str += from_ascii("—");
2745 str += from_ascii("–");
2751 // We don't want to escape the entities. Note that
2752 // it is safe to do this, since str can otherwise
2753 // only be "-". E.g., it can't be "<".
2754 xs << XHTMLStream::NextRaw() << str;
2758 font_old = font.fontInfo();
2766 bool Paragraph::isHfill(pos_type pos) const
2768 Inset const * inset = getInset(pos);
2769 return inset && (inset->lyxCode() == SPACE_CODE &&
2770 inset->isStretchableSpace());
2774 bool Paragraph::isNewline(pos_type pos) const
2776 Inset const * inset = getInset(pos);
2777 return inset && inset->lyxCode() == NEWLINE_CODE;
2781 bool Paragraph::isLineSeparator(pos_type pos) const
2783 char_type const c = d->text_[pos];
2784 if (isLineSeparatorChar(c))
2786 Inset const * inset = getInset(pos);
2787 return inset && inset->isLineSeparator();
2791 bool Paragraph::isWordSeparator(pos_type pos) const
2793 if (Inset const * inset = getInset(pos))
2794 return !inset->isLetter();
2795 char_type const c = d->text_[pos];
2796 // We want to pass the ' and escape chars to the spellchecker
2797 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2798 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2803 bool Paragraph::isChar(pos_type pos) const
2805 if (Inset const * inset = getInset(pos))
2806 return inset->isChar();
2807 char_type const c = d->text_[pos];
2808 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2812 bool Paragraph::isSpace(pos_type pos) const
2814 if (Inset const * inset = getInset(pos))
2815 return inset->isSpace();
2816 char_type const c = d->text_[pos];
2817 return lyx::isSpace(c);
2822 Paragraph::getParLanguage(BufferParams const & bparams) const
2825 return getFirstFontSettings(bparams).language();
2826 // FIXME: we should check the prev par as well (Lgb)
2827 return bparams.language;
2831 bool Paragraph::isRTL(BufferParams const & bparams) const
2833 return lyxrc.rtl_support
2834 && getParLanguage(bparams)->rightToLeft()
2835 && !inInset().getLayout().forceLTR();
2839 void Paragraph::changeLanguage(BufferParams const & bparams,
2840 Language const * from, Language const * to)
2842 // change language including dummy font change at the end
2843 for (pos_type i = 0; i <= size(); ++i) {
2844 Font font = getFontSettings(bparams, i);
2845 if (font.language() == from) {
2846 font.setLanguage(to);
2850 d->requestSpellCheck(size());
2854 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2856 Language const * doc_language = bparams.language;
2857 FontList::const_iterator cit = d->fontlist_.begin();
2858 FontList::const_iterator end = d->fontlist_.end();
2860 for (; cit != end; ++cit)
2861 if (cit->font().language() != ignore_language &&
2862 cit->font().language() != latex_language &&
2863 cit->font().language() != doc_language)
2869 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2871 FontList::const_iterator cit = d->fontlist_.begin();
2872 FontList::const_iterator end = d->fontlist_.end();
2874 for (; cit != end; ++cit) {
2875 Language const * lang = cit->font().language();
2876 if (lang != ignore_language &&
2877 lang != latex_language)
2878 languages.insert(lang);
2883 docstring Paragraph::asString(int options) const
2885 return asString(0, size(), options);
2889 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2891 odocstringstream os;
2894 && options & AS_STR_LABEL
2895 && !d->params_.labelString().empty())
2896 os << d->params_.labelString() << ' ';
2898 for (pos_type i = beg; i < end; ++i) {
2899 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2901 char_type const c = d->text_[i];
2902 if (isPrintable(c) || c == '\t'
2903 || (c == '\n' && (options & AS_STR_NEWLINES)))
2905 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2906 getInset(i)->tocString(os);
2907 if (getInset(i)->asInsetMath())
2916 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2918 odocstringstream os;
2921 && options & AS_STR_LABEL
2922 && !d->params_.labelString().empty())
2923 os << d->params_.labelString() << ' ';
2925 for (pos_type i = beg; i < end; ++i) {
2926 char_type const c = d->text_[i];
2927 if (isPrintable(c) || c == '\t'
2928 || (c == '\n' && (options & AS_STR_NEWLINES)))
2930 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2931 getInset(i)->plaintext(os, runparams);
2939 void Paragraph::setInsetOwner(Inset const * inset)
2941 d->inset_owner_ = inset;
2945 int Paragraph::id() const
2951 void Paragraph::setId(int id)
2957 Layout const & Paragraph::layout() const
2963 void Paragraph::setLayout(Layout const & layout)
2965 d->layout_ = &layout;
2969 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2971 setLayout(tc.defaultLayout());
2975 void Paragraph::setPlainLayout(DocumentClass const & tc)
2977 setLayout(tc.plainLayout());
2981 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2983 if (usePlainLayout())
2984 setPlainLayout(tclass);
2986 setDefaultLayout(tclass);
2990 Inset const & Paragraph::inInset() const
2992 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2993 _("Memory problem"), _("Paragraph not properly initialized")));
2994 return *d->inset_owner_;
2998 ParagraphParameters & Paragraph::params()
3004 ParagraphParameters const & Paragraph::params() const
3010 bool Paragraph::isFreeSpacing() const
3012 if (d->layout_->free_spacing)
3014 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3018 bool Paragraph::allowEmpty() const
3020 if (d->layout_->keepempty)
3022 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3026 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3028 if (!Encodings::isArabicChar(c))
3031 char_type prev_char = ' ';
3032 char_type next_char = ' ';
3034 for (pos_type i = pos - 1; i >= 0; --i) {
3035 char_type const par_char = d->text_[i];
3036 if (!Encodings::isArabicComposeChar(par_char)) {
3037 prev_char = par_char;
3042 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3043 char_type const par_char = d->text_[i];
3044 if (!Encodings::isArabicComposeChar(par_char)) {
3045 next_char = par_char;
3050 if (Encodings::isArabicChar(next_char)) {
3051 if (Encodings::isArabicChar(prev_char) &&
3052 !Encodings::isArabicSpecialChar(prev_char))
3053 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3055 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3057 if (Encodings::isArabicChar(prev_char) &&
3058 !Encodings::isArabicSpecialChar(prev_char))
3059 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3061 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3066 int Paragraph::checkBiblio(Buffer const & buffer)
3069 // This is getting more and more a mess. ...We really should clean
3070 // up this bibitem issue for 1.6. See also bug 2743.
3072 // Add bibitem insets if necessary
3073 if (d->layout_->labeltype != LABEL_BIBLIO)
3076 bool hasbibitem = !d->insetlist_.empty()
3077 // Insist on it being in pos 0
3078 && d->text_[0] == META_INSET
3079 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3081 bool track_changes = buffer.params().trackChanges;
3086 // remove a bibitem in pos != 0
3087 // restore it later in pos 0 if necessary
3088 // (e.g. if a user inserts contents _before_ the item)
3089 // we're assuming there's only one of these, which there
3091 int erasedInsetPosition = -1;
3092 InsetList::iterator it = d->insetlist_.begin();
3093 InsetList::iterator end = d->insetlist_.end();
3094 for (; it != end; ++it)
3095 if (it->inset->lyxCode() == BIBITEM_CODE
3097 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3098 oldkey = olditem->getParam("key");
3099 oldlabel = olditem->getParam("label");
3100 erasedInsetPosition = it->pos;
3101 eraseChar(erasedInsetPosition, track_changes);
3105 // There was an InsetBibitem at the beginning, and we didn't
3106 // have to erase one.
3107 if (hasbibitem && erasedInsetPosition < 0)
3110 // There was an InsetBibitem at the beginning and we did have to
3111 // erase one. So we give its properties to the beginning inset.
3113 InsetBibitem * inset =
3114 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3115 if (!oldkey.empty())
3116 inset->setParam("key", oldkey);
3117 inset->setParam("label", oldlabel);
3118 return -erasedInsetPosition;
3121 // There was no inset at the beginning, so we need to create one with
3122 // the key and label of the one we erased.
3123 InsetBibitem * inset =
3124 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3125 // restore values of previously deleted item in this par.
3126 if (!oldkey.empty())
3127 inset->setParam("key", oldkey);
3128 inset->setParam("label", oldlabel);
3129 insertInset(0, static_cast<Inset *>(inset),
3130 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3136 void Paragraph::checkAuthors(AuthorList const & authorList)
3138 d->changes_.checkAuthors(authorList);
3142 bool Paragraph::isChanged(pos_type pos) const
3144 return lookupChange(pos).changed();
3148 bool Paragraph::isInserted(pos_type pos) const
3150 return lookupChange(pos).inserted();
3154 bool Paragraph::isDeleted(pos_type pos) const
3156 return lookupChange(pos).deleted();
3160 InsetList const & Paragraph::insetList() const
3162 return d->insetlist_;
3166 void Paragraph::setBuffer(Buffer & b)
3168 d->insetlist_.setBuffer(b);
3172 Inset * Paragraph::releaseInset(pos_type pos)
3174 Inset * inset = d->insetlist_.release(pos);
3175 /// does not honour change tracking!
3176 eraseChar(pos, false);
3181 Inset * Paragraph::getInset(pos_type pos)
3183 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3184 ? d->insetlist_.get(pos) : 0;
3188 Inset const * Paragraph::getInset(pos_type pos) const
3190 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3191 ? d->insetlist_.get(pos) : 0;
3195 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3196 pos_type & right, TextCase action)
3198 // process sequences of modified characters; in change
3199 // tracking mode, this approach results in much better
3200 // usability than changing case on a char-by-char basis
3203 bool const trackChanges = bparams.trackChanges;
3205 bool capitalize = true;
3207 for (; pos < right; ++pos) {
3208 char_type oldChar = d->text_[pos];
3209 char_type newChar = oldChar;
3211 // ignore insets and don't play with deleted text!
3212 if (oldChar != META_INSET && !isDeleted(pos)) {
3214 case text_lowercase:
3215 newChar = lowercase(oldChar);
3217 case text_capitalization:
3219 newChar = uppercase(oldChar);
3223 case text_uppercase:
3224 newChar = uppercase(oldChar);
3229 if (isWordSeparator(pos) || isDeleted(pos)) {
3230 // permit capitalization again
3234 if (oldChar != newChar) {
3236 if (pos != right - 1)
3238 // step behind the changing area
3242 int erasePos = pos - changes.size();
3243 for (size_t i = 0; i < changes.size(); i++) {
3244 insertChar(pos, changes[i],
3245 getFontSettings(bparams,
3248 if (!eraseChar(erasePos, trackChanges)) {
3251 ++right; // expand selection
3259 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3260 pos_type pos, bool del) const
3262 int const strsize = str.length();
3264 pos_type const parsize = d->text_.size();
3265 for (i = 0; pos + i < parsize; ++i) {
3268 if (cs && str[i] != d->text_[pos + i])
3270 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3272 if (!del && isDeleted(pos + i))
3279 // if necessary, check whether string matches word
3281 if (pos > 0 && !isWordSeparator(pos - 1))
3283 if (pos + strsize < parsize
3284 && !isWordSeparator(pos + strsize))
3292 char_type Paragraph::getChar(pos_type pos) const
3294 return d->text_[pos];
3298 pos_type Paragraph::size() const
3300 return d->text_.size();
3304 bool Paragraph::empty() const
3306 return d->text_.empty();
3310 bool Paragraph::isInset(pos_type pos) const
3312 return d->text_[pos] == META_INSET;
3316 bool Paragraph::isSeparator(pos_type pos) const
3318 //FIXME: Are we sure this can be the only separator?
3319 return d->text_[pos] == ' ';
3323 void Paragraph::deregisterWords()
3325 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3326 Private::LangWordsMap::const_iterator ite = d->words_.end();
3327 for (; itl != ite; ++itl) {
3328 WordList * wl = theWordList(itl->first);
3329 Private::Words::const_iterator it = (itl->second).begin();
3330 Private::Words::const_iterator et = (itl->second).end();
3331 for (; it != et; ++it)
3338 void Paragraph::locateWord(pos_type & from, pos_type & to,
3339 word_location const loc) const
3342 case WHOLE_WORD_STRICT:
3343 if (from == 0 || from == size()
3344 || isWordSeparator(from)
3345 || isWordSeparator(from - 1)) {
3349 // no break here, we go to the next
3352 // If we are already at the beginning of a word, do nothing
3353 if (!from || isWordSeparator(from - 1))
3355 // no break here, we go to the next
3358 // always move the cursor to the beginning of previous word
3359 while (from && !isWordSeparator(from - 1))
3363 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3366 // no need to move the 'from' cursor
3370 while (to < size() && !isWordSeparator(to))
3375 void Paragraph::collectWords()
3377 // This is the value that needs to be exposed in the preferences
3378 // to resolve bug #6760.
3379 static int minlength = 6;
3380 pos_type n = size();
3381 for (pos_type pos = 0; pos < n; ++pos) {
3382 if (isWordSeparator(pos))
3384 pos_type from = pos;
3385 locateWord(from, pos, WHOLE_WORD);
3386 if (pos - from >= minlength) {
3387 docstring word = asString(from, pos, AS_STR_NONE);
3388 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3389 if (cit == d->fontlist_.end())
3391 Language const * lang = cit->font().language();
3392 d->words_[*lang].insert(word);
3398 void Paragraph::registerWords()
3400 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3401 Private::LangWordsMap::const_iterator ite = d->words_.end();
3402 for (; itl != ite; ++itl) {
3403 WordList * wl = theWordList(itl->first);
3404 Private::Words::const_iterator it = (itl->second).begin();
3405 Private::Words::const_iterator et = (itl->second).end();
3406 for (; it != et; ++it)
3412 void Paragraph::updateWords()
3420 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3422 SkipPositionsIterator begin = skips.begin();
3423 SkipPositions::iterator end = skips.end();
3424 if (pos > 0 && begin < end) {
3426 if (end->last == pos - 1) {
3431 skips.insert(end, FontSpan(pos, pos));
3435 Language * Paragraph::Private::locateSpellRange(
3436 pos_type & from, pos_type & to,
3437 SkipPositions & skips) const
3439 // skip leading white space
3440 while (from < to && owner_->isWordSeparator(from))
3442 // don't check empty range
3445 // get current language
3446 Language * lang = getSpellLanguage(from);
3447 pos_type last = from;
3448 bool samelang = true;
3449 bool sameinset = true;
3450 while (last < to && samelang && sameinset) {
3451 // hop to end of word
3452 while (last < to && !owner_->isWordSeparator(last)) {
3453 if (owner_->getInset(last)) {
3454 appendSkipPosition(skips, last);
3455 } else if (owner_->isDeleted(last)) {
3456 appendSkipPosition(skips, last);
3460 // hop to next word while checking for insets
3461 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3462 if (Inset const * inset = owner_->getInset(last))
3463 sameinset = inset->isChar() && inset->isLetter();
3464 if (sameinset && owner_->isDeleted(last)) {
3465 appendSkipPosition(skips, last);
3470 if (sameinset && last < to) {
3471 // now check for language change
3472 samelang = lang == getSpellLanguage(last);
3475 // if language change detected backstep is needed
3483 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3486 const_cast<Language *>(owner_->getFontSettings(
3487 inset_owner_->buffer().params(), from).language());
3488 if (lang == inset_owner_->buffer().params().language
3489 && !lyxrc.spellchecker_alt_lang.empty()) {
3491 string const lang_variety =
3492 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3493 lang->setCode(lang_code);
3494 lang->setVariety(lang_variety);
3500 void Paragraph::requestSpellCheck(pos_type pos)
3502 d->requestSpellCheck(pos == -1 ? size() : pos);
3506 bool Paragraph::needsSpellCheck() const
3508 SpellChecker::ChangeNumber speller_change_number = 0;
3509 if (theSpellChecker())
3510 speller_change_number = theSpellChecker()->changeNumber();
3511 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3512 d->speller_state_.needsCompleteRefresh(speller_change_number);
3514 return d->needsSpellCheck();
3518 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3519 WordLangTuple & wl, docstring_list & suggestions,
3520 bool do_suggestion, bool check_learned) const
3522 SpellChecker::Result result = SpellChecker::WORD_OK;
3523 SpellChecker * speller = theSpellChecker();
3527 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3530 locateWord(from, to, WHOLE_WORD);
3531 if (from == to || from >= size())
3534 docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3535 Language * lang = d->getSpellLanguage(from);
3537 wl = WordLangTuple(word, lang);
3542 if (needsSpellCheck() || check_learned) {
3543 // Ignore words with digits
3544 // FIXME: make this customizable
3545 // (note that some checkers ignore words with digits by default)
3546 if (!hasDigit(word)) {
3547 bool const trailing_dot = to < size() && d->text_[to] == '.';
3548 result = speller->check(wl);
3549 if (SpellChecker::misspelled(result) && trailing_dot) {
3550 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3551 result = speller->check(wl);
3552 if (!SpellChecker::misspelled(result)) {
3553 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3555 from << ".." << to << "]");
3559 d->setMisspelled(from, to, result);
3561 result = d->speller_state_.getState(from);
3564 bool const misspelled_ = SpellChecker::misspelled(result) ;
3565 if (misspelled_ && do_suggestion)
3566 speller->suggest(wl, suggestions);
3567 else if (misspelled_)
3568 LYXERR(Debug::GUI, "misspelled word: \"" <<
3570 from << ".." << to << "]");
3572 suggestions.clear();
3578 void Paragraph::Private::markMisspelledWords(
3579 pos_type const & first, pos_type const & last,
3580 SpellChecker::Result result,
3581 docstring const & word,
3582 SkipPositions const & skips)
3584 if (!SpellChecker::misspelled(result)) {
3585 setMisspelled(first, last, SpellChecker::WORD_OK);
3589 SpellChecker * speller = theSpellChecker();
3590 // locate and enumerate the error positions
3591 int nerrors = speller->numMisspelledWords();
3593 SkipPositionsIterator it = skips.begin();
3594 SkipPositionsIterator et = skips.end();
3595 for (int index = 0; index < nerrors; ++index) {
3598 speller->misspelledWord(index, wstart, wlen);
3599 /// should not happen if speller supports range checks
3600 if (!wlen) continue;
3601 docstring const misspelled = word.substr(wstart, wlen);
3602 wstart += first + numskipped;
3603 if (snext < wstart) {
3604 /// mark the range of correct spelling
3605 numskipped += countSkips(it, et, wstart);
3606 setMisspelled(snext,
3607 wstart - 1, SpellChecker::WORD_OK);
3609 snext = wstart + wlen;
3610 numskipped += countSkips(it, et, snext);
3611 /// mark the range of misspelling
3612 setMisspelled(wstart, snext, result);
3613 LYXERR(Debug::GUI, "misspelled word: \"" <<
3614 misspelled << "\" [" <<
3615 wstart << ".." << (snext-1) << "]");
3618 if (snext <= last) {
3619 /// mark the range of correct spelling at end
3620 setMisspelled(snext, last, SpellChecker::WORD_OK);
3625 void Paragraph::spellCheck() const
3627 SpellChecker * speller = theSpellChecker();
3628 if (!speller || !size() ||!needsSpellCheck())
3632 d->rangeOfSpellCheck(start, endpos);
3633 if (speller->canCheckParagraph()) {
3634 // loop until we leave the range
3635 for (pos_type first = start; first < endpos; ) {
3636 pos_type last = endpos;
3637 Private::SkipPositions skips;
3638 Language * lang = d->locateSpellRange(first, last, skips);
3639 if (first >= endpos)
3641 // start the spell checker on the unit of meaning
3642 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3643 WordLangTuple wl = WordLangTuple(word, lang);
3644 SpellChecker::Result result = word.size() ?
3645 speller->check(wl) : SpellChecker::WORD_OK;
3646 d->markMisspelledWords(first, last, result, word, skips);
3650 static docstring_list suggestions;
3651 pos_type to = endpos;
3652 while (start < endpos) {
3654 spellCheck(start, to, wl, suggestions, false);
3658 d->readySpellCheck();
3662 bool Paragraph::isMisspelled(pos_type pos) const
3664 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3668 string Paragraph::magicLabel() const
3671 ss << "magicparlabel-" << id();