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"
54 #include "insets/InsetSpecialChar.h"
56 #include "support/debug.h"
57 #include "support/docstring_list.h"
58 #include "support/ExceptionMessage.h"
59 #include "support/gettext.h"
60 #include "support/lassert.h"
61 #include "support/lstrings.h"
62 #include "support/textutils.h"
68 using namespace lyx::support;
73 /// Inset identifier (above 0x10ffff, for ucs-4)
74 char_type const META_INSET = 0x200001;
78 /////////////////////////////////////////////////////////////////////
82 /////////////////////////////////////////////////////////////////////
84 class SpellResultRange {
86 SpellResultRange(FontSpan range, SpellChecker::Result result)
87 : range_(range), result_(result)
90 FontSpan const & range() const { return range_; }
92 void range(FontSpan const & r) { range_ = r; }
94 SpellChecker::Result result() const { return result_; }
96 void result(SpellChecker::Result r) { result_ = r; }
98 bool inside(pos_type pos) const { return range_.inside(pos); }
100 bool covered(FontSpan const & r) const
102 // 1. first of new range inside current range or
103 // 2. last of new range inside current range or
104 // 3. first of current range inside new range or
105 // 4. last of current range inside new range
106 return range_.inside(r.first) || range_.inside(r.last) ||
107 r.inside(range_.first) || r.inside(range_.last);
110 void shift(pos_type pos, int offset)
112 if (range_.first > pos) {
113 range_.first += offset;
114 range_.last += offset;
115 } else if (range_.last > pos) {
116 range_.last += offset;
121 SpellChecker::Result result_ ;
125 /////////////////////////////////////////////////////////////////////
129 /////////////////////////////////////////////////////////////////////
131 class SpellCheckerState {
133 SpellCheckerState() {
134 needs_refresh_ = true;
135 current_change_number_ = 0;
138 void setRange(FontSpan const fp, SpellChecker::Result state)
140 eraseCoveredRanges(fp);
141 if (state != SpellChecker::WORD_OK)
142 ranges_.push_back(SpellResultRange(fp, state));
145 void increasePosAfterPos(pos_type pos)
147 correctRangesAfterPos(pos, 1);
151 void decreasePosAfterPos(pos_type pos)
153 correctRangesAfterPos(pos, -1);
157 void refreshLast(pos_type pos)
159 if (pos < refresh_.last)
163 SpellChecker::Result getState(pos_type pos) const
165 SpellChecker::Result result = SpellChecker::WORD_OK;
166 RangesIterator et = ranges_.end();
167 RangesIterator it = ranges_.begin();
168 for (; it != et; ++it) {
169 if(it->inside(pos)) {
176 bool needsRefresh() const {
177 return needs_refresh_;
180 SpellChecker::ChangeNumber currentChangeNumber() const {
181 return current_change_number_;
184 void refreshRange(pos_type & first, pos_type & last) const {
185 first = refresh_.first;
186 last = refresh_.last;
189 void needsRefresh(pos_type pos) {
190 if (needs_refresh_ && pos != -1) {
191 if (pos < refresh_.first)
192 refresh_.first = pos;
193 if (pos > refresh_.last)
195 } else if (pos != -1) {
196 refresh_.first = pos;
199 needs_refresh_ = pos != -1;
202 void needsCompleteRefresh(SpellChecker::ChangeNumber change_number) {
203 needs_refresh_ = true;
206 current_change_number_ = change_number;
210 typedef vector<SpellResultRange> Ranges;
211 typedef Ranges::const_iterator RangesIterator;
213 /// the area of the paragraph with pending spell check
216 /// spell state cache version number
217 SpellChecker::ChangeNumber current_change_number_;
220 void eraseCoveredRanges(FontSpan const fp)
223 RangesIterator et = ranges_.end();
224 RangesIterator it = ranges_.begin();
225 for (; it != et; ++it) {
226 if (!it->covered(fp))
227 result.push_back(SpellResultRange(it->range(), it->result()));
232 void correctRangesAfterPos(pos_type pos, int offset)
234 RangesIterator et = ranges_.end();
235 Ranges::iterator it = ranges_.begin();
236 for (; it != et; ++it) {
237 it->shift(pos, offset);
243 /////////////////////////////////////////////////////////////////////
245 // Paragraph::Private
247 /////////////////////////////////////////////////////////////////////
249 class Paragraph::Private
253 Private(Paragraph * owner, Layout const & layout);
254 /// "Copy constructor"
255 Private(Private const &, Paragraph * owner);
256 /// Copy constructor from \p beg to \p end
257 Private(Private const &, Paragraph * owner, pos_type beg, pos_type end);
260 void insertChar(pos_type pos, char_type c, Change const & change);
262 /// Output the surrogate pair formed by \p c and \p next to \p os.
263 /// \return the number of characters written.
264 int latexSurrogatePair(odocstream & os, char_type c, char_type next,
265 OutputParams const &);
267 /// Output a space in appropriate formatting (or a surrogate pair
268 /// if the next character is a combining character).
269 /// \return whether a surrogate pair was output.
270 bool simpleTeXBlanks(OutputParams const &,
271 odocstream &, TexRow & texrow,
273 unsigned int & column,
275 Layout const & style);
277 /// Output consecutive unicode chars, belonging to the same script as
278 /// specified by the latex macro \p ltx, to \p os starting from \p i.
279 /// \return the number of characters written.
280 int writeScriptChars(odocstream & os, docstring const & ltx,
281 Change const &, Encoding const &, pos_type & i);
283 /// This could go to ParagraphParameters if we want to.
284 int startTeXParParams(BufferParams const &, odocstream &, TexRow &,
285 OutputParams const &) const;
287 /// This could go to ParagraphParameters if we want to.
288 int endTeXParParams(BufferParams const &, odocstream &, TexRow &,
289 OutputParams const &) const;
292 void latexInset(BufferParams const &,
294 TexRow & texrow, OutputParams &,
297 Font const & outerfont,
299 Change & running_change,
300 Layout const & style,
302 unsigned int & column);
305 void latexSpecialChar(
307 OutputParams const & runparams,
308 Font const & running_font,
309 Change const & running_change,
310 Layout const & style,
312 unsigned int & column);
319 unsigned int & column);
321 bool latexSpecialTypewriter(
325 unsigned int & column);
327 bool latexSpecialPhrase(
330 unsigned int & column,
331 OutputParams const & runparams);
334 void validate(LaTeXFeatures & features) const;
336 /// Checks if the paragraph contains only text and no inset or font change.
337 bool onlyText(Buffer const & buf, Font const & outerfont,
338 pos_type initial) const;
340 /// match a string against a particular point in the paragraph
341 bool isTextAt(string const & str, pos_type pos) const;
343 /// a vector of speller skip positions
344 typedef vector<FontSpan> SkipPositions;
345 typedef SkipPositions::const_iterator SkipPositionsIterator;
347 void appendSkipPosition(SkipPositions & skips, pos_type const pos) const;
349 Language * getSpellLanguage(pos_type const from) const;
351 Language * locateSpellRange(pos_type & from, pos_type & to,
352 SkipPositions & skips) const;
354 bool hasSpellerChange() const {
355 SpellChecker::ChangeNumber speller_change_number = 0;
356 if (theSpellChecker())
357 speller_change_number = theSpellChecker()->changeNumber();
358 return speller_change_number > speller_state_.currentChangeNumber();
361 bool ignoreWord(docstring const & word) const ;
363 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
365 pos_type textsize = owner_->size();
366 // check for sane arguments
367 if (to < from || from >= textsize)
369 FontSpan fp = FontSpan(from, to);
370 // don't mark end of paragraph
371 if (fp.last >= textsize)
372 fp.last = textsize - 1;
373 speller_state_.setRange(fp, state);
376 void requestSpellCheck(pos_type pos) {
377 speller_state_.needsRefresh(pos);
380 void readySpellCheck() {
381 speller_state_.needsRefresh(-1);
384 bool needsSpellCheck() const
386 return speller_state_.needsRefresh();
389 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
391 speller_state_.refreshRange(first, last);
393 last = owner_->size();
396 pos_type endpos = last;
397 owner_->locateWord(first, endpos, WHOLE_WORD);
400 owner_->locateWord(last, endpos, WHOLE_WORD);
405 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
409 while (it != et && it->first < start) {
410 int skip = it->last - it->first + 1;
418 void markMisspelledWords(pos_type const & first, pos_type const & last,
419 SpellChecker::Result result,
420 docstring const & word,
421 SkipPositions const & skips);
423 InsetCode ownerCode() const
425 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
428 /// Which Paragraph owns us?
432 Inset const * inset_owner_;
441 ParagraphParameters params_;
443 /// for recording and looking up changes
447 InsetList insetlist_;
450 pos_type begin_of_body_;
452 typedef docstring TextContainer;
456 typedef set<docstring> Words;
457 typedef map<Language, Words> LangWordsMap;
461 Layout const * layout_;
463 SpellCheckerState speller_state_;
469 struct special_phrase {
475 special_phrase const special_phrases[] = {
476 { "LyX", from_ascii("\\LyX{}"), false },
477 { "TeX", from_ascii("\\TeX{}"), true },
478 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
479 { "LaTeX", from_ascii("\\LaTeX{}"), true },
482 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
487 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
488 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
494 // Initialization of the counter for the paragraph id's,
496 // FIXME: There should be a more intelligent way to generate and use the
497 // paragraph ids per buffer instead a global static counter for all InsetText
498 // in the running program.
499 static int paragraph_id = -1;
501 Paragraph::Private::Private(Private const & p, Paragraph * owner)
502 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
503 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
504 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
507 id_ = ++paragraph_id;
508 requestSpellCheck(p.text_.size());
512 Paragraph::Private::Private(Private const & p, Paragraph * owner,
513 pos_type beg, pos_type end)
514 : owner_(owner), inset_owner_(p.inset_owner_),
515 params_(p.params_), changes_(p.changes_),
516 insetlist_(p.insetlist_, beg, end),
517 begin_of_body_(p.begin_of_body_), words_(p.words_),
520 id_ = ++paragraph_id;
521 if (beg >= pos_type(p.text_.size()))
523 text_ = p.text_.substr(beg, end - beg);
525 FontList::const_iterator fcit = fontlist_.begin();
526 FontList::const_iterator fend = fontlist_.end();
527 for (; fcit != fend; ++fcit) {
528 if (fcit->pos() < beg)
530 if (fcit->pos() >= end) {
531 // Add last entry in the fontlist_.
532 fontlist_.set(text_.size() - 1, fcit->font());
535 // Add a new entry in the fontlist_.
536 fontlist_.set(fcit->pos() - beg, fcit->font());
538 requestSpellCheck(p.text_.size());
542 void Paragraph::addChangesToToc(DocIterator const & cdit,
543 Buffer const & buf) const
545 d->changes_.addToToc(cdit, buf);
549 bool Paragraph::isDeleted(pos_type start, pos_type end) const
551 LASSERT(start >= 0 && start <= size(), /**/);
552 LASSERT(end > start && end <= size() + 1, /**/);
554 return d->changes_.isDeleted(start, end);
558 bool Paragraph::isChanged(pos_type start, pos_type end) const
560 LASSERT(start >= 0 && start <= size(), /**/);
561 LASSERT(end > start && end <= size() + 1, /**/);
563 return d->changes_.isChanged(start, end);
567 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
569 // keep the logic here in sync with the logic of eraseChars()
573 Change const change = d->changes_.lookup(size());
574 return change.inserted() && change.currentAuthor();
578 void Paragraph::setChange(Change const & change)
580 // beware of the imaginary end-of-par character!
581 d->changes_.set(change, 0, size() + 1);
584 * Propagate the change recursively - but not in case of DELETED!
586 * Imagine that your co-author makes changes in an existing inset. He
587 * sends your document to you and you come to the conclusion that the
588 * inset should go completely. If you erase it, LyX must not delete all
589 * text within the inset. Otherwise, the change tracked insertions of
590 * your co-author get lost and there is no way to restore them later.
592 * Conclusion: An inset's content should remain untouched if you delete it
595 if (!change.deleted()) {
596 for (pos_type pos = 0; pos < size(); ++pos) {
597 if (Inset * inset = getInset(pos))
598 inset->setChange(change);
604 void Paragraph::setChange(pos_type pos, Change const & change)
606 LASSERT(pos >= 0 && pos <= size(), /**/);
607 d->changes_.set(change, pos);
609 // see comment in setChange(Change const &) above
610 if (!change.deleted() && pos < size())
611 if (Inset * inset = getInset(pos))
612 inset->setChange(change);
616 Change const & Paragraph::lookupChange(pos_type pos) const
618 LASSERT(pos >= 0 && pos <= size(), /**/);
619 return d->changes_.lookup(pos);
623 void Paragraph::acceptChanges(pos_type start, pos_type end)
625 LASSERT(start >= 0 && start <= size(), /**/);
626 LASSERT(end > start && end <= size() + 1, /**/);
628 for (pos_type pos = start; pos < end; ++pos) {
629 switch (lookupChange(pos).type) {
630 case Change::UNCHANGED:
631 // accept changes in nested inset
632 if (Inset * inset = getInset(pos))
633 inset->acceptChanges();
636 case Change::INSERTED:
637 d->changes_.set(Change(Change::UNCHANGED), pos);
638 // also accept changes in nested inset
639 if (Inset * inset = getInset(pos))
640 inset->acceptChanges();
643 case Change::DELETED:
644 // Suppress access to non-existent
645 // "end-of-paragraph char"
647 eraseChar(pos, false);
658 void Paragraph::rejectChanges(pos_type start, pos_type end)
660 LASSERT(start >= 0 && start <= size(), /**/);
661 LASSERT(end > start && end <= size() + 1, /**/);
663 for (pos_type pos = start; pos < end; ++pos) {
664 switch (lookupChange(pos).type) {
665 case Change::UNCHANGED:
666 // reject changes in nested inset
667 if (Inset * inset = getInset(pos))
668 inset->rejectChanges();
671 case Change::INSERTED:
672 // Suppress access to non-existent
673 // "end-of-paragraph char"
675 eraseChar(pos, false);
681 case Change::DELETED:
682 d->changes_.set(Change(Change::UNCHANGED), pos);
684 // Do NOT reject changes within a deleted inset!
685 // There may be insertions of a co-author inside of it!
693 void Paragraph::Private::insertChar(pos_type pos, char_type c,
694 Change const & change)
696 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
699 changes_.insert(change, pos);
701 // This is actually very common when parsing buffers (and
702 // maybe inserting ascii text)
703 if (pos == pos_type(text_.size())) {
704 // when appending characters, no need to update tables
706 // but we want spell checking
707 requestSpellCheck(pos);
711 text_.insert(text_.begin() + pos, c);
713 // Update the font table.
714 fontlist_.increasePosAfterPos(pos);
717 insetlist_.increasePosAfterPos(pos);
719 // Update list of misspelled positions
720 speller_state_.increasePosAfterPos(pos);
724 bool Paragraph::insertInset(pos_type pos, Inset * inset,
725 Change const & change)
727 LASSERT(inset, /**/);
728 LASSERT(pos >= 0 && pos <= size(), /**/);
730 // Paragraph::insertInset() can be used in cut/copy/paste operation where
731 // d->inset_owner_ is not set yet.
732 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
735 d->insertChar(pos, META_INSET, change);
736 LASSERT(d->text_[pos] == META_INSET, /**/);
738 // Add a new entry in the insetlist_.
739 d->insetlist_.insert(inset, pos);
741 // Some insets require run of spell checker
742 requestSpellCheck(pos);
747 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
749 LASSERT(pos >= 0 && pos <= size(), return false);
751 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
754 Change change = d->changes_.lookup(pos);
756 // set the character to DELETED if
757 // a) it was previously unchanged or
758 // b) it was inserted by a co-author
760 if (!change.changed() ||
761 (change.inserted() && !change.currentAuthor())) {
762 setChange(pos, Change(Change::DELETED));
763 // request run of spell checker
764 requestSpellCheck(pos);
768 if (change.deleted())
772 // Don't physically access the imaginary end-of-paragraph character.
773 // eraseChar() can only mark it as DELETED. A physical deletion of
774 // end-of-par must be handled externally.
780 d->changes_.erase(pos);
782 // if it is an inset, delete the inset entry
783 if (d->text_[pos] == META_INSET)
784 d->insetlist_.erase(pos);
786 d->text_.erase(d->text_.begin() + pos);
788 // Update the fontlist_
789 d->fontlist_.erase(pos);
791 // Update the insetlist_
792 d->insetlist_.decreasePosAfterPos(pos);
794 // Update list of misspelled positions
795 d->speller_state_.decreasePosAfterPos(pos);
796 d->speller_state_.refreshLast(size());
802 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
804 LASSERT(start >= 0 && start <= size(), /**/);
805 LASSERT(end >= start && end <= size() + 1, /**/);
808 for (pos_type count = end - start; count; --count) {
809 if (!eraseChar(i, trackChanges))
816 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
817 char_type next, OutputParams const & runparams)
819 // Writing next here may circumvent a possible font change between
820 // c and next. Since next is only output if it forms a surrogate pair
821 // with c we can ignore this:
822 // A font change inside a surrogate pair does not make sense and is
823 // hopefully impossible to input.
824 // FIXME: change tracking
825 // Is this correct WRT change tracking?
826 Encoding const & encoding = *(runparams.encoding);
827 docstring const latex1 = encoding.latexChar(next);
828 docstring const latex2 = encoding.latexChar(c);
829 if (docstring(1, next) == latex1) {
830 // the encoding supports the combination
831 os << latex2 << latex1;
832 return latex1.length() + latex2.length();
833 } else if (runparams.local_font &&
834 runparams.local_font->language()->lang() == "polutonikogreek") {
835 // polutonikogreek only works without the brackets
836 os << latex1 << latex2;
837 return latex1.length() + latex2.length();
839 os << latex1 << '{' << latex2 << '}';
840 return latex1.length() + latex2.length() + 2;
844 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
845 odocstream & os, TexRow & texrow,
847 unsigned int & column,
849 Layout const & style)
851 if (style.pass_thru || runparams.pass_thru)
854 if (i + 1 < int(text_.size())) {
855 char_type next = text_[i + 1];
856 if (Encodings::isCombiningChar(next)) {
857 // This space has an accent, so we must always output it.
858 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
863 if (runparams.linelen > 0
864 && column > runparams.linelen
866 && text_[i - 1] != ' '
867 && (i + 1 < int(text_.size()))
868 // same in FreeSpacing mode
869 && !owner_->isFreeSpacing()
870 // In typewriter mode, we want to avoid
871 // ! . ? : at the end of a line
872 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
873 && (text_[i - 1] == '.'
874 || text_[i - 1] == '?'
875 || text_[i - 1] == ':'
876 || text_[i - 1] == '!'))) {
879 texrow.start(owner_->id(), i + 1);
881 } else if (style.free_spacing) {
890 int Paragraph::Private::writeScriptChars(odocstream & os,
891 docstring const & ltx,
892 Change const & runningChange,
893 Encoding const & encoding,
896 // FIXME: modifying i here is not very nice...
898 // We only arrive here when a proper language for character text_[i] has
899 // not been specified (i.e., it could not be translated in the current
900 // latex encoding) or its latex translation has been forced, and it
901 // belongs to a known script.
902 // Parameter ltx contains the latex translation of text_[i] as specified
903 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
904 // The latex macro name "textXXX" specifies the script to which text_[i]
905 // belongs and we use it in order to check whether characters from the
906 // same script immediately follow, such that we can collect them in a
907 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
908 // for the first char but only "<spec>" for all subsequent chars.
909 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
910 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
911 string script = to_ascii(ltx.substr(1, brace1 - 1));
914 bool closing_brace = true;
915 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
916 // Correct encoding is being used, so we can avoid \textgreek.
919 closing_brace = false;
921 os << ltx.substr(pos, length);
922 int size = text_.size();
923 while (i + 1 < size) {
924 char_type const next = text_[i + 1];
925 // Stop here if next character belongs to another script
926 // or there is a change in change tracking status.
927 if (!Encodings::isKnownScriptChar(next, script) ||
928 runningChange != owner_->lookupChange(i + 1))
932 FontList::const_iterator cit = fontlist_.begin();
933 FontList::const_iterator end = fontlist_.end();
934 for (; cit != end; ++cit) {
935 if (cit->pos() >= i && !found) {
936 prev_font = cit->font();
939 if (cit->pos() >= i + 1)
942 // Stop here if there is a font attribute or encoding change.
943 if (found && cit != end && prev_font != cit->font())
945 docstring const latex = encoding.latexChar(next);
946 docstring::size_type const b1 =
947 latex.find_first_of(from_ascii("{"));
948 docstring::size_type const b2 =
949 latex.find_last_of(from_ascii("}"));
950 int const len = b2 - b1 - 1;
951 os << latex.substr(b1 + 1, len);
963 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
965 pos_type const len = str.length();
967 // is the paragraph large enough?
968 if (pos + len > int(text_.size()))
971 // does the wanted text start at point?
972 for (string::size_type i = 0; i < str.length(); ++i) {
973 // Caution: direct comparison of characters works only
974 // because str is pure ASCII.
975 if (str[i] != text_[pos + i])
979 return fontlist_.hasChangeInRange(pos, len);
983 void Paragraph::Private::latexInset(BufferParams const & bparams,
986 OutputParams & runparams,
989 Font const & outerfont,
991 Change & running_change,
992 Layout const & style,
994 unsigned int & column)
996 Inset * inset = owner_->getInset(i);
997 LASSERT(inset, /**/);
999 if (style.pass_thru) {
1000 inset->plaintext(os, runparams);
1004 // FIXME: move this to InsetNewline::latex
1005 if (inset->lyxCode() == NEWLINE_CODE) {
1006 // newlines are handled differently here than
1007 // the default in simpleTeXSpecialChars().
1008 if (!style.newline_allowed) {
1012 column += running_font.latexWriteEndChanges(
1013 os, bparams, runparams,
1014 basefont, basefont);
1018 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1021 basefont = owner_->getLayoutFont(bparams, outerfont);
1022 running_font = basefont;
1024 if (runparams.moving_arg)
1029 texrow.start(owner_->id(), i + 1);
1033 if (owner_->isDeleted(i)) {
1034 if( ++runparams.inDeletedInset == 1)
1035 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1038 if (inset->canTrackChanges()) {
1039 column += Changes::latexMarkChange(os, bparams, running_change,
1040 Change(Change::UNCHANGED), runparams);
1041 running_change = Change(Change::UNCHANGED);
1045 odocstream::pos_type const len = os.tellp();
1047 if (inset->forceLTR()
1048 && running_font.isRightToLeft()
1049 // ERT is an exception, it should be output with no
1050 // decorations at all
1051 && inset->lyxCode() != ERT_CODE) {
1052 if (running_font.language()->lang() == "farsi")
1059 // FIXME: Bug: we can have an empty font change here!
1060 // if there has just been a font change, we are going to close it
1061 // right now, which means stupid latex code like \textsf{}. AFAIK,
1062 // this does not harm dvi output. A minor bug, thus (JMarc)
1064 // Some insets cannot be inside a font change command.
1065 // However, even such insets *can* be placed in \L or \R
1066 // or their equivalents (for RTL language switches), so we don't
1067 // close the language in those cases.
1068 // ArabTeX, though, cannot handle this special behavior, it seems.
1069 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1070 || running_font.language()->lang() == "arabic_arabtex";
1071 if (open_font && inset->noFontChange()) {
1072 bool closeLanguage = arabtex
1073 || basefont.isRightToLeft() == running_font.isRightToLeft();
1074 unsigned int count = running_font.latexWriteEndChanges(os,
1075 bparams, runparams, basefont, basefont, closeLanguage);
1077 // if any font properties were closed, update the running_font,
1078 // making sure, however, to leave the language as it was
1080 // FIXME: probably a better way to keep track of the old
1081 // language, than copying the entire font?
1082 Font const copy_font(running_font);
1083 basefont = owner_->getLayoutFont(bparams, outerfont);
1084 running_font = basefont;
1086 running_font.setLanguage(copy_font.language());
1087 // leave font open if language is still open
1088 open_font = (running_font.language() == basefont.language());
1090 runparams.local_font = &basefont;
1097 tmp = inset->latex(os, runparams);
1098 } catch (EncodingException & e) {
1099 // add location information and throw again.
1106 if (running_font.language()->lang() == "farsi")
1113 texrow.newlines(tmp);
1114 texrow.start(owner_->id(), i + 1);
1117 column += (unsigned int)(os.tellp() - len);
1120 if (owner_->isDeleted(i))
1121 --runparams.inDeletedInset;
1125 void Paragraph::Private::latexSpecialChar(
1127 OutputParams const & runparams,
1128 Font const & running_font,
1129 Change const & running_change,
1130 Layout const & style,
1132 unsigned int & column)
1134 char_type const c = text_[i];
1136 if (style.pass_thru || runparams.pass_thru) {
1138 // FIXME UNICODE: This can fail if c cannot
1139 // be encoded in the current encoding.
1144 // If T1 font encoding is used, use the special
1145 // characters it provides.
1146 // NOTE: some languages reset the font encoding
1148 if (!running_font.language()->internalFontEncoding()
1149 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1152 // \tt font needs special treatment
1153 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1154 && latexSpecialTypewriter(c, os, i, column))
1157 // Otherwise, we use what LaTeX provides us.
1160 os << "\\textbackslash{}";
1164 os << "\\textless{}";
1168 os << "\\textgreater{}";
1172 os << "\\textbar{}";
1179 os << "\\char`\\\"{}";
1184 case '%': case '#': case '{':
1192 os << "\\textasciitilde{}";
1197 os << "\\textasciicircum{}";
1204 // avoid being mistaken for optional arguments
1212 // Blanks are printed before font switching.
1213 // Sure? I am not! (try nice-latex)
1214 // I am sure it's correct. LyX might be smarter
1215 // in the future, but for now, nothing wrong is
1221 if (latexSpecialPhrase(os, i, column, runparams))
1227 Encoding const & encoding = *(runparams.encoding);
1228 if (i + 1 < int(text_.size())) {
1229 char_type next = text_[i + 1];
1230 if (Encodings::isCombiningChar(next)) {
1231 column += latexSurrogatePair(os, c, next, runparams) - 1;
1237 docstring const latex = encoding.latexChar(c);
1238 if (Encodings::isKnownScriptChar(c, script)
1239 && prefixIs(latex, from_ascii("\\" + script)))
1240 column += writeScriptChars(os, latex,
1241 running_change, encoding, i) - 1;
1242 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1243 // Prevent eating of a following
1244 // space or command corruption by
1245 // following characters
1246 column += latex.length() + 1;
1247 os << latex << "{}";
1249 column += latex.length() - 1;
1257 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1258 pos_type i, unsigned int & column)
1264 // In T1 encoding, these characters exist
1265 // but we should avoid ligatures
1266 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1268 os << "\\textcompwordmark{}";
1275 // soul.sty breaks with \char`\"
1276 os << "\\textquotedbl{}";
1285 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1286 pos_type i, unsigned int & column)
1290 // within \ttfamily, "--" is merged to "-" (no endash)
1291 // so we avoid this rather irritating ligature
1292 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1299 // everything else has to be checked separately
1300 // (depending on the encoding)
1307 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1308 unsigned int & column, OutputParams const & runparams)
1310 // FIXME: if we have "LaTeX" with a font
1311 // change in the middle (before the 'T', then
1312 // the "TeX" part is still special cased.
1313 // Really we should only operate this on
1314 // "words" for some definition of word
1316 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1317 if (!isTextAt(special_phrases[pnr].phrase, i))
1319 if (runparams.moving_arg)
1321 os << special_phrases[pnr].macro;
1322 i += special_phrases[pnr].phrase.length() - 1;
1323 column += special_phrases[pnr].macro.length() - 1;
1330 void Paragraph::Private::validate(LaTeXFeatures & features) const
1332 if (layout_->inpreamble && inset_owner_) {
1333 bool const is_command = layout_->latextype == LATEX_COMMAND;
1334 Buffer const & buf = inset_owner_->buffer();
1335 BufferParams const & bp = buf.params();
1338 // Using a string stream here circumvents the encoding
1339 // switching machinery of odocstream. Therefore the
1340 // output is wrong if this paragraph contains content
1341 // that needs to switch encoding.
1342 odocstringstream ods;
1344 ods << '\\' << from_ascii(layout_->latexname());
1345 // we have to provide all the optional arguments here, even though
1346 // the last one is the only one we care about.
1347 // Separate handling of optional argument inset.
1348 if (layout_->optargs != 0 || layout_->reqargs != 0)
1349 latexArgInsets(*owner_, ods, features.runparams(),
1350 layout_->reqargs, layout_->optargs);
1352 ods << from_ascii(layout_->latexparam());
1354 docstring::size_type const length = ods.str().length();
1355 // this will output "{" at the beginning, but not at the end
1356 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1357 if (ods.str().length() > length) {
1360 string const snippet = to_utf8(ods.str());
1361 features.addPreambleSnippet(snippet);
1365 if (features.runparams().flavor == OutputParams::HTML
1366 && layout_->htmltitle()) {
1367 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1370 // check the params.
1371 if (!params_.spacing().isDefault())
1372 features.require("setspace");
1375 features.useLayout(layout_->name());
1378 fontlist_.validate(features);
1380 // then the indentation
1381 if (!params_.leftIndent().zero())
1382 features.require("ParagraphLeftIndent");
1385 InsetList::const_iterator icit = insetlist_.begin();
1386 InsetList::const_iterator iend = insetlist_.end();
1387 for (; icit != iend; ++icit) {
1389 icit->inset->validate(features);
1390 if (layout_->needprotect &&
1391 icit->inset->lyxCode() == FOOT_CODE)
1392 features.require("NeedLyXFootnoteCode");
1396 // then the contents
1397 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1398 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1399 if (!special_phrases[pnr].builtin
1400 && isTextAt(special_phrases[pnr].phrase, i)) {
1401 features.require(special_phrases[pnr].phrase);
1405 Encodings::validate(text_[i], features);
1409 /////////////////////////////////////////////////////////////////////
1413 /////////////////////////////////////////////////////////////////////
1416 Layout const emptyParagraphLayout;
1419 Paragraph::Paragraph()
1420 : d(new Paragraph::Private(this, emptyParagraphLayout))
1427 Paragraph::Paragraph(Paragraph const & par)
1428 : itemdepth(par.itemdepth),
1429 d(new Paragraph::Private(*par.d, this))
1435 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1436 : itemdepth(par.itemdepth),
1437 d(new Paragraph::Private(*par.d, this, beg, end))
1443 Paragraph & Paragraph::operator=(Paragraph const & par)
1445 // needed as we will destroy the private part before copying it
1447 itemdepth = par.itemdepth;
1451 d = new Private(*par.d, this);
1458 Paragraph::~Paragraph()
1467 // this shall be called just before every "os << ..." action.
1468 void flushString(ostream & os, docstring & s)
1477 void Paragraph::write(ostream & os, BufferParams const & bparams,
1478 depth_type & dth) const
1480 // The beginning or end of a deeper (i.e. nested) area?
1481 if (dth != d->params_.depth()) {
1482 if (d->params_.depth() > dth) {
1483 while (d->params_.depth() > dth) {
1484 os << "\n\\begin_deeper";
1488 while (d->params_.depth() < dth) {
1489 os << "\n\\end_deeper";
1495 // First write the layout
1496 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1498 d->params_.write(os);
1500 Font font1(inherit_font, bparams.language);
1502 Change running_change = Change(Change::UNCHANGED);
1504 // this string is used as a buffer to avoid repetitive calls
1505 // to to_utf8(), which turn out to be expensive (JMarc)
1506 docstring write_buffer;
1509 for (pos_type i = 0; i <= size(); ++i) {
1511 Change const change = lookupChange(i);
1512 if (change != running_change)
1513 flushString(os, write_buffer);
1514 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1515 running_change = change;
1520 // Write font changes
1521 Font font2 = getFontSettings(bparams, i);
1522 if (font2 != font1) {
1523 flushString(os, write_buffer);
1524 font2.lyxWriteChanges(font1, os);
1529 char_type const c = d->text_[i];
1532 if (Inset const * inset = getInset(i)) {
1533 flushString(os, write_buffer);
1534 if (inset->directWrite()) {
1535 // international char, let it write
1536 // code directly so it's shorter in
1542 os << "\\begin_inset ";
1544 os << "\n\\end_inset\n\n";
1550 flushString(os, write_buffer);
1551 os << "\n\\backslash\n";
1555 flushString(os, write_buffer);
1556 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1563 if ((column > 70 && c == ' ')
1565 flushString(os, write_buffer);
1569 // this check is to amend a bug. LyX sometimes
1570 // inserts '\0' this could cause problems.
1572 write_buffer.push_back(c);
1574 LYXERR0("NUL char in structure.");
1580 flushString(os, write_buffer);
1581 os << "\n\\end_layout\n";
1585 void Paragraph::validate(LaTeXFeatures & features) const
1587 d->validate(features);
1591 void Paragraph::insert(pos_type start, docstring const & str,
1592 Font const & font, Change const & change)
1594 for (size_t i = 0, n = str.size(); i != n ; ++i)
1595 insertChar(start + i, str[i], font, change);
1599 void Paragraph::appendChar(char_type c, Font const & font,
1600 Change const & change)
1603 d->changes_.insert(change, d->text_.size());
1604 // when appending characters, no need to update tables
1605 d->text_.push_back(c);
1606 setFont(d->text_.size() - 1, font);
1610 void Paragraph::appendString(docstring const & s, Font const & font,
1611 Change const & change)
1613 pos_type end = s.size();
1614 size_t oldsize = d->text_.size();
1615 size_t newsize = oldsize + end;
1616 size_t capacity = d->text_.capacity();
1617 if (newsize >= capacity)
1618 d->text_.reserve(max(capacity + 100, newsize));
1620 // when appending characters, no need to update tables
1623 // FIXME: Optimize this!
1624 for (size_t i = oldsize; i != newsize; ++i) {
1626 d->changes_.insert(change, i);
1628 d->fontlist_.set(oldsize, font);
1629 d->fontlist_.set(newsize - 1, font);
1633 void Paragraph::insertChar(pos_type pos, char_type c,
1636 d->insertChar(pos, c, Change(trackChanges ?
1637 Change::INSERTED : Change::UNCHANGED));
1641 void Paragraph::insertChar(pos_type pos, char_type c,
1642 Font const & font, bool trackChanges)
1644 d->insertChar(pos, c, Change(trackChanges ?
1645 Change::INSERTED : Change::UNCHANGED));
1650 void Paragraph::insertChar(pos_type pos, char_type c,
1651 Font const & font, Change const & change)
1653 d->insertChar(pos, c, change);
1658 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1659 Font const & font, Change const & change)
1661 bool const success = insertInset(pos, inset, change);
1662 // Set the font/language of the inset...
1668 void Paragraph::resetFonts(Font const & font)
1670 d->fontlist_.clear();
1671 d->fontlist_.set(0, font);
1672 d->fontlist_.set(d->text_.size() - 1, font);
1675 // Gets uninstantiated font setting at position.
1676 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1680 LYXERR0("pos: " << pos << " size: " << size());
1681 LASSERT(pos <= size(), /**/);
1684 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1685 if (cit != d->fontlist_.end())
1688 if (pos == size() && !empty())
1689 return getFontSettings(bparams, pos - 1);
1691 // Optimisation: avoid a full font instantiation if there is no
1692 // language change from previous call.
1693 static Font previous_font;
1694 static Language const * previous_lang = 0;
1695 Language const * lang = getParLanguage(bparams);
1696 if (lang != previous_lang) {
1697 previous_lang = lang;
1698 previous_font = Font(inherit_font, lang);
1700 return previous_font;
1704 FontSpan Paragraph::fontSpan(pos_type pos) const
1706 LASSERT(pos <= size(), /**/);
1709 FontList::const_iterator cit = d->fontlist_.begin();
1710 FontList::const_iterator end = d->fontlist_.end();
1711 for (; cit != end; ++cit) {
1712 if (cit->pos() >= pos) {
1713 if (pos >= beginOfBody())
1714 return FontSpan(max(start, beginOfBody()),
1717 return FontSpan(start,
1718 min(beginOfBody() - 1,
1721 start = cit->pos() + 1;
1724 // This should not happen, but if so, we take no chances.
1725 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1726 return FontSpan(pos, pos);
1730 // Gets uninstantiated font setting at position 0
1731 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1733 if (!empty() && !d->fontlist_.empty())
1734 return d->fontlist_.begin()->font();
1736 // Optimisation: avoid a full font instantiation if there is no
1737 // language change from previous call.
1738 static Font previous_font;
1739 static Language const * previous_lang = 0;
1740 if (bparams.language != previous_lang) {
1741 previous_lang = bparams.language;
1742 previous_font = Font(inherit_font, bparams.language);
1745 return previous_font;
1749 // Gets the fully instantiated font at a given position in a paragraph
1750 // This is basically the same function as Text::GetFont() in text2.cpp.
1751 // The difference is that this one is used for generating the LaTeX file,
1752 // and thus cosmetic "improvements" are disallowed: This has to deliver
1753 // the true picture of the buffer. (Asger)
1754 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1755 Font const & outerfont) const
1757 LASSERT(pos >= 0, /**/);
1759 Font font = getFontSettings(bparams, pos);
1761 pos_type const body_pos = beginOfBody();
1762 FontInfo & fi = font.fontInfo();
1764 fi.realize(d->layout_->labelfont);
1766 fi.realize(d->layout_->font);
1768 fi.realize(outerfont.fontInfo());
1769 fi.realize(bparams.getFont().fontInfo());
1775 Font const Paragraph::getLabelFont
1776 (BufferParams const & bparams, Font const & outerfont) const
1778 FontInfo tmpfont = d->layout_->labelfont;
1779 tmpfont.realize(outerfont.fontInfo());
1780 tmpfont.realize(bparams.getFont().fontInfo());
1781 return Font(tmpfont, getParLanguage(bparams));
1785 Font const Paragraph::getLayoutFont
1786 (BufferParams const & bparams, Font const & outerfont) const
1788 FontInfo tmpfont = d->layout_->font;
1789 tmpfont.realize(outerfont.fontInfo());
1790 tmpfont.realize(bparams.getFont().fontInfo());
1791 return Font(tmpfont, getParLanguage(bparams));
1795 /// Returns the height of the highest font in range
1796 FontSize Paragraph::highestFontInRange
1797 (pos_type startpos, pos_type endpos, FontSize def_size) const
1799 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1803 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1805 char_type c = d->text_[pos];
1806 if (!lyxrc.rtl_support)
1836 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1842 void Paragraph::setFont(pos_type pos, Font const & font)
1844 LASSERT(pos <= size(), /**/);
1846 // First, reduce font against layout/label font
1847 // Update: The setCharFont() routine in text2.cpp already
1848 // reduces font, so we don't need to do that here. (Asger)
1850 d->fontlist_.set(pos, font);
1854 void Paragraph::makeSameLayout(Paragraph const & par)
1856 d->layout_ = par.d->layout_;
1857 d->params_ = par.d->params_;
1861 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1863 if (isFreeSpacing())
1869 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1870 if (eraseChar(pos, trackChanges))
1876 return count > 0 || pos > 0;
1880 bool Paragraph::hasSameLayout(Paragraph const & par) const
1882 return par.d->layout_ == d->layout_
1883 && d->params_.sameLayout(par.d->params_);
1887 depth_type Paragraph::getDepth() const
1889 return d->params_.depth();
1893 depth_type Paragraph::getMaxDepthAfter() const
1895 if (d->layout_->isEnvironment())
1896 return d->params_.depth() + 1;
1898 return d->params_.depth();
1902 char Paragraph::getAlign() const
1904 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1905 return d->layout_->align;
1907 return d->params_.align();
1911 docstring const & Paragraph::labelString() const
1913 return d->params_.labelString();
1917 // the next two functions are for the manual labels
1918 docstring const Paragraph::getLabelWidthString() const
1920 if (d->layout_->margintype == MARGIN_MANUAL
1921 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1922 return d->params_.labelWidthString();
1924 return _("Senseless with this layout!");
1928 void Paragraph::setLabelWidthString(docstring const & s)
1930 d->params_.labelWidthString(s);
1934 docstring Paragraph::expandLabel(Layout const & layout,
1935 BufferParams const & bparams) const
1937 return expandParagraphLabel(layout, bparams, true);
1941 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1942 BufferParams const & bparams) const
1944 return expandParagraphLabel(layout, bparams, false);
1948 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1949 BufferParams const & bparams, bool process_appendix) const
1951 DocumentClass const & tclass = bparams.documentClass();
1952 string const & lang = getParLanguage(bparams)->code();
1953 bool const in_appendix = process_appendix && d->params_.appendix();
1954 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1956 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1957 && !layout.counter.empty())
1958 return tclass.counters().theCounter(layout.counter, lang);
1960 // handle 'inherited level parts' in 'fmt',
1961 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1962 size_t const i = fmt.find('@', 0);
1963 if (i != docstring::npos) {
1964 size_t const j = fmt.find('@', i + 1);
1965 if (j != docstring::npos) {
1966 docstring parent(fmt, i + 1, j - i - 1);
1967 docstring label = from_ascii("??");
1968 if (tclass.hasLayout(parent))
1969 docstring label = expandParagraphLabel(tclass[parent], bparams,
1971 fmt = docstring(fmt, 0, i) + label
1972 + docstring(fmt, j + 1, docstring::npos);
1976 return tclass.counters().counterLabel(fmt, lang);
1980 void Paragraph::applyLayout(Layout const & new_layout)
1982 d->layout_ = &new_layout;
1983 LyXAlignment const oldAlign = d->params_.align();
1985 if (!(oldAlign & d->layout_->alignpossible)) {
1986 frontend::Alert::warning(_("Alignment not permitted"),
1987 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1988 d->params_.align(LYX_ALIGN_LAYOUT);
1993 pos_type Paragraph::beginOfBody() const
1995 return d->begin_of_body_;
1999 void Paragraph::setBeginOfBody()
2001 if (d->layout_->labeltype != LABEL_MANUAL) {
2002 d->begin_of_body_ = 0;
2006 // Unroll the first two cycles of the loop
2007 // and remember the previous character to
2008 // remove unnecessary getChar() calls
2010 pos_type end = size();
2011 if (i < end && !isNewline(i)) {
2013 char_type previous_char = 0;
2016 previous_char = d->text_[i];
2017 if (!isNewline(i)) {
2019 while (i < end && previous_char != ' ') {
2024 previous_char = temp;
2030 d->begin_of_body_ = i;
2034 bool Paragraph::allowParagraphCustomization() const
2036 return inInset().allowParagraphCustomization();
2040 bool Paragraph::usePlainLayout() const
2042 return inInset().usePlainLayout();
2048 // paragraphs inside floats need different alignment tags to avoid
2051 bool noTrivlistCentering(InsetCode code)
2053 return code == FLOAT_CODE
2054 || code == WRAP_CODE
2055 || code == CELL_CODE;
2059 string correction(string const & orig)
2061 if (orig == "flushleft")
2062 return "raggedright";
2063 if (orig == "flushright")
2064 return "raggedleft";
2065 if (orig == "center")
2071 string const corrected_env(string const & suffix, string const & env,
2072 InsetCode code, bool const lastpar)
2074 string output = suffix + "{";
2075 if (noTrivlistCentering(code)) {
2077 // the last paragraph in non-trivlist-aligned
2078 // context is special (to avoid unwanted whitespace)
2079 if (suffix == "\\begin")
2080 return "\\" + correction(env) + "{}";
2083 output += correction(env);
2087 if (suffix == "\\begin")
2093 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2095 if (!contains(str, "\n"))
2096 column += str.size();
2100 column = rsplit(str, tmp, '\n').size();
2107 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2108 odocstream & os, TexRow & texrow,
2109 OutputParams const & runparams) const
2113 if (params_.noindent()) {
2114 os << "\\noindent ";
2118 LyXAlignment const curAlign = params_.align();
2120 if (curAlign == layout_->align)
2124 case LYX_ALIGN_NONE:
2125 case LYX_ALIGN_BLOCK:
2126 case LYX_ALIGN_LAYOUT:
2127 case LYX_ALIGN_SPECIAL:
2128 case LYX_ALIGN_DECIMAL:
2130 case LYX_ALIGN_LEFT:
2131 case LYX_ALIGN_RIGHT:
2132 case LYX_ALIGN_CENTER:
2133 if (runparams.moving_arg) {
2140 string const begin_tag = "\\begin";
2141 InsetCode code = ownerCode();
2142 bool const lastpar = runparams.isLastPar;
2145 case LYX_ALIGN_NONE:
2146 case LYX_ALIGN_BLOCK:
2147 case LYX_ALIGN_LAYOUT:
2148 case LYX_ALIGN_SPECIAL:
2149 case LYX_ALIGN_DECIMAL:
2151 case LYX_ALIGN_LEFT: {
2153 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2154 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2156 output = corrected_env(begin_tag, "flushright", code, lastpar);
2157 os << from_ascii(output);
2158 adjust_row_column(output, texrow, column);
2160 } case LYX_ALIGN_RIGHT: {
2162 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2163 output = corrected_env(begin_tag, "flushright", code, lastpar);
2165 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2166 os << from_ascii(output);
2167 adjust_row_column(output, texrow, column);
2169 } case LYX_ALIGN_CENTER: {
2171 output = corrected_env(begin_tag, "center", code, lastpar);
2172 os << from_ascii(output);
2173 adjust_row_column(output, texrow, column);
2182 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2183 odocstream & os, TexRow & texrow,
2184 OutputParams const & runparams) const
2188 LyXAlignment const curAlign = params_.align();
2190 if (curAlign == layout_->align)
2194 case LYX_ALIGN_NONE:
2195 case LYX_ALIGN_BLOCK:
2196 case LYX_ALIGN_LAYOUT:
2197 case LYX_ALIGN_SPECIAL:
2198 case LYX_ALIGN_DECIMAL:
2200 case LYX_ALIGN_LEFT:
2201 case LYX_ALIGN_RIGHT:
2202 case LYX_ALIGN_CENTER:
2203 if (runparams.moving_arg) {
2210 string const end_tag = "\n\\par\\end";
2211 InsetCode code = ownerCode();
2212 bool const lastpar = runparams.isLastPar;
2215 case LYX_ALIGN_NONE:
2216 case LYX_ALIGN_BLOCK:
2217 case LYX_ALIGN_LAYOUT:
2218 case LYX_ALIGN_SPECIAL:
2219 case LYX_ALIGN_DECIMAL:
2221 case LYX_ALIGN_LEFT: {
2223 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2224 output = corrected_env(end_tag, "flushleft", code, lastpar);
2226 output = corrected_env(end_tag, "flushright", code, lastpar);
2227 os << from_ascii(output);
2228 adjust_row_column(output, texrow, column);
2230 } case LYX_ALIGN_RIGHT: {
2232 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2233 output = corrected_env(end_tag, "flushright", code, lastpar);
2235 output = corrected_env(end_tag, "flushleft", code, lastpar);
2236 os << from_ascii(output);
2237 adjust_row_column(output, texrow, column);
2239 } case LYX_ALIGN_CENTER: {
2241 output = corrected_env(end_tag, "center", code, lastpar);
2242 os << from_ascii(output);
2243 adjust_row_column(output, texrow, column);
2252 // This one spits out the text of the paragraph
2253 void Paragraph::latex(BufferParams const & bparams,
2254 Font const & outerfont,
2255 odocstream & os, TexRow & texrow,
2256 OutputParams const & runparams,
2257 int start_pos, int end_pos, bool force) const
2259 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2261 // FIXME This check should not be needed. Perhaps issue an
2262 // error if it triggers.
2263 Layout const & style = inInset().forcePlainLayout() ?
2264 bparams.documentClass().plainLayout() : *d->layout_;
2266 if (!force && style.inpreamble)
2269 bool const allowcust = allowParagraphCustomization();
2271 // Current base font for all inherited font changes, without any
2272 // change caused by an individual character, except for the language:
2273 // It is set to the language of the first character.
2274 // As long as we are in the label, this font is the base font of the
2275 // label. Before the first body character it is set to the base font
2279 // Maybe we have to create a optional argument.
2280 pos_type body_pos = beginOfBody();
2281 unsigned int column = 0;
2284 // the optional argument is kept in curly brackets in
2285 // case it contains a ']'
2288 basefont = getLabelFont(bparams, outerfont);
2290 basefont = getLayoutFont(bparams, outerfont);
2293 // Which font is currently active?
2294 Font running_font(basefont);
2295 // Do we have an open font change?
2296 bool open_font = false;
2298 Change runningChange = Change(Change::UNCHANGED);
2300 Encoding const * const prev_encoding = runparams.encoding;
2302 texrow.start(id(), 0);
2304 // if the paragraph is empty, the loop will not be entered at all
2306 if (style.isCommand()) {
2311 column += d->startTeXParParams(bparams, os, texrow,
2315 for (pos_type i = 0; i < size(); ++i) {
2316 // First char in paragraph or after label?
2317 if (i == body_pos) {
2320 column += running_font.latexWriteEndChanges(
2321 os, bparams, runparams,
2322 basefont, basefont);
2325 basefont = getLayoutFont(bparams, outerfont);
2326 running_font = basefont;
2328 column += Changes::latexMarkChange(os, bparams,
2329 runningChange, Change(Change::UNCHANGED),
2331 runningChange = Change(Change::UNCHANGED);
2336 if (style.isCommand()) {
2342 column += d->startTeXParParams(bparams, os,
2347 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2350 if (bparams.outputChanges && runningChange != change) {
2352 column += running_font.latexWriteEndChanges(
2353 os, bparams, runparams, basefont, basefont);
2356 basefont = getLayoutFont(bparams, outerfont);
2357 running_font = basefont;
2359 column += Changes::latexMarkChange(os, bparams, runningChange,
2361 runningChange = change;
2364 // do not output text which is marked deleted
2365 // if change tracking output is disabled
2366 if (!bparams.outputChanges && change.deleted()) {
2372 // Fully instantiated font
2373 Font const font = getFont(bparams, i, outerfont);
2375 Font const last_font = running_font;
2377 // Do we need to close the previous font?
2379 (font != running_font ||
2380 font.language() != running_font.language()))
2382 column += running_font.latexWriteEndChanges(
2383 os, bparams, runparams, basefont,
2384 (i == body_pos-1) ? basefont : font);
2385 running_font = basefont;
2389 string const running_lang = runparams.use_polyglossia ?
2390 running_font.language()->polyglossia() : running_font.language()->babel();
2391 // close babel's font environment before opening CJK.
2392 string const lang_end_command = runparams.use_polyglossia ?
2393 "\\end{$$lang}" : lyxrc.language_command_end;
2394 if (!running_lang.empty() &&
2395 font.language()->encoding()->package() == Encoding::CJK) {
2396 string end_tag = subst(lang_end_command,
2399 os << from_ascii(end_tag);
2400 column += end_tag.length();
2403 // Switch file encoding if necessary (and allowed)
2404 if (!runparams.pass_thru && !style.pass_thru &&
2405 runparams.encoding->package() != Encoding::none &&
2406 font.language()->encoding()->package() != Encoding::none) {
2407 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2408 runparams, *(font.language()->encoding()));
2409 if (enc_switch.first) {
2410 column += enc_switch.second;
2411 runparams.encoding = font.language()->encoding();
2415 char_type const c = d->text_[i];
2417 // Do we need to change font?
2418 if ((font != running_font ||
2419 font.language() != running_font.language()) &&
2422 odocstringstream ods;
2423 column += font.latexWriteStartChanges(ods, bparams,
2424 runparams, basefont,
2426 running_font = font;
2428 docstring fontchange = ods.str();
2429 // check whether the fontchange ends with a \\textcolor
2430 // modifier and the text starts with a space (bug 4473)
2431 docstring const last_modifier = rsplit(fontchange, '\\');
2432 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2433 os << fontchange << from_ascii("{}");
2434 // check if the fontchange ends with a trailing blank
2435 // (like "\small " (see bug 3382)
2436 else if (suffixIs(fontchange, ' ') && c == ' ')
2437 os << fontchange.substr(0, fontchange.size() - 1)
2438 << from_ascii("{}");
2443 // FIXME: think about end_pos implementation...
2444 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2445 // FIXME: integrate this case in latexSpecialChar
2446 // Do not print the separation of the optional argument
2447 // if style.pass_thru is false. This works because
2448 // latexSpecialChar ignores spaces if
2449 // style.pass_thru is false.
2450 if (i != body_pos - 1) {
2451 if (d->simpleTeXBlanks(
2452 runparams, os, texrow,
2453 i, column, font, style)) {
2454 // A surrogate pair was output. We
2455 // must not call latexSpecialChar
2456 // in this iteration, since it would output
2457 // the combining character again.
2464 OutputParams rp = runparams;
2465 rp.free_spacing = style.free_spacing;
2466 rp.local_font = &font;
2467 rp.intitle = style.intitle;
2469 // Two major modes: LaTeX or plain
2470 // Handle here those cases common to both modes
2471 // and then split to handle the two modes separately.
2472 if (c == META_INSET) {
2473 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2474 d->latexInset(bparams, os,
2475 texrow, rp, running_font,
2476 basefont, outerfont, open_font,
2477 runningChange, style, i, column);
2480 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2482 d->latexSpecialChar(os, rp, running_font, runningChange,
2484 } catch (EncodingException & e) {
2485 if (runparams.dryrun) {
2486 os << "<" << _("LyX Warning: ")
2487 << _("uncodable character") << " '";
2491 // add location information and throw again.
2500 // Set the encoding to that returned from latexSpecialChar (see
2501 // comment for encoding member in OutputParams.h)
2502 runparams.encoding = rp.encoding;
2505 // If we have an open font definition, we have to close it
2507 #ifdef FIXED_LANGUAGE_END_DETECTION
2509 running_font.latexWriteEndChanges(os, bparams,
2510 runparams, basefont,
2511 next_->getFont(bparams, 0, outerfont));
2513 running_font.latexWriteEndChanges(os, bparams,
2514 runparams, basefont, basefont);
2517 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2518 //FIXME: there as we start another \selectlanguage with the next paragraph if
2519 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2520 running_font.latexWriteEndChanges(os, bparams, runparams,
2521 basefont, basefont);
2525 column += Changes::latexMarkChange(os, bparams, runningChange,
2526 Change(Change::UNCHANGED), runparams);
2528 // Needed if there is an optional argument but no contents.
2529 if (body_pos > 0 && body_pos == size()) {
2533 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2534 && runparams.encoding != prev_encoding) {
2535 runparams.encoding = prev_encoding;
2536 if (!runparams.isFullUnicode())
2537 os << setEncoding(prev_encoding->iconvName());
2540 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2544 bool Paragraph::emptyTag() const
2546 for (pos_type i = 0; i < size(); ++i) {
2547 if (Inset const * inset = getInset(i)) {
2548 InsetCode lyx_code = inset->lyxCode();
2549 // FIXME testing like that is wrong. What is
2551 if (lyx_code != TOC_CODE &&
2552 lyx_code != INCLUDE_CODE &&
2553 lyx_code != GRAPHICS_CODE &&
2554 lyx_code != ERT_CODE &&
2555 lyx_code != LISTINGS_CODE &&
2556 lyx_code != FLOAT_CODE &&
2557 lyx_code != TABULAR_CODE) {
2561 char_type c = d->text_[i];
2562 if (c != ' ' && c != '\t')
2570 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2573 for (pos_type i = 0; i < size(); ++i) {
2574 if (Inset const * inset = getInset(i)) {
2575 InsetCode lyx_code = inset->lyxCode();
2576 if (lyx_code == LABEL_CODE) {
2577 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2578 docstring const & id = il->getParam("name");
2579 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2587 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2591 for (i = 0; i < size(); ++i) {
2592 if (Inset const * inset = getInset(i)) {
2593 inset->docbook(os, runparams);
2595 char_type c = d->text_[i];
2598 os << sgml::escapeChar(c);
2605 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2609 for (i = 0; i < size(); ++i) {
2610 if (Inset const * inset = getInset(i)) {
2611 inset->xhtml(xs, runparams);
2613 char_type c = d->text_[i];
2623 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2626 pos_type size = text_.size();
2627 for (pos_type i = initial; i < size; ++i) {
2628 Font font = owner_->getFont(buf.params(), i, outerfont);
2629 if (text_[i] == META_INSET)
2631 if (i != initial && font != font_old)
2640 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2642 OutputParams const & runparams,
2643 Font const & outerfont,
2644 pos_type initial) const
2646 bool emph_flag = false;
2648 Layout const & style = *d->layout_;
2650 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2652 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2655 // parsing main loop
2656 for (pos_type i = initial; i < size(); ++i) {
2657 Font font = getFont(buf.params(), i, outerfont);
2659 // handle <emphasis> tag
2660 if (font_old.emph() != font.fontInfo().emph()) {
2661 if (font.fontInfo().emph() == FONT_ON) {
2664 } else if (i != initial) {
2665 os << "</emphasis>";
2670 if (Inset const * inset = getInset(i)) {
2671 inset->docbook(os, runparams);
2673 char_type c = d->text_[i];
2675 if (style.pass_thru)
2678 os << sgml::escapeChar(c);
2680 font_old = font.fontInfo();
2684 os << "</emphasis>";
2687 if (style.free_spacing)
2689 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2694 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2696 OutputParams const & runparams,
2697 Font const & outerfont,
2698 pos_type initial) const
2702 bool emph_flag = false;
2703 bool bold_flag = false;
2706 Layout const & style = *d->layout_;
2708 if (!runparams.for_toc && runparams.html_make_pars) {
2709 // generate a magic label for this paragraph
2710 string const attr = "id='" + magicLabel() + "'";
2711 xs << html::CompTag("a", attr);
2715 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2717 // parsing main loop
2718 for (pos_type i = initial; i < size(); ++i) {
2719 // let's not show deleted material in the output
2723 Font font = getFont(buf.params(), i, outerfont);
2726 if (font_old.emph() != font.fontInfo().emph()) {
2727 if (font.fontInfo().emph() == FONT_ON) {
2728 xs << html::StartTag("em");
2730 } else if (emph_flag && i != initial) {
2731 xs << html::EndTag("em");
2736 if (font_old.series() != font.fontInfo().series()) {
2737 if (font.fontInfo().series() == BOLD_SERIES) {
2738 xs << html::StartTag("strong");
2740 } else if (bold_flag && i != initial) {
2741 xs << html::EndTag("strong");
2746 // Other such tags? What about the other text ranges?
2748 Inset const * inset = getInset(i);
2750 if (!runparams.for_toc || inset->isInToc()) {
2751 OutputParams np = runparams;
2752 if (!inset->getLayout().htmlisblock())
2753 np.html_in_par = true;
2754 retval += inset->xhtml(xs, np);
2757 char_type c = d->text_[i];
2759 if (style.pass_thru)
2761 else if (c == '-') {
2764 if (j < size() && d->text_[j] == '-') {
2766 if (j < size() && d->text_[j] == '-') {
2767 str += from_ascii("—");
2770 str += from_ascii("–");
2776 // We don't want to escape the entities. Note that
2777 // it is safe to do this, since str can otherwise
2778 // only be "-". E.g., it can't be "<".
2779 xs << XHTMLStream::ESCAPE_NONE << str;
2783 font_old = font.fontInfo();
2791 bool Paragraph::isHfill(pos_type pos) const
2793 Inset const * inset = getInset(pos);
2794 return inset && (inset->lyxCode() == SPACE_CODE &&
2795 inset->isStretchableSpace());
2799 bool Paragraph::isNewline(pos_type pos) const
2801 Inset const * inset = getInset(pos);
2802 return inset && inset->lyxCode() == NEWLINE_CODE;
2806 bool Paragraph::isLineSeparator(pos_type pos) const
2808 char_type const c = d->text_[pos];
2809 if (isLineSeparatorChar(c))
2811 Inset const * inset = getInset(pos);
2812 return inset && inset->isLineSeparator();
2816 bool Paragraph::isWordSeparator(pos_type pos) const
2818 if (Inset const * inset = getInset(pos))
2819 return !inset->isLetter();
2820 char_type const c = d->text_[pos];
2821 // We want to pass the ' and escape chars to the spellchecker
2822 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2823 return (!isLetterChar(c) && !isDigitASCII(c) && !contains(quote, c))
2828 bool Paragraph::isChar(pos_type pos) const
2830 if (Inset const * inset = getInset(pos))
2831 return inset->isChar();
2832 char_type const c = d->text_[pos];
2833 return !isLetterChar(c) && !isDigitASCII(c) && !lyx::isSpace(c);
2837 bool Paragraph::isSpace(pos_type pos) const
2839 if (Inset const * inset = getInset(pos))
2840 return inset->isSpace();
2841 char_type const c = d->text_[pos];
2842 return lyx::isSpace(c);
2847 Paragraph::getParLanguage(BufferParams const & bparams) const
2850 return getFirstFontSettings(bparams).language();
2851 // FIXME: we should check the prev par as well (Lgb)
2852 return bparams.language;
2856 bool Paragraph::isRTL(BufferParams const & bparams) const
2858 return lyxrc.rtl_support
2859 && getParLanguage(bparams)->rightToLeft()
2860 && !inInset().getLayout().forceLTR();
2864 void Paragraph::changeLanguage(BufferParams const & bparams,
2865 Language const * from, Language const * to)
2867 // change language including dummy font change at the end
2868 for (pos_type i = 0; i <= size(); ++i) {
2869 Font font = getFontSettings(bparams, i);
2870 if (font.language() == from) {
2871 font.setLanguage(to);
2875 d->requestSpellCheck(size());
2879 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2881 Language const * doc_language = bparams.language;
2882 FontList::const_iterator cit = d->fontlist_.begin();
2883 FontList::const_iterator end = d->fontlist_.end();
2885 for (; cit != end; ++cit)
2886 if (cit->font().language() != ignore_language &&
2887 cit->font().language() != latex_language &&
2888 cit->font().language() != doc_language)
2894 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2896 FontList::const_iterator cit = d->fontlist_.begin();
2897 FontList::const_iterator end = d->fontlist_.end();
2899 for (; cit != end; ++cit) {
2900 Language const * lang = cit->font().language();
2901 if (lang != ignore_language &&
2902 lang != latex_language)
2903 languages.insert(lang);
2908 docstring Paragraph::asString(int options) const
2910 return asString(0, size(), options);
2914 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2916 odocstringstream os;
2919 && options & AS_STR_LABEL
2920 && !d->params_.labelString().empty())
2921 os << d->params_.labelString() << ' ';
2923 for (pos_type i = beg; i < end; ++i) {
2924 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2926 char_type const c = d->text_[i];
2927 if (isPrintable(c) || c == '\t'
2928 || (c == '\n' && (options & AS_STR_NEWLINES)))
2930 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2931 getInset(i)->toString(os);
2932 if (getInset(i)->asInsetMath())
2941 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2943 odocstringstream os;
2946 && options & AS_STR_LABEL
2947 && !d->params_.labelString().empty())
2948 os << d->params_.labelString() << ' ';
2950 for (pos_type i = beg; i < end; ++i) {
2951 char_type const c = d->text_[i];
2952 if (isPrintable(c) || c == '\t'
2953 || (c == '\n' && (options & AS_STR_NEWLINES)))
2955 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2956 getInset(i)->plaintext(os, runparams);
2964 void Paragraph::setInsetOwner(Inset const * inset)
2966 d->inset_owner_ = inset;
2970 int Paragraph::id() const
2976 void Paragraph::setId(int id)
2982 Layout const & Paragraph::layout() const
2988 void Paragraph::setLayout(Layout const & layout)
2990 d->layout_ = &layout;
2994 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2996 setLayout(tc.defaultLayout());
3000 void Paragraph::setPlainLayout(DocumentClass const & tc)
3002 setLayout(tc.plainLayout());
3006 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3008 if (usePlainLayout())
3009 setPlainLayout(tclass);
3011 setDefaultLayout(tclass);
3015 Inset const & Paragraph::inInset() const
3017 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3018 _("Memory problem"), _("Paragraph not properly initialized")));
3019 return *d->inset_owner_;
3023 ParagraphParameters & Paragraph::params()
3029 ParagraphParameters const & Paragraph::params() const
3035 bool Paragraph::isFreeSpacing() const
3037 if (d->layout_->free_spacing)
3039 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3043 bool Paragraph::allowEmpty() const
3045 if (d->layout_->keepempty)
3047 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3051 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3053 if (!Encodings::isArabicChar(c))
3056 char_type prev_char = ' ';
3057 char_type next_char = ' ';
3059 for (pos_type i = pos - 1; i >= 0; --i) {
3060 char_type const par_char = d->text_[i];
3061 if (!Encodings::isArabicComposeChar(par_char)) {
3062 prev_char = par_char;
3067 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3068 char_type const par_char = d->text_[i];
3069 if (!Encodings::isArabicComposeChar(par_char)) {
3070 next_char = par_char;
3075 if (Encodings::isArabicChar(next_char)) {
3076 if (Encodings::isArabicChar(prev_char) &&
3077 !Encodings::isArabicSpecialChar(prev_char))
3078 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3080 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3082 if (Encodings::isArabicChar(prev_char) &&
3083 !Encodings::isArabicSpecialChar(prev_char))
3084 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3086 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3091 int Paragraph::checkBiblio(Buffer const & buffer)
3094 // This is getting more and more a mess. ...We really should clean
3095 // up this bibitem issue for 1.6.
3097 // Add bibitem insets if necessary
3098 if (d->layout_->labeltype != LABEL_BIBLIO)
3101 bool hasbibitem = !d->insetlist_.empty()
3102 // Insist on it being in pos 0
3103 && d->text_[0] == META_INSET
3104 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3106 bool track_changes = buffer.params().trackChanges;
3111 // remove a bibitem in pos != 0
3112 // restore it later in pos 0 if necessary
3113 // (e.g. if a user inserts contents _before_ the item)
3114 // we're assuming there's only one of these, which there
3116 int erasedInsetPosition = -1;
3117 InsetList::iterator it = d->insetlist_.begin();
3118 InsetList::iterator end = d->insetlist_.end();
3119 for (; it != end; ++it)
3120 if (it->inset->lyxCode() == BIBITEM_CODE
3122 InsetCommand * olditem = it->inset->asInsetCommand();
3123 oldkey = olditem->getParam("key");
3124 oldlabel = olditem->getParam("label");
3125 erasedInsetPosition = it->pos;
3126 eraseChar(erasedInsetPosition, track_changes);
3130 // There was an InsetBibitem at the beginning, and we didn't
3131 // have to erase one.
3132 if (hasbibitem && erasedInsetPosition < 0)
3135 // There was an InsetBibitem at the beginning and we did have to
3136 // erase one. So we give its properties to the beginning inset.
3138 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3139 if (!oldkey.empty())
3140 inset->setParam("key", oldkey);
3141 inset->setParam("label", oldlabel);
3142 return -erasedInsetPosition;
3145 // There was no inset at the beginning, so we need to create one with
3146 // the key and label of the one we erased.
3147 InsetBibitem * inset =
3148 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3149 // restore values of previously deleted item in this par.
3150 if (!oldkey.empty())
3151 inset->setParam("key", oldkey);
3152 inset->setParam("label", oldlabel);
3153 insertInset(0, inset,
3154 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3160 void Paragraph::checkAuthors(AuthorList const & authorList)
3162 d->changes_.checkAuthors(authorList);
3166 bool Paragraph::isChanged(pos_type pos) const
3168 return lookupChange(pos).changed();
3172 bool Paragraph::isInserted(pos_type pos) const
3174 return lookupChange(pos).inserted();
3178 bool Paragraph::isDeleted(pos_type pos) const
3180 return lookupChange(pos).deleted();
3184 InsetList const & Paragraph::insetList() const
3186 return d->insetlist_;
3190 void Paragraph::setBuffer(Buffer & b)
3192 d->insetlist_.setBuffer(b);
3196 Inset * Paragraph::releaseInset(pos_type pos)
3198 Inset * inset = d->insetlist_.release(pos);
3199 /// does not honour change tracking!
3200 eraseChar(pos, false);
3205 Inset * Paragraph::getInset(pos_type pos)
3207 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3208 ? d->insetlist_.get(pos) : 0;
3212 Inset const * Paragraph::getInset(pos_type pos) const
3214 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3215 ? d->insetlist_.get(pos) : 0;
3219 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3220 pos_type & right, TextCase action)
3222 // process sequences of modified characters; in change
3223 // tracking mode, this approach results in much better
3224 // usability than changing case on a char-by-char basis
3227 bool const trackChanges = bparams.trackChanges;
3229 bool capitalize = true;
3231 for (; pos < right; ++pos) {
3232 char_type oldChar = d->text_[pos];
3233 char_type newChar = oldChar;
3235 // ignore insets and don't play with deleted text!
3236 if (oldChar != META_INSET && !isDeleted(pos)) {
3238 case text_lowercase:
3239 newChar = lowercase(oldChar);
3241 case text_capitalization:
3243 newChar = uppercase(oldChar);
3247 case text_uppercase:
3248 newChar = uppercase(oldChar);
3253 if (isWordSeparator(pos) || isDeleted(pos)) {
3254 // permit capitalization again
3258 if (oldChar != newChar) {
3260 if (pos != right - 1)
3262 // step behind the changing area
3266 int erasePos = pos - changes.size();
3267 for (size_t i = 0; i < changes.size(); i++) {
3268 insertChar(pos, changes[i],
3269 getFontSettings(bparams,
3272 if (!eraseChar(erasePos, trackChanges)) {
3275 ++right; // expand selection
3283 int Paragraph::find(docstring const & str, bool cs, bool mw,
3284 pos_type start_pos, bool del) const
3286 pos_type pos = start_pos;
3287 int const strsize = str.length();
3289 pos_type const parsize = d->text_.size();
3290 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3291 // Ignore ligature break and hyphenation chars while searching
3292 while (pos < parsize - 1 && isInset(pos)) {
3293 const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3295 || (isc->kind() != InsetSpecialChar::HYPHENATION
3296 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3300 if (cs && str[i] != d->text_[pos])
3302 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3304 if (!del && isDeleted(pos))
3311 // if necessary, check whether string matches word
3313 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3316 && !isWordSeparator(pos))
3320 return pos - start_pos;
3324 char_type Paragraph::getChar(pos_type pos) const
3326 return d->text_[pos];
3330 pos_type Paragraph::size() const
3332 return d->text_.size();
3336 bool Paragraph::empty() const
3338 return d->text_.empty();
3342 bool Paragraph::isInset(pos_type pos) const
3344 return d->text_[pos] == META_INSET;
3348 bool Paragraph::isSeparator(pos_type pos) const
3350 //FIXME: Are we sure this can be the only separator?
3351 return d->text_[pos] == ' ';
3355 void Paragraph::deregisterWords()
3357 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3358 Private::LangWordsMap::const_iterator ite = d->words_.end();
3359 for (; itl != ite; ++itl) {
3360 WordList * wl = theWordList(itl->first);
3361 Private::Words::const_iterator it = (itl->second).begin();
3362 Private::Words::const_iterator et = (itl->second).end();
3363 for (; it != et; ++it)
3370 void Paragraph::locateWord(pos_type & from, pos_type & to,
3371 word_location const loc) const
3374 case WHOLE_WORD_STRICT:
3375 if (from == 0 || from == size()
3376 || isWordSeparator(from)
3377 || isWordSeparator(from - 1)) {
3381 // no break here, we go to the next
3384 // If we are already at the beginning of a word, do nothing
3385 if (!from || isWordSeparator(from - 1))
3387 // no break here, we go to the next
3390 // always move the cursor to the beginning of previous word
3391 while (from && !isWordSeparator(from - 1))
3395 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3398 // no need to move the 'from' cursor
3402 while (to < size() && !isWordSeparator(to))
3407 void Paragraph::collectWords()
3409 // This is the value that needs to be exposed in the preferences
3410 // to resolve bug #6760.
3411 static int minlength = 6;
3412 pos_type n = size();
3413 for (pos_type pos = 0; pos < n; ++pos) {
3414 if (isWordSeparator(pos))
3416 pos_type from = pos;
3417 locateWord(from, pos, WHOLE_WORD);
3418 if (pos - from >= minlength) {
3419 docstring word = asString(from, pos, AS_STR_NONE);
3420 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3421 if (cit == d->fontlist_.end())
3423 Language const * lang = cit->font().language();
3424 d->words_[*lang].insert(word);
3430 void Paragraph::registerWords()
3432 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3433 Private::LangWordsMap::const_iterator ite = d->words_.end();
3434 for (; itl != ite; ++itl) {
3435 WordList * wl = theWordList(itl->first);
3436 Private::Words::const_iterator it = (itl->second).begin();
3437 Private::Words::const_iterator et = (itl->second).end();
3438 for (; it != et; ++it)
3444 void Paragraph::updateWords()
3452 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3454 SkipPositionsIterator begin = skips.begin();
3455 SkipPositions::iterator end = skips.end();
3456 if (pos > 0 && begin < end) {
3458 if (end->last == pos - 1) {
3463 skips.insert(end, FontSpan(pos, pos));
3467 Language * Paragraph::Private::locateSpellRange(
3468 pos_type & from, pos_type & to,
3469 SkipPositions & skips) const
3471 // skip leading white space
3472 while (from < to && owner_->isWordSeparator(from))
3474 // don't check empty range
3477 // get current language
3478 Language * lang = getSpellLanguage(from);
3479 pos_type last = from;
3480 bool samelang = true;
3481 bool sameinset = true;
3482 while (last < to && samelang && sameinset) {
3483 // hop to end of word
3484 while (last < to && !owner_->isWordSeparator(last)) {
3485 if (owner_->getInset(last)) {
3486 appendSkipPosition(skips, last);
3487 } else if (owner_->isDeleted(last)) {
3488 appendSkipPosition(skips, last);
3492 // hop to next word while checking for insets
3493 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3494 if (Inset const * inset = owner_->getInset(last))
3495 sameinset = inset->isChar() && inset->isLetter();
3496 if (sameinset && owner_->isDeleted(last)) {
3497 appendSkipPosition(skips, last);
3502 if (sameinset && last < to) {
3503 // now check for language change
3504 samelang = lang == getSpellLanguage(last);
3507 // if language change detected backstep is needed
3515 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3518 const_cast<Language *>(owner_->getFontSettings(
3519 inset_owner_->buffer().params(), from).language());
3520 if (lang == inset_owner_->buffer().params().language
3521 && !lyxrc.spellchecker_alt_lang.empty()) {
3523 string const lang_variety =
3524 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3525 lang->setCode(lang_code);
3526 lang->setVariety(lang_variety);
3532 void Paragraph::requestSpellCheck(pos_type pos)
3534 d->requestSpellCheck(pos == -1 ? size() : pos);
3538 bool Paragraph::needsSpellCheck() const
3540 SpellChecker::ChangeNumber speller_change_number = 0;
3541 if (theSpellChecker())
3542 speller_change_number = theSpellChecker()->changeNumber();
3543 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3544 d->speller_state_.needsCompleteRefresh(speller_change_number);
3546 return d->needsSpellCheck();
3550 bool Paragraph::Private::ignoreWord(docstring const & word) const
3552 // Ignore words with digits
3553 // FIXME: make this customizable
3554 // (note that some checkers ignore words with digits by default)
3555 docstring::const_iterator cit = word.begin();
3556 docstring::const_iterator const end = word.end();
3557 for (; cit != end; ++cit) {
3558 if (isNumber((*cit)))
3565 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3566 WordLangTuple & wl, docstring_list & suggestions,
3567 bool do_suggestion, bool check_learned) const
3569 SpellChecker::Result result = SpellChecker::WORD_OK;
3570 SpellChecker * speller = theSpellChecker();
3574 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3577 locateWord(from, to, WHOLE_WORD);
3578 if (from == to || from >= size())
3581 docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3582 Language * lang = d->getSpellLanguage(from);
3584 wl = WordLangTuple(word, lang);
3589 if (needsSpellCheck() || check_learned) {
3590 if (!d->ignoreWord(word)) {
3591 bool const trailing_dot = to < size() && d->text_[to] == '.';
3592 result = speller->check(wl);
3593 if (SpellChecker::misspelled(result) && trailing_dot) {
3594 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3595 result = speller->check(wl);
3596 if (!SpellChecker::misspelled(result)) {
3597 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3599 from << ".." << to << "]");
3603 d->setMisspelled(from, to, result);
3605 result = d->speller_state_.getState(from);
3608 bool const misspelled_ = SpellChecker::misspelled(result) ;
3609 if (misspelled_ && do_suggestion)
3610 speller->suggest(wl, suggestions);
3611 else if (misspelled_)
3612 LYXERR(Debug::GUI, "misspelled word: \"" <<
3614 from << ".." << to << "]");
3616 suggestions.clear();
3622 void Paragraph::Private::markMisspelledWords(
3623 pos_type const & first, pos_type const & last,
3624 SpellChecker::Result result,
3625 docstring const & word,
3626 SkipPositions const & skips)
3628 if (!SpellChecker::misspelled(result)) {
3629 setMisspelled(first, last, SpellChecker::WORD_OK);
3633 SpellChecker * speller = theSpellChecker();
3634 // locate and enumerate the error positions
3635 int nerrors = speller->numMisspelledWords();
3637 SkipPositionsIterator it = skips.begin();
3638 SkipPositionsIterator et = skips.end();
3639 for (int index = 0; index < nerrors; ++index) {
3642 speller->misspelledWord(index, wstart, wlen);
3643 /// should not happen if speller supports range checks
3644 if (!wlen) continue;
3645 docstring const misspelled = word.substr(wstart, wlen);
3646 wstart += first + numskipped;
3647 if (snext < wstart) {
3648 /// mark the range of correct spelling
3649 numskipped += countSkips(it, et, wstart);
3650 setMisspelled(snext,
3651 wstart - 1, SpellChecker::WORD_OK);
3653 snext = wstart + wlen;
3654 numskipped += countSkips(it, et, snext);
3655 /// mark the range of misspelling
3656 setMisspelled(wstart, snext, result);
3657 LYXERR(Debug::GUI, "misspelled word: \"" <<
3658 misspelled << "\" [" <<
3659 wstart << ".." << (snext-1) << "]");
3662 if (snext <= last) {
3663 /// mark the range of correct spelling at end
3664 setMisspelled(snext, last, SpellChecker::WORD_OK);
3669 void Paragraph::spellCheck() const
3671 SpellChecker * speller = theSpellChecker();
3672 if (!speller || !size() ||!needsSpellCheck())
3676 d->rangeOfSpellCheck(start, endpos);
3677 if (speller->canCheckParagraph()) {
3678 // loop until we leave the range
3679 for (pos_type first = start; first < endpos; ) {
3680 pos_type last = endpos;
3681 Private::SkipPositions skips;
3682 Language * lang = d->locateSpellRange(first, last, skips);
3683 if (first >= endpos)
3685 // start the spell checker on the unit of meaning
3686 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3687 WordLangTuple wl = WordLangTuple(word, lang);
3688 SpellChecker::Result result = word.size() ?
3689 speller->check(wl) : SpellChecker::WORD_OK;
3690 d->markMisspelledWords(first, last, result, word, skips);
3694 static docstring_list suggestions;
3695 pos_type to = endpos;
3696 while (start < endpos) {
3698 spellCheck(start, to, wl, suggestions, false);
3702 d->readySpellCheck();
3706 bool Paragraph::isMisspelled(pos_type pos) const
3708 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3712 string Paragraph::magicLabel() const
3715 ss << "magicparlabel-" << id();