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 SpellCheckerState {
86 needs_refresh_ = true;
87 current_change_number_ = 0;
90 void setRange(FontSpan const fp, SpellChecker::Result state)
92 eraseCoveredRanges(fp);
93 if (state != SpellChecker::WORD_OK)
97 void increasePosAfterPos(pos_type pos)
99 correctRangesAfterPos(pos, 1);
103 void decreasePosAfterPos(pos_type pos)
105 correctRangesAfterPos(pos, -1);
109 SpellChecker::Result getState(pos_type pos) const
111 SpellChecker::Result result = SpellChecker::WORD_OK;
112 RangesIterator et = ranges_.end();
113 RangesIterator it = ranges_.begin();
114 for (; it != et; ++it) {
115 FontSpan fc = it->first;
116 if(fc.first <= pos && pos <= fc.last) {
124 bool needsRefresh() const {
125 return needs_refresh_;
128 SpellChecker::ChangeNumber currentChangeNumber() const {
129 return current_change_number_;
132 void refreshRange(pos_type & first, pos_type & last) const {
133 first = refresh_.first;
134 last = refresh_.last;
137 void needsRefresh(pos_type pos) {
138 if (needs_refresh_ && pos != -1) {
139 if (pos < refresh_.first)
140 refresh_.first = pos;
141 if (pos > refresh_.last)
143 } else if (pos != -1) {
144 refresh_.first = pos;
147 needs_refresh_ = pos != -1;
150 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
151 needs_refresh_ = true;
154 current_change_number_ = change_number;
158 /// store the ranges as map of FontSpan and spell result pairs
159 typedef map<FontSpan, SpellChecker::Result> Ranges;
160 typedef Ranges::const_iterator RangesIterator;
165 SpellChecker::ChangeNumber current_change_number_;
167 void eraseCoveredRanges(FontSpan const fp)
170 RangesIterator et = ranges_.end();
171 RangesIterator it = ranges_.begin();
172 for (; it != et; ++it) {
173 FontSpan fc = it->first;
174 // 1. first of new range inside current range or
175 // 2. last of new range inside current range or
176 // 3. first of current range inside new range or
177 // 4. last of current range inside new range
178 if (fc.inside(fp.first) || fc.inside(fp.last) ||
179 fp.inside(fc.first) || fp.inside(fc.last))
183 result[fc] = it->second;
188 void correctRangesAfterPos(pos_type pos, int offset)
191 RangesIterator et = ranges_.end();
192 RangesIterator it = ranges_.begin();
193 for (; it != et; ++it) {
194 FontSpan m = it->first;
198 } else if (m.last > pos) {
201 result[m] = it->second;
208 /////////////////////////////////////////////////////////////////////
210 // Paragraph::Private
212 /////////////////////////////////////////////////////////////////////
214 class Paragraph::Private
218 Private(Paragraph * owner, Layout const & layout);
219 /// "Copy constructor"
220 Private(Private const &, Paragraph * owner);
221 /// Copy constructor from \p beg to \p end
222 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
225 void insertChar(pos_type pos, char_type c, Change const & change);
227 /// Output the surrogate pair formed by \p c and \p next to \p os.
228 /// \return the number of characters written.
229 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
230 OutputParams const &);
232 /// Output a space in appropriate formatting (or a surrogate pair
233 /// if the next character is a combining character).
234 /// \return whether a surrogate pair was output.
235 bool simpleTeXBlanks(OutputParams const &,
236 odocstream &, TexRow & texrow,
238 unsigned int & column,
240 Layout const & style);
242 /// Output consecutive unicode chars, belonging to the same script as
243 /// specified by the latex macro \p ltx, to \p os starting from \p i.
244 /// \return the number of characters written.
245 int writeScriptChars(odocstream & os, docstring const & ltx,
246 Change const &, Encoding const &, pos_type & i);
248 /// This could go to ParagraphParameters if we want to.
249 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
250 OutputParams const &) const;
252 /// This could go to ParagraphParameters if we want to.
253 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
254 OutputParams const &) const;
257 void latexInset(BufferParams const &,
259 TexRow & texrow, OutputParams &,
262 Font const & outerfont,
264 Change & running_change,
265 Layout const & style,
267 unsigned int & column);
270 void latexSpecialChar(
272 OutputParams const & runparams,
273 Font const & running_font,
274 Change const & running_change,
275 Layout const & style,
277 unsigned int & column);
284 unsigned int & column);
286 bool latexSpecialTypewriter(
290 unsigned int & column);
292 bool latexSpecialPhrase(
295 unsigned int & column,
296 OutputParams const & runparams);
299 void validate(LaTeXFeatures & features) const;
301 /// Checks if the paragraph contains only text and no inset or font change.
302 bool onlyText(Buffer const & buf, Font const & outerfont,
303 pos_type initial) const;
305 /// match a string against a particular point in the paragraph
306 bool isTextAt(string const & str, pos_type pos) const;
308 /// a vector of inset positions
309 typedef vector<pos_type> Positions;
310 typedef Positions::const_iterator PositionsIterator;
312 Language * getSpellLanguage(pos_type const from) const;
314 Language * locateSpellRange(pos_type & from, pos_type & to,
315 Positions & softbreaks) const;
317 bool hasSpellerChange() const {
318 SpellChecker::ChangeNumber speller_change_number = 0;
319 if (theSpellChecker())
320 speller_change_number = theSpellChecker()->changeNumber();
321 return speller_change_number > speller_state_.currentChangeNumber();
324 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
326 pos_type textsize = owner_->size();
327 // check for sane arguments
328 if (to < from || from >= textsize)
330 FontSpan fp = FontSpan(from, to);
331 // don't mark end of paragraph
332 if (fp.last >= textsize)
333 fp.last = textsize - 1;
334 speller_state_.setRange(fp, state);
337 void requestSpellCheck(pos_type pos) {
338 speller_state_.needsRefresh(pos);
341 void readySpellCheck() {
342 speller_state_.needsRefresh(-1);
345 bool needsSpellCheck() const
347 return speller_state_.needsRefresh();
350 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
352 speller_state_.refreshRange(first, last);
354 last = owner_->size();
357 pos_type endpos = last;
358 owner_->locateWord(first, endpos, WHOLE_WORD);
361 owner_->locateWord(last, endpos, WHOLE_WORD);
366 int countSoftbreaks(PositionsIterator & it, PositionsIterator const et,
370 while (it != et && *it < start) {
378 void markMisspelledWords(pos_type const & first, pos_type const & last,
379 SpellChecker::Result result,
380 docstring const & word,
381 Positions const & softbreaks);
383 InsetCode ownerCode() const
385 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
388 /// Which Paragraph owns us?
392 Inset const * inset_owner_;
401 ParagraphParameters params_;
403 /// for recording and looking up changes
407 InsetList insetlist_;
410 pos_type begin_of_body_;
412 typedef docstring TextContainer;
416 typedef set<docstring> Words;
417 typedef map<Language, Words> LangWordsMap;
421 Layout const * layout_;
423 SpellCheckerState speller_state_;
429 struct special_phrase {
435 special_phrase const special_phrases[] = {
436 { "LyX", from_ascii("\\LyX{}"), false },
437 { "TeX", from_ascii("\\TeX{}"), true },
438 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
439 { "LaTeX", from_ascii("\\LaTeX{}"), true },
442 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
447 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
448 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
454 // Initialization of the counter for the paragraph id's,
456 // FIXME: There should be a more intelligent way to generate and use the
457 // paragraph ids per buffer instead a global static counter for all InsetText
458 // in the running program.
459 static int paragraph_id = -1;
461 Paragraph::Private::Private(Private const & p, Paragraph * owner)
462 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
463 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
464 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
465 layout_(p.layout_), speller_state_(p.speller_state_)
467 id_ = ++paragraph_id;
468 requestSpellCheck(p.text_.size());
472 Paragraph::Private::Private(Private const & p, Paragraph * owner,
473 pos_type beg, pos_type end)
474 : owner_(owner), inset_owner_(p.inset_owner_),
475 params_(p.params_), changes_(p.changes_),
476 insetlist_(p.insetlist_, beg, end),
477 begin_of_body_(p.begin_of_body_), words_(p.words_),
478 layout_(p.layout_), speller_state_(p.speller_state_)
480 id_ = ++paragraph_id;
481 if (beg >= pos_type(p.text_.size()))
483 text_ = p.text_.substr(beg, end - beg);
485 FontList::const_iterator fcit = fontlist_.begin();
486 FontList::const_iterator fend = fontlist_.end();
487 for (; fcit != fend; ++fcit) {
488 if (fcit->pos() < beg)
490 if (fcit->pos() >= end) {
491 // Add last entry in the fontlist_.
492 fontlist_.set(text_.size() - 1, fcit->font());
495 // Add a new entry in the fontlist_.
496 fontlist_.set(fcit->pos() - beg, fcit->font());
498 requestSpellCheck(p.text_.size());
502 void Paragraph::addChangesToToc(DocIterator const & cdit,
503 Buffer const & buf) const
505 d->changes_.addToToc(cdit, buf);
509 bool Paragraph::isDeleted(pos_type start, pos_type end) const
511 LASSERT(start >= 0 && start <= size(), /**/);
512 LASSERT(end > start && end <= size() + 1, /**/);
514 return d->changes_.isDeleted(start, end);
518 bool Paragraph::isChanged(pos_type start, pos_type end) const
520 LASSERT(start >= 0 && start <= size(), /**/);
521 LASSERT(end > start && end <= size() + 1, /**/);
523 return d->changes_.isChanged(start, end);
527 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
529 // keep the logic here in sync with the logic of eraseChars()
533 Change const change = d->changes_.lookup(size());
534 return change.inserted() && change.currentAuthor();
538 void Paragraph::setChange(Change const & change)
540 // beware of the imaginary end-of-par character!
541 d->changes_.set(change, 0, size() + 1);
544 * Propagate the change recursively - but not in case of DELETED!
546 * Imagine that your co-author makes changes in an existing inset. He
547 * sends your document to you and you come to the conclusion that the
548 * inset should go completely. If you erase it, LyX must not delete all
549 * text within the inset. Otherwise, the change tracked insertions of
550 * your co-author get lost and there is no way to restore them later.
552 * Conclusion: An inset's content should remain untouched if you delete it
555 if (!change.deleted()) {
556 for (pos_type pos = 0; pos < size(); ++pos) {
557 if (Inset * inset = getInset(pos))
558 inset->setChange(change);
564 void Paragraph::setChange(pos_type pos, Change const & change)
566 LASSERT(pos >= 0 && pos <= size(), /**/);
567 d->changes_.set(change, pos);
569 // see comment in setChange(Change const &) above
570 if (!change.deleted() && pos < size())
571 if (Inset * inset = getInset(pos))
572 inset->setChange(change);
576 Change const & Paragraph::lookupChange(pos_type pos) const
578 LASSERT(pos >= 0 && pos <= size(), /**/);
579 return d->changes_.lookup(pos);
583 void Paragraph::acceptChanges(pos_type start, pos_type end)
585 LASSERT(start >= 0 && start <= size(), /**/);
586 LASSERT(end > start && end <= size() + 1, /**/);
588 for (pos_type pos = start; pos < end; ++pos) {
589 switch (lookupChange(pos).type) {
590 case Change::UNCHANGED:
591 // accept changes in nested inset
592 if (Inset * inset = getInset(pos))
593 inset->acceptChanges();
596 case Change::INSERTED:
597 d->changes_.set(Change(Change::UNCHANGED), pos);
598 // also accept changes in nested inset
599 if (Inset * inset = getInset(pos))
600 inset->acceptChanges();
603 case Change::DELETED:
604 // Suppress access to non-existent
605 // "end-of-paragraph char"
607 eraseChar(pos, false);
618 void Paragraph::rejectChanges(pos_type start, pos_type end)
620 LASSERT(start >= 0 && start <= size(), /**/);
621 LASSERT(end > start && end <= size() + 1, /**/);
623 for (pos_type pos = start; pos < end; ++pos) {
624 switch (lookupChange(pos).type) {
625 case Change::UNCHANGED:
626 // reject changes in nested inset
627 if (Inset * inset = getInset(pos))
628 inset->rejectChanges();
631 case Change::INSERTED:
632 // Suppress access to non-existent
633 // "end-of-paragraph char"
635 eraseChar(pos, false);
641 case Change::DELETED:
642 d->changes_.set(Change(Change::UNCHANGED), pos);
644 // Do NOT reject changes within a deleted inset!
645 // There may be insertions of a co-author inside of it!
653 void Paragraph::Private::insertChar(pos_type pos, char_type c,
654 Change const & change)
656 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
659 changes_.insert(change, pos);
661 // This is actually very common when parsing buffers (and
662 // maybe inserting ascii text)
663 if (pos == pos_type(text_.size())) {
664 // when appending characters, no need to update tables
666 // but we want spell checking
667 requestSpellCheck(pos);
671 text_.insert(text_.begin() + pos, c);
673 // Update the font table.
674 fontlist_.increasePosAfterPos(pos);
677 insetlist_.increasePosAfterPos(pos);
679 // Update list of misspelled positions
680 speller_state_.increasePosAfterPos(pos);
684 bool Paragraph::insertInset(pos_type pos, Inset * inset,
685 Change const & change)
687 LASSERT(inset, /**/);
688 LASSERT(pos >= 0 && pos <= size(), /**/);
690 // Paragraph::insertInset() can be used in cut/copy/paste operation where
691 // d->inset_owner_ is not set yet.
692 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
695 d->insertChar(pos, META_INSET, change);
696 LASSERT(d->text_[pos] == META_INSET, /**/);
698 // Add a new entry in the insetlist_.
699 d->insetlist_.insert(inset, pos);
701 // Some insets require run of spell checker
702 requestSpellCheck(pos);
707 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
709 LASSERT(pos >= 0 && pos <= size(), return false);
711 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
714 Change change = d->changes_.lookup(pos);
716 // set the character to DELETED if
717 // a) it was previously unchanged or
718 // b) it was inserted by a co-author
720 if (!change.changed() ||
721 (change.inserted() && !change.currentAuthor())) {
722 setChange(pos, Change(Change::DELETED));
726 if (change.deleted())
730 // Don't physically access the imaginary end-of-paragraph character.
731 // eraseChar() can only mark it as DELETED. A physical deletion of
732 // end-of-par must be handled externally.
738 d->changes_.erase(pos);
740 // if it is an inset, delete the inset entry
741 if (d->text_[pos] == META_INSET)
742 d->insetlist_.erase(pos);
744 d->text_.erase(d->text_.begin() + pos);
746 // Update the fontlist_
747 d->fontlist_.erase(pos);
749 // Update the insetlist_
750 d->insetlist_.decreasePosAfterPos(pos);
752 // Update list of misspelled positions
753 d->speller_state_.decreasePosAfterPos(pos);
759 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
761 LASSERT(start >= 0 && start <= size(), /**/);
762 LASSERT(end >= start && end <= size() + 1, /**/);
765 for (pos_type count = end - start; count; --count) {
766 if (!eraseChar(i, trackChanges))
773 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
774 char_type next, OutputParams const & runparams)
776 // Writing next here may circumvent a possible font change between
777 // c and next. Since next is only output if it forms a surrogate pair
778 // with c we can ignore this:
779 // A font change inside a surrogate pair does not make sense and is
780 // hopefully impossible to input.
781 // FIXME: change tracking
782 // Is this correct WRT change tracking?
783 Encoding const & encoding = *(runparams.encoding);
784 docstring const latex1 = encoding.latexChar(next);
785 docstring const latex2 = encoding.latexChar(c);
786 if (docstring(1, next) == latex1) {
787 // the encoding supports the combination
788 os << latex2 << latex1;
789 return latex1.length() + latex2.length();
790 } else if (runparams.local_font &&
791 runparams.local_font->language()->lang() == "polutonikogreek") {
792 // polutonikogreek only works without the brackets
793 os << latex1 << latex2;
794 return latex1.length() + latex2.length();
796 os << latex1 << '{' << latex2 << '}';
797 return latex1.length() + latex2.length() + 2;
801 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
802 odocstream & os, TexRow & texrow,
804 unsigned int & column,
806 Layout const & style)
808 if (style.pass_thru || runparams.pass_thru)
811 if (i + 1 < int(text_.size())) {
812 char_type next = text_[i + 1];
813 if (Encodings::isCombiningChar(next)) {
814 // This space has an accent, so we must always output it.
815 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
820 if (runparams.linelen > 0
821 && column > runparams.linelen
823 && text_[i - 1] != ' '
824 && (i + 1 < int(text_.size()))
825 // same in FreeSpacing mode
826 && !owner_->isFreeSpacing()
827 // In typewriter mode, we want to avoid
828 // ! . ? : at the end of a line
829 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
830 && (text_[i - 1] == '.'
831 || text_[i - 1] == '?'
832 || text_[i - 1] == ':'
833 || text_[i - 1] == '!'))) {
836 texrow.start(owner_->id(), i + 1);
838 } else if (style.free_spacing) {
847 int Paragraph::Private::writeScriptChars(odocstream & os,
848 docstring const & ltx,
849 Change const & runningChange,
850 Encoding const & encoding,
853 // FIXME: modifying i here is not very nice...
855 // We only arrive here when a proper language for character text_[i] has
856 // not been specified (i.e., it could not be translated in the current
857 // latex encoding) or its latex translation has been forced, and it
858 // belongs to a known script.
859 // Parameter ltx contains the latex translation of text_[i] as specified
860 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
861 // The latex macro name "textXXX" specifies the script to which text_[i]
862 // belongs and we use it in order to check whether characters from the
863 // same script immediately follow, such that we can collect them in a
864 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
865 // for the first char but only "<spec>" for all subsequent chars.
866 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
867 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
868 string script = to_ascii(ltx.substr(1, brace1 - 1));
871 bool closing_brace = true;
872 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
873 // Correct encoding is being used, so we can avoid \textgreek.
876 closing_brace = false;
878 os << ltx.substr(pos, length);
879 int size = text_.size();
880 while (i + 1 < size) {
881 char_type const next = text_[i + 1];
882 // Stop here if next character belongs to another script
883 // or there is a change in change tracking status.
884 if (!Encodings::isKnownScriptChar(next, script) ||
885 runningChange != owner_->lookupChange(i + 1))
889 FontList::const_iterator cit = fontlist_.begin();
890 FontList::const_iterator end = fontlist_.end();
891 for (; cit != end; ++cit) {
892 if (cit->pos() >= i && !found) {
893 prev_font = cit->font();
896 if (cit->pos() >= i + 1)
899 // Stop here if there is a font attribute or encoding change.
900 if (found && cit != end && prev_font != cit->font())
902 docstring const latex = encoding.latexChar(next);
903 docstring::size_type const b1 =
904 latex.find_first_of(from_ascii("{"));
905 docstring::size_type const b2 =
906 latex.find_last_of(from_ascii("}"));
907 int const len = b2 - b1 - 1;
908 os << latex.substr(b1 + 1, len);
920 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
922 pos_type const len = str.length();
924 // is the paragraph large enough?
925 if (pos + len > int(text_.size()))
928 // does the wanted text start at point?
929 for (string::size_type i = 0; i < str.length(); ++i) {
930 // Caution: direct comparison of characters works only
931 // because str is pure ASCII.
932 if (str[i] != text_[pos + i])
936 return fontlist_.hasChangeInRange(pos, len);
940 void Paragraph::Private::latexInset(BufferParams const & bparams,
943 OutputParams & runparams,
946 Font const & outerfont,
948 Change & running_change,
949 Layout const & style,
951 unsigned int & column)
953 Inset * inset = owner_->getInset(i);
954 LASSERT(inset, /**/);
956 if (style.pass_thru) {
957 inset->plaintext(os, runparams);
961 // FIXME: move this to InsetNewline::latex
962 if (inset->lyxCode() == NEWLINE_CODE) {
963 // newlines are handled differently here than
964 // the default in simpleTeXSpecialChars().
965 if (!style.newline_allowed) {
969 column += running_font.latexWriteEndChanges(
970 os, bparams, runparams,
975 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
978 basefont = owner_->getLayoutFont(bparams, outerfont);
979 running_font = basefont;
981 if (runparams.moving_arg)
986 texrow.start(owner_->id(), i + 1);
990 if (owner_->isDeleted(i)) {
991 if( ++runparams.inDeletedInset == 1)
992 runparams.changeOfDeletedInset = owner_->lookupChange(i);
995 if (inset->canTrackChanges()) {
996 column += Changes::latexMarkChange(os, bparams, running_change,
997 Change(Change::UNCHANGED), runparams);
998 running_change = Change(Change::UNCHANGED);
1002 odocstream::pos_type const len = os.tellp();
1004 if (inset->forceLTR()
1005 && running_font.isRightToLeft()
1006 // ERT is an exception, it should be output with no
1007 // decorations at all
1008 && inset->lyxCode() != ERT_CODE) {
1009 if (running_font.language()->lang() == "farsi")
1016 // FIXME: Bug: we can have an empty font change here!
1017 // if there has just been a font change, we are going to close it
1018 // right now, which means stupid latex code like \textsf{}. AFAIK,
1019 // this does not harm dvi output. A minor bug, thus (JMarc)
1021 // Some insets cannot be inside a font change command.
1022 // However, even such insets *can* be placed in \L or \R
1023 // or their equivalents (for RTL language switches), so we don't
1024 // close the language in those cases.
1025 // ArabTeX, though, cannot handle this special behavior, it seems.
1026 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1027 || running_font.language()->lang() == "arabic_arabtex";
1028 if (open_font && inset->noFontChange()) {
1029 bool closeLanguage = arabtex
1030 || basefont.isRightToLeft() == running_font.isRightToLeft();
1031 unsigned int count = running_font.latexWriteEndChanges(os,
1032 bparams, runparams, basefont, basefont, closeLanguage);
1034 // if any font properties were closed, update the running_font,
1035 // making sure, however, to leave the language as it was
1037 // FIXME: probably a better way to keep track of the old
1038 // language, than copying the entire font?
1039 Font const copy_font(running_font);
1040 basefont = owner_->getLayoutFont(bparams, outerfont);
1041 running_font = basefont;
1043 running_font.setLanguage(copy_font.language());
1044 // leave font open if language is still open
1045 open_font = (running_font.language() == basefont.language());
1047 runparams.local_font = &basefont;
1054 tmp = inset->latex(os, runparams);
1055 } catch (EncodingException & e) {
1056 // add location information and throw again.
1063 if (running_font.language()->lang() == "farsi")
1070 texrow.newlines(tmp);
1071 texrow.start(owner_->id(), i + 1);
1074 column += os.tellp() - len;
1077 if (owner_->isDeleted(i))
1078 --runparams.inDeletedInset;
1082 void Paragraph::Private::latexSpecialChar(
1084 OutputParams const & runparams,
1085 Font const & running_font,
1086 Change const & running_change,
1087 Layout const & style,
1089 unsigned int & column)
1091 char_type const c = text_[i];
1093 if (style.pass_thru || runparams.pass_thru) {
1095 // FIXME UNICODE: This can fail if c cannot
1096 // be encoded in the current encoding.
1101 // If T1 font encoding is used, use the special
1102 // characters it provides.
1103 // NOTE: some languages reset the font encoding
1105 if (!running_font.language()->internalFontEncoding()
1106 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1109 // \tt font needs special treatment
1110 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1111 && latexSpecialTypewriter(c, os, i, column))
1114 // Otherwise, we use what LaTeX provides us.
1117 os << "\\textbackslash{}";
1121 os << "\\textless{}";
1125 os << "\\textgreater{}";
1129 os << "\\textbar{}";
1136 os << "\\char`\\\"{}";
1141 case '%': case '#': case '{':
1149 os << "\\textasciitilde{}";
1154 os << "\\textasciicircum{}";
1161 // avoid being mistaken for optional arguments
1169 // Blanks are printed before font switching.
1170 // Sure? I am not! (try nice-latex)
1171 // I am sure it's correct. LyX might be smarter
1172 // in the future, but for now, nothing wrong is
1178 if (latexSpecialPhrase(os, i, column, runparams))
1184 Encoding const & encoding = *(runparams.encoding);
1185 if (i + 1 < int(text_.size())) {
1186 char_type next = text_[i + 1];
1187 if (Encodings::isCombiningChar(next)) {
1188 column += latexSurrogatePair(os, c, next, runparams) - 1;
1194 docstring const latex = encoding.latexChar(c);
1195 if (Encodings::isKnownScriptChar(c, script)
1196 && prefixIs(latex, from_ascii("\\" + script)))
1197 column += writeScriptChars(os, latex,
1198 running_change, encoding, i) - 1;
1199 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1200 // Prevent eating of a following
1201 // space or command corruption by
1202 // following characters
1203 column += latex.length() + 1;
1204 os << latex << "{}";
1206 column += latex.length() - 1;
1214 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1215 pos_type i, unsigned int & column)
1221 // In T1 encoding, these characters exist
1222 // but we should avoid ligatures
1223 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1225 os << "\\textcompwordmark{}";
1232 // soul.sty breaks with \char`\"
1233 os << "\\textquotedbl{}";
1242 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1243 pos_type i, unsigned int & column)
1247 // within \ttfamily, "--" is merged to "-" (no endash)
1248 // so we avoid this rather irritating ligature
1249 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1256 // everything else has to be checked separately
1257 // (depending on the encoding)
1264 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1265 unsigned int & column, OutputParams const & runparams)
1267 // FIXME: if we have "LaTeX" with a font
1268 // change in the middle (before the 'T', then
1269 // the "TeX" part is still special cased.
1270 // Really we should only operate this on
1271 // "words" for some definition of word
1273 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1274 if (!isTextAt(special_phrases[pnr].phrase, i))
1276 if (runparams.moving_arg)
1278 os << special_phrases[pnr].macro;
1279 i += special_phrases[pnr].phrase.length() - 1;
1280 column += special_phrases[pnr].macro.length() - 1;
1287 void Paragraph::Private::validate(LaTeXFeatures & features) const
1289 if (layout_->inpreamble && inset_owner_) {
1290 Buffer const & buf = inset_owner_->buffer();
1291 BufferParams const & bp = buf.params();
1294 odocstringstream ods;
1295 // we have to provide all the optional arguments here, even though
1296 // the last one is the only one we care about.
1297 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1298 docstring const d = ods.str();
1300 // this will have "{" at the beginning, but not at the end
1301 string const content = to_utf8(d);
1302 string const cmd = layout_->latexname();
1303 features.addPreambleSnippet("\\" + cmd + content + "}");
1307 if (features.runparams().flavor == OutputParams::HTML
1308 && layout_->htmltitle()) {
1309 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1312 // check the params.
1313 if (!params_.spacing().isDefault())
1314 features.require("setspace");
1317 features.useLayout(layout_->name());
1320 fontlist_.validate(features);
1322 // then the indentation
1323 if (!params_.leftIndent().zero())
1324 features.require("ParagraphLeftIndent");
1327 InsetList::const_iterator icit = insetlist_.begin();
1328 InsetList::const_iterator iend = insetlist_.end();
1329 for (; icit != iend; ++icit) {
1331 icit->inset->validate(features);
1332 if (layout_->needprotect &&
1333 icit->inset->lyxCode() == FOOT_CODE)
1334 features.require("NeedLyXFootnoteCode");
1338 // then the contents
1339 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1340 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1341 if (!special_phrases[pnr].builtin
1342 && isTextAt(special_phrases[pnr].phrase, i)) {
1343 features.require(special_phrases[pnr].phrase);
1347 Encodings::validate(text_[i], features);
1351 /////////////////////////////////////////////////////////////////////
1355 /////////////////////////////////////////////////////////////////////
1358 Layout const emptyParagraphLayout;
1361 Paragraph::Paragraph()
1362 : d(new Paragraph::Private(this, emptyParagraphLayout))
1369 Paragraph::Paragraph(Paragraph const & par)
1370 : itemdepth(par.itemdepth),
1371 d(new Paragraph::Private(*par.d, this))
1377 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1378 : itemdepth(par.itemdepth),
1379 d(new Paragraph::Private(*par.d, this, beg, end))
1385 Paragraph & Paragraph::operator=(Paragraph const & par)
1387 // needed as we will destroy the private part before copying it
1389 itemdepth = par.itemdepth;
1393 d = new Private(*par.d, this);
1400 Paragraph::~Paragraph()
1409 // this shall be called just before every "os << ..." action.
1410 void flushString(ostream & os, docstring & s)
1419 void Paragraph::write(ostream & os, BufferParams const & bparams,
1420 depth_type & dth) const
1422 // The beginning or end of a deeper (i.e. nested) area?
1423 if (dth != d->params_.depth()) {
1424 if (d->params_.depth() > dth) {
1425 while (d->params_.depth() > dth) {
1426 os << "\n\\begin_deeper";
1430 while (d->params_.depth() < dth) {
1431 os << "\n\\end_deeper";
1437 // First write the layout
1438 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1440 d->params_.write(os);
1442 Font font1(inherit_font, bparams.language);
1444 Change running_change = Change(Change::UNCHANGED);
1446 // this string is used as a buffer to avoid repetitive calls
1447 // to to_utf8(), which turn out to be expensive (JMarc)
1448 docstring write_buffer;
1451 for (pos_type i = 0; i <= size(); ++i) {
1453 Change const change = lookupChange(i);
1454 if (change != running_change)
1455 flushString(os, write_buffer);
1456 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1457 running_change = change;
1462 // Write font changes
1463 Font font2 = getFontSettings(bparams, i);
1464 if (font2 != font1) {
1465 flushString(os, write_buffer);
1466 font2.lyxWriteChanges(font1, os);
1471 char_type const c = d->text_[i];
1474 if (Inset const * inset = getInset(i)) {
1475 flushString(os, write_buffer);
1476 if (inset->directWrite()) {
1477 // international char, let it write
1478 // code directly so it's shorter in
1484 os << "\\begin_inset ";
1486 os << "\n\\end_inset\n\n";
1492 flushString(os, write_buffer);
1493 os << "\n\\backslash\n";
1497 flushString(os, write_buffer);
1498 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1505 if ((column > 70 && c == ' ')
1507 flushString(os, write_buffer);
1511 // this check is to amend a bug. LyX sometimes
1512 // inserts '\0' this could cause problems.
1514 write_buffer.push_back(c);
1516 LYXERR0("NUL char in structure.");
1522 flushString(os, write_buffer);
1523 os << "\n\\end_layout\n";
1527 void Paragraph::validate(LaTeXFeatures & features) const
1529 d->validate(features);
1533 void Paragraph::insert(pos_type start, docstring const & str,
1534 Font const & font, Change const & change)
1536 for (size_t i = 0, n = str.size(); i != n ; ++i)
1537 insertChar(start + i, str[i], font, change);
1541 void Paragraph::appendChar(char_type c, Font const & font,
1542 Change const & change)
1545 d->changes_.insert(change, d->text_.size());
1546 // when appending characters, no need to update tables
1547 d->text_.push_back(c);
1548 setFont(d->text_.size() - 1, font);
1552 void Paragraph::appendString(docstring const & s, Font const & font,
1553 Change const & change)
1555 pos_type end = s.size();
1556 size_t oldsize = d->text_.size();
1557 size_t newsize = oldsize + end;
1558 size_t capacity = d->text_.capacity();
1559 if (newsize >= capacity)
1560 d->text_.reserve(max(capacity + 100, newsize));
1562 // when appending characters, no need to update tables
1565 // FIXME: Optimize this!
1566 for (size_t i = oldsize; i != newsize; ++i) {
1568 d->changes_.insert(change, i);
1570 d->fontlist_.set(oldsize, font);
1571 d->fontlist_.set(newsize - 1, font);
1575 void Paragraph::insertChar(pos_type pos, char_type c,
1578 d->insertChar(pos, c, Change(trackChanges ?
1579 Change::INSERTED : Change::UNCHANGED));
1583 void Paragraph::insertChar(pos_type pos, char_type c,
1584 Font const & font, bool trackChanges)
1586 d->insertChar(pos, c, Change(trackChanges ?
1587 Change::INSERTED : Change::UNCHANGED));
1592 void Paragraph::insertChar(pos_type pos, char_type c,
1593 Font const & font, Change const & change)
1595 d->insertChar(pos, c, change);
1600 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1601 Font const & font, Change const & change)
1603 bool const success = insertInset(pos, inset, change);
1604 // Set the font/language of the inset...
1610 void Paragraph::resetFonts(Font const & font)
1612 d->fontlist_.clear();
1613 d->fontlist_.set(0, font);
1614 d->fontlist_.set(d->text_.size() - 1, font);
1617 // Gets uninstantiated font setting at position.
1618 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1622 LYXERR0("pos: " << pos << " size: " << size());
1623 LASSERT(pos <= size(), /**/);
1626 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1627 if (cit != d->fontlist_.end())
1630 if (pos == size() && !empty())
1631 return getFontSettings(bparams, pos - 1);
1633 // Optimisation: avoid a full font instantiation if there is no
1634 // language change from previous call.
1635 static Font previous_font;
1636 static Language const * previous_lang = 0;
1637 Language const * lang = getParLanguage(bparams);
1638 if (lang != previous_lang) {
1639 previous_lang = lang;
1640 previous_font = Font(inherit_font, lang);
1642 return previous_font;
1646 FontSpan Paragraph::fontSpan(pos_type pos) const
1648 LASSERT(pos <= size(), /**/);
1651 FontList::const_iterator cit = d->fontlist_.begin();
1652 FontList::const_iterator end = d->fontlist_.end();
1653 for (; cit != end; ++cit) {
1654 if (cit->pos() >= pos) {
1655 if (pos >= beginOfBody())
1656 return FontSpan(max(start, beginOfBody()),
1659 return FontSpan(start,
1660 min(beginOfBody() - 1,
1663 start = cit->pos() + 1;
1666 // This should not happen, but if so, we take no chances.
1667 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1668 return FontSpan(pos, pos);
1672 // Gets uninstantiated font setting at position 0
1673 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1675 if (!empty() && !d->fontlist_.empty())
1676 return d->fontlist_.begin()->font();
1678 // Optimisation: avoid a full font instantiation if there is no
1679 // language change from previous call.
1680 static Font previous_font;
1681 static Language const * previous_lang = 0;
1682 if (bparams.language != previous_lang) {
1683 previous_lang = bparams.language;
1684 previous_font = Font(inherit_font, bparams.language);
1687 return previous_font;
1691 // Gets the fully instantiated font at a given position in a paragraph
1692 // This is basically the same function as Text::GetFont() in text2.cpp.
1693 // The difference is that this one is used for generating the LaTeX file,
1694 // and thus cosmetic "improvements" are disallowed: This has to deliver
1695 // the true picture of the buffer. (Asger)
1696 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1697 Font const & outerfont) const
1699 LASSERT(pos >= 0, /**/);
1701 Font font = getFontSettings(bparams, pos);
1703 pos_type const body_pos = beginOfBody();
1704 FontInfo & fi = font.fontInfo();
1706 fi.realize(d->layout_->labelfont);
1708 fi.realize(d->layout_->font);
1710 fi.realize(outerfont.fontInfo());
1711 fi.realize(bparams.getFont().fontInfo());
1717 Font const Paragraph::getLabelFont
1718 (BufferParams const & bparams, Font const & outerfont) const
1720 FontInfo tmpfont = d->layout_->labelfont;
1721 tmpfont.realize(outerfont.fontInfo());
1722 tmpfont.realize(bparams.getFont().fontInfo());
1723 return Font(tmpfont, getParLanguage(bparams));
1727 Font const Paragraph::getLayoutFont
1728 (BufferParams const & bparams, Font const & outerfont) const
1730 FontInfo tmpfont = d->layout_->font;
1731 tmpfont.realize(outerfont.fontInfo());
1732 tmpfont.realize(bparams.getFont().fontInfo());
1733 return Font(tmpfont, getParLanguage(bparams));
1737 /// Returns the height of the highest font in range
1738 FontSize Paragraph::highestFontInRange
1739 (pos_type startpos, pos_type endpos, FontSize def_size) const
1741 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1745 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1747 char_type c = d->text_[pos];
1748 if (!lyxrc.rtl_support)
1778 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1784 void Paragraph::setFont(pos_type pos, Font const & font)
1786 LASSERT(pos <= size(), /**/);
1788 // First, reduce font against layout/label font
1789 // Update: The setCharFont() routine in text2.cpp already
1790 // reduces font, so we don't need to do that here. (Asger)
1792 d->fontlist_.set(pos, font);
1796 void Paragraph::makeSameLayout(Paragraph const & par)
1798 d->layout_ = par.d->layout_;
1799 d->params_ = par.d->params_;
1803 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1805 if (isFreeSpacing())
1811 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1812 if (eraseChar(pos, trackChanges))
1818 return count > 0 || pos > 0;
1822 bool Paragraph::hasSameLayout(Paragraph const & par) const
1824 return par.d->layout_ == d->layout_
1825 && d->params_.sameLayout(par.d->params_);
1829 depth_type Paragraph::getDepth() const
1831 return d->params_.depth();
1835 depth_type Paragraph::getMaxDepthAfter() const
1837 if (d->layout_->isEnvironment())
1838 return d->params_.depth() + 1;
1840 return d->params_.depth();
1844 char Paragraph::getAlign() const
1846 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1847 return d->layout_->align;
1849 return d->params_.align();
1853 docstring const & Paragraph::labelString() const
1855 return d->params_.labelString();
1859 // the next two functions are for the manual labels
1860 docstring const Paragraph::getLabelWidthString() const
1862 if (d->layout_->margintype == MARGIN_MANUAL
1863 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1864 return d->params_.labelWidthString();
1866 return _("Senseless with this layout!");
1870 void Paragraph::setLabelWidthString(docstring const & s)
1872 d->params_.labelWidthString(s);
1876 docstring Paragraph::expandLabel(Layout const & layout,
1877 BufferParams const & bparams) const
1879 return expandParagraphLabel(layout, bparams, true);
1883 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1884 BufferParams const & bparams) const
1886 return expandParagraphLabel(layout, bparams, false);
1890 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1891 BufferParams const & bparams, bool process_appendix) const
1893 DocumentClass const & tclass = bparams.documentClass();
1894 string const & lang = getParLanguage(bparams)->code();
1895 bool const in_appendix = process_appendix && d->params_.appendix();
1896 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1898 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1899 && !layout.counter.empty())
1900 return tclass.counters().theCounter(layout.counter, lang);
1902 // handle 'inherited level parts' in 'fmt',
1903 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1904 size_t const i = fmt.find('@', 0);
1905 if (i != docstring::npos) {
1906 size_t const j = fmt.find('@', i + 1);
1907 if (j != docstring::npos) {
1908 docstring parent(fmt, i + 1, j - i - 1);
1909 docstring label = from_ascii("??");
1910 if (tclass.hasLayout(parent))
1911 docstring label = expandParagraphLabel(tclass[parent], bparams,
1913 fmt = docstring(fmt, 0, i) + label
1914 + docstring(fmt, j + 1, docstring::npos);
1918 return tclass.counters().counterLabel(fmt, lang);
1922 void Paragraph::applyLayout(Layout const & new_layout)
1924 d->layout_ = &new_layout;
1925 LyXAlignment const oldAlign = d->params_.align();
1927 if (!(oldAlign & d->layout_->alignpossible)) {
1928 frontend::Alert::warning(_("Alignment not permitted"),
1929 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1930 d->params_.align(LYX_ALIGN_LAYOUT);
1935 pos_type Paragraph::beginOfBody() const
1937 return d->begin_of_body_;
1941 void Paragraph::setBeginOfBody()
1943 if (d->layout_->labeltype != LABEL_MANUAL) {
1944 d->begin_of_body_ = 0;
1948 // Unroll the first two cycles of the loop
1949 // and remember the previous character to
1950 // remove unnecessary getChar() calls
1952 pos_type end = size();
1953 if (i < end && !isNewline(i)) {
1955 char_type previous_char = 0;
1958 previous_char = d->text_[i];
1959 if (!isNewline(i)) {
1961 while (i < end && previous_char != ' ') {
1966 previous_char = temp;
1972 d->begin_of_body_ = i;
1976 bool Paragraph::allowParagraphCustomization() const
1978 return inInset().allowParagraphCustomization();
1982 bool Paragraph::usePlainLayout() const
1984 return inInset().usePlainLayout();
1990 // paragraphs inside floats need different alignment tags to avoid
1993 bool noTrivlistCentering(InsetCode code)
1995 return code == FLOAT_CODE
1996 || code == WRAP_CODE
1997 || code == CELL_CODE;
2001 string correction(string const & orig)
2003 if (orig == "flushleft")
2004 return "raggedright";
2005 if (orig == "flushright")
2006 return "raggedleft";
2007 if (orig == "center")
2013 string const corrected_env(string const & suffix, string const & env,
2014 InsetCode code, bool const lastpar)
2016 string output = suffix + "{";
2017 if (noTrivlistCentering(code)) {
2019 // the last paragraph in non-trivlist-aligned
2020 // context is special (to avoid unwanted whitespace)
2021 if (suffix == "\\begin")
2022 return "\\" + correction(env) + "{}";
2025 output += correction(env);
2029 if (suffix == "\\begin")
2035 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2037 if (!contains(str, "\n"))
2038 column += str.size();
2042 column = rsplit(str, tmp, '\n').size();
2049 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2050 odocstream & os, TexRow & texrow,
2051 OutputParams const & runparams) const
2055 if (params_.noindent()) {
2056 os << "\\noindent ";
2060 LyXAlignment const curAlign = params_.align();
2062 if (curAlign == layout_->align)
2066 case LYX_ALIGN_NONE:
2067 case LYX_ALIGN_BLOCK:
2068 case LYX_ALIGN_LAYOUT:
2069 case LYX_ALIGN_SPECIAL:
2070 case LYX_ALIGN_DECIMAL:
2072 case LYX_ALIGN_LEFT:
2073 case LYX_ALIGN_RIGHT:
2074 case LYX_ALIGN_CENTER:
2075 if (runparams.moving_arg) {
2082 string const begin_tag = "\\begin";
2083 InsetCode code = ownerCode();
2084 bool const lastpar = runparams.isLastPar;
2087 case LYX_ALIGN_NONE:
2088 case LYX_ALIGN_BLOCK:
2089 case LYX_ALIGN_LAYOUT:
2090 case LYX_ALIGN_SPECIAL:
2091 case LYX_ALIGN_DECIMAL:
2093 case LYX_ALIGN_LEFT: {
2095 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2096 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2098 output = corrected_env(begin_tag, "flushright", code, lastpar);
2099 os << from_ascii(output);
2100 adjust_row_column(output, texrow, column);
2102 } case LYX_ALIGN_RIGHT: {
2104 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2105 output = corrected_env(begin_tag, "flushright", code, lastpar);
2107 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2108 os << from_ascii(output);
2109 adjust_row_column(output, texrow, column);
2111 } case LYX_ALIGN_CENTER: {
2113 output = corrected_env(begin_tag, "center", code, lastpar);
2114 os << from_ascii(output);
2115 adjust_row_column(output, texrow, column);
2124 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2125 odocstream & os, TexRow & texrow,
2126 OutputParams const & runparams) const
2130 LyXAlignment const curAlign = params_.align();
2132 if (curAlign == layout_->align)
2136 case LYX_ALIGN_NONE:
2137 case LYX_ALIGN_BLOCK:
2138 case LYX_ALIGN_LAYOUT:
2139 case LYX_ALIGN_SPECIAL:
2140 case LYX_ALIGN_DECIMAL:
2142 case LYX_ALIGN_LEFT:
2143 case LYX_ALIGN_RIGHT:
2144 case LYX_ALIGN_CENTER:
2145 if (runparams.moving_arg) {
2152 string const end_tag = "\n\\par\\end";
2153 InsetCode code = ownerCode();
2154 bool const lastpar = runparams.isLastPar;
2157 case LYX_ALIGN_NONE:
2158 case LYX_ALIGN_BLOCK:
2159 case LYX_ALIGN_LAYOUT:
2160 case LYX_ALIGN_SPECIAL:
2161 case LYX_ALIGN_DECIMAL:
2163 case LYX_ALIGN_LEFT: {
2165 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2166 output = corrected_env(end_tag, "flushleft", code, lastpar);
2168 output = corrected_env(end_tag, "flushright", code, lastpar);
2169 os << from_ascii(output);
2170 adjust_row_column(output, texrow, column);
2172 } case LYX_ALIGN_RIGHT: {
2174 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2175 output = corrected_env(end_tag, "flushright", code, lastpar);
2177 output = corrected_env(end_tag, "flushleft", code, lastpar);
2178 os << from_ascii(output);
2179 adjust_row_column(output, texrow, column);
2181 } case LYX_ALIGN_CENTER: {
2183 output = corrected_env(end_tag, "center", code, lastpar);
2184 os << from_ascii(output);
2185 adjust_row_column(output, texrow, column);
2194 // This one spits out the text of the paragraph
2195 void Paragraph::latex(BufferParams const & bparams,
2196 Font const & outerfont,
2197 odocstream & os, TexRow & texrow,
2198 OutputParams const & runparams,
2199 int start_pos, int end_pos, bool force) const
2201 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2203 // FIXME This check should not be needed. Perhaps issue an
2204 // error if it triggers.
2205 Layout const & style = inInset().forcePlainLayout() ?
2206 bparams.documentClass().plainLayout() : *d->layout_;
2208 if (!force && style.inpreamble)
2211 bool const allowcust = allowParagraphCustomization();
2213 // Current base font for all inherited font changes, without any
2214 // change caused by an individual character, except for the language:
2215 // It is set to the language of the first character.
2216 // As long as we are in the label, this font is the base font of the
2217 // label. Before the first body character it is set to the base font
2221 // Maybe we have to create a optional argument.
2222 pos_type body_pos = beginOfBody();
2223 unsigned int column = 0;
2226 // the optional argument is kept in curly brackets in
2227 // case it contains a ']'
2230 basefont = getLabelFont(bparams, outerfont);
2232 basefont = getLayoutFont(bparams, outerfont);
2235 // Which font is currently active?
2236 Font running_font(basefont);
2237 // Do we have an open font change?
2238 bool open_font = false;
2240 Change runningChange = Change(Change::UNCHANGED);
2242 Encoding const * const prev_encoding = runparams.encoding;
2244 texrow.start(id(), 0);
2246 // if the paragraph is empty, the loop will not be entered at all
2248 if (style.isCommand()) {
2253 column += d->startTeXParParams(bparams, os, texrow,
2257 for (pos_type i = 0; i < size(); ++i) {
2258 // First char in paragraph or after label?
2259 if (i == body_pos) {
2262 column += running_font.latexWriteEndChanges(
2263 os, bparams, runparams,
2264 basefont, basefont);
2267 basefont = getLayoutFont(bparams, outerfont);
2268 running_font = basefont;
2270 column += Changes::latexMarkChange(os, bparams,
2271 runningChange, Change(Change::UNCHANGED),
2273 runningChange = Change(Change::UNCHANGED);
2278 if (style.isCommand()) {
2284 column += d->startTeXParParams(bparams, os,
2289 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2292 if (bparams.outputChanges && runningChange != change) {
2294 column += running_font.latexWriteEndChanges(
2295 os, bparams, runparams, basefont, basefont);
2298 basefont = getLayoutFont(bparams, outerfont);
2299 running_font = basefont;
2301 column += Changes::latexMarkChange(os, bparams, runningChange,
2303 runningChange = change;
2306 // do not output text which is marked deleted
2307 // if change tracking output is disabled
2308 if (!bparams.outputChanges && change.deleted()) {
2314 // Fully instantiated font
2315 Font const font = getFont(bparams, i, outerfont);
2317 Font const last_font = running_font;
2319 // Do we need to close the previous font?
2321 (font != running_font ||
2322 font.language() != running_font.language()))
2324 column += running_font.latexWriteEndChanges(
2325 os, bparams, runparams, basefont,
2326 (i == body_pos-1) ? basefont : font);
2327 running_font = basefont;
2331 // close babel's font environment before opening CJK.
2332 if (!running_font.language()->babel().empty() &&
2333 font.language()->encoding()->package() == Encoding::CJK) {
2334 string end_tag = subst(lyxrc.language_command_end,
2336 running_font.language()->babel());
2337 os << from_ascii(end_tag);
2338 column += end_tag.length();
2341 // Switch file encoding if necessary (and allowed)
2342 if (!runparams.pass_thru && !style.pass_thru &&
2343 runparams.encoding->package() != Encoding::none &&
2344 font.language()->encoding()->package() != Encoding::none) {
2345 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2346 runparams, *(font.language()->encoding()));
2347 if (enc_switch.first) {
2348 column += enc_switch.second;
2349 runparams.encoding = font.language()->encoding();
2353 char_type const c = d->text_[i];
2355 // Do we need to change font?
2356 if ((font != running_font ||
2357 font.language() != running_font.language()) &&
2360 odocstringstream ods;
2361 column += font.latexWriteStartChanges(ods, bparams,
2362 runparams, basefont,
2364 running_font = font;
2366 docstring fontchange = ods.str();
2367 // check whether the fontchange ends with a \\textcolor
2368 // modifier and the text starts with a space (bug 4473)
2369 docstring const last_modifier = rsplit(fontchange, '\\');
2370 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2371 os << fontchange << from_ascii("{}");
2372 // check if the fontchange ends with a trailing blank
2373 // (like "\small " (see bug 3382)
2374 else if (suffixIs(fontchange, ' ') && c == ' ')
2375 os << fontchange.substr(0, fontchange.size() - 1)
2376 << from_ascii("{}");
2381 // FIXME: think about end_pos implementation...
2382 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2383 // FIXME: integrate this case in latexSpecialChar
2384 // Do not print the separation of the optional argument
2385 // if style.pass_thru is false. This works because
2386 // latexSpecialChar ignores spaces if
2387 // style.pass_thru is false.
2388 if (i != body_pos - 1) {
2389 if (d->simpleTeXBlanks(
2390 runparams, os, texrow,
2391 i, column, font, style)) {
2392 // A surrogate pair was output. We
2393 // must not call latexSpecialChar
2394 // in this iteration, since it would output
2395 // the combining character again.
2402 OutputParams rp = runparams;
2403 rp.free_spacing = style.free_spacing;
2404 rp.local_font = &font;
2405 rp.intitle = style.intitle;
2407 // Two major modes: LaTeX or plain
2408 // Handle here those cases common to both modes
2409 // and then split to handle the two modes separately.
2410 if (c == META_INSET) {
2411 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2412 d->latexInset(bparams, os,
2413 texrow, rp, running_font,
2414 basefont, outerfont, open_font,
2415 runningChange, style, i, column);
2418 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2420 d->latexSpecialChar(os, rp, running_font, runningChange,
2422 } catch (EncodingException & e) {
2423 if (runparams.dryrun) {
2424 os << "<" << _("LyX Warning: ")
2425 << _("uncodable character") << " '";
2429 // add location information and throw again.
2438 // Set the encoding to that returned from latexSpecialChar (see
2439 // comment for encoding member in OutputParams.h)
2440 runparams.encoding = rp.encoding;
2443 // If we have an open font definition, we have to close it
2445 #ifdef FIXED_LANGUAGE_END_DETECTION
2447 running_font.latexWriteEndChanges(os, bparams,
2448 runparams, basefont,
2449 next_->getFont(bparams, 0, outerfont));
2451 running_font.latexWriteEndChanges(os, bparams,
2452 runparams, basefont, basefont);
2455 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2456 //FIXME: there as we start another \selectlanguage with the next paragraph if
2457 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2458 running_font.latexWriteEndChanges(os, bparams, runparams,
2459 basefont, basefont);
2463 column += Changes::latexMarkChange(os, bparams, runningChange,
2464 Change(Change::UNCHANGED), runparams);
2466 // Needed if there is an optional argument but no contents.
2467 if (body_pos > 0 && body_pos == size()) {
2471 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2472 && runparams.encoding != prev_encoding) {
2473 runparams.encoding = prev_encoding;
2474 if (!bparams.useXetex)
2475 os << setEncoding(prev_encoding->iconvName());
2478 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2482 bool Paragraph::emptyTag() const
2484 for (pos_type i = 0; i < size(); ++i) {
2485 if (Inset const * inset = getInset(i)) {
2486 InsetCode lyx_code = inset->lyxCode();
2487 // FIXME testing like that is wrong. What is
2489 if (lyx_code != TOC_CODE &&
2490 lyx_code != INCLUDE_CODE &&
2491 lyx_code != GRAPHICS_CODE &&
2492 lyx_code != ERT_CODE &&
2493 lyx_code != LISTINGS_CODE &&
2494 lyx_code != FLOAT_CODE &&
2495 lyx_code != TABULAR_CODE) {
2499 char_type c = d->text_[i];
2500 if (c != ' ' && c != '\t')
2508 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2511 for (pos_type i = 0; i < size(); ++i) {
2512 if (Inset const * inset = getInset(i)) {
2513 InsetCode lyx_code = inset->lyxCode();
2514 if (lyx_code == LABEL_CODE) {
2515 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2516 docstring const & id = il->getParam("name");
2517 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2525 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2529 for (i = 0; i < size(); ++i) {
2530 if (Inset const * inset = getInset(i)) {
2531 inset->docbook(os, runparams);
2533 char_type c = d->text_[i];
2536 os << sgml::escapeChar(c);
2543 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2547 for (i = 0; i < size(); ++i) {
2548 if (Inset const * inset = getInset(i)) {
2549 inset->xhtml(xs, runparams);
2551 char_type c = d->text_[i];
2561 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2564 pos_type size = text_.size();
2565 for (pos_type i = initial; i < size; ++i) {
2566 Font font = owner_->getFont(buf.params(), i, outerfont);
2567 if (text_[i] == META_INSET)
2569 if (i != initial && font != font_old)
2578 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2580 OutputParams const & runparams,
2581 Font const & outerfont,
2582 pos_type initial) const
2584 bool emph_flag = false;
2586 Layout const & style = *d->layout_;
2588 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2590 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2593 // parsing main loop
2594 for (pos_type i = initial; i < size(); ++i) {
2595 Font font = getFont(buf.params(), i, outerfont);
2597 // handle <emphasis> tag
2598 if (font_old.emph() != font.fontInfo().emph()) {
2599 if (font.fontInfo().emph() == FONT_ON) {
2602 } else if (i != initial) {
2603 os << "</emphasis>";
2608 if (Inset const * inset = getInset(i)) {
2609 inset->docbook(os, runparams);
2611 char_type c = d->text_[i];
2613 if (style.pass_thru)
2616 os << sgml::escapeChar(c);
2618 font_old = font.fontInfo();
2622 os << "</emphasis>";
2625 if (style.free_spacing)
2627 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2632 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2634 OutputParams const & runparams,
2635 Font const & outerfont,
2636 pos_type initial) const
2640 bool emph_flag = false;
2641 bool bold_flag = false;
2644 Layout const & style = *d->layout_;
2646 if (!runparams.for_toc && runparams.html_make_pars) {
2647 // generate a magic label for this paragraph
2648 string const attr = "id='" + magicLabel() + "'";
2649 xs << html::CompTag("a", attr);
2653 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2655 // parsing main loop
2656 for (pos_type i = initial; i < size(); ++i) {
2657 // let's not show deleted material in the output
2661 Font font = getFont(buf.params(), i, outerfont);
2664 if (font_old.emph() != font.fontInfo().emph()) {
2665 if (font.fontInfo().emph() == FONT_ON) {
2666 xs << html::StartTag("em");
2668 } else if (emph_flag && i != initial) {
2669 xs << html::EndTag("em");
2674 if (font_old.series() != font.fontInfo().series()) {
2675 if (font.fontInfo().series() == BOLD_SERIES) {
2676 xs << html::StartTag("strong");
2678 } else if (bold_flag && i != initial) {
2679 xs << html::EndTag("strong");
2684 // Other such tags? What about the other text ranges?
2686 Inset const * inset = getInset(i);
2688 InsetCommand const * ic = inset->asInsetCommand();
2689 InsetLayout const & il = inset->getLayout();
2690 InsetMath const * im = inset->asInsetMath();
2691 if (!runparams.for_toc
2692 || im || il.isInToc() || (ic && ic->isInToc())) {
2693 OutputParams np = runparams;
2694 if (!il.htmlisblock())
2695 np.html_in_par = true;
2696 retval += inset->xhtml(xs, np);
2699 char_type c = d->text_[i];
2701 if (style.pass_thru)
2703 else if (c == '-') {
2706 if (j < size() && d->text_[j] == '-') {
2708 if (j < size() && d->text_[j] == '-') {
2709 str += from_ascii("—");
2712 str += from_ascii("–");
2718 // We don't want to escape the entities. Note that
2719 // it is safe to do this, since str can otherwise
2720 // only be "-". E.g., it can't be "<".
2721 xs << XHTMLStream::NextRaw() << str;
2725 font_old = font.fontInfo();
2733 bool Paragraph::isHfill(pos_type pos) const
2735 Inset const * inset = getInset(pos);
2736 return inset && (inset->lyxCode() == SPACE_CODE &&
2737 inset->isStretchableSpace());
2741 bool Paragraph::isNewline(pos_type pos) const
2743 Inset const * inset = getInset(pos);
2744 return inset && inset->lyxCode() == NEWLINE_CODE;
2748 bool Paragraph::isLineSeparator(pos_type pos) const
2750 char_type const c = d->text_[pos];
2751 if (isLineSeparatorChar(c))
2753 Inset const * inset = getInset(pos);
2754 return inset && inset->isLineSeparator();
2758 bool Paragraph::isWordSeparator(pos_type pos) const
2760 if (Inset const * inset = getInset(pos))
2761 return !inset->isLetter();
2762 char_type const c = d->text_[pos];
2763 // We want to pass the ' and escape chars to the spellchecker
2764 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2765 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2770 bool Paragraph::isChar(pos_type pos) const
2772 if (Inset const * inset = getInset(pos))
2773 return inset->isChar();
2774 char_type const c = d->text_[pos];
2775 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2779 bool Paragraph::isSpace(pos_type pos) const
2781 if (Inset const * inset = getInset(pos))
2782 return inset->isSpace();
2783 char_type const c = d->text_[pos];
2784 return lyx::isSpace(c);
2789 Paragraph::getParLanguage(BufferParams const & bparams) const
2792 return getFirstFontSettings(bparams).language();
2793 // FIXME: we should check the prev par as well (Lgb)
2794 return bparams.language;
2798 bool Paragraph::isRTL(BufferParams const & bparams) const
2800 return lyxrc.rtl_support
2801 && getParLanguage(bparams)->rightToLeft()
2802 && !inInset().getLayout().forceLTR();
2806 void Paragraph::changeLanguage(BufferParams const & bparams,
2807 Language const * from, Language const * to)
2809 // change language including dummy font change at the end
2810 for (pos_type i = 0; i <= size(); ++i) {
2811 Font font = getFontSettings(bparams, i);
2812 if (font.language() == from) {
2813 font.setLanguage(to);
2817 d->requestSpellCheck(size());
2821 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2823 Language const * doc_language = bparams.language;
2824 FontList::const_iterator cit = d->fontlist_.begin();
2825 FontList::const_iterator end = d->fontlist_.end();
2827 for (; cit != end; ++cit)
2828 if (cit->font().language() != ignore_language &&
2829 cit->font().language() != latex_language &&
2830 cit->font().language() != doc_language)
2836 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2838 FontList::const_iterator cit = d->fontlist_.begin();
2839 FontList::const_iterator end = d->fontlist_.end();
2841 for (; cit != end; ++cit) {
2842 Language const * lang = cit->font().language();
2843 if (lang != ignore_language &&
2844 lang != latex_language)
2845 languages.insert(lang);
2850 docstring Paragraph::asString(int options) const
2852 return asString(0, size(), options);
2856 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2858 odocstringstream os;
2861 && options & AS_STR_LABEL
2862 && !d->params_.labelString().empty())
2863 os << d->params_.labelString() << ' ';
2865 for (pos_type i = beg; i < end; ++i) {
2866 char_type const c = d->text_[i];
2867 if (isPrintable(c) || c == '\t'
2868 || (c == '\n' && (options & AS_STR_NEWLINES)))
2870 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2871 getInset(i)->tocString(os);
2872 if (getInset(i)->asInsetMath())
2881 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2883 odocstringstream os;
2886 && options & AS_STR_LABEL
2887 && !d->params_.labelString().empty())
2888 os << d->params_.labelString() << ' ';
2890 for (pos_type i = beg; i < end; ++i) {
2891 char_type const c = d->text_[i];
2892 if (isPrintable(c) || c == '\t'
2893 || (c == '\n' && (options & AS_STR_NEWLINES)))
2895 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2896 getInset(i)->plaintext(os, runparams);
2904 void Paragraph::setInsetOwner(Inset const * inset)
2906 d->inset_owner_ = inset;
2910 int Paragraph::id() const
2916 void Paragraph::setId(int id)
2922 Layout const & Paragraph::layout() const
2928 void Paragraph::setLayout(Layout const & layout)
2930 d->layout_ = &layout;
2934 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2936 setLayout(tc.defaultLayout());
2940 void Paragraph::setPlainLayout(DocumentClass const & tc)
2942 setLayout(tc.plainLayout());
2946 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2948 if (usePlainLayout())
2949 setPlainLayout(tclass);
2951 setDefaultLayout(tclass);
2955 Inset const & Paragraph::inInset() const
2957 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2958 _("Memory problem"), _("Paragraph not properly initialized")));
2959 return *d->inset_owner_;
2963 ParagraphParameters & Paragraph::params()
2969 ParagraphParameters const & Paragraph::params() const
2975 bool Paragraph::isFreeSpacing() const
2977 if (d->layout_->free_spacing)
2979 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2983 bool Paragraph::allowEmpty() const
2985 if (d->layout_->keepempty)
2987 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2991 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2993 if (!Encodings::isArabicChar(c))
2996 char_type prev_char = ' ';
2997 char_type next_char = ' ';
2999 for (pos_type i = pos - 1; i >= 0; --i) {
3000 char_type const par_char = d->text_[i];
3001 if (!Encodings::isArabicComposeChar(par_char)) {
3002 prev_char = par_char;
3007 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3008 char_type const par_char = d->text_[i];
3009 if (!Encodings::isArabicComposeChar(par_char)) {
3010 next_char = par_char;
3015 if (Encodings::isArabicChar(next_char)) {
3016 if (Encodings::isArabicChar(prev_char) &&
3017 !Encodings::isArabicSpecialChar(prev_char))
3018 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3020 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3022 if (Encodings::isArabicChar(prev_char) &&
3023 !Encodings::isArabicSpecialChar(prev_char))
3024 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3026 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3031 int Paragraph::checkBiblio(Buffer const & buffer)
3034 // This is getting more and more a mess. ...We really should clean
3035 // up this bibitem issue for 1.6. See also bug 2743.
3037 // Add bibitem insets if necessary
3038 if (d->layout_->labeltype != LABEL_BIBLIO)
3041 bool hasbibitem = !d->insetlist_.empty()
3042 // Insist on it being in pos 0
3043 && d->text_[0] == META_INSET
3044 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3046 bool track_changes = buffer.params().trackChanges;
3051 // remove a bibitem in pos != 0
3052 // restore it later in pos 0 if necessary
3053 // (e.g. if a user inserts contents _before_ the item)
3054 // we're assuming there's only one of these, which there
3056 int erasedInsetPosition = -1;
3057 InsetList::iterator it = d->insetlist_.begin();
3058 InsetList::iterator end = d->insetlist_.end();
3059 for (; it != end; ++it)
3060 if (it->inset->lyxCode() == BIBITEM_CODE
3062 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3063 oldkey = olditem->getParam("key");
3064 oldlabel = olditem->getParam("label");
3065 erasedInsetPosition = it->pos;
3066 eraseChar(erasedInsetPosition, track_changes);
3070 // There was an InsetBibitem at the beginning, and we didn't
3071 // have to erase one.
3072 if (hasbibitem && erasedInsetPosition < 0)
3075 // There was an InsetBibitem at the beginning and we did have to
3076 // erase one. So we give its properties to the beginning inset.
3078 InsetBibitem * inset =
3079 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3080 if (!oldkey.empty())
3081 inset->setParam("key", oldkey);
3082 inset->setParam("label", oldlabel);
3083 return -erasedInsetPosition;
3086 // There was no inset at the beginning, so we need to create one with
3087 // the key and label of the one we erased.
3088 InsetBibitem * inset =
3089 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3090 // restore values of previously deleted item in this par.
3091 if (!oldkey.empty())
3092 inset->setParam("key", oldkey);
3093 inset->setParam("label", oldlabel);
3094 insertInset(0, static_cast<Inset *>(inset),
3095 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3101 void Paragraph::checkAuthors(AuthorList const & authorList)
3103 d->changes_.checkAuthors(authorList);
3107 bool Paragraph::isChanged(pos_type pos) const
3109 return lookupChange(pos).changed();
3113 bool Paragraph::isInserted(pos_type pos) const
3115 return lookupChange(pos).inserted();
3119 bool Paragraph::isDeleted(pos_type pos) const
3121 return lookupChange(pos).deleted();
3125 InsetList const & Paragraph::insetList() const
3127 return d->insetlist_;
3131 void Paragraph::setBuffer(Buffer & b)
3133 d->insetlist_.setBuffer(b);
3137 Inset * Paragraph::releaseInset(pos_type pos)
3139 Inset * inset = d->insetlist_.release(pos);
3140 /// does not honour change tracking!
3141 eraseChar(pos, false);
3146 Inset * Paragraph::getInset(pos_type pos)
3148 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3149 ? d->insetlist_.get(pos) : 0;
3153 Inset const * Paragraph::getInset(pos_type pos) const
3155 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3156 ? d->insetlist_.get(pos) : 0;
3160 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3161 pos_type & right, TextCase action)
3163 // process sequences of modified characters; in change
3164 // tracking mode, this approach results in much better
3165 // usability than changing case on a char-by-char basis
3168 bool const trackChanges = bparams.trackChanges;
3170 bool capitalize = true;
3172 for (; pos < right; ++pos) {
3173 char_type oldChar = d->text_[pos];
3174 char_type newChar = oldChar;
3176 // ignore insets and don't play with deleted text!
3177 if (oldChar != META_INSET && !isDeleted(pos)) {
3179 case text_lowercase:
3180 newChar = lowercase(oldChar);
3182 case text_capitalization:
3184 newChar = uppercase(oldChar);
3188 case text_uppercase:
3189 newChar = uppercase(oldChar);
3194 if (isWordSeparator(pos) || isDeleted(pos)) {
3195 // permit capitalization again
3199 if (oldChar != newChar) {
3201 if (pos != right - 1)
3203 // step behind the changing area
3207 int erasePos = pos - changes.size();
3208 for (size_t i = 0; i < changes.size(); i++) {
3209 insertChar(pos, changes[i],
3210 getFontSettings(bparams,
3213 if (!eraseChar(erasePos, trackChanges)) {
3216 ++right; // expand selection
3224 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3225 pos_type pos, bool del) const
3227 int const strsize = str.length();
3229 pos_type const parsize = d->text_.size();
3230 for (i = 0; pos + i < parsize; ++i) {
3233 if (cs && str[i] != d->text_[pos + i])
3235 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3237 if (!del && isDeleted(pos + i))
3244 // if necessary, check whether string matches word
3246 if (pos > 0 && !isWordSeparator(pos - 1))
3248 if (pos + strsize < parsize
3249 && !isWordSeparator(pos + strsize))
3257 char_type Paragraph::getChar(pos_type pos) const
3259 return d->text_[pos];
3263 pos_type Paragraph::size() const
3265 return d->text_.size();
3269 bool Paragraph::empty() const
3271 return d->text_.empty();
3275 bool Paragraph::isInset(pos_type pos) const
3277 return d->text_[pos] == META_INSET;
3281 bool Paragraph::isSeparator(pos_type pos) const
3283 //FIXME: Are we sure this can be the only separator?
3284 return d->text_[pos] == ' ';
3288 void Paragraph::deregisterWords()
3290 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3291 Private::LangWordsMap::const_iterator ite = d->words_.end();
3292 for (; itl != ite; ++itl) {
3293 WordList * wl = theWordList(itl->first);
3294 Private::Words::const_iterator it = (itl->second).begin();
3295 Private::Words::const_iterator et = (itl->second).end();
3296 for (; it != et; ++it)
3303 void Paragraph::locateWord(pos_type & from, pos_type & to,
3304 word_location const loc) const
3307 case WHOLE_WORD_STRICT:
3308 if (from == 0 || from == size()
3309 || isWordSeparator(from)
3310 || isWordSeparator(from - 1)) {
3314 // no break here, we go to the next
3317 // If we are already at the beginning of a word, do nothing
3318 if (!from || isWordSeparator(from - 1))
3320 // no break here, we go to the next
3323 // always move the cursor to the beginning of previous word
3324 while (from && !isWordSeparator(from - 1))
3328 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3331 // no need to move the 'from' cursor
3335 while (to < size() && !isWordSeparator(to))
3340 void Paragraph::collectWords()
3342 // This is the value that needs to be exposed in the preferences
3343 // to resolve bug #6760.
3344 static int minlength = 6;
3345 pos_type n = size();
3346 for (pos_type pos = 0; pos < n; ++pos) {
3347 if (isWordSeparator(pos))
3349 pos_type from = pos;
3350 locateWord(from, pos, WHOLE_WORD);
3351 if (pos - from >= minlength) {
3352 docstring word = asString(from, pos, AS_STR_NONE);
3353 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3354 if (cit == d->fontlist_.end())
3356 Language const * lang = cit->font().language();
3357 d->words_[*lang].insert(word);
3363 void Paragraph::registerWords()
3365 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3366 Private::LangWordsMap::const_iterator ite = d->words_.end();
3367 for (; itl != ite; ++itl) {
3368 WordList * wl = theWordList(itl->first);
3369 Private::Words::const_iterator it = (itl->second).begin();
3370 Private::Words::const_iterator et = (itl->second).end();
3371 for (; it != et; ++it)
3377 void Paragraph::updateWords()
3385 Language * Paragraph::Private::locateSpellRange(
3386 pos_type & from, pos_type & to,
3387 Positions & softbreaks) const
3389 // skip leading white space
3390 while (from < to && owner_->isWordSeparator(from))
3392 // don't check empty range
3395 // get current language
3396 Language * lang = getSpellLanguage(from);
3397 pos_type last = from;
3398 bool samelang = true;
3399 bool sameinset = true;
3400 while (last < to && samelang && sameinset) {
3401 // hop to end of word
3402 while (last < to && !owner_->isWordSeparator(last)) {
3403 if (owner_->getInset(last)) {
3404 softbreaks.insert(softbreaks.end(), last);
3408 // hop to next word while checking for insets
3409 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3410 if (Inset const * inset = owner_->getInset(last))
3411 sameinset = inset->isChar() && inset->isLetter();
3415 if (sameinset && last < to) {
3416 // now check for language change
3417 samelang = lang == getSpellLanguage(last);
3420 // if language change detected backstep is needed
3428 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3431 const_cast<Language *>(owner_->getFontSettings(
3432 inset_owner_->buffer().params(), from).language());
3433 if (lang == inset_owner_->buffer().params().language
3434 && !lyxrc.spellchecker_alt_lang.empty()) {
3436 string const lang_variety =
3437 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3438 lang->setCode(lang_code);
3439 lang->setVariety(lang_variety);
3445 void Paragraph::requestSpellCheck(pos_type pos)
3447 d->requestSpellCheck(pos == -1 ? size() : pos);
3451 bool Paragraph::needsSpellCheck() const
3453 SpellChecker::ChangeNumber speller_change_number = 0;
3454 if (theSpellChecker())
3455 speller_change_number = theSpellChecker()->changeNumber();
3456 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3457 d->speller_state_.needsCompleteRefresh(speller_change_number);
3459 return d->needsSpellCheck();
3463 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3464 WordLangTuple & wl, docstring_list & suggestions,
3465 bool do_suggestion, bool check_learned) const
3467 SpellChecker::Result result = SpellChecker::WORD_OK;
3468 SpellChecker * speller = theSpellChecker();
3472 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3475 locateWord(from, to, WHOLE_WORD);
3476 if (from == to || from >= pos_type(d->text_.size()))
3479 docstring word = asString(from, to, AS_STR_INSETS);
3480 Language * lang = d->getSpellLanguage(from);
3482 wl = WordLangTuple(word, lang);
3487 if (needsSpellCheck() || check_learned) {
3488 // Ignore words with digits
3489 // FIXME: make this customizable
3490 // (note that some checkers ignore words with digits by default)
3491 if (!hasDigit(word))
3492 result = speller->check(wl);
3493 d->setMisspelled(from, to, result);
3495 result = d->speller_state_.getState(from);
3498 bool const misspelled_ = SpellChecker::misspelled(result) ;
3499 if (misspelled_ && do_suggestion)
3500 speller->suggest(wl, suggestions);
3501 else if (misspelled_)
3502 LYXERR(Debug::GUI, "misspelled word: \"" <<
3504 from << ".." << to << "]");
3506 suggestions.clear();
3512 void Paragraph::Private::markMisspelledWords(
3513 pos_type const & first, pos_type const & last,
3514 SpellChecker::Result result,
3515 docstring const & word,
3516 Positions const & softbreaks)
3518 if (!SpellChecker::misspelled(result)) {
3519 setMisspelled(first, last, SpellChecker::WORD_OK);
3523 SpellChecker * speller = theSpellChecker();
3524 // locate and enumerate the error positions
3525 int nerrors = speller->numMisspelledWords();
3527 PositionsIterator it = softbreaks.begin();
3528 PositionsIterator et = softbreaks.end();
3529 for (int index = 0; index < nerrors; ++index) {
3532 speller->misspelledWord(index, wstart, wlen);
3533 /// should not happen if speller supports range checks
3534 if (!wlen) continue;
3535 docstring const misspelled = word.substr(wstart, wlen);
3536 wstart += first + numbreaks;
3537 if (snext < wstart) {
3538 /// mark the range of correct spelling
3539 numbreaks += countSoftbreaks(it, et, wstart);
3540 setMisspelled(snext,
3541 wstart - 1, SpellChecker::WORD_OK);
3543 snext = wstart + wlen;
3544 numbreaks += countSoftbreaks(it, et, snext);
3545 /// mark the range of misspelling
3546 setMisspelled(wstart, snext, result);
3547 LYXERR(Debug::GUI, "misspelled word: \"" <<
3548 misspelled << "\" [" <<
3549 wstart << ".." << (snext-1) << "]");
3552 if (snext <= last) {
3553 /// mark the range of correct spelling at end
3554 setMisspelled(snext, last, SpellChecker::WORD_OK);
3559 void Paragraph::spellCheck() const
3561 SpellChecker * speller = theSpellChecker();
3562 if (!speller || !size() ||!needsSpellCheck())
3566 d->rangeOfSpellCheck(start, endpos);
3567 if (speller->canCheckParagraph()) {
3568 // loop until we leave the range
3569 for (pos_type first = start; first < endpos; ) {
3570 pos_type last = endpos;
3571 Private::Positions softbreaks;
3572 Language * lang = d->locateSpellRange(first, last, softbreaks);
3573 if (first >= endpos)
3575 // start the spell checker on the unit of meaning
3576 docstring word = asString(first, last, AS_STR_INSETS);
3577 WordLangTuple wl = WordLangTuple(word, lang);
3578 SpellChecker::Result result = word.size() ?
3579 speller->check(wl) : SpellChecker::WORD_OK;
3580 d->markMisspelledWords(first, last, result, word, softbreaks);
3584 static docstring_list suggestions;
3585 pos_type to = endpos;
3586 while (start < endpos) {
3588 spellCheck(start, to, wl, suggestions, false);
3592 d->readySpellCheck();
3596 bool Paragraph::isMisspelled(pos_type pos) const
3598 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3602 string Paragraph::magicLabel() const
3605 ss << "magicparlabel-" << id();