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 inset positions
337 typedef vector<pos_type> Positions;
338 typedef Positions::const_iterator PositionsIterator;
340 Language * getSpellLanguage(pos_type const from) const;
342 Language * locateSpellRange(pos_type & from, pos_type & to,
343 Positions & softbreaks) const;
345 bool hasSpellerChange() const {
346 SpellChecker::ChangeNumber speller_change_number = 0;
347 if (theSpellChecker())
348 speller_change_number = theSpellChecker()->changeNumber();
349 return speller_change_number > speller_state_.currentChangeNumber();
352 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
354 pos_type textsize = owner_->size();
355 // check for sane arguments
356 if (to < from || from >= textsize)
358 FontSpan fp = FontSpan(from, to);
359 // don't mark end of paragraph
360 if (fp.last >= textsize)
361 fp.last = textsize - 1;
362 speller_state_.setRange(fp, state);
365 void requestSpellCheck(pos_type pos) {
366 speller_state_.needsRefresh(pos);
369 void readySpellCheck() {
370 speller_state_.needsRefresh(-1);
373 bool needsSpellCheck() const
375 return speller_state_.needsRefresh();
378 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
380 speller_state_.refreshRange(first, last);
382 last = owner_->size();
385 pos_type endpos = last;
386 owner_->locateWord(first, endpos, WHOLE_WORD);
389 owner_->locateWord(last, endpos, WHOLE_WORD);
394 int countSoftbreaks(PositionsIterator & it, PositionsIterator const et,
398 while (it != et && *it < start) {
406 void markMisspelledWords(pos_type const & first, pos_type const & last,
407 SpellChecker::Result result,
408 docstring const & word,
409 Positions const & softbreaks);
411 InsetCode ownerCode() const
413 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
416 /// Which Paragraph owns us?
420 Inset const * inset_owner_;
429 ParagraphParameters params_;
431 /// for recording and looking up changes
435 InsetList insetlist_;
438 pos_type begin_of_body_;
440 typedef docstring TextContainer;
444 typedef set<docstring> Words;
445 typedef map<Language, Words> LangWordsMap;
449 Layout const * layout_;
451 SpellCheckerState speller_state_;
457 struct special_phrase {
463 special_phrase const special_phrases[] = {
464 { "LyX", from_ascii("\\LyX{}"), false },
465 { "TeX", from_ascii("\\TeX{}"), true },
466 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
467 { "LaTeX", from_ascii("\\LaTeX{}"), true },
470 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
475 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
476 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
482 // Initialization of the counter for the paragraph id's,
484 // FIXME: There should be a more intelligent way to generate and use the
485 // paragraph ids per buffer instead a global static counter for all InsetText
486 // in the running program.
487 static int paragraph_id = -1;
489 Paragraph::Private::Private(Private const & p, Paragraph * owner)
490 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
491 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
492 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
495 id_ = ++paragraph_id;
496 requestSpellCheck(p.text_.size());
500 Paragraph::Private::Private(Private const & p, Paragraph * owner,
501 pos_type beg, pos_type end)
502 : owner_(owner), inset_owner_(p.inset_owner_),
503 params_(p.params_), changes_(p.changes_),
504 insetlist_(p.insetlist_, beg, end),
505 begin_of_body_(p.begin_of_body_), words_(p.words_),
508 id_ = ++paragraph_id;
509 if (beg >= pos_type(p.text_.size()))
511 text_ = p.text_.substr(beg, end - beg);
513 FontList::const_iterator fcit = fontlist_.begin();
514 FontList::const_iterator fend = fontlist_.end();
515 for (; fcit != fend; ++fcit) {
516 if (fcit->pos() < beg)
518 if (fcit->pos() >= end) {
519 // Add last entry in the fontlist_.
520 fontlist_.set(text_.size() - 1, fcit->font());
523 // Add a new entry in the fontlist_.
524 fontlist_.set(fcit->pos() - beg, fcit->font());
526 requestSpellCheck(p.text_.size());
530 void Paragraph::addChangesToToc(DocIterator const & cdit,
531 Buffer const & buf) const
533 d->changes_.addToToc(cdit, buf);
537 bool Paragraph::isDeleted(pos_type start, pos_type end) const
539 LASSERT(start >= 0 && start <= size(), /**/);
540 LASSERT(end > start && end <= size() + 1, /**/);
542 return d->changes_.isDeleted(start, end);
546 bool Paragraph::isChanged(pos_type start, pos_type end) const
548 LASSERT(start >= 0 && start <= size(), /**/);
549 LASSERT(end > start && end <= size() + 1, /**/);
551 return d->changes_.isChanged(start, end);
555 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
557 // keep the logic here in sync with the logic of eraseChars()
561 Change const change = d->changes_.lookup(size());
562 return change.inserted() && change.currentAuthor();
566 void Paragraph::setChange(Change const & change)
568 // beware of the imaginary end-of-par character!
569 d->changes_.set(change, 0, size() + 1);
572 * Propagate the change recursively - but not in case of DELETED!
574 * Imagine that your co-author makes changes in an existing inset. He
575 * sends your document to you and you come to the conclusion that the
576 * inset should go completely. If you erase it, LyX must not delete all
577 * text within the inset. Otherwise, the change tracked insertions of
578 * your co-author get lost and there is no way to restore them later.
580 * Conclusion: An inset's content should remain untouched if you delete it
583 if (!change.deleted()) {
584 for (pos_type pos = 0; pos < size(); ++pos) {
585 if (Inset * inset = getInset(pos))
586 inset->setChange(change);
592 void Paragraph::setChange(pos_type pos, Change const & change)
594 LASSERT(pos >= 0 && pos <= size(), /**/);
595 d->changes_.set(change, pos);
597 // see comment in setChange(Change const &) above
598 if (!change.deleted() && pos < size())
599 if (Inset * inset = getInset(pos))
600 inset->setChange(change);
604 Change const & Paragraph::lookupChange(pos_type pos) const
606 LASSERT(pos >= 0 && pos <= size(), /**/);
607 return d->changes_.lookup(pos);
611 void Paragraph::acceptChanges(pos_type start, pos_type end)
613 LASSERT(start >= 0 && start <= size(), /**/);
614 LASSERT(end > start && end <= size() + 1, /**/);
616 for (pos_type pos = start; pos < end; ++pos) {
617 switch (lookupChange(pos).type) {
618 case Change::UNCHANGED:
619 // accept changes in nested inset
620 if (Inset * inset = getInset(pos))
621 inset->acceptChanges();
624 case Change::INSERTED:
625 d->changes_.set(Change(Change::UNCHANGED), pos);
626 // also accept changes in nested inset
627 if (Inset * inset = getInset(pos))
628 inset->acceptChanges();
631 case Change::DELETED:
632 // Suppress access to non-existent
633 // "end-of-paragraph char"
635 eraseChar(pos, false);
646 void Paragraph::rejectChanges(pos_type start, pos_type end)
648 LASSERT(start >= 0 && start <= size(), /**/);
649 LASSERT(end > start && end <= size() + 1, /**/);
651 for (pos_type pos = start; pos < end; ++pos) {
652 switch (lookupChange(pos).type) {
653 case Change::UNCHANGED:
654 // reject changes in nested inset
655 if (Inset * inset = getInset(pos))
656 inset->rejectChanges();
659 case Change::INSERTED:
660 // Suppress access to non-existent
661 // "end-of-paragraph char"
663 eraseChar(pos, false);
669 case Change::DELETED:
670 d->changes_.set(Change(Change::UNCHANGED), pos);
672 // Do NOT reject changes within a deleted inset!
673 // There may be insertions of a co-author inside of it!
681 void Paragraph::Private::insertChar(pos_type pos, char_type c,
682 Change const & change)
684 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
687 changes_.insert(change, pos);
689 // This is actually very common when parsing buffers (and
690 // maybe inserting ascii text)
691 if (pos == pos_type(text_.size())) {
692 // when appending characters, no need to update tables
694 // but we want spell checking
695 requestSpellCheck(pos);
699 text_.insert(text_.begin() + pos, c);
701 // Update the font table.
702 fontlist_.increasePosAfterPos(pos);
705 insetlist_.increasePosAfterPos(pos);
707 // Update list of misspelled positions
708 speller_state_.increasePosAfterPos(pos);
712 bool Paragraph::insertInset(pos_type pos, Inset * inset,
713 Change const & change)
715 LASSERT(inset, /**/);
716 LASSERT(pos >= 0 && pos <= size(), /**/);
718 // Paragraph::insertInset() can be used in cut/copy/paste operation where
719 // d->inset_owner_ is not set yet.
720 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
723 d->insertChar(pos, META_INSET, change);
724 LASSERT(d->text_[pos] == META_INSET, /**/);
726 // Add a new entry in the insetlist_.
727 d->insetlist_.insert(inset, pos);
729 // Some insets require run of spell checker
730 requestSpellCheck(pos);
735 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
737 LASSERT(pos >= 0 && pos <= size(), return false);
739 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
742 Change change = d->changes_.lookup(pos);
744 // set the character to DELETED if
745 // a) it was previously unchanged or
746 // b) it was inserted by a co-author
748 if (!change.changed() ||
749 (change.inserted() && !change.currentAuthor())) {
750 setChange(pos, Change(Change::DELETED));
754 if (change.deleted())
758 // Don't physically access the imaginary end-of-paragraph character.
759 // eraseChar() can only mark it as DELETED. A physical deletion of
760 // end-of-par must be handled externally.
766 d->changes_.erase(pos);
768 // if it is an inset, delete the inset entry
769 if (d->text_[pos] == META_INSET)
770 d->insetlist_.erase(pos);
772 d->text_.erase(d->text_.begin() + pos);
774 // Update the fontlist_
775 d->fontlist_.erase(pos);
777 // Update the insetlist_
778 d->insetlist_.decreasePosAfterPos(pos);
780 // Update list of misspelled positions
781 d->speller_state_.decreasePosAfterPos(pos);
787 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
789 LASSERT(start >= 0 && start <= size(), /**/);
790 LASSERT(end >= start && end <= size() + 1, /**/);
793 for (pos_type count = end - start; count; --count) {
794 if (!eraseChar(i, trackChanges))
801 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
802 char_type next, OutputParams const & runparams)
804 // Writing next here may circumvent a possible font change between
805 // c and next. Since next is only output if it forms a surrogate pair
806 // with c we can ignore this:
807 // A font change inside a surrogate pair does not make sense and is
808 // hopefully impossible to input.
809 // FIXME: change tracking
810 // Is this correct WRT change tracking?
811 Encoding const & encoding = *(runparams.encoding);
812 docstring const latex1 = encoding.latexChar(next);
813 docstring const latex2 = encoding.latexChar(c);
814 if (docstring(1, next) == latex1) {
815 // the encoding supports the combination
816 os << latex2 << latex1;
817 return latex1.length() + latex2.length();
818 } else if (runparams.local_font &&
819 runparams.local_font->language()->lang() == "polutonikogreek") {
820 // polutonikogreek only works without the brackets
821 os << latex1 << latex2;
822 return latex1.length() + latex2.length();
824 os << latex1 << '{' << latex2 << '}';
825 return latex1.length() + latex2.length() + 2;
829 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
830 odocstream & os, TexRow & texrow,
832 unsigned int & column,
834 Layout const & style)
836 if (style.pass_thru || runparams.pass_thru)
839 if (i + 1 < int(text_.size())) {
840 char_type next = text_[i + 1];
841 if (Encodings::isCombiningChar(next)) {
842 // This space has an accent, so we must always output it.
843 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
848 if (runparams.linelen > 0
849 && column > runparams.linelen
851 && text_[i - 1] != ' '
852 && (i + 1 < int(text_.size()))
853 // same in FreeSpacing mode
854 && !owner_->isFreeSpacing()
855 // In typewriter mode, we want to avoid
856 // ! . ? : at the end of a line
857 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
858 && (text_[i - 1] == '.'
859 || text_[i - 1] == '?'
860 || text_[i - 1] == ':'
861 || text_[i - 1] == '!'))) {
864 texrow.start(owner_->id(), i + 1);
866 } else if (style.free_spacing) {
875 int Paragraph::Private::writeScriptChars(odocstream & os,
876 docstring const & ltx,
877 Change const & runningChange,
878 Encoding const & encoding,
881 // FIXME: modifying i here is not very nice...
883 // We only arrive here when a proper language for character text_[i] has
884 // not been specified (i.e., it could not be translated in the current
885 // latex encoding) or its latex translation has been forced, and it
886 // belongs to a known script.
887 // Parameter ltx contains the latex translation of text_[i] as specified
888 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
889 // The latex macro name "textXXX" specifies the script to which text_[i]
890 // belongs and we use it in order to check whether characters from the
891 // same script immediately follow, such that we can collect them in a
892 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
893 // for the first char but only "<spec>" for all subsequent chars.
894 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
895 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
896 string script = to_ascii(ltx.substr(1, brace1 - 1));
899 bool closing_brace = true;
900 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
901 // Correct encoding is being used, so we can avoid \textgreek.
904 closing_brace = false;
906 os << ltx.substr(pos, length);
907 int size = text_.size();
908 while (i + 1 < size) {
909 char_type const next = text_[i + 1];
910 // Stop here if next character belongs to another script
911 // or there is a change in change tracking status.
912 if (!Encodings::isKnownScriptChar(next, script) ||
913 runningChange != owner_->lookupChange(i + 1))
917 FontList::const_iterator cit = fontlist_.begin();
918 FontList::const_iterator end = fontlist_.end();
919 for (; cit != end; ++cit) {
920 if (cit->pos() >= i && !found) {
921 prev_font = cit->font();
924 if (cit->pos() >= i + 1)
927 // Stop here if there is a font attribute or encoding change.
928 if (found && cit != end && prev_font != cit->font())
930 docstring const latex = encoding.latexChar(next);
931 docstring::size_type const b1 =
932 latex.find_first_of(from_ascii("{"));
933 docstring::size_type const b2 =
934 latex.find_last_of(from_ascii("}"));
935 int const len = b2 - b1 - 1;
936 os << latex.substr(b1 + 1, len);
948 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
950 pos_type const len = str.length();
952 // is the paragraph large enough?
953 if (pos + len > int(text_.size()))
956 // does the wanted text start at point?
957 for (string::size_type i = 0; i < str.length(); ++i) {
958 // Caution: direct comparison of characters works only
959 // because str is pure ASCII.
960 if (str[i] != text_[pos + i])
964 return fontlist_.hasChangeInRange(pos, len);
968 void Paragraph::Private::latexInset(BufferParams const & bparams,
971 OutputParams & runparams,
974 Font const & outerfont,
976 Change & running_change,
977 Layout const & style,
979 unsigned int & column)
981 Inset * inset = owner_->getInset(i);
982 LASSERT(inset, /**/);
984 if (style.pass_thru) {
985 inset->plaintext(os, runparams);
989 // FIXME: move this to InsetNewline::latex
990 if (inset->lyxCode() == NEWLINE_CODE) {
991 // newlines are handled differently here than
992 // the default in simpleTeXSpecialChars().
993 if (!style.newline_allowed) {
997 column += running_font.latexWriteEndChanges(
998 os, bparams, runparams,
1003 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1006 basefont = owner_->getLayoutFont(bparams, outerfont);
1007 running_font = basefont;
1009 if (runparams.moving_arg)
1014 texrow.start(owner_->id(), i + 1);
1018 if (owner_->isDeleted(i)) {
1019 if( ++runparams.inDeletedInset == 1)
1020 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1023 if (inset->canTrackChanges()) {
1024 column += Changes::latexMarkChange(os, bparams, running_change,
1025 Change(Change::UNCHANGED), runparams);
1026 running_change = Change(Change::UNCHANGED);
1030 odocstream::pos_type const len = os.tellp();
1032 if (inset->forceLTR()
1033 && running_font.isRightToLeft()
1034 // ERT is an exception, it should be output with no
1035 // decorations at all
1036 && inset->lyxCode() != ERT_CODE) {
1037 if (running_font.language()->lang() == "farsi")
1044 // FIXME: Bug: we can have an empty font change here!
1045 // if there has just been a font change, we are going to close it
1046 // right now, which means stupid latex code like \textsf{}. AFAIK,
1047 // this does not harm dvi output. A minor bug, thus (JMarc)
1049 // Some insets cannot be inside a font change command.
1050 // However, even such insets *can* be placed in \L or \R
1051 // or their equivalents (for RTL language switches), so we don't
1052 // close the language in those cases.
1053 // ArabTeX, though, cannot handle this special behavior, it seems.
1054 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1055 || running_font.language()->lang() == "arabic_arabtex";
1056 if (open_font && inset->noFontChange()) {
1057 bool closeLanguage = arabtex
1058 || basefont.isRightToLeft() == running_font.isRightToLeft();
1059 unsigned int count = running_font.latexWriteEndChanges(os,
1060 bparams, runparams, basefont, basefont, closeLanguage);
1062 // if any font properties were closed, update the running_font,
1063 // making sure, however, to leave the language as it was
1065 // FIXME: probably a better way to keep track of the old
1066 // language, than copying the entire font?
1067 Font const copy_font(running_font);
1068 basefont = owner_->getLayoutFont(bparams, outerfont);
1069 running_font = basefont;
1071 running_font.setLanguage(copy_font.language());
1072 // leave font open if language is still open
1073 open_font = (running_font.language() == basefont.language());
1075 runparams.local_font = &basefont;
1082 tmp = inset->latex(os, runparams);
1083 } catch (EncodingException & e) {
1084 // add location information and throw again.
1091 if (running_font.language()->lang() == "farsi")
1098 texrow.newlines(tmp);
1099 texrow.start(owner_->id(), i + 1);
1102 column += os.tellp() - len;
1105 if (owner_->isDeleted(i))
1106 --runparams.inDeletedInset;
1110 void Paragraph::Private::latexSpecialChar(
1112 OutputParams const & runparams,
1113 Font const & running_font,
1114 Change const & running_change,
1115 Layout const & style,
1117 unsigned int & column)
1119 char_type const c = text_[i];
1121 if (style.pass_thru || runparams.pass_thru) {
1123 // FIXME UNICODE: This can fail if c cannot
1124 // be encoded in the current encoding.
1129 // If T1 font encoding is used, use the special
1130 // characters it provides.
1131 // NOTE: some languages reset the font encoding
1133 if (!running_font.language()->internalFontEncoding()
1134 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1137 // \tt font needs special treatment
1138 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1139 && latexSpecialTypewriter(c, os, i, column))
1142 // Otherwise, we use what LaTeX provides us.
1145 os << "\\textbackslash{}";
1149 os << "\\textless{}";
1153 os << "\\textgreater{}";
1157 os << "\\textbar{}";
1164 os << "\\char`\\\"{}";
1169 case '%': case '#': case '{':
1177 os << "\\textasciitilde{}";
1182 os << "\\textasciicircum{}";
1189 // avoid being mistaken for optional arguments
1197 // Blanks are printed before font switching.
1198 // Sure? I am not! (try nice-latex)
1199 // I am sure it's correct. LyX might be smarter
1200 // in the future, but for now, nothing wrong is
1206 if (latexSpecialPhrase(os, i, column, runparams))
1212 Encoding const & encoding = *(runparams.encoding);
1213 if (i + 1 < int(text_.size())) {
1214 char_type next = text_[i + 1];
1215 if (Encodings::isCombiningChar(next)) {
1216 column += latexSurrogatePair(os, c, next, runparams) - 1;
1222 docstring const latex = encoding.latexChar(c);
1223 if (Encodings::isKnownScriptChar(c, script)
1224 && prefixIs(latex, from_ascii("\\" + script)))
1225 column += writeScriptChars(os, latex,
1226 running_change, encoding, i) - 1;
1227 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1228 // Prevent eating of a following
1229 // space or command corruption by
1230 // following characters
1231 column += latex.length() + 1;
1232 os << latex << "{}";
1234 column += latex.length() - 1;
1242 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1243 pos_type i, unsigned int & column)
1249 // In T1 encoding, these characters exist
1250 // but we should avoid ligatures
1251 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1253 os << "\\textcompwordmark{}";
1260 // soul.sty breaks with \char`\"
1261 os << "\\textquotedbl{}";
1270 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1271 pos_type i, unsigned int & column)
1275 // within \ttfamily, "--" is merged to "-" (no endash)
1276 // so we avoid this rather irritating ligature
1277 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1284 // everything else has to be checked separately
1285 // (depending on the encoding)
1292 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1293 unsigned int & column, OutputParams const & runparams)
1295 // FIXME: if we have "LaTeX" with a font
1296 // change in the middle (before the 'T', then
1297 // the "TeX" part is still special cased.
1298 // Really we should only operate this on
1299 // "words" for some definition of word
1301 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1302 if (!isTextAt(special_phrases[pnr].phrase, i))
1304 if (runparams.moving_arg)
1306 os << special_phrases[pnr].macro;
1307 i += special_phrases[pnr].phrase.length() - 1;
1308 column += special_phrases[pnr].macro.length() - 1;
1315 void Paragraph::Private::validate(LaTeXFeatures & features) const
1317 if (layout_->inpreamble && inset_owner_) {
1318 Buffer const & buf = inset_owner_->buffer();
1319 BufferParams const & bp = buf.params();
1322 odocstringstream ods;
1323 // we have to provide all the optional arguments here, even though
1324 // the last one is the only one we care about.
1325 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1326 docstring const d = ods.str();
1328 // this will have "{" at the beginning, but not at the end
1329 string const content = to_utf8(d);
1330 string const cmd = layout_->latexname();
1331 features.addPreambleSnippet("\\" + cmd + content + "}");
1335 if (features.runparams().flavor == OutputParams::HTML
1336 && layout_->htmltitle()) {
1337 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1340 // check the params.
1341 if (!params_.spacing().isDefault())
1342 features.require("setspace");
1345 features.useLayout(layout_->name());
1348 fontlist_.validate(features);
1350 // then the indentation
1351 if (!params_.leftIndent().zero())
1352 features.require("ParagraphLeftIndent");
1355 InsetList::const_iterator icit = insetlist_.begin();
1356 InsetList::const_iterator iend = insetlist_.end();
1357 for (; icit != iend; ++icit) {
1359 icit->inset->validate(features);
1360 if (layout_->needprotect &&
1361 icit->inset->lyxCode() == FOOT_CODE)
1362 features.require("NeedLyXFootnoteCode");
1366 // then the contents
1367 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1368 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1369 if (!special_phrases[pnr].builtin
1370 && isTextAt(special_phrases[pnr].phrase, i)) {
1371 features.require(special_phrases[pnr].phrase);
1375 Encodings::validate(text_[i], features);
1379 /////////////////////////////////////////////////////////////////////
1383 /////////////////////////////////////////////////////////////////////
1386 Layout const emptyParagraphLayout;
1389 Paragraph::Paragraph()
1390 : d(new Paragraph::Private(this, emptyParagraphLayout))
1397 Paragraph::Paragraph(Paragraph const & par)
1398 : itemdepth(par.itemdepth),
1399 d(new Paragraph::Private(*par.d, this))
1405 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1406 : itemdepth(par.itemdepth),
1407 d(new Paragraph::Private(*par.d, this, beg, end))
1413 Paragraph & Paragraph::operator=(Paragraph const & par)
1415 // needed as we will destroy the private part before copying it
1417 itemdepth = par.itemdepth;
1421 d = new Private(*par.d, this);
1428 Paragraph::~Paragraph()
1437 // this shall be called just before every "os << ..." action.
1438 void flushString(ostream & os, docstring & s)
1447 void Paragraph::write(ostream & os, BufferParams const & bparams,
1448 depth_type & dth) const
1450 // The beginning or end of a deeper (i.e. nested) area?
1451 if (dth != d->params_.depth()) {
1452 if (d->params_.depth() > dth) {
1453 while (d->params_.depth() > dth) {
1454 os << "\n\\begin_deeper";
1458 while (d->params_.depth() < dth) {
1459 os << "\n\\end_deeper";
1465 // First write the layout
1466 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1468 d->params_.write(os);
1470 Font font1(inherit_font, bparams.language);
1472 Change running_change = Change(Change::UNCHANGED);
1474 // this string is used as a buffer to avoid repetitive calls
1475 // to to_utf8(), which turn out to be expensive (JMarc)
1476 docstring write_buffer;
1479 for (pos_type i = 0; i <= size(); ++i) {
1481 Change const change = lookupChange(i);
1482 if (change != running_change)
1483 flushString(os, write_buffer);
1484 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1485 running_change = change;
1490 // Write font changes
1491 Font font2 = getFontSettings(bparams, i);
1492 if (font2 != font1) {
1493 flushString(os, write_buffer);
1494 font2.lyxWriteChanges(font1, os);
1499 char_type const c = d->text_[i];
1502 if (Inset const * inset = getInset(i)) {
1503 flushString(os, write_buffer);
1504 if (inset->directWrite()) {
1505 // international char, let it write
1506 // code directly so it's shorter in
1512 os << "\\begin_inset ";
1514 os << "\n\\end_inset\n\n";
1520 flushString(os, write_buffer);
1521 os << "\n\\backslash\n";
1525 flushString(os, write_buffer);
1526 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1533 if ((column > 70 && c == ' ')
1535 flushString(os, write_buffer);
1539 // this check is to amend a bug. LyX sometimes
1540 // inserts '\0' this could cause problems.
1542 write_buffer.push_back(c);
1544 LYXERR0("NUL char in structure.");
1550 flushString(os, write_buffer);
1551 os << "\n\\end_layout\n";
1555 void Paragraph::validate(LaTeXFeatures & features) const
1557 d->validate(features);
1561 void Paragraph::insert(pos_type start, docstring const & str,
1562 Font const & font, Change const & change)
1564 for (size_t i = 0, n = str.size(); i != n ; ++i)
1565 insertChar(start + i, str[i], font, change);
1569 void Paragraph::appendChar(char_type c, Font const & font,
1570 Change const & change)
1573 d->changes_.insert(change, d->text_.size());
1574 // when appending characters, no need to update tables
1575 d->text_.push_back(c);
1576 setFont(d->text_.size() - 1, font);
1580 void Paragraph::appendString(docstring const & s, Font const & font,
1581 Change const & change)
1583 pos_type end = s.size();
1584 size_t oldsize = d->text_.size();
1585 size_t newsize = oldsize + end;
1586 size_t capacity = d->text_.capacity();
1587 if (newsize >= capacity)
1588 d->text_.reserve(max(capacity + 100, newsize));
1590 // when appending characters, no need to update tables
1593 // FIXME: Optimize this!
1594 for (size_t i = oldsize; i != newsize; ++i) {
1596 d->changes_.insert(change, i);
1598 d->fontlist_.set(oldsize, font);
1599 d->fontlist_.set(newsize - 1, font);
1603 void Paragraph::insertChar(pos_type pos, char_type c,
1606 d->insertChar(pos, c, Change(trackChanges ?
1607 Change::INSERTED : Change::UNCHANGED));
1611 void Paragraph::insertChar(pos_type pos, char_type c,
1612 Font const & font, bool trackChanges)
1614 d->insertChar(pos, c, Change(trackChanges ?
1615 Change::INSERTED : Change::UNCHANGED));
1620 void Paragraph::insertChar(pos_type pos, char_type c,
1621 Font const & font, Change const & change)
1623 d->insertChar(pos, c, change);
1628 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1629 Font const & font, Change const & change)
1631 bool const success = insertInset(pos, inset, change);
1632 // Set the font/language of the inset...
1638 void Paragraph::resetFonts(Font const & font)
1640 d->fontlist_.clear();
1641 d->fontlist_.set(0, font);
1642 d->fontlist_.set(d->text_.size() - 1, font);
1645 // Gets uninstantiated font setting at position.
1646 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1650 LYXERR0("pos: " << pos << " size: " << size());
1651 LASSERT(pos <= size(), /**/);
1654 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1655 if (cit != d->fontlist_.end())
1658 if (pos == size() && !empty())
1659 return getFontSettings(bparams, pos - 1);
1661 // Optimisation: avoid a full font instantiation if there is no
1662 // language change from previous call.
1663 static Font previous_font;
1664 static Language const * previous_lang = 0;
1665 Language const * lang = getParLanguage(bparams);
1666 if (lang != previous_lang) {
1667 previous_lang = lang;
1668 previous_font = Font(inherit_font, lang);
1670 return previous_font;
1674 FontSpan Paragraph::fontSpan(pos_type pos) const
1676 LASSERT(pos <= size(), /**/);
1679 FontList::const_iterator cit = d->fontlist_.begin();
1680 FontList::const_iterator end = d->fontlist_.end();
1681 for (; cit != end; ++cit) {
1682 if (cit->pos() >= pos) {
1683 if (pos >= beginOfBody())
1684 return FontSpan(max(start, beginOfBody()),
1687 return FontSpan(start,
1688 min(beginOfBody() - 1,
1691 start = cit->pos() + 1;
1694 // This should not happen, but if so, we take no chances.
1695 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1696 return FontSpan(pos, pos);
1700 // Gets uninstantiated font setting at position 0
1701 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1703 if (!empty() && !d->fontlist_.empty())
1704 return d->fontlist_.begin()->font();
1706 // Optimisation: avoid a full font instantiation if there is no
1707 // language change from previous call.
1708 static Font previous_font;
1709 static Language const * previous_lang = 0;
1710 if (bparams.language != previous_lang) {
1711 previous_lang = bparams.language;
1712 previous_font = Font(inherit_font, bparams.language);
1715 return previous_font;
1719 // Gets the fully instantiated font at a given position in a paragraph
1720 // This is basically the same function as Text::GetFont() in text2.cpp.
1721 // The difference is that this one is used for generating the LaTeX file,
1722 // and thus cosmetic "improvements" are disallowed: This has to deliver
1723 // the true picture of the buffer. (Asger)
1724 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1725 Font const & outerfont) const
1727 LASSERT(pos >= 0, /**/);
1729 Font font = getFontSettings(bparams, pos);
1731 pos_type const body_pos = beginOfBody();
1732 FontInfo & fi = font.fontInfo();
1734 fi.realize(d->layout_->labelfont);
1736 fi.realize(d->layout_->font);
1738 fi.realize(outerfont.fontInfo());
1739 fi.realize(bparams.getFont().fontInfo());
1745 Font const Paragraph::getLabelFont
1746 (BufferParams const & bparams, Font const & outerfont) const
1748 FontInfo tmpfont = d->layout_->labelfont;
1749 tmpfont.realize(outerfont.fontInfo());
1750 tmpfont.realize(bparams.getFont().fontInfo());
1751 return Font(tmpfont, getParLanguage(bparams));
1755 Font const Paragraph::getLayoutFont
1756 (BufferParams const & bparams, Font const & outerfont) const
1758 FontInfo tmpfont = d->layout_->font;
1759 tmpfont.realize(outerfont.fontInfo());
1760 tmpfont.realize(bparams.getFont().fontInfo());
1761 return Font(tmpfont, getParLanguage(bparams));
1765 /// Returns the height of the highest font in range
1766 FontSize Paragraph::highestFontInRange
1767 (pos_type startpos, pos_type endpos, FontSize def_size) const
1769 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1773 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1775 char_type c = d->text_[pos];
1776 if (!lyxrc.rtl_support)
1806 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1812 void Paragraph::setFont(pos_type pos, Font const & font)
1814 LASSERT(pos <= size(), /**/);
1816 // First, reduce font against layout/label font
1817 // Update: The setCharFont() routine in text2.cpp already
1818 // reduces font, so we don't need to do that here. (Asger)
1820 d->fontlist_.set(pos, font);
1824 void Paragraph::makeSameLayout(Paragraph const & par)
1826 d->layout_ = par.d->layout_;
1827 d->params_ = par.d->params_;
1831 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1833 if (isFreeSpacing())
1839 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1840 if (eraseChar(pos, trackChanges))
1846 return count > 0 || pos > 0;
1850 bool Paragraph::hasSameLayout(Paragraph const & par) const
1852 return par.d->layout_ == d->layout_
1853 && d->params_.sameLayout(par.d->params_);
1857 depth_type Paragraph::getDepth() const
1859 return d->params_.depth();
1863 depth_type Paragraph::getMaxDepthAfter() const
1865 if (d->layout_->isEnvironment())
1866 return d->params_.depth() + 1;
1868 return d->params_.depth();
1872 char Paragraph::getAlign() const
1874 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1875 return d->layout_->align;
1877 return d->params_.align();
1881 docstring const & Paragraph::labelString() const
1883 return d->params_.labelString();
1887 // the next two functions are for the manual labels
1888 docstring const Paragraph::getLabelWidthString() const
1890 if (d->layout_->margintype == MARGIN_MANUAL
1891 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1892 return d->params_.labelWidthString();
1894 return _("Senseless with this layout!");
1898 void Paragraph::setLabelWidthString(docstring const & s)
1900 d->params_.labelWidthString(s);
1904 docstring Paragraph::expandLabel(Layout const & layout,
1905 BufferParams const & bparams) const
1907 return expandParagraphLabel(layout, bparams, true);
1911 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1912 BufferParams const & bparams) const
1914 return expandParagraphLabel(layout, bparams, false);
1918 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1919 BufferParams const & bparams, bool process_appendix) const
1921 DocumentClass const & tclass = bparams.documentClass();
1922 string const & lang = getParLanguage(bparams)->code();
1923 bool const in_appendix = process_appendix && d->params_.appendix();
1924 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1926 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1927 && !layout.counter.empty())
1928 return tclass.counters().theCounter(layout.counter, lang);
1930 // handle 'inherited level parts' in 'fmt',
1931 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1932 size_t const i = fmt.find('@', 0);
1933 if (i != docstring::npos) {
1934 size_t const j = fmt.find('@', i + 1);
1935 if (j != docstring::npos) {
1936 docstring parent(fmt, i + 1, j - i - 1);
1937 docstring label = from_ascii("??");
1938 if (tclass.hasLayout(parent))
1939 docstring label = expandParagraphLabel(tclass[parent], bparams,
1941 fmt = docstring(fmt, 0, i) + label
1942 + docstring(fmt, j + 1, docstring::npos);
1946 return tclass.counters().counterLabel(fmt, lang);
1950 void Paragraph::applyLayout(Layout const & new_layout)
1952 d->layout_ = &new_layout;
1953 LyXAlignment const oldAlign = d->params_.align();
1955 if (!(oldAlign & d->layout_->alignpossible)) {
1956 frontend::Alert::warning(_("Alignment not permitted"),
1957 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1958 d->params_.align(LYX_ALIGN_LAYOUT);
1963 pos_type Paragraph::beginOfBody() const
1965 return d->begin_of_body_;
1969 void Paragraph::setBeginOfBody()
1971 if (d->layout_->labeltype != LABEL_MANUAL) {
1972 d->begin_of_body_ = 0;
1976 // Unroll the first two cycles of the loop
1977 // and remember the previous character to
1978 // remove unnecessary getChar() calls
1980 pos_type end = size();
1981 if (i < end && !isNewline(i)) {
1983 char_type previous_char = 0;
1986 previous_char = d->text_[i];
1987 if (!isNewline(i)) {
1989 while (i < end && previous_char != ' ') {
1994 previous_char = temp;
2000 d->begin_of_body_ = i;
2004 bool Paragraph::allowParagraphCustomization() const
2006 return inInset().allowParagraphCustomization();
2010 bool Paragraph::usePlainLayout() const
2012 return inInset().usePlainLayout();
2018 // paragraphs inside floats need different alignment tags to avoid
2021 bool noTrivlistCentering(InsetCode code)
2023 return code == FLOAT_CODE
2024 || code == WRAP_CODE
2025 || code == CELL_CODE;
2029 string correction(string const & orig)
2031 if (orig == "flushleft")
2032 return "raggedright";
2033 if (orig == "flushright")
2034 return "raggedleft";
2035 if (orig == "center")
2041 string const corrected_env(string const & suffix, string const & env,
2042 InsetCode code, bool const lastpar)
2044 string output = suffix + "{";
2045 if (noTrivlistCentering(code)) {
2047 // the last paragraph in non-trivlist-aligned
2048 // context is special (to avoid unwanted whitespace)
2049 if (suffix == "\\begin")
2050 return "\\" + correction(env) + "{}";
2053 output += correction(env);
2057 if (suffix == "\\begin")
2063 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2065 if (!contains(str, "\n"))
2066 column += str.size();
2070 column = rsplit(str, tmp, '\n').size();
2077 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2078 odocstream & os, TexRow & texrow,
2079 OutputParams const & runparams) const
2083 if (params_.noindent()) {
2084 os << "\\noindent ";
2088 LyXAlignment const curAlign = params_.align();
2090 if (curAlign == layout_->align)
2094 case LYX_ALIGN_NONE:
2095 case LYX_ALIGN_BLOCK:
2096 case LYX_ALIGN_LAYOUT:
2097 case LYX_ALIGN_SPECIAL:
2098 case LYX_ALIGN_DECIMAL:
2100 case LYX_ALIGN_LEFT:
2101 case LYX_ALIGN_RIGHT:
2102 case LYX_ALIGN_CENTER:
2103 if (runparams.moving_arg) {
2110 string const begin_tag = "\\begin";
2111 InsetCode code = ownerCode();
2112 bool const lastpar = runparams.isLastPar;
2115 case LYX_ALIGN_NONE:
2116 case LYX_ALIGN_BLOCK:
2117 case LYX_ALIGN_LAYOUT:
2118 case LYX_ALIGN_SPECIAL:
2119 case LYX_ALIGN_DECIMAL:
2121 case LYX_ALIGN_LEFT: {
2123 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2124 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2126 output = corrected_env(begin_tag, "flushright", code, lastpar);
2127 os << from_ascii(output);
2128 adjust_row_column(output, texrow, column);
2130 } case LYX_ALIGN_RIGHT: {
2132 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2133 output = corrected_env(begin_tag, "flushright", code, lastpar);
2135 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2136 os << from_ascii(output);
2137 adjust_row_column(output, texrow, column);
2139 } case LYX_ALIGN_CENTER: {
2141 output = corrected_env(begin_tag, "center", code, lastpar);
2142 os << from_ascii(output);
2143 adjust_row_column(output, texrow, column);
2152 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2153 odocstream & os, TexRow & texrow,
2154 OutputParams const & runparams) const
2158 LyXAlignment const curAlign = params_.align();
2160 if (curAlign == layout_->align)
2164 case LYX_ALIGN_NONE:
2165 case LYX_ALIGN_BLOCK:
2166 case LYX_ALIGN_LAYOUT:
2167 case LYX_ALIGN_SPECIAL:
2168 case LYX_ALIGN_DECIMAL:
2170 case LYX_ALIGN_LEFT:
2171 case LYX_ALIGN_RIGHT:
2172 case LYX_ALIGN_CENTER:
2173 if (runparams.moving_arg) {
2180 string const end_tag = "\n\\par\\end";
2181 InsetCode code = ownerCode();
2182 bool const lastpar = runparams.isLastPar;
2185 case LYX_ALIGN_NONE:
2186 case LYX_ALIGN_BLOCK:
2187 case LYX_ALIGN_LAYOUT:
2188 case LYX_ALIGN_SPECIAL:
2189 case LYX_ALIGN_DECIMAL:
2191 case LYX_ALIGN_LEFT: {
2193 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2194 output = corrected_env(end_tag, "flushleft", code, lastpar);
2196 output = corrected_env(end_tag, "flushright", code, lastpar);
2197 os << from_ascii(output);
2198 adjust_row_column(output, texrow, column);
2200 } case LYX_ALIGN_RIGHT: {
2202 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2203 output = corrected_env(end_tag, "flushright", code, lastpar);
2205 output = corrected_env(end_tag, "flushleft", code, lastpar);
2206 os << from_ascii(output);
2207 adjust_row_column(output, texrow, column);
2209 } case LYX_ALIGN_CENTER: {
2211 output = corrected_env(end_tag, "center", code, lastpar);
2212 os << from_ascii(output);
2213 adjust_row_column(output, texrow, column);
2222 // This one spits out the text of the paragraph
2223 void Paragraph::latex(BufferParams const & bparams,
2224 Font const & outerfont,
2225 odocstream & os, TexRow & texrow,
2226 OutputParams const & runparams,
2227 int start_pos, int end_pos, bool force) const
2229 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2231 // FIXME This check should not be needed. Perhaps issue an
2232 // error if it triggers.
2233 Layout const & style = inInset().forcePlainLayout() ?
2234 bparams.documentClass().plainLayout() : *d->layout_;
2236 if (!force && style.inpreamble)
2239 bool const allowcust = allowParagraphCustomization();
2241 // Current base font for all inherited font changes, without any
2242 // change caused by an individual character, except for the language:
2243 // It is set to the language of the first character.
2244 // As long as we are in the label, this font is the base font of the
2245 // label. Before the first body character it is set to the base font
2249 // Maybe we have to create a optional argument.
2250 pos_type body_pos = beginOfBody();
2251 unsigned int column = 0;
2254 // the optional argument is kept in curly brackets in
2255 // case it contains a ']'
2258 basefont = getLabelFont(bparams, outerfont);
2260 basefont = getLayoutFont(bparams, outerfont);
2263 // Which font is currently active?
2264 Font running_font(basefont);
2265 // Do we have an open font change?
2266 bool open_font = false;
2268 Change runningChange = Change(Change::UNCHANGED);
2270 Encoding const * const prev_encoding = runparams.encoding;
2272 texrow.start(id(), 0);
2274 // if the paragraph is empty, the loop will not be entered at all
2276 if (style.isCommand()) {
2281 column += d->startTeXParParams(bparams, os, texrow,
2285 for (pos_type i = 0; i < size(); ++i) {
2286 // First char in paragraph or after label?
2287 if (i == body_pos) {
2290 column += running_font.latexWriteEndChanges(
2291 os, bparams, runparams,
2292 basefont, basefont);
2295 basefont = getLayoutFont(bparams, outerfont);
2296 running_font = basefont;
2298 column += Changes::latexMarkChange(os, bparams,
2299 runningChange, Change(Change::UNCHANGED),
2301 runningChange = Change(Change::UNCHANGED);
2306 if (style.isCommand()) {
2312 column += d->startTeXParParams(bparams, os,
2317 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2320 if (bparams.outputChanges && runningChange != change) {
2322 column += running_font.latexWriteEndChanges(
2323 os, bparams, runparams, basefont, basefont);
2326 basefont = getLayoutFont(bparams, outerfont);
2327 running_font = basefont;
2329 column += Changes::latexMarkChange(os, bparams, runningChange,
2331 runningChange = change;
2334 // do not output text which is marked deleted
2335 // if change tracking output is disabled
2336 if (!bparams.outputChanges && change.deleted()) {
2342 // Fully instantiated font
2343 Font const font = getFont(bparams, i, outerfont);
2345 Font const last_font = running_font;
2347 // Do we need to close the previous font?
2349 (font != running_font ||
2350 font.language() != running_font.language()))
2352 column += running_font.latexWriteEndChanges(
2353 os, bparams, runparams, basefont,
2354 (i == body_pos-1) ? basefont : font);
2355 running_font = basefont;
2359 // close babel's font environment before opening CJK.
2360 if (!running_font.language()->babel().empty() &&
2361 font.language()->encoding()->package() == Encoding::CJK) {
2362 string end_tag = subst(lyxrc.language_command_end,
2364 running_font.language()->babel());
2365 os << from_ascii(end_tag);
2366 column += end_tag.length();
2369 // Switch file encoding if necessary (and allowed)
2370 if (!runparams.pass_thru && !style.pass_thru &&
2371 runparams.encoding->package() != Encoding::none &&
2372 font.language()->encoding()->package() != Encoding::none) {
2373 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2374 runparams, *(font.language()->encoding()));
2375 if (enc_switch.first) {
2376 column += enc_switch.second;
2377 runparams.encoding = font.language()->encoding();
2381 char_type const c = d->text_[i];
2383 // Do we need to change font?
2384 if ((font != running_font ||
2385 font.language() != running_font.language()) &&
2388 odocstringstream ods;
2389 column += font.latexWriteStartChanges(ods, bparams,
2390 runparams, basefont,
2392 running_font = font;
2394 docstring fontchange = ods.str();
2395 // check whether the fontchange ends with a \\textcolor
2396 // modifier and the text starts with a space (bug 4473)
2397 docstring const last_modifier = rsplit(fontchange, '\\');
2398 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2399 os << fontchange << from_ascii("{}");
2400 // check if the fontchange ends with a trailing blank
2401 // (like "\small " (see bug 3382)
2402 else if (suffixIs(fontchange, ' ') && c == ' ')
2403 os << fontchange.substr(0, fontchange.size() - 1)
2404 << from_ascii("{}");
2409 // FIXME: think about end_pos implementation...
2410 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2411 // FIXME: integrate this case in latexSpecialChar
2412 // Do not print the separation of the optional argument
2413 // if style.pass_thru is false. This works because
2414 // latexSpecialChar ignores spaces if
2415 // style.pass_thru is false.
2416 if (i != body_pos - 1) {
2417 if (d->simpleTeXBlanks(
2418 runparams, os, texrow,
2419 i, column, font, style)) {
2420 // A surrogate pair was output. We
2421 // must not call latexSpecialChar
2422 // in this iteration, since it would output
2423 // the combining character again.
2430 OutputParams rp = runparams;
2431 rp.free_spacing = style.free_spacing;
2432 rp.local_font = &font;
2433 rp.intitle = style.intitle;
2435 // Two major modes: LaTeX or plain
2436 // Handle here those cases common to both modes
2437 // and then split to handle the two modes separately.
2438 if (c == META_INSET) {
2439 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2440 d->latexInset(bparams, os,
2441 texrow, rp, running_font,
2442 basefont, outerfont, open_font,
2443 runningChange, style, i, column);
2446 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2448 d->latexSpecialChar(os, rp, running_font, runningChange,
2450 } catch (EncodingException & e) {
2451 if (runparams.dryrun) {
2452 os << "<" << _("LyX Warning: ")
2453 << _("uncodable character") << " '";
2457 // add location information and throw again.
2466 // Set the encoding to that returned from latexSpecialChar (see
2467 // comment for encoding member in OutputParams.h)
2468 runparams.encoding = rp.encoding;
2471 // If we have an open font definition, we have to close it
2473 #ifdef FIXED_LANGUAGE_END_DETECTION
2475 running_font.latexWriteEndChanges(os, bparams,
2476 runparams, basefont,
2477 next_->getFont(bparams, 0, outerfont));
2479 running_font.latexWriteEndChanges(os, bparams,
2480 runparams, basefont, basefont);
2483 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2484 //FIXME: there as we start another \selectlanguage with the next paragraph if
2485 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2486 running_font.latexWriteEndChanges(os, bparams, runparams,
2487 basefont, basefont);
2491 column += Changes::latexMarkChange(os, bparams, runningChange,
2492 Change(Change::UNCHANGED), runparams);
2494 // Needed if there is an optional argument but no contents.
2495 if (body_pos > 0 && body_pos == size()) {
2499 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2500 && runparams.encoding != prev_encoding) {
2501 runparams.encoding = prev_encoding;
2502 if (!bparams.useXetex)
2503 os << setEncoding(prev_encoding->iconvName());
2506 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2510 bool Paragraph::emptyTag() const
2512 for (pos_type i = 0; i < size(); ++i) {
2513 if (Inset const * inset = getInset(i)) {
2514 InsetCode lyx_code = inset->lyxCode();
2515 // FIXME testing like that is wrong. What is
2517 if (lyx_code != TOC_CODE &&
2518 lyx_code != INCLUDE_CODE &&
2519 lyx_code != GRAPHICS_CODE &&
2520 lyx_code != ERT_CODE &&
2521 lyx_code != LISTINGS_CODE &&
2522 lyx_code != FLOAT_CODE &&
2523 lyx_code != TABULAR_CODE) {
2527 char_type c = d->text_[i];
2528 if (c != ' ' && c != '\t')
2536 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2539 for (pos_type i = 0; i < size(); ++i) {
2540 if (Inset const * inset = getInset(i)) {
2541 InsetCode lyx_code = inset->lyxCode();
2542 if (lyx_code == LABEL_CODE) {
2543 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2544 docstring const & id = il->getParam("name");
2545 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2553 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2557 for (i = 0; i < size(); ++i) {
2558 if (Inset const * inset = getInset(i)) {
2559 inset->docbook(os, runparams);
2561 char_type c = d->text_[i];
2564 os << sgml::escapeChar(c);
2571 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2575 for (i = 0; i < size(); ++i) {
2576 if (Inset const * inset = getInset(i)) {
2577 inset->xhtml(xs, runparams);
2579 char_type c = d->text_[i];
2589 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2592 pos_type size = text_.size();
2593 for (pos_type i = initial; i < size; ++i) {
2594 Font font = owner_->getFont(buf.params(), i, outerfont);
2595 if (text_[i] == META_INSET)
2597 if (i != initial && font != font_old)
2606 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2608 OutputParams const & runparams,
2609 Font const & outerfont,
2610 pos_type initial) const
2612 bool emph_flag = false;
2614 Layout const & style = *d->layout_;
2616 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2618 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2621 // parsing main loop
2622 for (pos_type i = initial; i < size(); ++i) {
2623 Font font = getFont(buf.params(), i, outerfont);
2625 // handle <emphasis> tag
2626 if (font_old.emph() != font.fontInfo().emph()) {
2627 if (font.fontInfo().emph() == FONT_ON) {
2630 } else if (i != initial) {
2631 os << "</emphasis>";
2636 if (Inset const * inset = getInset(i)) {
2637 inset->docbook(os, runparams);
2639 char_type c = d->text_[i];
2641 if (style.pass_thru)
2644 os << sgml::escapeChar(c);
2646 font_old = font.fontInfo();
2650 os << "</emphasis>";
2653 if (style.free_spacing)
2655 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2660 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2662 OutputParams const & runparams,
2663 Font const & outerfont,
2664 pos_type initial) const
2668 bool emph_flag = false;
2669 bool bold_flag = false;
2672 Layout const & style = *d->layout_;
2674 if (!runparams.for_toc && runparams.html_make_pars) {
2675 // generate a magic label for this paragraph
2676 string const attr = "id='" + magicLabel() + "'";
2677 xs << html::CompTag("a", attr);
2681 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2683 // parsing main loop
2684 for (pos_type i = initial; i < size(); ++i) {
2685 // let's not show deleted material in the output
2689 Font font = getFont(buf.params(), i, outerfont);
2692 if (font_old.emph() != font.fontInfo().emph()) {
2693 if (font.fontInfo().emph() == FONT_ON) {
2694 xs << html::StartTag("em");
2696 } else if (emph_flag && i != initial) {
2697 xs << html::EndTag("em");
2702 if (font_old.series() != font.fontInfo().series()) {
2703 if (font.fontInfo().series() == BOLD_SERIES) {
2704 xs << html::StartTag("strong");
2706 } else if (bold_flag && i != initial) {
2707 xs << html::EndTag("strong");
2712 // Other such tags? What about the other text ranges?
2714 Inset const * inset = getInset(i);
2716 InsetCommand const * ic = inset->asInsetCommand();
2717 InsetLayout const & il = inset->getLayout();
2718 InsetMath const * im = inset->asInsetMath();
2719 if (!runparams.for_toc
2720 || im || il.isInToc() || (ic && ic->isInToc())) {
2721 OutputParams np = runparams;
2722 if (!il.htmlisblock())
2723 np.html_in_par = true;
2724 retval += inset->xhtml(xs, np);
2727 char_type c = d->text_[i];
2729 if (style.pass_thru)
2731 else if (c == '-') {
2734 if (j < size() && d->text_[j] == '-') {
2736 if (j < size() && d->text_[j] == '-') {
2737 str += from_ascii("—");
2740 str += from_ascii("–");
2746 // We don't want to escape the entities. Note that
2747 // it is safe to do this, since str can otherwise
2748 // only be "-". E.g., it can't be "<".
2749 xs << XHTMLStream::NextRaw() << str;
2753 font_old = font.fontInfo();
2761 bool Paragraph::isHfill(pos_type pos) const
2763 Inset const * inset = getInset(pos);
2764 return inset && (inset->lyxCode() == SPACE_CODE &&
2765 inset->isStretchableSpace());
2769 bool Paragraph::isNewline(pos_type pos) const
2771 Inset const * inset = getInset(pos);
2772 return inset && inset->lyxCode() == NEWLINE_CODE;
2776 bool Paragraph::isLineSeparator(pos_type pos) const
2778 char_type const c = d->text_[pos];
2779 if (isLineSeparatorChar(c))
2781 Inset const * inset = getInset(pos);
2782 return inset && inset->isLineSeparator();
2786 bool Paragraph::isWordSeparator(pos_type pos) const
2788 if (Inset const * inset = getInset(pos))
2789 return !inset->isLetter();
2790 char_type const c = d->text_[pos];
2791 // We want to pass the ' and escape chars to the spellchecker
2792 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2793 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2798 bool Paragraph::isChar(pos_type pos) const
2800 if (Inset const * inset = getInset(pos))
2801 return inset->isChar();
2802 char_type const c = d->text_[pos];
2803 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2807 bool Paragraph::isSpace(pos_type pos) const
2809 if (Inset const * inset = getInset(pos))
2810 return inset->isSpace();
2811 char_type const c = d->text_[pos];
2812 return lyx::isSpace(c);
2817 Paragraph::getParLanguage(BufferParams const & bparams) const
2820 return getFirstFontSettings(bparams).language();
2821 // FIXME: we should check the prev par as well (Lgb)
2822 return bparams.language;
2826 bool Paragraph::isRTL(BufferParams const & bparams) const
2828 return lyxrc.rtl_support
2829 && getParLanguage(bparams)->rightToLeft()
2830 && !inInset().getLayout().forceLTR();
2834 void Paragraph::changeLanguage(BufferParams const & bparams,
2835 Language const * from, Language const * to)
2837 // change language including dummy font change at the end
2838 for (pos_type i = 0; i <= size(); ++i) {
2839 Font font = getFontSettings(bparams, i);
2840 if (font.language() == from) {
2841 font.setLanguage(to);
2845 d->requestSpellCheck(size());
2849 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2851 Language const * doc_language = bparams.language;
2852 FontList::const_iterator cit = d->fontlist_.begin();
2853 FontList::const_iterator end = d->fontlist_.end();
2855 for (; cit != end; ++cit)
2856 if (cit->font().language() != ignore_language &&
2857 cit->font().language() != latex_language &&
2858 cit->font().language() != doc_language)
2864 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2866 FontList::const_iterator cit = d->fontlist_.begin();
2867 FontList::const_iterator end = d->fontlist_.end();
2869 for (; cit != end; ++cit) {
2870 Language const * lang = cit->font().language();
2871 if (lang != ignore_language &&
2872 lang != latex_language)
2873 languages.insert(lang);
2878 docstring Paragraph::asString(int options) const
2880 return asString(0, size(), options);
2884 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2886 odocstringstream os;
2889 && options & AS_STR_LABEL
2890 && !d->params_.labelString().empty())
2891 os << d->params_.labelString() << ' ';
2893 for (pos_type i = beg; i < end; ++i) {
2894 char_type const c = d->text_[i];
2895 if (isPrintable(c) || c == '\t'
2896 || (c == '\n' && (options & AS_STR_NEWLINES)))
2898 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2899 getInset(i)->tocString(os);
2900 if (getInset(i)->asInsetMath())
2909 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2911 odocstringstream os;
2914 && options & AS_STR_LABEL
2915 && !d->params_.labelString().empty())
2916 os << d->params_.labelString() << ' ';
2918 for (pos_type i = beg; i < end; ++i) {
2919 char_type const c = d->text_[i];
2920 if (isPrintable(c) || c == '\t'
2921 || (c == '\n' && (options & AS_STR_NEWLINES)))
2923 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2924 getInset(i)->plaintext(os, runparams);
2932 void Paragraph::setInsetOwner(Inset const * inset)
2934 d->inset_owner_ = inset;
2938 int Paragraph::id() const
2944 void Paragraph::setId(int id)
2950 Layout const & Paragraph::layout() const
2956 void Paragraph::setLayout(Layout const & layout)
2958 d->layout_ = &layout;
2962 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2964 setLayout(tc.defaultLayout());
2968 void Paragraph::setPlainLayout(DocumentClass const & tc)
2970 setLayout(tc.plainLayout());
2974 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2976 if (usePlainLayout())
2977 setPlainLayout(tclass);
2979 setDefaultLayout(tclass);
2983 Inset const & Paragraph::inInset() const
2985 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2986 _("Memory problem"), _("Paragraph not properly initialized")));
2987 return *d->inset_owner_;
2991 ParagraphParameters & Paragraph::params()
2997 ParagraphParameters const & Paragraph::params() const
3003 bool Paragraph::isFreeSpacing() const
3005 if (d->layout_->free_spacing)
3007 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3011 bool Paragraph::allowEmpty() const
3013 if (d->layout_->keepempty)
3015 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3019 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3021 if (!Encodings::isArabicChar(c))
3024 char_type prev_char = ' ';
3025 char_type next_char = ' ';
3027 for (pos_type i = pos - 1; i >= 0; --i) {
3028 char_type const par_char = d->text_[i];
3029 if (!Encodings::isArabicComposeChar(par_char)) {
3030 prev_char = par_char;
3035 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3036 char_type const par_char = d->text_[i];
3037 if (!Encodings::isArabicComposeChar(par_char)) {
3038 next_char = par_char;
3043 if (Encodings::isArabicChar(next_char)) {
3044 if (Encodings::isArabicChar(prev_char) &&
3045 !Encodings::isArabicSpecialChar(prev_char))
3046 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3048 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3050 if (Encodings::isArabicChar(prev_char) &&
3051 !Encodings::isArabicSpecialChar(prev_char))
3052 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3054 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3059 int Paragraph::checkBiblio(Buffer const & buffer)
3062 // This is getting more and more a mess. ...We really should clean
3063 // up this bibitem issue for 1.6. See also bug 2743.
3065 // Add bibitem insets if necessary
3066 if (d->layout_->labeltype != LABEL_BIBLIO)
3069 bool hasbibitem = !d->insetlist_.empty()
3070 // Insist on it being in pos 0
3071 && d->text_[0] == META_INSET
3072 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3074 bool track_changes = buffer.params().trackChanges;
3079 // remove a bibitem in pos != 0
3080 // restore it later in pos 0 if necessary
3081 // (e.g. if a user inserts contents _before_ the item)
3082 // we're assuming there's only one of these, which there
3084 int erasedInsetPosition = -1;
3085 InsetList::iterator it = d->insetlist_.begin();
3086 InsetList::iterator end = d->insetlist_.end();
3087 for (; it != end; ++it)
3088 if (it->inset->lyxCode() == BIBITEM_CODE
3090 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3091 oldkey = olditem->getParam("key");
3092 oldlabel = olditem->getParam("label");
3093 erasedInsetPosition = it->pos;
3094 eraseChar(erasedInsetPosition, track_changes);
3098 // There was an InsetBibitem at the beginning, and we didn't
3099 // have to erase one.
3100 if (hasbibitem && erasedInsetPosition < 0)
3103 // There was an InsetBibitem at the beginning and we did have to
3104 // erase one. So we give its properties to the beginning inset.
3106 InsetBibitem * inset =
3107 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3108 if (!oldkey.empty())
3109 inset->setParam("key", oldkey);
3110 inset->setParam("label", oldlabel);
3111 return -erasedInsetPosition;
3114 // There was no inset at the beginning, so we need to create one with
3115 // the key and label of the one we erased.
3116 InsetBibitem * inset =
3117 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3118 // restore values of previously deleted item in this par.
3119 if (!oldkey.empty())
3120 inset->setParam("key", oldkey);
3121 inset->setParam("label", oldlabel);
3122 insertInset(0, static_cast<Inset *>(inset),
3123 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3129 void Paragraph::checkAuthors(AuthorList const & authorList)
3131 d->changes_.checkAuthors(authorList);
3135 bool Paragraph::isChanged(pos_type pos) const
3137 return lookupChange(pos).changed();
3141 bool Paragraph::isInserted(pos_type pos) const
3143 return lookupChange(pos).inserted();
3147 bool Paragraph::isDeleted(pos_type pos) const
3149 return lookupChange(pos).deleted();
3153 InsetList const & Paragraph::insetList() const
3155 return d->insetlist_;
3159 void Paragraph::setBuffer(Buffer & b)
3161 d->insetlist_.setBuffer(b);
3165 Inset * Paragraph::releaseInset(pos_type pos)
3167 Inset * inset = d->insetlist_.release(pos);
3168 /// does not honour change tracking!
3169 eraseChar(pos, false);
3174 Inset * Paragraph::getInset(pos_type pos)
3176 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3177 ? d->insetlist_.get(pos) : 0;
3181 Inset const * Paragraph::getInset(pos_type pos) const
3183 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3184 ? d->insetlist_.get(pos) : 0;
3188 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3189 pos_type & right, TextCase action)
3191 // process sequences of modified characters; in change
3192 // tracking mode, this approach results in much better
3193 // usability than changing case on a char-by-char basis
3196 bool const trackChanges = bparams.trackChanges;
3198 bool capitalize = true;
3200 for (; pos < right; ++pos) {
3201 char_type oldChar = d->text_[pos];
3202 char_type newChar = oldChar;
3204 // ignore insets and don't play with deleted text!
3205 if (oldChar != META_INSET && !isDeleted(pos)) {
3207 case text_lowercase:
3208 newChar = lowercase(oldChar);
3210 case text_capitalization:
3212 newChar = uppercase(oldChar);
3216 case text_uppercase:
3217 newChar = uppercase(oldChar);
3222 if (isWordSeparator(pos) || isDeleted(pos)) {
3223 // permit capitalization again
3227 if (oldChar != newChar) {
3229 if (pos != right - 1)
3231 // step behind the changing area
3235 int erasePos = pos - changes.size();
3236 for (size_t i = 0; i < changes.size(); i++) {
3237 insertChar(pos, changes[i],
3238 getFontSettings(bparams,
3241 if (!eraseChar(erasePos, trackChanges)) {
3244 ++right; // expand selection
3252 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3253 pos_type pos, bool del) const
3255 int const strsize = str.length();
3257 pos_type const parsize = d->text_.size();
3258 for (i = 0; pos + i < parsize; ++i) {
3261 if (cs && str[i] != d->text_[pos + i])
3263 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3265 if (!del && isDeleted(pos + i))
3272 // if necessary, check whether string matches word
3274 if (pos > 0 && !isWordSeparator(pos - 1))
3276 if (pos + strsize < parsize
3277 && !isWordSeparator(pos + strsize))
3285 char_type Paragraph::getChar(pos_type pos) const
3287 return d->text_[pos];
3291 pos_type Paragraph::size() const
3293 return d->text_.size();
3297 bool Paragraph::empty() const
3299 return d->text_.empty();
3303 bool Paragraph::isInset(pos_type pos) const
3305 return d->text_[pos] == META_INSET;
3309 bool Paragraph::isSeparator(pos_type pos) const
3311 //FIXME: Are we sure this can be the only separator?
3312 return d->text_[pos] == ' ';
3316 void Paragraph::deregisterWords()
3318 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3319 Private::LangWordsMap::const_iterator ite = d->words_.end();
3320 for (; itl != ite; ++itl) {
3321 WordList * wl = theWordList(itl->first);
3322 Private::Words::const_iterator it = (itl->second).begin();
3323 Private::Words::const_iterator et = (itl->second).end();
3324 for (; it != et; ++it)
3331 void Paragraph::locateWord(pos_type & from, pos_type & to,
3332 word_location const loc) const
3335 case WHOLE_WORD_STRICT:
3336 if (from == 0 || from == size()
3337 || isWordSeparator(from)
3338 || isWordSeparator(from - 1)) {
3342 // no break here, we go to the next
3345 // If we are already at the beginning of a word, do nothing
3346 if (!from || isWordSeparator(from - 1))
3348 // no break here, we go to the next
3351 // always move the cursor to the beginning of previous word
3352 while (from && !isWordSeparator(from - 1))
3356 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3359 // no need to move the 'from' cursor
3363 while (to < size() && !isWordSeparator(to))
3368 void Paragraph::collectWords()
3370 // This is the value that needs to be exposed in the preferences
3371 // to resolve bug #6760.
3372 static int minlength = 6;
3373 pos_type n = size();
3374 for (pos_type pos = 0; pos < n; ++pos) {
3375 if (isWordSeparator(pos))
3377 pos_type from = pos;
3378 locateWord(from, pos, WHOLE_WORD);
3379 if (pos - from >= minlength) {
3380 docstring word = asString(from, pos, AS_STR_NONE);
3381 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3382 if (cit == d->fontlist_.end())
3384 Language const * lang = cit->font().language();
3385 d->words_[*lang].insert(word);
3391 void Paragraph::registerWords()
3393 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3394 Private::LangWordsMap::const_iterator ite = d->words_.end();
3395 for (; itl != ite; ++itl) {
3396 WordList * wl = theWordList(itl->first);
3397 Private::Words::const_iterator it = (itl->second).begin();
3398 Private::Words::const_iterator et = (itl->second).end();
3399 for (; it != et; ++it)
3405 void Paragraph::updateWords()
3413 Language * Paragraph::Private::locateSpellRange(
3414 pos_type & from, pos_type & to,
3415 Positions & softbreaks) const
3417 // skip leading white space
3418 while (from < to && owner_->isWordSeparator(from))
3420 // don't check empty range
3423 // get current language
3424 Language * lang = getSpellLanguage(from);
3425 pos_type last = from;
3426 bool samelang = true;
3427 bool sameinset = true;
3428 while (last < to && samelang && sameinset) {
3429 // hop to end of word
3430 while (last < to && !owner_->isWordSeparator(last)) {
3431 if (owner_->getInset(last)) {
3432 softbreaks.insert(softbreaks.end(), last);
3436 // hop to next word while checking for insets
3437 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3438 if (Inset const * inset = owner_->getInset(last))
3439 sameinset = inset->isChar() && inset->isLetter();
3443 if (sameinset && last < to) {
3444 // now check for language change
3445 samelang = lang == getSpellLanguage(last);
3448 // if language change detected backstep is needed
3456 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3459 const_cast<Language *>(owner_->getFontSettings(
3460 inset_owner_->buffer().params(), from).language());
3461 if (lang == inset_owner_->buffer().params().language
3462 && !lyxrc.spellchecker_alt_lang.empty()) {
3464 string const lang_variety =
3465 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3466 lang->setCode(lang_code);
3467 lang->setVariety(lang_variety);
3473 void Paragraph::requestSpellCheck(pos_type pos)
3475 d->requestSpellCheck(pos == -1 ? size() : pos);
3479 bool Paragraph::needsSpellCheck() const
3481 SpellChecker::ChangeNumber speller_change_number = 0;
3482 if (theSpellChecker())
3483 speller_change_number = theSpellChecker()->changeNumber();
3484 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3485 d->speller_state_.needsCompleteRefresh(speller_change_number);
3487 return d->needsSpellCheck();
3491 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3492 WordLangTuple & wl, docstring_list & suggestions,
3493 bool do_suggestion, bool check_learned) const
3495 SpellChecker::Result result = SpellChecker::WORD_OK;
3496 SpellChecker * speller = theSpellChecker();
3500 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3503 locateWord(from, to, WHOLE_WORD);
3504 if (from == to || from >= size())
3507 docstring word = asString(from, to, AS_STR_INSETS);
3508 Language * lang = d->getSpellLanguage(from);
3510 wl = WordLangTuple(word, lang);
3515 if (needsSpellCheck() || check_learned) {
3516 // Ignore words with digits
3517 // FIXME: make this customizable
3518 // (note that some checkers ignore words with digits by default)
3519 if (!hasDigit(word)) {
3520 bool const trailing_dot = to < size() && d->text_[to] == '.';
3521 result = speller->check(wl);
3522 if (SpellChecker::misspelled(result) && trailing_dot) {
3523 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3524 result = speller->check(wl);
3525 if (!SpellChecker::misspelled(result)) {
3526 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3528 from << ".." << to << "]");
3532 d->setMisspelled(from, to, result);
3534 result = d->speller_state_.getState(from);
3537 bool const misspelled_ = SpellChecker::misspelled(result) ;
3538 if (misspelled_ && do_suggestion)
3539 speller->suggest(wl, suggestions);
3540 else if (misspelled_)
3541 LYXERR(Debug::GUI, "misspelled word: \"" <<
3543 from << ".." << to << "]");
3545 suggestions.clear();
3551 void Paragraph::Private::markMisspelledWords(
3552 pos_type const & first, pos_type const & last,
3553 SpellChecker::Result result,
3554 docstring const & word,
3555 Positions const & softbreaks)
3557 if (!SpellChecker::misspelled(result)) {
3558 setMisspelled(first, last, SpellChecker::WORD_OK);
3562 SpellChecker * speller = theSpellChecker();
3563 // locate and enumerate the error positions
3564 int nerrors = speller->numMisspelledWords();
3566 PositionsIterator it = softbreaks.begin();
3567 PositionsIterator et = softbreaks.end();
3568 for (int index = 0; index < nerrors; ++index) {
3571 speller->misspelledWord(index, wstart, wlen);
3572 /// should not happen if speller supports range checks
3573 if (!wlen) continue;
3574 docstring const misspelled = word.substr(wstart, wlen);
3575 wstart += first + numbreaks;
3576 if (snext < wstart) {
3577 /// mark the range of correct spelling
3578 numbreaks += countSoftbreaks(it, et, wstart);
3579 setMisspelled(snext,
3580 wstart - 1, SpellChecker::WORD_OK);
3582 snext = wstart + wlen;
3583 numbreaks += countSoftbreaks(it, et, snext);
3584 /// mark the range of misspelling
3585 setMisspelled(wstart, snext, result);
3586 LYXERR(Debug::GUI, "misspelled word: \"" <<
3587 misspelled << "\" [" <<
3588 wstart << ".." << (snext-1) << "]");
3591 if (snext <= last) {
3592 /// mark the range of correct spelling at end
3593 setMisspelled(snext, last, SpellChecker::WORD_OK);
3598 void Paragraph::spellCheck() const
3600 SpellChecker * speller = theSpellChecker();
3601 if (!speller || !size() ||!needsSpellCheck())
3605 d->rangeOfSpellCheck(start, endpos);
3606 if (speller->canCheckParagraph()) {
3607 // loop until we leave the range
3608 for (pos_type first = start; first < endpos; ) {
3609 pos_type last = endpos;
3610 Private::Positions softbreaks;
3611 Language * lang = d->locateSpellRange(first, last, softbreaks);
3612 if (first >= endpos)
3614 // start the spell checker on the unit of meaning
3615 docstring word = asString(first, last, AS_STR_INSETS);
3616 WordLangTuple wl = WordLangTuple(word, lang);
3617 SpellChecker::Result result = word.size() ?
3618 speller->check(wl) : SpellChecker::WORD_OK;
3619 d->markMisspelledWords(first, last, result, word, softbreaks);
3623 static docstring_list suggestions;
3624 pos_type to = endpos;
3625 while (start < endpos) {
3627 spellCheck(start, to, wl, suggestions, false);
3631 d->readySpellCheck();
3635 bool Paragraph::isMisspelled(pos_type pos) const
3637 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3641 string Paragraph::magicLabel() const
3644 ss << "magicparlabel-" << id();