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 void setMisspelled(pos_type from, pos_type to, SpellChecker::Result state)
363 pos_type textsize = owner_->size();
364 // check for sane arguments
365 if (to < from || from >= textsize)
367 FontSpan fp = FontSpan(from, to);
368 // don't mark end of paragraph
369 if (fp.last >= textsize)
370 fp.last = textsize - 1;
371 speller_state_.setRange(fp, state);
374 void requestSpellCheck(pos_type pos) {
375 speller_state_.needsRefresh(pos);
378 void readySpellCheck() {
379 speller_state_.needsRefresh(-1);
382 bool needsSpellCheck() const
384 return speller_state_.needsRefresh();
387 void rangeOfSpellCheck(pos_type & first, pos_type & last) const
389 speller_state_.refreshRange(first, last);
391 last = owner_->size();
394 pos_type endpos = last;
395 owner_->locateWord(first, endpos, WHOLE_WORD);
398 owner_->locateWord(last, endpos, WHOLE_WORD);
403 int countSkips(SkipPositionsIterator & it, SkipPositionsIterator const et,
407 while (it != et && it->first < start) {
408 int skip = it->last - it->first + 1;
416 void markMisspelledWords(pos_type const & first, pos_type const & last,
417 SpellChecker::Result result,
418 docstring const & word,
419 SkipPositions const & skips);
421 InsetCode ownerCode() const
423 return inset_owner_ ? inset_owner_->lyxCode() : NO_CODE;
426 /// Which Paragraph owns us?
430 Inset const * inset_owner_;
439 ParagraphParameters params_;
441 /// for recording and looking up changes
445 InsetList insetlist_;
448 pos_type begin_of_body_;
450 typedef docstring TextContainer;
454 typedef set<docstring> Words;
455 typedef map<Language, Words> LangWordsMap;
459 Layout const * layout_;
461 SpellCheckerState speller_state_;
467 struct special_phrase {
473 special_phrase const special_phrases[] = {
474 { "LyX", from_ascii("\\LyX{}"), false },
475 { "TeX", from_ascii("\\TeX{}"), true },
476 { "LaTeX2e", from_ascii("\\LaTeXe{}"), true },
477 { "LaTeX", from_ascii("\\LaTeX{}"), true },
480 size_t const phrases_nr = sizeof(special_phrases)/sizeof(special_phrase);
485 Paragraph::Private::Private(Paragraph * owner, Layout const & layout)
486 : owner_(owner), inset_owner_(0), id_(-1), begin_of_body_(0), layout_(&layout)
492 // Initialization of the counter for the paragraph id's,
494 // FIXME: There should be a more intelligent way to generate and use the
495 // paragraph ids per buffer instead a global static counter for all InsetText
496 // in the running program.
497 static int paragraph_id = -1;
499 Paragraph::Private::Private(Private const & p, Paragraph * owner)
500 : owner_(owner), inset_owner_(p.inset_owner_), fontlist_(p.fontlist_),
501 params_(p.params_), changes_(p.changes_), insetlist_(p.insetlist_),
502 begin_of_body_(p.begin_of_body_), text_(p.text_), words_(p.words_),
505 id_ = ++paragraph_id;
506 requestSpellCheck(p.text_.size());
510 Paragraph::Private::Private(Private const & p, Paragraph * owner,
511 pos_type beg, pos_type end)
512 : owner_(owner), inset_owner_(p.inset_owner_),
513 params_(p.params_), changes_(p.changes_),
514 insetlist_(p.insetlist_, beg, end),
515 begin_of_body_(p.begin_of_body_), words_(p.words_),
518 id_ = ++paragraph_id;
519 if (beg >= pos_type(p.text_.size()))
521 text_ = p.text_.substr(beg, end - beg);
523 FontList::const_iterator fcit = fontlist_.begin();
524 FontList::const_iterator fend = fontlist_.end();
525 for (; fcit != fend; ++fcit) {
526 if (fcit->pos() < beg)
528 if (fcit->pos() >= end) {
529 // Add last entry in the fontlist_.
530 fontlist_.set(text_.size() - 1, fcit->font());
533 // Add a new entry in the fontlist_.
534 fontlist_.set(fcit->pos() - beg, fcit->font());
536 requestSpellCheck(p.text_.size());
540 void Paragraph::addChangesToToc(DocIterator const & cdit,
541 Buffer const & buf) const
543 d->changes_.addToToc(cdit, buf);
547 bool Paragraph::isDeleted(pos_type start, pos_type end) const
549 LASSERT(start >= 0 && start <= size(), /**/);
550 LASSERT(end > start && end <= size() + 1, /**/);
552 return d->changes_.isDeleted(start, end);
556 bool Paragraph::isChanged(pos_type start, pos_type end) const
558 LASSERT(start >= 0 && start <= size(), /**/);
559 LASSERT(end > start && end <= size() + 1, /**/);
561 return d->changes_.isChanged(start, end);
565 bool Paragraph::isMergedOnEndOfParDeletion(bool trackChanges) const
567 // keep the logic here in sync with the logic of eraseChars()
571 Change const change = d->changes_.lookup(size());
572 return change.inserted() && change.currentAuthor();
576 void Paragraph::setChange(Change const & change)
578 // beware of the imaginary end-of-par character!
579 d->changes_.set(change, 0, size() + 1);
582 * Propagate the change recursively - but not in case of DELETED!
584 * Imagine that your co-author makes changes in an existing inset. He
585 * sends your document to you and you come to the conclusion that the
586 * inset should go completely. If you erase it, LyX must not delete all
587 * text within the inset. Otherwise, the change tracked insertions of
588 * your co-author get lost and there is no way to restore them later.
590 * Conclusion: An inset's content should remain untouched if you delete it
593 if (!change.deleted()) {
594 for (pos_type pos = 0; pos < size(); ++pos) {
595 if (Inset * inset = getInset(pos))
596 inset->setChange(change);
602 void Paragraph::setChange(pos_type pos, Change const & change)
604 LASSERT(pos >= 0 && pos <= size(), /**/);
605 d->changes_.set(change, pos);
607 // see comment in setChange(Change const &) above
608 if (!change.deleted() && pos < size())
609 if (Inset * inset = getInset(pos))
610 inset->setChange(change);
614 Change const & Paragraph::lookupChange(pos_type pos) const
616 LASSERT(pos >= 0 && pos <= size(), /**/);
617 return d->changes_.lookup(pos);
621 void Paragraph::acceptChanges(pos_type start, pos_type end)
623 LASSERT(start >= 0 && start <= size(), /**/);
624 LASSERT(end > start && end <= size() + 1, /**/);
626 for (pos_type pos = start; pos < end; ++pos) {
627 switch (lookupChange(pos).type) {
628 case Change::UNCHANGED:
629 // accept changes in nested inset
630 if (Inset * inset = getInset(pos))
631 inset->acceptChanges();
634 case Change::INSERTED:
635 d->changes_.set(Change(Change::UNCHANGED), pos);
636 // also accept changes in nested inset
637 if (Inset * inset = getInset(pos))
638 inset->acceptChanges();
641 case Change::DELETED:
642 // Suppress access to non-existent
643 // "end-of-paragraph char"
645 eraseChar(pos, false);
656 void Paragraph::rejectChanges(pos_type start, pos_type end)
658 LASSERT(start >= 0 && start <= size(), /**/);
659 LASSERT(end > start && end <= size() + 1, /**/);
661 for (pos_type pos = start; pos < end; ++pos) {
662 switch (lookupChange(pos).type) {
663 case Change::UNCHANGED:
664 // reject changes in nested inset
665 if (Inset * inset = getInset(pos))
666 inset->rejectChanges();
669 case Change::INSERTED:
670 // Suppress access to non-existent
671 // "end-of-paragraph char"
673 eraseChar(pos, false);
679 case Change::DELETED:
680 d->changes_.set(Change(Change::UNCHANGED), pos);
682 // Do NOT reject changes within a deleted inset!
683 // There may be insertions of a co-author inside of it!
691 void Paragraph::Private::insertChar(pos_type pos, char_type c,
692 Change const & change)
694 LASSERT(pos >= 0 && pos <= int(text_.size()), /**/);
697 changes_.insert(change, pos);
699 // This is actually very common when parsing buffers (and
700 // maybe inserting ascii text)
701 if (pos == pos_type(text_.size())) {
702 // when appending characters, no need to update tables
704 // but we want spell checking
705 requestSpellCheck(pos);
709 text_.insert(text_.begin() + pos, c);
711 // Update the font table.
712 fontlist_.increasePosAfterPos(pos);
715 insetlist_.increasePosAfterPos(pos);
717 // Update list of misspelled positions
718 speller_state_.increasePosAfterPos(pos);
722 bool Paragraph::insertInset(pos_type pos, Inset * inset,
723 Change const & change)
725 LASSERT(inset, /**/);
726 LASSERT(pos >= 0 && pos <= size(), /**/);
728 // Paragraph::insertInset() can be used in cut/copy/paste operation where
729 // d->inset_owner_ is not set yet.
730 if (d->inset_owner_ && !d->inset_owner_->insetAllowed(inset->lyxCode()))
733 d->insertChar(pos, META_INSET, change);
734 LASSERT(d->text_[pos] == META_INSET, /**/);
736 // Add a new entry in the insetlist_.
737 d->insetlist_.insert(inset, pos);
739 // Some insets require run of spell checker
740 requestSpellCheck(pos);
745 bool Paragraph::eraseChar(pos_type pos, bool trackChanges)
747 LASSERT(pos >= 0 && pos <= size(), return false);
749 // keep the logic here in sync with the logic of isMergedOnEndOfParDeletion()
752 Change change = d->changes_.lookup(pos);
754 // set the character to DELETED if
755 // a) it was previously unchanged or
756 // b) it was inserted by a co-author
758 if (!change.changed() ||
759 (change.inserted() && !change.currentAuthor())) {
760 setChange(pos, Change(Change::DELETED));
761 // request run of spell checker
762 requestSpellCheck(pos);
766 if (change.deleted())
770 // Don't physically access the imaginary end-of-paragraph character.
771 // eraseChar() can only mark it as DELETED. A physical deletion of
772 // end-of-par must be handled externally.
778 d->changes_.erase(pos);
780 // if it is an inset, delete the inset entry
781 if (d->text_[pos] == META_INSET)
782 d->insetlist_.erase(pos);
784 d->text_.erase(d->text_.begin() + pos);
786 // Update the fontlist_
787 d->fontlist_.erase(pos);
789 // Update the insetlist_
790 d->insetlist_.decreasePosAfterPos(pos);
792 // Update list of misspelled positions
793 d->speller_state_.decreasePosAfterPos(pos);
794 d->speller_state_.refreshLast(size());
800 int Paragraph::eraseChars(pos_type start, pos_type end, bool trackChanges)
802 LASSERT(start >= 0 && start <= size(), /**/);
803 LASSERT(end >= start && end <= size() + 1, /**/);
806 for (pos_type count = end - start; count; --count) {
807 if (!eraseChar(i, trackChanges))
814 int Paragraph::Private::latexSurrogatePair(odocstream & os, char_type c,
815 char_type next, OutputParams const & runparams)
817 // Writing next here may circumvent a possible font change between
818 // c and next. Since next is only output if it forms a surrogate pair
819 // with c we can ignore this:
820 // A font change inside a surrogate pair does not make sense and is
821 // hopefully impossible to input.
822 // FIXME: change tracking
823 // Is this correct WRT change tracking?
824 Encoding const & encoding = *(runparams.encoding);
825 docstring const latex1 = encoding.latexChar(next);
826 docstring const latex2 = encoding.latexChar(c);
827 if (docstring(1, next) == latex1) {
828 // the encoding supports the combination
829 os << latex2 << latex1;
830 return latex1.length() + latex2.length();
831 } else if (runparams.local_font &&
832 runparams.local_font->language()->lang() == "polutonikogreek") {
833 // polutonikogreek only works without the brackets
834 os << latex1 << latex2;
835 return latex1.length() + latex2.length();
837 os << latex1 << '{' << latex2 << '}';
838 return latex1.length() + latex2.length() + 2;
842 bool Paragraph::Private::simpleTeXBlanks(OutputParams const & runparams,
843 odocstream & os, TexRow & texrow,
845 unsigned int & column,
847 Layout const & style)
849 if (style.pass_thru || runparams.pass_thru)
852 if (i + 1 < int(text_.size())) {
853 char_type next = text_[i + 1];
854 if (Encodings::isCombiningChar(next)) {
855 // This space has an accent, so we must always output it.
856 column += latexSurrogatePair(os, ' ', next, runparams) - 1;
861 if (runparams.linelen > 0
862 && column > runparams.linelen
864 && text_[i - 1] != ' '
865 && (i + 1 < int(text_.size()))
866 // same in FreeSpacing mode
867 && !owner_->isFreeSpacing()
868 // In typewriter mode, we want to avoid
869 // ! . ? : at the end of a line
870 && !(font.fontInfo().family() == TYPEWRITER_FAMILY
871 && (text_[i - 1] == '.'
872 || text_[i - 1] == '?'
873 || text_[i - 1] == ':'
874 || text_[i - 1] == '!'))) {
877 texrow.start(owner_->id(), i + 1);
879 } else if (style.free_spacing) {
888 int Paragraph::Private::writeScriptChars(odocstream & os,
889 docstring const & ltx,
890 Change const & runningChange,
891 Encoding const & encoding,
894 // FIXME: modifying i here is not very nice...
896 // We only arrive here when a proper language for character text_[i] has
897 // not been specified (i.e., it could not be translated in the current
898 // latex encoding) or its latex translation has been forced, and it
899 // belongs to a known script.
900 // Parameter ltx contains the latex translation of text_[i] as specified
901 // in the unicodesymbols file and is something like "\textXXX{<spec>}".
902 // The latex macro name "textXXX" specifies the script to which text_[i]
903 // belongs and we use it in order to check whether characters from the
904 // same script immediately follow, such that we can collect them in a
905 // single "\textXXX" macro. So, we have to retain "\textXXX{<spec>"
906 // for the first char but only "<spec>" for all subsequent chars.
907 docstring::size_type const brace1 = ltx.find_first_of(from_ascii("{"));
908 docstring::size_type const brace2 = ltx.find_last_of(from_ascii("}"));
909 string script = to_ascii(ltx.substr(1, brace1 - 1));
912 bool closing_brace = true;
913 if (script == "textgreek" && encoding.latexName() == "iso-8859-7") {
914 // Correct encoding is being used, so we can avoid \textgreek.
917 closing_brace = false;
919 os << ltx.substr(pos, length);
920 int size = text_.size();
921 while (i + 1 < size) {
922 char_type const next = text_[i + 1];
923 // Stop here if next character belongs to another script
924 // or there is a change in change tracking status.
925 if (!Encodings::isKnownScriptChar(next, script) ||
926 runningChange != owner_->lookupChange(i + 1))
930 FontList::const_iterator cit = fontlist_.begin();
931 FontList::const_iterator end = fontlist_.end();
932 for (; cit != end; ++cit) {
933 if (cit->pos() >= i && !found) {
934 prev_font = cit->font();
937 if (cit->pos() >= i + 1)
940 // Stop here if there is a font attribute or encoding change.
941 if (found && cit != end && prev_font != cit->font())
943 docstring const latex = encoding.latexChar(next);
944 docstring::size_type const b1 =
945 latex.find_first_of(from_ascii("{"));
946 docstring::size_type const b2 =
947 latex.find_last_of(from_ascii("}"));
948 int const len = b2 - b1 - 1;
949 os << latex.substr(b1 + 1, len);
961 bool Paragraph::Private::isTextAt(string const & str, pos_type pos) const
963 pos_type const len = str.length();
965 // is the paragraph large enough?
966 if (pos + len > int(text_.size()))
969 // does the wanted text start at point?
970 for (string::size_type i = 0; i < str.length(); ++i) {
971 // Caution: direct comparison of characters works only
972 // because str is pure ASCII.
973 if (str[i] != text_[pos + i])
977 return fontlist_.hasChangeInRange(pos, len);
981 void Paragraph::Private::latexInset(BufferParams const & bparams,
984 OutputParams & runparams,
987 Font const & outerfont,
989 Change & running_change,
990 Layout const & style,
992 unsigned int & column)
994 Inset * inset = owner_->getInset(i);
995 LASSERT(inset, /**/);
997 if (style.pass_thru) {
998 inset->plaintext(os, runparams);
1002 // FIXME: move this to InsetNewline::latex
1003 if (inset->lyxCode() == NEWLINE_CODE) {
1004 // newlines are handled differently here than
1005 // the default in simpleTeXSpecialChars().
1006 if (!style.newline_allowed) {
1010 column += running_font.latexWriteEndChanges(
1011 os, bparams, runparams,
1012 basefont, basefont);
1016 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY)
1019 basefont = owner_->getLayoutFont(bparams, outerfont);
1020 running_font = basefont;
1022 if (runparams.moving_arg)
1027 texrow.start(owner_->id(), i + 1);
1031 if (owner_->isDeleted(i)) {
1032 if( ++runparams.inDeletedInset == 1)
1033 runparams.changeOfDeletedInset = owner_->lookupChange(i);
1036 if (inset->canTrackChanges()) {
1037 column += Changes::latexMarkChange(os, bparams, running_change,
1038 Change(Change::UNCHANGED), runparams);
1039 running_change = Change(Change::UNCHANGED);
1043 odocstream::pos_type const len = os.tellp();
1045 if (inset->forceLTR()
1046 && running_font.isRightToLeft()
1047 // ERT is an exception, it should be output with no
1048 // decorations at all
1049 && inset->lyxCode() != ERT_CODE) {
1050 if (running_font.language()->lang() == "farsi")
1057 // FIXME: Bug: we can have an empty font change here!
1058 // if there has just been a font change, we are going to close it
1059 // right now, which means stupid latex code like \textsf{}. AFAIK,
1060 // this does not harm dvi output. A minor bug, thus (JMarc)
1062 // Some insets cannot be inside a font change command.
1063 // However, even such insets *can* be placed in \L or \R
1064 // or their equivalents (for RTL language switches), so we don't
1065 // close the language in those cases.
1066 // ArabTeX, though, cannot handle this special behavior, it seems.
1067 bool arabtex = basefont.language()->lang() == "arabic_arabtex"
1068 || running_font.language()->lang() == "arabic_arabtex";
1069 if (open_font && inset->noFontChange()) {
1070 bool closeLanguage = arabtex
1071 || basefont.isRightToLeft() == running_font.isRightToLeft();
1072 unsigned int count = running_font.latexWriteEndChanges(os,
1073 bparams, runparams, basefont, basefont, closeLanguage);
1075 // if any font properties were closed, update the running_font,
1076 // making sure, however, to leave the language as it was
1078 // FIXME: probably a better way to keep track of the old
1079 // language, than copying the entire font?
1080 Font const copy_font(running_font);
1081 basefont = owner_->getLayoutFont(bparams, outerfont);
1082 running_font = basefont;
1084 running_font.setLanguage(copy_font.language());
1085 // leave font open if language is still open
1086 open_font = (running_font.language() == basefont.language());
1088 runparams.local_font = &basefont;
1095 tmp = inset->latex(os, runparams);
1096 } catch (EncodingException & e) {
1097 // add location information and throw again.
1104 if (running_font.language()->lang() == "farsi")
1111 texrow.newlines(tmp);
1112 texrow.start(owner_->id(), i + 1);
1115 column += (unsigned int)(os.tellp() - len);
1118 if (owner_->isDeleted(i))
1119 --runparams.inDeletedInset;
1123 void Paragraph::Private::latexSpecialChar(
1125 OutputParams const & runparams,
1126 Font const & running_font,
1127 Change const & running_change,
1128 Layout const & style,
1130 unsigned int & column)
1132 char_type const c = text_[i];
1134 if (style.pass_thru || runparams.pass_thru) {
1136 // FIXME UNICODE: This can fail if c cannot
1137 // be encoded in the current encoding.
1142 // If T1 font encoding is used, use the special
1143 // characters it provides.
1144 // NOTE: some languages reset the font encoding
1146 if (!running_font.language()->internalFontEncoding()
1147 && lyxrc.fontenc == "T1" && latexSpecialT1(c, os, i, column))
1150 // \tt font needs special treatment
1151 if (running_font.fontInfo().family() == TYPEWRITER_FAMILY
1152 && latexSpecialTypewriter(c, os, i, column))
1155 // Otherwise, we use what LaTeX provides us.
1158 os << "\\textbackslash{}";
1162 os << "\\textless{}";
1166 os << "\\textgreater{}";
1170 os << "\\textbar{}";
1177 os << "\\char`\\\"{}";
1182 case '%': case '#': case '{':
1190 os << "\\textasciitilde{}";
1195 os << "\\textasciicircum{}";
1202 // avoid being mistaken for optional arguments
1210 // Blanks are printed before font switching.
1211 // Sure? I am not! (try nice-latex)
1212 // I am sure it's correct. LyX might be smarter
1213 // in the future, but for now, nothing wrong is
1219 if (latexSpecialPhrase(os, i, column, runparams))
1225 Encoding const & encoding = *(runparams.encoding);
1226 if (i + 1 < int(text_.size())) {
1227 char_type next = text_[i + 1];
1228 if (Encodings::isCombiningChar(next)) {
1229 column += latexSurrogatePair(os, c, next, runparams) - 1;
1235 docstring const latex = encoding.latexChar(c);
1236 if (Encodings::isKnownScriptChar(c, script)
1237 && prefixIs(latex, from_ascii("\\" + script)))
1238 column += writeScriptChars(os, latex,
1239 running_change, encoding, i) - 1;
1240 else if (latex.length() > 1 && latex[latex.length() - 1] != '}') {
1241 // Prevent eating of a following
1242 // space or command corruption by
1243 // following characters
1244 column += latex.length() + 1;
1245 os << latex << "{}";
1247 column += latex.length() - 1;
1255 bool Paragraph::Private::latexSpecialT1(char_type const c, odocstream & os,
1256 pos_type i, unsigned int & column)
1262 // In T1 encoding, these characters exist
1263 // but we should avoid ligatures
1264 if (i + 1 >= int(text_.size()) || text_[i + 1] != c)
1266 os << "\\textcompwordmark{}";
1273 // soul.sty breaks with \char`\"
1274 os << "\\textquotedbl{}";
1283 bool Paragraph::Private::latexSpecialTypewriter(char_type const c, odocstream & os,
1284 pos_type i, unsigned int & column)
1288 // within \ttfamily, "--" is merged to "-" (no endash)
1289 // so we avoid this rather irritating ligature
1290 if (i + 1 < int(text_.size()) && text_[i + 1] == '-') {
1297 // everything else has to be checked separately
1298 // (depending on the encoding)
1305 bool Paragraph::Private::latexSpecialPhrase(odocstream & os, pos_type & i,
1306 unsigned int & column, OutputParams const & runparams)
1308 // FIXME: if we have "LaTeX" with a font
1309 // change in the middle (before the 'T', then
1310 // the "TeX" part is still special cased.
1311 // Really we should only operate this on
1312 // "words" for some definition of word
1314 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1315 if (!isTextAt(special_phrases[pnr].phrase, i))
1317 if (runparams.moving_arg)
1319 os << special_phrases[pnr].macro;
1320 i += special_phrases[pnr].phrase.length() - 1;
1321 column += special_phrases[pnr].macro.length() - 1;
1328 void Paragraph::Private::validate(LaTeXFeatures & features) const
1330 if (layout_->inpreamble && inset_owner_) {
1331 Buffer const & buf = inset_owner_->buffer();
1332 BufferParams const & bp = buf.params();
1335 // Using a string stream here circumvents the encoding
1336 // switching machinery of odocstream. Therefore the
1337 // output is wrong if this paragraph contains content
1338 // that needs to switch encoding.
1339 odocstringstream ods;
1340 ods << '\\' << from_ascii(layout_->latexname());
1341 // we have to provide all the optional arguments here, even though
1342 // the last one is the only one we care about.
1343 // Separate handling of optional argument inset.
1344 if (layout_->optargs != 0 || layout_->reqargs != 0)
1345 latexArgInsets(*owner_, ods, features.runparams(),
1346 layout_->reqargs, layout_->optargs);
1348 ods << from_ascii(layout_->latexparam());
1349 docstring::size_type const length = ods.str().length();
1350 // this will output "{" at the beginning, but not at the end
1351 owner_->latex(bp, f, ods, tr, features.runparams(), 0, -1, true);
1352 if (ods.str().length() > length) {
1354 string const snippet = to_utf8(ods.str());
1355 features.addPreambleSnippet(snippet);
1359 if (features.runparams().flavor == OutputParams::HTML
1360 && layout_->htmltitle()) {
1361 features.setHTMLTitle(owner_->asString(AS_STR_INSETS));
1364 // check the params.
1365 if (!params_.spacing().isDefault())
1366 features.require("setspace");
1369 features.useLayout(layout_->name());
1372 fontlist_.validate(features);
1374 // then the indentation
1375 if (!params_.leftIndent().zero())
1376 features.require("ParagraphLeftIndent");
1379 InsetList::const_iterator icit = insetlist_.begin();
1380 InsetList::const_iterator iend = insetlist_.end();
1381 for (; icit != iend; ++icit) {
1383 icit->inset->validate(features);
1384 if (layout_->needprotect &&
1385 icit->inset->lyxCode() == FOOT_CODE)
1386 features.require("NeedLyXFootnoteCode");
1390 // then the contents
1391 for (pos_type i = 0; i < int(text_.size()) ; ++i) {
1392 for (size_t pnr = 0; pnr < phrases_nr; ++pnr) {
1393 if (!special_phrases[pnr].builtin
1394 && isTextAt(special_phrases[pnr].phrase, i)) {
1395 features.require(special_phrases[pnr].phrase);
1399 Encodings::validate(text_[i], features);
1403 /////////////////////////////////////////////////////////////////////
1407 /////////////////////////////////////////////////////////////////////
1410 Layout const emptyParagraphLayout;
1413 Paragraph::Paragraph()
1414 : d(new Paragraph::Private(this, emptyParagraphLayout))
1421 Paragraph::Paragraph(Paragraph const & par)
1422 : itemdepth(par.itemdepth),
1423 d(new Paragraph::Private(*par.d, this))
1429 Paragraph::Paragraph(Paragraph const & par, pos_type beg, pos_type end)
1430 : itemdepth(par.itemdepth),
1431 d(new Paragraph::Private(*par.d, this, beg, end))
1437 Paragraph & Paragraph::operator=(Paragraph const & par)
1439 // needed as we will destroy the private part before copying it
1441 itemdepth = par.itemdepth;
1445 d = new Private(*par.d, this);
1452 Paragraph::~Paragraph()
1461 // this shall be called just before every "os << ..." action.
1462 void flushString(ostream & os, docstring & s)
1471 void Paragraph::write(ostream & os, BufferParams const & bparams,
1472 depth_type & dth) const
1474 // The beginning or end of a deeper (i.e. nested) area?
1475 if (dth != d->params_.depth()) {
1476 if (d->params_.depth() > dth) {
1477 while (d->params_.depth() > dth) {
1478 os << "\n\\begin_deeper";
1482 while (d->params_.depth() < dth) {
1483 os << "\n\\end_deeper";
1489 // First write the layout
1490 os << "\n\\begin_layout " << to_utf8(d->layout_->name()) << '\n';
1492 d->params_.write(os);
1494 Font font1(inherit_font, bparams.language);
1496 Change running_change = Change(Change::UNCHANGED);
1498 // this string is used as a buffer to avoid repetitive calls
1499 // to to_utf8(), which turn out to be expensive (JMarc)
1500 docstring write_buffer;
1503 for (pos_type i = 0; i <= size(); ++i) {
1505 Change const change = lookupChange(i);
1506 if (change != running_change)
1507 flushString(os, write_buffer);
1508 Changes::lyxMarkChange(os, bparams, column, running_change, change);
1509 running_change = change;
1514 // Write font changes
1515 Font font2 = getFontSettings(bparams, i);
1516 if (font2 != font1) {
1517 flushString(os, write_buffer);
1518 font2.lyxWriteChanges(font1, os);
1523 char_type const c = d->text_[i];
1526 if (Inset const * inset = getInset(i)) {
1527 flushString(os, write_buffer);
1528 if (inset->directWrite()) {
1529 // international char, let it write
1530 // code directly so it's shorter in
1536 os << "\\begin_inset ";
1538 os << "\n\\end_inset\n\n";
1544 flushString(os, write_buffer);
1545 os << "\n\\backslash\n";
1549 flushString(os, write_buffer);
1550 if (i + 1 < size() && d->text_[i + 1] == ' ') {
1557 if ((column > 70 && c == ' ')
1559 flushString(os, write_buffer);
1563 // this check is to amend a bug. LyX sometimes
1564 // inserts '\0' this could cause problems.
1566 write_buffer.push_back(c);
1568 LYXERR0("NUL char in structure.");
1574 flushString(os, write_buffer);
1575 os << "\n\\end_layout\n";
1579 void Paragraph::validate(LaTeXFeatures & features) const
1581 d->validate(features);
1585 void Paragraph::insert(pos_type start, docstring const & str,
1586 Font const & font, Change const & change)
1588 for (size_t i = 0, n = str.size(); i != n ; ++i)
1589 insertChar(start + i, str[i], font, change);
1593 void Paragraph::appendChar(char_type c, Font const & font,
1594 Change const & change)
1597 d->changes_.insert(change, d->text_.size());
1598 // when appending characters, no need to update tables
1599 d->text_.push_back(c);
1600 setFont(d->text_.size() - 1, font);
1604 void Paragraph::appendString(docstring const & s, Font const & font,
1605 Change const & change)
1607 pos_type end = s.size();
1608 size_t oldsize = d->text_.size();
1609 size_t newsize = oldsize + end;
1610 size_t capacity = d->text_.capacity();
1611 if (newsize >= capacity)
1612 d->text_.reserve(max(capacity + 100, newsize));
1614 // when appending characters, no need to update tables
1617 // FIXME: Optimize this!
1618 for (size_t i = oldsize; i != newsize; ++i) {
1620 d->changes_.insert(change, i);
1622 d->fontlist_.set(oldsize, font);
1623 d->fontlist_.set(newsize - 1, font);
1627 void Paragraph::insertChar(pos_type pos, char_type c,
1630 d->insertChar(pos, c, Change(trackChanges ?
1631 Change::INSERTED : Change::UNCHANGED));
1635 void Paragraph::insertChar(pos_type pos, char_type c,
1636 Font const & font, bool trackChanges)
1638 d->insertChar(pos, c, Change(trackChanges ?
1639 Change::INSERTED : Change::UNCHANGED));
1644 void Paragraph::insertChar(pos_type pos, char_type c,
1645 Font const & font, Change const & change)
1647 d->insertChar(pos, c, change);
1652 bool Paragraph::insertInset(pos_type pos, Inset * inset,
1653 Font const & font, Change const & change)
1655 bool const success = insertInset(pos, inset, change);
1656 // Set the font/language of the inset...
1662 void Paragraph::resetFonts(Font const & font)
1664 d->fontlist_.clear();
1665 d->fontlist_.set(0, font);
1666 d->fontlist_.set(d->text_.size() - 1, font);
1669 // Gets uninstantiated font setting at position.
1670 Font const & Paragraph::getFontSettings(BufferParams const & bparams,
1674 LYXERR0("pos: " << pos << " size: " << size());
1675 LASSERT(pos <= size(), /**/);
1678 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
1679 if (cit != d->fontlist_.end())
1682 if (pos == size() && !empty())
1683 return getFontSettings(bparams, pos - 1);
1685 // Optimisation: avoid a full font instantiation if there is no
1686 // language change from previous call.
1687 static Font previous_font;
1688 static Language const * previous_lang = 0;
1689 Language const * lang = getParLanguage(bparams);
1690 if (lang != previous_lang) {
1691 previous_lang = lang;
1692 previous_font = Font(inherit_font, lang);
1694 return previous_font;
1698 FontSpan Paragraph::fontSpan(pos_type pos) const
1700 LASSERT(pos <= size(), /**/);
1703 FontList::const_iterator cit = d->fontlist_.begin();
1704 FontList::const_iterator end = d->fontlist_.end();
1705 for (; cit != end; ++cit) {
1706 if (cit->pos() >= pos) {
1707 if (pos >= beginOfBody())
1708 return FontSpan(max(start, beginOfBody()),
1711 return FontSpan(start,
1712 min(beginOfBody() - 1,
1715 start = cit->pos() + 1;
1718 // This should not happen, but if so, we take no chances.
1719 // LYXERR0("Paragraph::getEndPosOfFontSpan: This should not happen!");
1720 return FontSpan(pos, pos);
1724 // Gets uninstantiated font setting at position 0
1725 Font const & Paragraph::getFirstFontSettings(BufferParams const & bparams) const
1727 if (!empty() && !d->fontlist_.empty())
1728 return d->fontlist_.begin()->font();
1730 // Optimisation: avoid a full font instantiation if there is no
1731 // language change from previous call.
1732 static Font previous_font;
1733 static Language const * previous_lang = 0;
1734 if (bparams.language != previous_lang) {
1735 previous_lang = bparams.language;
1736 previous_font = Font(inherit_font, bparams.language);
1739 return previous_font;
1743 // Gets the fully instantiated font at a given position in a paragraph
1744 // This is basically the same function as Text::GetFont() in text2.cpp.
1745 // The difference is that this one is used for generating the LaTeX file,
1746 // and thus cosmetic "improvements" are disallowed: This has to deliver
1747 // the true picture of the buffer. (Asger)
1748 Font const Paragraph::getFont(BufferParams const & bparams, pos_type pos,
1749 Font const & outerfont) const
1751 LASSERT(pos >= 0, /**/);
1753 Font font = getFontSettings(bparams, pos);
1755 pos_type const body_pos = beginOfBody();
1756 FontInfo & fi = font.fontInfo();
1758 fi.realize(d->layout_->labelfont);
1760 fi.realize(d->layout_->font);
1762 fi.realize(outerfont.fontInfo());
1763 fi.realize(bparams.getFont().fontInfo());
1769 Font const Paragraph::getLabelFont
1770 (BufferParams const & bparams, Font const & outerfont) const
1772 FontInfo tmpfont = d->layout_->labelfont;
1773 tmpfont.realize(outerfont.fontInfo());
1774 tmpfont.realize(bparams.getFont().fontInfo());
1775 return Font(tmpfont, getParLanguage(bparams));
1779 Font const Paragraph::getLayoutFont
1780 (BufferParams const & bparams, Font const & outerfont) const
1782 FontInfo tmpfont = d->layout_->font;
1783 tmpfont.realize(outerfont.fontInfo());
1784 tmpfont.realize(bparams.getFont().fontInfo());
1785 return Font(tmpfont, getParLanguage(bparams));
1789 /// Returns the height of the highest font in range
1790 FontSize Paragraph::highestFontInRange
1791 (pos_type startpos, pos_type endpos, FontSize def_size) const
1793 return d->fontlist_.highestInRange(startpos, endpos, def_size);
1797 char_type Paragraph::getUChar(BufferParams const & bparams, pos_type pos) const
1799 char_type c = d->text_[pos];
1800 if (!lyxrc.rtl_support)
1830 if (uc != c && getFontSettings(bparams, pos).isRightToLeft())
1836 void Paragraph::setFont(pos_type pos, Font const & font)
1838 LASSERT(pos <= size(), /**/);
1840 // First, reduce font against layout/label font
1841 // Update: The setCharFont() routine in text2.cpp already
1842 // reduces font, so we don't need to do that here. (Asger)
1844 d->fontlist_.set(pos, font);
1848 void Paragraph::makeSameLayout(Paragraph const & par)
1850 d->layout_ = par.d->layout_;
1851 d->params_ = par.d->params_;
1855 bool Paragraph::stripLeadingSpaces(bool trackChanges)
1857 if (isFreeSpacing())
1863 while (pos < size() && (isNewline(pos) || isLineSeparator(pos))) {
1864 if (eraseChar(pos, trackChanges))
1870 return count > 0 || pos > 0;
1874 bool Paragraph::hasSameLayout(Paragraph const & par) const
1876 return par.d->layout_ == d->layout_
1877 && d->params_.sameLayout(par.d->params_);
1881 depth_type Paragraph::getDepth() const
1883 return d->params_.depth();
1887 depth_type Paragraph::getMaxDepthAfter() const
1889 if (d->layout_->isEnvironment())
1890 return d->params_.depth() + 1;
1892 return d->params_.depth();
1896 char Paragraph::getAlign() const
1898 if (d->params_.align() == LYX_ALIGN_LAYOUT)
1899 return d->layout_->align;
1901 return d->params_.align();
1905 docstring const & Paragraph::labelString() const
1907 return d->params_.labelString();
1911 // the next two functions are for the manual labels
1912 docstring const Paragraph::getLabelWidthString() const
1914 if (d->layout_->margintype == MARGIN_MANUAL
1915 || d->layout_->latextype == LATEX_BIB_ENVIRONMENT)
1916 return d->params_.labelWidthString();
1918 return _("Senseless with this layout!");
1922 void Paragraph::setLabelWidthString(docstring const & s)
1924 d->params_.labelWidthString(s);
1928 docstring Paragraph::expandLabel(Layout const & layout,
1929 BufferParams const & bparams) const
1931 return expandParagraphLabel(layout, bparams, true);
1935 docstring Paragraph::expandDocBookLabel(Layout const & layout,
1936 BufferParams const & bparams) const
1938 return expandParagraphLabel(layout, bparams, false);
1942 docstring Paragraph::expandParagraphLabel(Layout const & layout,
1943 BufferParams const & bparams, bool process_appendix) const
1945 DocumentClass const & tclass = bparams.documentClass();
1946 string const & lang = getParLanguage(bparams)->code();
1947 bool const in_appendix = process_appendix && d->params_.appendix();
1948 docstring fmt = translateIfPossible(layout.labelstring(in_appendix), lang);
1950 if (fmt.empty() && layout.labeltype == LABEL_COUNTER
1951 && !layout.counter.empty())
1952 return tclass.counters().theCounter(layout.counter, lang);
1954 // handle 'inherited level parts' in 'fmt',
1955 // i.e. the stuff between '@' in '@Section@.\arabic{subsection}'
1956 size_t const i = fmt.find('@', 0);
1957 if (i != docstring::npos) {
1958 size_t const j = fmt.find('@', i + 1);
1959 if (j != docstring::npos) {
1960 docstring parent(fmt, i + 1, j - i - 1);
1961 docstring label = from_ascii("??");
1962 if (tclass.hasLayout(parent))
1963 docstring label = expandParagraphLabel(tclass[parent], bparams,
1965 fmt = docstring(fmt, 0, i) + label
1966 + docstring(fmt, j + 1, docstring::npos);
1970 return tclass.counters().counterLabel(fmt, lang);
1974 void Paragraph::applyLayout(Layout const & new_layout)
1976 d->layout_ = &new_layout;
1977 LyXAlignment const oldAlign = d->params_.align();
1979 if (!(oldAlign & d->layout_->alignpossible)) {
1980 frontend::Alert::warning(_("Alignment not permitted"),
1981 _("The new layout does not permit the alignment previously used.\nSetting to default."));
1982 d->params_.align(LYX_ALIGN_LAYOUT);
1987 pos_type Paragraph::beginOfBody() const
1989 return d->begin_of_body_;
1993 void Paragraph::setBeginOfBody()
1995 if (d->layout_->labeltype != LABEL_MANUAL) {
1996 d->begin_of_body_ = 0;
2000 // Unroll the first two cycles of the loop
2001 // and remember the previous character to
2002 // remove unnecessary getChar() calls
2004 pos_type end = size();
2005 if (i < end && !isNewline(i)) {
2007 char_type previous_char = 0;
2010 previous_char = d->text_[i];
2011 if (!isNewline(i)) {
2013 while (i < end && previous_char != ' ') {
2018 previous_char = temp;
2024 d->begin_of_body_ = i;
2028 bool Paragraph::allowParagraphCustomization() const
2030 return inInset().allowParagraphCustomization();
2034 bool Paragraph::usePlainLayout() const
2036 return inInset().usePlainLayout();
2042 // paragraphs inside floats need different alignment tags to avoid
2045 bool noTrivlistCentering(InsetCode code)
2047 return code == FLOAT_CODE
2048 || code == WRAP_CODE
2049 || code == CELL_CODE;
2053 string correction(string const & orig)
2055 if (orig == "flushleft")
2056 return "raggedright";
2057 if (orig == "flushright")
2058 return "raggedleft";
2059 if (orig == "center")
2065 string const corrected_env(string const & suffix, string const & env,
2066 InsetCode code, bool const lastpar)
2068 string output = suffix + "{";
2069 if (noTrivlistCentering(code)) {
2071 // the last paragraph in non-trivlist-aligned
2072 // context is special (to avoid unwanted whitespace)
2073 if (suffix == "\\begin")
2074 return "\\" + correction(env) + "{}";
2077 output += correction(env);
2081 if (suffix == "\\begin")
2087 void adjust_row_column(string const & str, TexRow & texrow, int & column)
2089 if (!contains(str, "\n"))
2090 column += str.size();
2094 column = rsplit(str, tmp, '\n').size();
2101 int Paragraph::Private::startTeXParParams(BufferParams const & bparams,
2102 odocstream & os, TexRow & texrow,
2103 OutputParams const & runparams) const
2107 if (params_.noindent()) {
2108 os << "\\noindent ";
2112 LyXAlignment const curAlign = params_.align();
2114 if (curAlign == layout_->align)
2118 case LYX_ALIGN_NONE:
2119 case LYX_ALIGN_BLOCK:
2120 case LYX_ALIGN_LAYOUT:
2121 case LYX_ALIGN_SPECIAL:
2122 case LYX_ALIGN_DECIMAL:
2124 case LYX_ALIGN_LEFT:
2125 case LYX_ALIGN_RIGHT:
2126 case LYX_ALIGN_CENTER:
2127 if (runparams.moving_arg) {
2134 string const begin_tag = "\\begin";
2135 InsetCode code = ownerCode();
2136 bool const lastpar = runparams.isLastPar;
2139 case LYX_ALIGN_NONE:
2140 case LYX_ALIGN_BLOCK:
2141 case LYX_ALIGN_LAYOUT:
2142 case LYX_ALIGN_SPECIAL:
2143 case LYX_ALIGN_DECIMAL:
2145 case LYX_ALIGN_LEFT: {
2147 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2148 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2150 output = corrected_env(begin_tag, "flushright", code, lastpar);
2151 os << from_ascii(output);
2152 adjust_row_column(output, texrow, column);
2154 } case LYX_ALIGN_RIGHT: {
2156 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2157 output = corrected_env(begin_tag, "flushright", code, lastpar);
2159 output = corrected_env(begin_tag, "flushleft", code, lastpar);
2160 os << from_ascii(output);
2161 adjust_row_column(output, texrow, column);
2163 } case LYX_ALIGN_CENTER: {
2165 output = corrected_env(begin_tag, "center", code, lastpar);
2166 os << from_ascii(output);
2167 adjust_row_column(output, texrow, column);
2176 int Paragraph::Private::endTeXParParams(BufferParams const & bparams,
2177 odocstream & os, TexRow & texrow,
2178 OutputParams const & runparams) const
2182 LyXAlignment const curAlign = params_.align();
2184 if (curAlign == layout_->align)
2188 case LYX_ALIGN_NONE:
2189 case LYX_ALIGN_BLOCK:
2190 case LYX_ALIGN_LAYOUT:
2191 case LYX_ALIGN_SPECIAL:
2192 case LYX_ALIGN_DECIMAL:
2194 case LYX_ALIGN_LEFT:
2195 case LYX_ALIGN_RIGHT:
2196 case LYX_ALIGN_CENTER:
2197 if (runparams.moving_arg) {
2204 string const end_tag = "\n\\par\\end";
2205 InsetCode code = ownerCode();
2206 bool const lastpar = runparams.isLastPar;
2209 case LYX_ALIGN_NONE:
2210 case LYX_ALIGN_BLOCK:
2211 case LYX_ALIGN_LAYOUT:
2212 case LYX_ALIGN_SPECIAL:
2213 case LYX_ALIGN_DECIMAL:
2215 case LYX_ALIGN_LEFT: {
2217 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2218 output = corrected_env(end_tag, "flushleft", code, lastpar);
2220 output = corrected_env(end_tag, "flushright", code, lastpar);
2221 os << from_ascii(output);
2222 adjust_row_column(output, texrow, column);
2224 } case LYX_ALIGN_RIGHT: {
2226 if (owner_->getParLanguage(bparams)->babel() != "hebrew")
2227 output = corrected_env(end_tag, "flushright", code, lastpar);
2229 output = corrected_env(end_tag, "flushleft", code, lastpar);
2230 os << from_ascii(output);
2231 adjust_row_column(output, texrow, column);
2233 } case LYX_ALIGN_CENTER: {
2235 output = corrected_env(end_tag, "center", code, lastpar);
2236 os << from_ascii(output);
2237 adjust_row_column(output, texrow, column);
2246 // This one spits out the text of the paragraph
2247 void Paragraph::latex(BufferParams const & bparams,
2248 Font const & outerfont,
2249 odocstream & os, TexRow & texrow,
2250 OutputParams const & runparams,
2251 int start_pos, int end_pos, bool force) const
2253 LYXERR(Debug::LATEX, "Paragraph::latex... " << this);
2255 // FIXME This check should not be needed. Perhaps issue an
2256 // error if it triggers.
2257 Layout const & style = inInset().forcePlainLayout() ?
2258 bparams.documentClass().plainLayout() : *d->layout_;
2260 if (!force && style.inpreamble)
2263 bool const allowcust = allowParagraphCustomization();
2265 // Current base font for all inherited font changes, without any
2266 // change caused by an individual character, except for the language:
2267 // It is set to the language of the first character.
2268 // As long as we are in the label, this font is the base font of the
2269 // label. Before the first body character it is set to the base font
2273 // Maybe we have to create a optional argument.
2274 pos_type body_pos = beginOfBody();
2275 unsigned int column = 0;
2278 // the optional argument is kept in curly brackets in
2279 // case it contains a ']'
2282 basefont = getLabelFont(bparams, outerfont);
2284 basefont = getLayoutFont(bparams, outerfont);
2287 // Which font is currently active?
2288 Font running_font(basefont);
2289 // Do we have an open font change?
2290 bool open_font = false;
2292 Change runningChange = Change(Change::UNCHANGED);
2294 Encoding const * const prev_encoding = runparams.encoding;
2296 texrow.start(id(), 0);
2298 // if the paragraph is empty, the loop will not be entered at all
2300 if (style.isCommand()) {
2305 column += d->startTeXParParams(bparams, os, texrow,
2309 for (pos_type i = 0; i < size(); ++i) {
2310 // First char in paragraph or after label?
2311 if (i == body_pos) {
2314 column += running_font.latexWriteEndChanges(
2315 os, bparams, runparams,
2316 basefont, basefont);
2319 basefont = getLayoutFont(bparams, outerfont);
2320 running_font = basefont;
2322 column += Changes::latexMarkChange(os, bparams,
2323 runningChange, Change(Change::UNCHANGED),
2325 runningChange = Change(Change::UNCHANGED);
2330 if (style.isCommand()) {
2336 column += d->startTeXParParams(bparams, os,
2341 Change const & change = runparams.inDeletedInset ? runparams.changeOfDeletedInset
2344 if (bparams.outputChanges && runningChange != change) {
2346 column += running_font.latexWriteEndChanges(
2347 os, bparams, runparams, basefont, basefont);
2350 basefont = getLayoutFont(bparams, outerfont);
2351 running_font = basefont;
2353 column += Changes::latexMarkChange(os, bparams, runningChange,
2355 runningChange = change;
2358 // do not output text which is marked deleted
2359 // if change tracking output is disabled
2360 if (!bparams.outputChanges && change.deleted()) {
2366 // Fully instantiated font
2367 Font const font = getFont(bparams, i, outerfont);
2369 Font const last_font = running_font;
2371 // Do we need to close the previous font?
2373 (font != running_font ||
2374 font.language() != running_font.language()))
2376 column += running_font.latexWriteEndChanges(
2377 os, bparams, runparams, basefont,
2378 (i == body_pos-1) ? basefont : font);
2379 running_font = basefont;
2383 string const running_lang = runparams.use_polyglossia ?
2384 running_font.language()->polyglossia() : running_font.language()->babel();
2385 // close babel's font environment before opening CJK.
2386 string const lang_end_command = runparams.use_polyglossia ?
2387 "\\end{$$lang}" : lyxrc.language_command_end;
2388 if (!running_lang.empty() &&
2389 font.language()->encoding()->package() == Encoding::CJK) {
2390 string end_tag = subst(lang_end_command,
2393 os << from_ascii(end_tag);
2394 column += end_tag.length();
2397 // Switch file encoding if necessary (and allowed)
2398 if (!runparams.pass_thru && !style.pass_thru &&
2399 runparams.encoding->package() != Encoding::none &&
2400 font.language()->encoding()->package() != Encoding::none) {
2401 pair<bool, int> const enc_switch = switchEncoding(os, bparams,
2402 runparams, *(font.language()->encoding()));
2403 if (enc_switch.first) {
2404 column += enc_switch.second;
2405 runparams.encoding = font.language()->encoding();
2409 char_type const c = d->text_[i];
2411 // Do we need to change font?
2412 if ((font != running_font ||
2413 font.language() != running_font.language()) &&
2416 odocstringstream ods;
2417 column += font.latexWriteStartChanges(ods, bparams,
2418 runparams, basefont,
2420 running_font = font;
2422 docstring fontchange = ods.str();
2423 // check whether the fontchange ends with a \\textcolor
2424 // modifier and the text starts with a space (bug 4473)
2425 docstring const last_modifier = rsplit(fontchange, '\\');
2426 if (prefixIs(last_modifier, from_ascii("textcolor")) && c == ' ')
2427 os << fontchange << from_ascii("{}");
2428 // check if the fontchange ends with a trailing blank
2429 // (like "\small " (see bug 3382)
2430 else if (suffixIs(fontchange, ' ') && c == ' ')
2431 os << fontchange.substr(0, fontchange.size() - 1)
2432 << from_ascii("{}");
2437 // FIXME: think about end_pos implementation...
2438 if (c == ' ' && i >= start_pos && (end_pos == -1 || i < end_pos)) {
2439 // FIXME: integrate this case in latexSpecialChar
2440 // Do not print the separation of the optional argument
2441 // if style.pass_thru is false. This works because
2442 // latexSpecialChar ignores spaces if
2443 // style.pass_thru is false.
2444 if (i != body_pos - 1) {
2445 if (d->simpleTeXBlanks(
2446 runparams, os, texrow,
2447 i, column, font, style)) {
2448 // A surrogate pair was output. We
2449 // must not call latexSpecialChar
2450 // in this iteration, since it would output
2451 // the combining character again.
2458 OutputParams rp = runparams;
2459 rp.free_spacing = style.free_spacing;
2460 rp.local_font = &font;
2461 rp.intitle = style.intitle;
2463 // Two major modes: LaTeX or plain
2464 // Handle here those cases common to both modes
2465 // and then split to handle the two modes separately.
2466 if (c == META_INSET) {
2467 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2468 d->latexInset(bparams, os,
2469 texrow, rp, running_font,
2470 basefont, outerfont, open_font,
2471 runningChange, style, i, column);
2474 if (i >= start_pos && (end_pos == -1 || i < end_pos)) {
2476 d->latexSpecialChar(os, rp, running_font, runningChange,
2478 } catch (EncodingException & e) {
2479 if (runparams.dryrun) {
2480 os << "<" << _("LyX Warning: ")
2481 << _("uncodable character") << " '";
2485 // add location information and throw again.
2494 // Set the encoding to that returned from latexSpecialChar (see
2495 // comment for encoding member in OutputParams.h)
2496 runparams.encoding = rp.encoding;
2499 // If we have an open font definition, we have to close it
2501 #ifdef FIXED_LANGUAGE_END_DETECTION
2503 running_font.latexWriteEndChanges(os, bparams,
2504 runparams, basefont,
2505 next_->getFont(bparams, 0, outerfont));
2507 running_font.latexWriteEndChanges(os, bparams,
2508 runparams, basefont, basefont);
2511 //FIXME: For now we ALWAYS have to close the foreign font settings if they are
2512 //FIXME: there as we start another \selectlanguage with the next paragraph if
2513 //FIXME: we are in need of this. This should be fixed sometime (Jug)
2514 running_font.latexWriteEndChanges(os, bparams, runparams,
2515 basefont, basefont);
2519 column += Changes::latexMarkChange(os, bparams, runningChange,
2520 Change(Change::UNCHANGED), runparams);
2522 // Needed if there is an optional argument but no contents.
2523 if (body_pos > 0 && body_pos == size()) {
2527 if (allowcust && d->endTeXParParams(bparams, os, texrow, runparams)
2528 && runparams.encoding != prev_encoding) {
2529 runparams.encoding = prev_encoding;
2530 if (!runparams.isFullUnicode())
2531 os << setEncoding(prev_encoding->iconvName());
2534 LYXERR(Debug::LATEX, "Paragraph::latex... done " << this);
2538 bool Paragraph::emptyTag() const
2540 for (pos_type i = 0; i < size(); ++i) {
2541 if (Inset const * inset = getInset(i)) {
2542 InsetCode lyx_code = inset->lyxCode();
2543 // FIXME testing like that is wrong. What is
2545 if (lyx_code != TOC_CODE &&
2546 lyx_code != INCLUDE_CODE &&
2547 lyx_code != GRAPHICS_CODE &&
2548 lyx_code != ERT_CODE &&
2549 lyx_code != LISTINGS_CODE &&
2550 lyx_code != FLOAT_CODE &&
2551 lyx_code != TABULAR_CODE) {
2555 char_type c = d->text_[i];
2556 if (c != ' ' && c != '\t')
2564 string Paragraph::getID(Buffer const & buf, OutputParams const & runparams)
2567 for (pos_type i = 0; i < size(); ++i) {
2568 if (Inset const * inset = getInset(i)) {
2569 InsetCode lyx_code = inset->lyxCode();
2570 if (lyx_code == LABEL_CODE) {
2571 InsetLabel const * const il = static_cast<InsetLabel const *>(inset);
2572 docstring const & id = il->getParam("name");
2573 return "id='" + to_utf8(sgml::cleanID(buf, runparams, id)) + "'";
2581 pos_type Paragraph::firstWordDocBook(odocstream & os, OutputParams const & runparams)
2585 for (i = 0; i < size(); ++i) {
2586 if (Inset const * inset = getInset(i)) {
2587 inset->docbook(os, runparams);
2589 char_type c = d->text_[i];
2592 os << sgml::escapeChar(c);
2599 pos_type Paragraph::firstWordLyXHTML(XHTMLStream & xs, OutputParams const & runparams)
2603 for (i = 0; i < size(); ++i) {
2604 if (Inset const * inset = getInset(i)) {
2605 inset->xhtml(xs, runparams);
2607 char_type c = d->text_[i];
2617 bool Paragraph::Private::onlyText(Buffer const & buf, Font const & outerfont, pos_type initial) const
2620 pos_type size = text_.size();
2621 for (pos_type i = initial; i < size; ++i) {
2622 Font font = owner_->getFont(buf.params(), i, outerfont);
2623 if (text_[i] == META_INSET)
2625 if (i != initial && font != font_old)
2634 void Paragraph::simpleDocBookOnePar(Buffer const & buf,
2636 OutputParams const & runparams,
2637 Font const & outerfont,
2638 pos_type initial) const
2640 bool emph_flag = false;
2642 Layout const & style = *d->layout_;
2644 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2646 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2649 // parsing main loop
2650 for (pos_type i = initial; i < size(); ++i) {
2651 Font font = getFont(buf.params(), i, outerfont);
2653 // handle <emphasis> tag
2654 if (font_old.emph() != font.fontInfo().emph()) {
2655 if (font.fontInfo().emph() == FONT_ON) {
2658 } else if (i != initial) {
2659 os << "</emphasis>";
2664 if (Inset const * inset = getInset(i)) {
2665 inset->docbook(os, runparams);
2667 char_type c = d->text_[i];
2669 if (style.pass_thru)
2672 os << sgml::escapeChar(c);
2674 font_old = font.fontInfo();
2678 os << "</emphasis>";
2681 if (style.free_spacing)
2683 if (style.pass_thru && !d->onlyText(buf, outerfont, initial))
2688 docstring Paragraph::simpleLyXHTMLOnePar(Buffer const & buf,
2690 OutputParams const & runparams,
2691 Font const & outerfont,
2692 pos_type initial) const
2696 bool emph_flag = false;
2697 bool bold_flag = false;
2700 Layout const & style = *d->layout_;
2702 if (!runparams.for_toc && runparams.html_make_pars) {
2703 // generate a magic label for this paragraph
2704 string const attr = "id='" + magicLabel() + "'";
2705 xs << html::CompTag("a", attr);
2709 style.labeltype == LABEL_MANUAL ? style.labelfont : style.font;
2711 // parsing main loop
2712 for (pos_type i = initial; i < size(); ++i) {
2713 // let's not show deleted material in the output
2717 Font font = getFont(buf.params(), i, outerfont);
2720 if (font_old.emph() != font.fontInfo().emph()) {
2721 if (font.fontInfo().emph() == FONT_ON) {
2722 xs << html::StartTag("em");
2724 } else if (emph_flag && i != initial) {
2725 xs << html::EndTag("em");
2730 if (font_old.series() != font.fontInfo().series()) {
2731 if (font.fontInfo().series() == BOLD_SERIES) {
2732 xs << html::StartTag("strong");
2734 } else if (bold_flag && i != initial) {
2735 xs << html::EndTag("strong");
2740 // Other such tags? What about the other text ranges?
2742 Inset const * inset = getInset(i);
2744 if (!runparams.for_toc || inset->isInToc()) {
2745 OutputParams np = runparams;
2746 if (!inset->getLayout().htmlisblock())
2747 np.html_in_par = true;
2748 retval += inset->xhtml(xs, np);
2751 char_type c = d->text_[i];
2753 if (style.pass_thru)
2755 else if (c == '-') {
2758 if (j < size() && d->text_[j] == '-') {
2760 if (j < size() && d->text_[j] == '-') {
2761 str += from_ascii("—");
2764 str += from_ascii("–");
2770 // We don't want to escape the entities. Note that
2771 // it is safe to do this, since str can otherwise
2772 // only be "-". E.g., it can't be "<".
2773 xs << XHTMLStream::ESCAPE_NONE << str;
2777 font_old = font.fontInfo();
2785 bool Paragraph::isHfill(pos_type pos) const
2787 Inset const * inset = getInset(pos);
2788 return inset && (inset->lyxCode() == SPACE_CODE &&
2789 inset->isStretchableSpace());
2793 bool Paragraph::isNewline(pos_type pos) const
2795 Inset const * inset = getInset(pos);
2796 return inset && inset->lyxCode() == NEWLINE_CODE;
2800 bool Paragraph::isLineSeparator(pos_type pos) const
2802 char_type const c = d->text_[pos];
2803 if (isLineSeparatorChar(c))
2805 Inset const * inset = getInset(pos);
2806 return inset && inset->isLineSeparator();
2810 bool Paragraph::isWordSeparator(pos_type pos) const
2812 if (Inset const * inset = getInset(pos))
2813 return !inset->isLetter();
2814 char_type const c = d->text_[pos];
2815 // We want to pass the ' and escape chars to the spellchecker
2816 static docstring const quote = from_utf8(lyxrc.spellchecker_esc_chars + '\'');
2817 return (!isLetterChar(c) && !isDigit(c) && !contains(quote, c))
2822 bool Paragraph::isChar(pos_type pos) const
2824 if (Inset const * inset = getInset(pos))
2825 return inset->isChar();
2826 char_type const c = d->text_[pos];
2827 return !isLetterChar(c) && !isDigit(c) && !lyx::isSpace(c);
2831 bool Paragraph::isSpace(pos_type pos) const
2833 if (Inset const * inset = getInset(pos))
2834 return inset->isSpace();
2835 char_type const c = d->text_[pos];
2836 return lyx::isSpace(c);
2841 Paragraph::getParLanguage(BufferParams const & bparams) const
2844 return getFirstFontSettings(bparams).language();
2845 // FIXME: we should check the prev par as well (Lgb)
2846 return bparams.language;
2850 bool Paragraph::isRTL(BufferParams const & bparams) const
2852 return lyxrc.rtl_support
2853 && getParLanguage(bparams)->rightToLeft()
2854 && !inInset().getLayout().forceLTR();
2858 void Paragraph::changeLanguage(BufferParams const & bparams,
2859 Language const * from, Language const * to)
2861 // change language including dummy font change at the end
2862 for (pos_type i = 0; i <= size(); ++i) {
2863 Font font = getFontSettings(bparams, i);
2864 if (font.language() == from) {
2865 font.setLanguage(to);
2869 d->requestSpellCheck(size());
2873 bool Paragraph::isMultiLingual(BufferParams const & bparams) const
2875 Language const * doc_language = bparams.language;
2876 FontList::const_iterator cit = d->fontlist_.begin();
2877 FontList::const_iterator end = d->fontlist_.end();
2879 for (; cit != end; ++cit)
2880 if (cit->font().language() != ignore_language &&
2881 cit->font().language() != latex_language &&
2882 cit->font().language() != doc_language)
2888 void Paragraph::getLanguages(std::set<Language const *> & languages) const
2890 FontList::const_iterator cit = d->fontlist_.begin();
2891 FontList::const_iterator end = d->fontlist_.end();
2893 for (; cit != end; ++cit) {
2894 Language const * lang = cit->font().language();
2895 if (lang != ignore_language &&
2896 lang != latex_language)
2897 languages.insert(lang);
2902 docstring Paragraph::asString(int options) const
2904 return asString(0, size(), options);
2908 docstring Paragraph::asString(pos_type beg, pos_type end, int options) const
2910 odocstringstream os;
2913 && options & AS_STR_LABEL
2914 && !d->params_.labelString().empty())
2915 os << d->params_.labelString() << ' ';
2917 for (pos_type i = beg; i < end; ++i) {
2918 if ((options & AS_STR_SKIPDELETE) && isDeleted(i))
2920 char_type const c = d->text_[i];
2921 if (isPrintable(c) || c == '\t'
2922 || (c == '\n' && (options & AS_STR_NEWLINES)))
2924 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2925 getInset(i)->tocString(os);
2926 if (getInset(i)->asInsetMath())
2935 docstring Paragraph::stringify(pos_type beg, pos_type end, int options, OutputParams & runparams) const
2937 odocstringstream os;
2940 && options & AS_STR_LABEL
2941 && !d->params_.labelString().empty())
2942 os << d->params_.labelString() << ' ';
2944 for (pos_type i = beg; i < end; ++i) {
2945 char_type const c = d->text_[i];
2946 if (isPrintable(c) || c == '\t'
2947 || (c == '\n' && (options & AS_STR_NEWLINES)))
2949 else if (c == META_INSET && (options & AS_STR_INSETS)) {
2950 getInset(i)->plaintext(os, runparams);
2958 void Paragraph::setInsetOwner(Inset const * inset)
2960 d->inset_owner_ = inset;
2964 int Paragraph::id() const
2970 void Paragraph::setId(int id)
2976 Layout const & Paragraph::layout() const
2982 void Paragraph::setLayout(Layout const & layout)
2984 d->layout_ = &layout;
2988 void Paragraph::setDefaultLayout(DocumentClass const & tc)
2990 setLayout(tc.defaultLayout());
2994 void Paragraph::setPlainLayout(DocumentClass const & tc)
2996 setLayout(tc.plainLayout());
3000 void Paragraph::setPlainOrDefaultLayout(DocumentClass const & tclass)
3002 if (usePlainLayout())
3003 setPlainLayout(tclass);
3005 setDefaultLayout(tclass);
3009 Inset const & Paragraph::inInset() const
3011 LASSERT(d->inset_owner_, throw ExceptionMessage(BufferException,
3012 _("Memory problem"), _("Paragraph not properly initialized")));
3013 return *d->inset_owner_;
3017 ParagraphParameters & Paragraph::params()
3023 ParagraphParameters const & Paragraph::params() const
3029 bool Paragraph::isFreeSpacing() const
3031 if (d->layout_->free_spacing)
3033 return d->inset_owner_ && d->inset_owner_->isFreeSpacing();
3037 bool Paragraph::allowEmpty() const
3039 if (d->layout_->keepempty)
3041 return d->inset_owner_ && d->inset_owner_->allowEmpty();
3045 char_type Paragraph::transformChar(char_type c, pos_type pos) const
3047 if (!Encodings::isArabicChar(c))
3050 char_type prev_char = ' ';
3051 char_type next_char = ' ';
3053 for (pos_type i = pos - 1; i >= 0; --i) {
3054 char_type const par_char = d->text_[i];
3055 if (!Encodings::isArabicComposeChar(par_char)) {
3056 prev_char = par_char;
3061 for (pos_type i = pos + 1, end = size(); i < end; ++i) {
3062 char_type const par_char = d->text_[i];
3063 if (!Encodings::isArabicComposeChar(par_char)) {
3064 next_char = par_char;
3069 if (Encodings::isArabicChar(next_char)) {
3070 if (Encodings::isArabicChar(prev_char) &&
3071 !Encodings::isArabicSpecialChar(prev_char))
3072 return Encodings::transformChar(c, Encodings::FORM_MEDIAL);
3074 return Encodings::transformChar(c, Encodings::FORM_INITIAL);
3076 if (Encodings::isArabicChar(prev_char) &&
3077 !Encodings::isArabicSpecialChar(prev_char))
3078 return Encodings::transformChar(c, Encodings::FORM_FINAL);
3080 return Encodings::transformChar(c, Encodings::FORM_ISOLATED);
3085 int Paragraph::checkBiblio(Buffer const & buffer)
3088 // This is getting more and more a mess. ...We really should clean
3089 // up this bibitem issue for 1.6.
3091 // Add bibitem insets if necessary
3092 if (d->layout_->labeltype != LABEL_BIBLIO)
3095 bool hasbibitem = !d->insetlist_.empty()
3096 // Insist on it being in pos 0
3097 && d->text_[0] == META_INSET
3098 && d->insetlist_.begin()->inset->lyxCode() == BIBITEM_CODE;
3100 bool track_changes = buffer.params().trackChanges;
3105 // remove a bibitem in pos != 0
3106 // restore it later in pos 0 if necessary
3107 // (e.g. if a user inserts contents _before_ the item)
3108 // we're assuming there's only one of these, which there
3110 int erasedInsetPosition = -1;
3111 InsetList::iterator it = d->insetlist_.begin();
3112 InsetList::iterator end = d->insetlist_.end();
3113 for (; it != end; ++it)
3114 if (it->inset->lyxCode() == BIBITEM_CODE
3116 InsetCommand * olditem = it->inset->asInsetCommand();
3117 oldkey = olditem->getParam("key");
3118 oldlabel = olditem->getParam("label");
3119 erasedInsetPosition = it->pos;
3120 eraseChar(erasedInsetPosition, track_changes);
3124 // There was an InsetBibitem at the beginning, and we didn't
3125 // have to erase one.
3126 if (hasbibitem && erasedInsetPosition < 0)
3129 // There was an InsetBibitem at the beginning and we did have to
3130 // erase one. So we give its properties to the beginning inset.
3132 InsetCommand * inset = d->insetlist_.begin()->inset->asInsetCommand();
3133 if (!oldkey.empty())
3134 inset->setParam("key", oldkey);
3135 inset->setParam("label", oldlabel);
3136 return -erasedInsetPosition;
3139 // There was no inset at the beginning, so we need to create one with
3140 // the key and label of the one we erased.
3141 InsetBibitem * inset =
3142 new InsetBibitem(const_cast<Buffer *>(&buffer), InsetCommandParams(BIBITEM_CODE));
3143 // restore values of previously deleted item in this par.
3144 if (!oldkey.empty())
3145 inset->setParam("key", oldkey);
3146 inset->setParam("label", oldlabel);
3147 insertInset(0, inset,
3148 Change(track_changes ? Change::INSERTED : Change::UNCHANGED));
3154 void Paragraph::checkAuthors(AuthorList const & authorList)
3156 d->changes_.checkAuthors(authorList);
3160 bool Paragraph::isChanged(pos_type pos) const
3162 return lookupChange(pos).changed();
3166 bool Paragraph::isInserted(pos_type pos) const
3168 return lookupChange(pos).inserted();
3172 bool Paragraph::isDeleted(pos_type pos) const
3174 return lookupChange(pos).deleted();
3178 InsetList const & Paragraph::insetList() const
3180 return d->insetlist_;
3184 void Paragraph::setBuffer(Buffer & b)
3186 d->insetlist_.setBuffer(b);
3190 Inset * Paragraph::releaseInset(pos_type pos)
3192 Inset * inset = d->insetlist_.release(pos);
3193 /// does not honour change tracking!
3194 eraseChar(pos, false);
3199 Inset * Paragraph::getInset(pos_type pos)
3201 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3202 ? d->insetlist_.get(pos) : 0;
3206 Inset const * Paragraph::getInset(pos_type pos) const
3208 return (pos < pos_type(d->text_.size()) && d->text_[pos] == META_INSET)
3209 ? d->insetlist_.get(pos) : 0;
3213 void Paragraph::changeCase(BufferParams const & bparams, pos_type pos,
3214 pos_type & right, TextCase action)
3216 // process sequences of modified characters; in change
3217 // tracking mode, this approach results in much better
3218 // usability than changing case on a char-by-char basis
3221 bool const trackChanges = bparams.trackChanges;
3223 bool capitalize = true;
3225 for (; pos < right; ++pos) {
3226 char_type oldChar = d->text_[pos];
3227 char_type newChar = oldChar;
3229 // ignore insets and don't play with deleted text!
3230 if (oldChar != META_INSET && !isDeleted(pos)) {
3232 case text_lowercase:
3233 newChar = lowercase(oldChar);
3235 case text_capitalization:
3237 newChar = uppercase(oldChar);
3241 case text_uppercase:
3242 newChar = uppercase(oldChar);
3247 if (isWordSeparator(pos) || isDeleted(pos)) {
3248 // permit capitalization again
3252 if (oldChar != newChar) {
3254 if (pos != right - 1)
3256 // step behind the changing area
3260 int erasePos = pos - changes.size();
3261 for (size_t i = 0; i < changes.size(); i++) {
3262 insertChar(pos, changes[i],
3263 getFontSettings(bparams,
3266 if (!eraseChar(erasePos, trackChanges)) {
3269 ++right; // expand selection
3277 int Paragraph::find(docstring const & str, bool cs, bool mw,
3278 pos_type start_pos, bool del) const
3280 pos_type pos = start_pos;
3281 int const strsize = str.length();
3283 pos_type const parsize = d->text_.size();
3284 for (i = 0; i < strsize && pos < parsize; ++i, ++pos) {
3285 // Ignore ligature break and hyphenation chars while searching
3286 while (pos < parsize - 1 && isInset(pos)) {
3287 const InsetSpecialChar *isc = dynamic_cast<const InsetSpecialChar*>(getInset(pos));
3289 || (isc->kind() != InsetSpecialChar::HYPHENATION
3290 && isc->kind() != InsetSpecialChar::LIGATURE_BREAK))
3294 if (cs && str[i] != d->text_[pos])
3296 if (!cs && uppercase(str[i]) != uppercase(d->text_[pos]))
3298 if (!del && isDeleted(pos))
3305 // if necessary, check whether string matches word
3307 if (start_pos > 0 && !isWordSeparator(start_pos - 1))
3310 && !isWordSeparator(pos))
3314 return pos - start_pos;
3318 char_type Paragraph::getChar(pos_type pos) const
3320 return d->text_[pos];
3324 pos_type Paragraph::size() const
3326 return d->text_.size();
3330 bool Paragraph::empty() const
3332 return d->text_.empty();
3336 bool Paragraph::isInset(pos_type pos) const
3338 return d->text_[pos] == META_INSET;
3342 bool Paragraph::isSeparator(pos_type pos) const
3344 //FIXME: Are we sure this can be the only separator?
3345 return d->text_[pos] == ' ';
3349 void Paragraph::deregisterWords()
3351 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3352 Private::LangWordsMap::const_iterator ite = d->words_.end();
3353 for (; itl != ite; ++itl) {
3354 WordList * wl = theWordList(itl->first);
3355 Private::Words::const_iterator it = (itl->second).begin();
3356 Private::Words::const_iterator et = (itl->second).end();
3357 for (; it != et; ++it)
3364 void Paragraph::locateWord(pos_type & from, pos_type & to,
3365 word_location const loc) const
3368 case WHOLE_WORD_STRICT:
3369 if (from == 0 || from == size()
3370 || isWordSeparator(from)
3371 || isWordSeparator(from - 1)) {
3375 // no break here, we go to the next
3378 // If we are already at the beginning of a word, do nothing
3379 if (!from || isWordSeparator(from - 1))
3381 // no break here, we go to the next
3384 // always move the cursor to the beginning of previous word
3385 while (from && !isWordSeparator(from - 1))
3389 LYXERR0("Paragraph::locateWord: NEXT_WORD not implemented yet");
3392 // no need to move the 'from' cursor
3396 while (to < size() && !isWordSeparator(to))
3401 void Paragraph::collectWords()
3403 // This is the value that needs to be exposed in the preferences
3404 // to resolve bug #6760.
3405 static int minlength = 6;
3406 pos_type n = size();
3407 for (pos_type pos = 0; pos < n; ++pos) {
3408 if (isWordSeparator(pos))
3410 pos_type from = pos;
3411 locateWord(from, pos, WHOLE_WORD);
3412 if (pos - from >= minlength) {
3413 docstring word = asString(from, pos, AS_STR_NONE);
3414 FontList::const_iterator cit = d->fontlist_.fontIterator(pos);
3415 if (cit == d->fontlist_.end())
3417 Language const * lang = cit->font().language();
3418 d->words_[*lang].insert(word);
3424 void Paragraph::registerWords()
3426 Private::LangWordsMap::const_iterator itl = d->words_.begin();
3427 Private::LangWordsMap::const_iterator ite = d->words_.end();
3428 for (; itl != ite; ++itl) {
3429 WordList * wl = theWordList(itl->first);
3430 Private::Words::const_iterator it = (itl->second).begin();
3431 Private::Words::const_iterator et = (itl->second).end();
3432 for (; it != et; ++it)
3438 void Paragraph::updateWords()
3446 void Paragraph::Private::appendSkipPosition(SkipPositions & skips, pos_type const pos) const
3448 SkipPositionsIterator begin = skips.begin();
3449 SkipPositions::iterator end = skips.end();
3450 if (pos > 0 && begin < end) {
3452 if (end->last == pos - 1) {
3457 skips.insert(end, FontSpan(pos, pos));
3461 Language * Paragraph::Private::locateSpellRange(
3462 pos_type & from, pos_type & to,
3463 SkipPositions & skips) const
3465 // skip leading white space
3466 while (from < to && owner_->isWordSeparator(from))
3468 // don't check empty range
3471 // get current language
3472 Language * lang = getSpellLanguage(from);
3473 pos_type last = from;
3474 bool samelang = true;
3475 bool sameinset = true;
3476 while (last < to && samelang && sameinset) {
3477 // hop to end of word
3478 while (last < to && !owner_->isWordSeparator(last)) {
3479 if (owner_->getInset(last)) {
3480 appendSkipPosition(skips, last);
3481 } else if (owner_->isDeleted(last)) {
3482 appendSkipPosition(skips, last);
3486 // hop to next word while checking for insets
3487 while (sameinset && last < to && owner_->isWordSeparator(last)) {
3488 if (Inset const * inset = owner_->getInset(last))
3489 sameinset = inset->isChar() && inset->isLetter();
3490 if (sameinset && owner_->isDeleted(last)) {
3491 appendSkipPosition(skips, last);
3496 if (sameinset && last < to) {
3497 // now check for language change
3498 samelang = lang == getSpellLanguage(last);
3501 // if language change detected backstep is needed
3509 Language * Paragraph::Private::getSpellLanguage(pos_type const from) const
3512 const_cast<Language *>(owner_->getFontSettings(
3513 inset_owner_->buffer().params(), from).language());
3514 if (lang == inset_owner_->buffer().params().language
3515 && !lyxrc.spellchecker_alt_lang.empty()) {
3517 string const lang_variety =
3518 split(lyxrc.spellchecker_alt_lang, lang_code, '-');
3519 lang->setCode(lang_code);
3520 lang->setVariety(lang_variety);
3526 void Paragraph::requestSpellCheck(pos_type pos)
3528 d->requestSpellCheck(pos == -1 ? size() : pos);
3532 bool Paragraph::needsSpellCheck() const
3534 SpellChecker::ChangeNumber speller_change_number = 0;
3535 if (theSpellChecker())
3536 speller_change_number = theSpellChecker()->changeNumber();
3537 if (speller_change_number > d->speller_state_.currentChangeNumber()) {
3538 d->speller_state_.needsCompleteRefresh(speller_change_number);
3540 return d->needsSpellCheck();
3544 SpellChecker::Result Paragraph::spellCheck(pos_type & from, pos_type & to,
3545 WordLangTuple & wl, docstring_list & suggestions,
3546 bool do_suggestion, bool check_learned) const
3548 SpellChecker::Result result = SpellChecker::WORD_OK;
3549 SpellChecker * speller = theSpellChecker();
3553 if (!d->layout_->spellcheck || !inInset().allowSpellCheck())
3556 locateWord(from, to, WHOLE_WORD);
3557 if (from == to || from >= size())
3560 docstring word = asString(from, to, AS_STR_INSETS + AS_STR_SKIPDELETE);
3561 Language * lang = d->getSpellLanguage(from);
3563 wl = WordLangTuple(word, lang);
3568 if (needsSpellCheck() || check_learned) {
3569 // Ignore words with digits
3570 // FIXME: make this customizable
3571 // (note that some checkers ignore words with digits by default)
3572 if (!hasDigit(word)) {
3573 bool const trailing_dot = to < size() && d->text_[to] == '.';
3574 result = speller->check(wl);
3575 if (SpellChecker::misspelled(result) && trailing_dot) {
3576 wl = WordLangTuple(word.append(from_ascii(".")), lang);
3577 result = speller->check(wl);
3578 if (!SpellChecker::misspelled(result)) {
3579 LYXERR(Debug::GUI, "misspelled word is correct with dot: \"" <<
3581 from << ".." << to << "]");
3585 d->setMisspelled(from, to, result);
3587 result = d->speller_state_.getState(from);
3590 bool const misspelled_ = SpellChecker::misspelled(result) ;
3591 if (misspelled_ && do_suggestion)
3592 speller->suggest(wl, suggestions);
3593 else if (misspelled_)
3594 LYXERR(Debug::GUI, "misspelled word: \"" <<
3596 from << ".." << to << "]");
3598 suggestions.clear();
3604 void Paragraph::Private::markMisspelledWords(
3605 pos_type const & first, pos_type const & last,
3606 SpellChecker::Result result,
3607 docstring const & word,
3608 SkipPositions const & skips)
3610 if (!SpellChecker::misspelled(result)) {
3611 setMisspelled(first, last, SpellChecker::WORD_OK);
3615 SpellChecker * speller = theSpellChecker();
3616 // locate and enumerate the error positions
3617 int nerrors = speller->numMisspelledWords();
3619 SkipPositionsIterator it = skips.begin();
3620 SkipPositionsIterator et = skips.end();
3621 for (int index = 0; index < nerrors; ++index) {
3624 speller->misspelledWord(index, wstart, wlen);
3625 /// should not happen if speller supports range checks
3626 if (!wlen) continue;
3627 docstring const misspelled = word.substr(wstart, wlen);
3628 wstart += first + numskipped;
3629 if (snext < wstart) {
3630 /// mark the range of correct spelling
3631 numskipped += countSkips(it, et, wstart);
3632 setMisspelled(snext,
3633 wstart - 1, SpellChecker::WORD_OK);
3635 snext = wstart + wlen;
3636 numskipped += countSkips(it, et, snext);
3637 /// mark the range of misspelling
3638 setMisspelled(wstart, snext, result);
3639 LYXERR(Debug::GUI, "misspelled word: \"" <<
3640 misspelled << "\" [" <<
3641 wstart << ".." << (snext-1) << "]");
3644 if (snext <= last) {
3645 /// mark the range of correct spelling at end
3646 setMisspelled(snext, last, SpellChecker::WORD_OK);
3651 void Paragraph::spellCheck() const
3653 SpellChecker * speller = theSpellChecker();
3654 if (!speller || !size() ||!needsSpellCheck())
3658 d->rangeOfSpellCheck(start, endpos);
3659 if (speller->canCheckParagraph()) {
3660 // loop until we leave the range
3661 for (pos_type first = start; first < endpos; ) {
3662 pos_type last = endpos;
3663 Private::SkipPositions skips;
3664 Language * lang = d->locateSpellRange(first, last, skips);
3665 if (first >= endpos)
3667 // start the spell checker on the unit of meaning
3668 docstring word = asString(first, last, AS_STR_INSETS + AS_STR_SKIPDELETE);
3669 WordLangTuple wl = WordLangTuple(word, lang);
3670 SpellChecker::Result result = word.size() ?
3671 speller->check(wl) : SpellChecker::WORD_OK;
3672 d->markMisspelledWords(first, last, result, word, skips);
3676 static docstring_list suggestions;
3677 pos_type to = endpos;
3678 while (start < endpos) {
3680 spellCheck(start, to, wl, suggestions, false);
3684 d->readySpellCheck();
3688 bool Paragraph::isMisspelled(pos_type pos) const
3690 return SpellChecker::misspelled(d->speller_state_.getState(pos));
3694 string Paragraph::magicLabel() const
3697 ss << "magicparlabel-" << id();