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, pos_type & start) const
369 while (it != et && *it < start) {
377 void markMisspelledWords(pos_type const & first, pos_type const & last,
378 SpellChecker::Result result,
379 docstring const & word,
380 Positions const & softbreaks);
382 InsetCode ownerCode() const
384 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
387 /// Which Paragraph owns us?
391 Inset const * inset_owner_;
400 ParagraphParameters params_;
402 /// for recording and looking up changes
406 InsetList insetlist_;
409 pos_type begin_of_body_;
411 typedef docstring TextContainer;
415 typedef set<docstring> Words;
416 typedef map<Language, Words> LangWordsMap;
420 Layout const * layout_;
422 SpellCheckerState speller_state_;
428 struct special_phrase {
434 special_phrase const special_phrases[] = {
435 { "LyX", from_ascii("\\LyX{}"), false },
436 { "TeX", from_ascii("\\TeX{}"), true },
437 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
438 { "LaTeX", from_ascii("\\LaTeX{}"), true },
441 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
446 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
447 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
453 // Initialization of the counter for the paragraph id's,
455 // FIXME: There should be a more intelligent way to generate and use the
456 // paragraph ids per buffer instead a global static counter for all InsetText
457 // in the running program.
458 static int paragraph_id = -1;
460 Paragraph::Private::Private(Private const & p, Paragraph * owner)
461 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
462 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
463 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
464 layout_(p.layout_), speller_state_(p.speller_state_)
466 id_ = ++paragraph_id;
467 requestSpellCheck(p.text_.size());
471 Paragraph::Private::Private(Private const & p, Paragraph * owner,
472 pos_type beg, pos_type end)
473 : owner_(owner), inset_owner_(p.inset_owner_),
474 params_(p.params_), changes_(p.changes_),
475 insetlist_(p.insetlist_, beg, end),
476 begin_of_body_(p.begin_of_body_), words_(p.words_),
477 layout_(p.layout_), speller_state_(p.speller_state_)
479 id_ = ++paragraph_id;
480 if (beg >= pos_type(p.text_.size()))
482 text_ = p.text_.substr(beg, end - beg);
484 FontList::const_iterator fcit = fontlist_.begin();
485 FontList::const_iterator fend = fontlist_.end();
486 for (; fcit != fend; ++fcit) {
487 if (fcit->pos() < beg)
489 if (fcit->pos() >= end) {
490 // Add last entry in the fontlist_.
491 fontlist_.set(text_.size() - 1, fcit->font());
494 // Add a new entry in the fontlist_.
495 fontlist_.set(fcit->pos() - beg, fcit->font());
497 requestSpellCheck(p.text_.size());
501 void Paragraph::addChangesToToc(DocIterator const & cdit,
502 Buffer const & buf) const
504 d->changes_.addToToc(cdit, buf);
508 bool Paragraph::isDeleted(pos_type start, pos_type end) const
510 LASSERT(start >= 0 && start <= size(), /**/);
511 LASSERT(end > start && end <= size() + 1, /**/);
513 return d->changes_.isDeleted(start, end);
517 bool Paragraph::isChanged(pos_type start, pos_type end) const
519 LASSERT(start >= 0 && start <= size(), /**/);
520 LASSERT(end > start && end <= size() + 1, /**/);
522 return d->changes_.isChanged(start, end);
526 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
528 // keep the logic here in sync with the logic of eraseChars()
532 Change const change = d->changes_.lookup(size());
533 return change.inserted() && change.currentAuthor();
537 void Paragraph::setChange(Change const & change)
539 // beware of the imaginary end-of-par character!
540 d->changes_.set(change, 0, size() + 1);
543 * Propagate the change recursively - but not in case of DELETED!
545 * Imagine that your co-author makes changes in an existing inset. He
546 * sends your document to you and you come to the conclusion that the
547 * inset should go completely. If you erase it, LyX must not delete all
548 * text within the inset. Otherwise, the change tracked insertions of
549 * your co-author get lost and there is no way to restore them later.
551 * Conclusion: An inset's content should remain untouched if you delete it
554 if (!change.deleted()) {
555 for (pos_type pos = 0; pos < size(); ++pos) {
556 if (Inset * inset = getInset(pos))
557 inset->setChange(change);
563 void Paragraph::setChange(pos_type pos, Change const & change)
565 LASSERT(pos >= 0 && pos <= size(), /**/);
566 d->changes_.set(change, pos);
568 // see comment in setChange(Change const &) above
569 if (!change.deleted() && pos < size())
570 if (Inset * inset = getInset(pos))
571 inset->setChange(change);
575 Change const & Paragraph::lookupChange(pos_type pos) const
577 LASSERT(pos >= 0 && pos <= size(), /**/);
578 return d->changes_.lookup(pos);
582 void Paragraph::acceptChanges(pos_type start, pos_type end)
584 LASSERT(start >= 0 && start <= size(), /**/);
585 LASSERT(end > start && end <= size() + 1, /**/);
587 for (pos_type pos = start; pos < end; ++pos) {
588 switch (lookupChange(pos).type) {
589 case Change::UNCHANGED:
590 // accept changes in nested inset
591 if (Inset * inset = getInset(pos))
592 inset->acceptChanges();
595 case Change::INSERTED:
596 d->changes_.set(Change(Change::UNCHANGED), pos);
597 // also accept changes in nested inset
598 if (Inset * inset = getInset(pos))
599 inset->acceptChanges();
602 case Change::DELETED:
603 // Suppress access to non-existent
604 // "end-of-paragraph char"
606 eraseChar(pos, false);
617 void Paragraph::rejectChanges(pos_type start, pos_type end)
619 LASSERT(start >= 0 && start <= size(), /**/);
620 LASSERT(end > start && end <= size() + 1, /**/);
622 for (pos_type pos = start; pos < end; ++pos) {
623 switch (lookupChange(pos).type) {
624 case Change::UNCHANGED:
625 // reject changes in nested inset
626 if (Inset * inset = getInset(pos))
627 inset->rejectChanges();
630 case Change::INSERTED:
631 // Suppress access to non-existent
632 // "end-of-paragraph char"
634 eraseChar(pos, false);
640 case Change::DELETED:
641 d->changes_.set(Change(Change::UNCHANGED), pos);
643 // Do NOT reject changes within a deleted inset!
644 // There may be insertions of a co-author inside of it!
652 void Paragraph::Private::insertChar(pos_type pos, char_type c,
653 Change const & change)
655 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
658 changes_.insert(change, pos);
660 // This is actually very common when parsing buffers (and
661 // maybe inserting ascii text)
662 if (pos == pos_type(text_.size())) {
663 // when appending characters, no need to update tables
665 // but we want spell checking
666 requestSpellCheck(pos);
670 text_.insert(text_.begin() + pos, c);
672 // Update the font table.
673 fontlist_.increasePosAfterPos(pos);
676 insetlist_.increasePosAfterPos(pos);
678 // Update list of misspelled positions
679 speller_state_.increasePosAfterPos(pos);
683 bool Paragraph::insertInset(pos_type pos, Inset * inset,
684 Change const & change)
686 LASSERT(inset, /**/);
687 LASSERT(pos >= 0 && pos <= size(), /**/);
689 // Paragraph::insertInset() can be used in cut/copy/paste operation where
690 // d->inset_owner_ is not set yet.
691 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
694 d->insertChar(pos, META_INSET, change);
695 LASSERT(d->text_[pos] == META_INSET, /**/);
697 // Add a new entry in the insetlist_.
698 d->insetlist_.insert(inset, pos);
700 // Some insets require run of spell checker
701 requestSpellCheck(pos);
706 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
708 LASSERT(pos >= 0 && pos <= size(), return false);
710 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
713 Change change = d->changes_.lookup(pos);
715 // set the character to DELETED if
716 // a) it was previously unchanged or
717 // b) it was inserted by a co-author
719 if (!change.changed() ||
720 (change.inserted() && !change.currentAuthor())) {
721 setChange(pos, Change(Change::DELETED));
725 if (change.deleted())
729 // Don't physically access the imaginary end-of-paragraph character.
730 // eraseChar() can only mark it as DELETED. A physical deletion of
731 // end-of-par must be handled externally.
737 d->changes_.erase(pos);
739 // if it is an inset, delete the inset entry
740 if (d->text_[pos] == META_INSET)
741 d->insetlist_.erase(pos);
743 d->text_.erase(d->text_.begin() + pos);
745 // Update the fontlist_
746 d->fontlist_.erase(pos);
748 // Update the insetlist_
749 d->insetlist_.decreasePosAfterPos(pos);
751 // Update list of misspelled positions
752 d->speller_state_.decreasePosAfterPos(pos);
758 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
760 LASSERT(start >= 0 && start <= size(), /**/);
761 LASSERT(end >= start && end <= size() + 1, /**/);
764 for (pos_type count = end - start; count; --count) {
765 if (!eraseChar(i, trackChanges))
772 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
773 char_type next, OutputParams const & runparams)
775 // Writing next here may circumvent a possible font change between
776 // c and next. Since next is only output if it forms a surrogate pair
777 // with c we can ignore this:
778 // A font change inside a surrogate pair does not make sense and is
779 // hopefully impossible to input.
780 // FIXME: change tracking
781 // Is this correct WRT change tracking?
782 Encoding const & encoding = *(runparams.encoding);
783 docstring const latex1 = encoding.latexChar(next);
784 docstring const latex2 = encoding.latexChar(c);
785 if (docstring(1, next) == latex1) {
786 // the encoding supports the combination
787 os << latex2 << latex1;
788 return latex1.length() + latex2.length();
789 } else if (runparams.local_font &&
790 runparams.local_font->language()->lang() == "polutonikogreek") {
791 // polutonikogreek only works without the brackets
792 os << latex1 << latex2;
793 return latex1.length() + latex2.length();
795 os << latex1 << '{' << latex2 << '}';
796 return latex1.length() + latex2.length() + 2;
800 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
801 odocstream & os, TexRow & texrow,
803 unsigned int & column,
805 Layout const & style)
807 if (style.pass_thru || runparams.pass_thru)
810 if (i + 1 < int(text_.size())) {
811 char_type next = text_[i + 1];
812 if (Encodings::isCombiningChar(next)) {
813 // This space has an accent, so we must always output it.
814 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
819 if (runparams.linelen > 0
820 && column > runparams.linelen
822 && text_[i - 1] != ' '
823 && (i + 1 < int(text_.size()))
824 // same in FreeSpacing mode
825 && !owner_->isFreeSpacing()
826 // In typewriter mode, we want to avoid
827 // ! . ? : at the end of a line
828 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
829 && (text_[i - 1] == '.'
830 || text_[i - 1] == '?'
831 || text_[i - 1] == ':'
832 || text_[i - 1] == '!'))) {
835 texrow.start(owner_->id(), i + 1);
837 } else if (style.free_spacing) {
846 int Paragraph::Private::writeScriptChars(odocstream & os,
847 docstring const & ltx,
848 Change const & runningChange,
849 Encoding const & encoding,
852 // FIXME: modifying i here is not very nice...
854 // We only arrive here when a proper language for character text_[i] has
855 // not been specified (i.e., it could not be translated in the current
856 // latex encoding) or its latex translation has been forced, and it
857 // belongs to a known script.
858 // Parameter ltx contains the latex translation of text_[i] as specified
859 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
860 // The latex macro name "textXXX" specifies the script to which text_[i]
861 // belongs and we use it in order to check whether characters from the
862 // same script immediately follow, such that we can collect them in a
863 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
864 // for the first char but only "<spec>" for all subsequent chars.
865 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
866 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
867 string script = to_ascii(ltx.substr(1, brace1 - 1));
870 bool closing_brace = true;
871 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
872 // Correct encoding is being used, so we can avoid \textgreek.
875 closing_brace = false;
877 os << ltx.substr(pos, length);
878 int size = text_.size();
879 while (i + 1 < size) {
880 char_type const next = text_[i + 1];
881 // Stop here if next character belongs to another script
882 // or there is a change in change tracking status.
883 if (!Encodings::isKnownScriptChar(next, script) ||
884 runningChange != owner_->lookupChange(i + 1))
888 FontList::const_iterator cit = fontlist_.begin();
889 FontList::const_iterator end = fontlist_.end();
890 for (; cit != end; ++cit) {
891 if (cit->pos() >= i && !found) {
892 prev_font = cit->font();
895 if (cit->pos() >= i + 1)
898 // Stop here if there is a font attribute or encoding change.
899 if (found && cit != end && prev_font != cit->font())
901 docstring const latex = encoding.latexChar(next);
902 docstring::size_type const b1 =
903 latex.find_first_of(from_ascii("{"));
904 docstring::size_type const b2 =
905 latex.find_last_of(from_ascii("}"));
906 int const len = b2 - b1 - 1;
907 os << latex.substr(b1 + 1, len);
919 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
921 pos_type const len = str.length();
923 // is the paragraph large enough?
924 if (pos + len > int(text_.size()))
927 // does the wanted text start at point?
928 for (string::size_type i = 0; i < str.length(); ++i) {
929 // Caution: direct comparison of characters works only
930 // because str is pure ASCII.
931 if (str[i] != text_[pos + i])
935 return fontlist_.hasChangeInRange(pos, len);
939 void Paragraph::Private::latexInset(BufferParams const & bparams,
942 OutputParams & runparams,
945 Font const & outerfont,
947 Change & running_change,
948 Layout const & style,
950 unsigned int & column)
952 Inset * inset = owner_->getInset(i);
953 LASSERT(inset, /**/);
955 if (style.pass_thru) {
956 inset->plaintext(os, runparams);
960 // FIXME: move this to InsetNewline::latex
961 if (inset->lyxCode() == NEWLINE_CODE) {
962 // newlines are handled differently here than
963 // the default in simpleTeXSpecialChars().
964 if (!style.newline_allowed) {
968 column += running_font.latexWriteEndChanges(
969 os, bparams, runparams,
974 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
977 basefont = owner_->getLayoutFont(bparams, outerfont);
978 running_font = basefont;
980 if (runparams.moving_arg)
985 texrow.start(owner_->id(), i + 1);
989 if (owner_->isDeleted(i)) {
990 if( ++runparams.inDeletedInset == 1)
991 runparams.changeOfDeletedInset = owner_->lookupChange(i);
994 if (inset->canTrackChanges()) {
995 column += Changes::latexMarkChange(os, bparams, running_change,
996 Change(Change::UNCHANGED), runparams);
997 running_change = Change(Change::UNCHANGED);
1001 odocstream::pos_type const len = os.tellp();
1003 if (inset->forceLTR()
1004 && running_font.isRightToLeft()
1005 // ERT is an exception, it should be output with no
1006 // decorations at all
1007 && inset->lyxCode() != ERT_CODE) {
1008 if (running_font.language()->lang() == "farsi")
1015 // FIXME: Bug: we can have an empty font change here!
1016 // if there has just been a font change, we are going to close it
1017 // right now, which means stupid latex code like \textsf{}. AFAIK,
1018 // this does not harm dvi output. A minor bug, thus (JMarc)
1020 // Some insets cannot be inside a font change command.
1021 // However, even such insets *can* be placed in \L or \R
1022 // or their equivalents (for RTL language switches), so we don't
1023 // close the language in those cases.
1024 // ArabTeX, though, cannot handle this special behavior, it seems.
1025 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1026 || running_font.language()->lang() == "arabic_arabtex";
1027 if (open_font && inset->noFontChange()) {
1028 bool closeLanguage = arabtex
1029 || basefont.isRightToLeft() == running_font.isRightToLeft();
1030 unsigned int count = running_font.latexWriteEndChanges(os,
1031 bparams, runparams, basefont, basefont, closeLanguage);
1033 // if any font properties were closed, update the running_font,
1034 // making sure, however, to leave the language as it was
1036 // FIXME: probably a better way to keep track of the old
1037 // language, than copying the entire font?
1038 Font const copy_font(running_font);
1039 basefont = owner_->getLayoutFont(bparams, outerfont);
1040 running_font = basefont;
1042 running_font.setLanguage(copy_font.language());
1043 // leave font open if language is still open
1044 open_font = (running_font.language() == basefont.language());
1046 runparams.local_font = &basefont;
1053 tmp = inset->latex(os, runparams);
1054 } catch (EncodingException & e) {
1055 // add location information and throw again.
1062 if (running_font.language()->lang() == "farsi")
1069 texrow.newlines(tmp);
1070 texrow.start(owner_->id(), i + 1);
1073 column += os.tellp() - len;
1076 if (owner_->isDeleted(i))
1077 --runparams.inDeletedInset;
1081 void Paragraph::Private::latexSpecialChar(
1083 OutputParams const & runparams,
1084 Font const & running_font,
1085 Change const & running_change,
1086 Layout const & style,
1088 unsigned int & column)
1090 char_type const c = text_[i];
1092 if (style.pass_thru || runparams.pass_thru) {
1094 // FIXME UNICODE: This can fail if c cannot
1095 // be encoded in the current encoding.
1100 // If T1 font encoding is used, use the special
1101 // characters it provides.
1102 // NOTE: some languages reset the font encoding
1104 if (!running_font.language()->internalFontEncoding()
1105 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1108 // \tt font needs special treatment
1109 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1110 && latexSpecialTypewriter(c, os, i, column))
1113 // Otherwise, we use what LaTeX provides us.
1116 os << "\\textbackslash{}";
1120 os << "\\textless{}";
1124 os << "\\textgreater{}";
1128 os << "\\textbar{}";
1135 os << "\\char`\\\"{}";
1140 case '%': case '#': case '{':
1148 os << "\\textasciitilde{}";
1153 os << "\\textasciicircum{}";
1160 // avoid being mistaken for optional arguments
1168 // Blanks are printed before font switching.
1169 // Sure? I am not! (try nice-latex)
1170 // I am sure it's correct. LyX might be smarter
1171 // in the future, but for now, nothing wrong is
1177 if (latexSpecialPhrase(os, i, column, runparams))
1183 Encoding const & encoding = *(runparams.encoding);
1184 if (i + 1 < int(text_.size())) {
1185 char_type next = text_[i + 1];
1186 if (Encodings::isCombiningChar(next)) {
1187 column += latexSurrogatePair(os, c, next, runparams) - 1;
1193 docstring const latex = encoding.latexChar(c);
1194 if (Encodings::isKnownScriptChar(c, script)
1195 && prefixIs(latex, from_ascii("\\" + script)))
1196 column += writeScriptChars(os, latex,
1197 running_change, encoding, i) - 1;
1198 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1199 // Prevent eating of a following
1200 // space or command corruption by
1201 // following characters
1202 column += latex.length() + 1;
1203 os << latex << "{}";
1205 column += latex.length() - 1;
1213 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1214 pos_type i, unsigned int & column)
1220 // In T1 encoding, these characters exist
1221 // but we should avoid ligatures
1222 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1224 os << "\\textcompwordmark{}";
1231 // soul.sty breaks with \char`\"
1232 os << "\\textquotedbl{}";
1241 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1242 pos_type i, unsigned int & column)
1246 // within \ttfamily, "--" is merged to "-" (no endash)
1247 // so we avoid this rather irritating ligature
1248 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1255 // everything else has to be checked separately
1256 // (depending on the encoding)
1263 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1264 unsigned int & column, OutputParams const & runparams)
1266 // FIXME: if we have "LaTeX" with a font
1267 // change in the middle (before the 'T', then
1268 // the "TeX" part is still special cased.
1269 // Really we should only operate this on
1270 // "words" for some definition of word
1272 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1273 if (!isTextAt(special_phrases[pnr].phrase, i))
1275 if (runparams.moving_arg)
1277 os << special_phrases[pnr].macro;
1278 i += special_phrases[pnr].phrase.length() - 1;
1279 column += special_phrases[pnr].macro.length() - 1;
1286 void Paragraph::Private::validate(LaTeXFeatures & features) const
1288 if (layout_->inpreamble && inset_owner_) {
1289 Buffer const & buf = inset_owner_->buffer();
1290 BufferParams const & bp = buf.params();
1293 odocstringstream ods;
1294 // we have to provide all the optional arguments here, even though
1295 // the last one is the only one we care about.
1296 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1297 docstring const d = ods.str();
1299 // this will have "{" at the beginning, but not at the end
1300 string const content = to_utf8(d);
1301 string const cmd = layout_->latexname();
1302 features.addPreambleSnippet("\\" + cmd + content + "}");
1306 if (features.runparams().flavor == OutputParams::HTML
1307 && layout_->htmltitle()) {
1308 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1311 // check the params.
1312 if (!params_.spacing().isDefault())
1313 features.require("setspace");
1316 features.useLayout(layout_->name());
1319 fontlist_.validate(features);
1321 // then the indentation
1322 if (!params_.leftIndent().zero())
1323 features.require("ParagraphLeftIndent");
1326 InsetList::const_iterator icit = insetlist_.begin();
1327 InsetList::const_iterator iend = insetlist_.end();
1328 for (; icit != iend; ++icit) {
1330 icit->inset->validate(features);
1331 if (layout_->needprotect &&
1332 icit->inset->lyxCode() == FOOT_CODE)
1333 features.require("NeedLyXFootnoteCode");
1337 // then the contents
1338 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1339 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1340 if (!special_phrases[pnr].builtin
1341 && isTextAt(special_phrases[pnr].phrase, i)) {
1342 features.require(special_phrases[pnr].phrase);
1346 Encodings::validate(text_[i], features);
1350 /////////////////////////////////////////////////////////////////////
1354 /////////////////////////////////////////////////////////////////////
1357 Layout const emptyParagraphLayout;
1360 Paragraph::Paragraph()
1361 : d(new Paragraph::Private(this, emptyParagraphLayout))
1368 Paragraph::Paragraph(Paragraph const & par)
1369 : itemdepth(par.itemdepth),
1370 d(new Paragraph::Private(*par.d, this))
1376 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1377 : itemdepth(par.itemdepth),
1378 d(new Paragraph::Private(*par.d, this, beg, end))
1384 Paragraph & Paragraph::operator=(Paragraph const & par)
1386 // needed as we will destroy the private part before copying it
1388 itemdepth = par.itemdepth;
1392 d = new Private(*par.d, this);
1399 Paragraph::~Paragraph()
1408 // this shall be called just before every "os << ..." action.
1409 void flushString(ostream & os, docstring & s)
1418 void Paragraph::write(ostream & os, BufferParams const & bparams,
1419 depth_type & dth) const
1421 // The beginning or end of a deeper (i.e. nested) area?
1422 if (dth != d->params_.depth()) {
1423 if (d->params_.depth() > dth) {
1424 while (d->params_.depth() > dth) {
1425 os << "\n\\begin_deeper";
1429 while (d->params_.depth() < dth) {
1430 os << "\n\\end_deeper";
1436 // First write the layout
1437 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1439 d->params_.write(os);
1441 Font font1(inherit_font, bparams.language);
1443 Change running_change = Change(Change::UNCHANGED);
1445 // this string is used as a buffer to avoid repetitive calls
1446 // to to_utf8(), which turn out to be expensive (JMarc)
1447 docstring write_buffer;
1450 for (pos_type i = 0; i <= size(); ++i) {
1452 Change const change = lookupChange(i);
1453 if (change != running_change)
1454 flushString(os, write_buffer);
1455 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1456 running_change = change;
1461 // Write font changes
1462 Font font2 = getFontSettings(bparams, i);
1463 if (font2 != font1) {
1464 flushString(os, write_buffer);
1465 font2.lyxWriteChanges(font1, os);
1470 char_type const c = d->text_[i];
1473 if (Inset const * inset = getInset(i)) {
1474 flushString(os, write_buffer);
1475 if (inset->directWrite()) {
1476 // international char, let it write
1477 // code directly so it's shorter in
1483 os << "\\begin_inset ";
1485 os << "\n\\end_inset\n\n";
1491 flushString(os, write_buffer);
1492 os << "\n\\backslash\n";
1496 flushString(os, write_buffer);
1497 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1504 if ((column > 70 && c == ' ')
1506 flushString(os, write_buffer);
1510 // this check is to amend a bug. LyX sometimes
1511 // inserts '\0' this could cause problems.
1513 write_buffer.push_back(c);
1515 LYXERR0("NUL char in structure.");
1521 flushString(os, write_buffer);
1522 os << "\n\\end_layout\n";
1526 void Paragraph::validate(LaTeXFeatures & features) const
1528 d->validate(features);
1532 void Paragraph::insert(pos_type start, docstring const & str,
1533 Font const & font, Change const & change)
1535 for (size_t i = 0, n = str.size(); i != n ; ++i)
1536 insertChar(start + i, str[i], font, change);
1540 void Paragraph::appendChar(char_type c, Font const & font,
1541 Change const & change)
1544 d->changes_.insert(change, d->text_.size());
1545 // when appending characters, no need to update tables
1546 d->text_.push_back(c);
1547 setFont(d->text_.size() - 1, font);
1551 void Paragraph::appendString(docstring const & s, Font const & font,
1552 Change const & change)
1554 pos_type end = s.size();
1555 size_t oldsize = d->text_.size();
1556 size_t newsize = oldsize + end;
1557 size_t capacity = d->text_.capacity();
1558 if (newsize >= capacity)
1559 d->text_.reserve(max(capacity + 100, newsize));
1561 // when appending characters, no need to update tables
1564 // FIXME: Optimize this!
1565 for (size_t i = oldsize; i != newsize; ++i) {
1567 d->changes_.insert(change, i);
1569 d->fontlist_.set(oldsize, font);
1570 d->fontlist_.set(newsize - 1, font);
1574 void Paragraph::insertChar(pos_type pos, char_type c,
1577 d->insertChar(pos, c, Change(trackChanges ?
1578 Change::INSERTED : Change::UNCHANGED));
1582 void Paragraph::insertChar(pos_type pos, char_type c,
1583 Font const & font, bool trackChanges)
1585 d->insertChar(pos, c, Change(trackChanges ?
1586 Change::INSERTED : Change::UNCHANGED));
1591 void Paragraph::insertChar(pos_type pos, char_type c,
1592 Font const & font, Change const & change)
1594 d->insertChar(pos, c, change);
1599 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1600 Font const & font, Change const & change)
1602 bool const success = insertInset(pos, inset, change);
1603 // Set the font/language of the inset...
1609 void Paragraph::resetFonts(Font const & font)
1611 d->fontlist_.clear();
1612 d->fontlist_.set(0, font);
1613 d->fontlist_.set(d->text_.size() - 1, font);
1616 // Gets uninstantiated font setting at position.
1617 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1621 LYXERR0("pos: " << pos << " size: " << size());
1622 LASSERT(pos <= size(), /**/);
1625 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1626 if (cit != d->fontlist_.end())
1629 if (pos == size() && !empty())
1630 return getFontSettings(bparams, pos - 1);
1632 // Optimisation: avoid a full font instantiation if there is no
1633 // language change from previous call.
1634 static Font previous_font;
1635 static Language const * previous_lang = 0;
1636 Language const * lang = getParLanguage(bparams);
1637 if (lang != previous_lang) {
1638 previous_lang = lang;
1639 previous_font = Font(inherit_font, lang);
1641 return previous_font;
1645 FontSpan Paragraph::fontSpan(pos_type pos) const
1647 LASSERT(pos <= size(), /**/);
1650 FontList::const_iterator cit = d->fontlist_.begin();
1651 FontList::const_iterator end = d->fontlist_.end();
1652 for (; cit != end; ++cit) {
1653 if (cit->pos() >= pos) {
1654 if (pos >= beginOfBody())
1655 return FontSpan(max(start, beginOfBody()),
1658 return FontSpan(start,
1659 min(beginOfBody() - 1,
1662 start = cit->pos() + 1;
1665 // This should not happen, but if so, we take no chances.
1666 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1667 return FontSpan(pos, pos);
1671 // Gets uninstantiated font setting at position 0
1672 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1674 if (!empty() && !d->fontlist_.empty())
1675 return d->fontlist_.begin()->font();
1677 // Optimisation: avoid a full font instantiation if there is no
1678 // language change from previous call.
1679 static Font previous_font;
1680 static Language const * previous_lang = 0;
1681 if (bparams.language != previous_lang) {
1682 previous_lang = bparams.language;
1683 previous_font = Font(inherit_font, bparams.language);
1686 return previous_font;
1690 // Gets the fully instantiated font at a given position in a paragraph
1691 // This is basically the same function as Text::GetFont() in text2.cpp.
1692 // The difference is that this one is used for generating the LaTeX file,
1693 // and thus cosmetic "improvements" are disallowed: This has to deliver
1694 // the true picture of the buffer. (Asger)
1695 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1696 Font const & outerfont) const
1698 LASSERT(pos >= 0, /**/);
1700 Font font = getFontSettings(bparams, pos);
1702 pos_type const body_pos = beginOfBody();
1703 FontInfo & fi = font.fontInfo();
1705 fi.realize(d->layout_->labelfont);
1707 fi.realize(d->layout_->font);
1709 fi.realize(outerfont.fontInfo());
1710 fi.realize(bparams.getFont().fontInfo());
1716 Font const Paragraph::getLabelFont
1717 (BufferParams const & bparams, Font const & outerfont) const
1719 FontInfo tmpfont = d->layout_->labelfont;
1720 tmpfont.realize(outerfont.fontInfo());
1721 tmpfont.realize(bparams.getFont().fontInfo());
1722 return Font(tmpfont, getParLanguage(bparams));
1726 Font const Paragraph::getLayoutFont
1727 (BufferParams const & bparams, Font const & outerfont) const
1729 FontInfo tmpfont = d->layout_->font;
1730 tmpfont.realize(outerfont.fontInfo());
1731 tmpfont.realize(bparams.getFont().fontInfo());
1732 return Font(tmpfont, getParLanguage(bparams));
1736 /// Returns the height of the highest font in range
1737 FontSize Paragraph::highestFontInRange
1738 (pos_type startpos, pos_type endpos, FontSize def_size) const
1740 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1744 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1746 char_type c = d->text_[pos];
1747 if (!lyxrc.rtl_support)
1777 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1783 void Paragraph::setFont(pos_type pos, Font const & font)
1785 LASSERT(pos <= size(), /**/);
1787 // First, reduce font against layout/label font
1788 // Update: The setCharFont() routine in text2.cpp already
1789 // reduces font, so we don't need to do that here. (Asger)
1791 d->fontlist_.set(pos, font);
1795 void Paragraph::makeSameLayout(Paragraph const & par)
1797 d->layout_ = par.d->layout_;
1798 d->params_ = par.d->params_;
1802 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1804 if (isFreeSpacing())
1810 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1811 if (eraseChar(pos, trackChanges))
1817 return count > 0 || pos > 0;
1821 bool Paragraph::hasSameLayout(Paragraph const & par) const
1823 return par.d->layout_ == d->layout_
1824 && d->params_.sameLayout(par.d->params_);
1828 depth_type Paragraph::getDepth() const
1830 return d->params_.depth();
1834 depth_type Paragraph::getMaxDepthAfter() const
1836 if (d->layout_->isEnvironment())
1837 return d->params_.depth() + 1;
1839 return d->params_.depth();
1843 char Paragraph::getAlign() const
1845 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1846 return d->layout_->align;
1848 return d->params_.align();
1852 docstring const & Paragraph::labelString() const
1854 return d->params_.labelString();
1858 // the next two functions are for the manual labels
1859 docstring const Paragraph::getLabelWidthString() const
1861 if (d->layout_->margintype == MARGIN_MANUAL
1862 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1863 return d->params_.labelWidthString();
1865 return _("Senseless with this layout!");
1869 void Paragraph::setLabelWidthString(docstring const & s)
1871 d->params_.labelWidthString(s);
1875 docstring Paragraph::expandLabel(Layout const & layout,
1876 BufferParams const & bparams) const
1878 return expandParagraphLabel(layout, bparams, true);
1882 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1883 BufferParams const & bparams) const
1885 return expandParagraphLabel(layout, bparams, false);
1889 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1890 BufferParams const & bparams, bool process_appendix) const
1892 DocumentClass const & tclass = bparams.documentClass();
1893 string const & lang = getParLanguage(bparams)->code();
1894 bool const in_appendix = process_appendix && d->params_.appendix();
1895 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1897 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1898 && !layout.counter.empty())
1899 return tclass.counters().theCounter(layout.counter, lang);
1901 // handle 'inherited level parts' in 'fmt',
1902 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1903 size_t const i = fmt.find('@', 0);
1904 if (i != docstring::npos) {
1905 size_t const j = fmt.find('@', i + 1);
1906 if (j != docstring::npos) {
1907 docstring parent(fmt, i + 1, j - i - 1);
1908 docstring label = from_ascii("??");
1909 if (tclass.hasLayout(parent))
1910 docstring label = expandParagraphLabel(tclass[parent], bparams,
1912 fmt = docstring(fmt, 0, i) + label
1913 + docstring(fmt, j + 1, docstring::npos);
1917 return tclass.counters().counterLabel(fmt, lang);
1921 void Paragraph::applyLayout(Layout const & new_layout)
1923 d->layout_ = &new_layout;
1924 LyXAlignment const oldAlign = d->params_.align();
1926 if (!(oldAlign & d->layout_->alignpossible)) {
1927 frontend::Alert::warning(_("Alignment not permitted"),
1928 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1929 d->params_.align(LYX_ALIGN_LAYOUT);
1934 pos_type Paragraph::beginOfBody() const
1936 return d->begin_of_body_;
1940 void Paragraph::setBeginOfBody()
1942 if (d->layout_->labeltype != LABEL_MANUAL) {
1943 d->begin_of_body_ = 0;
1947 // Unroll the first two cycles of the loop
1948 // and remember the previous character to
1949 // remove unnecessary getChar() calls
1951 pos_type end = size();
1952 if (i < end && !isNewline(i)) {
1954 char_type previous_char = 0;
1957 previous_char = d->text_[i];
1958 if (!isNewline(i)) {
1960 while (i < end && previous_char != ' ') {
1965 previous_char = temp;
1971 d->begin_of_body_ = i;
1975 bool Paragraph::allowParagraphCustomization() const
1977 return inInset().allowParagraphCustomization();
1981 bool Paragraph::usePlainLayout() const
1983 return inInset().usePlainLayout();
1989 // paragraphs inside floats need different alignment tags to avoid
1992 bool noTrivlistCentering(InsetCode code)
1994 return code == FLOAT_CODE
1995 || code == WRAP_CODE
1996 || code == CELL_CODE;
2000 string correction(string const & orig)
2002 if (orig == "flushleft")
2003 return "raggedright";
2004 if (orig == "flushright")
2005 return "raggedleft";
2006 if (orig == "center")
2012 string const corrected_env(string const & suffix, string const & env,
2013 InsetCode code, bool const lastpar)
2015 string output = suffix + "{";
2016 if (noTrivlistCentering(code)) {
2018 // the last paragraph in non-trivlist-aligned
2019 // context is special (to avoid unwanted whitespace)
2020 if (suffix == "\\begin")
2021 return "\\" + correction(env) + "{}";
2024 output += correction(env);
2028 if (suffix == "\\begin")
2034 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2036 if (!contains(str, "\n"))
2037 column += str.size();
2041 column = rsplit(str, tmp, '\n').size();
2048 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2049 odocstream & os, TexRow & texrow,
2050 OutputParams const & runparams) const
2054 if (params_.noindent()) {
2055 os << "\\noindent ";
2059 LyXAlignment const curAlign = params_.align();
2061 if (curAlign == layout_->align)
2065 case LYX_ALIGN_NONE:
2066 case LYX_ALIGN_BLOCK:
2067 case LYX_ALIGN_LAYOUT:
2068 case LYX_ALIGN_SPECIAL:
2069 case LYX_ALIGN_DECIMAL:
2071 case LYX_ALIGN_LEFT:
2072 case LYX_ALIGN_RIGHT:
2073 case LYX_ALIGN_CENTER:
2074 if (runparams.moving_arg) {
2081 string const begin_tag = "\\begin";
2082 InsetCode code = ownerCode();
2083 bool const lastpar = runparams.isLastPar;
2086 case LYX_ALIGN_NONE:
2087 case LYX_ALIGN_BLOCK:
2088 case LYX_ALIGN_LAYOUT:
2089 case LYX_ALIGN_SPECIAL:
2090 case LYX_ALIGN_DECIMAL:
2092 case LYX_ALIGN_LEFT: {
2094 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2095 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2097 output = corrected_env(begin_tag, "flushright", code, lastpar);
2098 os << from_ascii(output);
2099 adjust_row_column(output, texrow, column);
2101 } case LYX_ALIGN_RIGHT: {
2103 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2104 output = corrected_env(begin_tag, "flushright", code, lastpar);
2106 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2107 os << from_ascii(output);
2108 adjust_row_column(output, texrow, column);
2110 } case LYX_ALIGN_CENTER: {
2112 output = corrected_env(begin_tag, "center", code, lastpar);
2113 os << from_ascii(output);
2114 adjust_row_column(output, texrow, column);
2123 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2124 odocstream & os, TexRow & texrow,
2125 OutputParams const & runparams) const
2129 LyXAlignment const curAlign = params_.align();
2131 if (curAlign == layout_->align)
2135 case LYX_ALIGN_NONE:
2136 case LYX_ALIGN_BLOCK:
2137 case LYX_ALIGN_LAYOUT:
2138 case LYX_ALIGN_SPECIAL:
2139 case LYX_ALIGN_DECIMAL:
2141 case LYX_ALIGN_LEFT:
2142 case LYX_ALIGN_RIGHT:
2143 case LYX_ALIGN_CENTER:
2144 if (runparams.moving_arg) {
2151 string const end_tag = "\n\\par\\end";
2152 InsetCode code = ownerCode();
2153 bool const lastpar = runparams.isLastPar;
2156 case LYX_ALIGN_NONE:
2157 case LYX_ALIGN_BLOCK:
2158 case LYX_ALIGN_LAYOUT:
2159 case LYX_ALIGN_SPECIAL:
2160 case LYX_ALIGN_DECIMAL:
2162 case LYX_ALIGN_LEFT: {
2164 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2165 output = corrected_env(end_tag, "flushleft", code, lastpar);
2167 output = corrected_env(end_tag, "flushright", code, lastpar);
2168 os << from_ascii(output);
2169 adjust_row_column(output, texrow, column);
2171 } case LYX_ALIGN_RIGHT: {
2173 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2174 output = corrected_env(end_tag, "flushright", code, lastpar);
2176 output = corrected_env(end_tag, "flushleft", code, lastpar);
2177 os << from_ascii(output);
2178 adjust_row_column(output, texrow, column);
2180 } case LYX_ALIGN_CENTER: {
2182 output = corrected_env(end_tag, "center", code, lastpar);
2183 os << from_ascii(output);
2184 adjust_row_column(output, texrow, column);
2193 // This one spits out the text of the paragraph
2194 void Paragraph::latex(BufferParams const & bparams,
2195 Font const & outerfont,
2196 odocstream & os, TexRow & texrow,
2197 OutputParams const & runparams,
2198 int start_pos, int end_pos, bool force) const
2200 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2202 // FIXME This check should not be needed. Perhaps issue an
2203 // error if it triggers.
2204 Layout const & style = inInset().forcePlainLayout() ?
2205 bparams.documentClass().plainLayout() : *d->layout_;
2207 if (!force && style.inpreamble)
2210 bool const allowcust = allowParagraphCustomization();
2212 // Current base font for all inherited font changes, without any
2213 // change caused by an individual character, except for the language:
2214 // It is set to the language of the first character.
2215 // As long as we are in the label, this font is the base font of the
2216 // label. Before the first body character it is set to the base font
2220 // Maybe we have to create a optional argument.
2221 pos_type body_pos = beginOfBody();
2222 unsigned int column = 0;
2225 // the optional argument is kept in curly brackets in
2226 // case it contains a ']'
2229 basefont = getLabelFont(bparams, outerfont);
2231 basefont = getLayoutFont(bparams, outerfont);
2234 // Which font is currently active?
2235 Font running_font(basefont);
2236 // Do we have an open font change?
2237 bool open_font = false;
2239 Change runningChange = Change(Change::UNCHANGED);
2241 Encoding const * const prev_encoding = runparams.encoding;
2243 texrow.start(id(), 0);
2245 // if the paragraph is empty, the loop will not be entered at all
2247 if (style.isCommand()) {
2252 column += d->startTeXParParams(bparams, os, texrow,
2256 for (pos_type i = 0; i < size(); ++i) {
2257 // First char in paragraph or after label?
2258 if (i == body_pos) {
2261 column += running_font.latexWriteEndChanges(
2262 os, bparams, runparams,
2263 basefont, basefont);
2266 basefont = getLayoutFont(bparams, outerfont);
2267 running_font = basefont;
2269 column += Changes::latexMarkChange(os, bparams,
2270 runningChange, Change(Change::UNCHANGED),
2272 runningChange = Change(Change::UNCHANGED);
2277 if (style.isCommand()) {
2283 column += d->startTeXParParams(bparams, os,
2288 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2291 if (bparams.outputChanges && runningChange != change) {
2293 column += running_font.latexWriteEndChanges(
2294 os, bparams, runparams, basefont, basefont);
2297 basefont = getLayoutFont(bparams, outerfont);
2298 running_font = basefont;
2300 column += Changes::latexMarkChange(os, bparams, runningChange,
2302 runningChange = change;
2305 // do not output text which is marked deleted
2306 // if change tracking output is disabled
2307 if (!bparams.outputChanges && change.deleted()) {
2313 // Fully instantiated font
2314 Font const font = getFont(bparams, i, outerfont);
2316 Font const last_font = running_font;
2318 // Do we need to close the previous font?
2320 (font != running_font ||
2321 font.language() != running_font.language()))
2323 column += running_font.latexWriteEndChanges(
2324 os, bparams, runparams, basefont,
2325 (i == body_pos-1) ? basefont : font);
2326 running_font = basefont;
2330 // close babel's font environment before opening CJK.
2331 if (!running_font.language()->babel().empty() &&
2332 font.language()->encoding()->package() == Encoding::CJK) {
2333 string end_tag = subst(lyxrc.language_command_end,
2335 running_font.language()->babel());
2336 os << from_ascii(end_tag);
2337 column += end_tag.length();
2340 // Switch file encoding if necessary (and allowed)
2341 if (!runparams.pass_thru && !style.pass_thru &&
2342 runparams.encoding->package() != Encoding::none &&
2343 font.language()->encoding()->package() != Encoding::none) {
2344 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2345 runparams, *(font.language()->encoding()));
2346 if (enc_switch.first) {
2347 column += enc_switch.second;
2348 runparams.encoding = font.language()->encoding();
2352 char_type const c = d->text_[i];
2354 // Do we need to change font?
2355 if ((font != running_font ||
2356 font.language() != running_font.language()) &&
2359 odocstringstream ods;
2360 column += font.latexWriteStartChanges(ods, bparams,
2361 runparams, basefont,
2363 running_font = font;
2365 docstring fontchange = ods.str();
2366 // check whether the fontchange ends with a \\textcolor
2367 // modifier and the text starts with a space (bug 4473)
2368 docstring const last_modifier = rsplit(fontchange, '\\');
2369 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2370 os << fontchange << from_ascii("{}");
2371 // check if the fontchange ends with a trailing blank
2372 // (like "\small " (see bug 3382)
2373 else if (suffixIs(fontchange, ' ') && c == ' ')
2374 os << fontchange.substr(0, fontchange.size() - 1)
2375 << from_ascii("{}");
2380 // FIXME: think about end_pos implementation...
2381 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2382 // FIXME: integrate this case in latexSpecialChar
2383 // Do not print the separation of the optional argument
2384 // if style.pass_thru is false. This works because
2385 // latexSpecialChar ignores spaces if
2386 // style.pass_thru is false.
2387 if (i != body_pos - 1) {
2388 if (d->simpleTeXBlanks(
2389 runparams, os, texrow,
2390 i, column, font, style)) {
2391 // A surrogate pair was output. We
2392 // must not call latexSpecialChar
2393 // in this iteration, since it would output
2394 // the combining character again.
2401 OutputParams rp = runparams;
2402 rp.free_spacing = style.free_spacing;
2403 rp.local_font = &font;
2404 rp.intitle = style.intitle;
2406 // Two major modes: LaTeX or plain
2407 // Handle here those cases common to both modes
2408 // and then split to handle the two modes separately.
2409 if (c == META_INSET) {
2410 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2411 d->latexInset(bparams, os,
2412 texrow, rp, running_font,
2413 basefont, outerfont, open_font,
2414 runningChange, style, i, column);
2417 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2419 d->latexSpecialChar(os, rp, running_font, runningChange,
2421 } catch (EncodingException & e) {
2422 if (runparams.dryrun) {
2423 os << "<" << _("LyX Warning: ")
2424 << _("uncodable character") << " '";
2428 // add location information and throw again.
2437 // Set the encoding to that returned from latexSpecialChar (see
2438 // comment for encoding member in OutputParams.h)
2439 runparams.encoding = rp.encoding;
2442 // If we have an open font definition, we have to close it
2444 #ifdef FIXED_LANGUAGE_END_DETECTION
2446 running_font.latexWriteEndChanges(os, bparams,
2447 runparams, basefont,
2448 next_->getFont(bparams, 0, outerfont));
2450 running_font.latexWriteEndChanges(os, bparams,
2451 runparams, basefont, basefont);
2454 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2455 //FIXME: there as we start another \selectlanguage with the next paragraph if
2456 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2457 running_font.latexWriteEndChanges(os, bparams, runparams,
2458 basefont, basefont);
2462 column += Changes::latexMarkChange(os, bparams, runningChange,
2463 Change(Change::UNCHANGED), runparams);
2465 // Needed if there is an optional argument but no contents.
2466 if (body_pos > 0 && body_pos == size()) {
2470 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2471 && runparams.encoding != prev_encoding) {
2472 runparams.encoding = prev_encoding;
2473 if (!bparams.useXetex)
2474 os << setEncoding(prev_encoding->iconvName());
2477 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2481 bool Paragraph::emptyTag() const
2483 for (pos_type i = 0; i < size(); ++i) {
2484 if (Inset const * inset = getInset(i)) {
2485 InsetCode lyx_code = inset->lyxCode();
2486 // FIXME testing like that is wrong. What is
2488 if (lyx_code != TOC_CODE &&
2489 lyx_code != INCLUDE_CODE &&
2490 lyx_code != GRAPHICS_CODE &&
2491 lyx_code != ERT_CODE &&
2492 lyx_code != LISTINGS_CODE &&
2493 lyx_code != FLOAT_CODE &&
2494 lyx_code != TABULAR_CODE) {
2498 char_type c = d->text_[i];
2499 if (c != ' ' && c != '\t')
2507 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2510 for (pos_type i = 0; i < size(); ++i) {
2511 if (Inset const * inset = getInset(i)) {
2512 InsetCode lyx_code = inset->lyxCode();
2513 if (lyx_code == LABEL_CODE) {
2514 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2515 docstring const & id = il->getParam("name");
2516 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2524 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2528 for (i = 0; i < size(); ++i) {
2529 if (Inset const * inset = getInset(i)) {
2530 inset->docbook(os, runparams);
2532 char_type c = d->text_[i];
2535 os << sgml::escapeChar(c);
2542 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2546 for (i = 0; i < size(); ++i) {
2547 if (Inset const * inset = getInset(i)) {
2548 inset->xhtml(xs, runparams);
2550 char_type c = d->text_[i];
2560 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2563 pos_type size = text_.size();
2564 for (pos_type i = initial; i < size; ++i) {
2565 Font font = owner_->getFont(buf.params(), i, outerfont);
2566 if (text_[i] == META_INSET)
2568 if (i != initial && font != font_old)
2577 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2579 OutputParams const & runparams,
2580 Font const & outerfont,
2581 pos_type initial) const
2583 bool emph_flag = false;
2585 Layout const & style = *d->layout_;
2587 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2589 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2592 // parsing main loop
2593 for (pos_type i = initial; i < size(); ++i) {
2594 Font font = getFont(buf.params(), i, outerfont);
2596 // handle <emphasis> tag
2597 if (font_old.emph() != font.fontInfo().emph()) {
2598 if (font.fontInfo().emph() == FONT_ON) {
2601 } else if (i != initial) {
2602 os << "</emphasis>";
2607 if (Inset const * inset = getInset(i)) {
2608 inset->docbook(os, runparams);
2610 char_type c = d->text_[i];
2612 if (style.pass_thru)
2615 os << sgml::escapeChar(c);
2617 font_old = font.fontInfo();
2621 os << "</emphasis>";
2624 if (style.free_spacing)
2626 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2631 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2633 OutputParams const & runparams,
2634 Font const & outerfont,
2635 pos_type initial) const
2639 bool emph_flag = false;
2640 bool bold_flag = false;
2643 Layout const & style = *d->layout_;
2645 if (!runparams.for_toc && runparams.html_make_pars) {
2646 // generate a magic label for this paragraph
2647 string const attr = "id='" + magicLabel() + "'";
2648 xs << html::CompTag("a", attr);
2652 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2654 // parsing main loop
2655 for (pos_type i = initial; i < size(); ++i) {
2656 // let's not show deleted material in the output
2660 Font font = getFont(buf.params(), i, outerfont);
2663 if (font_old.emph() != font.fontInfo().emph()) {
2664 if (font.fontInfo().emph() == FONT_ON) {
2665 xs << html::StartTag("em");
2667 } else if (emph_flag && i != initial) {
2668 xs << html::EndTag("em");
2673 if (font_old.series() != font.fontInfo().series()) {
2674 if (font.fontInfo().series() == BOLD_SERIES) {
2675 xs << html::StartTag("strong");
2677 } else if (bold_flag && i != initial) {
2678 xs << html::EndTag("strong");
2683 // Other such tags? What about the other text ranges?
2685 Inset const * inset = getInset(i);
2687 InsetCommand const * ic = inset->asInsetCommand();
2688 InsetLayout const & il = inset->getLayout();
2689 InsetMath const * im = inset->asInsetMath();
2690 if (!runparams.for_toc
2691 || im || il.isInToc() || (ic && ic->isInToc())) {
2692 OutputParams np = runparams;
2693 if (!il.htmlisblock())
2694 np.html_in_par = true;
2695 retval += inset->xhtml(xs, np);
2698 char_type c = d->text_[i];
2700 if (style.pass_thru)
2702 else if (c == '-') {
2705 if (j < size() && d->text_[j] == '-') {
2707 if (j < size() && d->text_[j] == '-') {
2708 str += from_ascii("—");
2711 str += from_ascii("–");
2717 // We don't want to escape the entities. Note that
2718 // it is safe to do this, since str can otherwise
2719 // only be "-". E.g., it can't be "<".
2720 xs << XHTMLStream::NextRaw() << str;
2724 font_old = font.fontInfo();
2732 bool Paragraph::isHfill(pos_type pos) const
2734 Inset const * inset = getInset(pos);
2735 return inset && (inset->lyxCode() == SPACE_CODE &&
2736 inset->isStretchableSpace());
2740 bool Paragraph::isNewline(pos_type pos) const
2742 Inset const * inset = getInset(pos);
2743 return inset && inset->lyxCode() == NEWLINE_CODE;
2747 bool Paragraph::isLineSeparator(pos_type pos) const
2749 char_type const c = d->text_[pos];
2750 if (isLineSeparatorChar(c))
2752 Inset const * inset = getInset(pos);
2753 return inset && inset->isLineSeparator();
2757 bool Paragraph::isWordSeparator(pos_type pos) const
2759 if (Inset const * inset = getInset(pos))
2760 return !inset->isLetter();
2761 char_type const c = d->text_[pos];
2762 // We want to pass the ' and escape chars to the spellchecker
2763 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2764 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2769 bool Paragraph::isChar(pos_type pos) const
2771 if (Inset const * inset = getInset(pos))
2772 return inset->isChar();
2773 char_type const c = d->text_[pos];
2774 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2778 bool Paragraph::isSpace(pos_type pos) const
2780 if (Inset const * inset = getInset(pos))
2781 return inset->isSpace();
2782 char_type const c = d->text_[pos];
2783 return lyx::isSpace(c);
2788 Paragraph::getParLanguage(BufferParams const & bparams) const
2791 return getFirstFontSettings(bparams).language();
2792 // FIXME: we should check the prev par as well (Lgb)
2793 return bparams.language;
2797 bool Paragraph::isRTL(BufferParams const & bparams) const
2799 return lyxrc.rtl_support
2800 && getParLanguage(bparams)->rightToLeft()
2801 && !inInset().getLayout().forceLTR();
2805 void Paragraph::changeLanguage(BufferParams const & bparams,
2806 Language const * from, Language const * to)
2808 // change language including dummy font change at the end
2809 for (pos_type i = 0; i <= size(); ++i) {
2810 Font font = getFontSettings(bparams, i);
2811 if (font.language() == from) {
2812 font.setLanguage(to);
2816 d->requestSpellCheck(size());
2820 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2822 Language const * doc_language = bparams.language;
2823 FontList::const_iterator cit = d->fontlist_.begin();
2824 FontList::const_iterator end = d->fontlist_.end();
2826 for (; cit != end; ++cit)
2827 if (cit->font().language() != ignore_language &&
2828 cit->font().language() != latex_language &&
2829 cit->font().language() != doc_language)
2835 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2837 FontList::const_iterator cit = d->fontlist_.begin();
2838 FontList::const_iterator end = d->fontlist_.end();
2840 for (; cit != end; ++cit) {
2841 Language const * lang = cit->font().language();
2842 if (lang != ignore_language &&
2843 lang != latex_language)
2844 languages.insert(lang);
2849 docstring Paragraph::asString(int options) const
2851 return asString(0, size(), options);
2855 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2857 odocstringstream os;
2860 && options & AS_STR_LABEL
2861 && !d->params_.labelString().empty())
2862 os << d->params_.labelString() << ' ';
2864 for (pos_type i = beg; i < end; ++i) {
2865 char_type const c = d->text_[i];
2866 if (isPrintable(c) || c == '\t'
2867 || (c == '\n' && (options & AS_STR_NEWLINES)))
2869 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2870 getInset(i)->tocString(os);
2871 if (getInset(i)->asInsetMath())
2880 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2882 odocstringstream os;
2885 && options & AS_STR_LABEL
2886 && !d->params_.labelString().empty())
2887 os << d->params_.labelString() << ' ';
2889 for (pos_type i = beg; i < end; ++i) {
2890 char_type const c = d->text_[i];
2891 if (isPrintable(c) || c == '\t'
2892 || (c == '\n' && (options & AS_STR_NEWLINES)))
2894 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2895 getInset(i)->plaintext(os, runparams);
2903 void Paragraph::setInsetOwner(Inset const * inset)
2905 d->inset_owner_ = inset;
2909 int Paragraph::id() const
2915 void Paragraph::setId(int id)
2921 Layout const & Paragraph::layout() const
2927 void Paragraph::setLayout(Layout const & layout)
2929 d->layout_ = &layout;
2933 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2935 setLayout(tc.defaultLayout());
2939 void Paragraph::setPlainLayout(DocumentClass const & tc)
2941 setLayout(tc.plainLayout());
2945 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
2947 if (usePlainLayout())
2948 setPlainLayout(tclass);
2950 setDefaultLayout(tclass);
2954 Inset const & Paragraph::inInset() const
2956 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
2957 _("Memory problem"), _("Paragraph not properly initialized")));
2958 return *d->inset_owner_;
2962 ParagraphParameters & Paragraph::params()
2968 ParagraphParameters const & Paragraph::params() const
2974 bool Paragraph::isFreeSpacing() const
2976 if (d->layout_->free_spacing)
2978 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
2982 bool Paragraph::allowEmpty() const
2984 if (d->layout_->keepempty)
2986 return d->inset_owner_ && d->inset_owner_->allowEmpty();
2990 char_type Paragraph::transformChar(char_type c, pos_type pos) const
2992 if (!Encodings::isArabicChar(c))
2995 char_type prev_char = ' ';
2996 char_type next_char = ' ';
2998 for (pos_type i = pos - 1; i >= 0; --i) {
2999 char_type const par_char = d->text_[i];
3000 if (!Encodings::isArabicComposeChar(par_char)) {
3001 prev_char = par_char;
3006 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3007 char_type const par_char = d->text_[i];
3008 if (!Encodings::isArabicComposeChar(par_char)) {
3009 next_char = par_char;
3014 if (Encodings::isArabicChar(next_char)) {
3015 if (Encodings::isArabicChar(prev_char) &&
3016 !Encodings::isArabicSpecialChar(prev_char))
3017 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3019 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3021 if (Encodings::isArabicChar(prev_char) &&
3022 !Encodings::isArabicSpecialChar(prev_char))
3023 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3025 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3030 int Paragraph::checkBiblio(Buffer const & buffer)
3033 // This is getting more and more a mess. ...We really should clean
3034 // up this bibitem issue for 1.6. See also bug 2743.
3036 // Add bibitem insets if necessary
3037 if (d->layout_->labeltype != LABEL_BIBLIO)
3040 bool hasbibitem = !d->insetlist_.empty()
3041 // Insist on it being in pos 0
3042 && d->text_[0] == META_INSET
3043 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3045 bool track_changes = buffer.params().trackChanges;
3050 // remove a bibitem in pos != 0
3051 // restore it later in pos 0 if necessary
3052 // (e.g. if a user inserts contents _before_ the item)
3053 // we're assuming there's only one of these, which there
3055 int erasedInsetPosition = -1;
3056 InsetList::iterator it = d->insetlist_.begin();
3057 InsetList::iterator end = d->insetlist_.end();
3058 for (; it != end; ++it)
3059 if (it->inset->lyxCode() == BIBITEM_CODE
3061 InsetBibitem * olditem = static_cast<InsetBibitem *>(it->inset);
3062 oldkey = olditem->getParam("key");
3063 oldlabel = olditem->getParam("label");
3064 erasedInsetPosition = it->pos;
3065 eraseChar(erasedInsetPosition, track_changes);
3069 // There was an InsetBibitem at the beginning, and we didn't
3070 // have to erase one.
3071 if (hasbibitem && erasedInsetPosition < 0)
3074 // There was an InsetBibitem at the beginning and we did have to
3075 // erase one. So we give its properties to the beginning inset.
3077 InsetBibitem * inset =
3078 static_cast<InsetBibitem *>(d->insetlist_.begin()->inset);
3079 if (!oldkey.empty())
3080 inset->setParam("key", oldkey);
3081 inset->setParam("label", oldlabel);
3082 return -erasedInsetPosition;
3085 // There was no inset at the beginning, so we need to create one with
3086 // the key and label of the one we erased.
3087 InsetBibitem * inset =
3088 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3089 // restore values of previously deleted item in this par.
3090 if (!oldkey.empty())
3091 inset->setParam("key", oldkey);
3092 inset->setParam("label", oldlabel);
3093 insertInset(0, static_cast<Inset *>(inset),
3094 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3100 void Paragraph::checkAuthors(AuthorList const & authorList)
3102 d->changes_.checkAuthors(authorList);
3106 bool Paragraph::isChanged(pos_type pos) const
3108 return lookupChange(pos).changed();
3112 bool Paragraph::isInserted(pos_type pos) const
3114 return lookupChange(pos).inserted();
3118 bool Paragraph::isDeleted(pos_type pos) const
3120 return lookupChange(pos).deleted();
3124 InsetList const & Paragraph::insetList() const
3126 return d->insetlist_;
3130 void Paragraph::setBuffer(Buffer & b)
3132 d->insetlist_.setBuffer(b);
3136 Inset * Paragraph::releaseInset(pos_type pos)
3138 Inset * inset = d->insetlist_.release(pos);
3139 /// does not honour change tracking!
3140 eraseChar(pos, false);
3145 Inset * Paragraph::getInset(pos_type pos)
3147 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3148 ? d->insetlist_.get(pos) : 0;
3152 Inset const * Paragraph::getInset(pos_type pos) const
3154 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3155 ? d->insetlist_.get(pos) : 0;
3159 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3160 pos_type & right, TextCase action)
3162 // process sequences of modified characters; in change
3163 // tracking mode, this approach results in much better
3164 // usability than changing case on a char-by-char basis
3167 bool const trackChanges = bparams.trackChanges;
3169 bool capitalize = true;
3171 for (; pos < right; ++pos) {
3172 char_type oldChar = d->text_[pos];
3173 char_type newChar = oldChar;
3175 // ignore insets and don't play with deleted text!
3176 if (oldChar != META_INSET && !isDeleted(pos)) {
3178 case text_lowercase:
3179 newChar = lowercase(oldChar);
3181 case text_capitalization:
3183 newChar = uppercase(oldChar);
3187 case text_uppercase:
3188 newChar = uppercase(oldChar);
3193 if (isWordSeparator(pos) || isDeleted(pos)) {
3194 // permit capitalization again
3198 if (oldChar != newChar) {
3200 if (pos != right - 1)
3202 // step behind the changing area
3206 int erasePos = pos - changes.size();
3207 for (size_t i = 0; i < changes.size(); i++) {
3208 insertChar(pos, changes[i],
3209 getFontSettings(bparams,
3212 if (!eraseChar(erasePos, trackChanges)) {
3215 ++right; // expand selection
3223 bool Paragraph::find(docstring const & str, bool cs, bool mw,
3224 pos_type pos, bool del) const
3226 int const strsize = str.length();
3228 pos_type const parsize = d->text_.size();
3229 for (i = 0; pos + i < parsize; ++i) {
3232 if (cs && str[i] != d->text_[pos + i])
3234 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos + i]))
3236 if (!del && isDeleted(pos + i))
3243 // if necessary, check whether string matches word
3245 if (pos > 0 && !isWordSeparator(pos - 1))
3247 if (pos + strsize < parsize
3248 && !isWordSeparator(pos + strsize))
3256 char_type Paragraph::getChar(pos_type pos) const
3258 return d->text_[pos];
3262 pos_type Paragraph::size() const
3264 return d->text_.size();
3268 bool Paragraph::empty() const
3270 return d->text_.empty();
3274 bool Paragraph::isInset(pos_type pos) const
3276 return d->text_[pos] == META_INSET;
3280 bool Paragraph::isSeparator(pos_type pos) const
3282 //FIXME: Are we sure this can be the only separator?
3283 return d->text_[pos] == ' ';
3287 void Paragraph::deregisterWords()
3289 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3290 Private::LangWordsMap::const_iterator ite = d->words_.end();
3291 for (; itl != ite; ++itl) {
3292 WordList * wl = theWordList(itl->first);
3293 Private::Words::const_iterator it = (itl->second).begin();
3294 Private::Words::const_iterator et = (itl->second).end();
3295 for (; it != et; ++it)
3302 void Paragraph::locateWord(pos_type & from, pos_type & to,
3303 word_location const loc) const
3306 case WHOLE_WORD_STRICT:
3307 if (from == 0 || from == size()
3308 || isWordSeparator(from)
3309 || isWordSeparator(from - 1)) {
3313 // no break here, we go to the next
3316 // If we are already at the beginning of a word, do nothing
3317 if (!from || isWordSeparator(from - 1))
3319 // no break here, we go to the next
3322 // always move the cursor to the beginning of previous word
3323 while (from && !isWordSeparator(from - 1))
3327 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3330 // no need to move the 'from' cursor
3334 while (to < size() && !isWordSeparator(to))
3339 void Paragraph::collectWords()
3341 // This is the value that needs to be exposed in the preferences
3342 // to resolve bug #6760.
3343 static int minlength = 6;
3344 pos_type n = size();
3345 for (pos_type pos = 0; pos < n; ++pos) {
3346 if (isWordSeparator(pos))
3348 pos_type from = pos;
3349 locateWord(from, pos, WHOLE_WORD);
3350 if (pos - from >= minlength) {
3351 docstring word = asString(from, pos, AS_STR_NONE);
3352 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3353 if (cit == d->fontlist_.end())
3355 Language const * lang = cit->font().language();
3356 d->words_[*lang].insert(word);
3362 void Paragraph::registerWords()
3364 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3365 Private::LangWordsMap::const_iterator ite = d->words_.end();
3366 for (; itl != ite; ++itl) {
3367 WordList * wl = theWordList(itl->first);
3368 Private::Words::const_iterator it = (itl->second).begin();
3369 Private::Words::const_iterator et = (itl->second).end();
3370 for (; it != et; ++it)
3376 void Paragraph::updateWords()
3384 Language * Paragraph::Private::locateSpellRange(
3385 pos_type & from, pos_type & to,
3386 Positions & softbreaks) const
3388 // skip leading white space
3389 while (from < to && owner_->isWordSeparator(from))
3391 // don't check empty range
3394 // get current language
3395 Language * lang = getSpellLanguage(from);
3396 pos_type last = from;
3397 bool samelang = true;
3398 bool sameinset = true;
3399 while (last < to && samelang && sameinset) {
3400 // hop to end of word
3401 while (last < to && !owner_->isWordSeparator(last)) {
3402 if (owner_->getInset(last)) {
3403 softbreaks.insert(softbreaks.end(), last);
3407 // hop to next word while checking for insets
3408 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3409 if (Inset const * inset = owner_->getInset(last))
3410 sameinset = inset->isChar() && inset->isLetter();
3414 if (sameinset && last < to) {
3415 // now check for language change
3416 samelang = lang == getSpellLanguage(last);
3419 // if language change detected backstep is needed
3427 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3430 const_cast<Language *>(owner_->getFontSettings(
3431 inset_owner_->buffer().params(), from).language());
3432 if (lang == inset_owner_->buffer().params().language
3433 && !lyxrc.spellchecker_alt_lang.empty()) {
3435 string const lang_variety =
3436 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3437 lang->setCode(lang_code);
3438 lang->setVariety(lang_variety);
3444 void Paragraph::requestSpellCheck(pos_type pos)
3446 d->requestSpellCheck(pos == -1 ? size() : pos);
3450 bool Paragraph::needsSpellCheck() const
3452 SpellChecker::ChangeNumber speller_change_number = 0;
3453 if (theSpellChecker())
3454 speller_change_number = theSpellChecker()->changeNumber();
3455 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3456 d->speller_state_.needsCompleteRefresh(speller_change_number);
3458 return d->needsSpellCheck();
3462 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3463 WordLangTuple & wl, docstring_list & suggestions,
3464 bool do_suggestion, bool check_learned) const
3466 SpellChecker::Result result = SpellChecker::WORD_OK;
3467 SpellChecker * speller = theSpellChecker();
3471 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3474 locateWord(from, to, WHOLE_WORD);
3475 if (from == to || from >= pos_type(d->text_.size()))
3478 docstring word = asString(from, to, AS_STR_INSETS);
3479 Language * lang = d->getSpellLanguage(from);
3481 wl = WordLangTuple(word, lang);
3486 if (needsSpellCheck() || check_learned) {
3487 // Ignore words with digits
3488 // FIXME: make this customizable
3489 // (note that some checkers ignore words with digits by default)
3490 if (!hasDigit(word))
3491 result = speller->check(wl);
3492 d->setMisspelled(from, to, result);
3494 result = d->speller_state_.getState(from);
3497 bool const misspelled_ = SpellChecker::misspelled(result) ;
3498 if (misspelled_ && do_suggestion)
3499 speller->suggest(wl, suggestions);
3500 else if (misspelled_)
3501 LYXERR(Debug::GUI, "misspelled word: \"" <<
3503 from << ".." << to << "]");
3505 suggestions.clear();
3511 void Paragraph::Private::markMisspelledWords(
3512 pos_type const & first, pos_type const & last,
3513 SpellChecker::Result result,
3514 docstring const & word,
3515 Positions const & softbreaks)
3517 if (!SpellChecker::misspelled(result)) {
3518 setMisspelled(first, last, SpellChecker::WORD_OK);
3521 pos_type snext = first;
3522 SpellChecker * speller = theSpellChecker();
3523 // locate and enumerate the error positions
3524 int nerrors = speller->numMisspelledWords();
3526 PositionsIterator it = softbreaks.begin();
3527 PositionsIterator et = softbreaks.end();
3528 for (int index = 0; index < nerrors; ++index) {
3531 speller->misspelledWord(index, wstart, wlen);
3532 /// should not happen if speller supports range checks
3533 if (!wlen) continue;
3534 docstring const misspelled = word.substr(wstart, wlen);
3535 wstart += first + numbreaks;
3536 if (snext < wstart) {
3537 /// mark the range of correct spelling
3538 numbreaks += countSoftbreaks(it, et, wstart);
3539 setMisspelled(snext,
3540 wstart - 1, SpellChecker::WORD_OK);
3542 snext = wstart + wlen;
3543 numbreaks += countSoftbreaks(it, et, snext);
3544 /// mark the range of misspelling
3545 setMisspelled(wstart, snext, result);
3546 LYXERR(Debug::GUI, "misspelled word: \"" <<
3547 misspelled << "\" [" <<
3548 wstart << ".." << (snext-1) << "]");
3551 if (snext <= last) {
3552 /// mark the range of correct spelling at end
3553 setMisspelled(snext, last, SpellChecker::WORD_OK);
3558 void Paragraph::spellCheck() const
3560 SpellChecker * speller = theSpellChecker();
3561 if (!speller || !size() ||!needsSpellCheck())
3565 d->rangeOfSpellCheck(start, endpos);
3566 if (speller->canCheckParagraph()) {
3567 // loop until we leave the range
3568 for (pos_type first = start; first < endpos; ) {
3569 pos_type last = endpos;
3570 Private::Positions softbreaks;
3571 Language * lang = d->locateSpellRange(first, last, softbreaks);
3572 if (first >= endpos)
3574 // start the spell checker on the unit of meaning
3575 docstring word = asString(first, last, AS_STR_INSETS);
3576 WordLangTuple wl = WordLangTuple(word, lang);
3577 SpellChecker::Result result = word.size() ?
3578 speller->check(wl) : SpellChecker::WORD_OK;
3579 d->markMisspelledWords(first, last, result, word, softbreaks);
3583 static docstring_list suggestions;
3584 pos_type to = endpos;
3585 while (start < endpos) {
3587 spellCheck(start, to, wl, suggestions, false);
3591 d->readySpellCheck();
3595 bool Paragraph::isMisspelled(pos_type pos) const
3597 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3601 string Paragraph::magicLabel() const
3604 ss << "magicparlabel-" << id();